gt-polecat-gastown-morsov

gt-polecat-gastown-morsov

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


gt-polecat-gastown-nux

gt-polecat-gastown-nux

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


gt-polecat-gastown-rictus

gt-polecat-gastown-rictus

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


gt-polecat-gastown-slit

gt-polecat-gastown-slit

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


gt-polecat-gastown-warboy

gt-polecat-gastown-warboy

role_type: polecat
rig: gastown
agent_state: spawning
hook_bead: null
role_bead: null


Polecat Role Definition

You are a Polecat - an autonomous worker assigned to a specific issue.

You work independently, following the mol-polecat-work formula, and signal
completion to your Witness. You are transient - spawned for work, cleaned up
after completion.

session_pattern: gt-{rig}-{name}
work_dir_pattern: {town}/{rig}/polecats/{name}
needs_pre_sync: true
start_command: export GT_ROLE=polecat GT_RIG={rig} GT_POLECAT={name} BD_ACTOR={rig}/polecats/{name} && claude --dangerously-skip-permissions

default_molecule: mol-polecat-work
capabilities:
  - execute_assigned_work
  - git_operations
  - branch_management
  - completion_signaling

## Core Responsibilities

1. Execute your pinned molecule's steps
2. Maintain clean git state
3. Signal completion via gt done
4. Wait for Witness to handle lifecycle

## You Do NOT

- Push directly to main (Refinery merges)
- Kill your own session (Witness does cleanup)
- Skip verification steps
- Work on anything other than your assigned issue

## Propulsion Principle

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

Your work is defined by your pinned molecule. Execute steps:
- bd ready (find next step)
- bd show <step-id> (see what to do)
- bd close <step-id> (mark complete)

## Completion Protocol

When done:
1. Tests pass: go test ./...
2. COMMIT changes: git add and git commit
3. Push branch: git push -u origin HEAD
4. Close issue: bd close <issue>
5. Sync beads: bd sync
6. Run gt done
7. WAIT: Witness will kill your session

## Communication

Mail your Witness when stuck:
gt mail send <rig>/witness -s "HELP: <problem>" -m "..."


Merge: morsov-1767074381346

attached_args: Code review this merge request

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

Already merged: morsov's work (commit 10e79789: Fix swarm not tracking dynamically added workers) is present in main. Branch is ancestor of main - no merge needed.


Digest: mol-deacon-patrol

Patrol complete: all healthy


Digest: mol-deacon-patrol

Patrol cycle 39: All healthy, no incidents


Add GitHub CI workflow for PRs

Gas Town has no CI. Add .github/workflows/ci.yml that runs tests and linter on PRs. Reference beads repo for example.

Added .github/workflows/ci.yml with test, lint, and beads protection jobs


Digest: mol-deacon-patrol

Patrol cycle 8: All 6 agents healthy


Digest: mol-deacon-patrol

Patrol 18: healthy


Day 2.2: Remove PID/tmux state inference

Remove ZFC violations where Go infers state from signals:
- No more PID file checks
- No more tmux session parsing
- No more branch pattern analysis

Daemon becomes pure transport layer.

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

Parent: gt-d0jqp

Removed PID/tmux state inference from refinery Status(), witness Status(), daemon ensureDeaconRunning(), and daemon pokeDeacon(). Daemon now trusts agent bead state per ZFC. Removed 78 lines of inference code.


Digest: mol-deacon-patrol

Cycle 7: quiet


Digest: mol-deacon-patrol

Patrol 75: Routine


Merge: ace-dogs

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


Post-work discovery: AI analysis finds follow-on issues

AI analyzes completed work to discover: bugs, punted work, follow-on tasks.

**From VC**: Supervisor.AnalyzeResult() with iterative refinement. ~300 lines.

**Gas Town implementation**: Post-work hook in molecule:
```yaml
post_work:
  discover:
    - bugs
    - punted_items
    - follow_on_work
  file_as: beads
```

Polecat output gets analyzed by AI, discovered work becomes beads issues.

**Value**: Nothing gets forgotten. VC found ~25% more issues with refinement.

**Key**: Use semantic deduplication (gt-xxx) to avoid pollution.


bd list: Add type aliases (mr→merge-request)

The --type flag requires exact matches. Add aliases for convenience:

- mr → merge-request
- feat → feature
- mol → molecule

**Context**: Refinery cleanup missed 6 open MRs because `--type=mr` returned nothing while `--type=merge-request` found them.

**Implementation**: In the type filter parsing, normalize aliases before matching.


Digest: mol-deacon-patrol

Patrol 15: all healthy


Digest: mol-deacon-patrol

Patrol 123: All healthy


Digest: mol-deacon-patrol

Patrol cycle 3: All 6 agents healthy, 2 polecats (furiosa, nux), refinery queues active (gastown:2, beads:1)


gt session start --issue doesn't pin work to hook

When starting a polecat with --issue, the work isn't pinned to the hook:
  gt session start beads/Toast --issue bd-oxgi

After session starts, 'gt mol status' shows empty hook.

The polecat had to manually discover the work via bd ready. The --issue flag should call 'gt hook attach' or equivalent to pin the work.

Fixed: --issue flag now hooks work to polecat via bd update --status=hooked


Work on ga-ct2: Add MR workflow to polecat completion. Wh...

Work on ga-ct2: Add MR workflow to polecat completion. When polecat completes work, auto-create MR to integration branch. When done, submit MR (not PR) to integration branch for Refinery.


Digest: mol-deacon-patrol

P9: stable


Digest: mol-deacon-patrol

Cycle 6: quiet


mol-crew-session: Startup/shutdown protocols for crew workers

Crew workers (like joe, max) don't have patrol molecules keeping them fresh. When gt gets rebuilt, they have stale binaries that cause hangs and bugs.

## Problem

- Crew binaries get stale when gt is rebuilt elsewhere
- No automatic pull/rebase/rebuild on session start
- No standardized shutdown protocol (sync, push, handoff)

## Solution: mol-crew-session

A molecule template for crew sessions:

### Startup Phase
1. `git pull --rebase` - get latest code
2. `bd sync` - sync beads
3. `go build -o gt ./cmd/gt` - rebuild gt (if in gastown)
4. `gt prime` - load context

### Work Phase
- Open-ended human interaction
- No molecule steps - just work until done

### Shutdown Phase
1. `git status` - check for uncommitted changes
2. `bd sync` - sync beads
3. `git push` - push code
4. Handoff if incomplete work

## Implementation

1. Define mol-crew-session in builtin_molecules.go
2. Update crew CLAUDE.md to reference the protocol
3. Optionally: gt prime auto-runs startup steps

## Dependencies

- Should implement after deacon/witness/polecat patrols are stable
- Consider: gt-3x0z.10 (Witness patrol molecules)

## Related

- gt-3x0z.9: Deacon wisp patrol (done)
- fix-gt script: Current workaround for binary freshness


Implement sendToAnnounce() for bulletin board delivery

Add announce message delivery to internal/mail/router.go.

SEMANTICS:
- ONE copy in shared location (not fan-out)
- Messages persist until retention limit reached
- No claiming, no removal on read

STORAGE:
- Location: {townRoot}/.beads/
- Metadata: announce_channel field to identify which channel

RETENTION:
- On send, count existing messages in channel
- If count >= retain_count, delete oldest
- retain_count=0 means unlimited

IMPLEMENTATION:
1. Add sendToAnnounce(msg *Message) error
2. Load AnnounceConfig from messaging.json
3. Validate sender is eligible (readers list) - optional
4. Create message bead with announce_channel metadata
5. Apply retention pruning

FILE: internal/mail/router.go
PATTERN: Similar to sendToQueue but no claiming


Digest: mol-deacon-patrol

Patrol cycle 2: all healthy


Digest: mol-deacon-patrol

Patrol cycle 1: inbox 0, all 6 rig monitors healthy, 1 dog idle, no incidents


Digest: mol-deacon-patrol

Patrol 83: All healthy, no incidents


Polecat template not found for non-gastown rigs

When adding a polecat to beads rig, warning shows:
  Warning: polecat template not found at /Users/stevey/gt/beads/mayor/rig/templates/polecat-CLAUDE.md

The template lookup should check the rig's template location, or fall back to a town-level default.


Merge: gt-5af.2

branch: polecat/Doof
target: main
source_issue: gt-5af.2
rig: gastown


CLI: mayor commands (start, attach, stop, status)

Mayor management CLI commands.

## Commands

### gt mayor start
```
gt mayor start [--continue] [--agent AGENT]
```
- --continue: Resume from previous session (check for handoff mail)
- --agent: claude (default) or other agent type

### gt mayor attach
```
gt mayor attach
```
Attach to running Mayor session.

### gt mayor stop
```
gt mayor stop [--grace-period N]
```
Stop Mayor session with optional grace period.

### gt mayor status
```
gt mayor status [--json]
```
Show Mayor running status.

## Session Management
Session name: `gt-mayor`
Working directory: `<town>/mayor/rig/` or `<town>/mayor/`

## Implementation
Similar to session commands but for special Mayor context.

```go
func getMayorPath(townRoot string) string {
    return filepath.Join(townRoot, "mayor")
}

func getMayorSessionName() string {
    return "gt-mayor"
}
```

## New File
internal/cmd/mayor.go

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

## Acceptance Criteria
- [ ] gt mayor start launches Mayor session
- [ ] gt mayor attach works
- [ ] gt mayor stop with grace period
- [ ] gt mayor status shows running state


Digest: mol-deacon-patrol

Patrol 13: 3 rigs healthy


Digest: mol-deacon-patrol

Patrol 2: All healthy, quiet cycle


Digest: mol-deacon-patrol

Patrol #12


E2E Phase 2 observability test

End-to-end test of Phase 2 observability:

Test scenario:
1. Sling work to polecat
2. Watch gt feed for polecat activity
3. Polecat completes, signals done
4. Watch gt feed for MQ events (merge_started, merged)
5. gt status shows queue depth changes
6. Swarm status visible in gt swarm status

All observable without checking .runtime/*.json files.

Success = glass cockpit is lit.

E2E test passed: gt feed shows polecat/bead/MQ events, gt status shows agents/hooks/mail, gt swarm list shows swarms, gt polecat list shows workers. Glass cockpit is lit.


Swarm doesn't track dynamically added workers

When creating a swarm with --worker flags and then adding more polecats later, the swarm status only shows the original workers.

Steps to reproduce:
1. gt swarm create gastown --epic gt-i26df --worker slit --worker rictus --start
2. Add more polecats: gt polecat add gastown capable
3. gt sling gt-xxx gastown/capable
4. gt swarm status gt-i26df -> only shows slit, rictus

Expected: Swarm tracks all workers that are working on swarm tasks.
Actual: Only original workers shown.

Fixed JSON field name (dependencies->dependents) and added Assignee field extraction in loadTasksFromBeads()


Merge: furiosa-1767075886199

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

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


Merge: furiosa-1767084006859

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


Simplify and reorganize molecular chemistry docs

The Gas Town molecular chemistry docs (molecules.md, molecular-chemistry.md, molecule-algebra.md) are too dramatic and verbose. They need a simplification pass to be more reference-manual style.

**Current problems:**
1. Too much metaphor and philosophy, not enough practical reference
2. Start with the chemistry abstraction instead of what users care about (patrols, workflows)
3. Layer cake is presented top-down (formulas → protos → molecules) instead of bottom-up (issues → dependencies → execution)

**Proposed structure (inverted pyramid):**

1. **Start with execution semantics:**
   - Work = issues with dependencies
   - Dependencies control execution (blocks = sequential, no dep = parallel)
   - Agents traverse dependency graphs until blocked
   - Multi-day workflows via compound bonding

2. **Move to molecules:**
   - Molecules are just epics with workflow intent
   - Bonding = creating dependencies between work graphs
   - No protos required for ad-hoc workflows

3. **Then templates (protos/wisps):**
   - Phase metaphor for storage locations
   - pour/wisp/squash/burn operations
   - When to use each phase

4. **Finally formulas (for advanced users):**
   - YAML compile-time composition
   - extends, compose, aspects
   - Only needed for complex reusable patterns

**Style guidelines:**
- Reference manual with quick examples
- Written like agent priming (context they need to execute)
- Less dramatic, more straightforward
- TL;DR at top of each doc

**See also:**
- beads/docs/MOLECULES.md has a simplified version to use as template
- The execution model section explains multi-day traversal clearly


Digest: mol-deacon-patrol

Patrol cycle 7: All healthy.


Session cycling UX: smooth transitions via TUI wrapper

## Problem

Current CLI agent session cycling is painful:
- Shell → CC starts → priming → context loads → ready → work → exit/crash → repeat
- Each cycle is 30-60 seconds of cold boot
- No continuity between shell and agent's inner state
- Raw "session not running, starting..." loop is the baseline

## GGT Advantages (already have)

- Beads: Work state survives session death completely
- Mail: Handoff notes from past-self to future-self
- Prime commands: Structured context reload

## Gap: Transition Mechanics

Ideas to explore when actively using CLI:

1. **In-band cycling** - `/restart` or `/cycle` command, agent handles own restart without dropping to shell

2. **Hot standby** - TUI maintains pre-warmed session in background, switch to already-primed agent

3. **Persistent wrapper** - Bubbletea TUI stays running across session cycles, CC sessions come/go inside it

4. **Session pooling** - Keep 2-3 primed sessions ready, never wait for cold start

## Deferred

Deliberately P4 until we're actively using the simpler CLI and feel the pain firsthand.


Dog agent beads with role_type=dog

## Dog Agent Beads for @group Resolution

Dogs need agent beads with `role_type=dog` for @dogs group resolution to work.

## Background

Dogs are Deacon's reusable helper workers (see patrol-system-design.md):
- Location: `deacon/dogs/<name>/`
- Scope: Town-level, cross-rig
- Managed by: Deacon
- Lifecycle: Reusable (not ephemeral like polecats)

## Deliverables

1. When `gt dog add <name>` creates a dog, also create agent bead:
   ```bash
   bd create --type=agent --title="Dog: <name>" \
     --labels="role_type:dog,rig:town,location:deacon/dogs/<name>"
   ```

2. When `gt dog remove <name>` removes a dog, close the agent bead

3. Ensure `bd list --type=agent --role_type=dog` returns all dogs

## Schema

Dog agent beads should have:
- `type: agent`
- `role_type: dog` (in labels or dedicated field)
- `rig: town` (dogs are town-level, not rig-level)
- `location: deacon/dogs/<name>`

## Dependencies
- gt dog add/remove commands (may not exist yet)
- Agent bead schema supports role_type

## Acceptance
- `bd list --type=agent --role_type=dog` returns all dogs
- Dog beads created/closed with dog lifecycle
- @dogs group resolution works in mail router

Implemented dog agent bead creation/deletion in gt dog add/remove commands. Dog beads have role_type:dog label for @dogs group resolution.


Digest: mol-deacon-patrol

Patrol 213: All nominal


Digest: mol-deacon-patrol

Patrol 8: routine


Digest: mol-deacon-patrol

Patrol 108: All healthy


Digest: mol-deacon-patrol

Patrol 2: All healthy


Merge: rictus-mjw3nj1a

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


Digest: mol-deacon-patrol

Patrol cycle 65: All healthy


Digest: mol-deacon-patrol

Patrol 98: All healthy


Digest: mol-deacon-patrol

Patrol complete: all agents healthy, no orphans, no callbacks


Digest: mol-deacon-patrol

Patrol 126: All healthy


Day 3.1: Wire witness patrol formula to daemon cron

Witness patrol molecule runs on schedule:
- Daemon pokes witness on cron interval
- Witness runs mol-witness-patrol steps
- Results in wisp (ephemeral), squashed later

Parent: gt-hwka3


Digest: mol-deacon-patrol

Patrol 18: all clear


Speed up test suite

Tests are running slow during MQ processing. Investigate and optimize:
- Profile test execution time
- Look for slow tests (network, file I/O, sleeps)
- Consider parallel test execution
- Cache expensive setup where possible


Digest: mol-deacon-patrol

Patrol 7: quiet


Digest: mol-deacon-patrol

Patrol 253 complete: no incidents


gt convoy create: Make --notify a boolean flag with default

--notify requires an argument but the default (mayor/) is sensible. Should work as boolean flag that defaults to mayor/ when no arg given.


Digest: mol-deacon-patrol

Patrol cycle 75: All healthy


Digest: mol-deacon-patrol

Patrol cycle 6: All quiet.


Digest: mol-deacon-patrol

Patrol cycle 26: All healthy, no incidents


Digest: mol-deacon-patrol

Patrol 9: healthy


Refinery and witness rigs should redirect .beads to mayor rig

The refinery's rig clone and witness rig clones should have their .beads directories redirect to the mayor's rig beads (like polecats do).

Current state:
- Polecats have .beads symlinked/redirected to mayor rig beads
- Refinery and witness have their own .beads (or none)

Desired state:
- refinery/rig/.beads -> mayor/rig/.beads (or equivalent redirect)
- witness/rig/.beads -> mayor/rig/.beads (or equivalent redirect)

This ensures all rig agents share the same issue tracking state.


Digest: mol-deacon-patrol

Patrol 212: All nominal


Digest: mol-deacon-patrol

Patrol 17 complete


Digest: mol-deacon-patrol

Patrol 104: All agents healthy, no incidents


Digest: mol-deacon-patrol

Patrol 1: All agents healthy, inbox empty, 1 dog idle


Merge: imperator-1767106079026

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


Digest: mol-deacon-patrol

Patrol cycle 67: All healthy


Digest: mol-deacon-patrol

Patrol 10: quick pass, hitting halfway point


Merge: valkyrie-1767147773208

branch: polecat/valkyrie-1767147773208
target: main
source_issue: valkyrie-1767147773208
rig: gastown


Digest: mol-deacon-patrol

Patrol 1: All agents healthy. Clone divergence (zoey/jack) noted for witnesses.


Digest: mol-deacon-patrol

Patrol 4: quiet


Digest: mol-deacon-patrol

Patrol 154: All healthy


Digest: mol-deacon-patrol

Cycle 200: Final cycle of session, all agents healthy, handoff triggered


Digest: mol-deacon-patrol

Patrol complete: all 3 rigs healthy, no incidents


Digest: mol-deacon-patrol

Patrol 12: quick pass


Witness events in gt feed

Wire witness patrol events to gt feed display.

After 'Witness emits activity events' is done:
- gt feed should show patrol activity
- Useful for debugging polecat issues

Example output:
  19:45 PATROL_COMPLETE gastown/witness (checked 3 polecats)
  19:44 POLECAT_NUDGED gastown/polecats/nux (idle 10m)
  19:40 ESCALATION mayor (polecat stuck)

Implemented: Wire witness patrol events to gt feed display. Added GtEventsSource for parsing .events.jsonl, CombinedSource for merging bd activity and gt events, and symbols/styling for patrol events.


Digest: mol-deacon-patrol

Patrol 81: All agents healthy, 2 epics in progress, 1 idle dog, inbox clear


Digest: mol-deacon-patrol

Patrol cycle 15: All healthy.


gt-refinery-gastown

Refinery - per-rig merge queue processor for gastown.

role_type: refinery
rig: gastown
agent_state: idle
hook_bead: null
role_bead: gt-refinery-role

Migrated to canonical naming: gt-gastown-witness/refinery


Refinery Role Definition

You are the Refinery - merge queue processor for your rig. You process
completed polecat work, merging it to main one branch at a time with
sequential rebasing.

Your mission: Process the merge queue sequentially, rebasing each branch
atop the current baseline before merging.

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

default_molecule: mol-refinery-patrol
capabilities:
  - merge_queue_processing
  - sequential_rebase
  - conflict_resolution
  - verification_gates

## The Engineer Mindset

You are Scotty in the engine room. The merge queue is your warp core.

The Beads Promise: Work is never lost. If you discover ANY problem:
1. Fix it now (preferred if quick), OR
2. File a bead and proceed (tracked for cleanup crew)

There is NO third option. Never "disavow" by noting something exists and moving on.

The Scotty Test: Before proceeding past any failure, ask yourself:
"Would Scotty walk past a warp core leak because it existed before his shift?"

## Propulsion Principle

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

Your work is defined by the mol-refinery-patrol molecule. Execute steps:
- bd ready (find next step)
- bd show <step-id> (see what to do)
- bd close <step-id> (mark complete)

## Sequential Rebase Protocol

WRONG (parallel merge - causes conflicts):
  main then branch-A (old main) + branch-B (old main) = CONFLICTS

RIGHT (sequential rebase):
  main then merge A (rebased on main) then merge B (rebased on main+A)

After every merge, main moves. Next branch MUST rebase on new baseline.

## Verification Gate

The handle-failures step is a verification gate:
- Tests PASSED: Gate satisfied, proceed to merge
- Tests FAILED (branch caused): Abort, notify polecat, skip branch
- Tests FAILED (pre-existing): MUST fix OR file bead - cannot proceed without

## Commands

### Patrol
- gt mol status - Check attached patrol
- bd ready / bd show / bd close - Step management
- bd mol spawn <mol> --wisp - Spawn patrol wisp

### Git Operations
- git fetch origin - Fetch all remote branches
- git branch -r | grep polecat - List polecat branches
- git rebase origin/main - Rebase on current main
- git push origin main - Push merged changes

### Communication
- gt mail inbox - Check for messages
- gt mail send <addr> -s "Subject" -m "Message" - Notify workers


Digest: mol-deacon-patrol

Patrol 5: Quiet


Digest: mol-deacon-patrol

Patrol cycle 2: All healthy, quick pass


Digest: mol-deacon-patrol

Patrol cycle 59: All healthy


Digest: mol-deacon-patrol

Patrol cycle 74: All healthy


Digest: mol-deacon-patrol

Patrol cycle 11: All healthy


Digest: mol-deacon-patrol

Patrol complete: gastown healthy, beads dormant


Digest: mol-deacon-patrol

Patrol 27: all polecats working, jack session started


Digest: mol-deacon-patrol

Patrol 6: all clear


Digest: mol-deacon-patrol

Patrol cycle 9: All healthy


gt crew remove: Does not close agent bead

When running 'gt crew remove <name>', the command removes the crew workspace directory but does not close the associated agent bead (gt-<rig>-crew-<name>).

This leaves orphaned agent beads in the system after crew removal.

The remove command should close the agent bead with a reason like 'Crew workspace removed'.

Fixed in commit 5260a9c - crew remove now closes agent bead


Digest: mol-deacon-patrol

Patrol 7: 3 rigs healthy


Digest: mol-deacon-patrol

Patrol cycle 14: All healthy - dag polecat started


mol-swarm-cleanup: Post-swarm debris cleanup molecule

After a 20+ worker swarm completed, found significant beads debris:
- 18 stale messages (work assignments, lifecycle requests, swarm instructions)
- 3 completed issues still open/in_progress
- Test messages accumulated

Need: Document a post-swarm checklist or create gt swarm cleanup command that:
1. Closes stale work assignment messages
2. Reviews in_progress issues for completion
3. Closes orphaned lifecycle messages
4. Optionally archives test messages


Digest: mol-deacon-patrol

Patrol 6: all healthy


Merge: capable-1767074974673

branch: polecat/capable-1767074974673
target: main
source_issue: capable-1767074974673
rig: gastown


Digest: mol-deacon-patrol

Cycle 19


Digest: mol-deacon-patrol

Patrol cycle 8: all healthy


Digest: mol-deacon-patrol

Patrol 5: healthy


Implement Boot: daemon entry point dog for Deacon triage

Boot is a dog (Deacon helper) that the daemon pokes instead of the Deacon directly.

Purpose: Centralize 'when to wake Deacon' decision in an agent that can reason about it.

Lifecycle:
- Daemon tick spawns Boot (fresh each time)
- Boot runs triage molecule:
  - Observe (wisps, mail, git state, tmux panes)
  - Decide (start/wake/nudge/interrupt/nothing)
  - Act
  - Clean inbox (discard stale handoffs)
  - Handoff (or exit in degraded mode)

Location: ~/gt/deacon/dogs/boot/
Session: gt-deacon-boot
Created by: bd doctor

Needs:
- Boot formula (mol-boot-triage.toml)
- gt dog prime boot command
- Daemon change to poke Boot instead of Deacon
- Degraded mode support (GT_DEGRADED=true)

See: gastown/mayor/rig/docs/operational-state.md

Implemented and merged in commit 2112804


Merge: bix-mjufugoo

branch: polecat/bix-mjufugoo
target: main
source_issue: bix-mjufugoo
rig: gastown


Day 1.4c: Create polecat agent bead lifecycle

Define ephemeral polecat agent bead lifecycle.

Polecats need agent beads for ZFC compliance (self-report state).

Lifecycle:
1. On spawn: Create agent bead
   ```yaml
   id: gt-polecat-<rig>-<name>
   type: agent
   role_type: polecat
   rig: <rig>
   state: spawning
   hook_bead: <assigned-issue>
   ```

2. On Claude ready: Update state=working

3. On completion: Update state=done

4. On nuke: Delete agent bead

Commands needed:
- gt polecat spawn creates agent bead
- gt polecat nuke deletes agent bead
- Polecat updates own state via bd agent state

Note: This ensures Witness can read polecat state from beads instead of tmux scraping.

Implemented polecat agent bead lifecycle: spawn creates bead with state=spawning, nuke deletes bead. State updates (spawning→working→done) require bd agent state command (beads CLI enhancement).


Multiple merge/landing models documented without clarification

Architecture describes three different merge models:

1. Refinery-only model (traditional)
2. Direct landing model (Mayor bypass)
3. Swarm integration branch model (internal/swarm)

These appear to conflict. Documentation should clarify:
- Which model is canonical?
- When to use which model?
- Or are some deprecated?

This is confusing for users trying to understand the system.


Digest: mol-deacon-patrol

Patrol 158 complete


HOP: Entity chain tracking for agents

Track work history per-entity (CV chains). See ~/ai/stevey-gastown/hop/decisions/002-entity-chains.md for design. Post-v0.1 work.


Digest: mol-deacon-patrol

Patrol cycle 6: All healthy


Clean up stale children on deacon handoff bead

The deacon handoff bead hq-8r8 has 7 stale children (hq-8r8.1 through hq-8r8.7) from a previous patrol that got incorrectly parented. These should be cleaned up.

The handoff bead should only contain the attached_molecule reference, not instantiated steps.


Witness patrol: stale MR queue detection needs state tracking

The mol-witness-patrol check-refinery step says 'if queue is non-empty for >30 min, send nudge' but doesn't explain how to track when the queue first became non-empty.

## Problem
The Witness needs to persist:
- When MR queue first became non-empty
- Previous queue state for comparison

Without this, the Witness can't detect stale queues.

## Solution
Add to witness handoff bead:
- mr_queue_nonempty_since: timestamp
- Update in save-state step
- Check in check-refinery step


Recover orphaned commits from polecat work

73 orphaned commits found via `gt orphans`. These are polecat work that was done
but never merged to main - either due to merge conflicts, refinery issues, or
premature session kills.

**Recovery Process:**
1. Run `gt orphans` to get full list with SHAs
2. For each commit, categorize:
   - Already merged (different SHA but same work) → skip
   - Needs cherry-pick → attempt cherry-pick, resolve conflicts
   - Obsolete (superseded by other work) → skip
3. Cherry-pick valuable commits in dependency order
4. Push recovered work to main

**Known valuable orphans (sample):**
- 77f9da07 convoy CLI (RECOVERED)
- 8d2f5ca8 Dog infrastructure (gt-0x5og.2)
- 5c3f1795 Swarm beads backing (gt-kc7yj.1)
- 341414df Wire MQ lifecycle events to gt feed (gt-lak31)
- Many more...

**Root cause to fix:**
- Witness closing tasks before verifying merge success
- Refinery not handling conflicts gracefully
- Need "Landing Rule" enforcement

Triage complete: 74 orphans analyzed. 69 already merged (different SHAs). 5 truly orphaned but obsolete/superseded. No recovery action needed.


Glass Cockpit: See WTF is happening

Glass cockpit - see what's happening across the system.

Phase 1 got the engine running. Phase 2 makes it observable.

**Pillars:**
- Pillar 4: Swarm-in-Beads (gt-kc7yj - already exists)
- Pillar 5: MQ Observability
- Pillar 6: Witness Observability
- Pillar 7: Unified Dashboard

**Success criteria:**
1. gt status shows per-rig queue depth and agent health
2. gt feed shows MQ and swarm lifecycle events
3. gt dashboard provides live system visibility
4. No .runtime/*.json files for observable state
5. Swarms fully tracked in beads

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

All dependencies complete: gt-kc7yj (Swarm-in-Beads), gt-lfi2d (.runtime cleanup), gt-qd7ri (E2E test). Glass Cockpit observability achieved.


Digest: mol-deacon-patrol

Patrol cycle 69: All healthy


Batch wisp squashing in Deacon maintenance

Add wisp squashing to Deacon's maintenance duties:
- Patrol plugin to find orphaned/completed wisps across all rigs
- Squash completed patrol wisps to digests
- Burn abandoned wisps that have no audit value
- Part of the hygiene/cleanup system

Also: Witness polecat shutdown should spawn its own short wisp for the cleanup protocol.


gt status: Show agent hook_bead (current work) in status output

attached_args: Implement the hook_bead display in gt status. The agent bead lifecycle is complete - just need to read hook_bead and display it.

## Current State

gt status shows agents with their agent_state from beads:
```
   crew/max       ✓ running [running]
```

## Enhancement

Show what each agent is working on (hook_bead field from agent beads):
```
   crew/max       ✓ running [running] → gt-abc (Fix auth bug)
   crew/joe       ✓ running [running] → gt-xyz (Add tests)
   refinery       ✓ running → refinery Handoff
```

This gives the overseer a quick view of:
1. Who is running
2. What each agent is working on
3. Progress at a glance

## Implementation

In status.go, when displaying agents:
1. Look up agent bead by ID (e.g., gt-crew-gastown-max)
2. Parse hook_bead from description
3. If hook_bead set, fetch its title for display
4. Show as: agent_state → hook_bead (title truncated)

## Related

The agent bead lifecycle is now complete:
- prime.go creates agent beads
- sling.go sets hook_bead
- done.go clears hook_bead and sets final state


Digest: mol-deacon-patrol

Patrol 13: all clear


Digest: mol-deacon-patrol

Patrol 4: 3 rigs healthy


gt swarm dispatch command not working

The "gt swarm dispatch" command shown in help does not work as expected.

**Observed:**
```
$ gt swarm dispatch bd-784c
[prints help text instead of dispatching]
```

**Expected:**
Should dispatch the next ready task from the epic to an available worker.

**Workaround:**
Had to manually use "gt sling <issue> <polecat>" for each task dispatch.

**Impact:**
- Manual task dispatch defeats swarm automation
- Coordinator has to track which tasks are ready and which polecats are free

**Suggestion:**
Implement or fix "gt swarm dispatch" to:
1. Find next unassigned task in epic
2. Find idle polecat in swarm
3. Sling task to polecat automatically

(Moved from bd-kp9y)

Implemented gt swarm dispatch command - now finds ready tasks and idle polecats, uses gt sling to dispatch


Remove gt context --usage estimation

The external context estimation approach doesn't work:
- tmux scrollback trick breaks with --cycle
- Can't see actual context usage from outside
- Only the agent knows its internal state

Remove or deprecate:
- gt context --usage flag
- Any external context monitoring logic

Document why in comments: 'Context management is agent-initiated, not externally monitored.
See self-check guidance in role templates.'

This is P3 because it's cleanup - the feature just doesn't work, not actively harmful.


Digest: mol-deacon-patrol

Patrol 160 complete


Filter agent session molecule noise from activity feed

Agent session molecules (gt-crew-gastown-joe, gt-crew-gastown-max, etc.) update frequently
and create noisy entries like:

  [10:22:37] → gt-crew-gastown-joe updated · gt-crew-gastown-joe

These are not useful in the activity feed. Options:
1. Filter them out entirely
2. Collapse repeated updates into single entries
3. Show them in a separate "agent status" section

Part of epic gt-u7dxq

Implemented filter for agent session molecule updates in the activity feed TUI. Agent session updates are now filtered from the event feed while still updating the agent tree for status visibility.


Digest: mol-deacon-patrol

Patrol cycle 11: All healthy - Witness/Refinery running, no pending spawns, no convoys, no gates, no orphans, inbox clean


Digest: mol-deacon-patrol

Patrol 45: All healthy


Merge: slit-1767073379145

attached_args: Code review

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

Already merged to main per refinery confirmation (commit 196c3bbf)


Digest: mol-deacon-patrol

Patrol cycle 7: all healthy


Digest: mol-deacon-patrol

Patrol cycle 19: All agents healthy


Digest: mol-deacon-patrol

Cycle 185: Nominal


Digest: mol-deacon-patrol

Patrol cycle 15: All healthy


Merge: slit-mjtj9dc8

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


Digest: mol-deacon-patrol

Cycle 14


Digest: mol-deacon-patrol

Patrol 5: all clear


Merge: slit-mjtj9dc8


Digest: mol-deacon-patrol

P15: stable


Polecat spawn: CLAUDE.md template lookup path is wrong

Template lookup uses rig.Path/templates/ but templates are in mayor/rig/templates/

In internal/polecat/manager.go installCLAUDETemplate():
  templatePath := filepath.Join(m.rig.Path, "templates", "polecat-CLAUDE.md")
  // Looks for: /Users/stevey/gt/gastown/templates/polecat-CLAUDE.md
  // But templates are at: /Users/stevey/gt/gastown/mayor/rig/templates/

This causes silent failure (template not found is OK) and polecats inherit the wrong CLAUDE.md from the git worktree.

Fix options:
1. Copy templates to rig root during rig init
2. Change lookup to use mayor/rig/templates/
3. Embed templates in binary


gt feed --follow: Town-level activity stream

Town-native command for aggregated activity feed.

Wraps bd activity --town with Gas Town conveniences:
- gt feed --follow         # Stream all rig activity
- gt feed --rig gastown    # Filter to specific rig
- gt feed --convoy hq-xxx  # Filter to convoy's tracked issues

Essential for Mayor/Deacon visibility into cross-rig work.

Depends on: bd-dx6e (bd activity --town)
Related: hq-7h8jx (Convoy System epic in town beads)

Implemented --town flag and --convoy placeholder for gt feed


Digest: mol-deacon-patrol

Patrol cycle 4: All agents healthy


Digest: mol-deacon-patrol

Patrol 10: 17 sessions


Digest: mol-deacon-patrol

Patrol 33: all quiet


Digest: mol-deacon-patrol

Patrol 9: 3 rigs healthy


Digest: mol-deacon-patrol

Cycle 10: quiet


Digest: mol-deacon-patrol

Patrol #11


Digest: mol-deacon-patrol

Patrol cycle 16: All healthy


Merge: rictus-1767081110235

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


Digest: mol-deacon-patrol

Patrol 9: quick pass


Exponential backoff for idle patrol agents

## Problem

Patrol agents (Refinery, Witness, Deacon) currently have no backoff when their queue is empty. They either:
- Loop immediately (wasting cycles)
- Exit and wait for 10-minute daemon respawn (too slow to respond)

## Solution: Feed-Driven Backoff

### The Pattern (from PRIMING.md)

> "Backoff isn't about polling less - it's about **waiting for signals with a timeout**."

Agents subscribe to `bd activity --follow` and wake on any beads mutation. The timeout increases exponentially during idle periods.

### Data Flow

```
bd/gt mutations → .events.jsonl → feed curator → .feed.jsonl
                                                      ↓
                    patrol agent: gt mol await-signal --backoff-*
                                                      ↓
                              signal → wake, reset idle_cycles
                              timeout → increment idle_cycles, sleep longer
```

### Backoff Formula

```
timeout = min(base × multiplier^idle_cycles, max)
```

| Idle Cycles | Timeout |
|-------------|---------|
| 0 | 30s |
| 1 | 1m |
| 2 | 2m |
| 3 | 4m |
| 4+ | 5m (capped) |

### Agent State Storage

Operational state stored as labels on agent beads (labels-as-cache pattern):
- `idle:3` - consecutive idle patrol cycles
- `backoff:2m` - current backoff interval (derived)
- `last_activity:2025-12-31T10:00:00Z` - timestamp

### Implementation Layers

**Layer 1: gt agent state command**
```bash
gt agent state <agent-bead>                    # Get labels
gt agent state <agent-bead> --set idle=0       # Set label
gt agent state <agent-bead> --incr idle        # Increment
```

**Layer 2: Fix await-signal iteration tracking**
- Read `idle:N` label from agent bead
- Calculate effective timeout using BackoffConfig
- On timeout: increment label, return "timeout"
- On signal: return "signal" (agent resets)

**Layer 3: Patrol formula integration**
Update burn-or-loop step:
```bash
# If work found
gt agent state $AGENT_BEAD --set idle=0

# If no work
gt mol await-signal --agent-bead $AGENT_BEAD   --backoff-base 30s --backoff-mult 2 --backoff-max 5m

# After 10 consecutive max-timeout cycles, exit for fresh session
```

**Layer 4: Feed signal sources**
Ensure these emit events:
- gt sling → TypeSling
- bd create/update/close → BeadMutation
- gt mail send → TypeMail

### ZFC Compliance

| Component | Role | ZFC |
|-----------|------|-----|
| Feed curator | Aggregates events | ✅ Transport |
| await-signal | Waits with timeout | ✅ Transport |
| Agent bead labels | Stores idle_cycles | ✅ Agent-written |
| Backoff decision | Agent decides | ✅ Agent decides |

Go code provides mechanics. **Agent decides** parameters, reset, and exit.

### Existing Infrastructure

- Feed Curator: internal/feed/curator.go ✅
- BackoffConfig: internal/beads/molecule.go ✅
- await-signal cmd: internal/cmd/molecule_await_signal.go (needs fix)
- Agent Beads: internal/beads/beads.go ✅
- Labels pattern: docs/operational-state.md ✅

### Exit Strategy

After N consecutive max-interval cycles (e.g., 10 × 5m = 50 minutes idle):
- Agent exits cleanly
- Daemon respawns fresh session
- Fresh session starts with idle:0


Digest: mol-deacon-patrol

Patrol 130: All healthy


Digest: mol-deacon-patrol

Patrol cycle 7: All quiet.


Deacon patrol molecules stored in wrong beads location

outputDeaconPatrolContext in prime.go hardcodes 'gastown/mayor/rig' (line 691) to find patrol molecules. But Deacon is a town-level role, not a rig role. Deacon molecules should be in town root beads (~/gt/.beads/) not rig beads. This also affects gt mol status which uses findLocalBeadsDir() - from ~/gt/deacon/ it won't find the right beads location.


check-refinery

Ensure the refinery is alive and processing merge requests.

Needs: inbox-check


Atomic gt done: all-or-nothing work submission

gt done performs multiple operations that can partially fail.

## Current Flow (non-atomic)
1. Create MR bead ← can fail
2. Send POLECAT_DONE mail ← can fail
3. Update agent bead state ← can fail
4. Report cleanup status ← can fail

If session dies mid-execution, state is inconsistent.

## Fix Options

### Option A: Retry on restart
- Write intent file before starting
- On polecat restart, check for incomplete gt done
- Resume/retry from where it left off

### Option B: Single-write submission
- Create a single 'submission' bead that contains all info
- Witness unpacks it into MR bead + cleanup wisp
- Polecat only needs one successful write

### Option C: Idempotent operations
- Each step checks if already done before doing
- Safe to re-run gt done multiple times

Recommend Option C for simplicity.

Implemented Option C (idempotent operations) for MR bead creation. Added FindMRForBranch to check for existing MR before creating.


Merge: cheedo-1767088553821

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


Digest: mol-deacon-patrol

Patrol 124: All healthy, 2 new polecats


Digest: mol-deacon-patrol

Patrol 17


Digest: mol-deacon-patrol

Patrol cycle 76: All healthy


ZFC #5: Move merge/conflict decisions from Go to Refinery agent

**ZFC Violation:** internal/refinery/manager.go:389-517

Go code currently makes engineering decisions in ProcessMR():
- Detect conflicts via string matching
- Decide to abort merge
- Decide to roll back on test failure
- Decide retry strategy

**Current anti-pattern:**
```go
if strings.Contains(errStr, "CONFLICT") {
    result.Conflict = true
    _ = m.gitRun("merge", "--abort")
    // Go decides what to do
}
```

**ZFC-compliant solution:**
Refinery AGENT runs the merge loop:
- Agent attempts merge
- Agent detects conflict and decides: retry, notify polecat, escalate
- Agent runs tests and decides: proceed, rollback, retry
- Go provides git operations, agent makes decisions

**Relates to:** Day 3.4 (Refinery processes MERGE_READY mail) but needs explicit agent decision-making

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

Implemented ZFC #5: ProcessMR deprecated, agent runs git commands directly and makes all merge/conflict decisions. Role template updated with ZFC compliance section.


Merge: dementus-1767073385126

attached_args: Code review this merge request

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

REJECTED: The swarm fix (gt-qd9p0) is already on main (commit 10e79789). This branch is stale and would revert important changes if merged (hookIssue support from 81b250ee, overseer validation from 32a623f8). No merge needed - work already complete.


Digest: mol-deacon-patrol

Patrol 241 complete: 3 witnesses, 3 refineries healthy; 6 polecats active; 1 dog idle; no orphans; no incidents


Merge: nux-1767084010093

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


Add gt mail claim command for queue message claiming

Add claim subcommand to internal/cmd/mail.go.

SYNTAX:
gt mail claim <queue-name>

BEHAVIOR:
1. List unclaimed messages in queue (claimed_by empty)
2. Pick oldest unclaimed message
3. Set claimed_by to caller identity
4. Set claimed_at to now
5. Print claimed message details

ELIGIBILITY CHECK:
- Load queue config from messaging.json
- Check if caller matches any pattern in workers list
- Reject if not eligible

FILE: internal/cmd/mail.go
ADD: claimCmd as subcommand of mailCmd

TESTS: Add TestMailClaim in mail_test.go or cmd_test.go

Implemented gt mail claim command with eligibility checking and tests


Beads witness sends HEALTH_OK to mayor instead of deacon

The beads/witness is responding to deacon health checks by sending to 'mayor/deacon' or 'mayor/' instead of 'deacon/'.

Current behavior:
gt mail send mayor/deacon -s "HEALTH_OK" ...

Expected behavior:
gt mail send deacon/ -s "HEALTH_OK" ...

The gastown witness was fixed and now correctly sends to deacon/. The beads witness needs the same fix.

Added Health Check Protocol section to witness template with correct deacon/ address


Add INSTALLING.md with full setup guide

README Quick Start is too brief. Create docs/INSTALLING.md with:
1. All prerequisites with install commands
2. Step-by-step install for macOS and Linux
3. Verification steps (gt doctor, gt status)
4. Troubleshooting common issues
5. Minimal mode vs full-stack mode setup

Created docs/INSTALLING.md with full setup guide


Refinery Patrol

Merge queue processor patrol loop with verification gates.


Hardcoded session ID prefixes and paths

Multiple hardcoded values throughout code:
- internal/mail/router.go: 'gt-mayor', 'gt-' session prefixes
- internal/lock/lock.go: '.runtime', 'agent.lock' paths
- Session ID generation uses string literals

Should move to:
- constants package for prefixes
- config for customizable paths

Low priority but improves maintainability.


Design: Polecat lifecycle and patrol coordination

## Context

This design captures thinking from a deep session about the Gas Town propulsion system - how Deacon, Witness, Refinery, and Polecats coordinate to move work smoothly through the system.

## Core Insight: Session-Per-Step Model

Polecats do NOT complete complex molecules end-to-end. Instead:
- One polecat SESSION per molecule STEP
- Same sandbox (branch/worktree) persists across sessions
- Each step: spawn → work → close bead → recycle session
- Final step: spawn → work → close bead → signal complete → merge → nuke sandbox

## Two Cleanup Stages

| Stage | Trigger | Kills | Survives |
|-------|---------|-------|----------|
| Step cleanup | Step bead closed | Session | Branch, worktree, molecule |
| Molecule cleanup | Merged | Session, branch, worktree | Digest |

## Per-Rig Polecat Channel

Need a mailing list/queue per rig for session-lifecycle requests:
- "Recycle me" (from polecat)
- "Recycle worker X" (from witness/mayor)
- "Spawn for step Y" (from anyone)

First-come-first-served by patrolling agents. Anyone on patrol (Witness, Refinery, Crew, Mayor) can service requests.

## GUPP + Pinned Work = Completion

As long as:
1. Work is pinned to polecat identity (e.g., gastown/furiosa)
2. Sandbox persists (branch + worktree)
3. Someone keeps spawning polecat when it dies

→ The molecule WILL get finished. GUPP ensures wake-and-work.

## Daemon → Deacon Heartbeat

The daemon pings the deacon, keeping the cycle alive. Deacon peeks into rig-wide channels during patrol and can service lifecycle requests.

## Open Design Questions

### Q1: Spoon-Feeding Bin-Packing
Two dimensions of granularity trade-offs:
- How many logical steps per physical molecule step?
- How many molecule steps per polecat session?

Too few steps → context exhaustion, forgetting
Too many steps → overhead, fragmentation

Needs: Analysis of optimal granularity based on step complexity.

### Q2: Mechanical vs Agent-Driven Recycling
Caution from deacon murder spree bug: mechanical detection of "stuck" workers is fragile.

Prefer: Explicit "recycle me" requests serviced by patrol agents.

Question: When is mechanical intervention appropriate?

### Q3: Channel Implementation
Options:
- Mail-based (gt mail to rig/polecats)
- Beads-based (special issue type)
- State file (rig/polecat-queue.json)

Mail seems most consistent with Gas Town patterns.

### Q4: Who Spawns Next Step?
Current: gt sling spawns fresh polecat
Needed: Mechanism for "continue molecule on existing sandbox"

Maybe: gt sling --continue or witness detects pending step.

## Related Issues

- gt-dtw9u: Witness monitoring (enhance survey-workers)
- gt-qpwv4: Completion detection (check ready branches)
- gt-6qyt1: Refinery queue (process MERGE_READY)
- gt-budeb: Auto-nuke (handle MERGED signal)
- gt-5j3ia: Swarm aggregation (batch completion)
- gt-1dbcp: Polecat auto-start (SessionStart hook issue)

## Design Principles (from HOP/MEOW context)

1. **Discovery over tracking** - observe reality each cycle
2. **Mail as coordination primitive** - agents signal via mail
3. **ZFC** - Claude makes judgment calls, no hardcoded thresholds
4. **Redundant monitoring** - overlapping observation is resilience
5. **Wisps are ephemeral** - patrol molecules flow like water

## Next Steps

1. Finalize channel design (mail-based queue)
2. Enhance witness patrol formula with completion detection
3. Enhance refinery patrol with MERGED signaling
4. Implement step-level recycling
5. Design spoon-feeding granularity guidelines


ZFC #4: Replace daemon identity parsing with agent self-registration

**ZFC Violation:** internal/daemon/lifecycle.go:209-309

The daemon has embedded switch statements that parse agent identity strings to determine:
- Session names
- Working directories
- Which agents need pre-sync
- Restart commands

**Current anti-pattern:**
```go
if strings.HasSuffix(identity, "-refinery") {
    needsPreSync = true
    workDir = filepath.Join(...)
}
```

**ZFC-compliant solution:**
Agent types self-register via role beads:
- Role bead contains: working_dir, session_name_pattern, needs_sync, restart_command
- Daemon reads role bead to get lifecycle config
- No identity string parsing in Go

**Depends on:** Day 1.5 (role beads exist)

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

Implemented role-based lifecycle configuration - daemon now uses role beads for session patterns, work directories, pre-sync, and start commands


gt mol attach: Auto-detect agent from cwd when single arg provided

## Current Behavior

gt mol attach requires 2 args:
  gt mol attach <agent-bead-id> <molecule-id>

## Expected Behavior

When called with 1 arg from an agent working directory:
  gt mol attach <molecule-id>

Should auto-detect the agent from cwd (same detection used by gt mail, bd, etc.)
and attach the molecule to that agent hook.

## Example

From ~/gt/gastown/mayor/rig:
  gt mol attach gt-y14l7
  -> detects mayor role
  -> attaches gt-y14l7 to gt-mayor hook

## Implementation

1. Check arg count
2. If 1 arg, call role detection from cwd
3. Resolve agent bead ID from role (gt-mayor, gt-witness-gastown, etc.)
4. Proceed with attachment

This makes the common case (attaching work to yourself) ergonomic.

Implemented: gt mol attach now accepts 1 arg and auto-detects agent bead ID from cwd


Merge: cheedo-mjtmlvge

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


Digest: mol-deacon-patrol

Patrol 20: 3 rigs healthy


Digest: mol-deacon-patrol

Patrol 20: All healthy, cycling session


gt mr: Add alias for merge request operations

Agent guessed `gt mr register <branch>` to submit a branch to the merge queue. The actual command is `gt mq submit`.

**Suggestion**: Add `gt mr` as an alias or subcommand for merge request workflows:
- `gt mr submit` → `gt mq submit`
- `gt mr status` → `gt mq status`
- `gt mr list` → `gt mq list`

**Why**: 'MR' (merge request) is the conceptual noun; 'mq' (merge queue) is the implementation detail. Agents and humans think in terms of 'I have a merge request' not 'I need to interact with the queue'.

**Alternative**: Just document `gt mq` more prominently, but aliases cost little and reduce friction.

Filed by: gastown/polecats/nux (agent UX feedback)


Digest: mol-deacon-patrol

Patrol cycle 11: all healthy


Digest: mol-deacon-patrol

Patrol cycle 1: all healthy, 3 rigs, 6 agents, no incidents


Digest: mol-deacon-patrol

Patrol 6: All healthy.


Boot needs CLAUDE.md and directory setup

Boot spawns in ~/gt/deacon but:
1. No ~/gt/deacon/dogs/boot/ directory exists
2. Boot reads Deacon's CLAUDE.md (wrong role context)
3. spawnTmux() doesn't send initial triage prompt

Fix:
- Create ~/gt/deacon/dogs/boot/CLAUDE.md with Boot role instructions
- Update EnsureDir() to create directory on spawn
- Consider sending 'gt boot triage' as initial prompt

Boot should know it's a fresh-each-tick watchdog that:
- Observes Deacon state
- Decides: start/wake/nudge/nothing
- Cleans stale inbox
- Exits (never handoffs)

Implemented: Created ~/gt/deacon/dogs/boot/CLAUDE.md with Boot role context, updated spawnTmux() to use bootDir instead of deaconDir, added 'gt boot triage' as initial prompt.


Digest: mol-deacon-patrol

Patrol 106: All healthy


Digest: mol-deacon-patrol

Patrol 2: All healthy, routine


Digest: mol-deacon-patrol

Patrol #5: All systems nominal


## @group Dynamic Resolution in Mail Router

Wire agent bead queries into mail router for @group addresses.

## Updated Approach (post agent-as-bead + Dogs)

Agent discovery uses bead queries:

```bash
bd list --type=agent --rig=gastown         # All agents in rig
bd list --type=agent --role_type=witness   # All witnesses
bd list --type=agent --role_type=dog       # All dogs
```

## Supported Patterns

| Pattern | Resolution | Scope |
|---------|------------|-------|
| `@rig/gastown` | `--rig=gastown` | All gastown agents |
| `@town` | `--rig=""` (no filter) | All town-level agents |
| `@witnesses` | `--role_type=witness` | All witnesses across rigs |
| `@crew/gastown` | `--role_type=crew --rig=gastown` | Gastown crew |
| `@dogs` | `--role_type=dog` | All Deacon dogs |
| `@overseer` | Special case (not bead query) | Human operator |

## Deliverables

1. Parse @group syntax in router
2. Resolve via `bd list --type=agent` queries
3. Fan-out at send time (N copies, one per recipient)
4. Special handling for `@overseer` (single recipient, uses overseer.json)

## @overseer Special Case

The overseer is the human operator - NOT an agent bead. Resolution:
- Load `mayor/overseer.json`
- Use `overseer/` as recipient address
- No bead query needed

## Dependencies
- Agent bead schema (gt-ikyo1) ✅ closed
- Dog agent beads need role_type=dog (new prereq)

## Acceptance
- @rig/gastown sends to all gastown agents
- @dogs sends to all Deacon dogs
- @overseer sends to human operator
- Each recipient gets own message copy

Beads dependency: bd-jsk7 (Agent beads: structured labels for filtering)

Implemented @group dynamic resolution in mail router with fan-out support


Add agent abstraction layer to support non-Claude agents

Currently Gas Town hardcodes 'claude --dangerously-skip-permissions' throughout the codebase for spawning agents. We should add an abstraction layer to support other AI agents (e.g., Gemini CLI, OpenAI agents, local models).

Locations that spawn Claude:
- internal/cmd/mayor.go:131
- internal/cmd/deacon.go:150
- internal/cmd/witness.go:280
- internal/cmd/crew.go (multiple locations)
- internal/cmd/up.go:190, 229
- internal/session/manager.go:146
- internal/refinery/manager.go:207

Suggested approach:
1. Create an agent package with an interface
2. Add configuration for agent type in town/rig config
3. Replace hardcoded claude commands with agent.Spawn() calls
4. Support agents: claude, gemini, openai, local (ollama, etc.)


Merge: capable-1767074974673

branch: polecat/capable-1767074974673
target: main
source_issue: capable-1767074974673
rig: gastown


attached_args: Refactor runStart into focused helper functions

Break up the 126-line runStart function in start.go.

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

## Current structure (lines 129-255)
runStart does:
1. Crew path detection
2. Workspace verification
3. Mayor session start
4. Deacon session start
5. Optional rig agent startup
6. Configured crew auto-start

## Refactoring plan
Extract these helpers:
```go
func startMayorSession(townRoot string, verbose bool) error
func startDeaconSession(townRoot string) error
func startRigAgents(townRoot string, rigs []string) error
func startConfiguredCrew(townRoot string, config *TownConfig) error
```

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


Digest: mol-deacon-patrol

Patrol 19: quick pass


Merge: rictus-1766959789036

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


queue: shared storage work queues

## queue: Shared Storage Work Queues

Work queue with shared storage (single copy, first-to-claim).

## Pattern Clarification

**Queue is a MAILBOX pattern** (pull-based):
- Workers poll shared queue
- First to claim gets the work
- Worker decides when to check

**This is DIFFERENT from Dog dispatch** (push-based):
- `gt sling <work> deacon/dogs` pushes to hook
- GUPP fires immediately
- Deacon decides when to assign

| Pattern | Mechanism | Initiative |
|---------|-----------|------------|
| `queue:` | Poll mailbox, claim | Worker pulls |
| Dog sling | Hook assignment | Deacon pushes |

## Use Cases for queue:

1. **Batch cleanup tasks** - Multiple agents can help, order does not matter
2. **Overflow work** - When primary handler is busy
3. **Opportunistic tasks** - Agents check between other work

## Deliverables

1. Parse queue:name syntax in router
2. Shared storage model:
   - Single message copy (NOT fan-out)
   - Stored in queue-specific location
   - Multiple agents can see it
3. Queue configuration in ~/gt/config/queues.json
4. Queue inbox command: gt mail queue <name>
5. Claim semantics: `gt mail claim <msg-id>` marks as claimed

## Key Difference from list:
- list: creates N copies (N obligations)
- queue: creates 1 copy (1 obligation, first-to-claim)

## Dependencies
- Config directory (gt-i6jvc) ✅ closed

## Acceptance
- queue:cleanup creates single message
- Multiple agents can view queue
- Claim marks message as taken
- Message invisible to others after claim

Implemented queue:name syntax, shared storage, gt mail queue, and gt mail claim


Digest: mol-deacon-patrol

Patrol 216: All nominal


Merge: furiosa-mjvtknih

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


Add witness plugin hook support

Implement plugin directories for witness patrol.

Structure:
  <rig>/plugins/witness/
  ├── pre-inspection/
  │   └── stale-branch-check/
  │       └── CLAUDE.md
  └── post-action/
      └── mq-health/
          └── CLAUDE.md

run-plugins step scans these directories and bonds mol-plugin-runner for each.


Analysis: Beads database size and hygiene strategy

Audit beads database size and plan medium-term hygiene.

## Questions
1. How many issues total (including tombstones)?
2. Size of issues.jsonl?
3. Growth rate per day/week?
4. What percentage are tombstones?

## Hygiene Topics
- Compaction: squash tombstones periodically
- Archival: move old closed issues to archive file
- Pruning: delete truly stale items (test beads, old MRs)
- Sync efficiency: large JSONL = slow sync

## Action Items
- [ ] Count total issues by status
- [ ] Count tombstones
- [ ] Measure file sizes
- [ ] Propose hygiene schedule


MCP beads tools fail from polecat directories

The beads MCP plugin (plugin:beads:beads) fails to find issues when invoked from polecat directories.

## Observed
- Polecat in /gt/gastown/polecats/dementus
- MCP tool: plugin:beads:beads - show (issue_id: 'gt-th7')
- Error: 'bd command failed: Error: no issue found matching gt-th7'

## Expected
MCP tools should work the same as running bd directly.

## Note
This may be related to gt-tmm (beads sync issue) rather than an MCP-specific bug. The MCP tool uses bd under the hood, and bd can't find the issue because the polecat's beads database is stale.

Fixed in beads-mcp plugin (bd-7t9a): Added _resolve_beads_redirect() function to follow .beads/redirect files during workspace auto-detection. Tests added and passing.


Digest: mol-deacon-patrol

Patrol 76: Routine


Merge: keeper-1767074342207

branch: polecat/keeper-1767074342207
target: main
source_issue: keeper-1767074342207
rig: gastown

Branch polecat/keeper-1767074342207 does not exist - polecat decommissioned without work to merge


Digest: mol-deacon-patrol

Patrol cycle 9: All 6 agents healthy


Build rig/worker tree view component

Bubbletea component showing hierarchical rig list with workers. Each rig expandable to show workers. Each worker shows: status indicator, current molecule title, step progress (X/Y), time since last activity.


Zombie session detection for refinery/witness

A Claude session can crash or hang while still appearing as 'running' in tmux. The current IsRunning checks only verify tmux session exists, not that Claude is actually processing.

## Problem
- Refinery session might be hung (Claude crashed, infinite loop, etc.)
- tmux HasSession returns true, so auto-start doesn't trigger
- MRs pile up with no processing

## Solution Options
1. **Activity-based detection**: Check last output timestamp in tmux
2. **Heartbeat file**: Agents write timestamp to file, check staleness
3. **Prompt detection**: Look for Claude '>' prompt indicating idle/stuck

## Related
- gt-bjft (spawn auto-start) assumes IsRunning means healthy
- Witness patrol assumes running refinery is processing


Merge: dag-mjtm8k85

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


Digest: mol-deacon-patrol

Patrol 3: All healthy, routine


Merge: gt-h5n.5

branch: polecat/Scabrous
target: main
source_issue: gt-h5n.5
rig: gastown


Merge: nux-mjui76op

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


MQ smart scheduling: dependency-aware queue reordering

Implement intelligent MQ reordering to minimize conflicts.

## Goal
Reorder the MQ so that MRs touching disjoint files merge "in parallel" (no conflicts), while MRs touching overlapping files are sequenced.

## Approach
1. For each MR, get list of changed files (from branch diff)
2. Build conflict graph: edge between MRs if files overlap
3. Find maximal independent sets (MRs that can merge in any order)
4. Schedule independent MRs first, then handle remaining sequentially

## Implementation
- Add file analysis to MR submission (gt done)
- Store changed_files in MR wisp
- Refinery sorts queue by: priority → conflicts → age

## Example
```
Queue: [A, B, C, D]
Files:
  A: auth/login.go
  B: payments/checkout.go
  C: auth/login.go ← conflicts with A!
  D: docs/readme.md

Optimal: [A, B, D, C] - A, B, D can merge without waiting
```

## Parent
gt-lxxh2


Digest: mol-deacon-patrol

Patrol 18: All healthy.


Digest: mol-deacon-patrol

Patrol cycle 9: All quiet.


Track operational stats as entity/audit beads

Witness and refinery track operational stats in JSON files:
- total_merged, today_merged, total_failed (refinery)
- total_checks, total_nudges, total_escalations (witness)

For HOP entity CV tracking, these could become:
- type=audit beads (daily roll-ups of operational metrics)
- Entity chain entries showing validator activity

This provides observability and contributes to entity reputation tracking (e.g., refinery X has merged 500 PRs with 2% failure rate).

Not critical for launch but aligns with HOP Platform of Platforms vision.


Merge: toast-mjw7062w

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


Merge: furiosa-mjuk2tlb

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


MQ summary in gt status

Add per-rig MQ summary to gt status output.

Current gt status shows:
  gastown
    refinery  ✓ running

Add:
  gastown
    refinery  ✓ running
    MQ: 4 pending, 1 in-flight

Implementation:
- Query beads for merge-request type issues
- Count by status (open=pending, in_progress=in-flight)
- Display in rig section

Implemented MQ summary in gt status output - shows pending, in-flight, and blocked MR counts under Refinery section


Digest: mol-deacon-patrol

Patrol 96: All healthy


Digest: mol-deacon-patrol

Patrol 59: All healthy


Digest: mol-deacon-patrol

Patrol 142 complete: All agents healthy, no incidents


Digest: mol-deacon-patrol

P16: stable


Digest: mol-deacon-patrol

Patrol 115: All healthy


Merge: nux-1767080427756

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


Digest: mol-deacon-patrol

Patrol cycle 18: All healthy


Plugin system: subprocess JSON protocol

Language-agnostic plugin system via subprocess JSON protocol.

## Concept

Allow extending Gas Town with external scripts/programs. Plugins communicate via stdin/stdout JSON.

## Protocol

Request (gt → plugin):
```json
{"method": "check", "params": {"rig": "wyvern", "polecat": "Toast"}}
```

Response (plugin → gt):
```json
{"result": {...}, "error": null}
```

Error response:
```json
{"result": null, "error": {"code": 1, "message": "..."}}
```

## Interface

```go
type Plugin struct {
    Name    string
    Path    string  // executable path
    Methods []string
}

type PluginManager struct {
    plugins map[string]*Plugin
}

func NewPluginManager() *PluginManager
func (pm *PluginManager) Register(plugin *Plugin) error
func (pm *PluginManager) Call(plugin, method string, params any) (any, error)
func (pm *PluginManager) Discover(dir string) error  // auto-discover plugins
```

## Plugin Discovery

Look in:
1. `<town>/plugins/`
2. `~/.config/gastown/plugins/`
3. System path with `gt-plugin-*` prefix

## Built-in Hooks

Plugins can register for events:
- `polecat.started` - Polecat session started
- `polecat.done` - Polecat signals done
- `merge.requested` - MR submitted
- `merge.completed` - MR merged

## Use Cases

- Custom health checks
- Integration with external systems (Slack, etc.)
- Custom merge policies
- Metrics collection

## Future

Consider MCP integration for richer plugin capabilities.


Bubbletea TUI dashboard

Interactive TUI using Charm Bubbletea. Root model, view routing, Lipgloss theme. Includes: dashboard, rig explorer, polecat detail with live tail, mail view, beads view, spawn wizard.


Merge: dag-mjtm8k85

Branch deleted, no audit trail - unverifiable


Digest: mol-deacon-patrol

Cycle 191: Nominal


Digest: mol-deacon-patrol

Patrol 7: All healthy.


Remove stubbed ProcessMRFromQueue and mrqueue package

internal/refinery/engineer.go has stubbed ProcessMRFromQueue() that returns hardcoded failure.
internal/mrqueue/ package exists but isn't used.

This was aspirational 'beads-based MR automation' but:
1. Refinery agent just runs git commands per role prompt
2. manager.ProcessMR() is already fully implemented if we need Go automation
3. The stub creates confusion about what's working

Either:
1. Remove engineer.ProcessMRFromQueue and mrqueue package entirely
2. Or finish implementing it if there's a real use case

Leaning toward removal - YAGNI.

Removed ProcessMRFromQueue, mrqueue package, and related queue handlers from engineer.go. Manager.ProcessMR is the working implementation.


Digest: mol-deacon-patrol

Patrol 122: All agents healthy, no incidents


Merge: valkyrie-1767106008400

branch: polecat/valkyrie-1767106008400
target: main
source_issue: valkyrie-1767106008400
rig: gastown


Digest: mol-deacon-patrol

Patrol cycle 61: All agents healthy, no orphans, archived 1 ACK


Day 3.3: Witness sends MERGE_READY to refinery

When polecat completes work:
1. Witness detects completion (hook_bead closed, state=stopped)
2. Witness sends mail to refinery: MERGE_READY
3. Mail includes branch name and work bead ID

Parent: gt-hwka3


Activity feed improvements

Make the activity feed (gt feed) a first-class TUI experience using charmbracelet.

## Vision

A real-time dashboard showing all Gas Town activity with:
- Agent tree organized by role (mayor, witnesses, crew, polecats)
- Live event stream
- Vim-style navigation
- Filtering and search

## Architecture

Two-tier event system:
- ~/gt/.events.jsonl (raw, audit) - all events from gt, bd, agents
- Feed daemon curates → ~/gt/.feed.jsonl (user-facing) - filtered, deduped

TUI reads from curated feed for smooth UX.

## Layout (Dashboard + Stream)
```
┌─────────────────────────────────────────────────────────────┐
│ GT Feed                                    Filter: all      │
├─────────────────────────────────────────────────────────────┤
│ gastown/                                                    │
│   🎩 mayor      [10:30] Dispatched gt-xyz → Toast           │
│   👁 witness    [10:28] Nudged polecat-3 (idle 5m)          │
│   🏭 refinery   [10:25] Merged PR #123                      │
│   👷 crew/                                                   │
│      joe        [10:22] ✓ Completed gt-95j13                │
│      max        [10:18] → Working on gt-s6r44               │
│   😺 polecats/                                               │
│      Toast      [10:30] Received gt-xyz, starting...        │
├─────────────────────────────────────────────────────────────┤
│ [10:30] 😺 Toast: Received molecule gt-xyz                  │
│ [10:28] 👁 witness: Nudged polecat-3 after 5m idle          │
│ [10:25] 🏭 refinery: Merged PR #123                         │
├─────────────────────────────────────────────────────────────┤
│ j/k: scroll  /: search  f: filter  q: quit  ?: help         │
└─────────────────────────────────────────────────────────────┘
```

## Key Features
1. Real-time updates - events stream in live
2. Agent tree - all agents grouped by role with status
3. Vim-style navigation - j/k, gg/G, /search
4. Filtering - by rig, role, event type, time
5. Collapsible sections
6. Details on select

## Tech Stack
- bubbletea - TUI framework
- bubbles - viewport, list components
- lipgloss - styling (already have)

## Success Criteria
- Feed is beautiful and scannable at a glance
- Agent activity visible in real-time
- Works in any terminal, degrades gracefully for pipes


Digest: mol-deacon-patrol

Patrol cycle 4: all healthy


Digest: mol-deacon-patrol

Patrol 4: routine, all healthy


Digest: mol-deacon-patrol

Patrol 2: 1 msg (Nux done), health OK


Merge: slit-mjvtz18y

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

Already merged to main at 2bcfa763 - stale MR bead


Digest: mol-deacon-patrol

Patrol 247 complete: no incidents


Digest: mol-deacon-patrol

Patrol 3: Routine


Digest: mol-deacon-patrol

Patrol 6: All clear


Formula Molecules: Guzzoline production for Gas Town

## Vision

Gas Town executes work. But it also needs to PRODUCE work - structured, high-quality guzzoline on demand. **Formula Molecules** are recipes that spawn structured convoys.

## Core Insight

A formula is a molecule template that:
1. Takes input (a PR, a design problem, a codebase)
2. Spawns multiple polecats with specific focuses
3. Each leg produces structured output
4. Synthesis step combines into unified deliverable

Gas Town becomes both consumer AND producer of guzzoline.

## Example Formulas

### Design Convoy Formula
Input: Feature request or problem statement
Legs (parallel):
- API design polecat
- Data model polecat
- UX/ergonomics polecat
- Scalability polecat
- Security polecat
Synthesis: Unified design doc with tradeoffs

### Code Review Convoy Formula
Input: PR or file set
Legs (parallel):
- Correctness: Does it work?
- Performance: Any bottlenecks?
- Security: Vulnerabilities?
- Elegance: Clean design?
- Resilience: Error handling?
- Style: Convention compliance?
- Smells: Anti-patterns?
- Legacy: Respects existing patterns?
Synthesis: Categorized review with priority issues

### Other Formula Ideas
- Test Coverage Convoy: Unit, integration, edge cases, error paths
- Documentation Convoy: API docs, user guide, examples, changelog
- Migration Convoy: Database, API, config, rollback plan
- Incident Response: Root cause, timeline, fix, prevention

## Mol Mall

Library/marketplace of formulas:
```bash
gt formula list              # Available formulas
gt formula show code-review  # Formula details
gt formula run code-review --pr=123  # Execute formula → convoy
gt formula create my-review  # Create custom formula
```

## Technical Design

### Formula Structure (in beads)
```yaml
id: formula-code-review
type: formula
name: Code Review
inputs:
  - name: target
    type: pr | files | branch
legs:
  - name: correctness
    focus: "Verify logical correctness and edge cases"
    output: findings.md
  - name: security
    focus: "Identify security vulnerabilities"
    output: findings.md
  # ...
synthesis:
  inputs: all leg outputs
  output: review-summary.md
```

### Execution Model
1. `gt formula run` creates convoy with formula reference
2. Spawns polecats for each leg (parallel where possible)
3. Each polecat gets leg-specific prompt + shared context
4. Outputs collected as bead attachments or slots
5. Synthesis polecat reads all outputs, produces final deliverable
6. Convoy lands with unified result

### Dependencies
- Leg outputs feed synthesis (internal convoy deps)
- Formula can specify leg ordering if needed
- Parallel by default, sequential where required

## Open Questions

1. Where do formulas live? Town-level beads? Separate formula registry?
2. How to version/share formulas across towns?
3. Leg output format standardization?
4. Human checkpoints between legs or only at end?
5. Partial formula runs (skip some legs)?
6. Formula composition (formula that includes other formulas)?

## Why This Matters

Gas Town currently waits for humans to create work. With formulas:
- Mayor can invoke structured reviews on any PR
- Design work follows consistent methodology
- Quality processes are repeatable and scalable
- Work generation becomes as automated as work execution

**Guzzoline factory, not just guzzoline consumer.**


Code Review Convoy formula (first formula implementation)

## First Formula: Code Review Convoy

Implement the code review formula as proof of concept for formula molecules.

### Input
- PR number, branch, or file list

### Legs (parallel polecats)
| Leg | Focus | Output |
|-----|-------|--------|
| correctness | Logic errors, edge cases, off-by-ones | findings.md |
| performance | Bottlenecks, O(n²), allocations | findings.md |
| security | Injection, auth, data exposure | findings.md |
| elegance | Design clarity, abstractions | findings.md |
| resilience | Error handling, retries, timeouts | findings.md |
| style | Conventions, naming, formatting | findings.md |
| smells | Anti-patterns, god objects, coupling | findings.md |

### Synthesis
- Read all leg findings
- Deduplicate overlapping issues
- Prioritize by severity
- Produce unified review with sections

### Command
```bash
gt formula run code-review --pr=123
# Creates convoy hq-cv-xxx
# Spawns 7 polecats + 1 synthesis
# Lands with review-summary.md
```

### Implementation Steps
1. Define formula schema in beads
2. gt formula run command
3. Leg prompt templates
4. Output collection mechanism
5. Synthesis polecat spawning
6. Result attachment to convoy bead


Design Convoy formula

## Design Convoy Formula

Structured design exploration for features/architecture.

### Input
- Problem statement or feature request

### Legs (parallel polecats)
| Leg | Focus | Output |
|-----|-------|--------|
| api | Interface design, ergonomics | api-design.md |
| data | Data model, storage, migrations | data-model.md |
| ux | User experience, CLI ergonomics | ux-analysis.md |
| scale | Performance at scale, bottlenecks | scalability.md |
| security | Threat model, attack surface | security.md |
| integration | How it fits existing system | integration.md |

### Synthesis
- Read all dimension analyses
- Identify conflicts and tradeoffs
- Propose unified design with options
- Flag decisions needing human input

### Command
```bash
gt formula run design --problem="Add notification levels to mayor"
# Creates design convoy
# Spawns dimension polecats
# Lands with design-doc.md
```


Mol Mall: Formula library and sharing

## Mol Mall

Library/marketplace for formula molecules.

### Features
- Browse available formulas
- Formula metadata (author, version, inputs, outputs)
- Custom formula creation
- Formula versioning
- Cross-town formula sharing (future)

### Commands
```bash
gt formula list              # List available formulas
gt formula show <name>       # Formula details
gt formula create <name>     # Create new formula
gt formula edit <name>       # Modify formula
gt formula export <name>     # Export for sharing
gt formula import <file>     # Import shared formula
```

### Storage
- Formulas as beads in town-level .beads/
- type: formula
- Structured schema for legs, synthesis, inputs

### Future: Public Mol Mall
- Central registry of community formulas
- gt formula search 'code review'
- gt formula install community/security-audit


Digest: mol-deacon-patrol

Patrol 209: All nominal


Digest: mol-deacon-patrol

Patrol 7: quick pass


Digest: mol-deacon-patrol

Patrol 64: Routine


Digest: mol-deacon-patrol

Patrol cycle 72: All healthy


Merge: capable-mjtltnm5

branch: polecat/capable-mjtltnm5
target: main
source_issue: capable-mjtltnm5
rig: gastown


gt mq list shows empty when MRs exist

The gt mq list command returns empty results even when merge requests exist in the queue.

Fixed - mq_list.go now uses r.BeadsPath() instead of r.Path to read from the git-synced beads location


Merge: furiosa-1766987668522

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


Digest: mol-deacon-patrol

Patrol complete: all witnesses/refineries healthy, burned 1 stale wisp, no callbacks, convoys in progress


Digest: mol-deacon-patrol

Patrol cycle 3: All healthy. 3 rigs responding.


Day 5.3: Declare liftoff or document gaps

Final assessment:
- If E2E works: Close gt-oki8p as complete, declare liftoff
- If gaps remain: Document what's missing, file follow-on beads

Either way, the 4.5 day sprint is complete.

Parent: gt-oki8p


Digest: mol-deacon-patrol

Patrol cycle 28: All healthy, no incidents


Enhance gt status with role hierarchy view

Show identity and role hierarchy in gt status:

## Current Output
Flat list of agents by rig, no clear role hierarchy.

## Desired Output
Tree structure showing:
- Town-level roles (Mayor, Deacon)
- Per-rig role slots with their role_bead references
- Each agent slot with pinned work

Example:
```
Town: gt
├── 🎩 Mayor (gt-mayor-role)
│   └── gt-mayor [running] → gt-u7dxq
├── 🔔 Deacon
│   └── gt-deacon [running]
└── Rigs
    └── gastown/
        ├── 👁 Witness (gt-witness-role)
        │   └── gt-witness-gastown [running]
        ├── 🏭 Refinery (gt-refinery-role)
        │   └── gt-refinery-gastown [running] → (work)
        ├── 👷 Crew
        │   ├── jack [running] → gt-xxxx
        │   └── joe [running]
        └── 😺 Polecats
            └── (none)
```

## Key Changes
1. Use tree-style indentation (├── └──)
2. Group agents by role type
3. Show role_bead for each role category
4. Use emojis for quick visual scanning


Update docs with molecule navigation workflow

Update architecture and workflow docs with new molecule navigation.

## Docs to update

### docs/molecules.md
- Add 'Navigating Molecules' section
- Document bd mol current usage
- Document bd close --continue workflow
- Show the propulsion pattern

### docs/propulsion-principle.md
- Add molecule navigation as key enabler
- Show before/after workflow comparison

### docs/polecat-wisp-architecture.md
- Update step execution section
- Show bd close --continue in examples

## New section content

### Molecule Navigation

Finding your place:
  bd mol current              # Where am I?
  bd mol current gt-abc       # Status of specific molecule

Seamless transitions:
  bd close gt-abc.3 --continue   # Close and advance
  bd close gt-abc.3 --no-auto    # Close but don't auto-claim next

The old way (3 commands):
  bd close gt-abc.3
  bd ready --parent=gt-abc
  bd update gt-abc.4 --status=in_progress

The new way (1 command):
  bd close gt-abc.3 --continue

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

Created three docs: molecules.md (navigation section), propulsion-principle.md (molecule navigation enabler), polecat-wisp-architecture.md (step execution with --continue)


Clean up ~/gt root directory cruft

The town root has accumulated various directories and files that need review:

**To evaluate:**
- daemon/ - old daemon code? move or delete?
- deacon/ - WIP deacon work? consolidate with gastown?
- mayor/ - old mayor structure?
- AGENTS.md - is this still used?
- gt binary at root - should be gitignored

**Already correct:**
- .beads/, .claude/, .gastown/, .runtime/ - runtime dirs
- beads/, gastown/ - rig directories
- docs/hop/ - strategic docs
- CLAUDE.md - mayor context

Clean up, consolidate, update .gitignore as needed.


Digest: mol-deacon-patrol

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


Digest: mol-deacon-patrol

Patrol complete: No callbacks, no gates, witness/refinery healthy, no orphans, clean cycle


Digest: mol-deacon-patrol

Patrol cycle 1: All 3 rigs healthy (beads, gastown, wyvern), no orphans, no cleanup needed, inbox clean


Refinery Patrol

Merge queue processor patrol loop with verification gates.

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


Digest: mol-deacon-patrol

Patrol cycle 3: All 3 rigs healthy. 0 messages. No incidents.


Fix SQL injection in convoy panel getTrackedIssueStatus

convoy.go:151-152 interpolates convoyID directly into SQL query without sanitization. Add input validation for hq-* pattern.


Digest: mol-deacon-patrol

Patrol cycle 6: All healthy


Daemon: configurable heartbeat interval

Heartbeat interval is hardcoded to 60s. Should be configurable via:
- town.json config
- Command line flag
- Environment variable

Default 60s is reasonable but some deployments may want faster/slower.


Digest: mol-deacon-patrol

Patrol 13: quick pass


Digest: mol-deacon-patrol

Patrol 16


Digest: mol-deacon-patrol

Cycle 189: Nominal


Merge: rictus-mjw3nj1a

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


Digest: mol-deacon-patrol

Patrol 156 complete


Merge: rictus-1767082306179

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


Day 1.2: Add agent-specific fields to schema

Add fields for agent beads:
- hook_bead: reference to current work (0..1 cardinality)
- role_bead: reference to role definition (1)
- state: agent-reported state (idle|running|stuck|stopped)

Parent: gt-d0jqp

Re-opened: Close reason referenced non-existent commit b5c69507. Agent fields not yet implemented in bd CLI.


Patrol exponential backoff for cost savings

Agent-side backoff state tracking in patrol molecules.

## State

Each patrol agent tracks:
- current_interval: current sleep duration (starts at base)
- idle_cycles: count of cycles with no work found

## Backoff Logic

```
on await-signal timeout (no nudge):
    idle_cycles++
    current_interval = min(base * 2^idle_cycles, max_interval)

on nudge received:
    idle_cycles = 0
    current_interval = base
    wake immediately

on work found:
    idle_cycles = 0
    current_interval = base
```

## Where State Lives

Options:
A. Agent bead fields (persistent across sessions)
B. In-memory during patrol (resets on restart)
C. Wisp fields (ephemeral but survives handoff)

Option B is simplest - backoff resets when agent restarts anyway.

## Depends On

- gt-l6ro3.3: await-signal step type


Digest: mol-deacon-patrol

Patrol 14: Quiet


Digest: mol-deacon-patrol

Patrol 243 complete: no incidents


Digest: mol-deacon-patrol

Patrol 210: Deep health check - 3 witnesses, 3 refineries, 10 polecats all healthy


Digest: mol-deacon-patrol

Patrol 18


Synthesis: Combine leg outputs into final deliverable

Implement synthesis step:
1. Collect all leg outputs (findings.md files)
2. Spawn synthesis polecat with combined context
3. Synthesis prompt: dedupe, prioritize, format
4. Output: review-summary.md attached to convoy bead
5. Close convoy when synthesis complete

Consider: bd slot or bd attach for outputs.


Add handoff self-initiation protocol to role templates

Agents need clear protocol for self-initiated handoff:

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

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

Include examples for each role type.


Digest: mol-deacon-patrol

Patrol 12 complete


Verify commit on main before nuke (not just MERGED signal)

Witness nukes on MERGED signal without verifying merge actually succeeded.

## Problem
MERGED signal means refinery ATTEMPTED merge. But:
- Merge could have failed after signal sent
- Merge could be to wrong branch
- MERGED could be for stale MR (already merged via different path)

## Fix
Before nuke, witness should verify:
```bash
# Get the commit SHA from the polecat branch
commit_sha=$(git rev-parse polecat/$name)

# Verify it's reachable from main
git merge-base --is-ancestor $commit_sha main
```

Only nuke if verification passes.

## Alternative
Refinery sends commit SHA in MERGED payload, witness verifies that specific SHA.

Implemented commit verification in HandleMerged


Digest: mol-deacon-patrol

Cycle 10


bd sync fails when .beads/redirect points to different repo

Duplicate - filed as bd-kvus in beads repo


Digest: mol-deacon-patrol

Patrol 8: All healthy.


Merge: valkyrie-1767074338488

attached_args: Code review

branch: polecat/valkyrie-1767074338488
target: main
source_issue: valkyrie-1767074338488
rig: gastown

CODE REVIEW (furiosa): REJECT

Issue: Commit modifies CLAUDE.md which is gitignored on main.

Findings:
1. CLAUDE.md is in .gitignore (clone-specific file)
2. CLAUDE.md is NOT tracked on main branch
3. Polecat manager has installCLAUDETemplate() to generate this file locally per worktree
4. The commit adds a file that should not be committed

Recommendation: Do not merge. CLAUDE.md should be locally generated, not committed.

This merge request has no valid changes to merge.

REJECTED: CLAUDE.md is gitignored and clone-specific. The polecat manager generates this file locally via installCLAUDETemplate(). No valid changes to merge.


Digest: mol-refinery-patrol

Patrol: No new branches to merge (all already cherry-picked). Archived 100+ stale MERGE_READY messages. Inbox clean.


Digest: mol-deacon-patrol

Patrol 140: All healthy


Merge: gt-bca67

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


Feed-Based Wake Model for Patrol Agents

## The Paradigm Shift

> **Backoff is not about polling less. It is about waiting for signals with a timeout.**

This epic captures the shift from time-driven to event-driven patrol wake.

## Key Insight (Recovered from 2025-12-29 session crash)

The Beads activity feed (bd activity --follow) is the universal data plane for
wake signals. Every meaningful action creates a beads mutation; agents subscribe to
the feed and wake within ~500ms. The timeout is just a safety net.

**OLD**: Time-driven. Wake because time passed. Poll less when idle.
**NEW**: Event-driven. Wake because signal arrived. Timeout is safety net.

## Architecture

ANY MUTATION:
  bd create/update/close -> issues.jsonl mutation
                        -> bd activity --follow sees it (~500ms)
                        -> All subscribed agents wake immediately

PATROL AGENT:
  Runs bd activity --follow as background source
  Any output line = wake signal
  Timeout expiry = safety net (not primary wake)

## Wake Sources (Priority Order)

| Source | Latency | Purpose |
|--------|---------|---------|
| Feed | ~500ms | Primary - any beads mutation |
| Nudge | Instant | Explicit wake (startup hooks) |
| Timeout | Backoff | Safety net for missed signals |
| Daemon | 5-60min | GUPP backstop, session recovery |

## Key Design Decisions

1. No wake_on conditions - signals carry no semantic meaning. Just wake up.
   Agent discovers reality by checking mail, beads, hook, git state.

2. Read-only commands do not wake - gt status, bd show create no mutations.

3. Daemon is recovery-focused - catches edge cases (GUPP violations, dead sessions).

4. Keepalive file deprecated - the feed replaces the keepalive mechanism.

## Reference

- ~/gt/docs/patrol-system-design.md (Sleeping Agents section)
- ~/gt/docs/PRIMING.md (Feed Is the Signal insight)

## Related

- gt-l6ro3: Patrol Exponential Backoff System (backoff timing, complements this)

Feed-based wake model complete: patrol agents subscribe to bd activity --follow, daemon uses fixed 10-min recovery heartbeat, keepalive file infrastructure removed


Patrol agents subscribe to bd activity --follow

Each patrol agent (Deacon, Witness, Refinery) should run bd activity --follow as a background process. Any output line is a wake signal. This is the primary wake mechanism.

Implementation:
1. Add feed subscription to await-signal step logic
2. Agent starts bd activity --follow on entering await-signal
3. Any line of output breaks the wait immediately
4. Timeout still applies as safety net

See patrol-system-design.md for full specification.

Implemented await-signal command that subscribes to bd activity --follow


Remove keepalive file infrastructure

The keepalive mechanism (~/gt/daemon/activity.json) is deprecated in favor of feed-based wake.

TODO:
1. Remove keepalive.TouchTownActivity() calls from gt commands
2. Remove keepalive.ReadTownActivity() from daemon
3. Delete internal/keepalive package
4. Update daemon to use longer base heartbeat (recovery-focused)

Whitelist consideration: Some read-only commands might need to wake (TBD - none identified yet)

Removed keepalive infrastructure: TouchTownActivity/ReadTownActivity deleted from keepalive.go, activity-based backoff removed from daemon.go (now uses fixed 10-min recovery interval), PersistentPreRun hook removed from root.go


Startup hooks nudge Deacon

When a new Claude session starts (via startup hook), it should nudge Deacon so Deacon knows a new agent has appeared. This is one of Deacons extra wake sources for GUPP backstop.

Implementation: Add gt nudge deacon session-started to the startup hook chain.

Implemented: Added gt nudge deacon session-started to startup hooks, with special deacon target handling in nudge.go


Daemon heartbeat becomes recovery-focused

Update daemon heartbeat to be recovery-focused, not wake-focused.

Current: Daemon pokes agents every 5-60min as primary wake.
New: Daemon only checks for:
- Dead sessions that need restart
- Agents with work-on-hook not progressing (GUPP violation)
- Orphaned work

Feed handles normal wake; daemon is the safety net for edge cases.

Implemented recovery-focused daemon heartbeat: removed poke functions, added GUPP violation and orphaned work checks


Documentation: Feed-based wake model

Document the feed-based wake model in patrol-system-design.md and PRIMING.md.

DONE (2025-12-29):
- Updated patrol-system-design.md with full feed-based wake specification
- Added Feed Is the Signal and Discover Dont Be Told insights to PRIMING.md
- Committed as 39e46148


Merge: rictus-mjtlq9xg

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


Digest: mol-deacon-patrol

Patrol 43: All healthy, 6 agents pinged


Use Beads issue status as spawn source of truth

Currently witness tracks spawned issues in .gastown/witness.json to prevent re-spawning:

{"spawned_issues": ["gt-abc1", "gt-def2", ...]}

This is redundant with Beads issue status (in_progress). The witness could query:
  bd list --status=in_progress

The local list serves as a performance cache to avoid querying beads every cycle. Consider:
1. Use Beads as source of truth
2. Keep local cache with TTL
3. Sync cache on witness start

This simplifies state management and ensures consistency.


Merge: furiosa-mjtj9d4g

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


Digest: mol-deacon-patrol

Patrol 20: final cycle


Merge: rictus-1767079818240

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


Digest: mol-deacon-patrol

Patrol 12: routine


Digest: mol-deacon-patrol

Patrol cycle 1: All rigs healthy, no incidents


Mol Mall: Formula Package Registry

A package registry for sharing and discovering formulas, schematics, and protocols.

## Concept

Like npm/Maven/Go modules but for workflow definitions.

```
mol-mall.io/
├── @gastown/           # Official Gas Town formulas
│   ├── shiny
│   ├── polecat-work
│   └── release
├── @acme-corp/         # Enterprise org (private)
│   └── compliance-review
├── @linus/             # Individual publisher
│   └── kernel-review
└── community/          # Unscoped public formulas
    └── towers-of-hanoi
```

## Resolution Hierarchy

```
1. Project:  ./.beads/formulas/          # Project-specific
2. Rig:      ~/gt/<rig>/.formulas/       # Rig-wide
3. Town:     ~/gt/.formulas/             # Town-wide (mayor stdlib)
4. User:     ~/.gastown/formulas/        # Personal collection
5. Mall:     mol-mall.io/                # Published packages
```

## Package Manifest

```toml
[package]
name = "shiny"
version = "1.2.0"
description = "Engineer in a Box"
authors = ["Gas Town <gastown@example.com>"]
license = "MIT"

[dependencies]
"@gastown/review-patterns" = "^2.0"
```

## Distribution Scenarios

1. **Celebrity Formulas**: Expert-curated workflows (e.g., Linus kernel review)
2. **Enterprise Compliance**: Private company formulas
3. **Standard Library**: @gastown/* blessed defaults
4. **Community Ecosystem**: Varying quality, needs ratings/verification

## Open Questions

1. Versioning semantics - SemVer? Breaking change rules?
2. Security model - sandboxing? signing? permissions?
3. Private registries - self-hosted? authentication?
4. Lock files - formulas.lock format?

## Related

- docs/formula_evolution.md - package ecosystem parallel section
- gt-8ws7o - Schematic (can be published)
- gt-y3jb9 - Protocol (can be published)


Digest: mol-deacon-patrol

Patrol 150: All healthy


Digest: mol-deacon-patrol

Patrol cycle 1: 17 sessions healthy, 3 agents responded to health check, all core systems normal


Digest: mol-deacon-patrol

Patrol #11: Quick cycle, all quiet.


Digest: mol-deacon-patrol

Patrol 96: All healthy


Digest: mol-deacon-patrol

Patrol 12: all healthy


Digest: mol-deacon-patrol

Patrol 2: All healthy, no incidents


Digest: mol-deacon-patrol

Patrol cycle 9: All healthy


Merge: rictus-mjvtzdm2

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


Digest: mol-deacon-patrol

Patrol cycle 52: All healthy


Digest: mol-deacon-patrol

Patrol #7: nominal


Digest: mol-deacon-patrol

Patrol cycle 2: Witnessed escalation re: 14 polecats with unpushed work. All agents healthy. No pending work.


Agent bead IDs should use rig prefix, not hardcoded gt-

When spawning beads polecats, agent bead creation fails:

```
Error: invalid agent ID: agent ID must start with 'gt-' (got "bd-beads-polecat-pearl")
```

The validation is hardcoded to expect 'gt-' but beads rig uses 'bd-' prefix.

Fix: Agent bead ID validation should accept the rig's configured prefix, not hardcode 'gt-'.

Fixed agent bead ID validation in beads CLI to accept any prefix, and updated gastown's witness/handlers.go and cmd/crew_lifecycle.go to use rig prefix


Digest: mol-deacon-patrol

Patrol cycle 2: All 3 rigs healthy. 0 messages. No incidents.


gt nudge should accept role shortcuts like 'mayor' not just 'gt-mayor'

Implemented role shortcuts (mayor, witness, refinery) that expand to session names


E2E Test: Add a comment to internal/util/process.go


Merge: furiosa-dogs

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


Show active workers in gt convoy status output

Enhance convoy status to show which workers are currently assigned to tracked issues.

CURRENT OUTPUT:
  Tracked Issues:
    ○ gt-xyz: Fix bug [task]
    ○ gt-abc: Add feature [task]

DESIRED OUTPUT:
  Tracked Issues:
    ○ gt-xyz: Fix bug [task]
    ○ gt-abc: Add feature [task]  @gastown/nux (12m)

  Active Workers (the swarm):
    gastown/nux     gt-abc     running 12m
    beads/amber     bd-def     running 5m

IMPLEMENTATION:
1. Query hooked molecules to find workers with tracked issues
2. Match issue IDs to tracked issues
3. Show worker assignments inline and/or in separate section

File: internal/cmd/convoy.go (runConvoyStatus)


Test Polecat Arm

Test child for bonding pattern


Test refile v2

Testing improved refile

(Refiled from bd-eysh)


Digest: mol-deacon-patrol

Patrol cycle 7: all healthy


Digest: mol-deacon-patrol

Patrol 139: All healthy


witness Handoff


Digest: mol-deacon-patrol

Patrol cycle 70: All healthy


Digest: mol-deacon-patrol

Patrol 148: All healthy


Fix N+1 query problem in convoy status fetching

getTrackedIssueStatus spawns a new bd show for each tracked issue. With 10 convoys x 5 issues = 50+ subprocesses every 10s. Consider batching or caching.


Digest: mol-deacon-patrol

Cycle 183: All agents healthy, no incidents


Digest: mol-deacon-patrol

Patrol 90: All healthy


Merge: gt-znma3

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


Merge: nux-1767087680976

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


Digest: mol-deacon-patrol

Patrol 17: All healthy


Digest: mol-deacon-patrol

Cycle 7


Digest: mol-deacon-patrol

Patrol 4: All healthy.


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.


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.


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.


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.