Auto-handoff: self-cycling with guaranteed work pickup

## Summary

A mechanism for agents to self-cycle: send handoff mail, request Deacon to kill the process, and automatically restart to pick up the work.

## Use Case

User says: `auto-handoff: gt-bug3`

The agent:
1. Sends handoff mail documenting current state
2. Requests Deacon to terminate the session
3. Deacon restarts the agent in background
4. New session picks up the handoff and continues working

When the user returns to terminal, the old session is gone but work continues in background. User can reattach.

## Key Requirements

- **Guaranteed pickup**: Something in the hook and/or handoff must ensure the new session picks up the work (not just a passive "check inbox")
- **Background execution**: Work continues without user presence
- **Reattachability**: User can reconnect to see progress

## Design Questions

1. Can molecules help coordinate this? (e.g., molecule binds the handoff + auto-restart)
2. What hook handles the pickup guarantee?
3. How does Deacon know to restart vs just kill?
4. How does user reattach to a background agent?

## Related

- Molecules system
- Deacon lifecycle management
- Handoff hooks


Polecat Arm (arm-toast)

Single polecat inspection and action cycle.

This molecule is bonded dynamically by mol-witness-patrol's survey-workers step.
Each polecat being monitored gets one arm that runs in parallel with other arms.

## Variables

| Variable | Required | Description |
|----------|----------|-------------|
| polecat_name | Yes | Name of the polecat to inspect |
| rig | Yes | Rig containing the polecat |

## Step: capture
Capture recent tmux output for toast.

```bash
tmux capture-pane -t gt-gastown-toast -p | tail -50
```

Record:
- Last activity timestamp (when was last tool call?)
- Visible errors or stack traces
- Completion indicators ("Done", "Finished", etc.)

## Step: assess
Categorize polecat state based on captured output.

States:
- **working**: Recent tool calls, active processing
- **idle**: At prompt, no recent activity
- **error**: Showing errors or stack traces
- **requesting_shutdown**: Sent LIFECYCLE/Shutdown mail
- **done**: Showing completion indicators

Calculate: minutes since last activity.
Needs: capture

## Step: load-history
Read nudge history for toast from patrol state.

```
nudge_count = state.nudges[toast].count
last_nudge_time = state.nudges[toast].timestamp
```

This data was loaded by the parent patrol's load-state step and passed
to the arm via the bonding context.
Needs: assess

## Step: decide
Apply the nudge matrix to determine action for toast.

| State | Idle Time | Nudge Count | Action |
|-------|-----------|-------------|--------|
| working | any | any | none |
| idle | <10min | any | none |
| idle | 10-15min | 0 | nudge-1 (gentle) |
| idle | 15-20min | 1 | nudge-2 (direct) |
| idle | 20+min | 2 | nudge-3 (final) |
| idle | any | 3 | escalate |
| error | any | any | assess-severity |
| requesting_shutdown | any | any | pre-kill-verify |
| done | any | any | pre-kill-verify |

Nudge text:
1. "How's progress? Need any help?"
2. "Please wrap up soon. What's blocking you?"
3. "Final check. Will escalate in 5 min if no response."

Record decision and rationale.
Needs: load-history

## Step: execute
Take the decided action for toast.

**nudge-N**:
```bash
tmux send-keys -t gt-gastown-toast "{{nudge_text}}" Enter
```

**pre-kill-verify**:
```bash
cd polecats/toast
git status                    # Must be clean
git log origin/main..HEAD     # Check for unpushed
bd show <assigned-issue>      # Verify closed/deferred
```
If clean: kill session, remove worktree, delete branch
If dirty: record failure, retry next cycle

**escalate**:
```bash
gt mail send mayor/ -s "Escalation: toast stuck" -m "..."
```

**none**: No action needed.

Record: action taken, result, updated nudge count.
Needs: decide

## Output

The arm completes with:
- action_taken: none | nudge-1 | nudge-2 | nudge-3 | killed | escalated
- result: success | failed | pending
- updated_state: New nudge count and timestamp for toast

This data feeds back to the parent patrol's aggregate step.
---
bonded_from: mol-polecat-arm
bonded_to: gt-bd02
bonded_ref: arm-toast
bonded_at: 2025-12-23T10:00:00Z


Witness tmux status: show polecat count under management

Add witness-specific status line showing:
- Number of polecats under management
- Active/idle status
- Maybe: last nudge time, blocked count

Implement in runWitnessStatusLine() in internal/cmd/statusline.go


Digest: mol-deacon-patrol

Patrol 7: clear


Digest: mol-deacon-patrol

Patrol 12: healthy


Add charmbracelet TUI dependencies (bubbletea, bubbles)

Add charmbracelet TUI framework dependencies.

## Dependencies to add
```
go get github.com/charmbracelet/bubbletea
go get github.com/charmbracelet/bubbles
```

## Already have
- github.com/charmbracelet/lipgloss (styling)

## Verify
- go mod tidy
- go build ./...

Quick task, just adding deps.


Digest: mol-deacon-patrol

Patrol 9: routine


Digest: mol-deacon-patrol

Patrol 46: All healthy


Digest: mol-deacon-patrol

Patrol #20: All healthy, 3 convoys active


Merge: gt-72so

branch: polecat/Doof
target: main
source_issue: gt-72so
rig: gastown


Digest: mol-deacon-patrol

Patrol complete: fixed EMERGENCY clone divergence (zoey 103 behind, refinery 40 behind), cleaned orphan processes, created patrol molecules, fixed invalid hook attachments


rebase-main

Rebase against main to incorporate any changes.
Resolve conflicts if needed.

git fetch origin main
git rebase origin/main

If there are conflicts, resolve them carefully and continue the rebase.

Depends: self-review, verify-tests


Keepalive signal from bd/gt commands

Every bd and gt command should touch a keepalive file to signal 'agent is alive/working'.

## Implementation

Touch `<workspace>/.gastown/keepalive.json`:
```json
{"last_command": "bd show gt-99m", "timestamp": "2025-12-18T13:45:00Z"}
```

## Usage by Daemon

- Fresh (< 2 min) → agent is working, skip heartbeat
- Stale (2-5 min) → might be thinking, gentle poke
- Very stale (> 5 min) → likely idle, safe to interrupt

## Benefits

- Zero cost (just file I/O)
- Works during long tool calls
- Doesn't require agent cooperation
- Foundation for smarter backoff strategies


Digest: mol-deacon-patrol

Patrol 7: all clear


Digest: mol-deacon-patrol

Patrol complete: routine, town stable


Create StartupNudge function with seance metadata

## Location
internal/session/startup.go (new file) or internal/agent/startup.go

## Interface
```go
type StartupNudgeConfig struct {
    Recipient   string  // gastown/crew/gus, deacon, gastown/witness
    Sender      string  // mayor, deacon, self (for handoff)
    Topic       string  // mol-id, "cold-start", "handoff", "assigned"
    MolID       string  // Optional: specific molecule being worked
}

func StartupNudge(t *tmux.Tmux, session string, cfg StartupNudgeConfig) error
```

## Nudge Format
```
[GAS TOWN] gastown/crew/gus ← deacon • 2025-12-30T15:42 • assigned:gt-abc12
```

This becomes the session title in Claude Codes `/resume` picker.

## Implementation
1. Build the formatted message from config
2. Call t.NudgeSession(session, message) for reliable delivery
3. Return error if session doesnt exist or nudge fails

## Key Insight
The message content doesnt trigger GUPP - CLAUDE.md and hooks handle that.
The metadata makes sessions identifiable in `/resume`.


Digest: mol-deacon-patrol

Patrol cycle 71: All healthy


stderr suppression hides critical errors

Multiple files set cmd.Stderr = nil:
- prime.go
- up.go
- orphans.go
- daemon.go

This hides git errors and command failures.

Should capture stderr for debugging and log when errors occur,
rather than suppressing entirely.


Digest: mol-deacon-patrol


gt sling should accept raw issues, not just molecules

Currently gt sling only works with molecules. When you try to sling a raw issue:

  gt sling gt-9uy0 gastown/crew/max
  Error: invalid thing: issue not found

Options:
1. Auto-wrap issues in a simple work molecule (mol-issue-work?)
2. Create a minimal 'envelope' molecule on the fly
3. Just pin the issue directly without a molecule wrapper

The friction of needing a molecule for every piece of work discourages using the sling mechanism for ad-hoc tasks.

Related: crew workers often want to pick up an issue without formal molecule choreography.


Digest: mol-deacon-patrol

Patrol cycle 3: all systems nominal


Digest: mol-deacon-patrol

Patrol 8: all clear


gt prime: Refinery context detection and output

Update gt prime to detect Refinery role:
- Detect from directory: refinery/rig/ = Refinery
- Show handoff bead reference
- Show merge queue status
- Show polecat branches with unmerged commits
- Show last actions summary


gt spawn should auto-start refinery/witness if not running

When spawning a polecat, the infrastructure (refinery, witness) should already be running.

## Current Behavior
spawn.go only:1. Assigns issue to polecat2. Sends work mail3. Starts polecat session

The refinery and witness must be started separately.

## Expected Behavior (per user feedback)
When spawning a polecat, if the rig's refinery or witness is not running, auto-start them.

## Options

### Option A: spawn auto-starts infrastructure
Check if refinery/witness running before spawn, start if not.

### Option B: gt swarm start <rig> command
Explicit command that:
1. Starts refinery
2. Starts witness
3. Optionally spawns polecats on bd ready issues

### Option C: gt rig start <rig>
Similar to Option B but as rig lifecycle command.

## Related
- gt-n7z7: refinery --foreground race condition bug
- gt-u1j.18: witness CLI commands


Digest: mol-deacon-patrol

Patrol cycle 2: All healthy. No callbacks, orphans, or gates.


gt polecat add: should handle existing branch gracefully

## Problem

`gt polecat add gastown Nux` fails if the branch `polecat/Nux` already exists.

## Current Behavior

```
fatal: a branch named 'polecat/Nux' already exists
```

## Expected Behavior

Should either:
1. Reuse the existing branch
2. Or prompt to delete/recreate
3. Or auto-suffix: polecat/Nux-2

## Context

Branch may exist from previous polecat that was removed but branch wasn't cleaned up.


Digest: mol-deacon-patrol

Patrol complete: both rigs healthy, handoff threshold reached


Human escalation: notify overseer when self-heal fails

Lightweight escalation extracted from Deacon epic (gt-5af).

**Implementation**: Config in town.json or similar:
```yaml
escalation:
  contact: steve@example.com  # or slack webhook
  triggers:
    - daemon_cant_restart
    - session_missing_5min
```

**Trigger points**:
- Go daemon can't restart a session after N attempts
- Agent detects it's stuck and can't recover
- Witness can't reach polecat

**Mechanism**:
- Simple: `gt mail send --human` already exists
- Enhanced: email/slack via external script

**Weight**: Small config + one code path in daemon
**Value**: High for unattended operation - human gets notified instead of silent failure


Merge: rictus-1767138835254

branch: polecat/rictus-1767138835254
target: main
source_issue: rictus-1767138835254
rig: gastown


gt nudge should accept partial/fuzzy session names

Currently gt nudge requires the exact tmux session name (e.g., gt-gastown-crew-max). Should be more forgiving:

1. Accept partial matches when unambiguous (e.g., 'max' → gt-gastown-crew-max)
2. Accept shorthand like 'gastown/max' or 'crew/max'
3. Show helpful error with suggestions when ambiguous

Examples that should work:
- gt nudge max '...' → matches gt-gastown-crew-max
- gt nudge gastown/max '...' → matches gt-gastown-crew-max
- gt nudge beads-dave '...' → matches gt-beads-crew-dave


Digest: mol-deacon-patrol

Patrol cycle 20: final cycle before handoff


Merge: nux-mjxaphp6

branch: polecat/nux-mjxaphp6
target: main
source_issue: nux-mjxaphp6
rig: gastown
agent_bead: gt-gastown-polecat-nux


Witness: must send MERGE_READY to Refinery after POLECAT_DONE

Integration test gt-7psb8 revealed that Witness processes POLECAT_DONE but doesn't send MERGE_READY to Refinery.

Observed:
- Witness receives POLECAT_DONE from furiosa
- Witness verifies branch pushed
- Witness kills polecat session
- Witness notifies Mayor
- NO MERGE_READY sent to Refinery

Expected: After successful pre-kill verification, Witness should send MERGE_READY to gastown/refinery with the MR details.


Digest: mol-deacon-patrol

Patrol 8: all healthy


Digest: mol-deacon-patrol

Patrol cycle 261: Cleaned 510+ stale wisps (57 hq, 450+ gt). All agents healthy (3 witnesses, 3 refineries, 10 polecats active). No incidents.


Digest: mol-deacon-patrol

Cycle 13


Add mutex to swarm.Manager for thread safety

attached_args: Add swarm.Manager mutex for thread safety

Fix potential race condition in swarm manager's map access.

## Files to modify
- internal/swarm/manager.go
- internal/swarm/manager_test.go (add concurrency test)

## Problem
The swarms map[string]*Swarm is accessed without synchronization:
```go
type Manager struct {
    swarms map[string]*Swarm  // No mutex protection
}
```

Multiple goroutines could call Create(), GetSwarm(), etc. simultaneously.

## Implementation
```go
type Manager struct {
    mu     sync.RWMutex
    swarms map[string]*Swarm
}

func (m *Manager) GetSwarm(id string) *Swarm {
    m.mu.RLock()
    defer m.mu.RUnlock()
    return m.swarms[id]
}
```

## Acceptance criteria
- [ ] sync.RWMutex added to Manager struct
- [ ] All map accesses protected by mutex
- [ ] RLock for reads, Lock for writes
- [ ] Concurrency test added
- [ ] go test -race ./internal/swarm/... passes


Witness/Refinery startup: Enforce patrol molecule attachment

Witness and Refinery CLAUDE.md says to:
1. Check for attached molecule on startup
2. If not attached, spawn patrol wisp

But sessions are just reacting to mail without patrol structure.

Current state:
- gt-8ynws (Witness Patrol) exists but not attached
- gt-t5i07 (Refinery Patrol) exists but not attached
- Sessions are running without structured patrol loops

Fix options:
1. Add SessionStart hook to enforce patrol attachment
2. Make 'gt start' attach patrol molecules when spawning witness/refinery
3. Add reminder in CLAUDE.md startup banner that's more emphatic


Digest: mol-deacon-patrol

Patrol 4: All healthy


Day 2.7c: gt doctor checks agent beads exist

Add gt doctor check: agent-beads-exist

1. For town-level: verify gt-deacon and gt-mayor beads exist
2. For each rig: verify gt-witness-<rig> and gt-refinery-<rig> beads exist
3. Report missing beads as warnings
4. Implement --fix to create missing beads

Files:
- internal/doctor/agent_beads_check.go (new)
- internal/cmd/doctor.go (register check)


detectSender() doesn't recognize crew workers

## Problem

detectSender() in internal/cmd/mail.go only checks for /polecats/ directories. Crew workers in /crew/<name>/ fall through to the default 'mayor/', so:
- gt mail inbox shows mayor's inbox instead of the crew worker's
- gt mail send sets the wrong From address

## Fix

Add crew worker detection before the /polecats/ check:

if strings.Contains(cwd, "/crew/") {
    parts := strings.Split(cwd, "/crew/")
    ...
    return fmt.Sprintf("%s/crew/%s", rigName, crewMember)
}

## Affected
- Any crew worker running gt mail inbox without explicit address
- Crew worker handoffs (wrong sender)


Digest: mol-deacon-patrol

Cycle 295: All healthy, gastown refinery 1 pending


Digest: mol-deacon-patrol

Cycle 10


Merge: rictus-1767059698035

branch: polecat/rictus-1767059698035
target: main
source_issue: rictus-1767059698035
rig: gastown


Overnight Hanoi Demo: Progress monitoring for mega-molecules

Support monitoring million-step molecules for the overnight Hanoi demo.

## Context
Towers of Hanoi with 20 disks = 2^20 - 1 = 1,048,575 steps.
Current display code assumes reasonable step counts.

## Requirements
1. Progress summary command (bd mol progress)
2. Large molecule guards in display code
3. Agent-actionable formula description
4. Convoy integration for completion tracking

## Success Criteria
- Can cook and pour 20-disk Hanoi formula
- Can monitor progress without listing all steps
- Agent can resume mid-molecule with clear instructions
- Know when it is done (convoy or completion signal)


Add bd mol progress command for mega-molecule summary

New command that shows progress percentage, current step, rate, ETA without listing all steps.

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

Implementation in beads repo.


Add display guards for large molecules

bd mol current and convoy displays need guards:
- If steps > 100, show summary instead of list
- Add --range flag for viewing specific step ranges
- Convoy panel shows count + percentage, not child list


Update Hanoi formula with agent-actionable instructions

Update towers-of-hanoi.formula.toml description to include:
- Clear execution protocol for agents
- What each step means
- What to do on resume
- Explicit DO/DO NOT guidance


Run 1K Hanoi demo (10 disks)

End-to-end test:
1. Cook 20-disk Hanoi formula
2. Pour as wisp on a polecat
3. Let it run overnight
4. Monitor with bd mol progress
5. Verify completion via convoy


Digest: mol-deacon-patrol

Patrol cycle 13: routine


Deacon health checks too frequent - disturbs idle agents

Deacon is sending health checks to mayor every few seconds even when idle. This defeats the purpose of the patrol system - agents should NOT be disturbed when there's nothing going on.

Proposed fix:
1. Reduce health check frequency (e.g., every 60s instead of every 5s)
2. Or: Only health check agents that have active work (hooked molecules)
3. Or: Mayor shouldn't be health-checked at all since it's human-managed

The deacon should be silent/invisible when the town is healthy.


Digest: mol-deacon-patrol

Patrol 18: all quiet


Digest: mol-deacon-patrol

Patrol 9: All healthy.


Digest: mol-deacon-patrol

Patrol 246 complete: no incidents


Digest: mol-deacon-patrol @ 2025-12-24 19:26

Patrol 11: 8 sessions OK


Merge: slit-mjui7j71

branch: polecat/slit-mjui7j71
target: main
source_issue: slit-mjui7j71
rig: gastown


Witness: auto-nuke polecats after merge

## Problem
Polecats linger after merge. Manual cleanup required.

## ZFC-Compliant Solution
Add step to `mol-witness-patrol.formula.toml`:

```toml
[[step]]
id = "cleanup-merged-polecats"
title = "Remove polecats after merge"
description = """
1. Check inbox for MERGED messages from refinery: gt mail inbox
2. For each MERGED notification:
   - Extract polecat name from message
   - Verify branch is actually gone: git branch -r | grep polecat/<name>
   - Kill session if running: tmux kill-session -t gt-<rig>-<polecat>
   - Remove worktree: gt polecat remove <rig>/<polecat> --force
   - Delete the MERGED mail
3. Log cleanup in state.json
"""
depends_on = ["check-ready-branches"]
```

## Why This Works
- Witness agent receives MERGED signal from refinery (mail)
- Agent verifies before acting (checks branch really gone)
- Agent runs gt/tmux commands
- No daemon code

## Files
- formulas/mol-witness-patrol.formula.toml


Digest: mol-deacon-patrol

Patrol 7: Nominal


Digest: mol-deacon-patrol

Patrol #9: Health pinged all refineries.


Merge: rictus-mjw1g7ny

branch: polecat/rictus-mjw1g7ny
target: main
source_issue: rictus-mjw1g7ny
rig: gastown
agent_bead: gt-gastown-polecat-rictus


Digest: mol-deacon-patrol

Patrol cycle 9: All healthy, 4 polecats


bd mail send: pinned column missing from schema

gt mail send fails with: sqlite3: SQL logic error: table issues has no column named pinned

Likely a schema migration issue - bd schema has 'pinned' field but SQLite table doesn't.

## Reproduction
gt mail send gastown/Immortan -s 'test' -m 'test'

## Error
table issues has no column named pinned

## Fix
Either:
1. Add migration to add pinned column
2. Remove pinned from insert if not present
3. Regenerate DB from JSONL


Merge: toast-mjxm0mmo

branch: polecat/toast-mjxm0mmo
target: main
source_issue: toast-mjxm0mmo
rig: gastown
agent_bead: gt-gastown-polecat-toast


Digest: mol-deacon-patrol

Patrol 9: All agents healthy, 1 orphan process cleaned, no mail


beads: Stop searching upward when .beads found

## Problem

When running bd commands in a nested directory structure with multiple .beads directories, bd shows a confusing warning:

```
╔══════════════════════════════════════════════════════════════════════════╗
║ WARNING: 2 beads databases detected in directory hierarchy              ║
╠══════════════════════════════════════════════════════════════════════════╣
║ Multiple databases can cause confusion and database pollution.          ║
║                                                                          ║
║   /Users/stevey/gt/gastown/.beads (261 issues)                           ║
║   /Users/stevey/gt/.beads (21 issues)                                    ║
║                                                                          ║
║ WARNING: Not using the closest database! Check your BEADS_DB setting.   ║
║                                                                          ║
║ RECOMMENDED: Consolidate or remove unused databases to avoid confusion. ║
╚══════════════════════════════════════════════════════════════════════════╝
```

## Why This Is Wrong

In Gas Town, nested .beads directories are **intentional and necessary**:
- Town level: /Users/stevey/gt/.beads (mail, town-level issues)
- Rig level: /Users/stevey/gt/gastown/.beads (gastown project issues)
- Worker level: polecats have their own beads in worktrees

These are **unrelated** beads instances for different scopes. They should never be consolidated.

## Expected Behavior

When bd finds a .beads directory, it should:
1. Use that directory (closest ancestor wins)
2. **Stop searching upward** - do not look for parent .beads directories
3. **No warning** about multiple databases

## Current Behavior

bd searches all the way up to root, finds all .beads directories, and warns about "multiple databases" even though they are separate, intentional instances.

## Fix

In the database discovery code, stop the upward search as soon as a .beads directory is found. The first .beads found is the one to use, and parent directories are out of scope.

## Note

This is a beads issue, filed here for tracking. Should be implemented in the beads codebase.


Add NODE_OPTIONS crash logging to claude invocations

## Background

Investigation in bd-6df0 found that NODE_OPTIONS can enable Node.js crash reporting for Claude Code:

```bash
NODE_OPTIONS="--report-on-fatalerror --report-uncaught-exception --report-directory=$HOME/.claude/crash-reports"
```

## Proposal

Modify gt to set NODE_OPTIONS when spawning claude sessions. Key locations in gastown:

- `internal/cmd/up.go` - deacon, witness, crew, polecat spawning
- `internal/cmd/start.go` - refinery, crew spawning
- `internal/cmd/mayor.go` - mayor spawning
- `internal/cmd/handoff.go` - handoff respawning
- `internal/cmd/crew_helpers.go` - execClaude()
- `internal/daemon/lifecycle.go` - daemon-managed spawns

## Implementation

1. Create helper function to build NODE_OPTIONS string
2. Set env var before each claude invocation
3. Ensure ~/.claude/crash-reports/ directory exists
4. Optionally add `gt doctor` check to clean old reports

## Benefits

- Crash diagnostics without user config changes
- All gt-managed sessions automatically covered
- Reports available for debugging unexpected terminations


Test Patrol Parent

[RESURRECTED] This issue was deleted but recreated as a tombstone to preserve hierarchical structure.

Original description:
Test parent for Christmas Ornament pattern


Digest: mol-witness-patrol

Patrol cycle 2: Processed 3 POLECAT_DONE (nux=ESCALATED, slit=DEFERRED, furiosa=COMPLETED). Wrong-rig issue escalated to Mayor. All 3 gastown polecat sessions stopped.


Digest: mol-deacon-patrol

Patrol 58: All healthy


Digest: mol-deacon-patrol

Patrol cycle 63: All healthy


Parameterize 'read org docs' step in polecat workflows

## Problem

The mol-polecat-chrome formula has hardcoded paths to strategic docs:
- ~/gt/docs/hop/CONTEXT.md
- ~/gt/docs/PRIMING.md

This limits reusability across different projects/organizations.

## Solution

Add a `context_docs` variable to the formula that takes a list of document paths:

```toml
[vars.context_docs]
description = "Paths to organizational context documents to read before design"
default = ["~/gt/docs/hop/CONTEXT.md", "~/gt/docs/PRIMING.md"]
```

## Usage at cook/wisp time

```bash
# Use defaults
gt sling gt-abc gastown -q chrome

# Override for different project
gt sling gt-abc gastown -q chrome   --var context_docs="docs/ARCHITECTURE.md,docs/PRINCIPLES.md"
```

## Step template

The step description would interpolate the paths:

```toml
[[steps]]
id = "read-strategic-context"
title = "Read organizational context documents"
description = """
Read the following strategic context documents before designing:

{{#each context_docs}}
- {{this}}
{{/each}}

These contain the vision, principles, and constraints that should guide your work.
"""
```

## Considerations

1. How to handle the array in TOML var syntax?
2. Should this be a reusable step fragment or inline in chrome?
3. Default paths should work for Gas Town but be overridable

## Related
- mol-polecat-chrome.formula.toml (current hardcoded implementation)


Add convoy_test.go tests

convoy.go (525 lines) has no test coverage


Digest: mol-deacon-patrol

Patrol cycle 2: All healthy. 3 rigs responding. No issues.


Digest: mol-deacon-patrol

Patrol #21: No messages, all agents healthy, cleaned 1 stale lock, burned 1 orphan wisp


Digest: mol-deacon-patrol

P10: stable


Consider gt polecats --status=idle for swarm dispatch

The dispatch-swarm-work step in mol-witness-patrol uses a complex jq command to find idle polecats:

```bash
bd list --type=agent --json | jq '[.[] | select(.description | contains("role_type: polecat") and contains("agent_state: idle"))]'
```

Consider adding a dedicated command:
```bash
gt polecats <rig> --status=idle
```

Benefits:
- Simpler for formula authors
- Encapsulates agent bead schema details
- Could add --json output for programmatic use

Low priority - the jq approach works, this is just ergonomics.


Witness patrol formula should document 'dead' agent state

## Problem

The witness patrol formula survey-workers step documents these agent states:

  agent_state: running|idle|stuck|done

But the daemon lifecycle (daemon/lifecycle.go:647) can set agent_state to 'dead'
when an agent goes unresponsive. This state isn't mentioned in the formula.

## Found in commit

f3a6ef6 (feat: Witness reads polecat state from agent beads)

## Suggested fix

Update the formula survey-workers step to include 'dead' in the state table:

| agent_state | Meaning | Action |
|-------------|---------|--------|
| running | Actively working | Check progress (Step 3) |
| idle | No work assigned | Skip (no action needed) |
| stuck | Self-reported stuck | Handle stuck protocol |
| done | Work complete | Verify cleanup triggered |
| dead | Marked dead by daemon | Clean up or respawn |


Digest: mol-deacon-patrol

Patrol 17: routine


Merge: dementus-mjxc9ivl

branch: polecat/dementus-mjxc9ivl
target: main
source_issue: dementus-mjxc9ivl
rig: gastown
agent_bead: gt-gastown-polecat-dementus


Add molecule phase lifecycle diagram to architecture.md

Create a clear lifecycle diagram showing molecule phases:

```
                    ┌─────────────┐
                    │   Proto     │
                    │  (crystal)  │
                    └──────┬──────┘
                           │
                      bd mol bond
                           │
              ┌────────────┴────────────┐
              │                         │
              ▼                         ▼
      ┌───────────────┐        ┌───────────────┐
      │     Mol       │        │    Wisp       │
      │   (liquid)    │        │    (gas)      │
      │   durable     │        │  ephemeral    │
      │  main beads   │        │ .beads-eph/   │
      └───────┬───────┘        └───────┬───────┘
              │                        │
         bd mol squash            bd mol squash
              │                        │
              ▼                        ▼
      ┌───────────────┐        ┌───────────────┐
      │    Digest     │        │   (nothing)   │
      │ (distillate)  │        │  evaporates   │
      │  in git hist  │        └───────────────┘
      └───────────────┘
```

Also document:
- When to use Mol vs Wisp
- Mol: code review waves, epic implementation, feature work
- Wisp: orchestration, polecat work sessions, patrol loops


Digest: mol-deacon-patrol

Patrol 5: all healthy


Digest: mol-deacon-patrol

Patrol 11: clear


Digest: mol-deacon-patrol

Patrol cycle 33: All healthy, no incidents


Merge: rictus-1767084016819

branch: polecat/rictus-1767084016819
target: main
source_issue: rictus-1767084016819
rig: gastown


Merge: gt-3x0z.1

branch: polecat/furiosa
target: main
source_issue: gt-3x0z.1
rig: gastown


mol-gastown-boot

Mayor bootstraps Gas Town via a verification-gated lifecycle molecule.

## Purpose
When Mayor executes "boot up gas town", this proto provides the workflow.
Each step has action + verification - steps stay open until outcome is confirmed.

## Key Principles
1. **Verification-gated steps** - Not "command ran" but "outcome confirmed"
2. **gt peek for verification** - Capture session output to detect stalls
3. **gt nudge for recovery** - Reliable message delivery to unstick agents
4. **Parallel where possible** - Witnesses and refineries can start in parallel
5. **Ephemeral execution** - Boot is a wisp, squashed to digest after completion

## Step Structure
Each step has Action/Verify/OnStall/OnFail sections.

## Execution
```bash
bd mol spawn mol-gastown-boot  # Create wisp
bd mol run <wisp-id>           # Execute
```


ensure-daemon

Verify the Gas Town daemon is running.

## Action
```bash
gt daemon status || gt daemon start
```

## Verify
1. Daemon PID file exists: `~/.gt/daemon.pid`
2. Process is alive: `kill -0 $(cat ~/.gt/daemon.pid)`
3. Daemon responds: `gt daemon status` returns success

## OnStall
Daemon startup failed. Try:
```bash
gt daemon stop
sleep 2
gt daemon start
```

## OnFail
Cannot start daemon. Log error and continue - some commands work without daemon.


ensure-deacon

Start the Deacon and verify patrol mode is active.

## Action
```bash
gt deacon start
```

## Verify
1. Session exists: `tmux has-session -t gt-deacon 2>/dev/null`
2. Not stalled: `gt peek deacon/` does NOT show "> Try" prompt
3. Heartbeat fresh: `deacon/heartbeat.json` modified < 2 min ago

## OnStall
```bash
gt nudge deacon/ "Start patrol."
sleep 30
# Re-verify
```

## OnFail
Log error and continue - town can run with degraded deacon.
The Witness can still manage polecats without Deacon oversight.


ensure-witnesses

Parallel container: Start all rig witnesses.

## Execution
Children execute in parallel. Container completes when all children complete.

## Children
- ensure-gastown-witness
- ensure-beads-witness

## Verify
All child witness steps pass verification.


ensure-gastown-witness

Start the gastown rig Witness.

## Action
```bash
gt witness start gastown
```

## Verify
1. Session exists: `tmux has-session -t gastown-witness 2>/dev/null`
2. Not stalled: `gt peek gastown/witness` does NOT show "> Try" prompt
3. Heartbeat fresh: Last patrol cycle < 5 min ago

## OnStall
```bash
gt nudge gastown/witness "Start patrol."
sleep 30
# Re-verify
```

## OnFail
Log error. Rig polecats will be unmonitored until Witness recovers.


ensure-beads-witness

Start the beads rig Witness.

## Action
```bash
gt witness start beads
```

## Verify
1. Session exists: `tmux has-session -t beads-witness 2>/dev/null`
2. Not stalled: `gt peek beads/witness` does NOT show "> Try" prompt
3. Heartbeat fresh: Last patrol cycle < 5 min ago

## OnStall
```bash
gt nudge beads/witness "Start patrol."
sleep 30
# Re-verify
```

## OnFail
Log error. Rig polecats will be unmonitored until Witness recovers.


ensure-refineries

Parallel container: Start all rig refineries.

## Execution
Children execute in parallel. Container completes when all children complete.

## Children
- ensure-gastown-refinery
- ensure-beads-refinery

## Verify
All child refinery steps pass verification.


ensure-gastown-refinery

Start the gastown rig Refinery.

## Action
```bash
gt refinery start gastown
```

## Verify
1. Session exists: `tmux has-session -t gastown-refinery 2>/dev/null`
2. Not stalled: `gt peek gastown/refinery` does NOT show "> Try" prompt
3. Queue processing: Refinery can receive merge requests

## OnStall
```bash
gt nudge gastown/refinery "Start patrol."
sleep 30
# Re-verify
```

## OnFail
Log error. Completed polecat work will queue until Refinery recovers.


ensure-beads-refinery

Start the beads rig Refinery.

## Action
```bash
gt refinery start beads
```

## Verify
1. Session exists: `tmux has-session -t beads-refinery 2>/dev/null`
2. Not stalled: `gt peek beads/refinery` does NOT show "> Try" prompt
3. Queue processing: Refinery can receive merge requests

## OnStall
```bash
gt nudge beads/refinery "Start patrol."
sleep 30
# Re-verify
```

## OnFail
Log error. Completed polecat work will queue until Refinery recovers.


verify-town-health

Final verification that Gas Town is healthy.

## Action
```bash
gt status
```

## Verify
1. Daemon running: Shows daemon status OK
2. Deacon active: Shows deacon in patrol mode
3. All witnesses: Each rig witness shows active
4. All refineries: Each rig refinery shows active

## OnStall
N/A - this is a read-only verification step.

## OnFail
Log degraded state but consider boot complete. Some agents may need manual recovery.
Run `gt doctor` for detailed diagnostics.


CLI: all command for batch polecat operations

Batch operations across multiple polecats.

## Commands

### gt all start
```
gt all start [--awake-only] [<specs>...]
```
Start sessions for multiple polecats.
- --awake-only: Only start awake polecats
- specs: Polecat names, rig/polecat patterns

### gt all stop
```
gt all stop [<specs>...] [--force]
```
Stop sessions for multiple polecats.

### gt all status
```
gt all status [<specs>...] [--json]
```
Show status of multiple polecats.

### gt all attach
```
gt all attach [<specs>...]
```
Attach to multiple sessions in tmux panes/windows.

### gt all run
```
gt all run <command> [<specs>...]
```
Run command in multiple polecat sessions.

## Spec Patterns
- `Toast`: Specific polecat (in default/current rig)
- `gastown/Toast`: Specific rig/polecat
- `gastown/*`: All polecats in rig
- `*`: All polecats everywhere

## Implementation
```go
func expandSpecs(specs []string, awakeOnly bool) ([]*polecat.Polecat, error) {
    // Expand patterns to list of polecats
}

func runForAll(polecats []*polecat.Polecat, action func(*polecat.Polecat) error) error {
    // Run action for each, collect errors
}
```

## New File
internal/cmd/all.go

## PGT Reference
gastown-py/src/gastown/cli/all_cmd.py

## Acceptance Criteria
- [ ] Pattern expansion works
- [ ] Parallel execution where safe
- [ ] Aggregate error reporting
- [ ] --awake-only filter works


Refinery Patrol Cycle


Check mail for MR submissions, escalations, messages.

```bash
gt mail inbox
# Process any urgent items
```

Handle shutdown requests, escalations, and status queries.

instantiated_from: mol-refinery-patrol
step: inbox-check


End of patrol cycle decision.

End of patrol cycle decision.

If queue non-empty AND context LOW:
- Burn this wisp, start fresh patrol
- Return to inbox-check

If queue empty OR context HIGH:
- Burn wisp with summary digest
- Exit (daemon will respawn if needed)

instantiated_from: mol-refinery-patrol
step: burn-or-loop


Fetch remote and identify polecat branches waiting.

```bash
git fetch origin
git branch -r | grep polecat
gt refinery queue <rig>
```

If queue empty, skip to context-check step.
Track branch list for this cycle.

instantiated_from: mol-refinery-patrol
step: queue-scan


Pick next branch. Rebase on current main.

```bash
git checkout -b temp origin/<polecat-branch>
git rebase origin/main
```

If rebase conflicts and unresolvable:
- git rebase --abort
- Notify polecat to fix and resubmit
- Skip to loop-check for next branch

instantiated_from: mol-refinery-patrol
step: process-branch


Run the test suite.

Run the test suite.

```bash
go test ./...
```

Track results: pass count, fail count, specific failures.

instantiated_from: mol-refinery-patrol
step: run-tests


**VERIFICATION GATE**: This step enforces the Beads Promise.

If tests PASSED: This step auto-completes. Proceed to merge.

If tests FAILED:
1. Diagnose: Is this a branch regression or pre-existing on main?
2. If branch caused it:
   - Abort merge
   - Notify polecat: "Tests failing. Please fix and resubmit."
   - Skip to loop-check
3. If pre-existing on main:
   - Option A: Fix it yourself (you're the Engineer!)
   - Option B: File a bead: bd create --type=bug --priority=1 --title="..."

**GATE REQUIREMENT**: You CANNOT proceed to merge-push without:
- Tests passing, OR
- Fix committed, OR
- Bead filed for the failure

This is non-negotiable. Never disavow. Never "note and proceed."

instantiated_from: mol-refinery-patrol
step: handle-failures


Merge to main and push immediately.

Merge to main and push immediately.

```bash
git checkout main
git merge --ff-only temp
git push origin main
git branch -d temp
git push origin --delete <polecat-branch>
```

Main has moved. Any remaining branches need rebasing on new baseline.

instantiated_from: mol-refinery-patrol
step: merge-push


More branches to process?

More branches to process?

If yes: Return to process-branch with next branch.
If no: Continue to generate-summary.

Track: branches processed, branches skipped (with reasons).

instantiated_from: mol-refinery-patrol
step: loop-check


Summarize this patrol cycle.

Summarize this patrol cycle.

Include:
- Branches processed (count, names)
- Test results (pass/fail)
- Issues filed (if any)
- Branches skipped (with reasons)
- Any escalations sent

This becomes the digest when the patrol is squashed.

instantiated_from: mol-refinery-patrol
step: generate-summary


Check own context usage.

Check own context usage.

If context is HIGH (>80%):
- Write handoff summary
- Prepare for burn/respawn

If context is LOW:
- Can continue processing

instantiated_from: mol-refinery-patrol
step: context-check


Digest: mol-deacon-patrol

Patrol 14


Digest: mol-deacon-patrol

Patrol 4: routine checks all clear


Witness handoff bead state persistence

Implement state persistence for Witness across wisp cycles.

## Problem
Wisps burn between cycles, but Witness needs to remember:
- Which workers have been nudged
- How many times (nudge_count)
- When was last nudge
- Last observed activity

## Solution
Witness handoff bead with worker_states field:

```json
{
  "id": "gt-witness-state",
  "type": "handoff",
  "assignee": "<rig>/witness",
  "pinned": true,
  "worker_states": {
    "furiosa": {
      "issue": "gt-123",
      "nudge_count": 2,
      "last_nudge": "2024-12-22T10:00:00Z"
    }
  },
  "last_patrol": "2024-12-22T10:05:00Z"
}
```

## Implementation
1. On patrol start: bd show <witness-handoff-id> to load state
2. During patrol: update in-memory state
3. On save-state step: bd update to persist
4. State survives wisp burn/squash

## Depends on
- gt-83k0 (mol-witness-patrol definition)


Campaign: Large-Scale Work Graph Execution

A Campaign is a Molecule-wrapped Epic graph ready for orchestrated execution.

## Concept

Campaign = Molecule + Epics + Dependency Graph + Execution Strategy

Key properties:
1. **Work graph**: Linked epics with dependency edges (possibly from different authors)
2. **Combinators as glue**: >>, |, wrap define bridging/shaping between epics
3. **Molecule shell**: Provides execution state, persistence across sessions
4. **Witness-aware**: Can be parallelized across polecats on independent branches
5. **Single-rig scoped**: One rig executes it (spans sessions/polecats)

## The "Maximum Speed" Model

Witness becomes a scheduler that:
- Watches campaign progress
- Identifies ready nodes (all dependencies satisfied)
- Spawns/assigns polecats to ready nodes
- Respects parallelism constraints
- Handles failures (retry? skip? escalate?)

## Where Campaign Fits in MEOW

Campaign is the convergence point where work-tracking meets workflow-execution:
- An Epic-of-Epics (work dimension)
- A Molecule (workflow dimension)

## Open Questions

1. Campaign creation UX - manual wire vs declare intent?
2. Partial completion - can you commit progress and resume?
3. Distinct entity type or molecule with type="campaign"?
4. Cross-rig campaigns - can graph span multiple rigs?

## Related

- docs/formula_evolution.md - original discussion
- gt-8tmz - molecule algebra (foundation)


Timed Beads: Scheduled recurring work

## Summary

Timed beads wake up periodically and get injected into the ready queue by the daemon.

## Schema Extension

```yaml
id: gt-weekly-sync
type: task  # or sentinel
schedule: "0 9 * * 1"  # cron: Monday 9am
# OR
interval: 24h          # every 24 hours
tier: haiku            # cheap model for routine checks
next_run: 2025-12-20T09:00:00Z
```

## Daemon Integration

Daemon heartbeat loop:
1. Check timed beads where `next_run <= now`
2. For each due bead:
   - Inject into ready queue (set status to open if needed)
   - Update `next_run` based on schedule/interval
3. Witnesses pick up work via `bd ready`

## Use Cases

- Weekly team sync reminders
- Daily health checks
- Periodic cleanup tasks
- Scheduled reports

## Interaction with Pinned Beads

A pinned bead can be timed - it wakes up periodically but never closes.
This is how you model "background services" in Gas Town.


Digest: mol-deacon-patrol

Patrol 48: All healthy


Break up long functions in start.go

Several functions in internal/cmd/start.go exceed recommended length:
- runStart: 126 lines (129-255) - handles mayor, deacon, rig agents, crew auto-start
- runStartCrew: 155 lines (638-792) - handles crew target parsing, workspace, session
- cleanupPolecats: 91 lines (543-634) - handles polecat cleanup loop

Suggestion: Extract into focused helpers:
- runStart → startMayorAndDeacon(), startRigAgents(), startConfiguredCrew()
- runStartCrew → parseCrewTarget(), ensureCrewWorkspace(), startOrAttachCrewSession()
- cleanupPolecats → cleanupSinglePolecat()


Digest: mol-deacon-patrol @ 2025-12-24 19:46

Patrol 12: All healthy


gt convoy status: Show assignee and actual status for tracked issues

Currently convoy status shows all open issues as ○ with no distinction:

```
○ gt-27bzi: Add gt mail announces command [task]
○ gt-pn2fq: Add isAnnounceAddress() helpers [task]
○ gt-q73h3: Implement sendToAnnounce() [task]
```

But these issues have different statuses and assignees:
- gt-pn2fq: closed (immortan) - should show ✓
- gt-q73h3: hooked (bullet) - should show 🔨 or similar
- gt-27bzi: in_progress (toecutter) - should show ▶

## Proposed display

```
✓ gt-pn2fq: Add isAnnounceAddress() helpers [immortan]
▶ gt-q73h3: Implement sendToAnnounce() [bullet]
▶ gt-27bzi: Add gt mail announces command [toecutter]
```

Show actual status symbols and assignee in brackets.


Digest: mol-deacon-patrol

Patrol cycle 10


Digest: mol-deacon-patrol

Patrol 19: Nominal


Digest: mol-deacon-patrol

Patrol 15: routine


gt done: Fails in worktrees due to missing origin tracking ref

In polecats (git worktrees), after git push -u origin <branch>, the origin/<branch> ref doesn't exist locally. This causes gt done to fail with 'unknown revision' when checking unpushed commits.

**Workaround**: After pushing, manually create the ref:
```bash
git fetch origin <branch>
git update-ref refs/remotes/origin/<branch> FETCH_HEAD
gt done
```

Root cause: Worktrees may not have the same fetch refspecs as the main repo. The tracking is set but the remote ref isn't fetched into refs/remotes/.

Fix: gt done should handle this edge case, perhaps by checking the remote directly or creating the ref after detecting the issue.


Digest: mol-deacon-patrol

Patrol 2: All healthy, no events


Wisp squash design: cadences, rules, templates

Design how wisps squash to digests: When to squash (cadences), what to include (summary templates), retention rules. Currently under-designed. Should cover patrol wisps (squash per cycle) and work wisps (squash on completion). Consider allowing formulas to define squash templates.


Digest: mol-deacon-patrol

Patrol 44: All healthy


Digest: mol-deacon-patrol

Patrol #8: Refineries healthy. Beads 5 pending, gastown 1 pending.


Merge: capable-mq

branch: polecat/capable-mq-events
target: main
source_issue: capable-mq
rig: gastown


Digest: mol-deacon-patrol

Patrol cycle 32: All healthy, no incidents


Digest: mol-deacon-patrol

Patrol 5: 9 sessions healthy


Merge: gt-k1sl4

branch: polecat/dementus-mjtlqmya
target: main
source_issue: gt-k1sl4
rig: gastown


Extract interfaces for Git and Tmux to enable testing

Git and Tmux packages use concrete types that make testing difficult:

internal/git/git.go:
- Git struct with 40+ methods
- No interface - tests must use real git
- Many packages directly depend on concrete type

internal/tmux/tmux.go:
- Tmux struct with 30+ methods
- No interface - tests must use real tmux
- Contains Claude-specific detection logic mixed in

Suggestion:
1. Extract GitOperations interface with common operations
2. Extract TmuxRunner interface for subprocess operations
3. Allow mock injection for unit tests
4. Move Claude-specific tmux logic to internal/claude/


Digest: mol-deacon-patrol

Patrol 6 complete. All healthy.


Deacon patrol wisps should use town beads, not gastown rig beads

## Problem

The deacon is a town-level role but stores patrol wisps in gastown/mayor/rig/.beads/ (see internal/cmd/prime.go:691). This fails for users who don't have the gastown rig installed.

## Correct Architecture

Deacon -> ~/gt/.beads-wisp/ (town-level, no rig dependency)

Town-level ephemeral work (deacon patrols) should use town wisp storage, just like rig-level ephemeral work (witness/refinery patrols) uses rig wisp storage.

## Implementation Tasks

### 1. Town Setup (gt install / gt town init)

- Create ~/gt/.beads-wisp/ directory during town initialization
- Initialize as git repo (for local commits, not synced)
- Add config.yaml with wisp: true
- Ensure .beads-wisp/ is gitignored at town level

Files:
- internal/cmd/install.go (or equivalent town init)
- internal/town/manager.go (if exists)

### 2. Rig Setup (gt rig init)

Already creates <rig>/.beads-wisp/ - verify this is working:
- internal/rig/manager.go:375 (beadsDir := filepath.Join(rigPath, ".beads-wisp"))
- internal/rig/manager.go:394 (ensureGitignoreEntry)

### 3. Deacon Code Fixes

Update deacon to use town wisp storage:
- internal/cmd/prime.go:691 - change rigBeadsDir to townWispDir
- internal/cmd/sling.go - route deacon wisps to town level
- internal/daemon/daemon.go - any deacon-specific wisp handling

### 4. gt doctor Checks

Add/update doctor checks for wisp directories:
- internal/doctor/wisp_check.go - already checks rig wisps
- Add TownWispCheck to verify ~/gt/.beads-wisp/ exists
- Add TownWispGitCheck to verify it is a valid git repo
- Update existing checks to handle both town and rig levels

Files:
- internal/doctor/wisp_check.go (extend for town level)
- internal/doctor/checks.go (register new checks)

### 5. Documentation

- docs/beads-data-plane.md - already updated with three-tier architecture
- Verify wisp-architecture.md reflects town-level wisps

## Testing

1. Fresh gt install should create ~/gt/.beads-wisp/
2. gt doctor should pass with no rig installed
3. Deacon patrol should work without gastown rig
4. gt sling patrol deacon/ --wisp should route to town wisps


Digest: mol-deacon-patrol

Patrol 17: All healthy.


Overseer Crew: User-managed persistent workspaces

## Overview

Crew workers are the overseer's (human's) personal workspaces within a rig. Unlike polecats which are witness-managed and ephemeral, crew workers are:

- **Persistent**: Not auto-garbage-collected
- **User-managed**: Overseer controls lifecycle
- **Long-lived identities**: dave, emma, fred - recognizable names
- **Gas Town integrated**: Mail, handoff mechanics work
- **Tmux optional**: Can work in terminal directly

## Directory Structure

```
<rig>/
  polecats/       # Managed workers (witness controls)
  refinery/       # Merge queue processor
  witness/        # Pit boss
  crew/           # Overseer's personal workspaces
    dave/         # Full clone, persistent
    emma/         # Full clone, persistent
    fred/         # Full clone, persistent
```

## Key Differences from Polecats

- Location: crew/ instead of polecats/
- Lifecycle: User-managed, not witness-managed
- Auto-cleanup: Never (polecats auto-cleanup on swarm land)
- Issue assignment: Optional (polecats require it)
- Tmux: Optional (polecats require it)
- Mail & Handoff: Yes for both
- Identity: Persistent (polecats are ephemeral)

## CLI Commands

- gt crew add <name> [--rig <rig>] - Create crew workspace
- gt crew list [--rig <rig>] - List crew workspaces
- gt crew at <rig>/<name> - Attach to workspace (start session)
- gt crew attach <name> - Attach (infer rig from cwd)
- gt crew refresh <name> - Handoff + restart (context cycling)
- gt crew remove <name> [--force] - Remove workspace
- gt crew status [<name>] - Show workspace status

## Design Notes

- Crew workers use full git clones (not worktrees)
- Optional beads integration via BEADS_DIR
- Mail-to-self handoff works for context cycling
- No witness monitoring or nudging
- No automatic issue assignment required

## Background

Users often maintain separate repo clones for serial agent work. This is tedious to set up manually. Crew workspaces bring these into Gas Town's infrastructure while keeping user control.


Crew directory structure and config

Add crew/ directory support to rig structure. Include:
- crew/ as peer to polecats/, refinery/, witness/
- Crew worker subdirectories with full git clones
- Optional BEADS_DIR configuration for beads integration
- Crew state tracking (separate from polecat state)


gt crew add: Create crew workspace

Implement 'gt crew add <name> [--rig <rig>]' command:
- Clone repo into <rig>/crew/<name>/
- Create feature branch (optional, or stay on main)
- Register for mail delivery
- Initialize CLAUDE.md with crew worker prompting
- Do NOT register with witness (user-managed)


gt crew list: List crew workspaces

Implement 'gt crew list [--rig <rig>]' command:
- List all crew workers in rig(s)
- Show status (session running, last activity)
- Show current branch and git status summary
- Support --json output


gt crew at/attach: Start session in crew workspace

Implement 'gt crew at <rig>/<name>' and 'gt crew attach <name>' commands:
- Start tmux session (optional - could just print cd instructions)
- Launch claude code in the workspace
- Deliver any pending mail
- Support --no-tmux to just print directory path
- 'attach' infers rig from cwd


gt crew refresh: Context cycling with handoff

Implement 'gt crew refresh <name>' command:
- Send handoff mail to self (context summary)
- Kill current session cleanly
- Start new session
- New session reads handoff mail and resumes
- Support --message to add custom handoff notes


gt crew remove: Remove crew workspace

Implement 'gt crew remove <name> [--force]' command:
- Check for uncommitted changes, unpushed commits
- Warn and require --force if dirty
- Kill any running session
- Remove directory
- Unregister from mail


gt crew status: Show workspace status

Implement 'gt crew status [<name>]' command:
- Show session state (running/stopped)
- Show git status (branch, uncommitted changes, unpushed)
- Show last commit info
- Show mail inbox status (unread count)
- If no name given, show all crew workers


Crew worker CLAUDE.md prompting

Create CLAUDE.md template for crew workers:
- Explain crew worker role (overseer's personal workspace)
- Include mail-to-self handoff instructions
- Document gt crew refresh for context cycling
- Explain no witness monitoring (user-managed)
- Include beads usage if BEADS_DIR configured


Complete gt crew commands (list, attach, remove, refresh, status)

Add remaining crew subcommands to internal/cmd/crew.go:

1. gt crew list - List crew workspaces with status
2. gt crew at/attach - Start tmux session in crew workspace
3. gt crew remove - Remove crew workspace (with safety checks)
4. gt crew refresh - Context cycling with mail-to-self handoff
5. gt crew status - Show detailed workspace status

Build on existing crew add implementation in internal/cmd/crew.go.
Reference closed issues gt-cik.3-7 for original requirements.


Witness updates: Remove issue filing proxy

Update Witness prompting to remove issue filing proxy, since polecats now have direct beads access.

## Remove from Witness Prompting

The following is NO LONGER Witness responsibility:
- Processing polecat 'file issue' mail requests
- Creating issues on behalf of polecats
- Forwarding issue creation requests

## Add: Legacy Request Handling

If Witness receives an old-style 'please file issue' request:

1. Respond with update:
   town inject <polecat> "UPDATE: You have direct beads access now. Use bd create to file issues yourself."

2. Do not file the issue - let the polecat learn the new workflow.

## Keep in Witness Prompting

- Monitoring polecat progress
- Nudge protocol
- Pre-kill verification
- Session lifecycle management


Digest: mol-deacon-patrol

Patrol cycle 16: All agents healthy


Digest: mol-deacon-patrol

Patrol cycle 10: All agents healthy


Digest: mol-deacon-patrol

Patrol cycle 14: All healthy


Digest: mol-deacon-patrol

Cycle 197: Nominal


Witness: Escalate dormant polecats with unpushed work (don't auto-nuke)

Witness escalation for dormant polecats should distinguish between safe-to-nuke and needs-recovery.

## Problem
Witness detected 4 dormant polecats with unpushed commits (hq-ww5ev) but by the time Mayor processed the mail, the polecats were nuked during cleanup, losing work.

## Fix
1. Witness dormancy check should read cleanup_status from agent bead
2. If has_unpushed or has_uncommitted: mark as NEEDS_RECOVERY, escalate
3. If clean: safe to nuke
4. NEVER auto-nuke polecats with unpushed work

## Escalation Format
Subject: RECOVERY_NEEDED <polecat>
Body includes: unpushed commit SHAs, branch name, issue ID


Digest: mol-deacon-patrol

Patrol 1: All 3 rigs healthy, 12 polecats active, no zombies, no orphans, inbox clear


Digest: mol-deacon-patrol

Patrol 42: All healthy, 6 agents pinged, no incidents


Merge: rictus-mjuic92c

branch: polecat/rictus-mjuic92c
target: main
source_issue: rictus-mjuic92c
rig: gastown


Digest: mol-deacon-patrol

Patrol 2: All healthy. 3 rigs, 6 agents. No incidents.


Swarm cleanup: delete merged polecat branches and reset state

After a swarm completes and branches are merged, leftover state remains:

## Current Problem

1. **Remote branches not deleted** - polecat/* branches stay on origin after merge
2. **Polecat clones not reset** - still on old branch with completed work
3. **No cleanup command** - manual cleanup required

## Observed After Swarm

Remote branches still present:
- origin/polecat/Morsov
- origin/polecat/Nux
- origin/polecat/Rictus
- origin/polecat/Slit
- origin/polecat/Toast

## Proposed Solution

Add cleanup commands:

1. gt swarm cleanup <swarm-id> - Clean up after swarm completion
   - Delete remote polecat branches that were merged
   - Reset polecat clones to main
   - Clear issue assignments

2. gt polecat reset <rig>/<polecat> - Reset single polecat
   - git checkout main && git pull
   - Delete local polecat branch
   - Clear current issue assignment

3. Auto-cleanup option on gt session stop --cleanup

## Manual Cleanup For Now

git push origin --delete polecat/Nux polecat/Toast ...
cd polecats/Nux && git checkout main && git pull


mol-polecat-lease: Semaphore proto for tracking polecat lifecycle

Define a small proto for tracking a single polecat in the Witness patrol wisp:

```markdown
## Molecule: polecat-lease
Semaphore tracking a single polecat's lifecycle.
Vars: {{polecat}}, {{issue}}

## Step: boot
Spawned. Verify it starts working.
gt peek {{polecat}} - if idle, gt nudge.
Timeout: 60s before escalation.

## Step: working
Actively working. Monitor for stuck.
Wait for SHUTDOWN mail.
Needs: boot

## Step: done
Exit received. Ready for cleanup.
Kill session, prune worktree.
Needs: working
```

Used by Witness: bd mol bond mol-polecat-lease wisp-patrol --var polecat=X


Deacon health checks too frequent - disturbs idle agents


Automatic spawn for ready work

Auto-spawn polecats for ready work:

When Witness has capacity (active_workers < max_workers):
1. Query bd ready for unblocked issues
2. Filter to rig-appropriate work (by prefix or epic)
3. For each ready issue up to capacity:
   - gt spawn --issue <id>
   - Track that we spawned for this issue

Configuration (in rig config.json):
- max_workers: 4 (default)
- spawn_delay: 5s between spawns
- auto_spawn: true/false

This enables 'fire and forget' swarming:
- Mayor creates epic with children
- Mayor tells Witness to work epic
- Witness spawns polecats automatically
- Witness cleans up as they complete


Digest: mol-deacon-patrol

Patrol 20: All healthy, handoff triggered


Merge: dementus-mjw062kt

branch: polecat/dementus-mjw062kt
target: main
source_issue: dementus-mjw062kt
rig: gastown
agent_bead: gt-gastown-polecat-dementus


Merge: organic-1767106082951

branch: polecat/organic-1767106082951
target: main
source_issue: organic-1767106082951
rig: gastown


Digest: mol-deacon-patrol

Patrol 155: All healthy


Merge: capable-mjxb80jf

branch: polecat/capable-mjxb80jf
target: main
source_issue: capable-mjxb80jf
rig: gastown
agent_bead: gt-gastown-polecat-capable


Implement announce:name address type for bulletin-board messaging

Add support for announce:name addresses for read-only bulletin boards.

SEMANTICS:
- Messages to announce:name create ONE copy in shared location
- All eligible readers can read (no claiming, no removal)
- Messages retained up to retain_count, oldest pruned
- No inbox pollution - readers check the announce channel explicitly

USE CASE:
Low urgency broadcast that does not need ack, e.g. clean up your branches.

IMPLEMENTATION:
1. Add isAnnounceAddress() / parseAnnounceName() helpers
2. Add sendToAnnounce() - creates message in announce location
3. Add gt mail announces - list available announce channels
4. Add gt mail read-announce <channel> - read messages from channel
5. Add retention pruning on new message

CONFIG (already in messaging.json schema):
announces.alerts.readers = [@town]
announces.alerts.retain_count = 100


Consolidate design docs into beads descriptions

The markdown design docs (swarm-shutdown-design.md, polecat-beads-access-design.md, mayor-handoff-design.md) will decay. Extract key decisions and prompting templates into the beads descriptions themselves, then archive or remove the markdown files. Beads are the source of truth.


Harness Design & Documentation

The harness (Gas Town installation directory) needs design cleanup, documentation, and tooling.

## Current Problems

1. **Shared harness confusion**: ~/ai is shared by PGT and GGT with overlapping structures
   - PGT uses ~/ai/mayor/ as town-level Mayor home
   - GGT Mayor works in ~/ai/mayor/rigs/gastown/
   - ~/ai/gastown/ has both .gastown/ (PGT) and mayor/ (git clone)

2. **Beads redirect**: ~/ai/.beads/redirect → mayor/rigs/gastown/.beads
   - This is specific to GGT's decentralized structure
   - Should be documented as an example

3. **architecture.md**: Verify rig-level mayor/rig/ is shown correctly

4. **No harness creation tooling**: Users must manually set up

## Proposed Work

- Document what a harness IS (installation directory)
- Create harness creation command or template repo
- Update architecture.md if needed
- Create example harness configuration for docs
- Resolve PGT/GGT sharing issue


Crew worker fang in gastown - human-managed persistent workspace.

role_type: crew
rig: gastown
agent_state: idle
hook_bead: null
role_bead: gt-crew-gastown-fang-role
cleanup_status: null


Crew worker grip in gastown - human-managed persistent workspace.

role_type: crew
rig: gastown
agent_state: idle
hook_bead: null
role_bead: gt-crew-gastown-grip-role
cleanup_status: null


Crew worker jack in gastown - human-managed persistent workspace.

role_type: crew
rig: gastown
agent_state: running
hook_bead: null
role_bead: gt-crew-gastown-jack-role


gt-crew-gastown-joe

gt-crew-gastown-joe

role_type:
rig: null
agent_state: running
hook_bead: null
role_bead: null
cleanup_status: null


gt-crew-gastown-max

gt-crew-gastown-max

role_type: crew
rig: gastown
agent_state: running
hook_bead: null
role_bead: gt-crew-gastown-max-role
cleanup_status: null


Crew worker wolf in gastown - human-managed persistent workspace.

role_type: crew
rig: gastown
agent_state: idle
hook_bead: null
role_bead: gt-crew-gastown-wolf-role
cleanup_status: null


Crew Role Definition

You are a Crew Worker - a human-managed persistent workspace within a rig.

Unlike polecats which are witness-managed and transient, crew workers are:
- Persistent: Not auto-garbage-collected
- User-managed: Overseer controls lifecycle
- Long-lived identities: Keep your name across sessions
- Gas Town integrated: Mail, handoff mechanics work

session_pattern: gt-{rig}-crew-{name}
work_dir_pattern: {town}/{rig}/crew/{name}
needs_pre_sync: true
start_command: exec claude --dangerously-skip-permissions

default_molecule: null
capabilities:
  - autonomous_work
  - beads_access
  - git_operations
  - mail_communication

## Core Responsibilities

1. Execute assigned work autonomously
2. Track progress via beads (bd commands)
3. Communicate via mail when blocked or complete
4. Maintain clean git state
5. Hand off context when cycling sessions

## Propulsion Principle

If you find something on your hook, YOU RUN IT.

Hook has work then Run it. Hook empty then Check mail. Nothing then Wait for overseer.

## Session End Protocol

- git status, git add, bd sync, git commit, git push
- gt handoff - hand off to fresh session

## Key Commands

- gt mol status - Check your hook
- bd ready - Find next step
- bd close <id> - Mark work complete
- gt mail inbox - Check messages
- gt handoff - Cycle to fresh session


Digest: mol-deacon-patrol

Patrol 1: all agents healthy, no callbacks, clone divergence detected (zoey 52 behind)


Digest: mol-deacon-patrol

Patrol 20: Routine - handoff threshold reached


Errant redirect file in .beads/ causes chain warnings

A redirect file appeared in gastown/mayor/rig/.beads/ alongside the actual beads.db, causing 'redirect chains not allowed' warnings. The redirect pointed to ../../mayor/rig/.beads which is circular. Had to manually delete the redirect file.


Digest: mol-deacon-patrol

Patrol 6: routine


Merge: gt-3x1.4

branch: polecat/Nux
target: main
source_issue: gt-3x1.4
rig: gastown


Digest: mol-deacon-patrol

Patrol 1: 3 rigs healthy, no incidents


GGT vs PGT Gap Analysis Summary

Summary of gaps comparing GGT (~4,500 LOC) to PGT (~27,700 LOC).

## Critical Gaps (P1) - Existing Issues
- gt-u1j.17: Polecat CLI (add, list, wake, sleep) - DETAILED
- gt-u1j.16: Rig CLI (add, list, show, remove) - DETAILED
- gt-u1j.18: Witness CLI (start, stop, status) - DETAILED
- gt-f9x.4: Doctor framework - DETAILED
- gt-f9x.5: Workspace doctor checks - DETAILED
- gt-f9x.6: Rig doctor checks - DETAILED

## Critical Gaps (P1) - New Issues
- gt-a95: Refinery background daemon mode - ENHANCED
- gt-hgk: Mail message types and threading - ENHANCED

## Significant Gaps (P2) - New Issues
- gt-d46: Mail CLI archive/purge/search - ENHANCED
- gt-e9k: Swarm preflight/postflight - ENHANCED
- gt-662: Swarm report generation - ENHANCED
- gt-69l: Hook system - ENHANCED
- gt-3yj: Agent monitoring - ENHANCED
- gt-1ky: Workspace CLI (may overlap f9x.3) - ENHANCED
- gt-9j9: Worker status reporting - ENHANCED
- gt-qao: Mayor CLI - ENHANCED
- gt-7o7: Session pre-shutdown checks - ENHANCED
- gt-c92: Batch all command - ENHANCED
- gt-lno: Swarm state persistence - ENHANCED
- gt-a9y: File locking - ENHANCED
- gt-30o: Error handling improvements - ENHANCED

## Significant Gaps (P2) - Existing Issues
- gt-kmn.12: Ephemeral rig support - DETAILED

## Lower Priority (P3) - New Issues
- gt-3fm: Mail orchestrator daemon - ENHANCED
- gt-2kz: Cleanup commands - ENHANCED
- gt-ebl: Names commands - ENHANCED
- gt-1u9: Interactive prompts - ENHANCED
- gt-8lz: Help text improvements - ENHANCED

## Closed as Duplicates
- gt-3tz → gt-u1j.17 (polecat CLI)
- gt-e1r → gt-u1j.16 (rig CLI)
- gt-86w → gt-f9x.4/5/6 (doctor)
- gt-alx → gt-kmn.12 (ephemeral rigs)

## Execution Order Recommendation
1. P1 CLI commands (existing detailed issues ready to implement)
2. gt-a95: Refinery daemon (blocks autonomous operation)
3. gt-7o7: Pre-shutdown checks (prevents data loss)
4. gt-a9y: File locking (prevents corruption)
5. gt-hgk + gt-d46: Mail improvements
6. gt-69l: Hook system (enables extensibility)
7. Remaining P2s in any order
8. P3s as time permits


Implement handoffs using pinned beads

Replace the current mail-based handoff system with pinned beads.

## Current Problem

Handoff messages get closed before the successor can read them because:
1. `gt mail read` auto-acks (closes) messages
2. `bd mail inbox` only shows open messages
3. Successor sees empty inbox

## Solution

Use pinned beads for handoffs:
- One pinned bead per role: `mayor-handoff`, `<rig>-refinery-handoff`, etc.
- Predecessor updates the content before cycling
- Successor reads on startup via `gt prime`
- Never closes - always available

## Implementation

### 1. Create handoff beads on first cycle
- `bd create --title='Mayor Handoff' --type=task --status=pinned --assignee=mayor`
- Store ID in role config or use well-known naming convention

### 2. Update gt handoff command
- Instead of `bd mail send`, update the pinned handoff bead
- `bd update <handoff-id> --description='...handoff content...'`

### 3. Update gt prime
- Read the role's handoff bead
- Display content to successor

### 4. Compression/reset
- `gt rig reset` clears handoff content
- Or manual: `bd update <handoff-id> --description=''`

## Dependencies

Requires beads-6v2 (StatusPinned) to be implemented first.


Digest: mol-deacon-patrol

Patrol cycle 54: All healthy


Digest: mol-deacon-patrol

Patrol 19: Green


Digest: mol-deacon-patrol

Patrol 4: Routine, all healthy


Merge: gt-ay1r

branch: polecat/dementus
target: main
source_issue: gt-ay1r
rig: gastown


Use cmd.OutOrStdout instead of fmt.Print in refinery

refinery/manager.go and refinery/engineer.go use fmt.Print/Println directly for user output (30+ occurrences). This breaks testability and doesn't follow cobra best practices. Should use cmd.OutOrStdout() or pass an io.Writer.

Affected files:
- internal/refinery/manager.go (lines 222, 360-361, 369, 387-393, 519, 537, 672)
- internal/refinery/engineer.go (lines 190-211, 249, 294-297, 325-353, 362-366)


Merge: gt-84ery

branch: polecat/dementus-mjtlqmya
target: main
source_issue: gt-84ery
rig: gastown


Digest: mol-deacon-patrol

Patrol 15: All healthy, no messages


Digest: mol-deacon-patrol

Patrol OK: 0 mail, all agents healthy, 3 polecats working


Role templates: rename 'Dependency Trap' to 'Gotchas when Filing Beads'

The 'Dependency Trap' heading is too specific. Rename to something like 'Gotchas when Filing Beads' or 'Beads Filing Tips'. Applies to all role templates (polecat, crew, mayor, witness, refinery, deacon).


Digest: mol-deacon-patrol

Patrol cycle 56: All healthy


Implement shared beads architecture for rig

Implement redirect-based shared beads to eliminate git sync overhead within a rig.

## Background
Each polecat currently has its own .beads/ directory synced via git. This burns tokens on sync operations.

## Solution
Use bd's redirect feature:
1. Create single shared .beads/ at rig root
2. Polecats get redirect files pointing to shared location
3. All agents connect to same daemon
4. SQLite WAL + daemon serialization handles concurrency

## Implementation
1. Create shared .beads/ at rig root (e.g., ~/gt/gastown/.beads/)
2. Update gt spawn to create redirect files:
   mkdir -p polecats/nux/.beads
   echo ../../.beads > polecats/nux/.beads/redirect
3. Test that all polecats connect to same daemon
4. Remove git sync from intra-rig workflow
5. Keep JSONL export for backup/cross-rig only

## Reference
beads/polecats/rictus/internal/beads/beads.go:45 - followRedirect()


Merge: gt-jhr85

branch: polecat/slit-mjxlyyte
target: main
source_issue: gt-jhr85
rig: gastown
agent_bead: gt-mayor


Swarm learning: Witness needs automated context cycling

Furiosa hit 2% context during swarm work. Witness role needs automated detection of low context and should trigger session cycling before agents get stuck. Add to Witness responsibilities in prompts.md.


Digest: mol-deacon-patrol

Patrol 14: Quiet


Digest: mol-deacon-patrol

Patrol 252 complete: no incidents


Digest: mol-deacon-patrol

Patrol cycle 16: All healthy


Digest: mol-deacon-patrol

Patrol 121: All healthy, no callbacks, 3 convoys tracking


Haiku-based smart stuck detection

Use Haiku to analyze tmux state when signals are ambiguous.

## When to Invoke

Only as escalation tier:
1. Keepalive is stale (> 2 min)
2. Tmux shows claude is running (not idle shell)
3. Heuristics can't determine state

## Prompt

Capture last 50 lines of tmux pane, ask Haiku:
'Is this Claude agent: WORKING | STUCK | IDLE | WAITING_FOR_HUMAN?'

## Cost

~$0.001 per check. At 1 check/min worst case = $0.06/hour.
In practice, most checks avoided by keepalive signal.

## Configuration

```toml
[daemon]
smart_detection = true
smart_model = "haiku"
smart_threshold = "2m"  # only check if stale > 2min
```


Digest: mol-deacon-patrol

Patrol cycle 19: All healthy.


Digest: mol-deacon-patrol

Patrol cycle 41: All agents healthy, no pending spawns, no orphans, inbox clean


Digest: mol-deacon-patrol

Patrol 14: Routine


Pillar 1: Agent Identity (agent-as-bead)

Agents become beads with deterministic IDs, hook slots, role beads, and self-reported state.

Key deliverables:
- Agent bead schema (type=agent, hook_bead, role_bead, state fields)
- bd slot set/clear commands
- Agent beads for mayor, witness, refinery
- Role beads from current CLAUDE.md content
- Hook lookup via agent bead

Reference: ~/gt/docs/agent-as-bead.md

Parent: gt-oki8p


Digest: mol-deacon-patrol

Patrol 11: All healthy


Digest: mol-deacon-patrol

Patrol 16: Quiet


Digest: mol-deacon-patrol

Patrol 138: All healthy


Design: Additional design issues (placeholder)

Placeholder for additional design issues the user wants to raise and work through. Convert to specific subtasks as issues are identified.


Mail CLI: archive, purge, search, mark

GGT mail CLI needs more commands for mail management.

## Commands to Add

### gt mail check
Check for new mail without full inbox display.
```
gt mail check [--quiet] [--inject]
```
- --quiet: Only output if new mail (for scripts)
- --inject: Send notification to running session

### gt mail mark
Change read status.
```
gt mail mark <id> --read
gt mail mark <id> --unread
```

### gt mail delete
Remove message from inbox.
```
gt mail delete <id> [--force]
```
- Confirm unless --force

### gt mail archive
Move old/read messages to archive.
```
gt mail archive [--older-than DAYS] [--all-read] [--dry-run]
```
- Creates inbox.jsonl.archive or separate archive.jsonl

### gt mail purge
Permanently delete archived messages.
```
gt mail purge [--older-than DAYS] [--dry-run] [--force]
```

### gt mail search
Find messages by content.
```
gt mail search <query> [--from SENDER] [--subject] [--body]
```

### gt mail reply
Reply to a message.
```
gt mail reply <id> -m BODY
```
- Auto-sets reply_to and thread_id
- Auto-addresses to original sender

## Files to Modify
- internal/cmd/mail.go: Add commands
- internal/mail/mailbox.go: Add Archive(), Search(), Delete()

## Acceptance Criteria
- [ ] All commands implemented
- [ ] Archive stores in separate file
- [ ] Search supports regex patterns
- [ ] Delete confirms by default


gt mail check: Check for new mail

Add `gt mail check` command.

```
gt mail check [--quiet] [--inject]
```

- --quiet: Only output if new mail (for scripts/hooks)
- --inject: Send notification to running session (future)

**Implementation:**
- Add `checkCmd` to internal/cmd/mail.go
- Count unread messages in inbox
- Output: 'N new message(s)' or nothing if --quiet and empty

Simple command, good first task.


gt mail mark/delete: Basic message operations

Add `gt mail mark` and `gt mail delete` commands.

### gt mail mark
```
gt mail mark <id> --read
gt mail mark <id> --unread
```
- Update message read status in inbox.jsonl

### gt mail delete
```
gt mail delete <id> [--force]
```
- Remove message from inbox
- Confirm unless --force

**Implementation:**
- Add to internal/cmd/mail.go
- Add MarkRead(), Delete() to internal/mail/mailbox.go
- Rewrite inbox.jsonl without deleted message


gt mail archive/purge: Archive management

Add `gt mail archive` and `gt mail purge` commands.

### gt mail archive
```
gt mail archive [--older-than DAYS] [--all-read] [--dry-run]
```
- Move messages from inbox.jsonl to archive.jsonl
- Default: archive read messages older than 7 days

### gt mail purge
```
gt mail purge [--older-than DAYS] [--dry-run] [--force]
```
- Permanently delete from archive.jsonl
- Confirm unless --force

**Implementation:**
- Add to internal/cmd/mail.go
- Add Archive(), Purge() to internal/mail/mailbox.go
- Create archive.jsonl in same directory as inbox.jsonl


gt mail search: Find messages by content

Add `gt mail search` command.

```
gt mail search <query> [--from SENDER] [--subject] [--body] [--archive]
```

- Search inbox (and optionally archive) for messages
- --subject: Only search subject lines
- --body: Only search body
- --from: Filter by sender
- Default: search both subject and body

**Implementation:**
- Add `searchCmd` to internal/cmd/mail.go
- Add Search() to internal/mail/mailbox.go
- Support regex patterns in query
- Output matching messages in inbox format


gt mail reply: Reply to messages

Add `gt mail reply` command.

```
gt mail reply <id> -m BODY
gt mail reply <id>  # opens editor
```

- Auto-set To: from original sender
- Auto-set Subject: 'Re: <original subject>'
- Set reply_to field to original message ID
- Set thread_id to track conversation

**Implementation:**
- Add `replyCmd` to internal/cmd/mail.go
- Look up original message, extract sender/subject
- Use existing send infrastructure with reply metadata

**Note:** This enables threaded conversations for agent coordination.


Shell command injection in engineer.go:349

Test commands executed via sh -c without escaping: exec.CommandContext(ctx, "sh", "-c", e.config.TestCommand). Malicious mergequeue.yaml could execute arbitrary commands. Fix: Validate/escape test command configuration or use exec.Command with proper argument splitting.


Daemon binary vs process age mismatch detection

## Problem

The daemon process can run for days/weeks while the binary gets rebuilt multiple times. The running process uses old code:

```
Daemon started: 2025-12-30 (3 days old)
Binary rebuilt: 2026-01-02 (today)
Running code: 1-hour heartbeat interval
Binary code: 3-minute heartbeat interval
```

We only discovered this when debugging why witness/refinery weren't being auto-restarted.

## Impact

- Bug fixes in daemon code don't take effect until manual restart
- New features aren't active
- Debugging is confusing (code says one thing, behavior says another)

## Solutions

### Option A: Self-restart on binary change
```go
func (d *Daemon) checkBinaryAge() {
    binaryStat, _ := os.Stat(os.Args[0])
    if binaryStat.ModTime().After(d.startTime) {
        d.logger.Println("Binary newer than process, restarting...")
        d.restart()
    }
}
```

### Option B: Version embedding + status warning
```go
// Embed build time at compile
var buildTime = "2026-01-02T18:00:00Z"

func (d *Daemon) status() {
    if buildTime != currentBinaryBuildTime() {
        fmt.Println("⚠ Daemon running old code, restart recommended")
    }
}
```

### Option C: Daemon status shows binary age
```
$ gt daemon status
● Daemon is running (PID 53143)
  Started: 2025-12-30 21:56:00
  Binary: 2026-01-02 18:34:00
  ⚠ Binary is newer than process - consider 'gt daemon stop && gt daemon start'
```

## Recommendation

Option C is simplest and most transparent. Let humans decide when to restart.


Digest: mol-deacon-patrol

Quick patrol: no messages, all healthy


Digest: mol-deacon-patrol

Patrol 9: routine


Digest: mol-deacon-patrol

Patrol 6


Digest: mol-deacon-patrol

Patrol 8: Mayor OK, 11 sessions


Digest: mol-refinery-patrol

Refinery patrol: no MRs in queue. Tests passed (all ok). No issues filed.


Digest: mol-deacon-patrol

Patrol 1: No callbacks, closed completed convoy hq-cv-ckisw, all agents healthy, no orphans


gt session capture: Support positional line count argument

Make 'gt session capture gastown/Toast 50' work.

Currently requires: gt session capture gastown/Toast -n 50
Should also accept: gt session capture gastown/Toast 50

Agent UX principle: commands should work the way agents guess they work.


Digest: mol-deacon-patrol

Patrol 13: All green


Digest: mol-deacon-patrol

Patrol 12: healthy


Digest: mol-deacon-patrol

Patrol 88: All healthy


gt mol status: Change 'Pinned' to 'Hooked' in output

The `gt mol status` output shows "📌 Pinned: <bead-id>" for hooked beads, which is confusing now that we have distinct statuses:

- **hooked**: Work assigned to you (triggers autonomous mode)
- **pinned**: Permanent reference beads (like agent beads, role beads)

The output currently says:
```
📌 Pinned: gt-3amkz: Overhaul autonomous-mode guidance...
No molecule attached
```

Should say:
```
🪝 Hooked: gt-3amkz: Overhaul autonomous-mode guidance...
No molecule attached
```

Additional improvements:
1. Change icon from 📌 to 🪝 for hooked beads
2. Add a note clarifying that hooked work triggers autonomous mode even without an attached molecule
3. Consider adding "AUTONOMOUS MODE" banner when hooked work is found (similar to gt prime)

Files to update:
- internal/cmd/molecule_status.go (outputMoleculeStatus function around line 576)


mol-polecat-arm

Single polecat inspection and action cycle.

This molecule is bonded dynamically by mol-witness-patrol's survey-workers step.
Each polecat being monitored gets one arm.

## Variables

| Variable | Required | Description |
|----------|----------|-------------|
| polecat_name | Yes | Name of the polecat to inspect |
| rig | Yes | Rig containing the polecat |

## Steps

### capture
Capture recent tmux output for this polecat.

```bash
tmux capture-pane -t gt-{{rig}}-{{polecat_name}} -p | tail -50
```

Record:
- Last activity timestamp (when was last tool call?)
- Visible errors or stack traces
- Completion indicators ("Done", "Finished", etc.)

### assess
Categorize polecat state.

States:
- **working**: Recent tool calls, active processing
- **idle**: At prompt, no recent activity
- **error**: Showing errors or stack traces
- **requesting_shutdown**: Sent LIFECYCLE/Shutdown mail
- **done**: Showing completion indicators

Calculate: minutes since last activity.
Needs: capture

### load-history
Read nudge history for this polecat from patrol state.

```
nudge_count = state.nudges[{{polecat_name}}].count
last_nudge_time = state.nudges[{{polecat_name}}].timestamp
```

Needs: assess

### decide
Apply the nudge matrix to determine action.

| State | Idle Time | Nudge Count | Action |
|-------|-----------|-------------|--------|
| working | any | any | none |
| idle | <10min | any | none |
| idle | 10-15min | 0 | nudge-1 (gentle) |
| idle | 15-20min | 1 | nudge-2 (direct) |
| idle | 20+min | 2 | nudge-3 (final) |
| idle | any | 3 | escalate |
| error | any | any | assess-severity |
| requesting_shutdown | any | any | pre-kill-verify |
| done | any | any | pre-kill-verify |

Nudge text:
1. "How's progress? Need any help?"
2. "Please wrap up soon. What's blocking you?"
3. "Final check. Will escalate in 5 min if no response."

Record decision and rationale.
Needs: load-history

### execute
Take the decided action.

**nudge-N**:
```bash
tmux send-keys -t gt-{{rig}}-{{polecat_name}} "{{nudge_text}}" Enter
```

**pre-kill-verify**:
```bash
cd polecats/{{polecat_name}}
git status                    # Must be clean
git log origin/main..HEAD     # Check for unpushed
bd show <assigned-issue>      # Verify closed/deferred
```
If clean: kill session, remove worktree, delete branch
If dirty: record failure, retry next cycle

**escalate**:
```bash
gt mail send mayor/ -s "Escalation: {{polecat_name}} stuck" -m "..."
```

**none**: No action needed.

Record: action taken, result, updated nudge count.
Needs: decide

## Output

The arm completes with:
- action_taken: none | nudge-1 | nudge-2 | nudge-3 | killed | escalated
- result: success | failed | pending
- updated_state: New nudge count and timestamp

This data feeds back to the patrol's aggregate step.

Labels: [template, christmas-ornament, polecat-arm]


Merge: gt-7919

branch: polecat/furiosa
target: main
source_issue: gt-7919
rig: gastown


Add runtime configuration for LLM commands

## Problem
Claude CLI invocation is hardcoded in 6+ places:
```go
"claude --dangerously-skip-permissions"
"claude --dangerously-skip-permissions \"gt prime\""
```

## Solution
Add runtime configuration to rig or town settings:

```toml
# settings/runtime.toml or in config.json
[agent]
runtime = "claude"

[agent.claude]
command = "claude"
args = ["--dangerously-skip-permissions"]
initial_prompt = ""  # Empty - hooks handle context

[agent.aider]
command = "aider"
args = ["--no-git"]
initial_prompt = "/help"
```

## Interface
```go
type RuntimeConfig struct {
    Command       string
    Args          []string
    InitialPrompt string  // Optional: first user message
}

func LoadRuntimeConfig(rigPath string) (*RuntimeConfig, error)
func (rc *RuntimeConfig) BuildCommand() string  // Returns full command line
```

## Usage
All startup paths read config instead of hardcoding:
```go
cfg := LoadRuntimeConfig(rigPath)
cmd := cfg.BuildCommand()  // "claude --dangerously-skip-permissions"
t.SendKeys(session, cmd)
```


Digest: mol-deacon-patrol

Patrol 49: All healthy


Digest: mol-deacon-patrol

Patrol 245 complete: no incidents


Digest: mol-deacon-patrol

Patrol #9: nominal


Update config location: .gastown/ → config/

Move rig configuration from hidden .gastown/ to visible config/:
- config/rig.json: Rig configuration
- config/engineer.json: Engineer settings (test command, etc.)
- config/witness.json: Witness settings (heartbeat interval, etc.)

Hidden directories are poorly discovered by AI agents.


Digest: mol-deacon-patrol

Patrol 12: All clear


gt molecule seed: create built-in molecules as beads

The molecule infrastructure is complete but built-in molecules (engineer-in-box, quick-fix, research) need to be seeded into the beads database.

## Current State
- `gt molecule list` works but shows 0 molecules
- BuiltinMolecules() in internal/beads/builtin_molecules.go has 3 molecules defined
- No way to create them as beads

## Needed
Add `gt molecule seed` command that:
1. Reads BuiltinMolecules()
2. Creates each as a bead with type: molecule
3. Uses well-known IDs (mol-engineer-in-box, mol-quick-fix, mol-research)
4. Idempotent (skip if already exists)

## Acceptance Criteria
```
gt molecule seed
gt molecule list   # Shows 3 built-in molecules
```

## Parent
gt-4nn: Molecules epic


Code review: session health monitoring (gt-i7wcn)

Review the session health monitoring and auto-restart implementation in internal/cmd/session.go, internal/daemon/daemon.go, and internal/daemon/lifecycle.go


attached_args: Extract molecule_lifecycle boilerplate

Extract duplicate boilerplate in molecule_lifecycle.go.

## Files to modify
- internal/cmd/molecule_lifecycle.go

## Current duplication
runMoleculeBurn (lines 17-53) and runMoleculeSquash (lines 121-165) share ~50 lines of identical target detection code:
- Get cwd
- Find workspace
- Parse target argument
- Determine rig from address or role

## Implementation
Extract helper function:
```go
type AgentContext struct {
    TownRoot string
    RigName  string
    Role     string
    Target   string  // polecat name or crew name
}

func getTargetAgentContext(args []string) (*AgentContext, error) {
    cwd, err := os.Getwd()
    if err != nil {
        return nil, fmt.Errorf("getting current directory: %w", err)
    }
    townRoot, err := workspace.FindFromCwd()
    if err != nil {
        return nil, fmt.Errorf("finding workspace: %w", err)
    }
    if townRoot == "" {
        return nil, fmt.Errorf("not in a Gas Town workspace")
    }
    // ... rest of target detection logic ...
}
```

## Acceptance criteria
- [ ] AgentContext struct defined
- [ ] getTargetAgentContext function extracts shared logic
- [ ] runMoleculeBurn uses getTargetAgentContext
- [ ] runMoleculeSquash uses getTargetAgentContext
- [ ] Duplicate code eliminated (diff shows net negative lines)
- [ ] go build ./... passes
- [ ] go test ./internal/cmd/... passes


gt-deacon

Deacon (daemon beacon) - receives mechanical heartbeats, runs town plugins and monitoring.

role_type: deacon
rig: null
agent_state: idle
hook_bead: null
role_bead: gt-deacon-role


Deacon Role Definition

You are the Deacon - the town-level lifecycle manager.

You run patrol cycles checking the health of all agents across all rigs,
nudging stuck workers, and managing session lifecycles.

session_pattern: gt-deacon
work_dir_pattern: {town}
needs_pre_sync: false
start_command: exec claude --dangerously-skip-permissions

default_molecule: mol-deacon-patrol
capabilities:
  - health_monitoring
  - session_lifecycle
  - cross_rig_visibility
  - agent_nudging

## Core Responsibilities

1. Run patrol cycles across all rigs
2. Monitor agent health and progress
3. Nudge stuck agents
4. Manage session lifecycles (kill/restart)
5. Escalate systemic issues to Mayor

## Patrol Cycle

Each patrol:
1. Check all agent sessions (gt status)
2. Identify stuck or idle agents
3. Nudge or restart as needed
4. Log patrol results
5. Sleep until next cycle

## Propulsion Principle

If you find something on your hook, YOU RUN IT.

Your work is the mol-deacon-patrol wisp. Execute patrol steps continuously.

## Commands

- gt status - Check all agents
- tmux kill-session -t <session> - Kill stuck session
- gt mail send <addr> - Communicate with agents
- gt mail send mayor/ - Escalate to Mayor

## Session Cycling

When context fills, hand off to fresh session:
gt handoff -s "Deacon patrol handoff" -m "Completed N cycles..."


Digest: mol-deacon-patrol

Patrol 67: Routine


Merge: slit-mjw18vx8

branch: polecat/slit-mjw18vx8
target: main
source_issue: slit-mjw18vx8
rig: gastown
agent_bead: gt-gastown-polecat-slit


P4: Graceful degradation without tmux

Low-priority: Add graceful degradation for environments without tmux.

Current state: Patrol formulas use tmux capture-pane for observing agent state.

tmux-independent alternatives (degraded mode):
1. Tail Claude Code session logs if available
2. Rely solely on agent bead state (less real-time)
3. Use claude --output-file and tail that
4. IPC mechanisms (named pipes, sockets)

NOT launch-blocking. By summer 2025, Claude Code is expected to add signaling and reflection features that will obviate tmux scraping.

For now:
- Keep tmux as primary observation mechanism
- Document the tmux dependency
- Add --no-tmux flag that falls back to bead-only observation

This is P4 backlog - address after liftoff.


Merge: toast-1767074299802

attached_args: Code review this merge request

branch: polecat/toast-1767074299802
target: main
source_issue: toast-1767074299802
rig: gastown


Digest: mol-deacon-patrol

Patrol 10: All green - halfway mark


Merge: dementus-mjxemx4j

branch: polecat/dementus-mjxemx4j
target: main
source_issue: dementus-mjxemx4j
rig: gastown
agent_bead: gt-gastown-polecat-dementus
Note: Session stopped without DONE - Witness cleanup


Add gate checking to Deacon patrol loop

Integrate gate checking into Deacon's patrol cycle.

## Patrol Integration
```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")
        }
    }
}
```

## Moved from beads
Originally bd-is6m. Deacon is in gastown, not beads.


Digest: mol-deacon-patrol

Patrol complete: inbox empty, polecats healthy (furiosa/nux idle), witness/refinery running, no orphans


Merge: capable-mjxogaq4

branch: polecat/capable-mjxogaq4
target: main
source_issue: capable-mjxogaq4
rig: gastown
agent_bead: gt-gastown-polecat-capable


gt handoff deadlock at handoff.go:125

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


Digest: mol-deacon-patrol

Patrol cycle 37: All healthy, no incidents


Merge: nux-1767081106779

branch: polecat/nux-1767081106779
target: main
source_issue: nux-1767081106779
rig: gastown


Merge: gt-ldk8

branch: polecat/nux
target: main
source_issue: gt-ldk8
rig: gastown


Add harness overview to Mayor priming

Update gt prime Mayor context to explain the harness concept: umbrella repo for GT installation, rigs underneath, Mayor sits above all rigs


Digest: mol-deacon-patrol

Patrol 125: All healthy


Merge: cheedo-1767079863534

branch: polecat/cheedo-1767079863534
target: main
source_issue: cheedo-1767079863534
rig: gastown


Digest: mol-deacon-patrol @ 2025-12-24 19:46

Patrol 13: All healthy


Digest: mol-deacon-patrol

Patrol cycle 6: All 6 agents healthy


Digest: mol-deacon-patrol

Patrol #17: Stable


Digest: mol-deacon-patrol

Patrol 17: quiet


Digest: mol-deacon-patrol

Patrol 3: all clear


BUG: gt status shows 'stopped' for running sessions (bead vs tmux mismatch)

## Problem

`gt status` shows agents as 'stopped' when their tmux session is actually running:

```
🐺 Deacon
   gt-deacon stopped     ← But session exists!
```

Meanwhile:
```bash
$ tmux has-session -t gt-deacon && echo exists
exists
```

## Root Cause

Status display uses agent bead state, not tmux session state. When they disagree, the display is misleading.

## Current Logic

```go
// Simplified
if agentBead.State == "running" {
    display "running"
} else {
    display "stopped"
}
```

## Expected Logic

```go
beadState := agentBead.State
sessionExists := tmux.HasSession(sessionName)

if beadState == "running" && sessionExists {
    display "running"
} else if beadState == "running" && !sessionExists {
    display "running [dead]"  // Bead thinks running, session gone
} else if beadState != "running" && sessionExists {
    display "stopped [session exists]"  // Session exists but bead says stopped
} else {
    display "stopped"
}
```

## Related

The 'running [dead]' state already exists for witness/refinery. This should be consistent across all agents.


Digest: mol-deacon-patrol

Patrol #20: Final cycle - all agents healthy. Beads 5 MQ pending, gastown 1 MQ pending. 1 dog idle. Clean handoff.


Digest: mol-deacon-patrol

Cycle 184: All systems nominal


Deacon patrol: Backup check for idle polecats that should be nuked

## Context
Witness is responsible for nuking polecats after completion (gt-xqh3y).
Deacon should have a backup check in case witness fails.

## Deacon Patrol Step
During patrol, check for polecats that are:
- State: idle
- Session: not running
- No hooked work
- Last activity > N minutes ago

These are zombies that witness should have nuked. Deacon should:
1. Log warning about witness failure
2. Nuke the polecat directly
3. Optionally notify mayor of witness issue

## Defense in Depth
Primary: Witness nukes after POLECAT_DONE
Backup: Deacon patrol catches stragglers


Split PGT/GGT harness or migrate to GGT-only

Current ~/ai harness is shared by PGT and GGT with confusing overlap. Options:
1. Keep separate (document the coexistence)
2. Migrate fully to GGT structure
3. Create separate harnesses

This affects the beads redirect, Mayor home location, and rig structure.


Digest: mol-deacon-patrol

Patrol #1: All witnesses running, wyvern refinery started, 3 convoys active (Hanoi/Boot+Polish/Messaging), no orphans, inbox clear


Digest: mol-deacon-patrol

Patrol cycle 1: All 3 rigs healthy. 0 messages processed. Witnesses/refineries pinged.


Digest: mol-deacon-patrol

Patrol 142: 3 polecats working, all agents healthy


Add no-PR instructions to mol-polecat-work at two points

Update mol-polecat-work in builtin_molecules.go to explicitly forbid GitHub PRs.

## Two Points to Add Instructions

### 1. submit-work step
When polecat is ready to submit:
- Push branch to origin
- Create beads merge-request issue
- DO NOT use gh pr create or GitHub PRs

### 2. CLAUDE.md polecat context
Add to polecat role instructions:
- Never use gh pr create
- Never create GitHub pull requests
- The Refinery processes merges via beads MR issues

## Why Two Points
- Molecule step description guides the workflow
- CLAUDE.md reinforces at context level
- Belt and suspenders approach

## Implementation
1. Update PolecatWorkMolecule() submit-work step description
2. Update prompts/roles/polecat.md with explicit prohibition

Related: gt-44wh (general no-PR bug)


Digest: mol-deacon-patrol

Patrol cycle 2: all quiet, agents healthy


mol-ready-work: graceful GitHub/label handling

## Summary

mol-ready-work assumes:
- GitHub repo exists with gh CLI configured
- Labels 'untriaged' and 'triaged' exist

Should handle gracefully:
1. No GitHub repo (beads-only project) → skip GH backlogs
2. Missing labels → skip that backlog tier, don't error
3. gh CLI not authenticated → warn and skip GH backlogs

## Implementation
Add checks in scan-backlogs step:
```bash
# Check if gh is available and authenticated
if gh auth status &>/dev/null; then
  # scan GH backlogs
fi
```

## Parent
Part of gt-tnca (mol-ready-work epic)


gt mol status: role detection fails from polecat directory

When running 'gt mol status' from a polecat's worktree directory (e.g., ~/gt/gastown/polecats/furiosa), the role detection incorrectly returns 'mayor' instead of 'gastown/furiosa'.

## Root Cause
The detectRole() function in prime.go calculates relPath from townRoot (~gt) to cwd (~/gt/gastown/polecats/furiosa), giving 'gastown/polecats/furiosa'. It then checks parts[0] == 'mayor' but 'gastown' != 'mayor', so it falls through to rig detection where it treats 'gastown' as a rig name.

However, the code then looks for parts[1] == 'polecats' but the actual check is parts[1] == 'polecats' which should work...

## Actual Issue
Need to debug further - the hook file IS created correctly by spawn, but gt mol status can't find it because it's looking for the wrong agent identity.

## Expected
Running from ~/gt/gastown/polecats/furiosa should detect:
- Role: polecat
- Rig: gastown
- Polecat: furiosa
- Agent identity: gastown/furiosa

## Actual
- Role: mayor
- Agent identity: mayor

This prevents polecats from seeing their slung work via gt mol status.


gt handoff: Deadlock in waitForRetirement


attached_args: Refactor runStartCrew into focused helper functions

Break up the 155-line runStartCrew function in start.go.

## Files to modify
- internal/cmd/start.go

## Current structure (lines 638-792)
runStartCrew does:
1. Parse crew target (rig/name)
2. Load rig config
3. Get/create crew workspace
4. Create/attach tmux session
5. Set environment variables
6. Apply theming
7. Start Claude

## Refactoring plan
Extract these helpers:
```go
func parseCrewTarget(args []string) (rigName, crewName string, err error)
func ensureCrewWorkspace(rig *rig.Rig, crewName string) (*crew.CrewWorker, error)
func startCrewSession(worker *crew.CrewWorker, opts CrewStartOpts) error
```

## Acceptance criteria
- [ ] runStartCrew reduced to <60 lines
- [ ] 3 helper functions extracted
- [ ] Each helper is <50 lines
- [ ] No change in behavior
- [ ] go test ./internal/cmd/... passes
- [ ] Manual test: gt start crew works correctly


Digest: mol-deacon-patrol

Patrol 18


Define Engineer as the Refinery agent role

Clarify the distinction:

- **Refinery** = place/module/directory/workspace
  - `<rig>/refinery/` directory structure
  - `gt refinery start/stop/status` commands
  - tmux session name: `refinery` or `<rig>-refinery`

- **Engineer** = role/agent who works in the Refinery
  - CLAUDE.md prompting: "You are an Engineer..."
  - Documentation: "The Engineer processes merge requests..."
  - Mail address: `<rig>/engineer` (or `<rig>/refinery`?)

Updates needed:
- Add Engineer role description to docs
- Update CLAUDE.md templates for refinery agents
- Keep `gt refinery` commands as-is (they manage the place)
- Internal code stays `internal/refinery/` (the module)

Future consideration: Multiple Engineers in one Refinery for parallel merge processing.


Witness: active polecat monitoring and nudging

## Problem
Witness runs but doesn't actively monitor polecats during patrol.

## ZFC-Compliant Solution
Add step to `mol-witness-patrol.formula.toml`:

```toml
[[step]]
id = "survey-polecats"
title = "Survey polecat health"
description = """
For each polecat in this rig:
1. Run: gt peek <rig>/<polecat> 20
2. Check if work is pinned: gt mol status --rig <rig>/<polecat>
3. If pinned but idle (no recent output), nudge: gt nudge <rig>/<polecat> "You have work on hook"
4. If stuck >15min with no progress, escalate to Mayor via mail
"""
depends_on = ["inbox-check"]
```

## Why This Works
- Witness Claude agent reads formula step
- Agent decides what "stuck" means (uses judgment)
- Agent runs gt commands (CLI can exist)
- No Go code makes decisions

## Files
- formulas/mol-witness-patrol.formula.toml


Digest: mol-deacon-patrol

Patrol 2: No changes from cycle 1, all healthy


Digest: mol-deacon-patrol

Patrol 105: All agents healthy, no incidents


Digest: mol-deacon-patrol

Patrol #13


Review: Deacon town-level wisp storage (gt-ci84)

Polecat slit implemented town-level wisp storage for deacon patrol. Review the changes to ensure deacon wisps are correctly stored in ~/gt/.beads-wisp/ instead of gastown rig beads.


Digest: mol-deacon-patrol

Patrol cycle 77: All healthy


Update swarm terminology to streams

Gas Town moved from batch swarms to continuous streaming of polecats. Update:
- Docs and designs
- Code comments
- CLI flags (remove --swarm if present, or reframe)
- Variable/function names where appropriate

Streams reflect the reality: polecats flow continuously, not in discrete batches.


Digest: mol-deacon-patrol

Patrol #8: nominal


Digest: mol-deacon-patrol

Patrol 17: Green


Merge: rictus-mjxemkiq

branch: polecat/rictus-mjxemkiq
target: main
source_issue: rictus-mjxemkiq
rig: gastown
agent_bead: gt-gastown-polecat-rictus