Move disk 4: B → A

Move disk 4 from peg B to peg A. (Move 424/1023)


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Idle Town Principle

**The Deacon should be silent/invisible when the town is healthy and idle.**

- Skip HEALTH_CHECK nudges when no active work exists
- Sleep 60+ seconds between patrol cycles (longer when idle)
- Let the feed subscription wake agents on actual events
- The daemon (10-minute heartbeat) is the safety net for dead sessions

This prevents flooding idle agents with health checks every few seconds.

## Second-Order Monitoring

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

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


Move disk 4: A → C

Move disk 4 from peg A to peg C. (Move 824/1023)


Merge: nux-mjxn8p5t

branch: polecat/nux-mjxn8p5t
target: main
source_issue: nux-mjxn8p5t
rig: gastown
agent_bead: gt-gastown-polecat-nux
retry_count: 0
last_conflict_sha: null
conflict_task_id: null


Session: gt-gastown-test completed gt-f7jxr


Digest: mol-deacon-patrol

P10: stable


Polecat name pooling: Bounded reusable names

Polecats reuse names from a bounded pool (50) with overflow to sequence numbers.

## Naming Scheme
- Pool: polecat-01 through polecat-50 (prefer low numbers)
- Overflow: <rigname>-<sequenceNumber> (e.g., beads-51, gastown-52)

## Design
- Witness tracks which pool names are in use
- On spawn: pick first available from pool
- If pool exhausted: use rigname-N format
- On completion: pool name returns, sequence numbers don't

## Why?
- User experience: tmux sessions survive polecat restarts
- Users stay attached, see new polecat start (like mayor respawn loop)
- Bounded resource usage for common case
- Scales beyond 50 when needed

## Implementation
- Witness maintains name allocation in beads or local state
- Tmux session runs respawn loop (like mayor)
- Name released on graceful exit or when witness detects dead session


Move disk 1: B → C

Move disk 1 from peg B to peg C. (Move 513/1023)


Fix patrol role priming

Patrol roles (deacon, witness, refinery) need proper context priming.

Current issue: Sessions start but may not have proper CLAUDE.md context.

Fix:
1. Ensure role templates include patrol formula reference
2. Verify SessionStart hook runs gt prime
3. Check that patrol loop starts automatically

Related: Role templates in internal/templates/roles/*.md.tmpl


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Second-Order Monitoring

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

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


Digest: mol-deacon-patrol

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


Digest: mol-deacon-patrol

Patrol #7: Quick cycle, no pending spawns.


Plugin: Plan-to-Epic converter

## Purpose

Help users create beads epics from various planning inputs.

## Inputs
- Markdown task lists
- GitHub issues
- Linear/Jira exports
- Free-form descriptions
- Existing beads epics

## Output
- Beads epic with properly structured children
- Dependencies set for wave ordering
- Priorities assigned
- Ready for `gt spawn --epic <id>`

## Implementation Options

### Option A: CLI Tool
```bash
gt plan import --from github --repo owner/repo --label batch-candidate
gt plan import --from markdown tasks.md
gt plan structure <epic-id>  # analyze and add dependencies
```

### Option B: Plugin Agent
A plugin at `<rig>/plugins/plan-oracle/` that:
- Receives planning requests via mail
- Analyzes scope and requirements
- Creates structured beads epic
- Sets dependencies based on analysis

### Option C: Interactive Mode
```bash
gt plan create
# Walks through questions, creates epic interactively
```

## Axiom

As stated: 'The Planning phase should end in the creation of a workable Beads plan.'

This plugin bridges the gap between human planning and machine-executable work.

## Priority

P2 - Nice to have for MVP. Manual epic creation works for now.

## Note

No "swarm IDs" - output is just a beads epic with children. Workers process it independently.


Add molecule to update local go binary on push to main

When pushing to main branch, automatically rebuild and install the gt binary on the local machine so changes are immediately available.


Digest: mol-deacon-patrol

Patrol 9: Quiet


Digest: mol-deacon-patrol

Patrol: no callbacks, no polecats, all agents healthy, cleaned 2 orphan processes + 2 stale locks


mol-deacon-patrol


Move disk 3: A → B

Move disk 3 from peg A to peg B. (Move 772/1023)


Digest: mol-deacon-patrol

Patrol cycle 64: All healthy


gt-gastown-polecat-imperator

gt-gastown-polecat-imperator

role_type: polecat
rig: gastown
agent_state: spawning
hook_bead: null
role_bead: gt-polecat-role
cleanup_status: has_stash
active_mr: gt-usytz
notification_level: null


Move disk 1: B → C

Move disk 1 from peg B to peg C. (Move 267/1023)


TIDY UP: Your previous work (gt-odvf: bd mol CLI docs) wa...

TIDY UP: Your previous work (gt-odvf: bd mol CLI docs) was already merged to main. Check your git status is clean, sync beads, and if nothing to do, just run 'gt done'.


Digest: mol-deacon-patrol

Patrol 8: quick pass


Move disk 2: B → A

Move disk 2 from peg B to peg A. (Move 802/1023)


Digest: mol-deacon-patrol

Patrol 2: All healthy, no changes


Digest: mol-deacon-patrol

Patrol 9: all quiet


Digest: mol-deacon-patrol

Patrol #5: Routine - 6 sessions healthy


Refinery Engineer placeholder code references tombstoned gt-3x1.2

The Refinery Engineer module has placeholder code that references gt-3x1.2, which is now tombstoned (gt-3x1 epic was superseded).

## Affected code:

1. **internal/refinery/engineer.go:203-225** - ProcessMR() says "This is a placeholder that will be fully implemented in gt-3x1.2" and returns failure with "ProcessMR not fully implemented (see gt-3x1.2)"

2. **internal/refinery/engineer.go:279-291** - handleFailure() says "This is a placeholder that will be fully implemented in gt-3x1.4"

3. **internal/refinery/engineer.go:307-312** - ProcessMRFromQueue() returns "ProcessMRFromQueue not fully implemented (see gt-3x1.2)"

## Context:
gt-3x1 was about updating Refinery to use Beads merge queue. The approach may have changed. Need to either:
- Implement the actual merge logic (new issue)
- Remove the placeholder code if not needed
- Update references to point to current strategy

## Related:
- gt-3x1 (tombstone) - original epic
- Current MQ implementation may have superseded this


Digest: mol-deacon-patrol

Patrol 15: Mayor OK, 11 sessions


Digest: mol-deacon-patrol

Patrol 1: All healthy, no lifecycle requests, no orphans


bd doctor: detect clone divergence emergencies

Add doctor check to detect:
1. Crew/Mayor on feature branches (should always be on main)
2. Significant divergence between clones that should be in sync
3. Distinguish from normal beads-sync vs main divergence (expected)

Context: bd sync --status shows all divergence as equal, but some is emergency (clones drifted) vs normal (sync branch mechanics).


Workspace doctor checks: Config, state, mail, Mayor, rigs

Workspace-level doctor checks.

## Checks

### ConfigExists
- Verify config/ directory exists
- Verify config/town.json exists
- Fix: Cannot auto-fix (need gt install)

### ConfigValid
- Parse town.json
- Verify required fields (type, version, name)
- Verify type == "town"
- Fix: Cannot auto-fix

### RigsRegistryValid
- Parse config/rigs.json
- Verify each registered rig directory exists
- Warn on missing rigs
- Fix: Remove missing rigs from registry

### MayorExists
- Verify mayor/ directory exists
- Verify mayor/CLAUDE.md exists
- Fix: Create from template

### MayorMailboxExists
- Verify mayor/mail/ directory exists
- Verify mayor/mail/inbox.jsonl exists (can be empty)
- Fix: Create directory and empty file

### MayorStateValid
- Parse mayor/state.json if exists
- Verify valid JSON
- Fix: Reset to default state

## Implementation

```go
var WorkspaceChecks = []Check{
    &ConfigExistsCheck{},
    &ConfigValidCheck{},
    &RigsRegistryValidCheck{},
    &MayorExistsCheck{},
    &MayorMailboxExistsCheck{},
    &MayorStateValidCheck{},
}
```


Merge: furiosa-1767059690595

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


Digest: mol-deacon-patrol

Cycle 297: All healthy, refinery busy


Session ended: gt-gastown-nux


Digest: mol-deacon-patrol

Patrol 19: all quiet


gt prime molecule execution prompt

Enhance gt prime to show molecule execution prompts.

## When Hook Has Molecule

gt prime should output:

```markdown
## Your Patrol: mol-deacon-patrol

**Current Step:** inbox-check
**Status:** pending (ready to execute)

### Step: inbox-check

Handle callbacks from agents.

Check the Mayor inbox for messages from:
- Witnesses reporting polecat status
- Refineries reporting merge results
...

**EXECUTE THIS STEP NOW.**

When complete, close the step:
  bd close <step-id>

Then check for next step:
  bd ready
```

## Logic

1. Check if hook has pinned molecule (via handoff bead with attachment)
2. Use bd mol current to find current step (derives from open children)
3. Get step details from the bead itself
4. Format execution prompt
5. Include close command (NOT bd mol advance - that was rejected)

## Key Insight (from bd-hulf rejection)

Molecule execution state is DERIVED from which child beads are closed vs open.
No separate state.yaml files. bd mol current already does this correctly.

"Advancing" a molecule = closing the current step bead. The next step
is whichever child is now ready (unblocked).

## Different from Slung Work

Slung work (bead) says "work on this issue"
Molecule says "execute this step of this workflow"

Both use the hook, but prompts differ.

## Files

- internal/cmd/prime.go
- Uses bd mol current for step discovery


Digest: mol-deacon-patrol

Patrol 8


Extract magic values to named constants

Magic strings and numbers throughout codebase:

Shells list repeated 4x:
- start.go:729, 773, 907
- crew_helpers.go
Pattern: []string{"bash", "zsh", "sh", "fish", "tcsh", "ksh"}

Timing values:
- time.Sleep(500 * time.Millisecond) in multiple places
- WaitForCommand 15*time.Second
- WaitForShellReady 5*time.Second
- Debounce 100ms default

Other magic values:
- "gt-" session prefix
- priority = 2 default
- Mail preview length 500 chars
- Heartbeat ages 5min/15min
- Divergence thresholds 10/50 commits

Suggestion: Add to constants/constants.go:
- SupportedShells
- ShutdownNotifyDelay, ClaudeStartTimeout, ShellReadyTimeout
- SessionPrefix
- DefaultPriority
- MailPreviewMaxLength


Move disk 1: C → A

Move disk 1 from peg C to peg A. (Move 491/1023)


Failure handling: assign back to worker, add labels

Handle merge failures appropriately.

Failure types and actions:
| Failure     | Action                                      |
|-------------|---------------------------------------------|
| conflict    | Add needs-rebase label, assign to worker    |
| tests_fail  | Add needs-fix label, assign to worker       |
| build_fail  | Add needs-fix label, assign to worker       |
| flaky_test  | Retry once, then treat as tests_fail        |
| push_fail   | Retry with backoff, escalate if persistent  |

Actions:
1. bd update <id> --status=open --assignee=<worker>
2. bd update <id> --labels=<failure-label>
3. Send mail to worker explaining failure
4. Log failure details

Reference: docs/merge-queue-design.md#handling-failures


Move disk 2: C → B

Move disk 2 from peg C to peg B. (Move 102/1023)


Day 1.7: Define per-rig agent bead ID pattern

Document and implement the agent bead ID pattern for per-rig agents.

Pattern: gt-<role>-<rig>
Examples:
- gt-witness-gastown
- gt-refinery-gastown
- gt-refinery-beads
- gt-polecat-gastown-nux

Town-level agents (no rig):
- gt-mayor
- gt-deacon

This pattern enables:
- Consistent lookup: bd show gt-witness-gastown
- Routing: routes.jsonl maps prefixes
- Filtering: bd list --type=agent --rig=gastown

Update:
- agent-as-bead.md with examples
- bd create --type=agent to validate pattern


Digest: mol-deacon-patrol

Patrol 14: All healthy


mol sling command: attach molecule to agent hook

Add `gt mol sling <molecule-id>` command to attach a molecule to the current agent's hook.

## Behavior

```bash
gt mol sling mol-witness-patrol
```

1. Find agent identity from cwd (witness, polecat, crew, etc.)
2. Find or create agent's handoff bead
3. Attach molecule to handoff bead (attached_molecule field)
4. Create root issue for this molecule instance
5. Instantiate molecule steps under the root

## Difference from mol attach

- `mol attach` attaches to an existing pinned bead
- `mol sling` creates a fresh instance for execution

## Output

```
🧬 Slung mol-witness-patrol on gastown/witness
  Instance: gt-xyz (9 steps)
  First step: inbox-check
```

## Implementation

- Reuse InstantiateMolecule from molecule.go
- Create wrapper issue for the instance
- Set attached_molecule on handoff bead


Move disk 2: A → C

Move disk 2 from peg A to peg C. (Move 374/1023)


gt crew add: Create crew workspace

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


Implement handoffs using pinned beads

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

## Current Problem

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

## Solution

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

## Implementation

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

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

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

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

## Dependencies

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


Digest: mol-deacon-patrol

Patrol #11


Crew Role Definition

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

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

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

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

## Core Responsibilities

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

## Propulsion Principle

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

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

## Session End Protocol

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

## Key Commands

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


Move disk 1: A → B

Move disk 1 from peg A to peg B. (Move 583/1023)


Move disk 6: C → B

Move disk 6 from peg C to peg B. (Move 288/1023)


Move disk 2: C → B

Move disk 2 from peg C to peg B. (Move 1002/1023)


Digest: mol-deacon-patrol

Patrol cycle 16: All agents healthy


Add runtime configuration for LLM commands

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

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

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

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

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

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

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

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


Daemon: Implement exponential backoff based on activity file

Modify daemon heartbeat logic to use exponential backoff when idle.

Read ~/gt/daemon/activity.json on each heartbeat.
Compute idle duration: time.Since(activity.Timestamp)
Adjust next ticker interval based on idle duration:

| Idle Duration | Next Heartbeat |
|---------------|----------------|
| 0-5 min       | 5 min (base)   |
| 5-15 min      | 10 min         |
| 15-45 min     | 30 min         |
| 45+ min       | 60 min (max)   |

Implementation:
1. Add activity file reading to daemon heartbeat
2. Replace fixed ticker with dynamic interval calculation
3. Reset to base interval when activity is fresh

No counter tracking needed - pure discovery from single timestamp.

CROSS-RIG DEPENDENCY: Also requires beads:bd-v8ku (assigned to beads/crew/dave)


Digest: mol-deacon-patrol

Patrol 20: Final patrol, handing off


Protocol message specification

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


Digest: mol-deacon-patrol

Patrol 119: All healthy


Merge: rictus-1767141956287

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


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Second-Order Monitoring

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

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


Move disk 1: B → C

Move disk 1 from peg B to peg C. (Move 369/1023)


MR field parsing: extract structured fields from description

Parse merge-request beads to extract structured fields:
- branch: source branch name
- target: target branch (main or integration/xxx)
- source_issue: the work item being merged
- worker: who did the work
- rig: which rig
- merge_commit: (set on close)
- close_reason: (set on close)

Fields stored in description as YAML block or key: value lines.
Provide helper functions: ParseMRFields(issue) and SetMRFields(issue, fields).

Reference: docs/merge-queue-design.md#merge-request-schema


Digest: mol-deacon-patrol

Patrol 18: Routine


Compile-time vs runtime cooking

Distinguish two cooking modes: 1) Compile-time: produces proto with variable placeholders, for modeling/estimation/contractor handoff. 2) Runtime: produces mol with real issue IDs. Compile-time lets you pre-decompose work for untrusted executors or planning purposes.


Implement gt hooks command

New command to show all hooks across a rig.

Usage: gt hooks [rig]

Output shows:
- All polecats and their hook status
- Witness hook status
- Refinery hook status
- Crew member hook status
- Progress bars for attached molecules


Move disk 1: A → B

Move disk 1 from peg A to peg B. (Move 85/1023)


Move disk 3: A → B

Move disk 3 from peg A to peg B. (Move 124/1023)


Move disk 2: B → A

Move disk 2 from peg B to peg A. (Move 190/1023)


Design: MQ Priority Objective Function

Define the priority scoring function for merge queue ordering.

## Inputs
- Convoy creation time (age)
- Epic/issue priority (P0-P4)
- Conflict retry count
- MR submission time

## Output
- Numeric score (higher = process first)

## Considerations
- Prevent convoy starvation (old convoys escalate)
- Respect epic priority (P0 bugs > P4 backlog)
- Penalize thrashing (multiple conflict cycles)
- Deterministic (same inputs = same score)

## Deliverable
- Go function: `func ScoreMR(mr MergeRequest) float64`
- Unit tests with edge cases
- Documentation of factor weights


CI integration tests for install/setup flow

Add automated tests that validate the complete setup flow catches regressions like #19 (wrong prefix).

## Scope
- Fresh gt install validation
- Rig setup validation
- Beads initialization and routing
- Basic polecat lifecycle

## Non-goals (for now)
- Full Claude Code integration tests (mock or skip)
- Performance testing
- Multi-rig scenarios

## Success criteria
- Tests run on PRs touching install/rig/beads code
- Catch prefix mismatches, redirect errors, route config issues
- < 60s runtime to not slow CI

GitHub: #20


Digest: mol-deacon-patrol

Patrol 215: All nominal


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.


Digest: mol-deacon-patrol

Patrol 216: All nominal


Digest: mol-deacon-patrol

Patrol cycle 8: all healthy


Digest: mol-deacon-patrol

Patrol cycle 14: All healthy


mol-deacon-patrol


Move disk 1: C → A

Move disk 1 from peg C to peg A. (Move 425/1023)


bd mol search: Find formulas using GitHub API

Search for formulas across GitHub.

Usage: bd mol search <query>

Should:
- Use GitHub API to search repos with formula.json
- Filter by topics (e.g., beads-formula)
- Display results with descriptions and stars
- Support pagination


Move disk 3: A → B

Move disk 3 from peg A to peg B. (Move 364/1023)


Digest: mol-deacon-patrol

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


Merge: dementus-mjw46vz4

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


Witness Plugin System

Patrol extensions via molecule bonding.

## Core Insight

Plugins ARE molecules. No separate format needed.

## How It Works

```
mol-witness-patrol
    │
    ├── survey-workers
    │
    ├── plugin-run ←── bonds registered plugin molecules
    │       │
    │       ├── mol-mood-check (if registered)
    │       ├── mol-security-scan (if registered)
    │       └── mol-custom-X (user-installed)
    │
    └── aggregate (WaitsFor: all-children)
```

## Plugin Molecule Structure

A plugin is just a molecule proto with specific labels:

```json
{
  "id": "mol-mood-check",
  "title": "Polecat Mood Check",
  "description": "Assess polecat emotional state from output. Vars: {{polecat_name}}, {{captured_output}}",
  "labels": ["template", "plugin", "witness", "tier:haiku"],
  "issue_type": "task"
}
```

Labels encode metadata:
- `plugin` - marks as bondable plugin
- `witness` / `deacon` / `refinery` - which patrol can use it
- `tier:haiku` / `tier:sonnet` - model tier hint

## Registration

Plugins registered in rig config or molecules.jsonl:

```bash
# Install from Mol Mall
bd mol install mol-mood-check

# Or add to ~/.beads/molecules.jsonl manually
```

## Execution

The `plugin-run` step in patrol:

```bash
# For each registered plugin molecule matching this patrol:
bd mol bond mol-mood-check $PATROL_WISP \
  --ref mood-{{polecat_name}} \
  --var polecat_name=$POLECAT \
  --var captured_output="$OUTPUT"
```

## CLI

- `bd mol list --label plugin` - List available plugins
- `bd mol install <id>` - Install from Mol Mall
- `gt patrol plugins <role>` - Show plugins for a patrol role

## Benefits

- No YAML schema to maintain
- No separate plugin loading code
- Plugins are versioned, synced, auditable (they are beads)
- Distribution via Mol Mall (molecules.jsonl registry)
- Same {{var}} substitution as all molecules


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Second-Order Monitoring

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

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


Digest: mol-deacon-patrol

Patrol 16: all clear


Move disk 1: A → B

Move disk 1 from peg A to peg B. (Move 601/1023)


Test Patrol Parent

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

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

Original description:
Test parent for Christmas Ornament pattern


Digest: mol-deacon-patrol

Patrol cycle 15: All agents healthy


Verify feed signal sources emit events

Layer 4: Verify that all required sources emit events to the activity feed.

Sources that should emit events:
- gt sling → TypeSling event
- bd create/update/close → BeadMutation event
- gt mail send → TypeMail event

Check internal/events package and verify event emission in each command.


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Idle Town Principle

**The Deacon should be silent/invisible when the town is healthy and idle.**

- Skip HEALTH_CHECK nudges when no active work exists
- Sleep 60+ seconds between patrol cycles (longer when idle)
- Let the feed subscription wake agents on actual events
- The daemon (10-minute heartbeat) is the safety net for dead sessions

This prevents flooding idle agents with health checks every few seconds.

## Second-Order Monitoring

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

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


Code review: session health monitoring (gt-i7wcn)

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


gt-gastown-polecat-valkyrie

gt-gastown-polecat-valkyrie

role_type: polecat
rig: gastown
agent_state: done
hook_bead: null
role_bead: gt-polecat-role
cleanup_status: has_uncommitted
active_mr: gt-i9pl9
notification_level: null


Move disk 1: A → B

Move disk 1 from peg A to peg B. (Move 961/1023)


Digest: mol-deacon-patrol

Patrol 12 complete


Cost tracking v2: Use beads instead of JSONL

## Overview

Revise cost tracking to use beads as the storage layer instead of `~/.gt/costs.jsonl`. This aligns with Gas Town's "Discover, Don't Track" principle and keeps beads as the single source of truth.

## Dependencies

- **bd-vii9**: Agent identity beads (service polecats) - provides the parent beads for sessions

## Model

### Agent Identity Bead (type: agent)

Created on first use of a polecat/agent name. Persists across session lifecycles.

```yaml
id: gt-gastown-polecat-toast
type: agent
title: "Agent: gt-gastown-polecat-toast"
status: open  # Always open (persistent identity)
metadata:
  role: polecat
  rig: gastown
  name: toast
labels:
  total_cost: "4.56"       # Cache for fast queries
  session_count: "12"
  last_active: "2026-01-02"
```

### Session Event Bead (type: session)

Created when a session ends (via Stop hook).

```yaml
id: gt-sess-abc123
type: session
title: "Session: toast completed gt-nrpiq"
parent: gt-gastown-polecat-toast   # Links to agent
status: closed
metadata:
  cost_usd: 1.23
  duration_seconds: 1800
  work_item: gt-nrpiq
  started_at: "2026-01-02T12:00:00Z"
  ended_at: "2026-01-02T12:30:00Z"
```

## Implementation

### 1. Update `gt costs record`

Instead of appending to JSONL:
```go
// Create session bead
bd create --type session --parent $AGENT_BEAD \
  --title "Session: $NAME completed $WORK_ITEM" \
  --metadata cost_usd=1.23,duration_seconds=1800,...

// Update agent bead labels (cache)
bd label $AGENT_BEAD total_cost=$NEW_TOTAL session_count=$NEW_COUNT
```

### 2. Update `gt costs` queries

Replace JSONL parsing with bd queries:
```bash
# Today's sessions
bd list --type=session --since=today

# Sessions for agent
bd list --type=session --parent=gt-gastown-polecat-toast

# All agents with costs
bd list --type=agent
```

### 3. Remove JSONL support

- Remove `~/.gt/costs.jsonl` writes
- Remove JSONL parsing code
- Migration: optionally import existing JSONL into beads

## Queries Supported

| Command | Implementation |
|---------|---------------|
| `gt costs` | Live tmux scrape (unchanged) |
| `gt costs --today` | `bd list --type=session --since=today` + sum |
| `gt costs --week` | `bd list --type=session --since=week` + sum |
| `gt costs --by-role` | `bd list --type=agent` + group by role label |
| `gt costs --by-rig` | `bd list --type=agent` + group by rig label |

## Benefits

- Single source of truth (beads)
- Git-backed audit trail
- Queryable via `bd list`
- Syncs with `bd sync`
- Follows "Events as State History, Labels as Cache" pattern

## Non-goals

- Per-message cost tracking (too granular)
- Real-time cost streaming (agent limitation)

## References

- GH #24 (original cost tracking issue)
- bd-vii9 (agent identity beads)
- docs/agent-compatibility.md


Digest: mol-deacon-patrol

Patrol 17: All healthy


Move disk 1: C → A

Move disk 1 from peg C to peg A. (Move 131/1023)


Digest: mol-deacon-patrol

Patrol 1: All healthy - Mayor OK, 2 witnesses OK, 2 refineries OK, 1 polecat active (furiosa). No lifecycle requests or orphans.


gt-gastown-polecat-toast

gt-gastown-polecat-toast

role_type: polecat
rig: gastown
agent_state: running
hook_bead: gt-38doh
role_bead: gt-polecat-role
cleanup_status: clean
active_mr: gt-4bi8o
notification_level: null


Burn-or-loop step execution

Fix step completion detection in patrol formulas. Ensure done() properly clears the molecule and triggers burn. Currently wisps accumulate because this step doesn't complete.


os.Exit() calls in library code prevent proper error handling

internal/cmd/mail.go and other files have os.Exit() calls.

Issues:
- Hard to test
- Prevents graceful shutdown
- Can lose unsaved state
- Doesn't compose well in library code

Should return errors instead of calling os.Exit() directly.
Let main() decide how to exit.


Extract timing constants to constants package

Extract hardcoded timing values to named constants.

## Files to modify
- internal/constants/constants.go (add constants)
- internal/cmd/start.go (use constants)
- internal/tmux/tmux.go (use constants)

## Implementation
Add to constants.go:
```go
const (
    ShutdownNotifyDelay  = 500 * time.Millisecond
    ClaudeStartTimeout   = 15 * time.Second
    ShellReadyTimeout    = 5 * time.Second
    DefaultDebounceMs    = 100
    DefaultDisplayMs     = 5000
)
```

## Acceptance criteria
- [ ] 5 timing constants added to constants.go
- [ ] start.go uses ShutdownNotifyDelay, ClaudeStartTimeout, ShellReadyTimeout
- [ ] tmux.go uses DefaultDebounceMs, DefaultDisplayMs
- [ ] go build ./... passes
- [ ] go test ./... passes


Digest: mol-deacon-patrol

Patrol 14: all clear


Move disk 1: C → A

Move disk 1 from peg C to peg A. (Move 797/1023)


Timed Beads: Scheduled recurring work

## Summary

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

## Schema Extension

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

## Daemon Integration

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

## Use Cases

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

## Interaction with Pinned Beads

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


Digest: mol-deacon-patrol

Patrol cycle 5: All healthy


CLI: all command for batch polecat operations

Batch operations across multiple polecats.

## Commands

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

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

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

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

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

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

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

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

## New File
internal/cmd/all.go

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

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


Outpost configuration: YAML config and OutpostManager

## Overview

Configuration file for outposts and manager to load/track them.

## Config File

`~/ai/config/outposts.yaml`:

```yaml
outposts:
  - name: local
    type: local
    max_workers: 4

  - name: gce-burst
    type: ssh
    host: 10.0.0.5
    user: steve
    ssh_key: ~/.ssh/gce_worker
    town_path: /home/steve/ai
    max_workers: 8

  - name: cloudrun-burst
    type: cloudrun
    project: my-gcp-project
    region: us-central1
    service: gastown-worker
    max_workers: 20
    cost_cap_hourly: 5.00

policy:
  default_preference: [local, gce-burst, cloudrun-burst]
  overrides:
    - condition: "priority >= P3"
      prefer: cloudrun-burst
```

## OutpostManager

```go
type OutpostManager struct {
    outposts map[string]Outpost
    policy   AssignmentPolicy
}

func NewOutpostManager(configPath string) (*OutpostManager, error)
func (m *OutpostManager) Get(name string) (Outpost, bool)
func (m *OutpostManager) List() []Outpost
func (m *OutpostManager) SelectOutpost(issue Issue) Outpost
```

## Files

- `internal/outpost/manager.go`
- `internal/outpost/config.go` (extend)
- `internal/outpost/policy.go`

Depends on: gt-9a2.1 (interfaces)


Merge: gt-5af.5

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


Digest: mol-deacon-patrol

Patrol 20: All healthy, handoff threshold reached


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

Patrol 18


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Second-Order Monitoring

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

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


Digest: mol-deacon-patrol

Patrol cycle 77: All healthy


Doctor check: Worker health and stuck detection

Detect and report stuck workers via gt doctor.

## Checks

### WorkerHealthCheck
- List all active workers (polecats with state=working)
- Check last activity timestamp for each
- Flag as potentially stuck if no progress for configurable threshold (default: 30 min)
- Check if Witness is running for the rig
- Verify Witness last heartbeat time

### Stuck Detection Criteria
- Polecat state=working but session not running
- Polecat state=working but output unchanged for threshold
- Witness not responding to health checks
- Multiple polecats in same rig all stuck

## Output

```
[WARN] Workers in rig 'wyvern' may be stuck:
  - Toast: working for 45m, no recent output
  - Capable: working for 52m, session not found
  - Witness: last heartbeat 20m ago

  Suggestions:
  - gt witness status wyvern
  - gt capture wyvern/Toast 50
  - gt stop --rig wyvern (kill all)
```

## Auto-Fix

Cannot auto-fix stuck workers (risk of data loss), but can:
- Restart Witness daemon if crashed
- Send warning mail to Mayor


max Handoff


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Idle Town Principle

**The Deacon should be silent/invisible when the town is healthy and idle.**

- Skip HEALTH_CHECK nudges when no active work exists
- Sleep 60+ seconds between patrol cycles (longer when idle)
- Let the feed subscription wake agents on actual events
- The daemon (10-minute heartbeat) is the safety net for dead sessions

This prevents flooding idle agents with health checks every few seconds.

## Second-Order Monitoring

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

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


Polecat Arm (arm-toast)

Single polecat inspection and action cycle.

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

## Variables

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

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

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

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

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

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

Calculate: minutes since last activity.
Needs: capture

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

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

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

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

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

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

Record decision and rationale.
Needs: load-history

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

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

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

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

**none**: No action needed.

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

## Output

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

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


mol-deacon-patrol


Digest: mol-deacon-patrol

Patrol cycle 9: All healthy


Move disk 3: C → A

Move disk 3 from peg C to peg A. (Move 740/1023)


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.


crew_add.go: Agent bead ID uses wrong format

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

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

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

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

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

Fix: Change line 84 to:

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


Refactor gt swarm to use beads backing

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

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

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

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

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


Move disk 2: B → A

Move disk 2 from peg B to peg A. (Move 646/1023)


Move disk 1: B → C

Move disk 1 from peg B to peg C. (Move 297/1023)


mol-refinery-patrol

Merge queue processor patrol loop.

The Refinery is the Engineer in the engine room. You process polecat branches, merging them to main one at a time with sequential rebasing.

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

## Merge Flow

The Refinery receives MERGE_READY mail from Witnesses when polecats complete work:

```
Witness                    Refinery                      Git
   │                          │                           │
   │ MERGE_READY              │                           │
   │─────────────────────────>│                           │
   │                          │                           │
   │                    (verify branch)                   │
   │                          │ fetch & rebase            │
   │                          │──────────────────────────>│
   │                          │                           │
   │                    (run tests)                       │
   │                          │                           │
   │                    (if pass)                         │
   │                          │ merge & push              │
   │                          │──────────────────────────>│
   │                          │                           │
   │ MERGED                   │                           │
   │<─────────────────────────│                           │
   │                          │                           │
```

After successful merge, Refinery sends MERGED mail back to Witness so it can
complete cleanup (nuke the polecat worktree).


Merge: nux-mjui76op

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


Digest: mol-deacon-patrol

Patrol complete: 20 cycles, handing off


End-of-cycle inbox hygiene

Verify inbox hygiene before ending patrol cycle.

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

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

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

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

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

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


Witness Arm Bonding

# Witness Patrol Redesign

> **Status**: Design pivoted from Christmas Ornament to linear patrol (Dec 2024)

## Original Problem

Witness needs to monitor and intervene on multiple polecats. Original design proposed "Christmas Ornament" pattern with dynamic arms per polecat and fanout gates.

## Design Pivot: Why Christmas Ornament Was Wrong

The Christmas Ornament pattern (dynamic mol-polecat-arm per worker) felt un-Gas-Town:

1. **Explicit state tracking**: Nudge counts, timestamps, per-polecat state
2. **Complex machinery**: Dynamic bonding, fanout gates, aggregation
3. **Against philosophy**: Gas Town prefers discovery over tracking, events over state

**Key insight**: With step-based polecat sessions (`gt mol step done` restarts session each step), polecats are either working a step or starting a step. "Nudge counts across sessions" becomes less meaningful.

## New Design: Linear Patrol + Task Tool Parallelism + Cleanup Wisps

### Patrol Shape (Deacon-style)

```
inbox-check -> process-cleanups -> check-refinery -> survey-workers -> context-check -> loop
```

No dynamic arms. No fanout gates. Linear and simple.

### Key Changes

| Aspect | Old (Christmas Ornament) | New (Linear Patrol) |
|--------|--------------------------|---------------------|
| Per-polecat inspection | mol-polecat-arm bonded dynamically | Task tool subagents within survey-workers |
| State tracking | Persistent nudge counts in handoff bead | Fresh observation each cycle (discover from beads timestamps) |
| Cleanup queue | Explicit list in patrol state | Cleanup wisps (finalizer pattern) |
| Parallelism | Molecule arms (fanout gate) | Task tool subagents |
| Aggregation | waits_for: all-children | Task tool returns |

### The Finalizer Pattern (Cleanup Wisps)

When POLECAT_DONE arrives, Witness creates a cleanup wisp:
```bash
bd create --wisp --title "cleanup:ace" --labels cleanup,polecat:ace
```

The wisp's existence IS the pending cleanup. Witness processes these in `process-cleanups` step:
- Verify git clean, issue closed, commits exist
- Kill session, remove worktree
- Burn the wisp

Failed cleanups? Leave wisp, retry next cycle. GC-style finalization.

### Task Tool Parallelism

Instead of molecule arms, use Claude's Task tool for parallel polecat inspection:

```markdown
## survey-workers step

For each polecat, launch a Task tool subagent:
- Capture tmux state
- Assess working/idle/error/done
- Check beads for step progress
- Decide and execute action (nudge/escalate/none)

Task tool handles parallelism. No molecule machinery needed.
```

## Implementation

- [x] Draft mol-witness-patrol-v2.formula.toml (linear patrol)
- [ ] Test new patrol formula
- [ ] Deprecate mol-polecat-arm
- [ ] Remove fanout gate dependency

## Files

- `.beads/formulas/mol-witness-patrol-v2.formula.toml` - New linear patrol
- `.beads/formulas/mol-witness-patrol.formula.toml` - Old Christmas Ornament (to deprecate)

## Success Criteria

- Witness patrols work with 3+ polecats using Task tool parallelism
- Cleanup wisps correctly track pending cleanups
- No persistent nudge state - fresh observation each cycle
- Simpler, more Gas Town-y design


Move disk 1: A → B

Move disk 1 from peg A to peg B. (Move 301/1023)


Formula cycle detection during cooking

Detect and error on circular extends chains during bd cook. E.g., if formula A extends B extends A, cooking should fail with clear error message pointing to the cycle.


Digest: mol-deacon-patrol

Patrol cycle 1: All agents healthy. Processed 14 inbox messages, archived status updates. Witness and Refinery running. No orphans, no cleanup needed.


Move disk 5: B → C

Move disk 5 from peg B to peg C. (Move 144/1023)


Digest: mol-deacon-patrol

Patrol 19


Move disk 4: B → A

Move disk 4 from peg B to peg A. (Move 328/1023)


inbox-check

Handle callbacks from agents. Check gt mail inbox, process lifecycle requests.


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 20: Final before handoff, all healthy


Digest: mol-deacon-patrol

Patrol 2: All healthy, no messages


Digest: mol-deacon-patrol

Patrol cycle 18: all healthy


Work on gt-role-template: Refine witness/CLAUDE.md role t...

Work on gt-role-template: Refine witness/CLAUDE.md role template. See issue for details. Run 'bd show gt-role-template' to see the full issue.


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Second-Order Monitoring

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

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


Witness: close arm when polecat completes

When witness cleans up a polecat, close its mol-polecat-arm issue.

## Changes to witness/manager.go

In cleanupPolecat():
1. Get arm ID from handoffState.WorkerStates[name].ArmID
2. If exists, call: bd close {armID} --reason='polecat cleaned up'
3. Clear ArmID from handoff state

## Arm Close Reasons

- 'polecat cleaned up' - normal completion
- 'polecat killed - stuck' - killed due to inactivity
- 'polecat killed - escalated' - killed after Mayor escalation

## State Update

The arm's description could be updated with final outcome before closing.
Needs: gt-59zd.4


attached_args: Remove os.Exit calls from Cobra RunE handlers

Replace os.Exit() calls with proper error returns in Cobra commands.

## Files to modify
- internal/cmd/mail.go (lines 546, 554, 561, 808-812)
- Any other files with os.Exit in RunE

## Problem
Some RunE handlers call os.Exit() directly:
```go
RunE: func(cmd *cobra.Command, args []string) error {
    ...
    os.Exit(1)  // BAD: bypasses Cobra error handling
}
```

## Fix
Return errors instead:
```go
RunE: func(cmd *cobra.Command, args []string) error {
    ...
    return fmt.Errorf("not in workspace")
}
```

## Acceptance criteria
- [ ] No os.Exit calls inside RunE functions
- [ ] Errors returned with proper context
- [ ] grep -n 'os.Exit' internal/cmd/*.go shows no RunE matches
- [ ] go build ./... passes
- [ ] Commands still exit with correct codes


gt witness/refinery start should have 'ensure' semantics (kill zombie if needed)

## Problem

`gt witness start <rig>` fails if the tmux session already exists:
```
⚠ Witness session already running
  Use 'gt witness attach' to connect
```

But the session might be a zombie (tmux alive, Claude dead). User has to manually:
1. `gt witness stop <rig>`
2. `gt witness start <rig>`

Or use `gt witness restart <rig>` which works but isn't intuitive.

## Proposal

`gt witness start` should have 'ensure running' semantics:

1. If no session exists → create new session
2. If session exists and healthy → do nothing (already running)
3. If session exists but zombie → kill and recreate

This makes `start` idempotent and safe to run repeatedly.

## Implementation

```go
func (w *Witness) Start(rig string) error {
    sessionName := witnessSessionName(rig)

    if w.tmux.HasSession(sessionName) {
        if w.isHealthy(sessionName) {
            return nil  // Already running and healthy
        }
        // Zombie - kill it
        w.tmux.KillSession(sessionName)
    }

    // Create fresh session
    return w.createSession(rig)
}
```

## Alternatives

- Keep current behavior, just improve error message: 'Session exists but appears dead, use restart'
- Add --force flag: `gt witness start --force <rig>`

## Recommendation

Make `start` idempotent. It's the principle of least surprise.


Agent state lifecycle incomplete for polecats

## Problem

The witness patrol formula (mol-witness-patrol.formula.toml) expects polecats to self-report states:
- running
- idle
- stuck
- done

But looking at the code, the only state transitions that actually happen are:

1. **spawning** - Set when polecat is created (polecat/manager.go:170)
2. **running** - Set when agent runs `gt prime` (prime.go:112)
3. **dead** - Set by daemon when agent goes unresponsive (daemon/lifecycle.go:647)

**Missing transitions:**
- `stuck` - No code path exists for agents to report this
- `done` - No code path exists for agents to report this
- `idle` - Only set for infrastructure agents, never for polecats

## Impact

The witness cannot rely on agent_state to detect stuck or done polecats, contradicting the ZFC principle stated in the formula.

## Found in commit

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

## Suggested fix

Add code paths for polecats to self-report:
1. `gt done` should update agent_state to "done"
2. When stuck (detected how?), agent should update to "stuck"
3. Consider if "idle" makes sense for polecats (no current work)


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.


Digest: mol-deacon-patrol

Patrol 9: quick pass


Digest: mol-deacon-patrol

Patrol #4: Stable


P0: Multiple agents can claim same worker identity

Multiple Claude Code sessions running simultaneously all think they are 'dave' on beads/crew/dave. No detection or prevention of identity collision. This breaks the single-agent-per-worker assumption.

## Fix Implemented

1. **Lock Package** (`internal/lock/lock.go`):
   - PID-based lockfile at `<worker>/.gastown/agent.lock`
   - Contains PID, timestamp, session ID, hostname
   - Stale lock detection (checks if owning PID is dead)

2. **Prevention in gt prime**:
   - Workers (crew/polecat) acquire identity lock before loading context
   - If another live process holds the lock, prime fails with clear error
   - Shows lock holder details and resolution steps

3. **Detection with gt agents**:
   - `gt agents check` - scans for collisions and stale locks
   - `gt agents fix` - cleans stale locks
   - JSON output available for patrol tooling

4. **Correction in gt doctor**:
   - New `identity-collision` check
   - `gt doctor --fix` cleans stale locks


Implement gt harness create command

Add scaffolding command to create a new harness:
- gt harness create [path]
- Creates config/, mayor/, .beads/redirect (optional)
- Optionally initializes git
- Generates CLAUDE.md with Mayor role
- Could also offer a template repo alternative


Digest: mol-deacon-patrol

Patrol 2: all agents healthy, no issues


Move disk 2: C → B

Move disk 2 from peg C to peg B. (Move 798/1023)


Digest: mol-deacon-patrol

Patrol 8: all healthy


Digest: mol-deacon-patrol

Patrol 36: rictus removed from rig


Merge: gt-si8rq.7

branch: polecat/nux-mjxkssaw
target: main
source_issue: gt-si8rq.7
rig: gastown
agent_bead: gt-gastown-polecat-nux


Digest: mol-deacon-patrol

Patrol 4: Nominal


Move disk 2: A → C

Move disk 2 from peg A to peg C. (Move 926/1023)


gt shutdown should fully cleanup polecats (worktrees, branches, inboxes)

Current gt shutdown only kills tmux sessions but leaves:

1. Git worktrees in polecats/ directory
2. Polecat branches (polecat/<name>)
3. Inbox messages
4. Beads assignee state

This causes stale polecats to be reused on next startup.

## Expected Behavior

gt shutdown should:
1. Kill all polecat tmux sessions (current behavior)
2. For each polecat with StateIdle or StateDone:
   - Remove worktree
   - Delete branch
   - Clear inbox
3. For polecats with uncommitted work:
   - REFUSE to clean up
   - Report which polecats have uncommitted changes
   - Require --force or --nuclear to proceed

## Current Code

- start.go:runImmediateShutdown() only calls t.KillSession()
- Witness cleanupPolecat() does full cleanup but isn't called by shutdown

## Fix

Either:
1. Call Witness cleanup for each polecat during shutdown
2. OR add rig.ShutdownPolecats() that does the full cleanup


Digest: mol-deacon-patrol

Patrol complete: all agents healthy, no mail, no orphans, no gates


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


Move disk 4: A → C

Move disk 4 from peg A to peg C. (Move 584/1023)


Move disk 6: A → C

Move disk 6 from peg A to peg C. (Move 800/1023)


Digest: mol-deacon-patrol

Patrol 3: All healthy, no changes


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 5: Nominal


gt crew refresh: Context cycling with handoff

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


Digest: mol-deacon-patrol

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


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Second-Order Monitoring

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

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


Digest: mol-deacon-patrol

Patrol 11


load-context

Run gt prime and bd prime. Verify issue assignment.
Check inbox for any relevant messages.

Read the assigned issue (gt-1wmw) and understand the requirements.
Identify any blockers or missing information.


mol-deacon-patrol


Merge: slit-mjwohabk

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


Digest: mol-deacon-patrol

Patrol 17: routine


Digest: mol-deacon-patrol

Patrol 15: routine


Move disk 2: B → A

Move disk 2 from peg B to peg A. (Move 994/1023)


Refactor: Extract common manager creation boilerplate

Five nearly identical functions exist for creating managers:
- getPolecatManager (polecat.go:241)
- getSessionManager (session.go:183)
- getCrewManager (crew_helpers.go:44)
- getRefineryManager (refinery.go:116)
- getWitnessManager (witness.go:102)

All follow the same pattern: find workspace, load config, get rig, create manager. Should extract to a common helper that takes a factory function.


Move disk 1: C → A

Move disk 1 from peg C to peg A. (Move 971/1023)


Digest: mol-deacon-patrol

Patrol cycle 17: All healthy


Agent-centric dashboard view (gt dashboard)

Charmbracelet TUI for gt feed with dashboard + stream layout.

## Layout (horizontal split)

**Top panel: Agent Tree (role/town view)**
- Shows EVERY agent organized by role
- Each agent shows their MOST RECENT activity inline
- At a glance: who is doing what RIGHT NOW
- Collapsible sections

**Bottom panel: Event Stream (chronological feed)**
- Full scrollable history of events
- Most recent at top
- More detail than the tree view
- This is what you scroll through

## Visual
```
+-------------------------------------------------------------+
| GT Feed                                    Filter: all      |
+-------------------------------------------------------------+
| gastown/                           <- AGENT TREE (top)      |
|   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                     |
+-------------------------------------------------------------+
| [10:30] Toast: Received molecule gt-xyz                     |
| [10:28] witness: Nudged polecat-3 after 5m idle             |
| [10:25] refinery: Merged PR #123                            |
| ...                                        <- EVENT STREAM  |
+-------------------------------------------------------------+
| j/k: scroll  /: search  f: filter  q: quit  ?: help         |
+-------------------------------------------------------------+
```

## Why this layout?
- Top answers: what is everyone doing?
- Bottom answers: what just happened?
- Together: complete situational awareness

## Replaces
- gt feed (currently just wraps bd activity)
- gt dashboard task merges into this

## Tech
- bubbletea Model with two viewports
- Tab switches focus between tree/stream
- j/k scrolls focused panel


Move disk 2: C → B

Move disk 2 from peg C to peg B. (Move 606/1023)


Digest: mol-deacon-patrol

Patrol 16: All healthy, mayor handoff observed (not for deacon)


Digest: mol-deacon-patrol

Patrol cycle 5: All 6 agents healthy, gastown queue cleared


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


Digest: mol-deacon-patrol

Patrol #10: All healthy


Digest: mol-deacon-patrol

Patrol 11: healthy


Computed range expansion (for-each over expressions)

Support for-each expansion over computed ranges, not just static lists:

for-each:
  var: move_num
  range: "1..2^{disks}"  # Computed at cook time

This enables formulas like Towers of Hanoi where the step count is a function of input variables. The range expression is evaluated during cooking.

Related: towers-of-hanoi.formula.yaml demonstrates the need.
Depends on: gt-8tmz.8 (Runtime dynamic expansion)


Polecat CLAUDE.md update for hook execution

Update polecat role CLAUDE.md to include hook execution instructions.

## Key Additions

### Startup Protocol

```markdown
## Startup Protocol

When you wake up:

1. **Check your hook first**
   Run: gt prime
   This shows your assigned work.

2. **If hook has molecule**
   You are running a workflow. Execute the current step.
   When done: bd mol advance <mol-id>

3. **If hook has slung bead**
   Work on that specific issue.
   Claim it: bd update <id> --status=in_progress

4. **If hook empty**
   Wait for assignment via mail or spawn.
```

### Work Completion

```markdown
## Completing Work

When you finish your assigned issue:

1. Commit changes: git add && git commit -m "description (issue-id)"
2. Push branch: git push -u origin <branch>
3. Create MR bead: bd create "Merge: <issue-id>" --type=merge-request
4. Close issue: bd close <issue-id> --reason "Fixed in commit abc123"
5. Sync: bd sync
6. Signal done: gt mail send witness/ -s "LIFECYCLE: Done" -m "Completed <issue-id>"
```

### Exit States

```markdown
## Exit States

When finishing, signal your state:

- COMPLETED: Work done successfully
- BLOCKED: Cannot proceed, need help
- ESCALATE: Problem beyond your scope
- HANDOFF: Passing to successor
```

## File

templates/polecat/CLAUDE.md


Implement pinned beads for handoff state

Add pinned bead support to beads:
- Pinned beads never close, only update
- Use for persistent state like Refinery handoffs
- bd create --pinned flag
- bd list --pinned to find them
- Update description to change state


mol-deacon-patrol


Migrate from .claude/commands/ to .claude/skills/ format

## Summary

Claude Code v2.0+ deprecated `.claude/commands/` in favor of `.claude/skills/`.
All gastown workers currently have `.claude/commands/handoff.md` which no longer loads.

## Current State

- Workers have `.claude/commands/handoff.md` (deprecated, not loading)
- `/handoff` skill is unavailable to agents

## Fix Required

1. Create `.claude/skills/handoff/SKILL.md` with proper frontmatter format
2. Remove deprecated `.claude/commands/handoff.md` files
3. Update worker setup process to use skills format

## Skill Format

```yaml
---
name: handoff
description: >
  Hand off to a fresh Claude session. Work continues from hook.
allowed-tools: "Bash(gt handoff:*),Bash(gt mail send:*)"
version: "1.0.0"
---
```

## Affected Locations

- ~/gt/gastown/crew/*/claude/commands/handoff.md (all crew workers)
- ~/gt/gastown/mayor/rig/.claude/commands/handoff.md
- ~/gt/gastown/refinery/rig/.claude/commands/handoff.md

## Reference

- beads already migrated: `.claude/skills/handoff/SKILL.md`
- User-wide skill added: `~/.claude/skills/handoff/SKILL.md`


File locking for concurrent access

Add file locking for concurrent access safety.

## At-Risk Files
- .gastown/swarms.json (or per-swarm state.json)
- .gastown/refinery.json
- polecats/<name>/state.json
- inbox.jsonl files

## Go File Locking
Use syscall.Flock for advisory locking:
```go
type FileLock struct {
    file *os.File
}

func AcquireLock(path string, timeout time.Duration) (*FileLock, error) {
    f, err := os.OpenFile(path+".lock", os.O_CREATE|os.O_RDWR, 0644)
    if err != nil {
        return nil, err
    }
    // Use syscall.Flock with timeout
}

func (l *FileLock) Release() error
```

## Integration Pattern
```go
func (m *Manager) saveState(ref *Refinery) error {
    lock, err := AcquireLock(m.stateFile(), 5*time.Second)
    if err != nil {
        return fmt.Errorf("could not acquire lock: %w", err)
    }
    defer lock.Release()

    // Read-modify-write cycle
}
```

## New Package
internal/filelock/
├── lock.go     # FileLock, AcquireLock
└── lock_test.go

## Apply To
- internal/refinery/manager.go: loadState/saveState
- internal/cmd/swarm.go: SwarmStore
- internal/mail/mailbox.go: Append, rewrite
- internal/polecat/manager.go: state operations

## Timeout Handling
Default 5 second timeout. Return error if lock not acquired.

## Acceptance Criteria
- [ ] Lock files created (.lock extension)
- [ ] Timeout on lock contention
- [ ] All state files protected
- [ ] Locks released on error paths


Digest: mol-deacon-patrol

Cycle 11: quiet


Move disk 3: C → A

Move disk 3 from peg C to peg A. (Move 236/1023)


Slim down rig root config.json to identity only

Rig root config.json should only contain identity:
- type, version, name, git_url, beads.prefix, created_at
- Remove any behavioral config (move to settings/config.json)
- Update RigConfig type to separate identity from settings
- Ensure loader reads identity from root, settings from settings/


Molecule execution support for polecats and crew

Enable agents to run bonded molecules through the full lifecycle.

## The Model
1. BOND - bd mol bond <template> --assignee <identity>
   Creates concrete issues, assigns root to agent

2. DISCOVER - Agent finds assigned molecules via bd ready
   DAG structure shows unblocked steps

3. WORK - Agent works through DAG, closing steps as done
   Can delegate children to lower-tier agents (haiku)

4. SURVIVE - Agent dies → beads persist
   Any agent resumes from DAG state

5. SUPERVISE - Witness monitors for stalled molecules
   Nudges owner or reassigns if dead

## Questions to Resolve
- Seed node terminology: seed vs root vs pole vs nucleus
- Assignee inheritance: single owner vs delegation model
- Stall detection: heartbeat vs activity timeout vs session monitoring

## Implementation
- Polecat startup: check for assigned molecules
- Polecat work loop: follow molecule DAG
- Witness: monitor molecule progress, detect stalls
- Mayor: can assign molecules, handle escalations

## Depends On
- beads: bd mol bond command (bd-usro in beads repo)


Move disk 7: B → C

Move disk 7 from peg B to peg C. (Move 576/1023)


Move disk 1: A → B

Move disk 1 from peg A to peg B. (Move 367/1023)


Digest: mol-deacon-patrol

Patrol 2: All healthy, 12 polecats, nudged gastown (active work)


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.


gt polecat nuke: Refuse if unpushed commits or open MR

Agent prompts can be ignored. Code cannot.

`gt polecat nuke` should REFUSE to delete a polecat if:
1. Worktree has unpushed commits
2. Polecat has open MR beads
3. Polecat has work on hook

This is enforcement in code, not just instructions. The command itself should be safe.

Use existing `computeCleanupStatus()` in done.go as reference.


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)


gt polecat add should spawn with --dangerously-skip-permissions

When adding polecats via gt polecat add, the subsequent Claude session needs --dangerously-skip-permissions flag to run autonomously.

Currently:
- gt polecat add creates worktree
- tmux new-session spawns 'claude' without flags
- Polecat gets stuck at permission prompts

Needed:
- gt polecat add (or gt sling) should spawn with --dangerously-skip-permissions
- Or store a config in polecat worktree indicating autonomous mode

This is critical for swarm automation - polecats can't self-approve permissions.


Move disk 2: B → A

Move disk 2 from peg B to peg A. (Move 742/1023)


Move disk 1: C → A

Move disk 1 from peg C to peg A. (Move 329/1023)


Digest: mol-deacon-patrol

Patrol 20: All healthy, handoff triggered


load-context

Run gt prime and bd prime. Verify issue assignment.
Check inbox for any relevant messages.

Read the assigned issue (gt-qwyu) and understand the requirements.
Identify any blockers or missing information.


Update Deacon template to emphasize staying in ~/gt/deacon directory

The Deacon template should instruct the agent to stay in ~/gt/deacon/ as much as possible, and always return there after any excursion. This prevents issues with identity detection (mail, mol status) which depend on cwd.


Phase 5.1: Document ephemeral architecture

Update docs with ephemeral molecule architecture.

## Files to Update

### docs/architecture.md
- Add Ephemeral Molecules section
- Diagram: Proto → Ephemeral → Digest flow
- Explain inversion of control for summaries

### docs/molecules.md (new or update)
- Proto molecule catalog
- Ephemeral vs main beads
- Molecule lifecycle
- Summary generation guidelines

### Agent CLAUDE.md files
- Polecat: molecule workflow protocol
- Deacon: patrol cycle pattern
- Witness: patrol cycle pattern
- Refinery: patrol cycle pattern

## Key Concepts to Document

1. Everything is a molecule
2. Orchestration molecules are ephemeral
3. Only digests reach main beads
4. Agents generate their own summaries
5. Crash recovery via ephemeral persistence


gt swarm start: Does not spawn polecat sessions

gt swarm start marks swarm as 'active' but doesn't start any polecat sessions.

Repro:
1. gt swarm create gastown --epic gt-hw6 --worker Toast --worker Nux
2. gt swarm start gt-hw6
3. gt session list - shows no new sessions

Expected: Polecat sessions should start for each worker.
Actual: No sessions started, workers sit idle.


Digest: mol-deacon-patrol

Patrol 254 complete: no incidents


Digest: mol-deacon-patrol

Patrol 20: Final patrol, all healthy, handoff


Merge: dementus-mjtlqmya

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


Test Patrol for Bonding

Parent issue for mol bond CLI test


witness Handoff


Digest: mol-deacon-patrol

Patrol cycle 12: nominal


Add 'gt account add' command

Register new account: create config dir, spawn claude with CLAUDE_CONFIG_DIR set, user completes /login, add entry to accounts.yaml.


Merge: dag-mjxm10sv

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


Digest: mol-deacon-patrol

Patrol 3: quick pass, all healthy


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Idle Town Principle

**The Deacon should be silent/invisible when the town is healthy and idle.**

- Skip HEALTH_CHECK nudges when no active work exists
- Sleep 60+ seconds between patrol cycles (longer when idle)
- Let the feed subscription wake agents on actual events
- The daemon (10-minute heartbeat) is the safety net for dead sessions

This prevents flooding idle agents with health checks every few seconds.

## Second-Order Monitoring

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

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


session stop: --force flag is defined but not used


Move disk 3: A → B

Move disk 3 from peg A to peg B. (Move 988/1023)


Move disk 4: C → B

Move disk 4 from peg C to peg B. (Move 456/1023)


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Second-Order Monitoring

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

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


Merge: gt-99a

branch: polecat/Slit
target: main
source_issue: gt-99a
rig: gastown


Digest: mol-deacon-patrol

Cycle 19


Digest: mol-deacon-patrol

Patrol 50: All healthy


Digest: mol-deacon-patrol

Cycle 5: 2 acks


Digest: mol-deacon-patrol

Patrol #1: All agents healthy, no messages, no orphans


Move disk 2: A → C

Move disk 2 from peg A to peg C. (Move 662/1023)


mol-town-shutdown: Full Gas Town reset molecule

## Summary
Molecule for clean town shutdown/restart. Sling it to Mayor when ready to reboot.

## Steps
1. Clear all inboxes (witness, refinery, crew - all rigs)
2. Unhook all agents (remove stale molecule attachments)
3. Kill any active polecats
4. Stop daemon
5. Rotate/archive logs
6. bd sync + git push
7. Send Mayor handoff (what's next)
8. Restart daemon fresh

## Invocation
```
gt hook mol-town-shutdown   # attach it
# Mayor runs it on next session
```

## Related
- Patrol cleanup (continuous) vs shutdown (nuclear)
- See gt-xxx for patrol hygiene


Verify final state

All 3 disks now on peg C. Tower intact, all moves were legal.


Digest: mol-deacon-patrol

Patrol #18: Stable


Digest: mol-deacon-patrol

Patrol 20: all healthy, handoff threshold reached


mol-deacon-patrol


Move disk 3: B → C

Move disk 3 from peg B to peg C. (Move 900/1023)


Move disk 2: C → B

Move disk 2 from peg C to peg B. (Move 138/1023)


gt spawn should verify daemon is running for polecat triggering

gt spawn notifies the Deacon (via mail) that a polecat was started, expecting the Deacon to trigger it once Claude is ready. But if the daemon isn't running, the mail sits unread and the polecat never gets triggered.

## Current Behavior
1. gt spawn starts polecat session
2. gt spawn sends POLECAT_STARTED to deacon/
3. (assumes daemon will trigger polecat)

## Problem
If gt daemon isn't running, step 3 never happens and polecat sits at prompt.

## Solution
In gt spawn, after session start:
1. Check if daemon is running (gt daemon status)
2. If not running, either:
   a. Start daemon: gt daemon start
   b. Or warn user: 'Daemon not running, polecat may not auto-start'

## Alternative
The user can manually trigger with gt nudge, but automated flow should work.


Digest: mol-deacon-patrol

Patrol 7: quiet


gt sling: Make target path parsing more forgiving

Current parsing rejects valid-looking paths like 'gastown/nux' or 'gastown/polecats/nux'.

Should accept:
- gastown/nux (polecat)
- gastown/Nux (polecat, case-insensitive)
- gastown/polecats/nux (explicit)
- gastown/crew/max (crew)
- gastown (auto-spawn)

The help says 'gastown/Toast' works but it doesn't. Parser is too strict.


Digest: mol-deacon-patrol

Patrol cycle 22: All healthy, no incidents


Split PGT/GGT harness or migrate to GGT-only

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

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


Built-in molecules: engineer-in-box, quick-fix, research

Create built-in molecules as Beads issues:

## engineer-in-box

```markdown
id: mol-engineer-in-box
type: molecule
title: Engineer in a Box

Full workflow from design to merge.

## Step: design
Think carefully about architecture. Consider:
- Existing patterns in the codebase
- Trade-offs between approaches
- Testability and maintainability

Write a brief design summary before proceeding.

## Step: implement
Write the code. Follow codebase conventions.
Needs: design

## Step: review
Self-review the changes. Look for:
- Bugs and edge cases
- Style issues
- Missing error handling
Needs: implement

## Step: test
Write and run tests. Cover happy path and edge cases.
Fix any failures before proceeding.
Needs: implement

## Step: submit
Submit for merge via refinery.
Needs: review, test
```

## quick-fix

```markdown
id: mol-quick-fix
type: molecule
title: Quick Fix

Fast path for small changes.

## Step: implement
Make the fix. Keep it focused.

## Step: test
Run relevant tests. Fix any regressions.
Needs: implement

## Step: submit
Submit for merge.
Needs: test
```

## research

```markdown
id: mol-research
type: molecule
title: Research

Investigation workflow.

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

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

## Storage

Built-in molecules live in `<town>/.beads/` as regular issues.
Created during `gt install` or `bd init`.


Digest: mol-deacon-patrol

Patrol 14: All healthy


Move disk 5: B → C

Move disk 5 from peg B to peg C. (Move 720/1023)


Crew startup missing metadata injection for gt seance

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

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


Merge: rictus-1767082306179

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


Digest: mol-deacon-patrol

Patrol 15: All clear


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.


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Idle Town Principle

**The Deacon should be silent/invisible when the town is healthy and idle.**

- Skip HEALTH_CHECK nudges when no active work exists
- Sleep 60+ seconds between patrol cycles (longer when idle)
- Let the feed subscription wake agents on actual events
- The daemon (10-minute heartbeat) is the safety net for dead sessions

This prevents flooding idle agents with health checks every few seconds.

## Second-Order Monitoring

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

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


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

Patrol 8: quiet, 8 sessions healthy


mol-deacon-patrol

Mayor's daemon patrol loop.

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

## Second-Order Monitoring

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

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


gt-gastown-polecat-alpha

gt-gastown-polecat-alpha

role_type: polecat
rig: gastown
agent_state: spawning
hook_bead: null
role_bead: gt-polecat-role
cleanup_status: null


Digest: mol-deacon-patrol

Patrol 55: All healthy


Day 4.1: Implement gt polecat recycle command

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

This enables session-per-step.

Parent: gt-4a2qt


Polecats should not push branches to remote

## Current Behavior

Polecats push their branches to origin (e.g., `polecat/furiosa`), which pollutes the remote with many short-lived branches.

## Desired Behavior

Polecats should only commit locally. The Refinery handles all remote pushes:
1. Polecat works on local `polecat/<name>` branch
2. Polecat signals done (state → idle)
3. Refinery pulls from local polecat branch
4. Refinery runs tests, merges to main
5. Refinery pushes main to remote
6. If PR review needed, Refinery creates the PR

## Benefits

- Clean remote (no branch pollution)
- Clear responsibility (Refinery is the quality gate)
- Simpler cleanup (local branches deleted with worktree)
- Less noise in GitHub UI

## Trade-offs

- If polecat crashes before Refinery merges, code is lost locally
- But beads issue remains open, another polecat can redo the work
- This is acceptable for ephemeral workers

## Implementation

In polecat CLAUDE.md or landing protocol:
- Remove `git push origin HEAD` from workflow
- Replace with just `git commit` + signal done
- Refinery handles the rest


Move disk 2: C → B

Move disk 2 from peg C to peg B. (Move 186/1023)


Move disk 1: B → C

Move disk 1 from peg B to peg C. (Move 471/1023)


Remove stale migration docs from gastown-py

The gastown-py repo has migration-related documentation that is now misinformation since we have made design decisions. Remove or clearly mark as obsolete: any docs about migration paths, old architecture assumptions, or superseded designs.


Test Patrol Parent

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

Original description:
Test parent for Christmas Ornament pattern


Digest: mol-deacon-patrol


Merge: capable-mjw47ef9

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


Town root .beads has schema mismatch with bd

The .beads directory at town root (/Users/stevey/gt/.beads) has an incompatible schema:

```
Error: failed to open database: failed to initialize schema: sqlite3: SQL logic error: no such column: thread_id
```

Meanwhile, gastown/.beads (symlinked to mayor/rig/.beads) works fine.

## Impact

- gt mail inbox fails at town root
- gt handoff sends mail to broken db
- Daemon can't check its inbox

## Options

1. Delete town root .beads/beads.db and let it recreate
2. Symlink town root .beads to gastown/.beads
3. Run schema migration on existing db

## Root Cause

Likely a beads version upgrade that added thread_id column, but the town root db was created before that.


mol-deacon-patrol


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)


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.


Aggregate arm results

Collect outcomes from all polecat inspection arms.

This is a **fanout gate** - it cannot proceed until ALL dynamically-bonded
polecat arms have completed their inspection cycles.

Once all arms complete, collect their outcomes:
- Actions taken per polecat (nudge, kill, escalate, none)
- Updated nudge counts
- Any errors or issues discovered

Build the consolidated state for save-state.


Move disk 1: B → C

Move disk 1 from peg B to peg C. (Move 93/1023)


Move disk 1: C → A

Move disk 1 from peg C to peg A. (Move 791/1023)


Digest: mol-witness-patrol

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


Move disk 3: B → C

Move disk 3 from peg B to peg C. (Move 60/1023)


Merge: gt-oiv0

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


Move disk 1: B → C

Move disk 1 from peg B to peg C. (Move 771/1023)


Merge: nux-mjtua3jw

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


gt hook: Support viewing other agents' hooks

Currently `gt hook` only shows your own hook. Would be useful to query any agent's hook:

```
gt hook show gastown/polecats/nux    # What's nux working on?
gt hook show gastown/witness         # What's the witness hooked to?
```

**Use cases**:
- Mayor checking what polecats are working on
- Witness checking polecat status
- Debugging coordination issues
- Quick status overview

**Compact output** (one line):
```
gastown/polecats/nux: gt-abc123 'Fix the widget bug' [in_progress]
```

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


Update gt doctor to check new config locations

Doctor should validate new structure:
- Check mayor/config.json exists and is valid
- Check settings/ exists for each rig
- Warn if old .gastown/ files still exist
- Offer --fix to migrate old locations to new


Witness role describes incorrect commands

prompts/roles/witness.md line 44 shows:
  gt polecat list {{ rig }}

But polecats are worktrees managed by Refinery/Mayor's clone,
not a separate polecat manager. The witness shouldn't manage
polecats directly.

Review and update witness role to match actual architecture.


Move disk 1: C → A

Move disk 1 from peg C to peg A. (Move 647/1023)


Check Witness and Refinery health

Check Witness and Refinery health for each rig.

**IMPORTANT: Idle Town Protocol**
Before sending health check nudges, check if the town is idle:
```bash
# Check for active work
bd list --status=in_progress --limit=5
```

If NO active work (empty result or only patrol molecules):
- **Skip HEALTH_CHECK nudges** - don't disturb idle agents
- Just verify sessions exist via status commands
- The town should be silent when healthy and idle

If ACTIVE work exists:
- Proceed with health check nudges below

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

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

# ONLY if active work exists - health ping (clears backoff as side effect)
gt nudge <rig>/witness 'HEALTH_CHECK from deacon'
gt nudge <rig>/refinery 'HEALTH_CHECK from deacon'
```

**Health Ping Benefit**: The nudge commands serve dual purposes:
1. **Liveness verification** - Agent responds to prove it's alive
2. **Backoff reset** - Any nudge resets agent's backoff to base interval

This ensures patrol agents remain responsive during active work periods.

**Signals to assess:**

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

**Tracking unresponsive cycles:**

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

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

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

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

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

Reset unresponsive_cycles to 0 when component responds normally.


Merge: gt-x4ad3

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


Digest: mol-deacon-patrol

Patrol 6: all healthy


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

Patrol 14: All healthy