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.


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


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


Digest: mol-deacon-patrol

Patrol cycle 8: all healthy


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-'.

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


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.


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

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.


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


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


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.


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


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

Patrol 17


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


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


Digest: mol-deacon-patrol

Patrol complete: town quiet, all healthy


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 cycle 9: All healthy


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)


Digest: mol-deacon-patrol

Patrol 14 complete


Digest: mol-deacon-patrol

Patrol 13: healthy


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


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


Digest: mol-deacon-patrol

Patrol 16: Quiet


Digest: mol-deacon-patrol

Patrol 14: quick pass


Digest: mol-deacon-patrol

Patrol 91: All healthy


Digest: mol-deacon-patrol

Patrol cycle 3: 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: 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


Mol Mall: Formula marketplace and aspect composition

## Summary

A marketplace for sharing molecule formulas using GitHub as backend, plus a new
**aspect composition** capability for cooking that allows formulas to be applied
as cross-cutting transformations to existing mols.

## Key Insight

Formulas aren't just standalone workflows—they're **transformations** you can
apply to other mols. This enables patterns like:
- "Apply Rule of Five code review to any coding task"
- "Wrap any epic with security review steps"
- "Add logging/metrics to any patrol molecule"

## Architecture

```
Remote Formulas (GitHub)
        ↓ install
Local Formulas (~/.gt/formulas/ or .beads/formulas/)
        ↓ cook --with
Mols (beads, git-tracked)
        ↓ pour/sling
Execution (ephemeral or tracked)
```

## Formula Types

1. **Standalone** - Complete workflows (mol-polecat-work, mol-deacon-patrol)
2. **Aspects** - Cross-cutting concerns woven into other mols (rule-of-five)
3. **Adapters** - Wrappers that make things runnable

## Aspect Composition (New Cooking Capability)

```bash
bd cook my-epic --with rule-of-five,security-review
```

Aspects declare injection points:

```yaml
# rule-of-five.formula.yaml
kind: aspect
name: rule-of-five
version: 1.2.0

inject_after:
  tag: generates-code  # matches any step with this tag

steps:
  - id: review-correctness
    title: "Review: Correctness"
  - id: review-edge-cases
    title: "Review: Edge Cases"
  - id: review-performance
    title: "Review: Performance"
  - id: review-security
    title: "Review: Security"
  - id: review-maintainability
    title: "Review: Maintainability"
```

Injection modes:
- `inject_after: <step-id or tag>` - insert steps after
- `inject_before: <step-id or tag>` - insert steps before
- `wrap: <step-id or tag>` - insert before AND after
- `replace: <step-id or tag>` - substitute entirely

## The Mall Index

A well-known repo maps short names to full references:

```yaml
# steveyegge/gt-mall/index.yaml
formulas:
  rule-of-five:
    repo: steveyegge/gt-formulas
    path: aspects/rule-of-five.formula.yaml
    version: v1.2.0
    description: "Five-lens code review"
    tags: [review, quality]
```

Commands:
- `gt mol search review` - search the index
- `gt mol install rule-of-five` - fetch from GitHub
- `gt mol install github.com/acme/formulas/custom@v1` - direct URL

## Implementation Phases

### Phase 1: Aspect Composition (Cooking)
- Extend `bd cook` to accept `--with aspect1,aspect2`
- Aspect application during mol generation
- Local aspects in `.beads/formulas/`

### Phase 2: Mall Index
- Create gt-mall repo with index.yaml
- `gt mol search` queries the index
- `gt mol install` fetches and caches formulas

### Phase 3: Publishing
- `gt mol publish` pushes to your formula repo
- PR workflow to add to mall index

### Phase 4: Refinements
- Aspect ordering and conflict detection
- Aspect dependencies (`requires: [other-aspect]`)
- Private formula repos (enterprise)
- Local overrides/forks

## Open Questions

1. **Ordering conflicts**: Two aspects inject after same step—which goes first?
2. **Aspect dependencies**: Aspect A requires aspect B?
3. **Compile-time vs runtime**: Aspects are compile-time (baked into mol).
   Wisps remain runtime (slung dynamically).

## Deferred Until

Gas Town patrols operational. Prerequisites:
- [ ] Patrol system working (Deacon, Witness, Refinery)
- [ ] Basic spawn/work/merge cycle
- [ ] Activity feed showing work progress

Then the mall becomes valuable for sharing patrol customizations.

## Supersedes

This replaces gt-uzf2l which had the original marketplace concept but lacked
the aspect composition insight.

## Related

- Cooking system (bd cook)
- Formula definitions (.formula.yaml)
- Wisp architecture (runtime molecules)

See docs/formula_evolution.md for expanded thinking on: formula resolution hierarchy, combinators (>>, |, wrap, inject, extends), algebraic properties, higher abstractions, Mol Mall registry predictions, distribution scenarios, and open questions. The aspect composition in this design corresponds to the Wrapping (AOP) and Injection combinators in that doc.


Digest: mol-deacon-patrol

Patrol complete


MessagingConfig: Add Type field for schema consistency

MessagingConfig lacks a Type field that other config types have (TownConfig has 'town', RigConfig has 'rig', etc). Add Type: 'messaging' for consistency.


Merge: morsov-1766966180179

branch: polecat/morsov-1766966180179
target: main
source_issue: morsov-1766966180179
rig: gastown


mol-sync-workspace: Add vars for build/test commands

Added build_command and test_command variables to mol-sync-workspace formula with template placeholders


Digest: mol-deacon-patrol

Patrol cycle 4: All healthy


Digest: mol-deacon-patrol

Patrol 248 complete: no incidents


Digest: mol-deacon-patrol

Patrol cycle 3: All healthy


Merge: dementus-mjto0502

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


mol-gastown-boot: Mayor-driven town bootstrap

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

## Vision

When user says "boot up gas town", Mayor slings `mol-gastown-boot` and executes it.
Each step has **action + verification** - steps stay open until outcome is confirmed.

## Key Principles

1. **No daemon-based timeouts** - Mayor keeps trying until verified
2. **Verification-gated steps** - Not "command ran" but "outcome confirmed"
3. **gt peek for verification** - Capture session output to detect stalls
4. **gt nudge for recovery** - Reliable message delivery to unstick agents
5. **Parallel where possible** - Witnesses can start in parallel
6. **Ephemeral execution** - Boot is a wisp, squashed to digest

## Proto Catalog

Town maintains a catalog of protos at `~/gt/molecules/`:

```
~/gt/molecules/
├── lifecycle/
│   ├── gastown-boot/       # Full town bootstrap
│   ├── rig-spinup/         # Add a rig at runtime
│   ├── rig-spindown/       # Remove a rig gracefully
│   └── agent-restart/      # Restart single agent
├── patrol/
│   ├── deacon-patrol/      # Deacon health loop
│   ├── witness-patrol/     # Witness polecat loop
│   └── refinery-patrol/    # Refinery merge loop
└── work/
    ├── polecat-work/       # Standard issue workflow
    ├── code-review/        # Pluggable review
    └── feature/            # Feature development
```

## mol-gastown-boot Structure

```
mol-gastown-boot (proto)
├── ensure-daemon       # Verify daemon running
├── ensure-deacon       # Start deacon, verify patrol active
├── ensure-witnesses    # Parallel: all rig witnesses
│   ├── ensure-gastown-witness
│   └── ensure-beads-witness
├── ensure-refineries   # Parallel: all rig refineries
│   ├── ensure-gastown-refinery
│   └── ensure-beads-refinery
└── verify-town-health  # Final gt status check
```

## Step Template

Each step in description includes action + verification:

```markdown
## Step: ensure-deacon

### Action
gt deacon start

### Verify
1. Session gt-deacon exists: `tmux has-session -t gt-deacon`
2. Not stalled: `gt peek deacon/` does NOT show "> Try"
3. Recent heartbeat: deacon/heartbeat.json < 2 min old

### On Stall
gt nudge deacon/ "Start patrol."
Wait 30s, re-verify.

### On Fail
Log error, continue to next step (town can run with degraded deacon)
```

## Event-Triggered Lifecycle

Beyond manual slinging, events can trigger lifecycle wisps:

| Event | Triggers |
|-------|----------|
| `gt town start` | mol-gastown-boot wisp |
| `gt rig add <name>` | mol-rig-spinup wisp |
| `gt rig remove <name>` | mol-rig-spindown wisp |
| Agent crash detected | mol-agent-restart wisp |

## Parameterization (Future)

For rig-spinup/spindown, need to pass rig name:

```bash
gt sling rig-spinup mayor/ --param rig=newproject
```

Molecule steps interpolate `${rig}` in their descriptions.

## Related Issues

- gt-lx3n: Witness startup bond
- gt-j6s8: Refinery startup bond
- gt-rana: Patrol System epic
- gt-sye: Mayor startup protocol


Implement verification patterns for boot steps

Define and implement the verification logic Mayor uses.

## Verification Utilities

Mayor needs to check:

### Session Exists
```bash
tmux has-session -t <session> 2>/dev/null && echo "exists"
```

### Not Stalled (Claude waiting at prompt)
```bash
gt peek <agent> 10 | grep -q "> Try" && echo "stalled"
```

Pattern: `> Try "..."` indicates Claude started but no message sent.

### Recent Heartbeat
```bash
# For deacon
age=$(( $(date +%s) - $(stat -f %m ~/gt/deacon/heartbeat.json) ))
[ $age -lt 120 ] && echo "fresh"
```

### Active Work Output
```bash
gt peek <agent> 20 | grep -q "⏺" && echo "working"
```

Pattern: `⏺` indicates Claude is executing tools.

## Mayor Execution Pattern

```
for each step in molecule:
  run action
  loop:
    check verification
    if verified: close step, continue
    if stalled: run on_stall recovery
    if timeout (5 attempts): log warning, continue
    sleep 10s
```

No hard timeout - Mayor keeps trying with increasing backoff.


Create molecules catalog directory structure

Establish the proto catalog at ~/gt/molecules/.

## Structure

```
~/gt/molecules/
├── README.md           # Catalog overview
├── lifecycle/
│   ├── gastown-boot/
│   │   └── PROTO.md    # Proto definition in markdown
│   ├── rig-spinup/
│   ├── rig-spindown/
│   └── agent-restart/
├── patrol/
│   ├── deacon-patrol/
│   ├── witness-patrol/
│   └── refinery-patrol/
└── work/
    ├── polecat-work/
    ├── code-review/
    └── feature/
```

## PROTO.md Format

```markdown
---
type: lifecycle
parallel: [ensure-witnesses, ensure-refineries]
ephemeral: true
---

# mol-gastown-boot

Town bootstrap molecule.

## Step: ensure-daemon
...
```

## Catalog Loading

`gt sling gastown-boot` should find the proto by:
1. Check beads for existing proto issue
2. If not found, scan ~/gt/molecules/lifecycle/gastown-boot/
3. Auto-create proto issue from PROTO.md

This enables file-based proto development with beads tracking.


Add parallel step support to molecules

Enable steps to run in parallel within a molecule.

## Current State

Molecules have linear step dependencies via "Needs:" directive.
Steps run sequentially.

## Proposed Change

Add parallel grouping:

```markdown
## Step: ensure-witnesses
Parallel: true

### Sub-steps
- ensure-gastown-witness
- ensure-beads-witness
```

Or via frontmatter:

```yaml
---
parallel: [ensure-witnesses, ensure-refineries]
---
```

Steps in parallel group:
- Start simultaneously
- Parent step closes when all children complete
- Failures in one dont block others

## Implementation

1. Parse parallel directive in proto
2. When bonding, create child steps with same dependency
3. Executor spawns parallel children concurrently
4. Track completion, close parent when all done

## For Mayor Bootstrap

Mayor can check all witnesses in parallel, then all refineries,
rather than sequentially. Faster boot time.


Add event-triggered lifecycle wisps

Commands like `gt town start` should auto-trigger lifecycle wisps.

## Event → Wisp Mapping

| Command | Triggers Wisp |
|---------|---------------|
| gt town start | mol-gastown-boot |
| gt rig add <name> | mol-rig-spinup (param: rig=<name>) |
| gt rig remove <name> | mol-rig-spindown (param: rig=<name>) |
| gt daemon restart | mol-gastown-boot |

## Implementation

1. Command implementation checks for lifecycle proto
2. Auto-slings wisp to Mayor with --wisp flag
3. Mayor picks up via molecule attachment

## Alternative: Explicit Sling

Keep commands simple, require explicit:

```bash
gt town start        # Just starts sessions
gt sling gastown-boot mayor/ --wisp   # Bootstrap with verification
```

This is more transparent - user sees the sling happen.

## Recommendation

Start with explicit sling. Add auto-trigger later once pattern proven.
`gt town start --verified` could trigger the wisp.


Design molecule parameterization

Enable protos to accept parameters for customization.

## Use Cases

1. rig-spinup needs rig name: `gt sling rig-spinup --param rig=newproject`
2. agent-restart needs agent: `gt sling agent-restart --param agent=gastown/witness`
3. code-review needs scope: `gt sling code-review --param scope=src/auth/`

## Proposed Syntax

### In Proto

```markdown
## Step: create-rig-structure
mkdir -p ~/gt/${rig}/refinery ~/gt/${rig}/witness
```

### In Sling

```bash
gt sling rig-spinup mayor/ --param rig=newproject --wisp
```

### In Bonded Molecule

Interpolation happens at bond time. Step descriptions have concrete values.

## Implementation

1. Proto declares params in frontmatter: `params: [rig]`
2. gt sling validates required params provided
3. bd mol bond receives params, interpolates descriptions
4. Bonded molecule has concrete step text

## Edge Cases

- Missing required param → error
- Unused param → warning
- Param in step title → interpolate there too


Update Mayor startup protocol for bootstrap

Teach Mayor to respond to "boot up gas town" by slinging mol-gastown-boot.

## Current Protocol

1. Announce: "Mayor, checking in."
2. Check mail
3. If handoff, continue
4. Await user instruction

## Enhanced Protocol

1. Announce: "Mayor, checking in."
2. Check mail
3. If handoff, continue
4. **If user says "boot"/"startup"/"bootstrap":**
   - Sling mol-gastown-boot as wisp
   - Execute verification-gated steps
   - Report town status when complete
5. Otherwise await instruction

## Trigger Phrases

- "boot up gas town"
- "bootstrap the town"
- "start gas town"
- "bring up the town"

## Execution

Mayor runs the molecule manually (not via subagent):

```
1. Bond the proto: bd mol bond mol-gastown-boot --wisp
2. For each step:
   a. Run action command
   b. Loop verification with backoff
   c. On stall, run recovery
   d. Close step when verified
3. Squash wisp with summary
4. Report: "Gas Town is up. All agents healthy."
```

## CLAUDE.md Update

Add to Mayor CLAUDE.md:

```markdown
## Bootstrap Command

When user requests town bootstrap:
1. gt sling gastown-boot mayor/ --wisp
2. Execute molecule steps with verification
3. Keep trying until all agents healthy
4. No timeouts - you are the town engineer
```


Digest: mol-deacon-patrol

Patrol 20: All healthy. Handoff after 20 cycles.


Digest: mol-deacon-patrol

Patrol 19: all healthy


Digest: mol-deacon-patrol

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


Digest: mol-deacon-patrol

Patrol 8: all healthy


Digest: mol-deacon-patrol

Patrol 82: All agents healthy, quiet cycle


Digest: mol-deacon-patrol

Patrol 134: All healthy


Merge: gt-594l2

branch: polecat/morsov-1766966180179
target: main
source_issue: gt-594l2
rig: gastown


Digest: mol-deacon-patrol

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


Digest: mol-deacon-patrol

Cycle 5: healthy


Digest: mol-deacon-patrol

Patrol 1: All healthy, no messages, no orphans


Digest: mol-deacon-patrol

Patrol 4: Quiet


Digest: mol-deacon-patrol

Patrol 8: Quiet


Digest: mol-deacon-patrol

Patrol cycle 20: all healthy, handing off


gt polecat done should auto-stop running session

Currently 'gt polecat done' fails if session is running, requiring a separate 'gt session stop' first. This is unnecessary friction - done should just stop the session automatically since that's always what you want.


Digest: mol-deacon-patrol

Patrol cycle 20: All agents healthy, handoff threshold reached


Digest: mol-deacon-patrol

Patrol 20: All healthy, 17 sessions


Digest: mol-deacon-patrol

Patrol 206: All nominal


Merge: nux-1767138828269

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


gt crew add: role_bead field references non-existent bead

## Problem

When `gt crew add` creates an agent bead (e.g., `gt-crew-gastown-grip`), it sets:
```
role_bead: gt-crew-gastown-grip-role
```

This is WRONG. It creates per-instance role bead references that don't exist.

## Correct Pattern

Role beads are SHARED templates defining what a role IS. Agent beads reference them:

| Role Type | Role Bead (shared) | Agent Bead (per-instance) |
|-----------|-------------------|---------------------------|
| Mayor | gt-mayor-role | gt-mayor |
| Deacon | gt-deacon-role | gt-deacon |
| Witness | gt-witness-role | gt-witness-<rig> |
| Refinery | gt-refinery-role | gt-refinery-<rig> |
| Crew | gt-crew-role | gt-crew-<rig>-<name> |
| Polecat | gt-polecat-role | gt-polecat-<rig>-<name> |

## Current State

Working correctly:
- gt-mayor → gt-mayor-role ✅
- gt-witness-gastown → gt-witness-role ✅
- gt-refinery-gastown → gt-refinery-role ✅

Broken:
- gt-deacon → gt-deacon-role (bead doesn't exist)
- gt-crew-* → gt-crew-<rig>-<name>-role (wrong pattern, beads don't exist)
- gt-polecat-* → (not set at all)

## Code Locations

1. `internal/cmd/crew_add.go:91` - sets `RoleBead: crewID + "-role"`
   Should be: `RoleBead: "gt-crew-role"`

2. `internal/polecat/manager.go:220,426` - doesn't set RoleBead
   Should set: `RoleBead: "gt-polecat-role"`

## Fix Required

1. Create missing role beads: gt-crew-role, gt-polecat-role, gt-deacon-role
2. Fix crew_add.go to use shared gt-crew-role
3. Fix polecat/manager.go to use shared gt-polecat-role
4. Update existing crew agent beads to point to gt-crew-role

Fixed. Created shared role beads (gt-crew-role, gt-polecat-role, gt-deacon-role). Fixed code to reference shared role beads. Updated existing crew agent beads via bd slot set.


Digest: mol-deacon-patrol

Patrol 11 complete


Witness emits activity events

Witness emits events to activity stream for patrol activity:

Events to emit:
- patrol_started: When witness begins patrol cycle
- polecat_checked: When witness checks a polecat
- polecat_nudged: When witness nudges a stuck polecat
- escalation_sent: When witness escalates to Mayor/Deacon
- patrol_complete: When patrol cycle finishes

This replaces stats tracking in .runtime/witness.json

Implemented witness activity events: patrol_started, polecat_checked, polecat_nudged, escalation_sent, patrol_complete. Added gt activity emit command for CLI access. Events write to ~/gt/.events.jsonl.


Digest: mol-deacon-patrol

Patrol cycle 10: all healthy


Digest: mol-deacon-patrol

Patrol #4: All systems nominal


Implement await type handlers (gh:run, gh:pr, timer, human, mail)

Implement condition checking for each await type.

## Handlers Needed
- gh:run:<id> - Check GitHub Actions run status via gh CLI
- gh:pr:<id> - Check PR merged/closed status via gh CLI
- timer:<duration> - Simple elapsed time check
- human:<prompt> - Check for human approval (via mail?)
- mail:<pattern> - Check for mail matching pattern

## Interface
```go
type AwaitHandler interface {
    Check(awaitID string) (completed bool, result string, err error)
}
```

## Moved from beads
Originally bd-2l03. Deacon handlers belong in gastown.


Digest: mol-deacon-patrol

Patrol 3: routine, all healthy


Digest: mol-deacon-patrol

Patrol 18 complete


MessagingConfig: Fix error message inconsistency in validation

Negative value errors don't wrap ErrMissingField while empty-list errors do. Should be consistent - either all wrap a sentinel or none do.


Digest: mol-deacon-patrol

Patrol 74: Routine


Digest: mol-deacon-patrol

Cycle 186: Nominal


Digest: mol-deacon-patrol

Patrol 5: all healthy


Cross-rig agent identity detection

## Problem

Several gt commands fail to correctly detect agent identity when operating
across rigs. Running commands from beads/crew/dave shows gastown/crew/joe
identity, or fails to resolve paths.

## Root Cause

Agent identity detection in gt commands assumes single-rig context. Cross-rig
crew paths like `beads/crew/dave` are not handled correctly.

## Scope

- gt hook - shows wrong identity from other rig crew dir
- gt peek - fails to resolve cross-rig crew paths
- gt sling - "." target not resolved to current agent

## Fix Strategy

Centralize agent identity detection to handle:
1. Current rig detection from cwd
2. Cross-rig path parsing (rig/crew/name vs rig/polecats/name)
3. "." resolution to current agent identity


Deacon Patrol

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

Duplicate patrol molecule beads - keeping gt-t5i07, gt-8ynws, gt-kt9qq


Digest: mol-deacon-patrol

Routine patrol, town stable


Digest: mol-deacon-patrol

Patrol 157: All healthy


Implement gt convoy add command

Add the 'add' subcommand to convoy for adding issues to existing convoys.

SYNTAX:
gt convoy add <convoy-id> <issue-id> [issue-id...]

BEHAVIOR:
1. Validate convoy exists
2. Add 'tracks' dependency for each issue
3. If convoy is closed, reopen it automatically
4. Print confirmation

IMPLEMENTATION:
File: internal/cmd/convoy.go
Add: convoyAddCmd as subcommand

Example:
gt convoy add hq-cv-abc gt-new-issue
# -> Added gt-new-issue to convoy hq-cv-abc

gt convoy add hq-cv-abc gt-followup  # convoy was closed
# -> Reopened convoy hq-cv-abc
# -> Added gt-followup to convoy hq-cv-abc

Verified implementation: build passes, help works, add/reopen tested


Merge: nux-1767087680976

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


Digest: mol-deacon-patrol

Patrol 7 complete. All healthy.


Digest: mol-deacon-patrol

Patrol 19: All clear


Merge: rictus-1767087768853

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


Digest: mol-deacon-patrol

Cycle 181: All agents healthy, processed 3 health acks, 7 doctor warnings noted (non-critical), no incidents


Digest: mol-deacon-patrol

Cycle 4: All healthy


Digest: mol-deacon-patrol

Quick patrol: no messages, all healthy


Digest: mol-deacon-patrol

Patrol 28: all quiet


gt done: Capture session_id in issue close for CV attribution

## Context

Per decision 009-session-events-architecture.md, work attribution should happen
by capturing session_id on beads mutations. This enables querying "what work
did this session do?" for entity CV building.

## Implementation

When gt done closes an issue, pass CLAUDE_SESSION_ID to bd close:

```go
// In done.go
sessionID := os.Getenv("CLAUDE_SESSION_ID")
if sessionID != "" {
    // Pass to bd close via --session flag or env var
}
```

## Acceptance Criteria

- [ ] gt done passes session_id to bd close
- [ ] Issue close events include session attribution
- [ ] Works for gt mol complete as well

## Dependencies

- Beads must support session_id on issue close (bd-* issue)

## Related

- docs/hop/decisions/009-session-events-architecture.md


Digest: mol-deacon-patrol

Patrol 41 complete: All agents healthy, 2 convoys in progress (Hanoi, Messaging), health pings sent, 1 idle dog


Digest: mol-deacon-patrol

Patrol 41: All healthy, 3 rigs, 3W/3R pinged, no incidents


Add gt mail clear command for bulk inbox clearing

Currently `gt mail delete` only accepts a single message-id. Need:

1. `gt mail clear` - Clear all messages from your inbox
2. `gt mail clear <target>` - Clear another agent's inbox (e.g., `gt mail clear gastown/joe`)
3. Or: `gt mail delete --all` flag

Use case: Town quiescence - need to reset all inboxes across all workers efficiently.

Current workaround: Loop through each message ID individually, which is tedious for 50+ messages per inbox.


Digest: mol-deacon-patrol

Patrol 150 complete


Digest: mol-deacon-patrol

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


Digest: mol-deacon-patrol

Cycle 4: healthy, refinery started


Digest: mol-deacon-patrol

Cycle 194: Nominal


Digest: mol-deacon-patrol

Patrol cycle 9: All healthy.


Digest: mol-deacon-patrol

Cycle 12: quiet


Digest: mol-deacon-patrol

Patrol 19: quiet


Digest: mol-deacon-patrol

Patrol 15: all clear


Digest: mol-deacon-patrol

Patrol 16: quiet


Test Patrol Parent

Test parent for Christmas Ornament pattern


gt crew add: CLAUDE.md customization leaves git dirty

When gt crew add generates a customized CLAUDE.md for crew workers, it differs from the repo version (Crew Worker Context vs Polecat Context, personalized footer). This leaves the git state 'dirty'.

Options:
1. Add CLAUDE.md to .gitignore in crew workspaces
2. Auto-commit the customized CLAUDE.md locally
3. Store crew CLAUDE.md content elsewhere (e.g., .claude/CLAUDE.md)

Current behavior is functional but 'gt crew list' shows 'Git: dirty' for new crew.

Found during: adding crew workers grip, fang, wolf


Mail inbox from witness/refinery dirs shows Mayor inbox

When running `gt mail inbox` from the witness or refinery directories, it shows the Mayor's inbox instead of the agent's own inbox.

Reproduction:
```
$ cd ~/gt/beads/witness && gt mail inbox
📬 Inbox: mayor/ (1 messages, 1 unread)
  ● 🤝 HANDOFF: Swarm session complete...
```

Expected: Should show beads/witness inbox

Likely cause: The cwd-based identity resolution isn't recognizing witness/refinery as valid mail identities, so it falls back to Mayor.

Fixed by falling back to cwd-based detection when GT_ROLE is not set


Digest: mol-deacon-patrol

Patrol 157 complete


Day 3.7: Witness pings Deacon for second-order monitoring

Add second-order monitoring: Witnesses monitor the Deacon.

Problem: Who monitors the Deacon? If Deacon dies, the whole town stalls.

Solution:
1. Each Witness periodically sends a ping to Deacon during patrol:
   ```bash
   gt mail send deacon/ -s "WITNESS_PING" -m "{\"rig\": \"gastown\"}"
   ```

2. Deacon patrol (inbox-check) aggregates witness pings as health signals

3. If Witness doesn't get Deacon response for 2 cycles:
   - Escalate to Mayor: "Deacon unresponsive"
   - Mayor can restart Deacon via daemon

This creates overlapping patrols:
- Deacon monitors Witnesses/Refineries
- Witnesses monitor Deacon (collectively)
- Mayor is escalation target for both

Add to mol-witness-patrol after survey-workers step.


Merge: nux-mjtj9d8q

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


Digest: mol-deacon-patrol

Patrol cycle 16: All healthy - 8 polecats running (max, jack, dementus, capable, toast, dag + crew). Handing off after 6 cycles.


Add neighbor-check steps to all patrol molecules

Part of the 'Gas Town is a Village' antifragility design.

Every patrol molecule should include optional neighbor-checking:
- Deacon checks Witness and Refinery health
- Witness checks Refinery health
- Refinery checks Witness health
- Polecats can peek other polecats

Use gt peek to check health states.
If stuck neighbor found, can nudge or escalate.

This creates distributed monitoring - no single point of failure.


Digest: mol-deacon-patrol

Patrol cycle 14: All 6 agents healthy


Digest: mol-deacon-patrol

Patrol cycle 17: All healthy


BUG: Cross-beads slot references silently fail

When slinging work from town beads (hq-*) to a polecat whose agent bead is in rig beads (gt-*), the hook_bead update silently fails.

**Reproduction:**
```
# From mayor (town root):
gt sling hq-oosxt gastown/polecats/nux

# This runs (in updateAgentHookBead):
bd slot set gt-gastown-polecat-nux hook hq-oosxt
# FAILS: can't find hq-oosxt (different beads directory)
# Error is silently ignored!
```

**Result:**
- Agent bead keeps stale hook_bead value
- gt hook shows wrong/old work
- Agent doesn't know what they're actually assigned

**Root cause:**
sling.go line 812-814 silently ignores UpdateAgentState errors:
```go
if err := bd.UpdateAgentState(agentBeadID, "running", &beadID); err != nil {
    // Silently ignore - agent bead might not exist yet
    return
}
```

**Fix options:**
1. Log warnings instead of silent ignore
2. Support cross-beads slot references (store as 'hq-oosxt@town' or similar)
3. Use external: prefix for cross-beads hooks
4. Always store hook in the WORK bead's directory, not agent bead

Discovered during investigation of stale hook issue.

Fixed: Use town root for routing in sling/done, log warnings instead of silent ignore


Digest: mol-deacon-patrol

Patrol 161: All agents healthy, no incidents, 1 dog idle


Digest: mol-deacon-patrol

P19: stable


Digest: mol-deacon-patrol

Patrol 19: All healthy


Digest: mol-deacon-patrol

Patrol 11: quick pass


Digest: mol-deacon-patrol

Patrol 12: All healthy


Session cycling: Auto-spawn successor when context full

Enable automatic session succession for crew workers.

When a crew worker's context fills up (>80%), they should:
1. Write handoff mail to themselves
2. Signal session end
3. System auto-spawns successor session
4. Successor reads handoff, finds attached work, auto-continues

This completes the autonomous overnight work pattern from gt-9g82.

Depends on:
- Detecting context fullness (Claude Code API?)
- Session spawning mechanism (tmux/daemon)
- Handoff protocol already implemented


ZFC #9: Explicit MR registration instead of branch parsing

**ZFC Violation:** internal/refinery/manager.go:346-370

Go infers work metadata from branch naming conventions:
```go
pattern := regexp.MustCompile(`^polecat/([^/]+)(?:/(.+))?$`)
worker := matches[1]
issueID = matches[2]
```

**ZFC-compliant solution:**
Polecats register MRs with explicit structured data:
- `gt mq submit --worker=nux --issue=gt-xyz --branch=polecat/nux/gt-xyz`
- Creates MR bead with explicit fields
- No regex parsing of branch names

**Benefits:**
- Work metadata is explicit, not inferred
- Branch naming can evolve without breaking refinery
- Audit trail in beads

Reference: ~/gt/docs/zfc-violations-audit.md #9


Digest: mol-deacon-patrol

Patrol 102: All agents healthy, no incidents


Digest: mol-deacon-patrol

Patrol 100: All healthy. Handing off after 20 patrols.


Digest: mol-deacon-patrol

Patrol 3: Quiet


Digest: mol-deacon-patrol

Patrol 70: Routine


Merge: dementus-1767074970788

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

Branch no longer exists on remote - already merged or cleaned up


Fix gt polecats docs in reference.md

reference.md:211 documents 'gt polecats <rig>' but actual command is 'gt polecat list [rig]'. Already fixed in ~/gt/CLAUDE.md.

Fixed: updated gt polecats to gt polecat list in Go files and templates


Digest: mol-deacon-patrol

Patrol 20: all healthy, handoff threshold reached


Digest: mol-deacon-patrol

Patrol cycle 24: All healthy, no incidents


Digest: mol-deacon-patrol

Patrol cycle 16: All healthy.


Digest: mol-deacon-patrol

Patrol cycle 3: All quiet. Agents healthy. No pending work.


Merge: ace-mjufugk0

branch: polecat/ace-mjufugk0
target: main
source_issue: ace-mjufugk0
rig: gastown


Create AgentIdentity type for session name parsing

attached_args: Create AgentIdentity type - depends on completed gt-atqr8

Create AgentIdentity type to parse and construct session names, replacing duplicated logic.

## Files to modify
- internal/session/identity.go (NEW)
- internal/cmd/sling.go (update to use new type)
- internal/cmd/handoff.go (update to use new type)

## Implementation
```go
type AgentIdentity struct {
    Role     string // mayor, deacon, witness, refinery, crew, polecat
    Rig      string // empty for mayor/deacon
    Name     string // crew/polecat name
}

func ParseSessionName(session string) (*AgentIdentity, error)
func (a *AgentIdentity) SessionName() string
func (a *AgentIdentity) Address() string // e.g., "gastown/crew/max"
```

## Acceptance criteria
- [ ] AgentIdentity type with Role, Rig, Name fields
- [ ] ParseSessionName handles all agent types (mayor, deacon, witness, refinery, crew, polecat)
- [ ] SessionName() reconstructs valid session name
- [ ] Address() returns mail-style address
- [ ] sling.go:sessionToAgentID replaced with ParseSessionName
- [ ] handoff.go:sessionToGTRole replaced with ParseSessionName
- [ ] Unit tests for all parsing cases
- [ ] go test ./... passes


Digest: mol-deacon-patrol

Patrol 6: quick pass


Digest: mol-deacon-patrol

Patrol 14: all healthy


Maintenance: Regular cleanup of closed MR/gate beads

Closed merge-request and gate beads accumulate over time. Need regular cleanup.

## Cleanup Candidates
- type=merge-request with status=closed
- type=gate with status=closed
- type=molecule with status=closed (completed workflows)

## Options
1. **Deacon patrol step** - squash closed MRs periodically
2. **Refinery post-merge** - close and tombstone MR after successful merge
3. **bd doctor check** - warn when stale MR count exceeds threshold

## Consideration
Keep some audit trail? Or just tombstone after N days?


Digest: mol-deacon-patrol

Patrol cycle 16: all healthy


Digest: mol-deacon-patrol

Patrol cycle 81: All healthy. 3 rigs, 6 agents pinged. No incidents.


Merge: nux-1767073376184

attached_args: Code review this merge request

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

Code review complete. BLOCKED: needs rebase before merge. Stale branch would revert swarm fixes from 10e79789. See comments for details.


Merge: nux-1767079896198

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


Digest: mol-deacon-patrol

Cycle 19


Digest: mol-deacon-patrol

Patrol cycle 18: All healthy.


Add unit tests for internal/lock package

attached_args: Lock package tests

Add comprehensive tests for the file locking package.

## Files to create
- internal/lock/lock_test.go

## Test cases to cover
1. Lock() acquires lock successfully
2. Lock() blocks when lock held by another
3. Unlock() releases lock
4. TryLock() returns immediately if locked
5. IsLocked() detects lock state
6. Lock file contains correct PID
7. Stale lock detection (if implemented)

## Acceptance criteria
- [ ] internal/lock/lock_test.go created
- [ ] At least 5 test functions
- [ ] Tests pass: go test ./internal/lock/...
- [ ] Coverage > 70%: go test -cover ./internal/lock/...


gt doctor: add Claude settings.json validation

Add a new doctor check to validate Claude Code settings in worker directories:

**Check for:**
1. .claude/settings.json exists in polecats/*, crew/*, witness/rig, refinery/rig
2. SessionStart hook has 'gt prime' command
3. Autonomous roles (polecat, witness, refinery) have 'gt mail check --inject' in SessionStart
4. Interactive roles (crew, mayor) have mail check in UserPromptSubmit only

**Auto-fix capability:**
Use internal/claude.EnsureSettingsForRole() to create missing settings files.

Context: The spawn priming race condition fix (gt-6957) added embedded settings templates. Doctor should validate these are in place.


Extend gt nudge to support channel:name syntax

Add channel support to internal/cmd/nudge.go.

CURRENT BEHAVIOR:
gt nudge <session> <message> - nudges single session

NEW BEHAVIOR:
gt nudge channel:<name> <message> - nudges all members of channel

IMPLEMENTATION:
1. Detect if target starts with 'channel:'
2. If so, extract channel name
3. Load messaging.json via config.LoadMessagingConfig
4. Look up NudgeChannels[name]
5. Resolve each member pattern to session names (use existing resolution logic)
6. Call t.NudgeSession() for each

PATTERN RESOLUTION:
- Literal: gastown/witness → session name
- Wildcards: gastown/polecats/* → expand via getAgentSessions()
- @groups: @town → expand via parseGroupAddress() patterns

FILE: internal/cmd/nudge.go
TESTS: Add TestNudgeChannel

NOTE: Look at broadcast.go for session enumeration patterns.

Implemented channel:name syntax with pattern resolution and tests


Day 2.6: Define bd agent state command

Add command for agents to write their own state to agent beads.

```bash
bd agent state <agent-id> <state>
# Example: bd agent state gt-mayor running
# States: idle | running | stuck | stopped | dead
```

Implementation:
1. Lookup agent bead by ID
2. Update state field
3. Update last_activity timestamp
4. Trigger bd sync if configured

Also add:
- bd agent heartbeat <agent-id> - just updates last_activity
- bd agent show <agent-id> - show agent bead details

This is the ZFC-compliant way for agents to self-report state.

Delegated to beads repo: bd-uxlb. Assign to beads/crew/dave.


Digest: mol-deacon-patrol

Patrol cycle 73: All healthy


MEOW Stack Evolution: Higher-Order Workflow Abstractions

Molecular Expression of Work (MEOW) - the full taxonomy of workflow abstractions.

## Current Hierarchy

```
WORK TRACKING              WORKFLOW EXECUTION
─────────────              ──────────────────

Bead (issue)               Step (action)
    │                          │
    ▼                          ▼
Epic (bead group)          Molecule (runtime)
    │                          │
    ▼                          │
    └───────► CAMPAIGN ◄───────┘
                  │
                  ▼
             Schematic (domain template)
                  │
                  ▼
             Protocol (interface/type)
                  │
                  ▼
             Catalyst (meta-generator)
                  │
                  ▼
             Mol Mall (distribution)
```

## Key Concepts

1. **Campaign** (gt-camx5): Molecule-wrapped Epic graph for orchestrated execution
2. **Schematic** (gt-8ws7o): Domain-level formula composition
3. **Protocol** (gt-y3jb9): Type system for formulas
4. **SDK** (gt-ihzqr): Developer tooling (Forge, Lab, Validator)
5. **Mol Mall** (gt-vm85o): Package registry for distribution

## Design Principles

- Chemistry metaphor: atoms → molecules → compounds → materials
- Two orthogonal dimensions: work tracking × workflow execution
- Campaign is the convergence point
- Everything compiles down to executable molecules

## Origin

Discussion: 2024-12-26, Mayor session
Related: docs/formula_evolution.md
Foundation: gt-8tmz (Molecule Algebra)


Digest: mol-deacon-patrol

Patrol 141: All agents healthy, 4 polecats working, no issues


Digest: mol-deacon-patrol

Patrol cycle 16: All 6 agents healthy


Digest: mol-deacon-patrol

Patrol cycle 13: All healthy


mol-sync-workspace: Add Refinery-specific inline conflict resolution guidance


Digest: mol-deacon-patrol

Cycle 187: Nominal


Digest: mol-deacon-patrol

Patrol 37: all quiet


Digest: mol-deacon-patrol

Patrol 15: All healthy


Digest: mol-deacon-patrol

Patrol 93: All healthy


Digest: mol-deacon-patrol

Patrol cycle 2: all healthy, no incidents


Digest: mol-deacon-patrol

Patrol 120: All healthy - session complete


Digest: mol-deacon-patrol

Patrol 10 complete


Digest: mol-deacon-patrol

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


Digest: mol-deacon-patrol

Patrol 26: furiosa session started, all quiet


Digest: mol-deacon-patrol

Patrol cycle 5: All agents healthy


Digest: mol-deacon-patrol

Patrol 29: all quiet


Digest: mol-deacon-patrol

Patrol 11: routine


Digest: mol-deacon-patrol

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


Digest: mol-deacon-patrol

Patrol 257 complete: no incidents


Day 2.7b: gt rig add creates Witness and Refinery agent beads

Update gt rig add to create agent beads:

1. After initializing rig beads, create:
   - gt-witness-<rig> agent bead (role_type: witness, rig: <rig>, agent_state: idle)
   - gt-refinery-<rig> agent bead (role_type: refinery, rig: <rig>, agent_state: idle)

2. Use bd create --type=agent or internal beads API

Files:
- internal/cmd/rig.go
- internal/rig/manager.go


Plugin: merge-oracle (merge queue analysis)

Example plugin that analyzes changesets before Refinery processes them. Builds overlap graph, classifies disjointness (parallel-safe vs needs-sequencing), uses LLM for semantic complexity, identifies high-risk patterns. Based on merge-orchestration proposal. See docs/architecture.md.


Digest: mol-deacon-patrol

Patrol 9


Digest: mol-deacon-patrol

Cycle 5: 2 acks


Digest: mol-deacon-patrol

Patrol cycle 10: All healthy


Test Patrol Parent

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

Original description:
Test parent for Christmas Ornament pattern


Digest: mol-deacon-patrol

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


Add isAnnounceAddress() and parseAnnounceName() helpers to router.go

Add announce address detection to internal/mail/router.go.

PATTERN TO FOLLOW:
Look at isListAddress() and parseListName() at lines 53-60 as the template.

IMPLEMENTATION:
1. Add isAnnounceAddress(address string) bool - returns true if address starts with 'announce:'
2. Add parseAnnounceName(address string) string - extracts announce name after 'announce:'
3. Add var ErrUnknownAnnounce = errors.New("unknown announce channel")

FILE: internal/mail/router.go
TESTS: Add tests in internal/mail/router_test.go

Small, focused task - just address detection, not delivery.


Digest: mol-deacon-patrol

Patrol 19: Quiet


Implement git merge logic in Engineer.ProcessMR

The Engineer module in internal/refinery/engineer.go has stub implementations for ProcessMR() and ProcessMRFromQueue() that need actual git merge logic.

## Current State
- ProcessMR() logs intent but returns failure
- ProcessMRFromQueue() same - logs and returns failure
- handleSuccess() and handleFailure() are implemented

## Required Implementation
1. **Fetch source branch**: git fetch origin <branch>
2. **Conflict check**: git merge --no-commit --no-ff to test
3. **Run tests** if configured (config.RunTests, config.TestCommand)
4. **Perform merge**: git merge with appropriate commit message
5. **Push to origin**: git push origin <target>
6. **Handle failures**: conflicts, test failures, push failures

## Context
- There are 28+ pending merge-request issues waiting for this
- Infrastructure (config, result types, success/failure handlers) is ready
- Just needs the core git operations

## Files
- internal/refinery/engineer.go - ProcessMR(), ProcessMRFromQueue()
- internal/git/git.go - may need Merge(), Fetch() methods

Implemented ProcessMR and ProcessMRFromQueue with full git merge logic: fetch, conflict check, test run, merge, push


gt-polecat-gastown-ace

gt-polecat-gastown-ace

role_type: polecat
rig: gastown
agent_state: running
hook_bead: gt-795e8
role_bead: null


gt-polecat-gastown-capable

gt-polecat-gastown-capable

role_type: polecat
rig: gastown
agent_state: running
hook_bead: gt-tkbd5
role_bead: null


gt-polecat-gastown-furiosa

gt-polecat-gastown-furiosa

role_type: polecat
rig: gastown
agent_state: done
hook_bead: null
role_bead: null
cleanup_status: clean