CI: GitHub Actions workflow for integration tests

Set up CI to run integration tests:

## Requirements
- Run on PRs touching: internal/cmd/install.go, internal/cmd/rig.go, internal/config/
- Use build tag: //go:build integration
- Timeout: 5 minutes max
- Cache Go modules

## Workflow structure
```yaml
name: Integration Tests
on:
  pull_request:
    paths:
      - 'internal/cmd/install.go'
      - 'internal/cmd/rig.go'
      - 'internal/config/**'
      - 'internal/routing/**'
jobs:
  integration:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
      - run: go test -tags=integration ./...
```


Heartbeat convention: simple liveness signal for agents

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

**Implementation**: Each agent writes a timestamp file on activity:
```bash
echo '{"ts":"'$(date -Iseconds)'"}' > ~/gt/<role>/heartbeat.json
```

**Integration points**:
- SessionStart hook writes heartbeat
- Periodic activity (mail check, work completion) refreshes it
- `gt status` shows staleness (e.g., 'mayor: 5m ago')

**Weight**: ~5 lines per agent
**Value**: Quick debugging - see which agents are active at a glance

No monitoring daemon needed - human checks `gt status` when curious.


Digest: mol-deacon-patrol

Patrol 20: All healthy - handoff cycle


Test session event


Digest: mol-deacon-patrol

Patrol 158: All healthy


Fix potential race conditions in state file operations

Non-atomic state file operations could cause data loss:

All packages with state files (witness, refinery, crew, swarm):
State is loaded, modified, and saved without locking:
  ref, err := m.loadState()
  // ... modify ref ...
  return m.saveState(ref)

If two processes modify state simultaneously, one update may be lost.

internal/polecat/namepool.go (lines 179-194):
Save() uses RLock() but performs file I/O - should use write lock.

internal/swarm/manager.go:
swarms map[string]*Swarm accessed without mutex but multiple goroutines could call Create/GetSwarm.

Suggestion:
1. Use file locking (flock) for critical state updates
2. Or use atomic write pattern (write to temp, then rename)
3. Add mutex to swarm.Manager.swarms map


Pillar 2: Patrol Ignition

Witness and Refinery patrol loops fire reliably.

Key deliverables:
- Witness patrol reads agent beads for polecat state
- Witness sends MERGE_READY to refinery on completion
- Refinery processes MERGE_READY mail
- Both send completion signals

Subsumes existing work:
- gt-6qyt1: Refinery event-driven merge queue
- gt-qpwv4: Witness detect completion
- gt-dtw9u: Witness active monitoring

Reference: ~/gt/docs/liftoff-plan.md

Parent: gt-oki8p


BUG: Refinery checks git ls-remote instead of gt mq list

The refinery patrol checks 'git ls-remote origin | grep polecat' to see if there's work, but the merge queue is tracked in beads via 'gt mq list'. This caused 41 MRs to pile up while refinery reported 'Queue clear'.

Root cause: Refinery implementation is checking the wrong data source.

Fix: Change refinery patrol to use 'gt mq list <rig>' as the source of truth for pending merge requests.

Related: hq-eggh5

Fixed refinery template to remove misleading git branch grep reference and add explicit warnings about using gt mq list as the only source of truth


Digest: mol-deacon-patrol

Patrol 12: All clear


Digest: mol-deacon-patrol

Patrol 9 complete


Crew agent beads never created (dead code in reportAgentState)

## Problem

In prime.go, reportAgentState is called for ALL roles including crew workers.
The function calls bd.UpdateAgentState for crew with ID like gt-crew-gastown-max.

But crew agent beads are NEVER created:
- Polecats: Created on spawn (polecat/manager.go:167)
- Infrastructure: Created by doctor/install (doctor/agent_beads_check.go)
- Crew: Nothing creates them

The error is silently ignored, so this doesn't break anything, but it's dead code.

## Found in commit

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

## Decision

**Create crew agent beads** on first gt prime if they don't exist.

Crew workers are human-managed but their state is still valuable for:
- Town-wide status dashboards
- Understanding who's working on what
- Consistent agent bead model across all agent types

## Implementation

In prime.go reportAgentState(), before calling UpdateAgentState:
1. Try to get the agent bead
2. If it doesn't exist, create it with CreateAgentBead
3. Then update state as normal


Digest: mol-deacon-patrol

Patrol 1: All checks passed, no incidents. Witness/Refinery healthy, 1 dog idle, no polecats.


Digest: mol-deacon-patrol

Patrol 51: All healthy


Digest: mol-deacon-patrol

Patrol 9: Quiet


Digest: mol-deacon-patrol

Patrol 3: All healthy, no changes


Digest: mol-deacon-patrol

Patrol 12: quiet


Digest: mol-deacon-patrol

Patrol cycle 19: All healthy


Merge: capable-mjxdb1vx

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

Branches merged, cleaning up stale MR beads


Code Smell Cleanup: Gas Town Code Quality

Comprehensive code smell cleanup identified in code review session.

## Scope
Fixes for duplication, thread safety, missing tests, inconsistent patterns, and dead code.

## Child issues (18 total)

### Thread Safety & Data Integrity (P2)
- gt-wled7: Atomic write pattern for state files
- gt-xtsb5: Fix namepool Save() mutex
- gt-bp0ht: Add swarm.Manager mutex

### Duplication Removal (P2)
- gt-560ge: Extract processExists function
- gt-ddw3y: Extract molecule_lifecycle boilerplate
- gt-atqr8: Session name helper functions
- gt-ov2uv: AgentIdentity type for parsing

### Missing Tests (P2)
- gt-p2eg5: Lock package tests
- gt-0vu9e: mrqueue package tests
- gt-1pelm: mail router/mailbox tests

### Code Quality (P2)
- gt-gcnnr: Add logging for ignored errors

### Constants Extraction (P3)
- gt-4u682: SupportedShells constant
- gt-795e8: Timing constants

### Refactoring (P3)
- gt-tkbd5: Refactor runStart
- gt-dsqxw: Refactor runStartCrew

### Error Handling (P3)
- gt-h3skz: Remove os.Exit from RunE
- gt-g6kor: Standardize warning output

### Dead Code (P4)
- gt-2g130: Remove unused code

## Acceptance criteria
- [ ] All child issues closed
- [ ] go build ./... passes
- [ ] go test ./... passes
- [ ] go test -race ./... passes


Digest: mol-deacon-patrol

Patrol #19: Dog pool healthy, 1 idle.


Digest: mol-deacon-patrol

Patrol 6: Routine


Digest: mol-deacon-patrol

Patrol complete: inbox empty, 2 polecats working, all agents healthy


Digest: mol-deacon-patrol

Patrol cycle 19: All 6 agents healthy


Digest: mol-deacon-patrol

Patrol 12: all healthy


Digest: mol-deacon-patrol

Patrol cycle 78: All healthy


Config directory and schema for messaging

Create ~/gt/config/ directory structure for messaging configuration.

## Deliverables

1. Create ~/gt/config/ directory
2. Define JSON schema for lists.json:
   ```json
   {
     "oncall": ["mayor/", "gastown/witness"],
     "cleanup/gastown": ["gastown/witness", "deacon/"]
   }
   ```
3. Define JSON schema for queues.json (if separate from lists)
4. Add config loading utility in internal/config/

## Acceptance
- Config directory exists
- Schema documented
- Load/parse functions work


Digest: mol-deacon-patrol

Patrol complete: 0 callbacks, no gates, all witnesses/refineries healthy, no orphans


Merge: toast-1767146237529

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


Digest: mol-deacon-patrol

Patrol 11: all clear


Digest: mol-deacon-patrol

Patrol 149 complete


Merge: rictus-mjtlq9xg

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


Merge: rictus-1767084016819

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


Polecat sessions terminate unexpectedly during work

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

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

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

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

Implemented session health monitoring and auto-restart for crashed polecats. Changes include: (1) daemon now proactively checks polecat session health and auto-restarts crashed sessions with work-on-hook, (2) added polecat support to lifecycle identity mapping, (3) added 'gt session check' command for manual health checking.


Digest: mol-deacon-patrol

Cycle 193: Nominal


Merge: toast-1767146237529


Digest: mol-deacon-patrol

Patrol 3: 3 rigs healthy, no incidents


Review: Beads Universal Data Plane documentation

Review new docs/beads-data-plane.md (275 lines) for accuracy.

## Commit
- 54c8269: Add Beads Universal Data Plane documentation

## Review focus
- Accuracy of beads architecture description
- Correct field mappings (mail → beads fields)
- Two-level architecture (town vs rig beads) correctly explained


Polecat didn't commit before gt done

Integration test gt-7psb8: Polecat furiosa ran gt done before committing changes.

The polecat:
1. Created a test file
2. Closed the bead with bd close --force
3. Ran bd sync
4. Ran gt done

But it NEVER ran:
- git add <file>
- git commit

Result: Branch pushed with no new commits. Refinery detected branch at same commit as main.

The polecat CLAUDE.md or session close protocol should enforce commit before gt done.


Digest: mol-deacon-patrol

Patrol cycle 12


Digest: mol-deacon-patrol

Patrol 103: All agents healthy, no incidents


crew_add.go: Agent bead ID uses wrong format

In internal/cmd/crew_add.go:84, the agent bead ID is constructed as:

  crewID := fmt.Sprintf("gt-crew-%s-%s", rigName, name)

This produces 'gt-crew-gastown-joe' but existing beads and the session name format use:

  gt-<rig>-crew-<name>  (e.g., gt-gastown-crew-joe)

This causes agent beads to not be found/matched properly.

Fix: Change line 84 to:

  crewID := fmt.Sprintf("gt-%s-crew-%s", rigName, name)

Already fixed by max in c31bff4 - now uses beads.CrewBeadIDWithPrefix()


Digest: mol-deacon-patrol

P13: stable


Digest: mol-deacon-patrol

Patrol 5: Routine


Digest: mol-deacon-patrol

Patrol cycle 17: All healthy


Digest: mol-deacon-patrol

Patrol 8: All healthy


CRITICAL: Merge formula CLI scaffold (gt-gpifj)

Commit 60da7926 (formula CLI scaffold) is on branch polecat/nux-mjw18ii8 but NOT merged to main. This blocks formula execution functionality. Main still has old formulas.go that just delegates to bd formula list.


Digest: mol-deacon-patrol

Patrol 18: Quiet


Agent bead creation uses wrong prefix for non-gastown rigs

When adding a polecat to beads rig, agent bead creation fails:
  Error: issue ID 'gt-polecat-beads-Toast' does not match configured prefix 'bd'

The agent bead ID should use the rig's prefix (bd-) not hardcoded gt-.

Fixed: Added WithPrefix variants to agent bead ID functions, updated crew_add.go, rig/manager.go, and doctor/agent_beads_check.go to use rig's configured prefix


Formula SDK: Developer Tooling for Workflow Authors

SDK for creating, testing, debugging, and validating formulas.

## Components

### Forge (Creation)
```bash
mol forge new my-workflow        # Scaffold new formula
mol forge extend base-workflow   # Create variant
mol forge lint my-workflow       # Check syntax/style
```

### Lab (Testing)
```bash
mol lab run my-workflow --dry-run   # Mock execution
mol lab test my-workflow            # Run formula tests
mol lab trace my-workflow           # Step-through debug
```

### Validator (Verification)
```bash
mol validate my-workflow                    # Check well-formedness
mol validate my-workflow --protocol=Reviewable  # Check protocol compliance
mol validate my-workflow --schematic=shiny  # Check schematic compatibility
```

### Analyzer (Static Analysis)
```bash
mol analyze my-workflow --deps     # Dependency graph
mol analyze my-workflow --coverage # Step coverage
mol analyze my-workflow --cycles   # Detect cycles
```

## Relationship to Other Concepts

The SDK operates on:
- Formulas (source level)
- Protos (compiled level)
- Molecules (runtime level)

And validates against:
- Protocols (type system)
- Schematics (domain composition)

## Open Questions

1. Bundled vs separate - mol subcommands or formula-kit binary?
2. IDE integration - LSP for formula files?
3. Test harness - how to mock steps? fixtures?

## Related

- docs/formula_evolution.md - "SDK Question" section
- gt-8tmz.30 - Proto debugging tools (subset)
- gt-8tmz.31 - Formula validation (subset)


Merge: gt-2hwi9

branch: polecat/furiosa-mjw349y2
target: main
source_issue: gt-2hwi9
rig: gastown
agent_bead: gt-gastown-polecat-furiosa


Digest: mol-deacon-patrol

Patrol cycle 1: All healthy - 3 rigs, 6 agents, 1 dog idle, no issues


gt convoy list --tree: Show convoy + child status tree

Add a --tree flag to 'gt convoy list' that shows convoys with their child issues in a tree format.

Example output:
```
🚚 hq-cv-wvqi6: Boot + Polish swarm (16/17)
├── ✓ bd-11lm: Increase ClaudeStartTimeout
├── ✓ bd-49oe: Cache GetGitDir()
├── ○ gt-74ivo: Witness: Don't nuke polecats with open MRs  ← remaining
└── ...

🚚 hq-cv-w3nm6: Messaging Channels (4/10)
├── ✓ gt-0q3cg: Add isQueueAddress()
├── ○ gt-27bzi: Add gt mail announces
└── ...
```

Makes convoy progress visible at a glance without running 'gt convoy status' on each one.

(Moved from hq-q3tki)


Day 1.1: Add type=agent to bead schema

Add agent as a valid bead type in the schema. This is the foundation for agent-as-bead.

Parent: gt-d0jqp

Re-opened: Close reason referenced non-existent commit 927e8374. Type=agent not yet implemented in bd CLI.


bd update --claim for work queue semantics

Atomic claim operation for work queue messages.

## Deliverables

1. Add --claim flag to bd update
2. Atomic operation:
   - Sets assignee to claimer
   - Sets status to in_progress
   - Fails if already claimed
3. Conflict detection:
   - If already claimed, return error: "already claimed by X"
4. Integration with gt mail for queue messages

## Example
```bash
gt mail queue cleanup/gastown  # See available work
bd update msg-xxx --claim       # Claim it atomically
# Returns error if someone else claimed first
```

## Dependencies
- queue: shared storage (gt-???)

## Acceptance
- --claim sets assignee + status atomically
- Double-claim returns clear error
- Works with queue messages

Implemented --claim flag for bd update: sets assignee + status atomically, fails if already claimed. Branch: feature/claim-flag pushed to beads repo.


Refinery: Add lifecycle-notify step to patrol

After successful merge in handleSuccess(), send lifecycle notification to Witness.

## Implementation

1. Add new mail type: `LIFECYCLE: work merged`
2. In engineer.go handleSuccess(), after closing MR and source issue:
   ```
   gt mail send <rig>/witness -s "LIFECYCLE: work merged" -m "
   Worker: <polecat>
   MR: <mr-id>
   Issue: <source-issue>
   Commit: <merge-commit>
   Action: Polecat work merged. Worktree eligible for recycling.
   "
   ```

3. Update mol-refinery-patrol to include lifecycle-notify step between merge-push and loop-check

## Acceptance
- Successful merges send mail to Witness
- Mail includes worker name, MR id, source issue, commit SHA


Witness: Handle LIFECYCLE work-merged mail

Witness should process the `LIFECYCLE: work merged` notification from Refinery.

## Implementation

1. In Witness mail processing, add handler for subject containing "LIFECYCLE: work merged"
2. Parse worker name from mail body
3. Update polecat state to `merged` (new state - see sibling task)
4. Log completion for metrics
5. Worktree is now eligible for cleanup on next gc cycle

## Acceptance
- Witness correctly parses and handles work-merged mail
- Polecat state updated to merged
- No action taken if polecat already cleaned up (idempotent)


MQ Submit: Notify Witness on MR submission

When `gt mq submit` is run, notify the Witness so it can verify the submission.

## Implementation

1. In mq_submit.go after successful MR creation:
   ```
   gt mail send <rig>/witness -s "LIFECYCLE: mr submitted" -m "
   Worker: <polecat>
   MR: <mr-id>
   Branch: <branch-name>
   Target: <target-branch>
   Action: Verify MR submission, help polecat if needed.
   "
   ```

2. This happens BEFORE the existing polecat auto-cleanup logic

## Acceptance
- MR submission sends notification to Witness
- Witness receives mail with all relevant details
- Works for both polecat and crew submissions


Witness: Verify MR submission on notification

When Witness receives `LIFECYCLE: mr submitted`, verify the submission was clean.

## Implementation

1. Add handler for "LIFECYCLE: mr submitted" mail
2. Check MR status: `gt mq status <mr-id>`
3. If MR looks good (status=open, no errors): log success, allow polecat to idle
4. If MR has issues:
   - Check polecat git state
   - Nudge polecat to fix if session still alive
   - Log issue for monitoring

## Acceptance
- Witness verifies MR after submission notification
- Can detect problematic submissions
- Provides early intervention opportunity


Polecat state tracking: Add mr_submitted and merged states

Track polecat lifecycle state separate from session state.

## New States

| State | Meaning |
|-------|---------|
| active | Working on assigned issue |
| mr_submitted | MR submitted, waiting for merge |
| idle | No current work, session may be alive |
| merged | Work successfully merged by Refinery |
| retired | Session killed, worktree removed |

## Implementation

1. Add state field to polecat tracking (state.json or beads)
2. `gt polecat update <name> --state=<state>`
3. `gt polecat list` shows state column
4. State transitions:
   - active → mr_submitted (on gt mq submit)
   - mr_submitted → merged (on Refinery notification)
   - merged → retired (on worktree cleanup)

## Acceptance
- Polecat state tracked and queryable
- State transitions happen at correct lifecycle points
- `gt polecat list` shows current state


Refinery patrol: Add sibling-check step

Refinery should check on Witness health as part of patrol (village sibling watch).

## Implementation

1. Add `sibling-check` step to mol-refinery-patrol (early in cycle)
2. Use `gt peek <rig>/witness 20` to check Witness output
3. Look for signs of health:
   - Recent activity (tool calls, log messages)
   - No error stack traces
   - Responsive to pings
4. If Witness seems stuck:
   - Send status request mail
   - Note for potential escalation
   - Don't block Refinery work

## Acceptance
- Refinery checks Witness each patrol cycle
- Anomalies logged
- Non-blocking (Refinery continues even if Witness is down)


Witness patrol: Add sibling-check for Refinery

Witness should check on Refinery health as part of patrol (village sibling watch).

## Implementation

1. Add `sibling-check` step to mol-witness-patrol
2. Use `gt peek <rig>/refinery 20` to check Refinery output
3. Check Refinery queue status: `gt mq list <rig>`
4. Look for:
   - Refinery session alive
   - Queue processing (if items present)
   - No stuck MRs (same MR in_progress for too long)
5. If Refinery seems stuck:
   - Send nudge or status request
   - Consider escalation to Deacon

## Acceptance
- Witness checks Refinery each patrol cycle
- Can detect stuck Refinery
- Provides backup oversight for merge queue


Recovery: Detect orphaned merged polecats

Safety net for when Refinery misses sending lifecycle notification.

## Detection Points

**Witness polecat-scan**:
- For each polecat in `mr_submitted` state:
  - Check MR status: `gt mq status <mr-id>`
  - If MR is closed/merged but polecat state is still mr_submitted:
    - Update polecat state to `merged`
    - Log recovery action

**Deacon orphan-check**:
- Query all closed MRs
- Cross-reference with polecat states
- If merged MR but polecat not in merged/retired state:
  - Send correction to Witness
  - Log for metrics (indicates Refinery notification missed)

## Acceptance
- Orphaned polecats detected and corrected
- Recovery is logged for monitoring
- No work lost due to missed notifications


Digest: mol-deacon-patrol

Patrol 16: all clear


gt sling: nudge crew/mayor if session is running

When slinging to crew or mayor, if they have an active tmux session, send a nudge notification so they know work has landed on their hook.

Currently only slingToPolecat nudges (lines 514-521 in internal/cmd/sling.go).

Missing nudge in:
- slingToCrew (line ~669)
- slingToMayor (line ~876)

NOTE: For patrol-based agents (witness, refinery, deacon), see gt-arjlu which handles nudging them when work is dispatched to polecats in their rig. That's a different pattern - not slinging TO them, but notifying them of activity.

Implementation:
1. For crew: need to determine session name (e.g., gastown-crew-max)
2. Check if session running via tmux
3. If running, call t.NudgeSession() with appropriate message


Merge: dementus-mjxaqvb9

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


Digest: mol-deacon-patrol

Patrol 66: Routine


Merge: furiosa-1767082251065

branch: polecat/furiosa-1767082251065
target: main
source_issue: furiosa-1767082251065
rig: gastown


Digest: mol-deacon-patrol

Patrol #4: All agents healthy.


Refactor formula transformation pipeline to shared helper

The formula transformation pipeline (control flow, advice, expansions, aspects) is duplicated between cook.go and mol_bond.go. Should be extracted to a shared function in the formula package.

Current duplication in:
- cmd/bd/cook.go:96-136
- cmd/bd/mol_bond.go:598-633

Suggested approach:
- Add formula.Transform(resolved *Formula, parser *Parser) (*Formula, error)
- Handles all transformation steps in order
- Both cook.go and mol_bond.go call this single function


Digest: mol-deacon-patrol

Patrol cycle 19: all healthy


Digest: mol-deacon-patrol

Patrol cycle 43: All healthy, no incidents


mol-deacon-patrol

Mayor's daemon patrol loop.

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


Liftoff test: Add timestamp comment to manager.go

Simple liftoff test task.

Add a comment at the top of internal/polecat/manager.go with the current timestamp, like:
// Liftoff test: <timestamp>

This tests the full polecat → refinery → witness cycle.


Digest: mol-deacon-patrol

Patrol 15: all healthy


Digest: mol-deacon-patrol

Patrol cycle 6: All healthy.


Digest: mol-deacon-patrol

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


Missing space in error messages (handoff.go, prime.go)

Minor typo in error messages at two locations:

**handoff.go L895**:
```go
fmt.Println(style.Dim.Render("Run manually: bd --no-daemon wisp" + protoID))
// Missing space before protoID
```

**prime.go L1061**:
Same issue.

**Fix**: Add space before protoID:
```go
fmt.Println(style.Dim.Render("Run manually: bd --no-daemon wisp " + protoID))
```


Digest: mol-deacon-patrol

Patrol 56: All healthy


Refactor all startup paths to use StartupNudge

## Files to Refactor

| File | Function | Current Approach |
|------|----------|------------------|
| start.go:788 | runStartCrew | SendKeys(claude) then SendKeys(gt prime) |
| start.go:747 | runStartCrew restart | Same |
| start.go:929 | another path | SendKeys without prime |
| crew_lifecycle.go:354 | restart | SendKeys(gt prime) after start |
| crew_lifecycle.go:525 | another path | Same |
| crew_at.go:154 | --detached | Claude arg "gt prime" ✓ |
| handoff.go:331 | handoff | Claude arg "gt prime" ✓ |
| deacon.go:294 | deacon start | Relies on hooks |
| witness.go:336 | witness start | Relies on hooks |
| polecat_spawn.go | spawn | Various |

## Pattern
Replace scattered logic with:
```go
cfg := StartupNudgeConfig{
    Recipient: address,
    Sender:    sender,
    Topic:     "cold-start",  // or "handoff", mol-id, etc.
}
if err := session.StartupNudge(t, sessionName, cfg); err \!= nil {
    // handle
}
```

## Dependencies
- gt-bgfqy: Create StartupNudge function
- gt-dc2fs: Add runtime configuration

Refactored all startup paths to use RuntimeConfig and helper functions. Updated 12+ files across cmd/, daemon/, session/, refinery/, and boot/ packages. All hardcoded 'claude --dangerously-skip-permissions' invocations now use config.GetRuntimeCommand(), config.BuildAgentStartupCommand(), config.BuildPolecatStartupCommand(), config.BuildCrewStartupCommand(), or config.BuildStartupCommand(). Build passes, all tests pass.


Day 5.1: End-to-end liftoff test

Full integration test:
1. gt sling gt-task123 gastown/nux
2. Watch polecat work (no manual intervention)
3. Watch refinery merge (no manual intervention)
4. Watch witness clean up (no manual intervention)
5. See cycle complete in bd activity or logs

Success = no human touches needed.

Parent: gt-oki8p


Digest: mol-deacon-patrol

Patrol 10: all clear


Digest: mol-deacon-patrol

Patrol 3: All agents healthy.


Merge: capable-mjw47ef9

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


refinery Handoff

# Merge queue tracking
last_processed_branch: null
branches_merged_this_cycle: 0


Digest: mol-deacon-patrol

Patrol cycle 15: All healthy


Digest: mol-deacon-patrol

Patrol 1 complete: inbox clear, 3 polecats working, fixed 3 stale locks


Digest: mol-deacon-patrol

Patrol 11: All healthy.


Digest: mol-deacon-patrol

Patrol cycle 13: all healthy


Digest: mol-deacon-patrol

Patrol complete: all agents healthy, 0 inbox messages, no orphans


Day 4.1: Implement gt polecat recycle command

Add gt polecat recycle <name> command:
- Kill the Claude session (tmux kill-session)
- Preserve the sandbox (branch/worktree)
- Update agent bead state to 'stopped'
- Leave for respawn on next step

This enables session-per-step.

Parent: gt-4a2qt


Digest: mol-deacon-patrol

Patrol 250 complete: no incidents


Digest: mol-deacon-patrol

Patrol 101: All agents healthy, 3 rigs checked, no incidents


Digest: mol-deacon-patrol

Patrol 80: Routine, completing 20-cycle handoff


Fix deprecated strings.Title in formula.go

formula.go uses deprecated strings.Title (Go 1.18+). Should use cases.Title(language.English).String() from golang.org/x/text/cases.

Replaced deprecated strings.Title with cases.Title from golang.org/x/text


Digest: mol-deacon-patrol

Patrol cycle 1: All 6 agents healthy, inbox clean, no incidents


gt crew add should provision .claude/commands/

When adding a crew member with 'gt crew add', provision the .claude/commands/ directory with standard commands like handoff.md.

Currently only polecats get this via the spawning process. Crew members are added manually and miss out on slash commands like /handoff.

Also: gt doctor should detect missing .claude/commands/ in crew directories and offer to fix.

Implemented commands provisioning for crew and polecat workspaces


Deacon has no rig-level presence - only global gt-deacon

The Deacon patrol role exists only at the global level (~/gt/deacon) but doesn't have per-rig presence like Witness and Refinery.

Current structure:
```
~/gt/
├── deacon/           ← Global deacon only
├── beads/
│   ├── witness/      ← Per-rig witness
│   ├── refinery/     ← Per-rig refinery
│   └── (no deacon)   ← Missing
└── gastown/
    ├── witness/
    ├── refinery/
    └── (no deacon)   ← Missing
```

Question: Should Deacon be per-rig like Witness/Refinery, or is global-only intentional?

If per-rig is needed: Create beads/deacon and gastown/deacon with appropriate CLAUDE.md files.


Digest: mol-deacon-patrol

Patrol cycle 34: All healthy, no incidents


Digest: mol-deacon-patrol

Patrol 19 complete


Digest: mol-deacon-patrol

Patrol 256 complete: no incidents


Merge: dementus-1767084022436

branch: polecat/dementus-1767084022436
target: main
source_issue: dementus-1767084022436
rig: gastown


Digest: mol-deacon-patrol

Patrol 93: All healthy


Digest: mol-deacon-patrol

Patrol cycle 3: All agents healthy


Digest: mol-refinery-patrol

Patrol: empty queue, inbox clean, no orphaned MRs


Digest: mol-deacon-patrol

Cycle 14: quiet


Digest: mol-deacon-patrol

Patrol 5 complete. All healthy.


Auto-create convoy when slinging single issue

When gt sling is used without an existing convoy context, auto-create one for dashboard visibility.

CURRENT:
gt sling bd-xyz beads/amber
# Issue assigned, but not tracked in convoy dashboard

DESIRED:
gt sling bd-xyz beads/amber
# -> Created convoy 'Work: bd-xyz' (hq-cv-xxx)
# -> Tracking bd-xyz
# -> Assigned to beads/amber

This ensures ALL work appears in gt convoy list, even 'swarm of one'.

IMPLEMENTATION:
File: internal/cmd/sling.go
1. Check if issue is already tracked by a convoy
2. If not, create convoy with title 'Work: <issue-title>'
3. Add tracks relation
4. Proceed with normal sling

OPTIONAL FLAG:
--no-convoy to skip auto-convoy creation

Implemented auto-convoy creation in gt sling


Digest: mol-deacon-patrol

Patrol 15: 3 rigs healthy


Digest: mol-deacon-patrol

Patrol #19


SQL injection in convoy.go:581

User input interpolated directly into SQL via fmt.Sprintf(). convoyID from args[0] used in: fmt.Sprintf(`SELECT depends_on_id, type FROM dependencies WHERE issue_id = '%s'`, convoyID). Fix: Use parameterized queries.

Fixed: escape single quotes in SQL query


Merge: dag-1767146241770

branch: polecat/dag-1767146241770
target: main
source_issue: dag-1767146241770
rig: gastown


Digest: mol-deacon-patrol

Patrol 6: 3 rigs healthy


Digest: mol-deacon-patrol

Patrol complete: all healthy, no events


Digest: mol-deacon-patrol

Patrol 12: 3 rigs healthy


Digest: mol-deacon-patrol

Cycle 190: 10-cycle checkpoint, all agents healthy


Crew startup missing metadata injection for gt seance

When crew members are started via 'gt crew start', they don't receive the metadata string that gt seance uses to identify running sessions. This makes it harder to track which crew sessions are active.

The metadata injection should happen during crew startup similar to how other agent types get their identifiers injected.

Fixed - now uses BuildCrewStartupCommand for proper env var injection


Digest: mol-deacon-patrol

Patrol cycle 1: All healthy - 19 polecats, witness/refinery running, 3 MQ items, no zombies


Digest: mol-deacon-patrol

Patrol cycle 12: All healthy


Digest: mol-deacon-patrol

Patrol 4: quiet, health OK


Platform of Platforms (POP) Foundation

Design and implementation of the Platform Adapter Layer for HOP. Enables multiple work platforms to integrate with the universal work ledger. See ~/gt/docs/hop/PLATFORM-OF-PLATFORMS.md for full architecture.


Define PlatformAdapter interface

Define the PlatformAdapter interface in Go. The interface specification is already
documented in ~/gt/docs/hop/PLATFORM-OF-PLATFORMS.md (lines 118-152).

**Location**: Create `internal/hop/platform.go` in the beads repo

**Interface methods** (from doc):
- Registration: GetPlatformID, GetPlatformMetadata
- Identity: MapIdentity, GetSovereigntyTier, ResolveEntity
- Work Translation: TranslateWorkUnit, TranslateToNative
- Validation: SubmitCompletion, QueryValidations
- Skills: ExtractSkills, GetSkillOntology
- Governance: GetPlatformRules, ValidateWork
- Payment (optional): GetPaymentRails, RecordPayment
- Federation: GetFederationEndpoint, CanFederateWith

**Supporting types needed**:
- SovereigntyTier enum (see gt-jzmsj.2)
- PlatformMetadata struct
- HopEntity (maps to existing EntityRef)
- HopWorkUnit (maps to existing Issue/Bead)
- ValidationRecord (maps to existing Validation)
- SkillVector, SkillOntology (stub for now)
- GovernanceRules, Violation
- PaymentRail, Payment, Receipt

**Acceptance criteria**:
1. Interface compiles and is documented
2. Types compile with reasonable defaults
3. No implementation yet - interface only


Add sovereignty tier to entity model

Add SovereigntyTier to the entity model. This determines what identity information
is revealed and to whom.

**Location**: beads repo, `internal/types/types.go`

**Changes required**:

1. Add SovereigntyTier type and constants:
```go
type SovereigntyTier string

const (
    TierPublic         SovereigntyTier = "public"         // Full legal identity, full visibility
    TierOrganizational SovereigntyTier = "organizational" // Known to org, private outside
    TierPseudonymous   SovereigntyTier = "pseudonymous"   // KYC verified, operates under handle
    TierAnonymous      SovereigntyTier = "anonymous"      // Cryptographic identity only
)
```

2. Add field to EntityRef:
```go
type EntityRef struct {
    // ... existing fields ...
    SovereigntyTier SovereigntyTier `json:"sovereignty_tier,omitempty"`
}
```

3. Add IsValid() method to SovereigntyTier

4. Update ComputeContentHash to include sovereignty tier

**Acceptance criteria**:
1. SovereigntyTier type with 4 values defined
2. EntityRef has optional sovereignty_tier field
3. Empty/missing tier defaults to "public" (backward compatible)
4. Content hash includes sovereignty tier
5. Tests pass


Gas Town as reference platform adapter

Implement Gas Town as the reference PlatformAdapter. This proves the interface works
and serves as a template for other platforms.

**Depends on**: gt-jzmsj.1 (interface must exist first)

**Location**: gastown repo, `internal/hop/gastown_adapter.go`

**Implementation mapping** (from ~/gt/docs/hop/PLATFORM-OF-PLATFORMS.md lines 381-398):
- Platform ID: "gastown"
- Sovereignty: Tier 2-3 (organizational/pseudonymous)
- Identity: Map BD_ACTOR format (rig/role/name) → HOP EntityRef
- Work Units: Beads (issues, molecules) → HopWorkUnit
- Validation: Refinery approvals → ValidationRecord
- Skills: Stub returning empty (future work)
- Governance: Return GUPP rules reference
- Payment: Return nil (future work)
- Federation: Return town URI

**Key mappings**:
- Issue → HopWorkUnit (1:1, most fields align)
- BD_ACTOR "gastown/crew/max" → EntityRef{Platform: "gastown", Org: "steveyegge", ID: "crew-max"}
- Validation struct → ValidationRecord (already aligned)

**Acceptance criteria**:
1. GasTownAdapter implements PlatformAdapter interface
2. MapIdentity correctly parses BD_ACTOR format
3. TranslateWorkUnit converts Issue to HopWorkUnit
4. Basic test coverage


Design skill ontology for cross-platform matching

Design the universal skill vocabulary that maps across platforms. This enables
matching workers to work across platform boundaries.

**Reference**: ~/gt/docs/hop/PLATFORM-OF-PLATFORMS.md (lines 331-357)

**Deliverable**: Design document defining:

1. **Skill representation**:
   - SkillVector struct (skill ID, level 0-5, evidence count, attestation count)
   - How levels are derived from work history
   - How attestations compound across platforms

2. **Ontology structure**:
   - Hierarchical skill taxonomy (e.g., Programming > Go > Concurrency)
   - Cross-platform skill equivalence mappings
   - Confidence scores for derived skills

3. **Extraction algorithm**:
   - How to derive skills from work units (keywords, labels, validation)
   - How to aggregate across platforms
   - Decay model for stale skills

4. **Example mappings**:
   - GitHub: languages, frameworks from commits/PRs
   - Enterprise: role competencies, certifications
   - Gas Town: labels, successful completions

**Acceptance criteria**:
1. Design doc in ~/gt/docs/hop/SKILL-ONTOLOGY.md
2. SkillVector and SkillOntology types sketched
3. Algorithm pseudocode for skill extraction
4. Example aggregation scenario


RPG platform design: gamification layer

Design the RPG UX metaphor - the flagship consumer experience for HOP.
Makes real work feel like a game because the game IS real work.

**Reference**: ~/gt/docs/hop/PLATFORM-OF-PLATFORMS.md (lines 188-214)

**Deliverable**: Design document defining:

1. **Core metaphor mappings**:
   - Quests = Work units (beads/issues)
   - Skills = Stats derived from work history
   - Leveling = Reputation accumulation
   - Guilds = Organizations
   - Loot = Payment/rewards

2. **Progression mechanics**:
   - XP calculation from work completions
   - Skill tree visualization
   - Level thresholds and prestige ranks
   - Achievement system

3. **Social features**:
   - Guild formation and management
   - Leaderboards (opt-in, privacy-aware)
   - Cooperative quests (swarming as raids)
   - Mentorship system

4. **Engagement hooks**:
   - Daily/weekly quest boards
   - Streak bonuses
   - Rare quest discovery
   - Boss battles (epic issues)

5. **Why it works**:
   - Progress feels real because it IS real
   - Stats are accurate because they're derived from actual work
   - Social proof from genuine collaboration

**Acceptance criteria**:
1. Design doc in ~/gt/docs/hop/RPG-PLATFORM.md
2. Core metaphor mappings defined
3. UI/UX wireframes or mockup descriptions
4. Privacy model (what's public vs. private
EOF
)


Digest: mol-deacon-patrol

Patrol 2 complete. All agents healthy.


Merge: slit-mjxlyyte

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


Digest: mol-deacon-patrol

Patrol cycle 9: All 3 rigs healthy. No incidents.


gt doctor: Add Boot health check (vet mode)

gt doctor should check Boot health:
- Is Boot directory present?
- Is Boot session alive?
- Last execution status (success/error)
- Marker file freshness

The vet checks on the dog.

Implemented Boot health check in gt doctor


Digest: mol-deacon-patrol

Cycle 297: All healthy, refinery busy


Day 3.0: Document mail protocol for patrol coordination

Document the mail protocol used for patrol coordination.

**Mail types:**
- POLECAT_DONE: Polecat → Witness (work complete, ready for merge)
- MERGE_READY: Witness → Refinery (branch ready for merge queue)
- MERGED: Refinery → Witness (merge complete, safe to nuke)
- WITNESS_PING: Witness → Deacon (health check for second-order monitoring)
- HELP: Any → escalation target (stuck, need intervention)
- HANDOFF: Any → self (session continuity)

**Format conventions:**
- Subject prefix indicates type (e.g., 'POLECAT_DONE: nux')
- Body contains structured data (branch, bead ID, etc.)

This documentation enables consistent implementation across all patrol formulas.


Day 5.0: gt status shows pinned role beads and slots

Enhance gt status to display:
- All pinned role beads (mayor, witness, refinery, polecats)
- Their current hook slot contents (what molecule/bead is attached)
- Agent state if available

This gives a single-command view of who's working on what across the town.

Example output:
```
gt status

Town: gastown
Daemon: running (pid 1234)

Agents:
  mayor/           gt-liftoff (pinned)     idle
  witness/gastown  gt-wisp-abc (patrol)    running
  refinery/gastown (empty)                 idle
  polecat/nux      gt-xyz (in_progress)    working
  polecat/rictus   (empty)                 idle
```


Digest: mol-deacon-patrol

Patrol 9: All healthy


Digest: mol-deacon-patrol

Patrol cycle 51: All healthy


Digest: mol-deacon-patrol

Patrol cycle 11: All agents healthy


Digest: mol-deacon-patrol

Patrol #2: All systems nominal, 3 convoys active, no incidents


Digest: mol-deacon-patrol

Patrol 18: routine


Build context self-check into patrol molecules

Patrol molecules (witness-patrol, refinery-patrol, deacon-patrol) should have
explicit context self-check as part of each cycle:

After each patrol cycle step:
- Self-assess context pressure
- If high: complete current step, then initiate handoff
- If OK: continue to next cycle

This could be:
1. Explicit step in molecule: 'context-check'
2. Guidance in step instructions: 'Before continuing, assess context...'
3. Protocol baked into the patrol loop description

The key is making it unavoidable - not optional guidance that gets ignored.


Document StartupNudge format in seance/session docs

## Context

The StartupNudge migration (gt-7pp3l) changed the session title format used for predecessor discovery.

## Format Change

```
Old: [GAS TOWN] address • molID • timestamp
New: [GAS TOWN] recipient <- sender • timestamp • topic[:mol-id]
```

## Documentation Needed

1. Update any docs referencing the old SessionBeacon format
2. Document the sender values and when each is used:
   - human: crew, mayor (human-managed)
   - daemon: deacon
   - deacon: witness
   - witness: polecats
   - self: handoff
3. Document the topic values:
   - cold-start, restart, refresh, patrol, assigned, dispatch, handoff

## Files to Check

- docs/understanding-gas-town.md
- docs/reference.md
- Role templates in internal/templates/

## Related

- gt-7pp3l: Migrate startup paths from SessionBeacon to StartupNudge
- gt-7qvd7: gt seance command

Removed SessionBeacon and documented StartupNudge format in reference.md


Swarm-in-Beads: Discovery-based swarm execution

Swarm-in-Beads: Make swarm state derive from beads, not separate JSON. See ~/gt/docs/swarm-architecture.md for full design. Core principles: discovery over tracking, ready front model, nondeterministic idempotence.

All children complete: swarm state now discovered from beads, Manager stateless, legacy swarms.json deleted


Refactor gt swarm to use beads backing

Migrate gt swarm commands from .runtime/swarms.json to beads molecules.

Current gt swarm stores state in .runtime/swarms.json - violating discovery over tracking.
The refactored version should use bd swarm create/status to work with beads molecules.

Implementation:
- gt swarm create calls bd swarm create
- gt swarm status calls bd swarm status
- gt swarm list queries bd list --mol-type=swarm
- Remove .runtime/swarms.json dependency

CROSS-RIG DEPENDENCIES (must complete first in beads repo):
- bd-oxgi: mol_type schema field
- bd-fa1q: bd swarm create command
- bd-5x0j: bd swarm status command

Reference: ~/gt/docs/swarm-architecture.md


Witness swarm integration

Add swarm coordination to Witness patrol.

The Witness should be able to:
1. Receive swarm assignments via mail (SWARM: subject prefix)
2. Query ready front and dispatch to available polecats
3. Monitor polecat progress on swarm tasks
4. Detect completion and close swarm molecule
5. Use Christmas Ornament pattern for arm-bonding (optional)

Implementation:
- Add swarm handling to mol-witness-patrol formula
- Mail trigger: SWARM in subject
- Dispatch: bd ready --parent=<epic> to find ready issues
- Assign: gt sling <issue> to available polecat
- Monitor: Check polecat status during patrol
- Complete: When bd ready --parent returns empty and all closed

Reference: ~/gt/docs/swarm-architecture.md - Witness Integration section

Dependencies: gt-kc7yj.1 (gt swarm refactor)

Added dispatch-swarm-work step to mol-witness-patrol formula. Witness can now dispatch ready swarm tasks to idle polecats via gt sling.


Swarm completion detection and auto-close

Detect when all epic children are closed and auto-close the swarm molecule.

Core logic:
1. After any issue closes, check if it was part of a swarm
2. Query bd list --parent=<epic> --status=open
3. If empty (all closed), close the swarm molecule
4. Fire completion event for activity feed

Can be implemented as:
- Part of Witness patrol
- Or as a bd hook triggered on issue close
- Or as a gt swarm check command called periodically

Reference: ~/gt/docs/swarm-architecture.md - Recovery Protocol

Dependencies: gt-kc7yj.1 (gt swarm refactor)

Implemented swarm completion detection and auto-close in Witness patrol formula


End-to-end swarm integration test

Full integration test for swarm lifecycle.

Test scenario:
1. Create a small epic with 3-4 issues and dependencies
2. Run bd swarm validate - should pass
3. Run gt swarm create with the epic
4. Verify swarm molecule created with mol_type=swarm
5. Run gt swarm status - verify ready front
6. Simulate issue completion (bd close)
7. Verify ready front advances
8. Complete all issues
9. Verify swarm auto-closes

Can be manual test documented in test file, or automated.

Dependencies: gt-kc7yj.2 (Witness integration), gt-kc7yj.3 (completion detection)

E2E swarm test complete. Validated: 1) Epic with DAG dependencies 2) bd swarm validate wave analysis 3) Swarm molecule creation with mol_type=swarm 4) Ready front advancement on issue close 5) 100% completion detection. Filed gt-594a4 for gt swarm routing bug. Documented test protocol in manager_test.go.


gt crew add: Agent bead uses hardcoded gt- prefix instead of rig prefix

When running 'gt crew add <name> --rig beads', the command tries to create an agent bead with ID 'gt-crew-beads-<name>' but beads rig uses 'bd' prefix.

Error: issue ID 'gt-crew-beads-grip' does not match configured prefix 'bd'

The agent bead ID should use the target rig's prefix, not hardcode 'gt-'.


Digest: mol-deacon-patrol

Patrol 20: all healthy - handoff


Code review: await-signal command (gt-vdprb.1)

Review the await-signal molecule step implementation in internal/cmd/molecule_await_signal.go

Code review complete: ACCEPT. Implementation is functional and safe. Found minor issues: (1) incomplete backoff iteration tracking (Medium), (2) stub GetCurrentStepBackoff function (Low), (3) potential goroutine leak on edge cases (Low), (4) no stderr capture (Low). No security or crash issues. Backoff enhancement can be filed as follow-up if needed.


Digest: mol-deacon-patrol

Patrol 219: All nominal


Digest: mol-deacon-patrol

Patrol cycle 4: All 3 rigs healthy. No incidents.


Refinery: Send MERGED notification to witness after merge

During liftoff test (gt-j0gx2), observed that refinery:
1. Received MERGE_READY for nux
2. Fetched, rebased, resolved conflicts correctly
3. Ran tests (passed)
4. Merged to main and pushed
5. Deleted polecat branch

But did NOT:
- Send MERGED mail to witness
- Close the MR bead (gt-5qkah)

The mol-refinery-patrol.formula.toml documents this step but the agent didn't execute it.

Impact:
- Witness never receives MERGED signal
- Polecat worktree never gets nuked
- MR beads accumulate as open

Fix:
After successful merge+push, refinery must:
```bash
gt mail send <rig>/witness -s "MERGED <polecat>" -m "..."
bd close <mr-bead> --reason "Merged to main"
```


Merge: rictus-mjtlq9xg

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


Parallel refinery: reduce merge queue bottleneck

Single refinery processes MRs sequentially, causing backlog.

## Problem
- 12 swarms × 5 polecats = 60 MRs
- Refinery: 1 merge at a time
- Branches go stale waiting
- Conflicts compound

## Options

### Option A: Multiple refinery workers
- Spawn N refinery instances
- Each claims MRs from queue
- Risk: merge conflicts between concurrent merges

### Option B: Integration branches
- Polecats merge to integration/swarm-xxx first
- Refinery merges integration branch to main
- Reduces main contention

### Option C: Batched merges
- Refinery collects N MRs
- Attempts octopus merge
- Falls back to sequential on conflict

### Recommendation
Start with Option A (2-3 workers) with locking on main.

Implemented Option A (multiple refinery workers with claiming). Added ClaimedBy/ClaimedAt to MR struct, claim/release/unclaimed CLI commands, and updated patrol formula to use claiming for parallel processing coordination.


Digest: mol-deacon-patrol

Patrol 5: 3 rigs healthy


Digest: mol-deacon-patrol

Patrol cycle 10: All 6 agents healthy


Digest: mol-deacon-patrol

Patrol cycle 68: All healthy


Merge: imperator-1767106079026

branch: polecat/imperator-1767106079026
target: main
source_issue: imperator-1767106079026
rig: gastown


Digest: mol-deacon-patrol

Patrol 9: all healthy


Merge: cal-mjufugtb

branch: polecat/cal-mjufugtb
target: main
source_issue: cal-mjufugtb
rig: gastown


Patrol agent state.json not updated on activity

Witness and Refinery state.json files show last_active from Dec 19 even though sessions have been running. The state should update each patrol cycle.

Evidence:
```
$ cat beads/witness/state.json
{"role": "witness", "last_active": "2025-12-19T17:50:00Z"}

$ cat beads/refinery/state.json
{"role": "refinery", "last_active": "2025-12-19T17:50:00Z"}
```

Expected: last_active should update each time the agent runs a patrol cycle.

Impact: Can't tell if patrol agents are actually active vs just having an open tmux session.


Digest: mol-deacon-patrol

Patrol cycle 8: All agents healthy


Merge: nux-1767083432904

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


Digest: mol-deacon-patrol

Patrol cycle 2: All agents healthy, 6 health pings sent


Ephemeral rig support for ad-hoc batch work

Support for temporary worker rigs for ad-hoc batch work.

## Use Case

Ad-hoc batch work where you want temporary workers:
- gt spawn --epic <epic-id> --ephemeral --workers 3
- Creates temp rig with 3 clones
- Workers process epic children
- Work merges through queue
- Clones cleaned up when done

## Interface

```go
type EphemeralRig struct {
    ID               string
    GitURL           string
    BaseCommit       string
    Workers          []string
    IntegrationBranch string
    EpicID           string  // associated epic (for cleanup trigger)
    CreatedAt        time.Time
}

func InitEphemeralRig(gitURL string, numWorkers int) (*EphemeralRig, error)
func (r *EphemeralRig) AddWorker(name string) error
func (r *EphemeralRig) Destroy(force bool) error
```

## Directory Structure

```
<rig>/ephemeral/
└── rig-a3f7/
    ├── config.json
    ├── Alice/     # clone
    ├── Bob/       # clone
    └── Carol/     # clone
```

## Cleanup Trigger

When all issues in the associated epic are closed AND merged, the ephemeral rig can be destroyed.

## Note

No swarm ID needed - the epic ID provides the grouping. Ephemeral rig is just a convenience for temporary clones.

## Reference

PGT: ephemeral.py (for structure, ignore swarm ID coupling)


Plugin: work-oracle (pre-dispatch analysis)

Plugin for pre-dispatch task analysis and decomposition.

## Purpose

Before dispatching workers for an epic, ask work-oracle to:
- Validate task breakdown
- Identify parallelization opportunities
- Predict conflicts between tasks
- Suggest worker count

## Hook Point

Mayor consults work-oracle before spawning workers.

## Interface

Input (via mail):
- Epic ID with proposed child issues
- Rig context (current state of codebase)

Output (via mail + bead):
- Recommended task groupings
- Dependency suggestions
- Risk assessment (which files might conflict)
- Optimal worker count

## Structure

```
<rig>/plugins/work-oracle/
├── CLAUDE.md       # Analysis prompts
├── mail/inbox.jsonl
└── state.json
```

Uses existing plugin-as-agent architecture.

## Note

Was "swarm-oracle" - renamed because there are no swarm IDs. This plugin helps plan batch work, not manage swarm entities.


Digest: mol-deacon-patrol

Patrol 18: healthy


Digest: mol-deacon-patrol

Cycle 14


Digest: mol-deacon-patrol

Patrol 214: All nominal


Digest: mol-deacon-patrol

Patrol cycle 17: All healthy


Digest: mol-deacon-patrol

deacon patrol: 21 cycles complete


Deacon Patrol

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


Merge: rictus-mjxlzc5r

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


Merge: ace-mjwjb633

branch: polecat/ace-mjwjb633
target: main
source_issue: ace-mjwjb633
rig: gastown
agent_bead: gt-gastown-polecat-ace


Digest: mol-deacon-patrol

Patrol 10: healthy


Merge: dag-1767079859283

branch: polecat/dag-1767079859283
target: main
source_issue: dag-1767079859283
rig: gastown


Digest: mol-deacon-patrol

Patrol 16: healthy


Digest: mol-deacon-patrol

Patrol 3: All healthy, 2 convoys in progress


Digest: mol-deacon-patrol

Patrol cycle 7: All agents healthy


Digest: mol-deacon-patrol

Patrol 23: Quick cycle, no changes. All agents healthy.


Digest: mol-deacon-patrol

Patrol complete: all healthy, no issues


Merge: slit-1767084013378

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


Merge: gt-nq3pr

branch: polecat/testcat6-mjtkcfjm
target: main
source_issue: gt-nq3pr
rig: gastown


Handoff mail not delivered to mayor inbox

Town log shows predecessor handed off at 12:59:33 with message about gt-7psb8, but gt mail inbox shows 0 messages. The handoff context was lost.

Reproduction:
1. Mayor runs gt handoff with -s 'context'
2. New mayor session starts
3. gt mail inbox shows empty

Expected: Handoff mail in inbox

(Moved from hq-zs2t8)

Fixed: trailing slash added to town-level agent IDs in sling.go (dementus MR merged)


Digest: mol-deacon-patrol

Patrol 18: Quiet


Update gastown to use 'ephemeral' instead of 'wisp' terminology

After beads renames 'wisp' to 'ephemeral' (bd-o18s), update gastown code:

- patrol_helpers.go: bd wisp create → bd ephemeral create (or new API)
- doctor/wisp_check.go: rename to ephemeral_check.go
- All references to Wisp field → Ephemeral

Depends on: bd-o18s


Digest: mol-refinery-patrol

Patrol: No MRs in queue. Found 1 pending branch (gt-jq8i4) without MR bead. 8 stale branches detected (work already on main).


Digest: mol-deacon-patrol

Patrol 123: All agents healthy


Merge: toast-mjxb88ev

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


Patrol Exponential Backoff System

Cost-saving await-signal model for patrol agents.

## The Problem

Patrol agents (witness, refinery) poll continuously even when idle, burning API credits.

## The Solution: Await-Signal

Agents don't poll constantly. They **wait for a signal**, then **discover reality**.

```
PATROL LOOP:
    await-signal (just wake me)
         ↓ awake
    check-reality (mail, beads, hook, git)
         ↓
    work found? → DO WORK → loop
         ↓ no
    increase backoff → loop
```

**Key principle (ZFC-aligned):** Signal carries no semantic meaning - just 'wake up'.
Agent discovers what to do by examining reality.

## Two-Level Wake

| Level | State | Command |
|-------|-------|---------|
| 1 | Running (backoff) | `gt nudge` clears backoff |
| 2 | Asleep | `gt rig boot` starts session |

**Boot+nudge pattern:**
```bash
gt rig boot <rig>              # Wake if asleep (idempotent)
gt nudge <rig>/witness 'wake'  # Clear backoff if running
```

## Backoff Curve

Base: 30s → 60s → 120s → 240s → ... → 10min cap

Resets on: nudge received, work found, deacon ping.

## Reference

See ~/gt/docs/patrol-system-design.md (Await-Signal Model section)


Daemon activity detection and rig nudging

Daemon monitors activity feed and nudges patrol agents when commands detected.

## Implementation

1. Daemon watches activity feed (or logs) for gt/bd command execution
2. Track per-rig last-activity timestamps
3. On activity in rig: nudge witness + refinery for that rig
4. Nudge clears their backoff → immediate poll

## Activity Sources

- gt commands (sling, mail, polecat, etc.)
- bd commands (create, update, close, sync, etc.)
- Maybe: file writes in rig directories

## Graceful Behavior

- If agent session not running: no-op (not an error)
- Activity detection is best-effort
- Backoff still works without this (just slower wake)

Obsoleted by feed-based wake model (gt-vdprb). Agents subscribe directly to feed; daemon does not mediate activity detection.


Deacon health pings clear agent backoff

Deacon's periodic health checks also clear patrol agent backoff.

## Current Flow (mol-deacon-patrol)

Deacon already pings witnesses/refineries for health checks. These pings should:
1. Verify agent is alive
2. Clear their backoff as side effect

## Implementation

In mol-deacon-patrol health-scan step:
- gt nudge <rig>/witness 'HEALTH_CHECK from deacon'
- gt nudge <rig>/refinery 'HEALTH_CHECK from deacon'

Receiving agent:
- Responds to prove liveness
- Resets backoff to base interval

## Ping Interval

Deacon patrols every ~1-2 minutes. This ensures:
- Maximum backoff is bounded by deacon ping interval
- Even if daemon misses activity, deacon catches up

Added health ping nudges to mol-deacon-patrol health-scan step. These nudges clear agent backoff as a side effect, ensuring patrol agents remain responsive even during quiet periods.


Molecule await-signal step type

Add await-signal as a molecule step type for patrol agents.

## Step Definition

```toml
[[steps]]
id = "await-signal"
type = "wait"
backoff = { base = "30s", multiplier = 2, max = "10m" }
description = "Wait for signal, then check reality"
```

## Behavior

1. Sleep for current backoff interval
2. Wake immediately on nudge (or timeout expires)
3. Proceed to next step (check-reality)
4. If no work found, loop back with increased backoff
5. If work found, reset backoff to base

## Implementation Options

A. Formula-level: Define in TOML, agent interprets
B. Code-level: Agent implements wait loop with backoff

Option A is cleaner but needs formula parser support.
Option B works now but less declarative.

## Used By

- mol-witness-patrol (first step)
- mol-refinery-patrol (first step)

Implemented Type and Backoff fields in MoleculeStep with parsing support for await-signal step type


Deacon stuck-session detection and force-kill protocol

Deacon detects and kills genuinely stuck/hung Claude Code sessions.

## The Problem

Claude Code sessions can get stuck:
- Infinite loop / hung tool call
- Crashed but tmux session still exists
- Unresponsive to nudges

`gt rig boot` is idempotent (won't kill) - it only starts if not running.
Someone needs to detect stuck sessions and force-kill them.

## Detection Protocol

During Deacon health rounds:

1. **Ping test**: `gt nudge <agent> 'HEALTH_CHECK'`
2. **Wait for response**: Agent should update agent bead `last_activity`
3. **Timeout**: If no activity update within N seconds, mark suspicious
4. **Consecutive failures**: After M consecutive failures, declare stuck

## Force-Kill Protocol

When stuck detected:

```bash
# 1. Log the intervention
gt mail send <agent> -s 'FORCE_KILL: unresponsive' -m 'Deacon detected...'

# 2. Kill the tmux session
tmux kill-session -t <session-name>

# 3. Update agent bead state
bd update <agent-bead> --status=killed --reason='Deacon force-kill: unresponsive'

# 4. Notify mayor (optional, for visibility)
gt mail send mayor/ -s 'Agent killed: <agent>' -m 'Reason: unresponsive...'
```

## Recovery

After force-kill, the agent is 'asleep'. Normal wake mechanisms apply:
- `gt rig boot` restarts it
- Or stays asleep until next activity trigger

## Parameters (configurable)

- ping_timeout: 30s (how long to wait for response)
- consecutive_failures: 3 (how many before force-kill)
- cooldown: 5m (minimum time between force-kills of same agent)

## NOT Deacon's Job

- Graceful shutdown (agent does this itself)
- Context-based recycling (agent self-handoffs)
- Normal backoff/sleep transitions

Deacon only force-kills when agent is genuinely unresponsive.

Implemented stuck-session detection and force-kill protocol with new commands: health-check, force-kill, health-state


Digest: mol-deacon-patrol

Patrol 1: inbox clear, gates clear, no pending spawns, witnesses/refineries healthy, no orphans


gt crew at fails to detect existing crew session

## Summary
`gt crew at` started a new Claude session instead of attaching to an existing one for the same crew worker.

## Reproduction
1. Have a crew worker (joe) running in gastown/crew/joe (PID 27526 on tty s030)
2. Run `gt crew at` from the same directory (gastown/crew/joe)
3. Expected: Attach to existing session on s030
4. Actual: Started a brand new Claude session (PID 67618 on s026)

## Evidence
```
# Old joe still running:
PID 27526 on s030: /Users/stevey/gt/gastown/crew/joe (started 10:22AM)

# New joe spawned by 'gt crew at':
PID 67618 on s026: /Users/stevey/gt/gastown/crew/joe (started 10:39AM)
```

## Impact
- Duplicate crew workers cause confusion
- User expected to attach to existing session, not spawn a second one
- The original session was still functional (just stuck in feed display)

## Likely cause
`gt crew at` probably doesn't check for running Claude processes in the crew directory before spawning a new one. It should:
1. Check for existing tmux sessions for this crew worker
2. Check for running `claude` processes with cwd matching the crew directory
3. If found, attach to existing session instead of spawning new one

Fixed by adding FindSessionByWorkDir() to detect existing Claude sessions in the crew directory before creating a new one


Beads epic templates for batch work patterns

Optional: Define templates for common batch work patterns.

## Concept

A template encodes a workflow pattern that can be instantiated as beads:

```yaml
# templates/batch-basic.yaml
name: basic-batch
description: Simple batch work pattern
phases:
  - name: startup
    issues:
      - title: "Verify workers ready"
  - name: working
    # Actual work issues added separately
  - name: cleanup
    issues:
      - title: "Merge all branches"
      - title: "Clean up workers"
      - title: "Report to Mayor"
```

## Usage

```bash
gt spawn --template basic-batch --epic gt-u1j --workers 3
```

Creates beads epic with template phases + actual work from gt-u1j children.

## Decision Point

Templates are OPTIONAL. The core design (beads as state, multi-wave orchestration) works without templates. Templates are sugar for common patterns.

Consider deferring to P3 or dropping entirely if beads epics with dependencies suffice.

## Note

No "swarm IDs" involved - templates just pre-populate epic/issue structure.


Exclude deacon from tmux rig count in status displays

Deacon is a town-level patrol agent, not a project rig. It shows up in tmux session counts alongside actual rigs (gastown, beads, wyvern), which is confusing.

Fix: Status/tmux reporting should exclude deacon from rig counts. Deacon is infrastructure, not a workspace.

Affected: Any status displays that count tmux sessions as rigs.


Digest: mol-deacon-patrol

Patrol 84: All healthy, quiet


Test MR

branch: test-branch
target: main
source_issue: gt-test
rig: gastown


Digest: mol-deacon-patrol

Patrol 7: healthy


MQ events in gt feed

Wire MQ lifecycle events to gt feed display.

After 'Refinery emits activity events' is done:
- gt feed should show merge_started, merged, merge_failed events
- Format: timestamp, event type, MR details
- Color coding: green for merged, red for failed

Example output:
  19:45 MERGED gt-abc123 (polecat/nux → main)
  19:42 MERGE_STARTED gt-abc123
  19:40 MERGE_FAILED gt-xyz789 (conflict)

Implemented MQ lifecycle events in gt feed using standalone mqevents package


Digest: mol-deacon-patrol

Patrol 146 complete: All healthy


Digest: mol-deacon-patrol

Patrol 18: quiet


Merge: furiosa-mjw349y2

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


Digest: mol-deacon-patrol

P11: stable


Digest: mol-deacon-patrol

Patrol cycle 29: All healthy, no incidents


Merge: gt-3x1

branch: polecat/Slit
target: main
source_issue: gt-3x1
rig: gastown


Digest: mol-deacon-patrol

Patrol 204: Fast pass, all nominal


Merge: slit-1767079899677

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


Create internal/tui/ package with feed model

Create the TUI infrastructure for gt feed.

## Package structure
```
internal/tui/
  feed/
    model.go       # bubbletea Model struct
    view.go        # View() rendering
    update.go      # Update() message handling
    events.go      # Event stream subscription (tail .feed.jsonl)
    styles.go      # lipgloss styles
    keys.go        # Key bindings
```

## Model components
1. **AgentTree** - Collapsible tree of agents by role
2. **EventStream** - Scrollable viewport of recent events
3. **StatusBar** - Current filter, help hints
4. **FilterPopup** - Modal for setting filters

## Key bindings
- j/k - scroll events
- J/K - scroll agent tree
- tab - switch focus (tree/stream)
- enter - expand/details
- / - search
- f - filter popup
- q - quit
- ? - help

## Event subscription
- Tail ~/gt/.feed.jsonl using fsnotify or polling
- Parse JSONL events
- Send as bubbletea messages to update model


Digest: mol-deacon-patrol

Patrol cycle 11: All 3 rigs healthy. No incidents.


Delete .runtime/*.json observable state

Remove JSON files that tracked observable state (now in beads/activity stream).

Files to delete or minimize:
- .runtime/refinery.json - remove stats (keep minimal process state if needed)
- .runtime/witness.json - remove stats
- .runtime/swarms.json - delete entirely (gt-kc7yj moves to beads)

Prerequisite: All events flowing through activity stream, swarms in beads.

This is the cleanup step after observability is working.

Removed Stats fields from witness and refinery types. Observable metrics now flow through activity stream.


Digest: mol-deacon-patrol

Patrol 5


Digest: mol-deacon-patrol

Cycle 192: Nominal


Digest: mol-deacon-patrol

Patrol 205: All nominal


Digest: mol-deacon-patrol

Patrol 10: all healthy, sessions up


gt rig stop <rig>... - stop rig workers with shutdown semantics

Stop one or more rigs with same flags and semantics as gt shutdown (for polecats). Should support multiple rigs: gt rig stop gastown beads

Implemented gt rig stop command with multi-rig support and shutdown semantics


Digest: mol-deacon-patrol

Patrol #16: Quick cycle, all quiet.


Digest: mol-deacon-patrol

Patrol 110: All healthy


Liftoff implementation plan in Beads

## Context

Session on 2025-12-27 produced three key docs:
- `~/gt/docs/agent-as-bead.md` - Agents ARE beads (identity, hook slots, CV chain roots)
- `~/gt/docs/zfc-violations-audit.md` - Where Go infers instead of trusting agents
- `~/gt/docs/liftoff-plan.md` - 4.5 day plan to self-sustaining Gas Town

## Work Required

### Phase 1: Audit existing beads ✅
- Review all open beads in gt- prefix
- Close obsolete/stale issues
- Update any that need refinement
- Note which existing beads align with liftoff plan

### Phase 2: File new beads ✅
Translate liftoff-plan.md into beads with proper dependencies.

Three pillars:
1. **Pillar 1: Agent Identity** (gt-d0jqp) - schema, slot commands, migration
2. **Pillar 2: Patrol Ignition** (gt-hwka3) - witness/refinery formula wiring
3. **Pillar 3: Polecat Lifecycle** (gt-4a2qt) - recycle/nuke commands, session-per-step

### Phase 3: Review ✅
Human reviews the plan.

## Deliverable

A complete dependency graph in beads that can be:
1. Queried with `bd ready` to find available work
2. Slung to polecats in dependency order
3. Tracked to completion

## References

- ~/gt/docs/liftoff-plan.md - 4.5 day plan
- ~/gt/docs/agent-as-bead.md - Agent identity design
- ~/gt/docs/zfc-violations-audit.md - ZFC violations addressed


Day 1.6: Update gt mol status to use hook slot

Migrate gt mol status from:
- Query(status=pinned AND assignee=me)
To:
- Read agent bead → check hook_bead field

This eliminates hook ambiguity.

Parent: gt-d0jqp


Merge: nux-mjxn8p5t

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


Digest: mol-deacon-patrol

Patrol complete: town quiet, all healthy


Merge: nux-mjxeh79t

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


Digest: mol-deacon-patrol

Patrol 5: 3 polecats working


Digest: mol-deacon-patrol

Patrol cycle 64: All healthy


Digest: mol-deacon-patrol

Patrol 10: quiet


gt commands should follow .beads/redirect

## Problem

`gt sling` (and likely other gt commands) don't follow the `.beads/redirect` file that `bd` uses to share beads across clones.

This caused confusion during the v0.39.0 release: molecules were poured successfully to mayor/rig's beads (via redirect), but `gt sling` couldn't find them because it was looking in the crew clone's local .beads/.

## Expected Behavior

All `gt` commands that interact with beads should follow the redirect mechanism that `bd` uses.

## Affected Commands (likely)

- `gt sling`
- `gt hook`
- `gt mol status`
- `gt mol attach`
- Any command that shells out to `bd show` or similar

## Solution

When `gt` needs to find the beads directory, check for `.beads/redirect` and follow it, same as `bd` does.


Integration test: simple file creation

Test task for polecat integration test (gt-7psb8).

Simple task: Create a file ~/gt/gastown/test-polecat-integration.txt with content 'Polecat integration test successful'.

This is an intentionally trivial task to verify the polecat → witness → refinery → merged flow works end-to-end.


Digest: mol-deacon-patrol

Patrol #5: Health pinged all witnesses.


Digest: mol-deacon-patrol

Patrol 160: All healthy - handoff after 20 cycles


Digest: mol-deacon-patrol

Patrol 8


Digest: mol-deacon-patrol

Patrol 2: All agents healthy, no issues.


Digest: mol-deacon-patrol

Patrol 159 complete


Witness: Reduce chattiness, increase autonomy

Witness is spamming Mayor with routine status:
- 'Polecat X processed' - routine, no action needed
- 'Idle polecats: X needs work' - wrong direction

Witness should be a local sheriff:
1. Handle routine lifecycle autonomously (don't report)
2. Only escalate genuine problems requiring human/mayor intervention
3. Use convoy system for batch 'work complete' notifications
4. Never ask Mayor to assign work - either do it yourself or let polecats idle

Remove these mail types:
- POLECAT_PROCESSED (routine)
- IDLE_POLECAT (wrong escalation direction)

Keep these:
- ESCALATION (genuine problem)
- BLOCKED (needs human decision)
- CRASH_RECOVERY (informational, useful)

Implemented: Removed routine POLECAT_PROCESSED and WITNESS_REPORT/REFINERY_REPORT mail types. Witness now handles lifecycle autonomously, only escalating genuine problems.


Digest: mol-deacon-patrol

Patrol cycle 10: All healthy


Test refile command

Testing bd refile

(Refiled from bd-v4hq)


gt done --exit: Self-terminate polecat session after MR submission

## Problem

Polecats finish work, call `gt done`, and then sit idle at Claude prompt waiting for Witness to kill them. This wastes money (idle Claude sessions still cost).

## Solution

Add `--exit` flag to `gt done` that:
1. Submits MR to merge queue (existing behavior)
2. Sends POLECAT_DONE to Witness (existing behavior)
3. Exits the Claude session immediately (new)

```bash
gt done --exit  # Submit MR and exit session
```

## Implementation

In `internal/cmd/done.go`:
1. Add `--exit` flag
2. After successful MR submission and witness notification:
   - Print final status
   - Call `os.Exit(0)` OR run `/exit` command

## Notes

- Witness still receives POLECAT_DONE and handles cleanup (nuke worktree) async
- No waiting = no idle sessions = no wasted money
- Session exit is safe because all work is pushed and MR submitted before exit

Implemented --exit flag for session self-termination


Digest: mol-deacon-patrol

Patrol 14 complete


Digest: mol-deacon-patrol

Patrol 19: routine


Digest: mol-deacon-patrol

Patrol cycle 16: All 3 rigs healthy. No incidents.


Digest: mol-deacon-patrol

Cycle 182: All agents healthy, no incidents


Merge: dementus-mjtlqmya

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


Digest: mol-deacon-patrol

Patrol 78: Routine


Digest: mol-deacon-patrol

Patrol 135: All healthy


Merge: furiosa-1767073359963

attached_args: Code review this merge request

branch: polecat/furiosa-1767073359963
target: main
source_issue: furiosa-1767073359963
rig: gastown

REVIEW REJECTED by rictus: Commits claim await-signal but no such code exists. Feature removals conflict with rictus branch quality-level work. Needs clarification and reconciliation.


Agent Communication Protocol

Structured mail between agents for coordination.

## Problem
Agents communicate via freeform mail. This works but lacks parseable structure for automated handling.

## Protocols

### Witness to Refinery
- POLECAT_READY: worker X completed, branch ready for merge
- REWORK_COMPLETE: worker Y finished requested rework

### Refinery to Witness
- MERGE_SUCCESS: worker X merged, can be cleaned up
- MERGE_FAILED: worker X needs rework (reason attached)
- REWORK_REQUEST: please have worker X rebase on current main

### Polecat to Witness
- WORK_COMPLETE: done with assigned issue
- NEED_HELP: stuck, requesting intervention

### Any to Deacon
- ESCALATION: problem requiring Mayor attention

## Mail Format
Subject: [PROTOCOL_TYPE] brief description
Body: Structured YAML or JSON payload

## Success Criteria
- Patrol steps parse protocol messages automatically
- Handlers exist for each protocol type
- Integration test: polecat completes -> witness notifies -> refinery merges -> witness cleans up

Consolidates gt-0qki.


Protocol message specification

Define YAML format for protocol messages. Subject: [PROTOCOL_TYPE] brief. Body: structured payload. Document all protocol types: POLECAT_READY, MERGE_SUCCESS, MERGE_FAILED, REWORK_REQUEST, WORK_COMPLETE, NEED_HELP, ESCALATION.

Documented YAML format for all protocol messages in docs/mail-protocol.md. Subject format: [PROTOCOL_TYPE] brief. Body: YAML with protocol, timestamp, agent fields. All 8 protocol types fully documented with schemas and examples.


Witness-Refinery protocol handlers

Implement handlers for: POLECAT_READY (witness→refinery: worker done, branch ready), MERGE_SUCCESS (refinery→witness: merged, cleanup ok), MERGE_FAILED (refinery→witness: needs rework), REWORK_REQUEST (refinery→witness: rebase needed).

Implemented Witness-Refinery protocol handlers in internal/protocol/ package. Includes message types (MERGE_READY, MERGED, MERGE_FAILED, REWORK_REQUEST), message builders, payload parsers, handler interfaces and default implementations for both Witness and Refinery. Full test coverage added.


Polecat-Witness protocol handlers

Implement handlers for: WORK_COMPLETE (polecat→witness: done with issue), NEED_HELP (polecat→witness: stuck, requesting intervention). Witness patrol steps should parse and act on these.

Implemented protocol handlers in internal/witness/protocol.go and handlers.go with tests


Agent protocol integration test

End-to-end test: polecat completes work → sends WORK_COMPLETE → witness receives and sends POLECAT_READY → refinery merges → sends MERGE_SUCCESS → witness cleans up polecat. All via structured protocol messages.


Polecats go off-task instead of working pinned bead

During swarm execution, polecats frequently stop working on their assigned task (pinned bead) and start doing other things like:
- Asking about other polecats
- Checking mail
- Monitoring swarm status
- Working on unrelated issues

Expected: Polecat receives task via gt sling, works on it until completion, signals done.
Actual: Polecat gets distracted and stops working on assigned task.

Root cause hypothesis: CLAUDE.md instructions don't strongly enforce 'work your hook' behavior. Need clearer polecat template that emphasizes single-task focus.


Digest: mol-deacon-patrol

Patrol cycle 21: All 3 witnesses and refineries healthy, no orphans, no gates, inbox clean


Code review: gt sling --naked fix

Review the fix for gt sling --naked to bypass pane lookup for terminated polecats in internal/cmd/sling.go

Code review complete. Fix is correct: resolveTargetAgent now accepts skipPane parameter to bypass tmux pane lookup when --naked flag is set. Allows slinging to terminated polecats.


Sling reports 'already pinned' but mol status shows empty hook

During swarm operations, gt sling reported beads were 'already pinned' but gt mol status showed nothing on the hook.

**Observed:**
```
$ gt sling bd-9btu beads/Nux
Error: bead bd-9btu is already pinned to gt-beads-nux

$ gt mol status beads/Nux
Nothing on hook - no work slung
```

**Expected:**
If a bead is pinned, mol status should show it. If mol status shows empty, sling should work.

**Workaround:**
Used --force flag to re-sling, which worked.

**Root cause hypothesis:**
Agent bead state may be stored in town beads but polecat's local view doesn't see it, or the pin record exists but session state is stale.


Digest: mol-deacon-patrol

Patrol 12: All healthy.


gt-mayor

gt-mayor

role_type: mayor
rig: null
agent_state: stopped
hook_bead: null
role_bead: gt-mayor-role
cleanup_status: has_stash
active_mr: gt-z4lxc
notification_level: null


Mayor Role Definition

You are the Mayor - global coordinator of Gas Town. You sit above all rigs,
coordinating work across the entire workspace.

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

default_molecule: mol-mayor-patrol
capabilities:
  - dispatch_work
  - cross_rig_coordination
  - escalation_handling

## Responsibilities

- Work dispatch: Spawn workers for issues, coordinate batch work on epics
- Cross-rig coordination: Route work between rigs when needed
- Escalation handling: Resolve issues Witnesses cannot handle
- Strategic decisions: Architecture, priorities, integration planning

NOT your job: Per-worker cleanup, session killing, nudging workers (Witness handles that)

## Propulsion Principle

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

Your pinned molecule persists across sessions. Hook has work then Run it.
Hook empty then Check mail. Nothing anywhere then Wait for user.

## Key Commands

### Communication
- gt mail inbox - Check your messages
- gt mail read <id> - Read a specific message
- gt mail send <addr> -s "Subject" -m "Message" - Send mail

### Status
- gt status - Overall town status
- gt rigs - List all rigs
- gt polecats <rig> - List polecats in a rig

### Work Management
- bd ready - Issues ready to work (no blockers)
- gt sling <bead> <rig> - Assign work to polecat in rig

## Session End Protocol

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


Digest: mol-deacon-patrol

Patrol 5: quick pass


Digest: mol-deacon-patrol

Patrol 1: all healthy, 17 sessions, 3 rigs online


Merge: dag-mjw70jg8

branch: polecat/dag-mjw70jg8
target: main
source_issue: dag-mjw70jg8
rig: gastown
agent_bead: gt-gastown-polecat-dag


Digest: mol-deacon-patrol

Patrol 16: Quiet


Digest: mol-deacon-patrol

Patrol cycle 18


Digest: mol-deacon-patrol

Patrol 14: quick pass


Digest: mol-deacon-patrol

Patrol 91: All healthy


Digest: mol-deacon-patrol

Patrol 11: All healthy


Refinery gates: test/lint/build before merge

Before merging polecat work to main, run configurable quality gates.

**From VC**: internal/gates/ - parallel execution with timeout, any failure = overall failure.

**Gas Town implementation**: Refinery config with gate commands:
```yaml
gates:
  test:
    cmd: go test ./...
    timeout: 5m
  lint:
    cmd: golangci-lint run
    timeout: 2m
  build:
    cmd: go build ./...
    timeout: 3m
parallel: true
```

If gates fail, don't merge. Polecat can iterate and retry.

**Value**: Prevents broken code from reaching main. VC had 90.9% gate pass rate.

**VC complexity**: ~200 lines Go
**Gas Town complexity**: ~10 lines YAML


Digest: mol-deacon-patrol

Patrol complete


Digest: mol-deacon-patrol

Patrol complete: all agents healthy, no orphans, 0 inbox messages


Dynamically discover rigs in checkStaleAgents

In internal/daemon/lifecycle.go:734-735, the rig list is hardcoded:

```go
// Add rig-specific agents (witness, refinery) for known rigs
// For now, we check gastown - could be expanded to discover rigs dynamically
rigs := []string{"gastown", "beads"}
```

This should use gt rigs or similar to dynamically discover configured rigs instead of hardcoding.

Affects: checkStaleAgents() which checks for dead agents that stopped updating their bead state.

Implemented: dynamic rig discovery using config.LoadRigsConfig


Digest: mol-deacon-patrol

Patrol complete: 20 cycles, handing off


Digest: mol-deacon-patrol

Patrol #3: All healthy, 1 dog idle. No messages.


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Second-Order Monitoring

Witnesses send WITNESS_PING messages to verify the Deacon is alive. This
prevents the "who watches the watchers" problem - if the Deacon dies,
Witnesses detect it and escalate to the Mayor.

The Deacon's agent bead last_activity timestamp is updated during each patrol
cycle. Witnesses check this timestamp to verify health.

Deacon patrol cycle complete: all 15 steps executed. Key findings: Witness/Refinery healthy, no convoys or gates pending, cleanup flagged for manual fix (7 missing agent beads, 4 stale locks)


mol-polecat-work

Full polecat lifecycle from assignment to decommission.

This proto enables nondeterministic idempotence for polecat work. A polecat that crashes after any step can restart, read its molecule state, and continue from the last completed step. No work is lost.

## Variables

| Variable | Required | Description |
|----------|----------|-------------|
| issue | Yes | The source issue ID being worked on |


Check convoy completion

Check convoy completion status.

Convoys are coordination beads that track multiple issues across rigs. When all tracked issues close, the convoy auto-closes.

**Step 1: Find open convoys**
```bash
bd list --type=convoy --status=open
```

**Step 2: For each open convoy, check tracked issues**
```bash
bd show <convoy-id>
# Look for 'tracks' or 'dependencies' field listing tracked issues
```

**Step 3: If all tracked issues are closed, close the convoy**
```bash
# Check each tracked issue
for issue in tracked_issues:
    bd show <issue-id>
    # If status is open/in_progress, convoy stays open
    # If all are closed (completed, wontfix, etc.), convoy is complete

# Close convoy when all tracked issues are done
bd close <convoy-id> --reason "All tracked issues completed"
```

**Note**: Convoys support cross-prefix tracking (e.g., hq-* convoy can track gt-*, bd-* issues). Use full IDs when checking.


Maintain dog pool

Ensure dog pool has available workers for dispatch.

**Step 1: Check dog pool status**
```bash
gt dog status
# Shows idle/working counts
```

**Step 2: Ensure minimum idle dogs**
If idle count is 0 and working count is at capacity, consider spawning:
```bash
# If no idle dogs available
gt dog add <name>
# Names: alpha, bravo, charlie, delta, etc.
```

**Step 3: Retire stale dogs (optional)**
Dogs that have been idle for >24 hours can be removed to save resources:
```bash
gt dog status <name>
# Check last_active timestamp
# If idle > 24h: gt dog remove <name>
```

**Pool sizing guidelines:**
- Minimum: 1 idle dog always available
- Maximum: 4 dogs total (balance resources vs throughput)
- Spawn on demand when pool is empty

**Exit criteria:** Pool has at least 1 idle dog.

Dog pool feature not yet implemented (gt dog command unavailable)


Burn and respawn or loop

Burn and let daemon respawn, or exit if context high.

Decision point at end of patrol cycle:

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

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

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

This enables infinite patrol duration via context-aware respawning.

Patrol cycle complete - all 15 steps executed


Check Witness and Refinery health

Check Witness and Refinery health for each rig.

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

For each rig, run:
```bash
gt witness status <rig>
gt refinery status <rig>
```

**Signals to assess:**

| Component | Healthy Signals | Concerning Signals |
|-----------|-----------------|-------------------|
| Witness | State: running, recent activity | State: not running, no heartbeat |
| Refinery | State: running, queue processing | Queue stuck, merge failures |

**Tracking unresponsive cycles:**

Maintain in your patrol state (persisted across cycles):
```
health_state:
  <rig>:
    witness:
      unresponsive_cycles: 0
      last_seen_healthy: <timestamp>
    refinery:
      unresponsive_cycles: 0
      last_seen_healthy: <timestamp>
```

**Decision matrix** (you decide the thresholds based on context):

| Cycles Unresponsive | Suggested Action |
|---------------------|------------------|
| 1-2 | Note it, check again next cycle |
| 3-4 | Attempt restart: gt witness restart <rig> |
| 5+ | Escalate to Mayor with context |

**Restart commands:**
```bash
gt witness restart <rig>
gt refinery restart <rig>
```

**Escalation:**
```bash
gt mail send mayor/ -s "Health: <rig> <component> unresponsive" \
  -m "Component has been unresponsive for N cycles. Restart attempts failed.
      Last healthy: <timestamp>
      Error signals: <details>"
```

Reset unresponsive_cycles to 0 when component responds normally.

Witness and Refinery healthy: both running, no issues detected


Nudge newly spawned polecats

Nudge newly spawned polecats that are ready for input.

When polecats are spawned, their Claude session takes 10-20 seconds to initialize. The spawn command returns immediately without waiting. This step finds spawned polecats that are now ready and sends them a trigger to start working.

**ZFC-Compliant Observation** (AI observes AI):

```bash
# View pending spawns with captured terminal output
gt deacon pending
```

For each pending session, analyze the captured output:
- Look for Claude's prompt indicator "> " at the start of a line
- If prompt is visible, Claude is ready for input
- Make the judgment call yourself - you're the AI observer

For each ready polecat:
```bash
# 1. Trigger the polecat
gt nudge <session> "Begin."

# 2. Clear from pending list
gt deacon pending <session>
```

This triggers the UserPromptSubmit hook, which injects mail so the polecat sees its assignment.

**Bootstrap mode** (daemon-only, no AI available):
The daemon uses `gt deacon trigger-pending` with regex detection. This ZFC violation is acceptable during cold startup when no AI agent is running yet.


Execute registered plugins

Execute registered plugins.

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

See docs/deacon-plugins.md for full documentation.

Gate types:
- cooldown: Time since last run (e.g., 24h)
- cron: Schedule-based (e.g., "0 9 * * *")
- condition: Metric threshold (e.g., wisp count > 50)
- event: Trigger-based (e.g., startup, heartbeat)

For each plugin:
1. Read plugin.md frontmatter to check gate
2. Compare against state.json (last run, etc.)
3. If gate is open, execute the plugin

Plugins marked parallel: true can run concurrently using Task tool subagents. Sequential plugins run one at a time in directory order.

Skip this step if ~/gt/plugins/ does not exist or is empty.

No plugins registered (~/gt/plugins/ is empty)


Self-review

Review your own changes. Look for:
- Bugs and edge cases
- Style issues
- Missing error handling
- Security concerns

Fix any issues found before proceeding.


Handle callbacks from agents

Handle callbacks from agents.

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

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

**WITNESS_PING**:
Witnesses periodically ping to verify Deacon is alive. Simply acknowledge
and archive - the fact that you're processing mail proves you're running.
Your agent bead last_activity is updated automatically during patrol.
```bash
gt mail archive <message-id>
```

**HELP / Escalation**:
Assess and handle or forward to Mayor.
Archive after handling:
```bash
gt mail archive <message-id>
```

**LIFECYCLE messages**:
Polecats reporting completion, refineries reporting merge results.
Archive after processing:
```bash
gt mail archive <message-id>
```

**DOG_DONE messages**:
Dogs report completion after infrastructure tasks (orphan-scan, session-gc, etc.).
Subject format: `DOG_DONE <hostname>`
Body contains: task name, counts, status.
```bash
# Parse the report, log metrics if needed
gt mail read <id>
# Archive after noting completion
gt mail archive <message-id>
```
Dogs return to idle automatically. The report is informational - no action needed
unless the dog reports errors that require escalation.

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

**Hygiene principle**: Archive messages after they're fully processed.
Keep inbox near-empty - only unprocessed items should remain.


Rotate logs and prune state

Maintain daemon logs and state files.

**Step 1: Check daemon.log size**
```bash
# Get log file size
ls -la ~/.beads/daemon*.log 2>/dev/null || ls -la ~/gt/.beads/daemon*.log 2>/dev/null
```

If daemon.log exceeds 10MB:
```bash
# Rotate with date suffix and gzip
LOGFILE="$HOME/gt/.beads/daemon.log"
if [ -f "$LOGFILE" ] && [ $(stat -f%z "$LOGFILE" 2>/dev/null || stat -c%s "$LOGFILE") -gt 10485760 ]; then
    DATE=$(date +%Y-%m-%dT%H-%M-%S)
    mv "$LOGFILE" "${LOGFILE%.log}-${DATE}.log"
    gzip "${LOGFILE%.log}-${DATE}.log"
fi
```

**Step 2: Archive old daemon logs**

Clean up daemon logs older than 7 days:
```bash
find ~/gt/.beads/ -name "daemon-*.log.gz" -mtime +7 -delete
```

**Step 3: Prune state.json of dead sessions**

The state.json tracks active sessions. Prune entries for sessions that no longer exist:
```bash
# Check for stale session entries
gt daemon status --json 2>/dev/null
```

If state.json references sessions not in tmux:
- Remove the stale entries
- The daemon's internal cleanup should handle this, but verify

**Note**: Log rotation prevents disk bloat from long-running daemons.
State pruning keeps runtime state accurate.

Daemon log at 7MB (under 10MB threshold), no archives over 7 days old


Request shutdown

Send shutdown request to Witness.
Wait for termination.

The polecat is now ready to be cleaned up.
Do not exit directly - wait for Witness to kill the session.


End-of-cycle inbox hygiene

Verify inbox hygiene before ending patrol cycle.

**Step 1: Check inbox state**
```bash
gt mail inbox
```

Inbox should be EMPTY or contain only just-arrived unprocessed messages.

**Step 2: Archive any remaining processed messages**

All message types should have been archived during inbox-check processing:
- WITNESS_PING → archived after acknowledging
- HELP/Escalation → archived after handling
- LIFECYCLE → archived after processing

If any were missed:
```bash
# For each stale message found:
gt mail archive <message-id>
```

**Goal**: Inbox should have ≤2 active messages at end of cycle.
Deacon mail should flow through quickly - no accumulation.

Archived 2 stale messages, inbox now empty


Fire notifications

Fire notifications for convoy and cross-rig events.

After convoy completion or cross-rig dependency resolution, notify relevant parties.

**Convoy completion notifications:**
When a convoy closes (all tracked issues done), notify the Overseer:
```bash
# Convoy gt-convoy-xxx just completed
gt mail send mayor/ -s "Convoy complete: <convoy-title>" \
  -m "Convoy <id> has completed. All tracked issues closed.
      Duration: <start to end>
      Issues: <count>

      Summary: <brief description of what was accomplished>"
```

**Cross-rig resolution notifications:**
When a cross-rig dependency resolves, notify the affected rig:
```bash
# Issue bd-xxx closed, unblocking gt-yyy
gt mail send gastown/witness -s "Dependency resolved: <bd-xxx>" \
  -m "External dependency bd-xxx has closed.
      Unblocked: gt-yyy (<title>)
      This issue may now proceed."
```

**Notification targets:**
- Convoy complete → mayor/ (for strategic visibility)
- Cross-rig dep resolved → <rig>/witness (for operational awareness)

Keep notifications brief and actionable. The recipient can run bd show for details.

No convoy completions or cross-rig resolutions to notify


Check own context limit

Check own context limit.

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

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

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

This enables the Deacon to burn and respawn cleanly.

Context usage command not implemented (gt context --usage unavailable)


Resolve external dependencies

Resolve external dependencies across rigs.

When an issue in one rig closes, any dependencies in other rigs should be notified. This enables cross-rig coordination without tight coupling.

**Step 1: Check recent closures from feed**
```bash
gt feed --since 10m --plain | grep "✓"
# Look for recently closed issues
```

**Step 2: For each closed issue, check cross-rig dependents**
```bash
bd show <closed-issue>
# Look at 'blocks' field - these are issues that were waiting on this one
# If any blocked issue is in a different rig/prefix, it may now be unblocked
```

**Step 3: Update blocked status**
For blocked issues in other rigs, the closure should automatically unblock them (beads handles this). But verify:
```bash
bd blocked
# Should no longer show the previously-blocked issue if dependency is met
```

**Cross-rig scenarios:**
- bd-xxx closes → gt-yyy that depended on it is unblocked
- External issue closes → internal convoy step can proceed
- Rig A issue closes → Rig B issue waiting on it proceeds

No manual intervention needed if dependencies are properly tracked - this step just validates the propagation occurred.

No cross-rig closures to propagate; blocked issues are correctly tracked


Detect cleanup needs

**DETECT ONLY** - Check if cleanup is needed and dispatch to dog.

**Step 1: Preview cleanup needs**
```bash
gt doctor -v
# Check output for issues that need cleaning
```

**Step 2: If cleanup needed, dispatch to dog**
```bash
# Sling session-gc formula to an idle dog
gt sling mol-session-gc deacon/dogs --var mode=conservative
```

**Important:** Do NOT run `gt doctor --fix` inline. Dogs handle cleanup.
The Deacon stays lightweight - detection only.

**Step 3: If nothing to clean**
Skip dispatch - system is healthy.

**Cleanup types (for reference):**
- orphan-sessions: Dead tmux sessions
- orphan-processes: Orphaned Claude processes
- wisp-gc: Old wisps past retention

**Exit criteria:** Session GC dispatched to dog (if needed).

Cleanup needed (7 missing agent beads, 4 stale locks, 1 diverged clone) but dog dispatch not available - requires manual 'gt doctor --fix'


Evaluate pending async gates

Evaluate pending async gates.

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

**Timer gates** (await_type: timer):
Check if elapsed time since creation exceeds the timeout duration.

```bash
# List all open gates
bd gate list --json

# For each timer gate, check if elapsed:
# - CreatedAt + Timeout < Now → gate is ready to close
# - Close with: bd gate close <id> --reason "Timer elapsed"
```

**GitHub gates** (await_type: gh:run, gh:pr) - handled in separate step.

**Human/Mail gates** - require external input, skip here.

After closing a gate, the Waiters field contains mail addresses to notify.
Send a brief notification to each waiter that the gate has cleared.


Detect abandoned work

**DETECT ONLY** - Check for orphaned state and dispatch to dog if found.

**Step 1: Quick orphan scan**
```bash
# Check for in_progress issues with dead assignees
bd list --status=in_progress --json | head -20
```

For each in_progress issue, check if assignee session exists:
```bash
tmux has-session -t <session> 2>/dev/null && echo "alive" || echo "orphan"
```

**Step 2: If orphans detected, dispatch to dog**
```bash
# Sling orphan-scan formula to an idle dog
gt sling mol-orphan-scan deacon/dogs --var scope=town
```

**Important:** Do NOT fix orphans inline. Dogs handle recovery.
The Deacon's job is detection and dispatch, not execution.

**Step 3: If no orphans detected**
Skip dispatch - nothing to do.

**Exit criteria:** Orphan scan dispatched to dog (if needed).

No in_progress issues found, no orphans to detect