184 Commits

Author SHA1 Message Date
mayor
a07fa8bf7f chore: bump version to v0.2.2
Some checks failed
Release / goreleaser (push) Failing after 4m11s
Release / publish-npm (push) Has been skipped
Release / update-homebrew (push) Has been skipped
Rig operational state management, unified agent startup, and extensive
stability fixes. See CHANGELOG.md for full release notes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 01:35:17 -08:00
gus
06d40925d1 feat(daemon): warn when rig wisp config missing
Logs a warning when checking rig operational state if the wisp
config file doesn't exist. This helps diagnose cases where a
parked rig unexpectedly restarts because its parked state was lost.
2026-01-07 01:34:49 -08:00
mayor
e2a211e295 docs: clarify worktree architecture and beads routing
- Remove references to non-existent .repo.git bare repo
- Clarify that polecats/refinery are worktrees from mayor/rig
- Clarify that crew/* are full clones for human developers
- Update routes.jsonl examples to match actual format
- Add explanation of why routes point to mayor/rig

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 01:00:54 -08:00
gastown/crew/george
b834bf5858 fix: restore .beads/issues.jsonl to tracking
Reverts accidental removal - this is the project issue database.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 00:46:49 -08:00
mayor
11d469edc3 fix(beads): SetupRedirect preserves tracked files (gt-fj0ol)
Previously, SetupRedirect used os.RemoveAll() which deleted all files
in .beads/ including tracked files like formulas/, README.md, config.yaml.

Now cleanBeadsRuntimeFiles() selectively removes only gitignored runtime
files (*.db, daemon.*, issues.jsonl, etc.) while preserving tracked content.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 00:40:38 -08:00
gastown/crew/george
de376007e0 chore: pre-release cleanup
- Untrack .beads/issues.jsonl (was committed despite gitignore)
- Fix README formula example: YAML → TOML syntax

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 00:31:13 -08:00
mayor
5855b525fd chore: remove pregenerated hanoi test formulas
These were test artifacts that shouldn't be in the repo.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 00:23:16 -08:00
mayor
f89c6f3693 Merge: capable-mk3qt4k3 (gt-j44ri) - require --restart-sessions flag
🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-01-07 00:21:27 -08:00
capable
ee167ae1f1 fix(doctor): require --restart-sessions flag to cycle patrol sessions (gt-j44ri)
Previously `gt doctor --fix` would automatically kill and restart patrol
sessions when fixing stale settings.json files. This was disruptive as it
interrupted work without explicit consent.

Now session cycling only happens when `--restart-sessions` is explicitly
passed along with `--fix`. Without the flag, settings files are updated
but running sessions are left alone.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 00:18:02 -08:00
Steve Yegge
a6157829d7 Merge pull request #239 from julianknutsen/fix/claude-settings-inheritance
fix: Isolate Claude settings outside source repos, unify agent startup
2026-01-07 00:10:05 -08:00
max
4a94187068 fix(cycle): town session cycling works from any directory
The isTownLevelSession() function was checking workspace.FindFromCwd()
which fails when gt cycle is invoked via tmux run-shell, since run-shell
executes from whatever directory the tmux server started in (often / or
home), not from within the Gas Town workspace.

Town-level sessions (hq-mayor, hq-deacon) can be identified by their
fixed names alone - no workspace context needed. This fix removes the
unnecessary workspace dependency, allowing C-b n/p to cycle between
Mayor and Deacon sessions as intended.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 00:06:55 -08:00
Steve Yegge
93bdf88f6e Merge pull request #238 from joshuavial/fix/sling-on-wisp-json-parse
fix(sling): parse bd mol wisp --json new_epic_id
2026-01-07 00:06:09 -08:00
mayor
59799f551c fix(doctor): only cycle patrol roles on --fix, not crew/polecats (hq-qthgye)
gt doctor --fix was killing all sessions with stale settings, including
crew and polecats that cannot auto-recover. Now only kills patrol roles
(witness, refinery, deacon, mayor) which the daemon will restart.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 23:58:30 -08:00
max
85d1e783b0 fix(polecat): don't block nuke for stale hooks pointing to closed beads (gt-jc7bq)
When checking if a polecat can be nuked, verify that any hooked bead is
still active (not closed). If the hooked bead was closed externally, the
hook is stale and should not block the nuke.

Also shows 'stale' in dry-run output when hook points to a closed bead.
2026-01-06 23:44:30 -08:00
max
bf16f7894b fix(deacon): use session package for hq- session names (gt-r38pj)
stale_hooks.go was using hardcoded 'gt-deacon' and 'gt-mayor' instead of
session.DeaconSessionName() and session.MayorSessionName() which return
'hq-deacon' and 'hq-mayor'. This caused incorrect session lookups.

Also fixes duplicate WorktreeAddFromRef method from merge conflict.
2026-01-06 23:42:03 -08:00
mayor
0dc0174b26 fix: remove duplicate WorktreeAddFromRef method
Merge artifact - two versions of the method existed. Keep the one
with sparse checkout support.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 23:41:33 -08:00
max
5f8690dbda Merge branch 'fix/polecat-start-from-origin-main' 2026-01-06 23:38:05 -08:00
max
5f206fb658 feat(statusline): show parked/docked rigs with pause emoji
Rigs in PARKED or DOCKED state now show ⏸️ instead of 🔴,
distinguishing intentionally offline rigs from failed ones.
2026-01-06 23:37:39 -08:00
max
d6add3f9b4 feat(tmux): add hq- prefix support to cycle bindings
Makes C-b n/p/a work in hq- sessions (mayor) in addition to gt- sessions.
2026-01-06 23:37:09 -08:00
nux
c25368cbe1 fix: use town root beads for Deacon patrol context (gt-sstg)
Deacon is a town-level role, so its beads should be at ctx.TownRoot
(~/gt/.beads/) not ctx.WorkDir (~/gt/deacon/). This fixes the issue
where outputDeaconPatrolContext couldn't find patrol molecules because
it was looking in the wrong location.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 23:31:49 -08:00
jack
52ef89c559 fix(sling): use bd native prefix routing instead of BEADS_DIR override
verifyBeadExists was setting BEADS_DIR to town root, which overrides
bd's native prefix-based routing via routes.jsonl. This broke resolution
of rig-level beads (e.g., gt-* beads routed via gt- -> gastown/mayor/rig).

Fix:
- Remove BEADS_DIR override in verifyBeadExists
- Set cmd.Dir to town root so bd can find routes.jsonl
- Apply same fix to getBeadInfo for consistency

Now gt sling gt-xxx correctly finds beads using the same routing as
bd show gt-xxx.

(gt-l5qwb)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 22:57:13 -08:00
julianknutsen
541e1ac2a3 chore: regenerate formulas and fix lint warnings
- Regenerate formulas to sync with source templates
- Fix unparam lint warnings in status.go (unused townRoot parameters)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 22:54:25 -08:00
furiosa
2922affa02 feat(deps): add minimum beads version check (gt-im3fl)
Add version check that enforces beads >= 0.44.0 at CLI startup,
required for custom type support (bd-i54l). Commands like version,
help, and completion bypass the check.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 22:52:32 -08:00
julianknutsen
ab0d56dec9 Add Claude settings location verification to rig add test
Verify that rig add creates settings.json in correct locations:
- witness/.claude/settings.json (outside git repo)
- refinery/.claude/settings.json (outside git repo)
- crew/.claude/settings.json (shared, outside git repos)
- polecats/.claude/settings.json (shared, outside git repos)

Also verify settings are NOT created inside source repos
(witness/rig/.claude, refinery/rig/.claude) which would
pollute the source repos.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 22:50:21 -08:00
joshuavial
b095b9c04c fix(sling): parse bd mol wisp --json new_epic_id 2026-01-07 19:50:01 +13:00
julianknutsen
feeee3912a Update install test for new Claude settings locations
CLAUDE.md moved from town root to mayor/ to prevent inheritance
pollution to child workspaces.

Also verify mayor/.claude/settings.json and deacon/.claude/settings.json
exist at their correct locations (outside source repos).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 22:48:59 -08:00
julianknutsen
29e2c6ed9c Fix daemon polecat respawn to pass rigPath for rig agent settings
Daemon's restartPolecatSession was calling BuildPolecatStartupCommand
with empty rigPath, causing polecats to fall back to town-level defaults
instead of honoring rig-specific agent settings.

Now passes rigPath so rig agent settings are honored.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 22:44:16 -08:00
julianknutsen
454b2f76e7 Fix witness to pass rigPath for rig agent settings
Witness was calling BuildAgentStartupCommand with empty rigPath,
causing it to fall back to town-level defaults instead of honoring
rig-specific agent settings (like RigSettings.Agent).

Now passes m.rig.Path so rig agent settings are honored, consistent
with how refinery already passes the rig path.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 22:40:34 -08:00
julianknutsen
21c1bbc118 Fix Claude settings tests for correct mayor settings location
Tests were creating mayor settings at townRoot/.claude/ but the check
now correctly identifies that location as wrong (should be mayor/.claude/).

Updated tests to use mayor/.claude/settings.json which is the correct
location that doesn't pollute child workspaces via directory traversal.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 22:37:23 -08:00
julianknutsen
ea8bef2029 refactor: unify agent startup with Manager pattern
- Create mayor.Manager for mayor lifecycle (Start/Stop/IsRunning/Status)
- Create deacon.Manager for deacon lifecycle with respawn loop
- Move session.Manager to polecat.SessionManager (clearer naming)
- Add zombie session detection for mayor/deacon (kills tmux if Claude dead)
- Remove duplicate session startup code from up.go, start.go, mayor.go
- Rename sessMgr -> polecatMgr for consistency
- Make witness/refinery SessionName() public for status display

All agent types now follow the same Manager pattern:
  mgr := agent.NewManager(...)
  mgr.Start(...)
  mgr.Stop()
  mgr.IsRunning()
  mgr.Status()

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 22:32:35 -08:00
julianknutsen
432d14d9df Install Claude settings during rig and HQ creation
Creates settings.json automatically during initial setup, so Claude
settings are available immediately on launch.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 21:44:05 -08:00
julianknutsen
b7b8e141b1 Move mayor files into mayor/ subdirectory
Prevents mayor-specific files (CLAUDE.md, hooks) from polluting child
agent workspaces. Child agents inherit the parent's working directory,
so keeping mayor files in a dedicated subdirectory ensures they don't
interfere with agent operations.

Includes:
- MayorDir constant in templates for consistent path handling
- Updated hooks.go, prime.go, role.go to use mayor/ paths
- Documentation updates

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 21:44:05 -08:00
julianknutsen
72544cc06d Unify agent startup with Manager pattern
Refactors all agent startup paths (witness, refinery, crew, polecat) to use
a consistent Manager interface with Start(), Stop(), IsRunning(), and
SessionName() methods.

Includes:
- Witness manager with GUPP propulsion nudge for startup
- Refinery manager for engineer sessions
- Crew manager for worker agents
- Session/polecat manager updates
- claude_settings_check doctor check for settings validation
- Settings management consolidated from rig/manager.go
- Settings location moved outside source repos to prevent conflicts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 21:44:04 -08:00
julianknutsen
81a7d04239 Add sparse checkout to exclude Claude context files from source repos
Excludes all Claude Code context files to prevent source repo instructions
from interfering with Gas Town agent configuration:
- .claude/       : settings, rules, agents, commands
- CLAUDE.md      : primary context file
- CLAUDE.local.md: personal context file
- .mcp.json      : MCP server configuration

Legacy configurations (only excluding .claude/) are detected and upgraded
by gt doctor --fix.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 21:01:07 -08:00
gastown/crew/joe
fc4b9de02c fix: use tmux for agent liveness in daemon checks (gt-zecmc)
Complete the "discover, don't track" refactoring:

- checkGUPPViolations: use tmux.IsClaudeRunning() instead of agent_state
- checkOrphanedWork: derive dead agents from tmux, not agent_state=dead
- assessStaleness: rely on HasActiveSession (tmux), not agent_state

Non-observable states (stuck, awaiting-gate) are still respected.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 20:50:01 -08:00
capable
9729e05f86 feat(rig): add operational state to gt rig status
Add Status line showing operational state (OPERATIONAL/PARKED/DOCKED)
with source indication (local/global - synced/default).

The state is looked up using the property layer system:
1. Wisp layer (local/ephemeral): .beads-wisp/config/<rig>.json
2. Rig bead labels (global/synced): status:parked or status:docked
3. Default: OPERATIONAL

Example output:
  gastown
    Status: PARKED (local)
    Path: /Users/stevey/gt/gastown
    ...

Closes: gt-5l7h4

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 20:43:51 -08:00
nux
3f920048cb feat(rig): add dock/undock commands for Level 2 rig control (gt-9gm9n)
Implement gt rig dock <rig> and gt rig undock <rig> commands for
global/persistent rig control:

- dock: stops witness/refinery, sets status:docked label on rig bead
- undock: removes docked label, allows daemon to restart agents

This is Level 2 (global/persistent) control:
- Uses rig identity bead labels (synced via git)
- Affects all clones of the rig
- Persists until explicitly undocked

Also includes cherry-picked rig identity bead infrastructure:
- RigFields struct for rig metadata
- CreateRigBead and RigBeadID helpers
- Auto-create rig bead for legacy rigs on first dock

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 20:43:27 -08:00
rictus
d00e73f110 feat(daemon): respect rig operational state for auto-start
Update daemon to check rig config before auto-starting agents:
- Check wisp config "status" - skip if parked or docked
- Check "auto_restart" config - skip if blocked or false
- Log skip reason for visibility

Affects ensureWitnessRunning, ensureRefineryRunning,
restartPolecatSession, and lifecycle restartSession.

(gt-68c46)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 20:43:00 -08:00
gastown/crew/joe
87169a3fc7 fix: complete removal of agent_state observable tracking (gt-zecmc)
Additional cleanup from the agent_state refactoring:

- Remove dead code: checkStaleAgents(), markAgentDead() in lifecycle.go
- Remove dead code: reportAgentState(), getAgentFields() in prime.go
- Update getAgentBeadState() comment to clarify non-observable states only
- Update mol-witness-patrol.formula.toml to use tmux discovery
- Update mol-polecat-lease.formula.toml to use POLECAT_DONE mail
- Update docs/watchdog-chain.md to reflect new architecture

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 20:42:23 -08:00
furiosa
6e84489ca3 feat(rig): add park/unpark commands for Level 1 rig control
Implement gt rig park <rig> and gt rig unpark <rig> commands:
- park: stops witness/refinery, sets status=parked in wisp layer
- unpark: clears parked status, allows daemon to restart agents

This is Level 1 (local/ephemeral) control - affects only this town
and disappears on wisp cleanup. Exports IsRigParked() for daemon use.

(gt-vxv0u)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 20:41:01 -08:00
dementus
29aed4b42f feat(rig): add gt rig config commands (gt-hhmkq)
Implements config viewing and manipulation commands for rig configuration
across property layers.

Commands:
- gt rig config show <rig>           # Show effective config
- gt rig config show <rig> --layers  # Show source of each value
- gt rig config set <rig> <key> <value>          # Set in wisp layer
- gt rig config set <rig> <key> <value> --global # Set in bead layer
- gt rig config set <rig> <key> --block          # Block inheritance
- gt rig config unset <rig> <key>                # Remove from wisp

Includes cherry-picked dependencies:
- Property layer lookup (cb927a73, gt-emh1c)
- Rig identity bead schema for bead layer

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 20:40:40 -08:00
slit
805ac7c17a feat(rig): implement property layer lookup (gt-emh1c)
Implements unified config lookup across all layers:
1. Wisp layer (transient, town-local)
2. Rig identity bead labels
3. Town defaults
4. System defaults (compiled-in)

Two lookup modes:
- Override: First non-nil value wins (default)
- Stacking: Integer values sum (for priority_adjustment)

API on Rig:
- GetConfig(key) interface{}
- GetIntConfig(key) int (stacking for priority_adjustment)
- GetBoolConfig(key) bool
- GetStringConfig(key) string
- GetConfigWithSource(key) (value, source)

Includes cherry-picked dependencies:
- Wisp config storage layer (nux, gt-3w685)
- Rig identity bead schema (furiosa, gt-zmznh)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 20:40:14 -08:00
furiosa
ec53dfbb40 feat(rig): add rig identity bead schema and creation (gt-zmznh)
- Add RigFields struct, CreateRigBead, RigBeadID helpers to beads package
- Modify gt rig add to create rig identity bead after rig creation
- Schema: id=<prefix>-rig-<name>, type=rig, with repo/prefix/state fields

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 20:39:41 -08:00
gastown/crew/joe
1f44482ad0 fix: remove observable states from agent_state (discover, don't track)
The agent_state field was recording observable state like "running",
"dead", "idle" which violated the "Discover, Don't Track" principle.
This caused stale state bugs where agents were marked "dead" in beads
but actually running in tmux.

Changes:
- Remove daemon's checkStaleAgents() which marked agents "dead"
- Simplify ensureXxxRunning() to use tmux.IsClaudeRunning() directly
- Remove reportAgentState() calls from gt prime and gt handoff
- Add SetHookBead/ClearHookBead helpers that don't update agent_state
- Use ClearHookBead in gt done and gt unsling
- Simplify gt status to derive state from tmux, not bead

Non-observable states (stuck, awaiting-gate, muted, paused) are still
set because they represent intentional agent decisions that can't be
discovered from tmux state.

Fixes: gt-zecmc

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 20:32:02 -08:00
gastown/crew/jack
950e35317e feat(status): add compact one-line-per-worker output as default
- Add --verbose/-v flag to show detailed multi-line output (old behavior)
- Compact mode shows: name + status indicator (●/○) + hook + mail count
- MQ info displayed inline with refinery
- Fix Makefile install target to use ~/.local/bin

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 20:12:39 -08:00
gastown/crew/joe
6dbb841e22 fix(daemon): nudge agents on state divergence instead of silent accept
When the daemon detects that an agent bead state doesn't match tmux
(e.g., bead says stopped but Claude is running), it now:

1. Logs the divergence clearly with STATE DIVERGENCE prefix
2. Nudges the agent with an actionable command to fix its state
3. Still skips the restart (safety - don't kill healthy sessions)

This prevents silent state drift where bead state diverges from reality.
Applied to: Deacon, Witness, Refinery ensure functions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 19:23:52 -08:00
jv
d89aae5b5c docs: mention agent config and --agent in onboarding 2026-01-06 19:13:14 -08:00
jv
11e3e85e9d docs: document --agent overrides 2026-01-06 19:13:14 -08:00
jv
99aae0bf02 fix: use canonical hq role bead IDs 2026-01-06 19:13:14 -08:00
jv
22693c1dcc feat: runtime-aware tmux agent checks 2026-01-06 19:13:14 -08:00
jv
02ca9e43fa fix: honor rig agent when starting witness/refinery 2026-01-06 19:12:55 -08:00
jv
6afd85df4b feat: add --agent overrides to start/attach 2026-01-06 19:11:58 -08:00
jv
3b9ca71fc4 feat: add --agent override for sling 2026-01-06 19:11:58 -08:00
Subhrajit Makur
93b19a7e72 feat: add watch mode to gt status (#8) (#11) (#231)
* feat: add watch mode to gt status

- Add --watch/-w flag for continuous status refresh
- Add --interval/-n flag to set refresh interval (default 2s)
- Clears screen and shows timestamp on each refresh
- Graceful Ctrl+C handling to stop watch mode
- Works with existing --fast and --json flags

* fix(status): validate watch interval to prevent panic on zero/negative values

* fix(status): harden watch mode with signal cleanup, TTY detection, and tests

- Add defer signal.Stop() to prevent signal handler leak
- Reject --json + --watch combination (produces invalid output)
- Add TTY detection for ANSI escapes (safe when piped)
- Use style.Dim for header when in TTY mode
- Fix duplicate '(default 2)' in flag help
- Add tests for interval validation and flag conflicts
2026-01-06 19:10:43 -08:00
gastown/crew/joe
c2451b85e7 Merge origin/main into fix/205-address-claude-startup-issues
Resolved conflict in internal/witness/manager.go:
- Kept session import (used by PR code)
- Kept PR's more accurate comment for PID check
- Removed duplicate sessionName method introduced by merge
2026-01-06 19:04:29 -08:00
nux
ae88c12e07 feat(wisp): add config storage layer for transient/local settings
Implement wisp-based config storage at .beads-wisp/config/<rig>.json
for local-only settings that are never synced via git.

API:
- Get(key) - returns value or nil
- Set(key, value) - stores value
- Block(key) - marks key as blocked (NullValue equivalent)
- Unset(key) - removes from values and blocked
- IsBlocked(key) - checks if blocked

(gt-3w685)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 19:01:34 -08:00
gastown/crew/joe
e7a8e0a3db bead: ZFC convoy auto-close on bd close (gt-3qw5s) 2026-01-06 18:53:59 -08:00
gastown/crew/joe
56742d95da docs: Add property-layers.md implementation guide
Multi-level configuration for Gas Town:
- gt rig park/unpark (local, ephemeral)
- gt rig dock/undock (global, persistent)
- Property layer lookup implementation

Related: gt-ih6xy

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 17:39:03 -08:00
furiosa
60e7471cea fix(witness): Kill tmux session on Stop()
The witness manager's Stop() method was only updating runtime JSON state
without killing the tmux session, causing 'gt rig shutdown' to leave
witness sessions running.

Added sessionName() method and tmux kill-session logic to match the
refinery's existing implementation.

Fixes: bd-gxaf

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 14:04:52 -08:00
gastown/crew/jack
7edd75021b fix: revert heretical gt witness process command, update formula for ZFC (gt-h3gzj)
The previous commit (a3bccc8) violated ZFC by implementing molecule step logic
in Go handlers. Per PRIMING.md: Agent decides. Go transports.

This commit:
1. Reverts the gt witness process command (Go code should not make decisions)
2. Updates mol-witness-patrol formula with explicit CLI commands
3. Fixes --wisp to --ephemeral (bd create flag correction)
4. Removes --wisp from bd list calls (invalid flag)

The Witness Claude agent now has explicit instructions:
- Parse POLECAT_DONE message for polecat name
- Check cleanup_status via bd show
- Run gt polecat nuke or bd create --ephemeral based on status
- Archive mail after handling

ZFC: Agent decides. Go transports.
2026-01-06 13:33:20 -08:00
gastown/crew/max
a787d60add fix(crew): add dry-run support and error handling to crew stop (gt-kjcx4)
Fixed two issues in `gt crew stop <name>`:

1. --dry-run flag now works for individual crew stops (previously only
   worked with --all)

2. HasSession errors are now properly handled instead of being ignored,
   which could cause "No session found" messages even when sessions exist

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 13:25:10 -08:00
gastown/crew/jack
a3bccc881b fix: add gt witness process command to invoke polecat cleanup handlers (gt-h3gzj)
The Witness handlers (HandlePolecatDone, HandleMerged, etc.) existed in Go
code but were never called - there was no CLI command to invoke them.

This caused polecats to remain in 'done' state after MR merge because
POLECAT_DONE messages were never processed.

Changes:
- Add `gt witness process <rig>` command to process Witness mail
- Fix --wisp flag to --ephemeral in cleanup wisp creation
- Command processes POLECAT_DONE, MERGED, HELP, SWARM_START messages
- Auto-nukes clean polecats, creates cleanup wisps for dirty ones

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 13:22:10 -08:00
gastown/crew/gus
74409dc32b feat(deacon): add stale hooked bead cleanup (gt-2yls3)
Add `gt deacon stale-hooks` command to find and unhook stale beads.

Problem: Beads can get stuck in 'hooked' status when agents die or
abandon work without properly unhooking.

Solution:
- New command scans for hooked beads older than threshold (default 1h)
- Checks if assignee agent is still alive (tmux session exists)
- Unhooks beads with dead agents (sets status back to 'open')
- Supports --dry-run to preview without making changes

Also adds "stale-hook-check" step to Deacon patrol formula.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 13:20:45 -08:00
gastown/crew/george
ac63b10aa8 feat(formula): update mol-town-shutdown to v3 with full cleanup (gt-ux23f)
Added steps from discovered cleanup operations:
- clear-hooks: Detach all hooked work from agents
- reset-in-progress: Reset in-progress beads to open status
- burn-wisps: Clean up wisp directories and ephemeral beads
- validate-clean: Verify all cleanup operations succeeded

Updated existing steps with more detailed procedures.

Key principles preserved:
- No forcing, no lost work
- Idempotent (safe to run multiple times)
- Crew workers NOT affected (user-managed)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 13:19:00 -08:00
gastown/crew/george
c306879a31 fix(refinery): merge local branches instead of fetching from origin (gt-cio03)
Phase 2 of Heresy Correction: Local-Only Polecat Branches

Changes:
- Replace FetchBranch("origin", branch) with BranchExists() check
- Use local branch directly for CheckConflicts() and MergeNoFF()
- Remove "origin/" prefix from branch references

The Refinery worktree shares .repo.git with polecat worktrees, so
branches created by polecats are already visible locally without
needing to fetch from origin.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 13:14:58 -08:00
gastown/crew/max
ac4649ba7d docs(polecat): remove push instructions for local-only branches (gt-cqw0n)
Phase 3 of heresy correction: polecat branches stay local, Refinery
accesses them via shared .repo.git.

Changes:
- templates/polecat-CLAUDE.md: Remove push from completion checklist
- mol-polecat-work.formula.toml: Remove push step from cleanup-workspace
- polecat.md.tmpl: Update landing rule for local branches
- refinery.md.tmpl: Change origin/polecat to local branch references

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 13:11:54 -08:00
gastown/crew/gus
63af29284b feat(witness): delay polecat cleanup until MR merges (gt-12hwb)
Phase 4 of local-only polecat branches: Handle conflict resolution edge case.

Problem: If polecat worktree is nuked before MR merges, the local branch
is gone and conflict resolution can't access it.

Solution: Witness now defers cleanup for polecats with pending MRs:
- HandlePolecatDone creates a cleanup wisp with "merge-requested" state
- Polecat worktree preserved until MERGED signal arrives
- HandleMerged then nukes the polecat (existing behavior)

Also updated mol-polecat-conflict-resolve.formula.toml:
- Removed fetch from origin (branches are local-only now)
- Added instructions to fetch from source polecat's worktree
- Added rig and source_polecat variables

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 13:11:43 -08:00
gastown/crew/jack
b79e4a7c3b fix: remove BranchPushedToRemote checks from gt done and mq submit (gt-dymy5)
Phase 1 of local-only polecat branches. Removes push verification checks
since polecats will no longer push branches to remote.

- done.go: Remove push check, keep existing CommitsAhead validation
- mq_submit.go: Remove push check entirely

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 13:09:32 -08:00
markov-kernel
6fe25c757c fix(refinery): Send MERGE_FAILED to Witness when merge is rejected
When the Refinery detects a build error or test failure and refuses
to merge, the polecat was never notified. This fixes the notification
pipeline by:

1. Adding MERGE_FAILED protocol support to Witness:
   - PatternMergeFailed regex pattern
   - ProtoMergeFailed protocol type constant
   - MergeFailedPayload struct with all failure details
   - ParseMergeFailed parser function
   - ClassifyMessage case for MERGE_FAILED

2. Adding HandleMergeFailed handler to Witness:
   - Parses the failure notification
   - Sends HIGH priority mail to polecat with fix instructions
   - Includes branch, issue, failure type, and error details

3. Adding mail notification in Refinery's handleFailureFromQueue:
   - Creates mail.Router for sending protocol messages
   - Sends MERGE_FAILED to Witness when merge fails
   - Includes failure type (build/tests/conflict) and error

4. Adding comprehensive unit tests:
   - TestParseMergeFailed for full body parsing
   - TestParseMergeFailed_MinimalBody for minimal body
   - TestParseMergeFailed_InvalidSubject for error handling
   - ClassifyMessage test cases for MERGE_FAILED

Fixes #114

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 13:02:46 -08:00
mayor
9cb14cc41a fix(sling): resolve rig path for cross-rig bead hooking
gt sling failed when hooking rig-level beads from town root because
bd update doesn't support cross-database routing like bd show does.

The fix adds a ResolveHookDir helper that:
1. Extracts the prefix from bead ID (e.g., "ap-xxx" → "ap-")
2. Looks up the rig path from routes.jsonl
3. Falls back to townRoot if prefix not found

Also removes the BEADS_DIR environment override which was preventing
routing from working correctly.

Fixes #148
2026-01-06 13:00:46 -08:00
Martin Emde
201ef3a9c8 Replace gt rigs with gt rig list in templates and docs (#217)
The command was renamed from `gt rigs` to `gt rig` with subcommands.
This updates all references to use `gt rig list` for listing rigs.
2026-01-06 12:59:49 -08:00
Martin Emde
9e416e9ff5 Fix handoff loses claude code environment variables (#216)
buildRestartCommand() now propagates Claude-related env vars when
respawning sessions via tmux. Fresh shells don't inherit parent env,
so CLAUDE_CODE_USE_BEDROCK, ANTHROPIC_API_KEY, AWS_*, etc. were lost.
This caused any tmux respawn to result in a non-functional claude.

Adds claudeEnvVars list and includes them in the export command when
building the restart command.
2026-01-06 12:59:45 -08:00
Dave Williams
83c47df980 📝 (README.md): rewrite documentation with comprehensive guides, archi… (#226)
* 📝 (README.md): rewrite documentation with comprehensive guides, architecture diagrams, and detailed workflows
The README has been completely overhauled to provide a more structured and detailed explanation of the Gas Town system. It now includes architecture diagrams, in-depth descriptions of core concepts, step-by-step installation and usage guides, and troubleshooting tips to improve the developer onboarding experience.

* 📝 (README.md): improve formatting, alignment, and spacing

The tables are realigned to improve readability in the raw view, and missing newlines are added before code blocks and after section headers to ensure proper rendering and visual separation.
2026-01-06 12:59:44 -08:00
Subhrajit Makur
7fe505d673 fix: create mayor/daemon.json during gt start and gt doctor --fix (#225)
* fix: create mayor/daemon.json during gt start and gt doctor --fix (#5)

- Add DaemonPatrolConfig type with heartbeat and patrol settings
- Add Load/Save/Ensure functions for daemon patrol config
- Create daemon.json in gt start (non-fatal if fails)
- Make PatrolHooksWiredCheck fixable with Fix() method
- Add comprehensive tests for both config and doctor checks

This fixes the issue where gt doctor expects mayor/daemon.json to exist
but it was never created by gt start or any other command.

* refactor: use constants.DirMayor instead of hardcoded string
2026-01-06 12:59:41 -08:00
Julian Knutsen
9d7dcde1e2 feat: Unified beads redirect for tracked and local beads (#222)
* feat: Beads redirect architecture for tracked and local beads

This change implements proper redirect handling so that all rig agents
(Witness, Refinery, Crew, Polecats) can work with both:
- Tracked beads: .beads/ checked into git at mayor/rig/.beads
- Local beads: .beads/ created at rig root during gt rig add

Key changes:

1. SetupRedirect now handles tracked beads by skipping redirect chains.
   The bd CLI doesn't support chains (A→B→C), so worktrees redirect
   directly to the final destination (mayor/rig/.beads for tracked).

2. ResolveBeadsDir is now used consistently in polecat and refinery
   managers instead of hardcoded mayor/rig paths.

3. Rig-level agents (witness, refinery) now use rig beads with rig
   prefix instead of town beads. This follows the architecture where
   town beads are only for Mayor/Deacon.

4. prime.go simplified to always use ../../.beads for crew redirects,
   letting rig-level redirect handle tracked vs local routing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(doctor): Add beads-redirect check for tracked beads

When a repo has .beads/ tracked in git (at mayor/rig/.beads), the rig root
needs a redirect file pointing to that location. This check:

- Detects missing rig-level redirect for tracked beads
- Verifies redirect points to correct location (mayor/rig/.beads)
- Auto-fixes with 'gt doctor --fix'

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: Handle fileLock.Unlock error in daemon

Wrap fileLock.Unlock() return value to satisfy errcheck linter.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 12:59:37 -08:00
Martin Emde
16fb45bb2a Add .repo.git/ to gitignore during rig setup (#219)
This prevents .repo.git/ directories from showing up as untracked files
in town git status.

Changes:
- manager.go: Add .repo.git/ to rig .gitignore during setup
2026-01-06 12:59:33 -08:00
Olivier Debeuf De Rijcker
87a2e27fcc fix(sling): Wait for Claude to be ready before nudging existing sessions (#146)
When `gt sling` targets an existing polecat session, it now waits for
Claude to be ready before sending the nudge message. This fixes issue #115
where the "Work slung" message would arrive before Claude had fully started.

Changes:
- Add getSessionFromPane() to extract session name from pane target
- Add ensureClaudeReady() to wait for Claude startup using the same
  pragmatic approach as session.Start() (poll for node, accept bypass
  dialog, then 8-second delay)
- Call ensureClaudeReady() before injectStartPrompt() in runSling()

The fix uses IsClaudeRunning() for a fast path when Claude is already
running, avoiding unnecessary delays for sessions that have been
running for a while.

Fixes #115

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 12:59:05 -08:00
Greg Hughes
ad6169201a docs(mayor): Add Polecat Operations section (#140)
Searching for polecat spawn you are? Here it is not. Hrmmm.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 12:58:37 -08:00
julianknutsen
09bbb0f430 Fix lint issues and sparse checkout for empty repos
- Handle empty repos in ConfigureSparseCheckout (skip read-tree when no HEAD)
- Fix errcheck: wrap fileLock.Unlock() error in defer
- Fix unparam: remove unused *rig.Rig return from getWitnessManager
- Fix unparam: mark unused agentType parameter with blank identifier

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 02:16:15 -08:00
mayor
be815db5e4 Fix cost recording for hq-* tmux sessions
detectCurrentTmuxSession() was only accepting gt-* prefix sessions,
rejecting town-level sessions like hq-mayor. Now accepts both gt-*
and hq-* prefixes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 01:52:19 -08:00
mayor
31a32c084b Unify agent startup with GUPP propulsion nudge
Witness and Refinery startup was duplicated across cmd/witness.go, cmd/up.go,
cmd/rig.go, and daemon.go. Worse, not all code paths sent the propulsion nudge
(GUPP - Gas Town Universal Propulsion Principle). Now unified in Manager.Start()
which handles everything including nudges.

Changes:
- witness/manager.go: Full rewrite with session creation, env vars, theming,
  WaitForClaudeReady, startup nudge, and propulsion nudge (GUPP)
- refinery/manager.go: Add propulsion nudge sequence after Claude startup
- cmd/witness.go: Simplify to just call mgr.Start(), remove ensureWitnessSession
- cmd/rig.go: Use witness.Manager.Start() instead of inline session creation
- cmd/start.go: Use witness.Manager.Start()
- cmd/up.go: Use witness.Manager.Start(), remove ensureWitness(),
  add EnsureSettingsForRole in ensureSession()
- daemon.go: Use witness.Manager.Start() and refinery.Manager.Start() for
  unified startup with proper nudges

This ensures all agent startup paths (gt witness start, gt rig boot, gt up,
daemon restarts) consistently apply GUPP propulsion nudges.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 01:51:25 -08:00
mayor
f6f6acdb2d Consolidate Claude settings management
Settings creation was scattered across multiple places (createPatrolHooks,
ensurePatrolHooks, inline code). Now unified via claude.EnsureSettingsForRole().

Changes:
- Add "deacon" to autonomous roles in claude/settings.go
- Remove ensurePatrolHooks() from cmd/deacon.go, use EnsureSettingsForRole
- Remove createPatrolHooks() from rig/manager.go (no longer needed at rig add)
- Add EnsureSettingsForRole call in crew_lifecycle.go
- Add doctor check for stale/missing Claude settings files
- Wire up claude-settings check in cmd/doctor.go

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 01:51:24 -08:00
mayor
4799cb086f Add sparse checkout to exclude source repo .claude/ directories
When cloning or creating worktrees from repos that have their own .claude/
directory, those settings would override Gas Town's agent settings. This adds
sparse checkout configuration to automatically exclude .claude/ from all
clones and worktrees.

Changes:
- Add ConfigureSparseCheckout() to git.go, called from all Clone/WorktreeAdd methods
- Add IsSparseCheckoutConfigured() to detect if sparse checkout is properly set up
- Add doctor check to verify sparse checkout config (checks config, not symptoms)
- Doctor --fix will configure sparse checkout for repos missing it

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 01:48:42 -08:00
Cong
6e4f2bea29 fix: replace panic with fallback in ID generation (#213)
Replace panic calls in generateID() and generateThreadID() with
time-based fallback when crypto/rand.Read fails. This is an extremely
rare error case, but panicking is not the right behavior for ID
generation functions.

🤝 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 21:33:40 -08:00
gastown/crew/gus
c8150ab017 chore: update .beads/.gitignore with additional entries
- Add sync-state.json, last-touched to ignores
- Add redirect file ignore (worktree paths)
- Update comments explaining why negation patterns removed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 21:31:12 -08:00
gastown/crew/jack
637df1d289 feat(doctor): add prefix mismatch detection check (gt-17wdl)
Add a new 'prefix-mismatch' check to gt doctor that detects when the
prefix configured in rigs.json differs from what routes.jsonl actually
uses for a rig's beads.

This can happen when:
- deriveBeadsPrefix() generates a different prefix than what's in the DB
- Someone manually edited rigs.json with the wrong prefix
- Beads were initialized before auto-derive existed with a different prefix

The check is fixable: running 'gt doctor --fix' will update rigs.json
to match the actual prefixes from routes.jsonl.

Includes comprehensive tests for:
- No routes (nothing to check)
- No rigs.json (nothing to check)
- Matching prefixes (OK)
- Mismatched prefixes (Warning)
- Fix functionality

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 21:30:11 -08:00
Steve Yegge
cf1eac8521 Merge pull request #198 from EscapeVelocityOperations/main
fix(refinery): use rig's default_branch instead of hardcoded 'main'
2026-01-05 21:26:31 -08:00
gastown/crew/george
296440579a feat: add LED status indicators for rigs in Mayor tmux status line
Replace generic "3 rigs" display with per-rig LED indicators showing
witness/refinery status:
- 🟢 = both witness and refinery running (fully active)
- 🟡 = one running (partially active)
-  = neither running (inactive)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 21:18:15 -08:00
gastown/crew/max
03fef16748 feat(rig): add route from rig beads to town beads
Add AppendRouteToDir helper and use it to add hq-* route during rig
initialization. This allows rig beads to resolve role beads and other
hq-* prefixed beads stored in town beads.

Uses safe append pattern (load, merge, write) instead of overwriting
to avoid clobbering future rig routes.

Supersedes PR #184 with proper implementation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 19:55:34 -08:00
gastown/crew/jack
e8d27e7212 fix: Create and lookup rig agent beads with correct prefix
Per docs/architecture.md, Witness and Refinery are rig-level agents that
should use the rig's configured prefix (e.g., pi- for pixelforge) instead
of hardcoded "gt-".

This extends PR #183's creation fix to also fix all lookup paths:
- internal/rig/manager.go: Create agent beads in rig beads with rig prefix
- internal/daemon/daemon.go: Use rig prefix when looking up agent state
- internal/daemon/lifecycle.go: Use rig prefix for identity-to-bead mapping
- internal/cmd/sling.go: Pass townRoot for prefix lookup
- internal/cmd/unsling.go: Pass townRoot for prefix lookup
- internal/cmd/molecule_status.go: Use rig prefix for agent bead lookups
- internal/cmd/molecule_attach.go: Use rig prefix for agent bead lookups
- internal/config/loader.go: Add GetRigPrefix helper

Without this fix, the daemon would:
- Create pi-gastown-witness but look for gt-gastown-witness
- Report agents as missing/dead when they are running
- Fail to manage agent lifecycle correctly

Based on work by Johann Taberlet in PR #183.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Johann Taberlet <johann.taberlet@gmail.com>
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 19:39:57 -08:00
mayor
fc0b506253 Merge polecat branches, resolve conflicts 2026-01-05 19:39:25 -08:00
mayor
5224dfb50d Merge remote-tracking branch 'origin/polecat/slit-mk1wa0rj' 2026-01-05 19:39:01 -08:00
mayor
b33df5fa36 Merge remote-tracking branch 'origin/polecat/shiny-mk0vvt3o' 2026-01-05 19:39:00 -08:00
mayor
5ae89b3a27 Merge remote-tracking branch 'origin/polecat/road-warrior-mk0vt2ef' 2026-01-05 19:38:59 -08:00
mayor
2ed8de0e20 Merge remote-tracking branch 'origin/polecat/mediocre-mk0vwdaf' 2026-01-05 19:38:59 -08:00
mayor
155e7dd438 Merge remote-tracking branch 'origin/polecat/interceptor-mk0vtimo' 2026-01-05 19:38:58 -08:00
mayor
8249e8a7f6 Merge remote-tracking branch 'origin/polecat/interceptor-mk0uvp71' 2026-01-05 19:38:57 -08:00
mayor
2ec66214e1 Merge remote-tracking branch 'origin/polecat/fury-mk0vskad' 2026-01-05 19:38:56 -08:00
mayor
c199f7e940 Merge remote-tracking branch 'origin/polecat/furiosa-mk1uozyl' 2026-01-05 19:38:56 -08:00
mayor
b9d1813301 Merge remote-tracking branch 'origin/polecat/citadel-mk0vro62' 2026-01-05 19:38:55 -08:00
mayor
362917f52e Merge remote-tracking branch 'origin/polecat/chrome-mk0vvab8' 2026-01-05 19:38:54 -08:00
mayor
0607c3a749 Merge remote-tracking branch 'origin/polecat/bullet-farmer-mk0vqzi0' 2026-01-05 19:38:54 -08:00
mayor
c073125b3b Merge remote-tracking branch 'origin/polecat/blackfinger-mk0vu0da' 2026-01-05 19:38:53 -08:00
mayor
86c79e750c Merge remote-tracking branch 'origin/polecat/blackfinger-mk0uw6ym' 2026-01-05 19:38:45 -08:00
gastown
43cca06460 feat: Add Windows-compatible file locking for daemon
Replace Unix-only syscall.Flock with gofrs/flock library for
cross-platform file locking. This enables the daemon to run on
Windows in addition to Unix-like systems.

- Add github.com/gofrs/flock v0.13.0 dependency
- Replace syscall.Flock calls with flock.TryLock/Unlock
- Maintain same non-blocking exclusive lock semantics

(gt-5354h)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 19:21:09 -08:00
nux
b88d3e8ee7 fix: restart Claude when session exists but Claude is dead
In startConfiguredCrew(), only HasSession() was checked, missing the case
where a tmux session exists but Claude has exited. Now checks IsClaudeRunning()
and restarts Claude with BuildCrewStartupCommand if dead, matching the behavior
in runStartCrew(). (gt-ms8s4)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 19:18:16 -08:00
Johann Taberlet
97564dfc13 fix: Initialize git before beads to enable repo fingerprint (#180)
Fix: Initialize git before beads to enable repo fingerprint computation

Fixes #25
2026-01-05 19:14:23 -08:00
gastown/crew/max
688624ca6b feat(crew): add --purge flag for full crew obliteration
- Add --purge flag to gt crew remove that:
  - Deletes the agent bead (not just closes it)
  - Unassigns any beads assigned to the crew member
  - Properly handles git worktrees (not just regular clones)
- Add gt doctor crew-worktrees check to detect stale cross-rig worktrees
- Worktrees in crew/ with hyphenated names are now properly cleaned up
  using git worktree remove instead of rm -rf

The --purge flag is for accidental/test crew that should leave no trace
in the capability ledger. Normal crew removal closes the agent bead to
preserve CV history per HOP architecture.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 19:11:14 -08:00
Steve Yegge
c529d09e77 Merge pull request #181 from michaellady/polecat/goose-mk1b5dbp
[DO NOT MERGE] fix: Use --initial-branch=main in rig integration tests
2026-01-05 18:50:14 -08:00
Steve Yegge
0c5cfcea2a Merge pull request #139 from greghughespdx/fix/path-in-hooks
fix(hooks): Add PATH export to hook commands
2026-01-05 18:46:38 -08:00
buzzard
c24c3ba873 fix: Auto-close session-ended events to prevent accumulation (gt-8tc1v)
Session-ended event beads were accumulating without being processed.
Modified costs.go to auto-close these events immediately after creation
since they are informational audit events. The event data is preserved
in the closed bead and remains queryable.

Also bulk-closed 83 existing stale session-ended events.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 18:23:00 -08:00
slit
8110aab257 fix: Add GUPP propulsion nudge to daemon restartSession
When Deacon respawns refinery/witness sessions via LIFECYCLE requests,
the new sessions were starting at the Claude welcome screen without
the propulsion nudge that triggers autonomous execution.

Added StartupNudge and PropulsionNudgeForRole calls to restartSession()
in lifecycle.go, matching the pattern used in ensureRefinerySession()
in start.go. This ensures respawned agents receive the GUPP nudge and
begin autonomous work immediately.

Fixes: gt-01jpg

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 17:14:49 -08:00
joe
d34e9b006c fix(crew): default to --all when only rig name provided (gt-s8mpt)
gt crew start beads and gt crew stop beads now default to --all
behavior when no crew names are specified, matching user expectations.

- crew start: accepts 0-1 args (rig only) and starts all crew
- crew stop: detects if single arg is a rig name vs crew name
- Updated help text with new examples

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 16:32:22 -08:00
furiosa
85a522f725 fix: Use hq- prefix for global agents in status display (gt-vcvyd)
Global agents like mayor and deacon are town-level agents that should use
the "hq-" prefix, not "gt-". Changed to use AgentBeadIDWithPrefix with
TownBeadsPrefix for consistency with the beads architecture.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 16:30:28 -08:00
Steve Yegge
5be232ff8c Merge pull request #141 from julianknutsen/cleanup/sling-dead-flags
cleanup: remove dead sling flags (--quality, --molecule)
2026-01-05 16:29:41 -08:00
mayor
eb6fb3c73b fix(refinery): use rig's default_branch instead of hardcoded 'main'
- Add DefaultBranch field to RoleData struct
- Update refinery.md.tmpl to use {{ .DefaultBranch }} template variable
- Populate DefaultBranch from rig config in prime.go and rig/manager.go
- Default to 'main' if not configured
- Add test verifying DefaultBranch rendering in refinery template

Fixes issue where refinery agents merged to master instead of the
configured default branch (e.g., 'develop' or 'develop-cstar').
2026-01-05 20:24:47 +01:00
goose
52533c354d fix: Use --initial-branch=main in rig integration tests
The test helper createTestGitRepo was using plain `git init` which
creates a branch based on the system's init.defaultBranch config.
When AddRig tries to detect and checkout the default branch, it
falls back to "main" if detection fails, causing "pathspec 'main'
did not match" errors in CI where the system default is "master".

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 07:23:06 -08:00
max
7ae08ed219 chore: Bump version to 0.2.1
Some checks failed
Release / goreleaser (push) Failing after 4m18s
Release / publish-npm (push) Has been skipped
Release / update-homebrew (push) Has been skipped
2026-01-05 00:51:00 -08:00
max
25a49f80c3 docs: Add CHANGELOG entry for v0.2.1 2026-01-05 00:50:34 -08:00
gastown/crew/jack
6b8c897e37 feat: use hq- prefix for Mayor and Deacon session names
Town-level services (Mayor, Deacon) now use hq- prefix instead of gt-:
- hq-mayor (was gt-mayor)
- hq-deacon (was gt-deacon)

This distinguishes town-level sessions from rig-level sessions which
continue to use gt- prefix (gt-gastown-witness, gt-gastown-crew-max, etc).

Changes:
- session.MayorSessionName() returns "hq-mayor"
- session.DeaconSessionName() returns "hq-deacon"
- ParseSessionName() handles both hq- and gt- prefixes
- categorizeSession() handles both prefixes
- categorizeSessions() accepts both prefixes
- Updated all tests and documentation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:42:24 -08:00
blackfinger
a459cd9fd6 docs: Add test coverage and quality review (gt-a02fj.9)
Audit of test coverage identifying:
- 10 packages with 0 test coverage (2,452 lines)
- Priority list for new tests (internal/lock is P0)
- 1 flaky test candidate (feed/curator_test.go)
- Test quality analysis and recommendations

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:36:21 -08:00
nux
ca71f9b8de fix: Polecat lifecycle cleanup - stale worktrees and git tracking
Fixes gt-v07fl: Polecat lifecycle cleanup for stale worktrees and git
tracking conflicts.

Changes:
1. Add .claude/ to .gitignore (prevents untracked file accumulation)
2. Add beads runtime state patterns to .gitignore (prevents future tracking)
3. Remove .beads/ runtime state from git tracking (mq/, issues.jsonl, etc.)
   - Formulas and config remain tracked (needed for go install)
   - Created follow-up gt-mpyuq for formulas refactor
4. Add DetectStalePolecats() to polecat manager for identifying cleanup candidates
5. Add CountCommitsBehind() to git package for staleness detection
6. Add `gt polecat stale <rig>` command for stale polecat detection/cleanup
   - Shows polecats without active sessions
   - Identifies polecats far behind main (configurable threshold)
   - Optional --cleanup flag to auto-nuke stale polecats

The existing `gt polecat gc` command handles branch cleanup.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:23:34 -08:00
shiny
a5ff31428b fix(sling): use correct beads database for rig-level beads (gt-n5gga)
When slinging rig-level beads (gt-*, bd-*, etc.), the BEADS_DIR was
unconditionally set to town beads, which could bypass the redirect-based
routing needed for these beads. This caused assignee updates to potentially
fail silently or target the wrong database.

Changes:
- sling.go: Only set BEADS_DIR for town-level (hq-*) beads; rig-level
  beads now use redirect from polecat worktree for proper routing
- convoy.go: Add --no-daemon to bd show calls to ensure fresh data

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:21:42 -08:00
mediocre
f49197243d refactor: extract shared AgentStateManager pattern (gt-gaw8e)
- Create internal/agent package with shared State type and StateManager
- StateManager uses Go generics for type-safe load/save operations
- Update witness and refinery to use shared State type alias
- Replace loadState/saveState implementations with StateManager delegation
- Maintains backwards compatibility through re-exported constants

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:19:41 -08:00
blackfinger
904a773ade refactor: Add CleanupStatus type to replace raw strings (gt-77gq7)
Introduces a typed CleanupStatus with constants:
- CleanupClean, CleanupUncommitted, CleanupStash, CleanupUnpushed, CleanupUnknown

Adds helper methods:
- IsSafe(): true for clean status
- RequiresRecovery(): true for uncommitted/stash/unpushed
- CanForceRemove(): true if force flag can bypass

Updated files to use the new type:
- internal/polecat/types.go: Type definition and methods
- internal/polecat/manager.go: Validation logic
- internal/witness/handlers.go: Nuke safety checks
- internal/cmd/done.go: Status reporting
- internal/cmd/polecat.go: Recovery status checks

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:19:00 -08:00
wraith
ef248a1824 refactor: extract ExecWithOutput utility for command execution (gt-vurfr)
Create util.ExecWithOutput and util.ExecRun to consolidate repeated
exec.Command patterns across witness/handlers.go and refinery/manager.go.

Changes:
- Add internal/util/exec.go with ExecWithOutput (returns stdout) and
  ExecRun (runs command without output)
- Refactor witness/handlers.go to use utility functions (7 call sites)
- Refactor refinery/manager.go, removing unused gitRun/gitOutput methods
- Add comprehensive tests in exec_test.go

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:18:47 -08:00
road-warrior
4ebb96fbbc refactor: Extract runBdCommand helper to DRY mail package (gt-8i6bg)
Extracted duplicate bd command execution pattern from mailbox.go and
router.go into a new helper function in bd.go. This reduces code
duplication and provides consistent error handling via the bdError type.

Changes:
- Added internal/mail/bd.go with runBdCommand helper and bdError type
- Refactored 5 functions in mailbox.go to use runBdCommand
- Refactored 5 functions in router.go to use runBdCommand
- Net reduction of 55 lines of code

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:18:05 -08:00
chrome
168e805d0c fix: log rig discovery errors instead of silently swallowing (gt-rsnj9)
- DiscoverRigs() now logs failed rig loads to stderr instead of silently
  continuing
- AddRig warnings now output to stderr instead of stdout, matching the
  codebase convention for non-fatal warnings
- Added clarifying comment for best-effort git ref update in worktree

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:18:01 -08:00
citadel
c678d2e3d4 fix: Close hooked beads before clearing agent hook (gt-vwjz6)
Previously, when gt done was called, it cleared the agent's hook_bead
slot but didn't update the status of the hooked bead itself. This left
handoff beads with status=hooked forever.

Now the hooked bead is closed (status changed from hooked to closed)
before clearing the agent's hook slot.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:16:40 -08:00
interceptor
8c91ff22db refactor: DRY config expansion with generic helper (gt-i85sg)
Consolidated expandList, expandQueue, and expandAnnounce functions
using a generic expandFromConfig[T] helper. Reduces duplicate code
for: townRoot check, config path building, config loading, map lookup.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:14:29 -08:00
wretched
2141be7672 fix: Sync database before beads integration test to prevent flaky failures
The TestIntegration test was flaky because it uses the real .beads directory
and the SQLite database could be out of sync with the JSONL file (e.g., after
git pull updates the JSONL but before the database is re-imported).

The fix runs `bd sync --import-only` at the start of the test to ensure
the database is synchronized before running the actual test operations.

Fixes gt-5ww96

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:13:34 -08:00
bullet-farmer
1be9edc272 feat: Add debug logging for suppressed errors in session startup (gt-6d7eh)
Add debugSession helper that logs non-fatal errors when GT_DEBUG_SESSION=1.
Replaced all _ = error patterns with debugSession() calls for better
visibility when diagnosing session startup issues.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:12:47 -08:00
fury
bdaff31117 fix: Return error when all mailbox queries fail in listFromDir
Previously, listFromDir silently ignored all query errors and returned an
empty list with no error if all queries failed. This could hide real problems
like a corrupted beads database or missing bd command.

Now the function tracks whether at least one query succeeded. If all queries
fail, it returns the last error wrapped with context. This enables graceful
degradation (partial results if some queries work) while surfacing complete
failures.

(gt-lm41t)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:12:35 -08:00
julianknutsen
e30ebaf8ac fix(sling): remove dead --molecule flag
The --molecule flag was defined but never wired up - the slingMolecule
variable was set by the flag parser but never read by any code path.

Users should use --on instead, which is fully implemented:
  gt sling <formula> --on <bead> <target>

The --on flag properly instantiates the formula (cook + wisp + bond)
and applies it to the target bead before slinging.

Keeping --on as the canonical way to apply formulas to beads since it's
actually wired up and working. The --molecule flag can be re-added later
if a different argument order is desired.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:06:46 -08:00
julianknutsen
59414834ec fix(sling): remove obsolete --quality flag
The --quality flag (basic|shiny|chrome) referenced mol-polecat-* formulas
that were removed in c47a746 ("Remove obsolete polecat formula files") but
the flag code was left behind, causing errors when used.

Rather than restore the formulas, remove the flag entirely since:
- The default `gt sling <bead> <rig>` is now the standard workflow
- Formula-on-bead via `--on` or `--molecule` covers custom workflows
- The quality-level formulas were intentionally deprecated

Removes:
- --quality/-q flag and help text
- qualityToFormula() function
- Quality Levels section from command documentation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:06:44 -08:00
gastown/crew/joe
18578b3030 fix(security): validate beads prefix to prevent command injection (gt-l1xsa)
Add isValidBeadsPrefix() to validate prefix format before passing to
exec.Command. Prefixes from config files (detectBeadsPrefixFromConfig)
are now validated to contain only alphanumeric and hyphen characters,
start with a letter, and be max 20 chars.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:02:43 -08:00
george
b50d2a6fdb fix: validate crew names to prevent path traversal (gt-wzxwm)
Add validateCrewName() that rejects:
- Path separators (/, \)
- Parent directory references (..)
- Characters that break agent ID parsing (-, ., space)

Applied to all public entry points: Add, Remove, Get, Pristine.
2026-01-05 00:01:39 -08:00
Steve Yegge
d9962c54d6 Merge pull request #138 from greghughespdx/fix/sling-no-daemon
fix(sling): Add --no-daemon and BEADS_DIR for reliable bd calls
2026-01-05 00:01:17 -08:00
gus
7a7d558116 feat(doctor): Add hooks-path-configured check
Verifies all clones have core.hooksPath set to .githooks.
Auto-fixable with 'gt doctor --fix'.

This ensures the pre-push hook is active on all clones,
blocking pushes to invalid branches (no internal PRs).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 00:01:07 -08:00
Steve Yegge
325f818e11 Merge pull request #131 from greghughespdx/polecat/furiosa-mk0rmk9b
fix(sling): Set hook slot when creating agent beads
2026-01-04 23:59:33 -08:00
george
117e6a1852 fix: handle crypto/rand.Read error in ID generation (gt-qysj9)
Panic if crypto/rand.Read fails rather than silently returning
zero IDs which could cause message collisions.
2026-01-04 23:58:37 -08:00
Steve Yegge
820ff17f9a Merge pull request #129 from dlukt/main
feat: Add gt config command for managing agent settings
2026-01-04 23:53:43 -08:00
gastown/crew/joe
2c6654b5b2 fix(mail): prevent ReDoS in Search by escaping user input
Use regexp.QuoteMeta to treat Query and FromFilter as literal strings
instead of raw regex patterns. This prevents ReDoS attacks from malicious
patterns and provides more intuitive literal string matching for users.

Fixes gt-kwa09

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:53:36 -08:00
interceptor
7e591ec0a1 docs: Infrastructure & utilities code review (gt-a02fj.8)
Reviewed 14 internal packages for dead code, missing abstractions,
performance concerns, and error handling consistency:

Key findings:
- internal/keepalive/ is 100% dead (entire package unused)
- ~44% dead code in internal/constants/
- claude/RoleTypeFor() missing deacon/crew roles (bug)
- config/GetAccount() has pointer-to-stack bug
- polecat/pending.go uses non-atomic writes
- 6 duplicate patterns identified for consolidation
- 12 performance issues documented

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:50:54 -08:00
blackfinger
59484b2af7 docs: Add test coverage and quality review (gt-a02fj.9)
Audit of test coverage identifying:
- 10 packages with 0 test coverage (2,452 lines)
- Priority list for new tests (internal/lock is P0)
- 1 flaky test candidate (feed/curator_test.go)
- Test quality analysis and recommendations

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:49:25 -08:00
Greg Hughes
39d904e125 fix(hooks): Add PATH export to hook commands
Because you can't gt there from here without it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:42:06 -08:00
gus
254288800d fix: Fix YAML syntax in block-internal-prs workflow
Avoid template literals with backticks that confuse YAML parsers.
Use array.join() instead.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:38:31 -08:00
gus
e0e6473556 fix: Allow polecat/* branches, remove hanoi test formulas
- Update pre-push hook to allow polecat/* branches (Refinery merges these)
- Remove towers-of-hanoi formulas (test fixtures, not production)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:31:40 -08:00
Greg Hughes
afe5cab0ad fix(sling): Add --no-daemon and BEADS_DIR for reliable bd calls
- Add --no-daemon to all 17 bd exec calls to bypass daemon socket timing issues
- Set BEADS_DIR in verifyBeadExists() so bd can find beads from any directory

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:28:13 -08:00
gus
ff670c5bd4 feat: Block internal PRs via pre-push hook and GitHub Action
Gas Town agents must push directly to main, not create PRs.
This adds defense-in-depth:

1. .githooks/pre-push - Blocks pushes to non-main branches locally
2. .github/workflows/block-internal-prs.yml - Auto-closes PRs from
   the same repo (forks/contributors can still create PRs)
3. internal/git/git.go - Auto-configures core.hooksPath on clone

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:28:11 -08:00
mayor
e0ba057821 Merge remote-tracking branch 'origin/polecat/prime-mk0rmco7' 2026-01-04 23:18:08 -08:00
mayor
dd815e80d1 Merge remote-tracking branch 'origin/polecat/dinki-mk0rlxqc' 2026-01-04 23:18:06 -08:00
mayor
252dcc41f8 Merge remote-tracking branch 'origin/polecat/rockryder-mk0frt3g' 2026-01-04 23:17:58 -08:00
mayor
7507cd85c4 fix: Sync embedded formulas with .beads/formulas
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:13:44 -08:00
mayor
32cc3e42bc fix: Resolve CI lint and build errors
- Add error suppression for enc.Encode() calls in info.go (errcheck lint)
- Add missing encoding/json import in install_integration_test.go

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:13:03 -08:00
jack
fd3cb6133e fix(done): use ResolveBeadsDir in getDispatcherFromBead
Fixes PR #39 to follow the pattern established in PR #54 - all beads
initialization in done.go should use ResolveBeadsDir to support
.beads/redirect files in worktrees.
2026-01-04 23:10:11 -08:00
Steve Yegge
b207d2976b Merge pull request #39 from cvsloane/fix/polecat-dispatcher-notification
feat: notify dispatcher when polecat work completes
2026-01-04 23:09:23 -08:00
Raymond Weitekamp
1e76bfd7ce fix: Commit embedded formulas for go install @latest (#117)
* fix: Commit embedded formulas for go install @latest

The internal/formula/formulas/ directory was gitignored, causing
`go install github.com/steveyegge/gastown/cmd/gt@latest` to fail with:

  pattern formulas/*.formula.json: no matching files found

The go:embed directive requires these files at build time, but
go install @latest doesn't run go:generate. By committing the
generated formulas, users can install directly without cloning.

Maintainers should run `go generate ./...` after modifying
.beads/formulas/ to keep the embedded copy in sync.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* ci: Add check for committed embedded formulas

Adds a new CI job that:
1. Builds without running go:generate (catches missing formulas)
2. Verifies committed formulas match .beads/formulas/ source

Also removes redundant go:generate steps from other jobs since
formulas are now committed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore: exclude towers-of-hanoi test formulas from embed

These are durability stress test fixtures (pre-computed move sequences),
not production formulas users need. Excluding them reduces embedded
content by ~10K lines.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: gus <steve.yegge@gmail.com>
2026-01-04 23:08:55 -08:00
Steve Yegge
4ffdc4fe40 Merge pull request #54 from michaellady/polecat/fixer-mjy8jxh1
Clean 2-line fix with comprehensive tests. All tests pass locally.
2026-01-04 23:06:01 -08:00
Steve Yegge
97e06be2b4 Merge pull request #123 from akatz-ai/fix/convoy-cross-rig-tracking
fix(sling): Format cross-rig beads as external refs in convoy tracking
2026-01-04 23:05:44 -08:00
greghughespdx
92c9f544fe fix(sling): Set hook slot when creating agent beads (#124)
Sync with mayor/rig fix: Set hook slot in CreateAgentBead and pass
beadID to UpdateAgentState.

Fixes: mi-619

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:05:21 -08:00
Darko Luketic
c1897f5843 fix: Honor town default_agent for town-level agents (mayor, deacon)
Previously, BuildStartupCommand, GetRuntimeCommand, and
GetRuntimeCommandWithPrompt would fall back to DefaultRuntimeConfig()
(hardcoded "claude") when rigPath was empty, instead of reading
the town settings for the default_agent.

This meant that `gt config default-agent` had no effect on town-level
agents like the mayor.

Fix: Added findTownRootFromCwd() to detect town root from cwd,
then call ResolveAgentConfig() to read the town's default_agent
setting and custom agents.

Now `gt mayor attach` (and other town-level agents) correctly use
the agent configured in town settings.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-05 07:41:03 +01:00
dave
a455016361 fix(rig): infer rig name from cwd for 'gt rig status'
When no rig argument is provided, now uses GetRole() to detect the
rig from the current directory or GT_ROLE environment variable.
Shows a helpful error message if rig cannot be determined.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 22:26:49 -08:00
george
cfdce55770 fix: pass gt prime as initial prompt in crew start commands
The issue: gt crew start --all was not priming crew sessions like
gt crew at does.

Root cause: gt crew at passes "gt prime" as the initial prompt to
BuildCrewStartupCommand(), while gt crew start (via startCrewMember
and runStartCrew) passed an empty string and tried to send gt prime
afterwards via NudgeSession. This created a race condition where the
SessionStart hook would fire and Claude would start responding before
the nudge arrived.

Fix: Pass "gt prime" directly in the startup command for all three
cases: startCrewMember, runStartCrew new session, and runStartCrew
session restart. This makes the behavior consistent with gt crew at.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 22:18:24 -08:00
prime
7a0143cedf docs: Update wisp architecture to reflect beads storage
Wisps now live in main .beads/ directory with type=wisp instead
of a separate .beads-wisp/ directory. Updated documentation to
reflect this architectural change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 22:18:00 -08:00
dinki
7404eb6b94 Fix PR→MR terminology in workflow docs (gt-xmy0y)
- docs/reference.md: "review PRs" → "review MRs"
- docs/INSTALLING.md: "PR review" → "MR review"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 22:15:08 -08:00
Darko Luketic
b6dd6f005a Merge branch 'steveyegge:main' into main 2026-01-05 07:14:19 +01:00
Darko Luketic
4cef25c4cb docs: Add gt config command documentation
Updates README.md and docs/reference.md with the new gt config command usage, including:
- All subcommands (agent list, get, set, remove, default-agent)
- Example of setting up a custom agent (claude-glm)
- Note about overriding built-in agents

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-05 07:12:14 +01:00
Steve Yegge
1508177d9a fix(crew): infer rig from cwd for 'gt crew start --all'
The crew start command now infers the rig name from the current
working directory when using --all without specifying a rig. This
matches the behavior of crew stop and other commands.

Before: gt crew start gastown --all (required)
After:  gt crew start --all (infers from cwd)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 22:10:47 -08:00
Darko Luketic
5787a16067 feat: Add gt config command for managing agent settings
Implements GitHub issue #127 - allow custom agent configuration
through a CLI interface instead of command-line aliases.

The gt config command provides:
- gt config agent list [--json]    List all agents
- gt config agent get <name>       Show agent configuration
- gt config agent set <name> <cmd> Set custom agent command
- gt config agent remove <name>    Remove custom agent
- gt config default-agent [name]   Get/set default agent

Users can now define custom agents (e.g., claude-glm) and
override built-in presets (claude, gemini, codex) through
town settings instead of shell aliases.

Changes:
- Add SaveTownSettings() to internal/config/loader.go
- Add internal/cmd/config.go with full config command implementation
- Add comprehensive unit tests for both SaveTownSettings and
  all config subcommands (17 test cases covering success and
  error scenarios)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-05 06:58:46 +01:00
slit
2d56b6c02b test: Add E2E integration tests for hook slot verification (mi-3zc)
Add comprehensive integration tests covering hook slot operations:
- BasicHook: Verify bead can be hooked to an agent
- Singleton: Document that bd allows multiple hooks (gt enforces singleton)
- Unhook: Verify hook removal via status change
- DifferentAgents: Verify independent hooks per agent
- HookPersistence: Verify hooks survive beads instance recreation
- StatusTransitions: Test open -> hooked -> open -> hooked -> closed

Also fix missing json import in install_integration_test.go.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 19:46:27 -08:00
alice
8f03b44771 test: Add unit tests for formatTrackBeadID helper
Extract the cross-rig bead formatting logic into a testable helper
function and add comprehensive unit tests:

- TestFormatTrackBeadID: 8 test cases covering HQ beads, cross-rig
  beads, and edge cases (single segment, empty string, many segments)
- TestFormatTrackBeadIDConsumerCompatibility: 3 test cases verifying
  the external ref format can be correctly parsed by consumers in
  convoy.go, model.go, feed/convoy.go, and web/fetcher.go

The helper function includes godoc with examples showing expected
behavior for different bead ID formats.
2026-01-04 20:53:17 -05:00
gastown/witness
e11bcb931e fix(sling): Format cross-rig beads as external refs in convoy tracking
When creating auto-convoys for cross-rig beads (e.g., gt-xxx or gu-xxx),
the tracking relation was failing because bd couldn't resolve the bead ID
from HQ context. Now formats non-HQ beads as external:prefix:id for proper
resolution.

Fixes convoy tracking for cross-rig sling operations.
2026-01-04 20:28:28 -05:00
vuvalini
f0c94db99e fix: Add explicit wisp respawn instructions for patrol agents
When patrol agents (witness, refinery, deacon) complete their patrol wisp,
they were left idle because the instructions only said "loop back" without
specifying the command to create a new wisp.

Updated:
- Work loop instructions in prime.go now explicitly tell agents:
  * If context LOW: run `bd mol wisp mol-<role>-patrol` to create new wisp
  * If context HIGH: use `gt handoff` and exit for daemon respawn
- mol-witness-patrol.formula.toml loop-or-exit step now has clear commands

This ensures patrol agents always either create a new wisp or exit cleanly,
preventing the "session alive but idle" state that caused mail to pile up.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 16:55:56 -08:00
rockryder
8592098036 fix: Hook persists across session interruption via in_progress lookup (gt-ttn3h)
The hook query now falls back to checking in_progress beads assigned to the
agent when no hooked beads are found. This ensures work is not lost when
a session is interrupted after claiming work.

Previously, gt hook only looked for status=hooked beads, so work that had
been claimed but not completed appeared lost. The fix extends the query to
also include in_progress beads assigned to the agent.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 16:52:42 -08:00
nux
3b9d1a113c fix(sling): Set hook slot when creating agent beads
Sync with mayor/rig fix: Set hook slot in CreateAgentBead and pass
beadID to UpdateAgentState.

Fixes: mi-619

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 16:28:57 -08:00
Olivier Debeuf De Rijcker
84009a3ee8 fix: add missing encoding/json import in integration test 2026-01-04 22:57:51 +01:00
Olivier Debeuf De Rijcker
3d0183a3bb Merge branch 'main' into fix/polecat-start-from-origin-main 2026-01-04 22:54:55 +01:00
Olivier Debeuf De Rijcker
fec51d60e0 fix: add missing encoding/json import in integration test 2026-01-04 22:35:55 +01:00
Olivier Debeuf De Rijcker
569cb182a6 fix: polecat workers start from origin/<default-branch> when recycled
When a polecat worker is recycled via RecreateWithOptions, it now starts
from the latest fetched origin/<default-branch> instead of the stale HEAD.

Previously, `WorktreeAdd` created branches from the current HEAD, but after
fetching, HEAD still pointed to old commits. The new `WorktreeAddFromRef`
method allows specifying a start point (e.g., "origin/main").

Fixes #101
2026-01-04 22:15:30 +01:00
rictus
12236f24e3 Make TestDoneRedirectChain assertion deterministic
Address review comment: the test now explicitly asserts that ResolveBeadsDir
follows exactly one level of redirect, returning intermediate (not canonical).

The implementation intentionally does NOT follow chains transitively - it stops
at the first resolved path and prints a warning about the detected chain.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 10:33:27 -08:00
Mike Lady
717a82753c test(done): add tests for beads redirect support
Add tests verifying that done.go correctly uses beads.ResolveBeadsDir()
to follow .beads/redirect files. This is critical for polecat/crew
worktrees that redirect to a shared mayor/rig/.beads directory.

Tests cover:
- Redirect followed from polecat directory
- Both ExitCompleted (line 181) and ExitPhaseComplete (line 277) paths
- Fallback behavior when no redirect exists
- Empty redirect file handling
- Circular redirect protection
- Redirect chain handling

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 04:12:19 -08:00
Mike Lady
c3269ec841 fix(done): use ResolveBeadsDir for redirect file support
gt done was not following .beads/redirect files, causing it to fail
in worktrees where beads are redirected to a shared location.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 04:01:44 -08:00
nux
b8eca6c04a feat: notify dispatcher when polecat work completes
When a crew or other agent dispatches work to a polecat using `gt sling`,
the polecat now tracks who dispatched the work and sends them a completion
notification when running `gt done`.

Changes:
- Add DispatchedBy field to AttachmentFields in beads/fields.go
- Store dispatcher agent ID in bead when slinging (both direct and formula)
- Check for dispatcher in done.go and send WORK_DONE notification to them

This fixes the orchestration issue where crews were left waiting because
polecats only notified the Witness on completion, not the dispatcher.

Fixes: id-c17

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 22:24:48 -05:00
243 changed files with 24819 additions and 9367 deletions

16
.beads/.gitignore vendored
View File

@@ -10,6 +10,8 @@ daemon.lock
daemon.log
daemon.pid
bd.sock
sync-state.json
last-touched
# Local version tracking (prevents upgrade notification spam after git ops)
.local_version
@@ -18,6 +20,10 @@ bd.sock
db.sqlite
bd.db
# Worktree redirect file (contains relative path to main repo's .beads/)
# Must not be committed as paths would be wrong in other clones
redirect
# Merge artifacts (temporary files from 3-way merge)
beads.base.jsonl
beads.base.meta.json
@@ -26,8 +32,8 @@ beads.left.meta.json
beads.right.jsonl
beads.right.meta.json
# Keep JSONL exports and config (source of truth for git)
!issues.jsonl
!interactions.jsonl
!metadata.json
!config.json
# NOTE: Do NOT add negation patterns (e.g., !issues.jsonl) here.
# They would override fork protection in .git/info/exclude, allowing
# contributors to accidentally commit upstream issue databases.
# The JSONL files (issues.jsonl, interactions.jsonl) and config files
# are tracked by git by default since no pattern above ignores them.

View File

@@ -56,7 +56,7 @@ needs = ['patrol-cleanup']
title = 'Check own context limit'
[[steps]]
description = "End of patrol cycle decision.\n\n**If context LOW**:\n- Sleep briefly to avoid tight loop (30-60 seconds)\n- Return to inbox-check step\n- Continue patrolling\n\n**If context HIGH**:\n- Write handoff mail to self with any notable observations:\n```bash\ngt handoff -s \"Witness patrol handoff\" -m \"<observations>\"\n```\n- Exit cleanly (daemon respawns fresh Witness)\n\nThe daemon ensures Witness is always running."
description = "End of patrol cycle decision.\n\n**If context LOW** (can continue patrolling):\n1. Generate a brief summary of this patrol cycle\n2. Squash the current wisp:\n```bash\nbd mol squash <mol-id> --summary \"<patrol-summary>\"\n```\n3. Create a new patrol wisp:\n```bash\nbd mol wisp mol-witness-patrol\n```\n4. Continue executing from the inbox-check step of the new wisp\n\n**If context HIGH** (approaching limit):\n1. Write handoff mail with notable observations:\n```bash\ngt handoff -s \"Witness patrol handoff\" -m \"<observations>\"\n```\n2. Exit cleanly - the daemon will respawn a fresh Witness session\n\n**IMPORTANT**: You must either create a new wisp (context LOW) or exit (context HIGH).\nNever leave the session idle without work on your hook."
id = 'loop-or-exit'
needs = ['context-check']
title = 'Loop or exit for respawn'

File diff suppressed because one or more lines are too long

View File

@@ -1 +0,0 @@
gt-gastown-polecat-warboy

View File

@@ -1,4 +0,0 @@
{
"database": "beads.db",
"jsonl_export": "issues.jsonl"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-09eim",
"branch": "polecat/toast-1767088545235",
"target": "main",
"source_issue": "toast-1767088545235",
"worker": "",
"rig": "gastown",
"title": "Merge: toast-1767088545235",
"priority": 2,
"created_at": "2025-12-30T02:01:08.537717-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-0a0vr",
"branch": "polecat/furiosa-1767087671424",
"target": "main",
"source_issue": "furiosa-1767087671424",
"worker": "",
"rig": "gastown",
"title": "Merge: furiosa-1767087671424",
"priority": 2,
"created_at": "2025-12-30T01:53:07.730594-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-0h89l",
"branch": "polecat/furiosa-1767084006859",
"target": "main",
"source_issue": "furiosa-1767084006859",
"worker": "",
"rig": "gastown",
"title": "Merge: furiosa-1767084006859",
"priority": 2,
"created_at": "2025-12-30T00:47:11.803227-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-215tk",
"branch": "polecat/warboy-1767106060799",
"target": "main",
"source_issue": "warboy-1767106060799",
"worker": "",
"rig": "gastown",
"title": "Merge: warboy-1767106060799",
"priority": 2,
"created_at": "2025-12-30T10:40:55.503776-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-2c4o0",
"branch": "polecat/dementus-1767087772272",
"target": "main",
"source_issue": "dementus-1767087772272",
"worker": "",
"rig": "gastown",
"title": "Merge: dementus-1767087772272",
"priority": 2,
"created_at": "2025-12-30T02:06:35.286507-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-2hirc",
"branch": "polecat/capable-1767084028536",
"target": "main",
"source_issue": "capable-1767084028536",
"worker": "",
"rig": "gastown",
"title": "Merge: capable-1767084028536",
"priority": 2,
"created_at": "2025-12-30T01:03:19.471054-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-2puev",
"branch": "polecat/dementus-1767081113622",
"target": "main",
"source_issue": "dementus-1767081113622",
"worker": "dementus-1767081113622",
"rig": "gastown",
"title": "Merge: dementus-1767081113622",
"priority": 2,
"created_at": "2025-12-30T00:05:15.468509-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-2tspu",
"branch": "polecat/furiosa-dogs",
"target": "main",
"source_issue": "furiosa-dogs",
"worker": "",
"rig": "gastown",
"title": "Merge: furiosa-dogs",
"priority": 2,
"created_at": "2025-12-30T10:42:17.458391-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-3gepq",
"branch": "polecat/toast-1767081120579",
"target": "main",
"source_issue": "toast-1767081120579",
"worker": "toast-1767081120579",
"rig": "gastown",
"title": "Merge: toast-1767081120579",
"priority": 2,
"created_at": "2025-12-30T00:05:15.468721-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-4a9y4",
"branch": "polecat/slit-1767138831931",
"target": "main",
"source_issue": "slit-1767138831931",
"worker": "",
"rig": "gastown",
"title": "Merge: slit-1767138831931",
"priority": 2,
"created_at": "2025-12-30T16:15:39.347085-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-4nobz",
"branch": "polecat/capable-1767140263101",
"target": "main",
"source_issue": "capable-1767140263101",
"worker": "",
"rig": "gastown",
"title": "Merge: capable-1767140263101",
"priority": 2,
"created_at": "2025-12-30T16:26:48.128098-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-4q7wh",
"branch": "polecat/nux-1767141948667",
"target": "main",
"source_issue": "nux-1767141948667",
"worker": "",
"rig": "gastown",
"title": "Merge: nux-1767141948667",
"priority": 2,
"created_at": "2025-12-30T16:51:43.00565-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-5ggcs",
"branch": "polecat/slit-1767082302712",
"target": "main",
"source_issue": "slit-1767082302712",
"worker": "",
"rig": "gastown",
"title": "Merge: slit-1767082302712",
"priority": 2,
"created_at": "2025-12-30T00:18:54.19263-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-643ie",
"branch": "polecat/slit-1767141951901",
"target": "main",
"source_issue": "slit-1767141951901",
"worker": "",
"rig": "gastown",
"title": "Merge: slit-1767141951901",
"priority": 2,
"created_at": "2025-12-30T16:56:13.685311-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-6l7h1",
"branch": "polecat/morsov-dogs",
"target": "main",
"source_issue": "morsov-dogs",
"worker": "",
"rig": "gastown",
"title": "Merge: morsov-dogs",
"priority": 2,
"created_at": "2025-12-30T10:41:30.109352-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-804je",
"branch": "polecat/dementus-1767146229184",
"target": "main",
"source_issue": "dementus-1767146229184",
"worker": "",
"rig": "gastown",
"title": "Merge: dementus-1767146229184",
"priority": 2,
"created_at": "2025-12-30T18:01:50.012819-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-860md",
"branch": "polecat/capable-1767146233256",
"target": "main",
"source_issue": "capable-1767146233256",
"worker": "",
"rig": "gastown",
"title": "Merge: capable-1767146233256",
"priority": 2,
"created_at": "2025-12-30T18:03:37.998767-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-9g6md",
"branch": "polecat/nux-1767082300311",
"target": "main",
"source_issue": "nux-1767082300311",
"worker": "",
"rig": "gastown",
"title": "Merge: nux-1767082300311",
"priority": 2,
"created_at": "2025-12-30T00:18:32.959791-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-9hfky",
"branch": "polecat/toast-1767140378007",
"target": "main",
"source_issue": "toast-1767140378007",
"worker": "",
"rig": "gastown",
"title": "Merge: toast-1767140378007",
"priority": 2,
"created_at": "2025-12-30T16:28:18.459411-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-aa1jz",
"branch": "polecat/keeper-dogs",
"target": "main",
"source_issue": "keeper-dogs",
"worker": "",
"rig": "gastown",
"title": "Merge: keeper-dogs",
"priority": 2,
"created_at": "2025-12-30T10:36:28.247719-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-apft7",
"branch": "polecat/capable-1767084028536",
"target": "main",
"source_issue": "capable-1767084028536",
"worker": "",
"rig": "gastown",
"title": "Merge: capable-1767084028536",
"priority": 2,
"created_at": "2025-12-30T01:04:07.334023-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-bnfus",
"branch": "polecat/rictus-1767138835254",
"target": "main",
"source_issue": "rictus-1767138835254",
"worker": "",
"rig": "gastown",
"title": "Merge: rictus-1767138835254",
"priority": 2,
"created_at": "2025-12-30T16:27:17.228997-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-bx4ki",
"branch": "polecat/keeper-dogs",
"target": "main",
"source_issue": "keeper-dogs",
"worker": "",
"rig": "gastown",
"title": "Merge: keeper-dogs",
"priority": 2,
"created_at": "2025-12-30T10:53:39.674941-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-c7qtp",
"branch": "polecat/rictus-1767084016819",
"target": "main",
"source_issue": "rictus-1767084016819",
"worker": "",
"rig": "gastown",
"title": "Merge: rictus-1767084016819",
"priority": 2,
"created_at": "2025-12-30T00:49:18.337909-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-cfpd8",
"branch": "polecat/capable-mq-events",
"target": "main",
"source_issue": "capable-mq",
"worker": "",
"rig": "gastown",
"title": "Merge: capable-mq",
"priority": 2,
"created_at": "2025-12-30T01:14:13.648371-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-cpxxv",
"branch": "polecat/organic-1767106082951",
"target": "main",
"source_issue": "organic-1767106082951",
"worker": "",
"rig": "gastown",
"title": "Merge: organic-1767106082951",
"priority": 2,
"created_at": "2025-12-30T10:42:25.228746-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-djv74",
"branch": "polecat/nux-1767081106779",
"target": "main",
"source_issue": "nux-1767081106779",
"worker": "nux-1767081106779",
"rig": "gastown",
"title": "Merge: nux-1767081106779",
"priority": 2,
"created_at": "2025-12-30T00:05:15.468625-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-dufx1",
"branch": "polecat/capable-1767140263101",
"target": "main",
"source_issue": "capable-1767140263101",
"worker": "",
"rig": "gastown",
"title": "Merge: capable-1767140263101",
"priority": 2,
"created_at": "2025-12-30T16:24:39.547495-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-e0p84",
"branch": "polecat/toast-1767081120579",
"target": "main",
"source_issue": "toast-1767081120579",
"worker": "toast-1767081120579",
"rig": "gastown",
"title": "Merge: toast-1767081120579",
"priority": 2,
"created_at": "2025-12-30T00:05:15.468573-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-gdbcb",
"branch": "polecat/rictus-1767141956287",
"target": "main",
"source_issue": "rictus-1767141956287",
"worker": "",
"rig": "gastown",
"title": "Merge: rictus-1767141956287",
"priority": 2,
"created_at": "2025-12-30T16:47:36.875216-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-gnuat",
"branch": "polecat/dementus-1767081113622",
"target": "main",
"source_issue": "dementus-1767081113622",
"worker": "dementus-1767081113622",
"rig": "gastown",
"title": "Merge: dementus-1767081113622",
"priority": 2,
"created_at": "2025-12-30T00:05:15.468374-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-gres0",
"branch": "polecat/nux-1767084010093",
"target": "main",
"source_issue": "nux-1767084010093",
"worker": "",
"rig": "gastown",
"title": "Merge: nux-1767084010093",
"priority": 2,
"created_at": "2025-12-30T00:48:40.079116-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-hrhts",
"branch": "polecat/cheedo-1767146245543",
"target": "main",
"source_issue": "cheedo-1767146245543",
"worker": "",
"rig": "gastown",
"title": "Merge: cheedo-1767146245543",
"priority": 2,
"created_at": "2025-12-30T18:00:27.283919-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-i6xqu",
"branch": "polecat/toast-1767146237529",
"target": "main",
"source_issue": "toast-1767146237529",
"worker": "",
"rig": "gastown",
"title": "Merge: toast-1767146237529",
"priority": 2,
"created_at": "2025-12-30T18:03:32.883944-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-i7tmd",
"branch": "polecat/rictus-1767084016819",
"target": "main",
"source_issue": "rictus-1767084016819",
"worker": "",
"rig": "gastown",
"title": "Merge: rictus-1767084016819",
"priority": 2,
"created_at": "2025-12-30T00:58:46.110174-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-i9y2a",
"branch": "polecat/toast-1767146237529",
"target": "main",
"source_issue": "toast-1767146237529",
"worker": "",
"rig": "gastown",
"title": "Merge: toast-1767146237529",
"priority": 2,
"created_at": "2025-12-30T18:04:15.705404-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-iai8v",
"branch": "polecat/nux-1767082300311",
"target": "main",
"source_issue": "nux-1767082300311",
"worker": "",
"rig": "gastown",
"title": "Merge: nux-1767082300311",
"priority": 2,
"created_at": "2025-12-30T00:16:15.874394-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-jl4ze",
"branch": "polecat/dementus-1767084022436",
"target": "main",
"source_issue": "dementus-1767084022436",
"worker": "",
"rig": "gastown",
"title": "Merge: dementus-1767084022436",
"priority": 2,
"created_at": "2025-12-30T00:49:44.391479-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-jsoiw",
"branch": "polecat/dag-1767146241770",
"target": "main",
"source_issue": "dag-1767146241770",
"worker": "",
"rig": "gastown",
"title": "Merge: dag-1767146241770",
"priority": 2,
"created_at": "2025-12-30T18:03:10.025552-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-klu0r",
"branch": "polecat/nux-1767083432904",
"target": "main",
"source_issue": "nux-1767083432904",
"worker": "",
"rig": "gastown",
"title": "Merge: nux-1767083432904",
"priority": 2,
"created_at": "2025-12-30T00:35:43.911656-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-l2b6v",
"branch": "polecat/slit-1767084013378",
"target": "main",
"source_issue": "slit-1767084013378",
"worker": "",
"rig": "gastown",
"title": "Merge: slit-1767084013378",
"priority": 2,
"created_at": "2025-12-30T00:49:46.335483-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-nduix",
"branch": "polecat/nux-1767138828269",
"target": "main",
"source_issue": "nux-1767138828269",
"worker": "",
"rig": "gastown",
"title": "Merge: nux-1767138828269",
"priority": 2,
"created_at": "2025-12-30T16:17:54.718789-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-npu0m",
"branch": "polecat/imperator-1767106079026",
"target": "main",
"source_issue": "imperator-1767106079026",
"worker": "",
"rig": "gastown",
"title": "Merge: imperator-1767106079026",
"priority": 2,
"created_at": "2025-12-30T10:40:11.954481-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-nq5l9",
"branch": "polecat/nux-1767087680976",
"target": "main",
"source_issue": "nux-1767087680976",
"worker": "",
"rig": "gastown",
"title": "Merge: nux-1767087680976",
"priority": 2,
"created_at": "2025-12-30T13:43:41.691922-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-nu47q",
"branch": "polecat/rictus-1767087768853",
"target": "main",
"source_issue": "rictus-1767087768853",
"worker": "",
"rig": "gastown",
"title": "Merge: rictus-1767087768853",
"priority": 2,
"created_at": "2025-12-30T01:54:12.913353-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-pulkh",
"branch": "polecat/ace-dogs",
"target": "main",
"source_issue": "ace-dogs",
"worker": "",
"rig": "gastown",
"title": "Merge: ace-dogs",
"priority": 2,
"created_at": "2025-12-30T10:36:01.970507-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-qduud",
"branch": "polecat/furiosa-1767084006859",
"target": "main",
"source_issue": "furiosa-1767084006859",
"worker": "",
"rig": "gastown",
"title": "Merge: furiosa-1767084006859",
"priority": 2,
"created_at": "2025-12-30T00:48:06.518381-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-r099o",
"branch": "polecat/imperator-1767106079026",
"target": "main",
"source_issue": "imperator-1767106079026",
"worker": "",
"rig": "gastown",
"title": "Merge: imperator-1767106079026",
"priority": 2,
"created_at": "2025-12-30T10:46:40.452899-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-sp1tv",
"branch": "polecat/rictus-1767081110235",
"target": "main",
"source_issue": "rictus-1767081110235",
"worker": "rictus-1767081110235",
"rig": "gastown",
"title": "Merge: rictus-1767081110235",
"priority": 2,
"created_at": "2025-12-30T00:05:15.468677-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-svmj8",
"branch": "polecat/cheedo-1767088553821",
"target": "main",
"source_issue": "cheedo-1767088553821",
"worker": "",
"rig": "gastown",
"title": "Merge: cheedo-1767088553821",
"priority": 2,
"created_at": "2025-12-30T10:37:17.028645-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-t072g",
"branch": "polecat/nux-1767084010093",
"target": "main",
"source_issue": "nux-1767084010093",
"worker": "",
"rig": "gastown",
"title": "Merge: nux-1767084010093",
"priority": 2,
"created_at": "2025-12-30T00:50:06.177433-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-tjy9r",
"branch": "polecat/capable-1767074974673",
"target": "main",
"source_issue": "capable-1767074974673",
"worker": "capable-1767074974673",
"rig": "gastown",
"title": "Merge: capable-1767074974673",
"priority": 2,
"created_at": "2025-12-30T00:05:15.468769-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-tpq7i",
"branch": "polecat/keeper-1767074342207",
"target": "main",
"source_issue": "keeper-1767074342207",
"worker": "keeper-1767074342207",
"rig": "gastown",
"title": "Merge: keeper-1767074342207",
"priority": 2,
"created_at": "2025-12-30T00:05:15.468817-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-u65t8",
"branch": "polecat/valkyrie-1767106008400",
"target": "main",
"source_issue": "valkyrie-1767106008400",
"worker": "",
"rig": "gastown",
"title": "Merge: valkyrie-1767106008400",
"priority": 2,
"created_at": "2025-12-30T10:43:03.505961-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-ug23r",
"branch": "polecat/cheedo-1767088553821",
"target": "main",
"source_issue": "cheedo-1767088553821",
"worker": "",
"rig": "gastown",
"title": "Merge: cheedo-1767088553821",
"priority": 2,
"created_at": "2025-12-30T02:00:38.571996-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-w4v1o",
"branch": "polecat/furiosa-dogs",
"target": "main",
"source_issue": "furiosa-dogs",
"worker": "",
"rig": "gastown",
"title": "Merge: furiosa-dogs",
"priority": 2,
"created_at": "2025-12-30T11:01:55.023855-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-x1xf4",
"branch": "polecat/slit-1767087730371",
"target": "main",
"source_issue": "slit-1767087730371",
"worker": "",
"rig": "gastown",
"title": "Merge: slit-1767087730371",
"priority": 2,
"created_at": "2025-12-30T01:52:04.349503-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-xv6b6",
"branch": "polecat/dementus-1767140140908",
"target": "main",
"source_issue": "dementus-1767140140908",
"worker": "",
"rig": "gastown",
"title": "Merge: dementus-1767140140908",
"priority": 2,
"created_at": "2025-12-30T16:23:04.504091-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-yh051",
"branch": "polecat/rictus-1767084016819",
"target": "main",
"source_issue": "rictus-1767084016819",
"worker": "",
"rig": "gastown",
"title": "Merge: rictus-1767084016819",
"priority": 2,
"created_at": "2025-12-30T00:48:16.329248-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-yjrb7",
"branch": "polecat/furiosa-dogs",
"target": "main",
"source_issue": "furiosa-dogs",
"worker": "",
"rig": "gastown",
"title": "Merge: furiosa-dogs",
"priority": 2,
"created_at": "2025-12-30T10:52:57.896189-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-yqxcq",
"branch": "polecat/furiosa-1767141944421",
"target": "main",
"source_issue": "furiosa-1767141944421",
"worker": "",
"rig": "gastown",
"title": "Merge: furiosa-1767141944421",
"priority": 2,
"created_at": "2025-12-30T16:49:14.139123-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-zet9d",
"branch": "polecat/nux-1767087680976",
"target": "main",
"source_issue": "nux-1767087680976",
"worker": "",
"rig": "gastown",
"title": "Merge: nux-1767087680976",
"priority": 2,
"created_at": "2025-12-30T01:50:53.298145-08:00"
}

View File

@@ -1,11 +0,0 @@
{
"id": "gt-zvfnu",
"branch": "polecat/furiosa-1767138824776",
"target": "main",
"source_issue": "furiosa-1767138824776",
"worker": "",
"rig": "gastown",
"title": "Merge: furiosa-1767138824776",
"priority": 2,
"created_at": "2025-12-30T16:09:55.272069-08:00"
}

33
.githooks/pre-push Executable file
View File

@@ -0,0 +1,33 @@
#!/bin/bash
# Block PRs by preventing pushes to arbitrary feature branches.
# Gas Town agents push to main (crew) or polecat/* branches (polecats).
# PRs are for external contributors only.
# Allowed patterns:
# main, beads-sync - Direct work branches
# polecat/* - Polecat working branches (Refinery merges these)
while read local_ref local_sha remote_ref remote_sha; do
branch="${remote_ref#refs/heads/}"
case "$branch" in
main|beads-sync|polecat/*)
# Allowed branches
;;
*)
echo "ERROR: Invalid branch for Gas Town agents."
echo ""
echo "Blocked push to: $branch"
echo ""
echo "Allowed branches:"
echo " main - Crew workers push here directly"
echo " polecat/* - Polecat working branches"
echo " beads-sync - Beads synchronization"
echo ""
echo "Do NOT create PRs. Push to main or let Refinery merge polecat work."
exit 1
;;
esac
done
exit 0

View File

@@ -0,0 +1,51 @@
name: Block Internal PRs
on:
pull_request:
types: [opened, reopened]
jobs:
block-internal-prs:
name: Block Internal PRs
# Only run if PR is from the same repo (not a fork)
if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
steps:
- name: Close PR and comment
uses: actions/github-script@v7
with:
script: |
const prNumber = context.issue.number;
const branch = context.payload.pull_request.head.ref;
const body = [
'**Internal PRs are not allowed.**',
'',
'Gas Town agents push directly to main. PRs are for external contributors only.',
'',
'To land your changes:',
'```bash',
'git checkout main',
'git merge ' + branch,
'git push origin main',
'git push origin --delete ' + branch,
'```',
'',
'See CLAUDE.md: "Crew workers push directly to main. No feature branches. NEVER create PRs."'
].join('\n');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
body: body
});
await github.rest.pulls.update({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: prNumber,
state: 'closed'
});
core.setFailed('Internal PR blocked. Push directly to main instead.');

View File

@@ -33,6 +33,36 @@ jobs:
fi
echo "No .beads/issues.jsonl changes detected"
# Verify committed formulas allow build without go:generate
# This catches issues where go install @latest would fail
check-embedded-formulas:
name: Check embedded formulas
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
- name: Build without go:generate
run: |
# This must succeed with committed formulas only
# If this fails, run: go generate ./... && git add -A && git commit
go build -v ./cmd/gt
- name: Verify formulas are in sync
run: |
# Regenerate and check for differences
go generate ./internal/formula/...
if ! git diff --exit-code internal/formula/formulas/; then
echo ""
echo "ERROR: Committed formulas are out of sync with .beads/formulas/"
echo "Run: go generate ./... && git add -A && git commit"
exit 1
fi
test:
name: Test
runs-on: ubuntu-latest
@@ -49,9 +79,6 @@ jobs:
git config --global user.name "CI Bot"
git config --global user.email "ci@gastown.test"
- name: Generate embedded files
run: go generate ./internal/formula/...
- name: Build
run: go build -v ./cmd/gt
@@ -69,9 +96,6 @@ jobs:
with:
go-version: '1.24'
- name: Generate embedded files
run: go generate ./internal/formula/...
- name: golangci-lint
uses: golangci/golangci-lint-action@v9
with:
@@ -97,9 +121,6 @@ jobs:
- name: Install beads (bd)
run: go install github.com/steveyegge/beads/cmd/bd@latest
- name: Generate embedded files
run: go generate ./internal/formula/...
- name: Build gt
run: go build -v -o gt ./cmd/gt

17
.gitignore vendored
View File

@@ -17,6 +17,9 @@
.DS_Store
Thumbs.db
# Claude Code local state
.claude/
# Test
coverage.out
*.test
@@ -29,10 +32,20 @@ gt
# Runtime state
state.json
.runtime/
# Beads runtime state (not tracked)
# Formulas ARE tracked for `go install @latest` - see bottom of file
.beads/redirect
.beads/issues.jsonl
.beads/interactions.jsonl
.beads/metadata.json
.beads/mq/
.beads/last-touched
.beads/daemon-*.log.gz
.beads-wisp/
# Clone-specific CLAUDE.md (regenerated locally per clone)
CLAUDE.md
# Generated by go:generate from .beads/formulas/
internal/formula/formulas/
# Embedded formulas are committed so `go install @latest` works
# Run `go generate ./...` after modifying .beads/formulas/

View File

@@ -7,6 +7,178 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.2.2] - 2026-01-07
Rig operational state management, unified agent startup, and extensive stability fixes.
### Added
#### Rig Operational State Management
- **`gt rig park/unpark` commands** - Level 1 rig control: pause daemon auto-start while preserving sessions
- **`gt rig dock/undock` commands** - Level 2 rig control: stop all sessions and prevent auto-start (gt-9gm9n)
- **`gt rig config` commands** - Per-rig configuration management (gt-hhmkq)
- **Rig identity beads** - Schema and creation for rig identity tracking (gt-zmznh)
- **Property layer lookup** - Hierarchical configuration resolution (gt-emh1c)
- **Operational state in status** - `gt rig status` shows park/dock state
#### Agent Configuration & Startup
- **`--agent` overrides** - Override agent for start/attach/sling commands
- **Unified agent startup** - Manager pattern for consistent agent initialization
- **Claude settings installation** - Auto-install during rig and HQ creation
- **Runtime-aware tmux checks** - Detect actual agent state from tmux sessions
#### Status & Monitoring
- **`gt status --watch`** - Watch mode with auto-refresh (#231)
- **Compact status output** - One-line-per-worker format as new default
- **LED status indicators** - Visual indicators for rigs in Mayor tmux status line
- **Parked/docked indicators** - Pause emoji (⏸) for inactive rigs in statusline
#### Beads & Workflow
- **Minimum beads version check** - Validates beads CLI compatibility (gt-im3fl)
- **ZFC convoy auto-close** - `bd close` triggers convoy completion (gt-3qw5s)
- **Stale hooked bead cleanup** - Deacon clears orphaned hooks (gt-2yls3)
- **Doctor prefix mismatch detection** - Detect misconfigured rig prefixes (gt-17wdl)
- **Unified beads redirect** - Single redirect system for tracked and local beads (#222)
- **Route from rig to town beads** - Cross-level bead routing
#### Infrastructure
- **Windows-compatible file locking** - Daemon lock works on Windows
- **`--purge` flag for crews** - Full crew obliteration option
- **Debug logging for suppressed errors** - Better visibility into startup issues (gt-6d7eh)
- **hq- prefix in tmux cycle bindings** - Navigate to Mayor/Deacon sessions
- **Wisp config storage layer** - Transient/local settings for ephemeral workflows
- **Sparse checkout** - Exclude Claude context files from source repos
### Changed
- **Daemon respects rig operational state** - Parked/docked rigs not auto-started
- **Agent startup unified** - Manager pattern replaces ad-hoc initialization
- **Mayor files moved** - Reorganized into `mayor/` subdirectory
- **Refinery merges local branches** - No longer fetches from origin (gt-cio03)
- **Polecats start from origin/default-branch** - Consistent recycled state
- **Observable states removed** - Discover agent state from tmux, don't track (gt-zecmc)
- **mol-town-shutdown v3** - Complete cleanup formula (gt-ux23f)
- **Witness delays polecat cleanup** - Wait until MR merges (gt-12hwb)
- **Nudge on divergence** - Daemon nudges agents instead of silent accept
- **README rewritten** - Comprehensive guides and architecture docs (#226)
- **`gt rigs``gt rig list`** - Command renamed in templates/docs (#217)
### Fixed
#### Doctor & Lifecycle
- **`--restart-sessions` flag required** - Doctor won't cycle sessions without explicit flag (gt-j44ri)
- **Only cycle patrol roles** - Doctor --fix doesn't restart crew/polecats (hq-qthgye)
- **Session-ended events auto-closed** - Prevent accumulation (gt-8tc1v)
- **GUPP propulsion nudge** - Added to daemon restartSession
#### Sling & Beads
- **Sling uses bd native routing** - No BEADS_DIR override needed
- **Sling parses wisp JSON correctly** - Handle `new_epic_id` field
- **Sling resolves rig path** - Cross-rig bead hooking works
- **Sling waits for Claude ready** - Don't nudge until session responsive (#146)
- **Correct beads database for sling** - Rig-level beads used (gt-n5gga)
- **Close hooked beads before clearing** - Proper cleanup order (gt-vwjz6)
- **Removed dead sling flags** - `--molecule` and `--quality` cleaned up
#### Agent Sessions
- **Witness kills tmux on Stop()** - Clean session termination
- **Deacon uses session package** - Correct hq- session names (gt-r38pj)
- **Honor rig agent for witness/refinery** - Respect per-rig settings
- **Canonical hq role bead IDs** - Consistent naming
- **hq- prefix in status display** - Global agents shown correctly (gt-vcvyd)
- **Restart Claude when dead** - Recover sessions where tmux exists but Claude died
- **Town session cycling** - Works from any directory
#### Polecat & Crew
- **Nuke not blocked by stale hooks** - Closed beads don't prevent cleanup (gt-jc7bq)
- **Crew stop dry-run support** - Preview cleanup before executing (gt-kjcx4)
- **Crew defaults to --all** - `gt crew start <rig>` starts all crew (gt-s8mpt)
- **Polecat cleanup handlers** - `gt witness process` invokes handlers (gt-h3gzj)
#### Daemon & Configuration
- **Create mayor/daemon.json** - `gt start` and `gt doctor --fix` initialize daemon state (#225)
- **Initialize git before beads** - Enable repo fingerprint (#180)
- **Handoff preserves env vars** - Claude Code environment not lost (#216)
- **Agent settings passed correctly** - Witness and daemon respawn use rigPath
- **Log rig discovery errors** - Don't silently swallow (gt-rsnj9)
#### Refinery & Merge Queue
- **Use rig's default_branch** - Not hardcoded 'main'
- **MERGE_FAILED sent to Witness** - Proper failure notification
- **Removed BranchPushedToRemote checks** - Local-only workflow support (gt-dymy5)
#### Misc Fixes
- **BeadsSetupRedirect preserves tracked files** - Don't clobber existing files (gt-fj0ol)
- **PATH export in hooks** - Ensure commands find binaries
- **Replace panic with fallback** - ID generation gracefully degrades (#213)
- **Removed duplicate WorktreeAddFromRef** - Code cleanup
- **Town root beads for Deacon** - Use correct beads location (gt-sstg)
### Refactored
- **AgentStateManager pattern** - Shared state management extracted (gt-gaw8e)
- **CleanupStatus type** - Replace raw strings (gt-77gq7)
- **ExecWithOutput utility** - Common command execution (gt-vurfr)
- **runBdCommand helper** - DRY mail package (gt-8i6bg)
- **Config expansion helper** - Generic DRY config (gt-i85sg)
### Documentation
- **Property layers guide** - Implementation documentation
- **Worktree architecture** - Clarified beads routing
- **Agent config** - Onboarding docs mention --agent overrides
- **Polecat Operations section** - Added to Mayor docs (#140)
### Contributors
Thanks to all contributors for this release:
- @julianknutsen - Claude settings inheritance (#239)
- @joshuavial - Sling wisp JSON parse (#238)
- @michaellady - Unified beads redirect (#222), daemon.json fix (#225)
- @greghughespdx - PATH in hooks fix (#139)
## [0.2.1] - 2026-01-05
Bug fixes, security hardening, and new `gt config` command.
### Added
- **`gt config` command** - Manage agent settings (model, provider) per-rig or globally
- **`hq-` prefix for patrol sessions** - Mayor and Deacon sessions use town-prefixed names
- **Doctor hooks-path check** - Verify Git hooks path is configured correctly
- **Block internal PRs** - Pre-push hook and GitHub Action prevent accidental internal PRs (#117)
- **Dispatcher notifications** - Notify dispatcher when polecat work completes
- **Unit tests** - Added tests for `formatTrackBeadID` helper, done redirect, hook slot E2E
### Fixed
#### Security
- **Command injection prevention** - Validate beads prefix to prevent injection (gt-l1xsa)
- **Path traversal prevention** - Validate crew names to prevent traversal (gt-wzxwm)
- **ReDoS prevention** - Escape user input in mail search (gt-qysj9)
- **Error handling** - Handle crypto/rand.Read errors in ID generation
#### Convoy & Sling
- **Hook slot initialization** - Set hook slot when creating agent beads during sling (#124)
- **Cross-rig bead formatting** - Format cross-rig beads as external refs in convoy tracking (#123)
- **Reliable bd calls** - Add `--no-daemon` and `BEADS_DIR` for reliable beads operations
#### Rig Inference
- **`gt rig status`** - Infer rig name from current working directory
- **`gt crew start --all`** - Infer rig from cwd for batch crew starts
- **`gt prime` in crew start** - Pass as initial prompt in crew start commands
- **Town default_agent** - Honor default agent setting for Mayor and Deacon
#### Session & Lifecycle
- **Hook persistence** - Hook persists across session interruption via `in_progress` lookup (gt-ttn3h)
- **Polecat cleanup** - Clean up stale worktrees and git tracking
- **`gt done` redirect** - Use ResolveBeadsDir for redirect file support
#### Build & CI
- **Embedded formulas** - Sync and commit formulas for `go install @latest`
- **CI lint fixes** - Resolve lint and build errors
- **Flaky test fix** - Sync database before beads integration tests
## [0.2.0] - 2026-01-04
Major release featuring the Convoy Dashboard, two-level beads architecture, and significant multi-agent improvements.

View File

@@ -23,7 +23,7 @@ ifeq ($(shell uname),Darwin)
endif
install: build
cp $(BUILD_DIR)/$(BINARY) ~/bin/$(BINARY)
cp $(BUILD_DIR)/$(BINARY) ~/.local/bin/$(BINARY)
clean:
rm -f $(BUILD_DIR)/$(BINARY)

578
README.md
View File

@@ -1,372 +1,436 @@
# Gas Town
Multi-agent orchestrator for Claude Code. Track work with convoys; sling to agents.
**Multi-agent orchestration system for Claude Code with persistent work tracking**
## Why Gas Town?
## Overview
| Without | With Gas Town |
|---------|---------------|
| Agents forget work after restart | Work persists on hooks - survives crashes, compaction, restarts |
| Manual coordination | Agents have mailboxes, identities, and structured handoffs |
| 4-10 agents is chaotic | Comfortably scale to 20-30 agents |
| Work state in agent memory | Work state in Beads (git-backed ledger) |
Gas Town is a workspace manager that lets you coordinate multiple Claude Code agents working on different tasks. Instead of losing context when agents restart, Gas Town persists work state in git-backed hooks, enabling reliable multi-agent workflows.
## Prerequisites
### What Problem Does This Solve?
- **Go 1.23+** - [go.dev/dl](https://go.dev/dl/)
- **Git 2.25+** - for worktree support
- **beads (bd)** - [github.com/steveyegge/beads](https://github.com/steveyegge/beads) - required for issue tracking
- **tmux 3.0+** - recommended for the full experience (the Mayor session is the primary interface)
- **Claude Code CLI** - [claude.ai/code](https://claude.ai/code)
| Challenge | Gas Town Solution |
| ------------------------------- | -------------------------------------------- |
| Agents lose context on restart | Work persists in git-backed hooks |
| Manual agent coordination | Built-in mailboxes, identities, and handoffs |
| 4-10 agents become chaotic | Scale comfortably to 20-30 agents |
| Work state lost in agent memory | Work state stored in Beads ledger |
## Quick Start
### Architecture
```bash
# Install
go install github.com/steveyegge/gastown/cmd/gt@latest
```mermaid
graph TB
Mayor[The Mayor<br/>AI Coordinator]
Town[Town Workspace<br/>~/gt/]
# Ensure Go binaries are in your PATH (add to ~/.zshrc or ~/.bashrc)
export PATH="$PATH:$HOME/go/bin"
Town --> Mayor
Town --> Rig1[Rig: Project A]
Town --> Rig2[Rig: Project B]
# Create workspace (--git auto-initializes git repository)
gt install ~/gt --git
cd ~/gt
Rig1 --> Crew1[Crew Member<br/>Your workspace]
Rig1 --> Hooks1[Hooks<br/>Persistent storage]
Rig1 --> Polecats1[Polecats<br/>Worker agents]
# Add a project
gt rig add myproject https://github.com/you/repo.git
Rig2 --> Crew2[Crew Member]
Rig2 --> Hooks2[Hooks]
Rig2 --> Polecats2[Polecats]
# Create your personal workspace
gt crew add <yourname> --rig myproject
Hooks1 -.git worktree.-> GitRepo1[Git Repository]
Hooks2 -.git worktree.-> GitRepo2[Git Repository]
# Start working
cd myproject/crew/<yourname>
```
For advanced multi-agent coordination, use the Mayor session:
```bash
gt mayor attach # Enter the Mayor's office
```
Inside the Mayor session, you're talking to Claude with full town context:
> "Help me fix the authentication bug in myproject"
The Mayor will create convoys, dispatch workers, and coordinate everything. You can also run CLI commands directly:
```bash
# Create a convoy and sling work (CLI workflow)
gt convoy create "Feature X" issue-123 issue-456 --notify --human
gt sling issue-123 myproject
# Track progress
gt convoy list
# Switch between agent sessions
gt agents
style Mayor fill:#e1f5ff
style Town fill:#f0f0f0
style Rig1 fill:#fff4e1
style Rig2 fill:#fff4e1
```
## Core Concepts
**The Mayor** is your AI coordinator. It's Claude Code with full context about your workspace, projects, and agents. The Mayor session (`gt prime`) is the primary way to interact with Gas Town - just tell it what you want to accomplish.
### The Mayor 🎩
```
Town (~/gt/) Your workspace
├── Mayor Your AI coordinator (start here)
├── Rig (project) Container for a git project + its agents
│ ├── Polecats Workers (ephemeral, spawn → work → disappear)
│ ├── Witness Monitors workers, handles lifecycle
│ └── Refinery Merge queue processor
```
Your primary AI coordinator. The Mayor is a Claude Code instance with full context about your workspace, projects, and agents. **Start here** - just tell the Mayor what you want to accomplish.
**Hook**: Each agent has a hook where work hangs. On wake, run what's on your hook.
### Town 🏘️
**Beads**: Git-backed issue tracker. All work state lives here. [github.com/steveyegge/beads](https://github.com/steveyegge/beads)
Your workspace directory (e.g., `~/gt/`). Contains all projects, agents, and configuration.
## Workflows
### Rigs 🏗️
### Full Stack (Recommended)
Project containers. Each rig wraps a git repository and manages its associated agents.
The primary Gas Town experience. Agents run in tmux sessions with the Mayor as your interface.
### Crew Members 👤
Your personal workspace within a rig. Where you do hands-on work.
### Polecats 🦨
Ephemeral worker agents that spawn, complete a task, and disappear.
### Hooks 🪝
Git worktree-based persistent storage for agent work. Survives crashes and restarts.
### Convoys 🚚
Work tracking units. Bundle multiple issues/tasks that get assigned to agents.
### Beads Integration 📿
Git-backed issue tracking system that stores work state as structured data.
## Installation
### Prerequisites
- **Go 1.23+** - [go.dev/dl](https://go.dev/dl/)
- **Git 2.25+** - for worktree support
- **beads (bd) 0.44.0+** - [github.com/steveyegge/beads](https://github.com/steveyegge/beads) (required for custom type support)
- **tmux 3.0+** - recommended for full experience
- **Claude Code CLI** - [claude.ai/code](https://claude.ai/code)
### Setup
```bash
gt start # Start Gas Town (daemon + Mayor session)
gt mayor attach # Enter Mayor session
# Install Gas Town
go install github.com/steveyegge/gastown/cmd/gt@latest
# Inside Mayor session, just ask:
# "Create a convoy for issues 123 and 456 in myproject"
# "What's the status of my work?"
# "Show me what the witness is doing"
# Add Go binaries to PATH (add to ~/.zshrc or ~/.bashrc)
export PATH="$PATH:$HOME/go/bin"
# Or use CLI commands:
gt convoy create "Feature X" issue-123 issue-456
gt sling issue-123 myproject # Spawns polecat automatically
gt convoy list # Dashboard view
gt agents # Navigate between sessions
# Create workspace with git initialization
gt install ~/gt --git
cd ~/gt
# Add your first project
gt rig add myproject https://github.com/you/repo.git
# Create your crew workspace
gt crew add yourname --rig myproject
cd myproject/crew/yourname
# Start the Mayor session (your main interface)
gt mayor attach
```
### Minimal (No Tmux)
## Quick Start Guide
Run individual Claude Code instances manually. Gas Town just tracks state.
### Basic Workflow
```mermaid
sequenceDiagram
participant You
participant Mayor
participant Convoy
participant Agent
participant Hook
You->>Mayor: Tell Mayor what to build
Mayor->>Convoy: Create convoy with issues
Mayor->>Agent: Sling issue to agent
Agent->>Hook: Store work state
Agent->>Agent: Complete work
Agent->>Convoy: Report completion
Mayor->>You: Summary of progress
```
### Example: Feature Development
```bash
gt convoy create "Fix bugs" issue-123 # Create convoy (sling auto-creates if skipped)
gt sling issue-123 myproject # Assign to worker
claude --resume # Agent reads mail, runs work
gt convoy list # Check progress
# 1. Start the Mayor
gt mayor attach
# 2. In Mayor session, create a convoy
gt convoy create "Feature X" issue-123 issue-456 --notify --human
# 3. Assign work to an agent
gt sling issue-123 myproject
# 4. Track progress
gt convoy list
# 5. Monitor agents
gt agents
```
### Pick Your Roles
## Common Workflows
Gas Town is modular. Run what you need:
### Mayor Workflow (Recommended)
- **Polecats only**: Manual spawning, no monitoring
- **+ Witness**: Automatic worker lifecycle, stuck detection
- **+ Refinery**: Merge queue, code review
- **+ Mayor**: Cross-project coordination
**Best for:** Coordinating complex, multi-issue work
## Cooking Formulas
```mermaid
flowchart LR
Start([Start Mayor]) --> Tell[Tell Mayor<br/>what to build]
Tell --> Creates[Mayor creates<br/>convoy + agents]
Creates --> Monitor[Monitor progress<br/>via convoy list]
Monitor --> Done{All done?}
Done -->|No| Monitor
Done -->|Yes| Review[Review work]
```
Formulas define structured workflows. Cook them, sling them to agents.
**Commands:**
### Basic Example
```bash
# Attach to Mayor
gt mayor attach
# In Mayor, create convoy and let it orchestrate
gt convoy create "Auth System" issue-101 issue-102 --notify
# Track progress
gt convoy list
```
### Beads Formula Workflow
**Best for:** Predefined, repeatable processes
Formulas are TOML-defined workflows stored in `.beads/formulas/`.
**Example Formula** (`.beads/formulas/release.formula.toml`):
```toml
# .beads/formulas/shiny.formula.toml
formula = "shiny"
description = "Design before code, review before ship"
description = "Standard release process"
formula = "release"
version = 1
[[steps]]
id = "design"
description = "Think about architecture"
[[steps]]
id = "implement"
needs = ["design"]
[[steps]]
id = "test"
needs = ["implement"]
[[steps]]
id = "submit"
needs = ["test"]
```
### Using Formulas
```bash
bd formula list # See available formulas
bd cook shiny # Cook into a protomolecule
bd mol pour shiny --var feature=auth # Create runnable molecule
gt convoy create "Auth feature" gt-xyz # Track with convoy
gt sling gt-xyz myproject # Assign to worker
gt convoy list # Monitor progress
```
### What Happens
1. **Cook** expands the formula into a protomolecule (frozen template)
2. **Pour** creates a molecule (live workflow) with steps as beads
3. **Worker executes** each step, closing beads as it goes
4. **Crash recovery**: Worker restarts, reads molecule, continues from last step
### Example: Beads Release Molecule
A real workflow for releasing a new beads version:
```toml
formula = "beads-release"
description = "Version bump and release workflow"
[vars.version]
description = "The semantic version to release (e.g., 1.2.0)"
required = true
[[steps]]
id = "bump-version"
description = "Update version in version.go and CHANGELOG"
[[steps]]
id = "update-deps"
needs = ["bump-version"]
description = "Run go mod tidy, update go.sum"
title = "Bump version"
description = "Run ./scripts/bump-version.sh {{version}}"
[[steps]]
id = "run-tests"
needs = ["update-deps"]
description = "Full test suite, check for regressions"
title = "Run tests"
description = "Run make test"
needs = ["bump-version"]
[[steps]]
id = "build-binaries"
id = "build"
title = "Build"
description = "Run make build"
needs = ["run-tests"]
description = "Cross-compile for all platforms"
[[steps]]
id = "create-tag"
needs = ["build-binaries"]
description = "Git tag with version, push to origin"
title = "Create release tag"
description = "Run git tag -a v{{version}} -m 'Release v{{version}}'"
needs = ["build"]
[[steps]]
id = "publish-release"
id = "publish"
title = "Publish"
description = "Run ./scripts/publish.sh"
needs = ["create-tag"]
description = "Create GitHub release with binaries"
```
Cook it, pour it, sling it. The polecat runs through each step, and if it crashes
after `run-tests`, a new polecat picks up at `build-binaries`.
**Execute:**
### Formula Composition
```bash
# List available formulas
bd formula list
```toml
# Extend an existing formula
formula = "shiny-enterprise"
extends = ["shiny"]
# Run a formula with variables
bd cook release --var version=1.2.0
[compose]
aspects = ["security-audit"] # Add cross-cutting concerns
# Create formula instance for tracking
bd mol pour release --var version=1.2.0
```
### Manual Convoy Workflow
**Best for:** Direct control over work distribution
```bash
# Create convoy manually
gt convoy create "Bug Fixes" --human
# Add issues
gt convoy add-issue bug-101 bug-102
# Assign to specific agents
gt sling bug-101 myproject/my-agent
# Check status
gt convoy show
```
## Key Commands
### For Humans (Overseer)
### Workspace Management
```bash
gt start # Start Gas Town (daemon + agents)
gt shutdown # Graceful shutdown
gt status # Town overview
gt <role> attach # Jump into any agent session
# e.g., gt mayor attach, gt witness attach
gt install <path> # Initialize workspace
gt rig add <name> <repo> # Add project
gt rig list # List projects
gt crew add <name> --rig <rig> # Create crew workspace
```
Most other work happens through agents - just ask them.
### For Agents
### Agent Operations
```bash
# Convoy (primary dashboard)
gt convoy list # Active work across all rigs
gt convoy status <id> # Detailed convoy progress
gt convoy create "name" <issues> # Create new convoy
gt agents # List active agents
gt sling <issue> <rig> # Assign work to agent
gt sling <issue> <rig> --agent codex # Override runtime for this sling/spawn
gt mayor attach # Start Mayor session
gt mayor start --agent gemini # Run Mayor with a specific agent alias
gt prime # Alternative to mayor attach
```
# Work assignment
gt sling <bead> <rig> # Assign work to polecat
bd ready # Show available work
bd list --status=in_progress # Active work
### Convoy (Work Tracking)
# Communication
gt mail inbox # Check messages
gt mail send <addr> -s "..." -m "..."
```bash
gt convoy create <name> [issues...] # Create convoy
gt convoy list # List all convoys
gt convoy show [id] # Show convoy details
gt convoy add-issue <issue> # Add issue to convoy
```
# Lifecycle
gt handoff # Request session cycle
gt peek <agent> # Check agent health
### Configuration
# Diagnostics
gt doctor # Health check
gt doctor --fix # Auto-repair
```bash
# Set custom agent command
gt config agent set claude-glm "claude-glm --model glm-4"
gt config agent set codex-low "codex --thinking low"
# Set default agent
gt config default-agent claude-glm
# View config
gt config show
```
### Beads Integration
```bash
bd formula list # List formulas
bd cook <formula> # Execute formula
bd mol pour <formula> # Create trackable instance
bd mol list # List active instances
```
## Dashboard
Web-based dashboard for monitoring Gas Town activity.
Gas Town includes a web dashboard for monitoring:
```bash
# Start the dashboard
# Start dashboard
gt dashboard --port 8080
# Open in browser
open http://localhost:8080
```
**Features:**
- **Convoy tracking** - View all active convoys with progress bars and work status
- **Polecat workers** - See active worker sessions and their activity status
- **Refinery status** - Monitor merge queue and PR processing
- **Auto-refresh** - Updates every 10 seconds via htmx
Features:
Work status indicators:
| Status | Color | Meaning |
|--------|-------|---------|
| `complete` | Green | All tracked items done |
| `active` | Green | Recent activity (< 1 min) |
| `stale` | Yellow | Activity 1-5 min ago |
| `stuck` | Red | Activity > 5 min ago |
| `waiting` | Gray | No assignee/activity |
- Real-time agent status
- Convoy progress tracking
- Hook state visualization
- Configuration management
## Advanced Concepts
### The Propulsion Principle
Gas Town uses git hooks as a propulsion mechanism. Each hook is a git worktree with:
1. **Persistent state** - Work survives agent restarts
2. **Version control** - All changes tracked in git
3. **Rollback capability** - Revert to any previous state
4. **Multi-agent coordination** - Shared through git
### Hook Lifecycle
```mermaid
stateDiagram-v2
[*] --> Created: Agent spawned
Created --> Active: Work assigned
Active --> Suspended: Agent paused
Suspended --> Active: Agent resumed
Active --> Completed: Work done
Completed --> Archived: Hook archived
Archived --> [*]
```
### MEOW (Mayor-Enhanced Orchestration Workflow)
MEOW is the recommended pattern:
1. **Tell the Mayor** - Describe what you want
2. **Mayor analyzes** - Breaks down into tasks
3. **Convoy creation** - Mayor creates convoy with issues
4. **Agent spawning** - Mayor spawns appropriate agents
5. **Work distribution** - Issues slung to agents via hooks
6. **Progress monitoring** - Track through convoy status
7. **Completion** - Mayor summarizes results
## Shell Completions
Enable tab completion for `gt` commands:
### Bash
```bash
# Add to ~/.bashrc
source <(gt completion bash)
# Bash
gt completion bash > /etc/bash_completion.d/gt
# Or install permanently
gt completion bash > /usr/local/etc/bash_completion.d/gt
```
### Zsh
```bash
# Add to ~/.zshrc (before compinit)
source <(gt completion zsh)
# Or install to fpath
# Zsh
gt completion zsh > "${fpath[1]}/_gt"
```
### Fish
```bash
# Fish
gt completion fish > ~/.config/fish/completions/gt.fish
```
## Roles
## Project Roles
| Role | Scope | Job |
|------|-------|-----|
| **Overseer** | Human | Sets strategy, reviews output, handles escalations |
| **Mayor** | Town-wide | Cross-rig coordination, work dispatch |
| **Deacon** | Town-wide | Daemon process, agent lifecycle, plugin execution |
| **Witness** | Per-rig | Monitor polecats, nudge stuck workers |
| **Refinery** | Per-rig | Merge queue, PR review, integration |
| **Polecat** | Per-task | Execute work, file discovered issues, request shutdown |
| Role | Description | Primary Interface |
| --------------- | ------------------ | -------------------- |
| **Mayor** | AI coordinator | `gt mayor attach` |
| **Human (You)** | Crew member | Your crew directory |
| **Polecat** | Worker agent | Spawned by Mayor |
| **Hook** | Persistent storage | Git worktree |
| **Convoy** | Work tracker | `gt convoy` commands |
## The Propulsion Principle
## Tips
> If your hook has work, RUN IT.
- **Always start with the Mayor** - It's designed to be your primary interface
- **Use convoys for coordination** - They provide visibility across agents
- **Leverage hooks for persistence** - Your work won't disappear
- **Create formulas for repeated tasks** - Save time with Beads recipes
- **Monitor the dashboard** - Get real-time visibility
- **Let the Mayor orchestrate** - It knows how to manage agents
Agents wake up, check their hook, execute the molecule. No waiting for commands.
Molecules survive crashes - any agent can continue where another left off.
## Troubleshooting
---
### Agents lose connection
## Optional: MEOW Deep Dive
Check hooks are properly initialized:
**M**olecular **E**xpression **O**f **W**ork - the full algebra.
```bash
gt hooks list
gt hooks repair
```
### States of Matter
### Convoy stuck
| Phase | Name | Storage | Behavior |
|-------|------|---------|----------|
| Ice-9 | Formula | `.beads/formulas/` | Source template, composable |
| Solid | Protomolecule | `.beads/` | Frozen template, reusable |
| Liquid | Mol | `.beads/` | Flowing work, persistent |
| Vapor | Wisp | `.beads/` (ephemeral flag) | Transient, for patrols |
Force refresh:
*(Protomolecules are an homage to The Expanse. Ice-9 is a nod to Vonnegut.)*
```bash
gt convoy refresh <convoy-id>
```
### Operators
### Mayor not responding
| Operator | From → To | Effect |
|----------|-----------|--------|
| `cook` | Formula → Protomolecule | Expand macros, flatten |
| `pour` | Proto → Mol | Instantiate as persistent |
| `wisp` | Proto → Wisp | Instantiate as ephemeral |
| `squash` | Mol/Wisp → Digest | Condense to permanent record |
| `burn` | Wisp → ∅ | Discard without record |
Restart Mayor session:
---
```bash
gt mayor detach
gt mayor attach
```
## License
MIT
MIT License - see LICENSE file for details
---
**Getting Started:** Run `gt install ~/gt --git && cd ~/gt && gt config agent list && gt mayor attach` (or `gt mayor attach --agent codex`) and tell the Mayor what you want to build!

View File

@@ -130,6 +130,29 @@ gt doctor # Run health checks
gt status # Show workspace status
```
### Step 5: Configure Agents (Optional)
Gas Town supports built-in runtimes (`claude`, `gemini`, `codex`) plus custom agent aliases.
```bash
# List available agents
gt config agent list
# Create an alias (aliases can encode model/thinking flags)
gt config agent set codex-low "codex --thinking low"
gt config agent set claude-haiku "claude --model haiku --dangerously-skip-permissions"
# Set the town default agent (used when a rig doesn't specify one)
gt config default-agent codex-low
```
You can also override the agent per command without changing defaults:
```bash
gt start --agent codex-low
gt sling issue-123 myproject --agent claude-haiku
```
## Minimal Mode vs Full Stack Mode
Gas Town supports two operational modes:
@@ -184,7 +207,7 @@ Gas Town is modular. Enable only what you need:
|--------------|-------|----------|
| **Polecats only** | Workers | Manual spawning, no monitoring |
| **+ Witness** | + Monitor | Automatic lifecycle, stuck detection |
| **+ Refinery** | + Merge queue | PR review, code integration |
| **+ Refinery** | + Merge queue | MR review, code integration |
| **+ Mayor** | + Coordinator | Cross-project coordination |
## Troubleshooting

View File

@@ -84,29 +84,43 @@ Each agent bead references its role bead via the `role_bead` field.
│ └── town.json Town configuration
└── <rig>/ Project container (NOT a git clone)
├── config.json Rig identity and beads prefix
├── .beads/ → mayor/rig/.beads Symlink to canonical beads
├── .repo.git/ Bare repo (shared by worktrees)
├── mayor/rig/ Mayor's clone (canonical beads)
├── refinery/rig/ Worktree on main
├── mayor/rig/ Canonical clone (beads live here)
│ └── .beads/ Rig-level beads database
├── refinery/rig/ Worktree from mayor/rig
├── witness/ No clone (monitors only)
├── crew/<name>/ Human workspaces
└── polecats/<name>/ Worker worktrees
├── crew/<name>/ Human workspaces (full clones)
└── polecats/<name>/ Worker worktrees from mayor/rig
```
### Worktree Architecture
Polecats and refinery are git worktrees, not full clones. This enables fast spawning
and shared object storage. The worktree base is `mayor/rig`:
```go
// From polecat/manager.go - worktrees are based on mayor/rig
git worktree add -b polecat/<name>-<timestamp> polecats/<name>
```
Crew workspaces (`crew/<name>/`) are full git clones for human developers who need
independent repos. Polecats are ephemeral and benefit from worktree efficiency.
## Beads Routing
The `routes.jsonl` file maps issue ID prefixes to their storage locations:
The `routes.jsonl` file maps issue ID prefixes to rig locations (relative to town root):
```jsonl
{"prefix":"hq","path":"/Users/stevey/gt/.beads"}
{"prefix":"gt","path":"/Users/stevey/gt/gastown/mayor/rig/.beads"}
{"prefix":"hq-","path":"."}
{"prefix":"gt-","path":"gastown/mayor/rig"}
{"prefix":"bd-","path":"beads/mayor/rig"}
```
Routes point to `mayor/rig` because that's where the canonical `.beads/` lives.
This enables transparent cross-rig beads operations:
```bash
bd show hq-mayor # Routes to town beads
bd show gt-xyz # Routes to gastown rig beads
bd show hq-mayor # Routes to town beads (~/.gt/.beads)
bd show gt-xyz # Routes to gastown/mayor/rig/.beads
```
## See Also

View File

@@ -12,7 +12,7 @@ They execute molecule steps sequentially, closing each step as they complete it.
| Type | Storage | Use Case |
|------|---------|----------|
| **Regular Molecule** | `.beads/` (synced) | Discrete deliverables, audit trail |
| **Wisp** | `.beads-wisp/` (ephemeral) | Patrol cycles, operational loops |
| **Wisp** | `.beads/` (ephemeral, type=wisp) | Patrol cycles, operational loops |
Polecats typically use **regular molecules** because each assignment has audit value.
Patrol agents (Witness, Refinery, Deacon) use **wisps** to prevent accumulation.

300
docs/property-layers.md Normal file
View File

@@ -0,0 +1,300 @@
# Property Layers: Multi-Level Configuration
> Implementation guide for Gas Town's configuration system.
> Created: 2025-01-06
## Overview
Gas Town uses a layered property system for configuration. Properties are
looked up through multiple layers, with earlier layers overriding later ones.
This enables both local control and global coordination.
## The Four Layers
```
┌─────────────────────────────────────────────────────────────┐
│ 1. WISP LAYER (transient, town-local) │
│ Location: <rig>/.beads-wisp/config/ │
│ Synced: Never │
│ Use: Temporary local overrides │
└─────────────────────────────┬───────────────────────────────┘
│ if missing
┌─────────────────────────────────────────────────────────────┐
│ 2. RIG BEAD LAYER (persistent, synced globally) │
│ Location: <rig>/.beads/ (rig identity bead labels) │
│ Synced: Via git (all clones see it) │
│ Use: Project-wide operational state │
└─────────────────────────────┬───────────────────────────────┘
│ if missing
┌─────────────────────────────────────────────────────────────┐
│ 3. TOWN DEFAULTS │
│ Location: ~/gt/config.json or ~/gt/.beads/ │
│ Synced: N/A (per-town) │
│ Use: Town-wide policies │
└─────────────────────────────┬───────────────────────────────┘
│ if missing
┌─────────────────────────────────────────────────────────────┐
│ 4. SYSTEM DEFAULTS (compiled in) │
│ Use: Fallback when nothing else specified │
└─────────────────────────────────────────────────────────────┘
```
## Lookup Behavior
### Override Semantics (Default)
For most properties, the first non-nil value wins:
```go
func GetConfig(key string) interface{} {
if val := wisp.Get(key); val != nil {
if val == Blocked { return nil }
return val
}
if val := rigBead.GetLabel(key); val != nil {
return val
}
if val := townDefaults.Get(key); val != nil {
return val
}
return systemDefaults[key]
}
```
### Stacking Semantics (Integers)
For integer properties, values from wisp and bead layers **add** to the base:
```go
func GetIntConfig(key string) int {
base := getBaseDefault(key) // Town or system default
beadAdj := rigBead.GetInt(key) // 0 if missing
wispAdj := wisp.GetInt(key) // 0 if missing
return base + beadAdj + wispAdj
}
```
This enables temporary adjustments without changing the base value.
### Blocking Inheritance
You can explicitly block a property from being inherited:
```bash
gt rig config set gastown auto_restart --block
```
This creates a "blocked" marker in the wisp layer. Even if the rig bead
or defaults say `auto_restart: true`, the lookup returns nil.
## Rig Identity Beads
Each rig has an identity bead for operational state:
```yaml
id: gt-rig-gastown
type: rig
name: gastown
repo: git@github.com:steveyegge/gastown.git
prefix: gt
labels:
- status:operational
- priority:normal
```
These beads sync via git, so all clones of the rig see the same state.
## Two-Level Rig Control
### Level 1: Park (Local, Ephemeral)
```bash
gt rig park gastown # Stop services, daemon won't restart
gt rig unpark gastown # Allow services to run
```
- Stored in wisp layer (`.beads-wisp/config/`)
- Only affects this town
- Disappears on cleanup
- Use: Local maintenance, debugging
### Level 2: Dock (Global, Persistent)
```bash
gt rig dock gastown # Set status:docked label on rig bead
gt rig undock gastown # Remove label
```
- Stored on rig identity bead
- Syncs to all clones via git
- Permanent until explicitly changed
- Use: Project-wide maintenance, coordinated downtime
### Daemon Behavior
The daemon checks both levels before auto-restarting:
```go
func shouldAutoRestart(rig *Rig) bool {
status := rig.GetConfig("status")
if status == "parked" || status == "docked" {
return false
}
return true
}
```
## Configuration Keys
| Key | Type | Behavior | Description |
|-----|------|----------|-------------|
| `status` | string | Override | operational/parked/docked |
| `auto_restart` | bool | Override | Daemon auto-restart behavior |
| `max_polecats` | int | Override | Maximum concurrent polecats |
| `priority_adjustment` | int | **Stack** | Scheduling priority modifier |
| `maintenance_window` | string | Override | When maintenance allowed |
| `dnd` | bool | Override | Do not disturb mode |
## Commands
### View Configuration
```bash
gt rig config show gastown # Show effective config (all layers)
gt rig config show gastown --layer # Show which layer each value comes from
```
### Set Configuration
```bash
# Set in wisp layer (local, ephemeral)
gt rig config set gastown key value
# Set in bead layer (global, permanent)
gt rig config set gastown key value --global
# Block inheritance
gt rig config set gastown key --block
# Clear from wisp layer
gt rig config unset gastown key
```
### Rig Lifecycle
```bash
gt rig park gastown # Local: stop + prevent restart
gt rig unpark gastown # Local: allow restart
gt rig dock gastown # Global: mark as offline
gt rig undock gastown # Global: mark as operational
gt rig status gastown # Show current state
```
## Examples
### Temporary Priority Boost
```bash
# Base priority: 0 (from defaults)
# Give this rig temporary priority boost for urgent work
gt rig config set gastown priority_adjustment 10
# Effective priority: 0 + 10 = 10
# When done, clear it:
gt rig config unset gastown priority_adjustment
```
### Local Maintenance
```bash
# I'm upgrading the local clone, don't restart services
gt rig park gastown
# ... do maintenance ...
gt rig unpark gastown
```
### Project-Wide Maintenance
```bash
# Major refactor in progress, all clones should pause
gt rig dock gastown
# Syncs via git - other towns see the rig as docked
bd sync
# When done:
gt rig undock gastown
bd sync
```
### Block Auto-Restart Locally
```bash
# Rig bead says auto_restart: true
# But I'm debugging and don't want that here
gt rig config set gastown auto_restart --block
# Now auto_restart returns nil for this town only
```
## Implementation Notes
### Wisp Storage
Wisp config stored in `.beads-wisp/config/<rig>.json`:
```json
{
"rig": "gastown",
"values": {
"status": "parked",
"priority_adjustment": 10
},
"blocked": ["auto_restart"]
}
```
### Rig Bead Labels
Rig operational state stored as labels on the rig identity bead:
```bash
bd label add gt-rig-gastown status:docked
bd label remove gt-rig-gastown status:docked
```
### Daemon Integration
The daemon's lifecycle manager checks config before starting services:
```go
func (d *Daemon) maybeStartRigServices(rig string) {
r := d.getRig(rig)
status := r.GetConfig("status")
if status == "parked" || status == "docked" {
log.Info("Rig %s is offline, skipping auto-start", rig)
return
}
d.ensureWitness(rig)
d.ensureRefinery(rig)
}
```
## Related Documents
- `~/gt/docs/hop/PROPERTY-LAYERS.md` - Strategic architecture
- `wisp-architecture.md` - Wisp system design
- `agent-as-bead.md` - Agent identity beads (similar pattern)

View File

@@ -7,24 +7,38 @@ Technical reference for Gas Town internals. Read the README first.
```
~/gt/ Town root
├── .beads/ Town-level beads (hq-* prefix)
├── mayor/ Mayor config
── town.json
├── mayor/ Mayor agent home (town coordinator)
── town.json Town configuration
│ ├── CLAUDE.md Mayor context (on disk)
│ └── .claude/settings.json Mayor Claude settings
├── deacon/ Deacon agent home (background supervisor)
│ └── .claude/settings.json Deacon settings (context via gt prime)
└── <rig>/ Project container (NOT a git clone)
├── config.json Rig identity
├── .beads/ → mayor/rig/.beads
├── .repo.git/ Bare repo (shared by worktrees)
├── mayor/rig/ Mayor's clone (canonical beads)
├── refinery/rig/ Worktree on main
├── witness/ No clone (monitors only)
├── crew/<name>/ Human workspaces
── polecats/<name>/ Worker worktrees
│ └── CLAUDE.md Per-rig mayor context (on disk)
├── witness/ Witness agent home (monitors only)
│ └── .claude/settings.json (context via gt prime)
── refinery/ Refinery settings parent
│ ├── .claude/settings.json
│ └── rig/ Worktree on main
│ └── CLAUDE.md Refinery context (on disk)
├── crew/ Crew settings parent (shared)
│ ├── .claude/settings.json (context via gt prime)
│ └── <name>/rig/ Human workspaces
└── polecats/ Polecat settings parent (shared)
├── .claude/settings.json (context via gt prime)
└── <name>/rig/ Worker worktrees
```
**Key points:**
- Rig root is a container, not a clone
- `.repo.git/` is bare - refinery and polecats are worktrees
- Mayor clone holds canonical `.beads/`, others inherit via redirect
- Per-rig `mayor/rig/` holds canonical `.beads/`, others inherit via redirect
- Settings placed in parent dirs (not git clones) for upward traversal
## Beads Routing
@@ -204,6 +218,123 @@ gt mol step done <step> # Complete a molecule step
| `GT_RIG` | Rig name for rig-level agents |
| `GT_POLECAT` | Polecat name (for polecats only) |
## Agent Working Directories and Settings
Each agent runs in a specific working directory and has its own Claude settings.
Understanding this hierarchy is essential for proper configuration.
### Working Directories by Role
| Role | Working Directory | Notes |
|------|-------------------|-------|
| **Mayor** | `~/gt/mayor/` | Town-level coordinator, isolated from rigs |
| **Deacon** | `~/gt/deacon/` | Background supervisor daemon |
| **Witness** | `~/gt/<rig>/witness/` | No git clone, monitors polecats only |
| **Refinery** | `~/gt/<rig>/refinery/rig/` | Worktree on main branch |
| **Crew** | `~/gt/<rig>/crew/<name>/rig/` | Persistent human workspace clone |
| **Polecat** | `~/gt/<rig>/polecats/<name>/rig/` | Ephemeral worker worktree |
Note: The per-rig `<rig>/mayor/rig/` directory is NOT a working directory—it's
a git clone that holds the canonical `.beads/` database for that rig.
### Settings File Locations
Claude Code searches for `.claude/settings.json` starting from the working
directory and traversing upward. Settings are placed in **parent directories**
(not inside git clones) so they're found via directory traversal without
polluting source repositories:
```
~/gt/
├── mayor/.claude/settings.json # Mayor settings
├── deacon/.claude/settings.json # Deacon settings
└── <rig>/
├── witness/.claude/settings.json # Witness settings (no rig/ subdir)
├── refinery/.claude/settings.json # Found by refinery/rig/ via traversal
├── crew/.claude/settings.json # Shared by all crew/<name>/rig/
└── polecats/.claude/settings.json # Shared by all polecats/<name>/rig/
```
**Why parent directories?** Agents working in git clones (like `refinery/rig/`)
would pollute the source repo if settings were placed there. By putting settings
one level up, Claude finds them via upward traversal, and all workers of the
same type share the same settings.
### CLAUDE.md Locations
Role context is delivered via CLAUDE.md files or ephemeral injection:
| Role | CLAUDE.md Location | Method |
|------|-------------------|--------|
| **Mayor** | `~/gt/mayor/CLAUDE.md` | On disk |
| **Deacon** | (none) | Injected via `gt prime` at SessionStart |
| **Witness** | (none) | Injected via `gt prime` at SessionStart |
| **Refinery** | `<rig>/refinery/rig/CLAUDE.md` | On disk (inside worktree) |
| **Crew** | (none) | Injected via `gt prime` at SessionStart |
| **Polecat** | (none) | Injected via `gt prime` at SessionStart |
Additionally, each rig has `<rig>/mayor/rig/CLAUDE.md` for the per-rig mayor clone
(used for beads operations, not a running agent).
**Why ephemeral injection?** Writing CLAUDE.md into git clones would:
1. Pollute source repos when agents commit/push
2. Leak Gas Town internals into project history
3. Conflict with project-specific CLAUDE.md files
The `gt prime` command runs at SessionStart hook and injects context without
persisting it to disk.
### Sparse Checkout (Source Repo Isolation)
When agents work on source repositories that have their own Claude Code configuration,
Gas Town uses git sparse checkout to exclude all context files:
```bash
# Automatically configured for worktrees - excludes:
# - .claude/ : settings, rules, agents, commands
# - CLAUDE.md : primary context file
# - CLAUDE.local.md: personal context file
# - .mcp.json : MCP server configuration
git sparse-checkout set --no-cone '/*' '!/.claude/' '!/CLAUDE.md' '!/CLAUDE.local.md' '!/.mcp.json'
```
This ensures agents use Gas Town's context, not the source repo's instructions.
**Doctor check**: `gt doctor` verifies sparse checkout is configured correctly.
Run `gt doctor --fix` to update legacy configurations missing the newer patterns.
### Settings Inheritance
Claude Code's settings search order (first match wins):
1. `.claude/settings.json` in current working directory
2. `.claude/settings.json` in parent directories (traversing up)
3. `~/.claude/settings.json` (user global settings)
Gas Town places settings at each agent's working directory root, so agents
find their role-specific settings before reaching any parent or global config.
### Settings Templates
Gas Town uses two settings templates based on role type:
| Type | Roles | Key Difference |
|------|-------|----------------|
| **Interactive** | Mayor, Crew | Mail injected on `UserPromptSubmit` hook |
| **Autonomous** | Polecat, Witness, Refinery, Deacon | Mail injected on `SessionStart` hook |
Autonomous agents may start without user input, so they need mail checked
at session start. Interactive agents wait for user prompts.
### Troubleshooting
| Problem | Solution |
|---------|----------|
| Agent using wrong settings | Check `gt doctor`, verify sparse checkout |
| Settings not found | Ensure `.claude/settings.json` exists at role home |
| Source repo settings leaking | Run `gt doctor --fix` to configure sparse checkout |
| Mayor settings affecting polecats | Mayor should run in `mayor/`, not town root |
## CLI Reference
### Town Management
@@ -215,6 +346,28 @@ gt doctor # Health check
gt doctor --fix # Auto-repair
```
### Configuration
```bash
# Agent management
gt config agent list [--json] # List all agents (built-in + custom)
gt config agent get <name> # Show agent configuration
gt config agent set <name> <cmd> # Create or update custom agent
gt config agent remove <name> # Remove custom agent (built-ins protected)
# Default agent
gt config default-agent [name] # Get or set town default agent
```
**Built-in agents**: `claude`, `gemini`, `codex`
**Custom agents**: Define per-town in `mayor/town.json`:
```bash
gt config agent set claude-glm "claude-glm --model glm-4"
gt config agent set claude "claude-opus" # Override built-in
gt config default-agent claude-glm # Set default
```
### Rig Management
```bash
@@ -242,12 +395,19 @@ Note: "Swarm" is ephemeral (workers on a convoy's issues). See [Convoys](convoy.
# Standard workflow: convoy first, then sling
gt convoy create "Feature X" gt-abc gt-def
gt sling gt-abc <rig> # Assign to polecat
gt sling gt-def <rig> --molecule=<proto> # With workflow template
gt sling gt-abc <rig> --agent codex # Override runtime for this sling/spawn
gt sling <proto> --on gt-def <rig> # With workflow template
# Quick sling (auto-creates convoy)
gt sling <bead> <rig> # Auto-convoy for dashboard visibility
```
Agent overrides:
- `gt start --agent <alias>` overrides the Mayor/Deacon runtime for this launch.
- `gt mayor start|attach|restart --agent <alias>` and `gt deacon start|attach|restart --agent <alias>` do the same.
- `gt start crew <name> --agent <alias>` and `gt crew at <name> --agent <alias>` override the crew worker runtime.
### Communication
```bash
@@ -323,7 +483,7 @@ Deacon, Witness, and Refinery run continuous patrol loops using wisps:
|-------|-----------------|----------------|
| **Deacon** | `mol-deacon-patrol` | Agent lifecycle, plugin execution, health checks |
| **Witness** | `mol-witness-patrol` | Monitor polecats, nudge stuck workers |
| **Refinery** | `mol-refinery-patrol` | Process merge queue, review PRs |
| **Refinery** | `mol-refinery-patrol` | Process merge queue, review MRs |
```
1. bd mol wisp mol-<role>-patrol

View File

@@ -0,0 +1,220 @@
# Infrastructure & Utilities Code Review
**Review ID**: gt-a02fj.8
**Date**: 2026-01-04
**Reviewer**: gastown/polecats/interceptor (polecat gus)
## Executive Summary
Reviewed 14 infrastructure packages for dead code, missing abstractions, performance concerns, and error handling consistency. Found significant cleanup opportunities totaling ~44% dead code in constants package and an entire unused package (keepalive).
---
## 1. Dead Code Inventory
### Critical: Entire Package Unused
| Package | Status | Recommendation |
|---------|--------|----------------|
| `internal/keepalive/` | 100% unused | **DELETE ENTIRE PACKAGE** |
The keepalive package (5 functions) was removed from the codebase on Dec 30, 2025 as part of the shift to feed-based activation. No imports exist anywhere.
### High Priority: Functions to Remove
| Package | Function | Location | Notes |
|---------|----------|----------|-------|
| `config` | `NewExampleAgentRegistry()` | agents.go:361-381 | Zero usage in codebase |
| `constants` | `DirMayor`, `DirPolecats`, `DirCrew`, etc. | constants.go:32-59 | 9 unused directory constants |
| `constants` | `FileRigsJSON`, `FileTownJSON`, etc. | constants.go:62-74 | 4 unused file constants |
| `constants` | `BranchMain`, `BranchBeadsSync`, etc. | constants.go:77-89 | 4 unused branch constants |
| `constants` | `RigBeadsPath()`, `RigPolecatsPath()`, etc. | constants.go | 5 unused path helper functions |
| `doctor` | `itoa()` | daemon_check.go:93-111 | Duplicate of `strconv.Itoa()` |
| `lock` | `DetectCollisions()` | lock.go:367-402 | Superseded by doctor checks |
| `events` | `BootPayload()` | events.go:186-191 | Never called |
| `events` | `TypePatrolStarted`, `TypeSessionEnd` | events.go:50,54 | Never emitted |
| `events` | `VisibilityBoth` | events.go:32 | Never set |
| `boot` | `DeaconDir()` | boot.go:235-237 | Exported but never called |
| `dog` | `IdleCount()`, `WorkingCount()` | manager.go:532-562 | Inlined in callers |
### Medium Priority: Duplicate Definitions
| Package | Item | Duplicate Location | Action |
|---------|------|-------------------|--------|
| `constants` | `RigSettingsPath()` | Also in config/loader.go:673 | Remove from constants |
| `util` | Atomic write pattern | Also in mrqueue/, wisp/ | Consolidate to util |
| `doctor` | `findRigs()` | 3 identical implementations | Extract shared helper |
---
## 2. Utility Consolidation Plan
### Pattern: Atomic Write (Priority: HIGH)
**Current state**: Duplicated in 3+ locations
- `util/atomic.go` (canonical)
- `mrqueue/mrqueue.go` (duplicate)
- `wisp/io.go` (duplicate)
- `polecat/pending.go` (NON-ATOMIC - bug!)
**Action**:
1. Fix `polecat/pending.go:SavePending()` to use `util.AtomicWriteJSON`
2. Replace inline atomic writes in mrqueue and wisp with util calls
### Pattern: Rig Discovery (Priority: HIGH)
**Current state**: 7+ implementations scattered across doctor package
- `BranchCheck.findPersistentRoleDirs()`
- `OrphanSessionCheck.getValidRigs()`
- `PatrolMoleculesExistCheck.discoverRigs()`
- `config_check.go.findAllRigs()`
- Multiple `findCrewDirs()` implementations
**Action**: Create `internal/workspace/discovery.go`:
```go
type RigDiscovery struct { ... }
func (d *RigDiscovery) FindAllRigs() []string
func (d *RigDiscovery) FindCrewDirs(rig string) []string
func (d *RigDiscovery) FindPolecatDirs(rig string) []string
```
### Pattern: Clone Validation (Priority: MEDIUM)
**Current state**: Duplicate logic in doctor checks
- `rig_check.go`: Validates .git, runs git status
- `branch_check.go`: Similar traversal logic
**Action**: Create `internal/workspace/clone.go`:
```go
type CloneValidator struct { ... }
func (v *CloneValidator) ValidateClone(path string) error
func (v *CloneValidator) GetCloneInfo(path string) (*CloneInfo, error)
```
### Pattern: Tmux Session Handling (Priority: MEDIUM)
**Current state**: Fragmented across lock, doctor, daemon
- `lock/lock.go`: `getActiveTmuxSessions()`
- `doctor/identity_check.go`: Similar logic
- `cmd/agents.go`: Uses `tmux.NewTmux()`
**Action**: Consolidate into `internal/tmux/sessions.go`
### Pattern: Load/Validate Config Files (Priority: LOW)
**Current state**: 8 near-identical Load* functions in config/loader.go
- `LoadTownConfig`, `LoadRigsConfig`, `LoadRigConfig`, etc.
**Action**: Create generic loader using Go generics:
```go
func loadConfigFile[T Validator](path string) (*T, error)
```
### Pattern: Math Utilities (Priority: LOW)
**Current state**: `min()`, `max()`, `min3()`, `abs()` in suggest/suggest.go
**Action**: If needed elsewhere, move to `internal/util/math.go`
---
## 3. Performance Concerns
### Critical: File I/O Per-Event
| Package | Issue | Impact | Recommendation |
|---------|-------|--------|----------------|
| `events` | Opens/closes file for every event | High on busy systems | Batch writes or buffered logger |
| `townlog` | Opens/closes file per log entry | Medium | Same as events |
| `events` | `workspace.FindFromCwd()` on every Log() | Low-medium | Cache town root |
### Critical: Process Tree Walking
| Package | Issue | Impact | Recommendation |
|---------|-------|--------|----------------|
| `doctor/orphan_check` | `hasCrewAncestor()` calls `ps` in loop | O(n) subprocess calls | Batch gather process info |
### High: Directory Traversal Inefficiencies
| Package | Issue | Impact | Recommendation |
|---------|-------|--------|----------------|
| `doctor/hook_check` | Uses `exec.Command("find")` | Subprocess overhead | Use `filepath.Walk` |
| `lock` | `FindAllLocks()` - unbounded Walk | Scales poorly | Add depth limits |
| `townlog` | `TailEvents()` reads entire file | Memory for large logs | Implement true tail |
### Medium: Redundant Operations
| Package | Issue | Recommendation |
|---------|-------|----------------|
| `dog` | `List()` + iterate = double work | Provide `CountByState()` |
| `dog` | Creates new git.Git per worktree | Cache or batch |
| `doctor/rig_check` | Runs git status twice per polecat | Combine operations |
| `checkpoint/Capture` | 3 separate git commands | Use combined flags |
### Low: JSON Formatting Overhead
| Package | Issue | Recommendation |
|---------|-------|----------------|
| `lock` | `MarshalIndent()` for lock files | Use `Marshal()` (no indentation needed) |
| `townlog` | No compression for old logs | Consider gzip rotation |
---
## 4. Error Handling Issues
### Pattern: Silent Failures
| Package | Location | Issue | Fix |
|---------|----------|-------|-----|
| `events` | All callers | 19 instances of `_ = events.LogFeed()` | Standardize: always ignore or always check |
| `townlog` | `ParseLogLines()` | Silently skips malformed lines | Log warnings |
| `lock` | Lines 91, 180, 194-195 | Silent `_ =` without comments | Document intent |
| `checkpoint` | `Capture()` | Returns nil error but git commands fail | Return actual errors |
| `deps` | `BeadsUnknown` case | Silently passes | Log warning or fail |
### Pattern: Inconsistent State Handling
| Package | Issue | Recommendation |
|---------|-------|----------------|
| `dog/Get()` | Returns minimal Dog if state missing | Document or error |
| `config/GetAccount()` | Returns pointer to loop variable (bug!) | Return by value |
| `boot` | `LoadStatus()` returns empty struct if missing | Document behavior |
### Bug: Missing Role Mapping
| Package | Issue | Impact |
|---------|-------|--------|
| `claude` | `RoleTypeFor()` missing `deacon`, `crew` | Wrong settings applied |
---
## 5. Testing Gaps
| Package | Gap | Priority |
|---------|-----|----------|
| `checkpoint` | No unit tests | HIGH (crash recovery) |
| `dog` | 4 tests, major paths untested | HIGH |
| `deps` | Minimal failure path testing | MEDIUM |
| `claude` | No tests | LOW |
---
## Summary Statistics
| Category | Count | Packages Affected |
|----------|-------|-------------------|
| **Dead Code Items** | 25+ | config, constants, doctor, lock, events, boot, dog, keepalive |
| **Duplicate Patterns** | 6 | util, doctor, config, lock |
| **Performance Issues** | 12 | events, townlog, doctor, dog, lock, checkpoint |
| **Error Handling Issues** | 15 | events, townlog, lock, checkpoint, deps, claude |
| **Testing Gaps** | 4 packages | checkpoint, dog, deps, claude |
## Recommended Priority
1. **Delete keepalive package** (entire package unused)
2. **Fix claude/RoleTypeFor()** (incorrect behavior)
3. **Fix config/GetAccount()** (pointer to stack bug)
4. **Fix polecat/pending.go** (non-atomic writes)
5. **Delete 21 unused constants** (maintenance burden)
6. **Consolidate atomic write pattern** (DRY)
7. **Add checkpoint tests** (crash recovery critical)

View File

@@ -0,0 +1,154 @@
# Test Coverage and Quality Review
**Reviewed by**: polecat/gus
**Date**: 2026-01-04
**Issue**: gt-a02fj.9
## Executive Summary
- **80 test files** covering **32 out of 42 packages** (76% package coverage)
- **631 test functions** with 192 subtests (30% use table-driven pattern)
- **10 packages** with **0 test coverage** (2,452 lines)
- **1 confirmed flaky test** candidate
- Test quality is generally good with moderate mocking
---
## Coverage Gap Inventory
### Packages Without Tests (Priority Order)
| Priority | Package | Lines | Risk | Notes |
|----------|---------|-------|------|-------|
| **P0** | `internal/lock` | 402 | **CRITICAL** | Multi-agent lock management. Bugs cause worker collisions. Already has `execCommand` mockable for testing. |
| **P1** | `internal/events` | 295 | HIGH | Event bus for audit trail. Mutex-protected writes. Core observability. |
| **P1** | `internal/boot` | 242 | HIGH | Boot watchdog lifecycle. Spawns tmux sessions. |
| **P1** | `internal/checkpoint` | 216 | HIGH | Session crash recovery. Critical for polecat continuity. |
| **P2** | `internal/tui/convoy` | 601 | MEDIUM | TUI component. Harder to test but user-facing. |
| **P2** | `internal/constants` | 221 | LOW | Mostly configuration constants. Low behavioral risk. |
| **P3** | `internal/style` | 331 | LOW | Output formatting. Visual only. |
| **P3** | `internal/claude` | 80 | LOW | Claude settings parsing. |
| **P3** | `internal/wisp` | 52 | LOW | Ephemeral molecule I/O. Small surface. |
| **P4** | `cmd/gt` | 12 | TRIVIAL | Main entry point. Minimal code. |
**Total untested lines**: 2,452
---
## Flaky Test Candidates
### Confirmed: `internal/feed/curator_test.go`
**Issue**: Uses `time.Sleep()` for synchronization (lines 59, 71, 119, 138)
```go
// Give curator time to start
time.Sleep(50 * time.Millisecond)
...
// Wait for processing
time.Sleep(300 * time.Millisecond)
```
**Risk**: Flaky under load, CI delays, or slow machines.
**Fix**: Replace with channel-based synchronization or polling with timeout:
```go
// Wait for condition with timeout
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
if conditionMet() {
break
}
time.Sleep(10 * time.Millisecond)
}
```
---
## Test Quality Analysis
### Strengths
1. **Table-driven tests**: 30% of tests use `t.Run()` (192/631)
2. **Good isolation**: Only 2 package-level test variables
3. **Dedicated integration tests**: 15 files with explicit integration/e2e naming
4. **Error handling**: 316 uses of `if err != nil` in tests
5. **No random data**: No `rand.` usage in tests (deterministic)
6. **Environment safety**: Uses `t.Setenv()` for clean env var handling
### Areas for Improvement
1. **`testing.Short()`**: Only 1 usage. Long-running tests should check this.
2. **External dependencies**: 26 tests skip when `bd` or `tmux` unavailable - consider mocking more.
3. **time.Sleep usage**: Found in `curator_test.go` - should be eliminated.
---
## Test Smells (Minor)
| Smell | Location | Severity | Notes |
|-------|----------|----------|-------|
| Sleep-based sync | `feed/curator_test.go` | HIGH | See flaky section |
| External dep skips | Multiple files | LOW | Reasonable for integration tests |
| Skip-heavy file | `tmux/tmux_test.go` | LOW | Acceptable - tmux not always available |
---
## Priority List for New Tests
### Immediate (P0)
1. **`internal/lock`** - Critical path
- Test `Acquire()` with stale lock cleanup
- Test `Check()` with live/dead PIDs
- Test `CleanStaleLocks()` with mock tmux sessions
- Test `DetectCollisions()`
- Test concurrent lock acquisition (race detection)
### High Priority (P1)
2. **`internal/events`**
- Test `Log()` file creation and append
- Test `write()` mutex behavior
- Test payload helpers
- Test graceful handling when not in workspace
3. **`internal/boot`**
- Test `IsRunning()` with stale markers
- Test `AcquireLock()` / `ReleaseLock()` cycle
- Test `SaveStatus()` / `LoadStatus()` round-trip
- Test degraded mode path
4. **`internal/checkpoint`**
- Test `Read()` / `Write()` round-trip
- Test `Capture()` git state extraction
- Test `IsStale()` with various durations
- Test `Summary()` output
### Medium Priority (P2)
5. **`internal/tui/convoy`** - Consider golden file tests for view output
6. **`internal/constants`** - Test any validation logic
---
## Missing Test Types
| Type | Current State | Recommendation |
|------|--------------|----------------|
| Unit tests | Good coverage where present | Add for P0-P1 packages |
| Integration tests | 15 dedicated files | Adequate |
| E2E tests | `browser_e2e_test.go` | Consider more CLI E2E |
| Fuzz tests | None | Consider for parsers (`formula/parser.go`) |
| Benchmark tests | None visible | Add for hot paths (`lock`, `events`) |
---
## Actionable Next Steps
1. **Fix flaky test**: Refactor `feed/curator_test.go` to use channels/polling
2. **Add lock tests**: Highest priority - bugs here break multi-agent
3. **Add events tests**: Core observability must be tested
4. **Add checkpoint tests**: Session recovery is critical path
5. **Run with race detector**: `go test -race ./...` to catch data races
6. **Consider `-short` flag**: Add `testing.Short()` checks to slow tests

View File

@@ -26,7 +26,7 @@ These roles manage the Gas Town system itself:
| Role | Description | Lifecycle |
|------|-------------|-----------|
| **Mayor** | Global coordinator at town root | Singleton, persistent |
| **Mayor** | Global coordinator at mayor/ | Singleton, persistent |
| **Deacon** | Background supervisor daemon ([watchdog chain](watchdog-chain.md)) | Singleton, persistent |
| **Witness** | Per-rig polecat lifecycle manager | One per rig, persistent |
| **Refinery** | Per-rig merge queue processor | One per rig, persistent |

View File

@@ -66,10 +66,10 @@ The daemon could directly monitor agents without AI, but:
| Agent | Session Name | Location | Lifecycle |
|-------|--------------|----------|-----------|
| Daemon | (Go process) | `~/gt/daemon/` | Persistent, auto-restart |
| Boot | `gt-deacon-boot` | `~/gt/deacon/dogs/boot/` | Ephemeral, fresh each tick |
| Deacon | `gt-deacon` | `~/gt/deacon/` | Long-running, handoff loop |
| Boot | `gt-boot` | `~/gt/deacon/dogs/boot/` | Ephemeral, fresh each tick |
| Deacon | `hq-deacon` | `~/gt/deacon/` | Long-running, handoff loop |
**Critical**: Boot runs in `gt-deacon-boot`, NOT `gt-deacon`. This prevents Boot
**Critical**: Boot runs in `gt-boot`, NOT `hq-deacon`. This prevents Boot
from conflicting with a running Deacon session.
## Heartbeat Mechanics
@@ -82,11 +82,11 @@ The daemon runs a heartbeat tick every 3 minutes:
func (d *Daemon) heartbeatTick() {
d.ensureBootRunning() // 1. Spawn Boot for triage
d.checkDeaconHeartbeat() // 2. Belt-and-suspenders fallback
d.ensureWitnessesRunning() // 3. Witness health
d.triggerPendingSpawns() // 4. Bootstrap polecats
d.processLifecycleRequests() // 5. Cycle/restart requests
d.checkStaleAgents() // 6. Timeout detection
// ... more checks
d.ensureWitnessesRunning() // 3. Witness health (checks tmux directly)
d.ensureRefineriesRunning() // 4. Refinery health (checks tmux directly)
d.triggerPendingSpawns() // 5. Bootstrap polecats
d.processLifecycleRequests() // 6. Cycle/restart requests
// Agent state derived from tmux, not recorded in beads (gt-zecmc)
}
```
@@ -190,7 +190,7 @@ Multiple layers ensure recovery:
1. **Boot triage** - Intelligent observation, first line
2. **Daemon checkDeaconHeartbeat()** - Belt-and-suspenders if Boot fails
3. **Daemon checkStaleAgents()** - Timeout-based detection
3. **Tmux-based discovery** - Daemon checks tmux sessions directly (no bead state)
4. **Human escalation** - Mail to overseer for unrecoverable states
## State Files
@@ -227,21 +227,23 @@ gt deacon health-check
### Boot Spawns in Wrong Session
**Symptom**: Boot runs in `gt-deacon` instead of `gt-deacon-boot`
**Symptom**: Boot runs in `hq-deacon` instead of `gt-boot`
**Cause**: Session name confusion in spawn code
**Fix**: Ensure `gt boot triage` specifies `--session=gt-deacon-boot`
**Fix**: Ensure `gt boot triage` specifies `--session=gt-boot`
### Zombie Sessions Block Restart
**Symptom**: tmux session exists but Claude is dead
**Cause**: Daemon checks session existence, not process health
**Fix**: Kill zombie sessions before recreating: `gt session kill gt-deacon`
**Fix**: Kill zombie sessions before recreating: `gt session kill hq-deacon`
### Status Shows Wrong State
**Symptom**: `gt status` shows "stopped" for running agents
**Cause**: Bead state and tmux state diverged
**Fix**: Reconcile with `gt sync-status` or restart agent
**Symptom**: `gt status` shows wrong state for agents
**Cause**: Previously bead state and tmux state could diverge
**Fix**: As of gt-zecmc, status derives state from tmux directly (no bead state for
observable conditions like running/stopped). Non-observable states (stuck, awaiting-gate)
are still stored in beads.
## Design Decision: Keep Separation
@@ -250,15 +252,15 @@ The issue [gt-1847v] considered three options:
### Option A: Keep Boot/Deacon Separation (CHOSEN)
- Boot is ephemeral, spawns fresh each heartbeat
- Boot runs in `gt-deacon-boot`, exits after triage
- Deacon runs in `gt-deacon`, continuous patrol
- Boot runs in `gt-boot`, exits after triage
- Deacon runs in `hq-deacon`, continuous patrol
- Clear session boundaries, clear lifecycle
**Verdict**: This is the correct design. The implementation needs fixing, not the architecture.
### Option B: Merge Boot into Deacon (Rejected)
- Single `gt-deacon` session handles everything
- Single `hq-deacon` session handles everything
- Deacon checks "should I be awake?" internally
**Why rejected**:
@@ -284,7 +286,7 @@ The separation is correct; these bugs need fixing:
1. **Session confusion** (gt-sgzsb): Boot spawns in wrong session
2. **Zombie blocking** (gt-j1i0r): Daemon can't kill zombie sessions
3. **Status mismatch** (gt-doih4): Bead vs tmux state divergence
3. ~~**Status mismatch** (gt-doih4): Bead vs tmux state divergence~~ → FIXED in gt-zecmc
4. **Ensure semantics** (gt-ekc5u): Start should kill zombies first
## Summary

7
go.mod
View File

@@ -7,6 +7,8 @@ require (
github.com/charmbracelet/bubbles v0.21.0
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/lipgloss v1.1.0
github.com/go-rod/rod v0.116.2
github.com/gofrs/flock v0.13.0
github.com/google/uuid v1.6.0
github.com/spf13/cobra v1.10.2
golang.org/x/term v0.38.0
@@ -34,5 +36,10 @@ require (
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.9 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/ysmood/fetchup v0.2.3 // indirect
github.com/ysmood/goob v0.4.0 // indirect
github.com/ysmood/got v0.40.0 // indirect
github.com/ysmood/gson v0.7.3 // indirect
github.com/ysmood/leakless v0.9.0 // indirect
golang.org/x/sys v0.39.0 // indirect
)

26
go.sum
View File

@@ -27,8 +27,14 @@ github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEX
github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4=
github.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/go-rod/rod v0.116.2 h1:A5t2Ky2A+5eD/ZJQr1EfsQSe5rms5Xof/qj296e+ZqA=
github.com/go-rod/rod v0.116.2/go.mod h1:H+CMO9SCNc2TJ2WfrG+pKhITz57uGNYU43qYHh438Mg=
github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw=
github.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8P+Z0=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
@@ -47,6 +53,8 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
@@ -54,8 +62,24 @@ github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/ysmood/fetchup v0.2.3 h1:ulX+SonA0Vma5zUFXtv52Kzip/xe7aj4vqT5AJwQ+ZQ=
github.com/ysmood/fetchup v0.2.3/go.mod h1:xhibcRKziSvol0H1/pj33dnKrYyI2ebIvz5cOOkYGns=
github.com/ysmood/goob v0.4.0 h1:HsxXhyLBeGzWXnqVKtmT9qM7EuVs/XOgkX7T6r1o1AQ=
github.com/ysmood/goob v0.4.0/go.mod h1:u6yx7ZhS4Exf2MwciFr6nIM8knHQIE22lFpWHnfql18=
github.com/ysmood/gop v0.2.0 h1:+tFrG0TWPxT6p9ZaZs+VY+opCvHU8/3Fk6BaNv6kqKg=
github.com/ysmood/gop v0.2.0/go.mod h1:rr5z2z27oGEbyB787hpEcx4ab8cCiPnKxn0SUHt6xzk=
github.com/ysmood/got v0.40.0 h1:ZQk1B55zIvS7zflRrkGfPDrPG3d7+JOza1ZkNxcc74Q=
github.com/ysmood/got v0.40.0/go.mod h1:W7DdpuX6skL3NszLmAsC5hT7JAhuLZhByVzHTq874Qg=
github.com/ysmood/gotrace v0.6.0 h1:SyI1d4jclswLhg7SWTL6os3L1WOKeNn/ZtzVQF8QmdY=
github.com/ysmood/gotrace v0.6.0/go.mod h1:TzhIG7nHDry5//eYZDYcTzuJLYQIkykJzCRIo4/dzQM=
github.com/ysmood/gson v0.7.3 h1:QFkWbTH8MxyUTKPkVWAENJhxqdBa4lYTQWqZCiLG6kE=
github.com/ysmood/gson v0.7.3/go.mod h1:3Kzs5zDl21g5F/BlLTNcuAGAYLKt2lV5G8D1zF3RNmg=
github.com/ysmood/leakless v0.9.0 h1:qxCG5VirSBvmi3uynXFkcnLMzkphdh3xx5FtrORwDCU=
github.com/ysmood/leakless v0.9.0/go.mod h1:R8iAXPRaG97QJwqxs74RdwzcRHT1SWCGTNqY8q0JvMQ=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
@@ -68,3 +92,5 @@ golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

76
internal/agent/state.go Normal file
View File

@@ -0,0 +1,76 @@
// Package agent provides shared types and utilities for Gas Town agents
// (witness, refinery, deacon, etc.).
package agent
import (
"encoding/json"
"os"
"path/filepath"
"github.com/steveyegge/gastown/internal/util"
)
// State represents an agent's running state.
type State string
const (
// StateStopped means the agent is not running.
StateStopped State = "stopped"
// StateRunning means the agent is actively operating.
StateRunning State = "running"
// StatePaused means the agent is paused (not operating but not stopped).
StatePaused State = "paused"
)
// StateManager handles loading and saving agent state to disk.
// It uses generics to work with any state type.
type StateManager[T any] struct {
stateFilePath string
defaultFactory func() *T
}
// NewStateManager creates a new StateManager for the given state file path.
// The defaultFactory function is called when the state file doesn't exist
// to create a new state with default values.
func NewStateManager[T any](rigPath, stateFileName string, defaultFactory func() *T) *StateManager[T] {
return &StateManager[T]{
stateFilePath: filepath.Join(rigPath, ".runtime", stateFileName),
defaultFactory: defaultFactory,
}
}
// StateFile returns the path to the state file.
func (m *StateManager[T]) StateFile() string {
return m.stateFilePath
}
// Load loads agent state from disk.
// If the file doesn't exist, returns a new state created by the default factory.
func (m *StateManager[T]) Load() (*T, error) {
data, err := os.ReadFile(m.stateFilePath)
if err != nil {
if os.IsNotExist(err) {
return m.defaultFactory(), nil
}
return nil, err
}
var state T
if err := json.Unmarshal(data, &state); err != nil {
return nil, err
}
return &state, nil
}
// Save persists agent state to disk using atomic write.
func (m *StateManager[T]) Save(state *T) error {
dir := filepath.Dir(m.stateFilePath)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
return util.AtomicWriteJSON(m.stateFilePath, state)
}

View File

@@ -71,15 +71,162 @@ func ResolveBeadsDir(workDir string) string {
return beadsDir
}
// Detect redirect chains: check if resolved path also has a redirect
resolvedRedirect := filepath.Join(resolved, "redirect")
if _, err := os.Stat(resolvedRedirect); err == nil {
fmt.Fprintf(os.Stderr, "Warning: redirect chain detected: %s -> %s (which also has a redirect)\n", beadsDir, resolved)
// Don't follow chains - just return the first resolved path
// The target's redirect is likely errant and should be removed
// Follow redirect chains (e.g., crew/.beads -> rig/.beads -> mayor/rig/.beads)
// This is intentional for the rig-level redirect architecture.
// Limit depth to prevent infinite loops from misconfigured redirects.
return resolveBeadsDirWithDepth(resolved, 3)
}
// resolveBeadsDirWithDepth follows redirect chains with a depth limit.
func resolveBeadsDirWithDepth(beadsDir string, maxDepth int) string {
if maxDepth <= 0 {
fmt.Fprintf(os.Stderr, "Warning: redirect chain too deep at %s, stopping\n", beadsDir)
return beadsDir
}
return resolved
redirectPath := filepath.Join(beadsDir, "redirect")
data, err := os.ReadFile(redirectPath) //nolint:gosec // G304: path is constructed internally
if err != nil {
// No redirect, this is the final destination
return beadsDir
}
redirectTarget := strings.TrimSpace(string(data))
if redirectTarget == "" {
return beadsDir
}
// Resolve relative to parent of beadsDir (the workDir)
workDir := filepath.Dir(beadsDir)
resolved := filepath.Clean(filepath.Join(workDir, redirectTarget))
// Detect circular redirect
if resolved == beadsDir {
fmt.Fprintf(os.Stderr, "Warning: circular redirect detected in %s, stopping\n", redirectPath)
return beadsDir
}
// Recursively follow
return resolveBeadsDirWithDepth(resolved, maxDepth-1)
}
// cleanBeadsRuntimeFiles removes gitignored runtime files from a .beads directory
// while preserving tracked files (formulas/, README.md, config.yaml, .gitignore).
// This is safe to call even if the directory doesn't exist.
func cleanBeadsRuntimeFiles(beadsDir string) error {
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
return nil // Nothing to clean
}
// Runtime files/patterns that are gitignored and safe to remove
runtimePatterns := []string{
// SQLite databases
"*.db", "*.db-*", "*.db?*",
// Daemon runtime
"daemon.lock", "daemon.log", "daemon.pid", "bd.sock",
// Sync state
"sync-state.json", "last-touched", "metadata.json",
// Version tracking
".local_version",
// Redirect file (we're about to recreate it)
"redirect",
// Merge artifacts
"beads.base.*", "beads.left.*", "beads.right.*",
// JSONL files (tracked but will be redirected, safe to remove in worktrees)
"issues.jsonl", "interactions.jsonl",
// Runtime directories
"mq",
}
for _, pattern := range runtimePatterns {
matches, err := filepath.Glob(filepath.Join(beadsDir, pattern))
if err != nil {
continue // Invalid pattern, skip
}
for _, match := range matches {
os.RemoveAll(match) // Best effort, ignore errors
}
}
return nil
}
// SetupRedirect creates a .beads/redirect file for a worktree to point to the rig's shared beads.
// This is used by crew, polecats, and refinery worktrees to share the rig's beads database.
//
// Parameters:
// - townRoot: the town root directory (e.g., ~/gt)
// - worktreePath: the worktree directory (e.g., <rig>/crew/<name> or <rig>/refinery/rig)
//
// The function:
// 1. Computes the relative path from worktree to rig-level .beads
// 2. Cleans up runtime files (preserving tracked files like formulas/)
// 3. Creates the redirect file
//
// Safety: This function refuses to create redirects in the canonical beads location
// (mayor/rig) to prevent circular redirect chains.
func SetupRedirect(townRoot, worktreePath string) error {
// Get rig root from worktree path
// worktreePath = <town>/<rig>/crew/<name> or <town>/<rig>/refinery/rig etc.
relPath, err := filepath.Rel(townRoot, worktreePath)
if err != nil {
return fmt.Errorf("computing relative path: %w", err)
}
parts := strings.Split(filepath.ToSlash(relPath), "/")
if len(parts) < 2 {
return fmt.Errorf("invalid worktree path: must be at least 2 levels deep from town root")
}
// Safety check: prevent creating redirect in canonical beads location (mayor/rig)
// This would create a circular redirect chain since rig/.beads redirects to mayor/rig/.beads
if len(parts) >= 2 && parts[1] == "mayor" {
return fmt.Errorf("cannot create redirect in canonical beads location (mayor/rig)")
}
rigRoot := filepath.Join(townRoot, parts[0])
rigBeadsPath := filepath.Join(rigRoot, ".beads")
if _, err := os.Stat(rigBeadsPath); os.IsNotExist(err) {
return fmt.Errorf("no rig .beads found at %s", rigBeadsPath)
}
// Clean up runtime files in .beads/ but preserve tracked files (formulas/, README.md, etc.)
worktreeBeadsDir := filepath.Join(worktreePath, ".beads")
if err := cleanBeadsRuntimeFiles(worktreeBeadsDir); err != nil {
return fmt.Errorf("cleaning runtime files: %w", err)
}
// Create .beads directory if it doesn't exist
if err := os.MkdirAll(worktreeBeadsDir, 0755); err != nil {
return fmt.Errorf("creating .beads dir: %w", err)
}
// Compute relative path from worktree to rig root
// e.g., crew/<name> (depth 2) -> ../../.beads
// refinery/rig (depth 2) -> ../../.beads
depth := len(parts) - 1 // subtract 1 for rig name itself
redirectPath := strings.Repeat("../", depth) + ".beads"
// Check if rig-level beads has a redirect (tracked beads case).
// If so, redirect directly to the final destination to avoid chains.
// The bd CLI doesn't support redirect chains, so we must skip intermediate hops.
rigRedirectPath := filepath.Join(rigBeadsPath, "redirect")
if data, err := os.ReadFile(rigRedirectPath); err == nil {
rigRedirectTarget := strings.TrimSpace(string(data))
if rigRedirectTarget != "" {
// Rig has redirect (e.g., "mayor/rig/.beads" for tracked beads).
// Redirect worktree directly to the final destination.
redirectPath = strings.Repeat("../", depth) + rigRedirectTarget
}
}
// Create redirect file
redirectFile := filepath.Join(worktreeBeadsDir, "redirect")
if err := os.WriteFile(redirectFile, []byte(redirectPath+"\n"), 0644); err != nil {
return fmt.Errorf("creating redirect file: %w", err)
}
return nil
}
// Issue represents a beads issue.
@@ -249,6 +396,13 @@ func (b *Beads) run(args ...string) ([]byte, error) {
return stdout.Bytes(), nil
}
// Run executes a bd command and returns stdout.
// This is a public wrapper around the internal run method for cases where
// callers need to run arbitrary bd commands.
func (b *Beads) Run(args ...string) ([]byte, error) {
return b.run(args...)
}
// wrapError wraps bd errors with context.
func (b *Beads) wrapError(err error, stderr string, args []string) error {
stderr = strings.TrimSpace(stderr)
@@ -975,6 +1129,16 @@ func (b *Beads) CreateAgentBead(id, title string, fields *AgentFields) (*Issue,
}
}
// Set the hook slot if specified (this is the authoritative storage)
// This fixes the slot inconsistency bug where bead status is 'hooked' but
// agent's hook slot is empty. See mi-619.
if fields != nil && fields.HookBead != "" {
if _, err := b.run("slot", "set", id, "hook", fields.HookBead); err != nil {
// Non-fatal: warn but continue - description text has the backup
fmt.Printf("Warning: could not set hook slot: %v\n", err)
}
}
return &issue, nil
}
@@ -1026,6 +1190,38 @@ func (b *Beads) UpdateAgentState(id string, state string, hookBead *string) erro
return nil
}
// SetHookBead sets the hook_bead slot on an agent bead.
// This is a convenience wrapper that only sets the hook without changing agent_state.
// Per gt-zecmc: agent_state ("running", "dead", "idle") is observable from tmux
// and should not be recorded in beads ("discover, don't track" principle).
func (b *Beads) SetHookBead(agentBeadID, hookBeadID string) error {
// Set the hook using bd slot set
// This updates the hook_bead column directly in SQLite
_, err := b.run("slot", "set", agentBeadID, "hook", hookBeadID)
if err != nil {
// If slot is already occupied, clear it first then retry
errStr := err.Error()
if strings.Contains(errStr, "already occupied") {
_, _ = b.run("slot", "clear", agentBeadID, "hook")
_, err = b.run("slot", "set", agentBeadID, "hook", hookBeadID)
}
if err != nil {
return fmt.Errorf("setting hook: %w", err)
}
}
return nil
}
// ClearHookBead clears the hook_bead slot on an agent bead.
// Used when work is complete or unslung.
func (b *Beads) ClearHookBead(agentBeadID string) error {
_, err := b.run("slot", "clear", agentBeadID, "hook")
if err != nil {
return fmt.Errorf("clearing hook: %w", err)
}
return nil
}
// UpdateAgentCleanupStatus updates the cleanup_status field in an agent bead.
// This is called by the polecat to self-report its git state (ZFC compliance).
// Valid statuses: clean, has_uncommitted, has_stash, has_unpushed
@@ -1623,3 +1819,113 @@ func (b *Beads) MergeSlotEnsureExists() (string, error) {
return status.ID, nil
}
// ===== Rig Identity Beads =====
// RigFields contains the fields specific to rig identity beads.
type RigFields struct {
Repo string // Git URL for the rig's repository
Prefix string // Beads prefix for this rig (e.g., "gt", "bd")
State string // Operational state: active, archived, maintenance
}
// FormatRigDescription formats the description field for a rig identity bead.
func FormatRigDescription(name string, fields *RigFields) string {
if fields == nil {
return ""
}
var lines []string
lines = append(lines, fmt.Sprintf("Rig identity bead for %s.", name))
lines = append(lines, "")
if fields.Repo != "" {
lines = append(lines, fmt.Sprintf("repo: %s", fields.Repo))
}
if fields.Prefix != "" {
lines = append(lines, fmt.Sprintf("prefix: %s", fields.Prefix))
}
if fields.State != "" {
lines = append(lines, fmt.Sprintf("state: %s", fields.State))
}
return strings.Join(lines, "\n")
}
// ParseRigFields extracts rig fields from an issue's description.
func ParseRigFields(description string) *RigFields {
fields := &RigFields{}
for _, line := range strings.Split(description, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
colonIdx := strings.Index(line, ":")
if colonIdx == -1 {
continue
}
key := strings.TrimSpace(line[:colonIdx])
value := strings.TrimSpace(line[colonIdx+1:])
if value == "null" || value == "" {
value = ""
}
switch strings.ToLower(key) {
case "repo":
fields.Repo = value
case "prefix":
fields.Prefix = value
case "state":
fields.State = value
}
}
return fields
}
// CreateRigBead creates a rig identity bead for tracking rig metadata.
// The ID format is: <prefix>-rig-<name> (e.g., gt-rig-gastown)
// Use RigBeadID() helper to generate correct IDs.
// The created_by field is populated from BD_ACTOR env var for provenance tracking.
func (b *Beads) CreateRigBead(id, title string, fields *RigFields) (*Issue, error) {
description := FormatRigDescription(title, fields)
args := []string{"create", "--json",
"--id=" + id,
"--type=rig",
"--title=" + title,
"--description=" + description,
}
// Default actor from BD_ACTOR env var for provenance tracking
if actor := os.Getenv("BD_ACTOR"); actor != "" {
args = append(args, "--actor="+actor)
}
out, err := b.run(args...)
if err != nil {
return nil, err
}
var issue Issue
if err := json.Unmarshal(out, &issue); err != nil {
return nil, fmt.Errorf("parsing bd create output: %w", err)
}
return &issue, nil
}
// RigBeadIDWithPrefix generates a rig identity bead ID using the specified prefix.
// Format: <prefix>-rig-<name> (e.g., gt-rig-gastown)
func RigBeadIDWithPrefix(prefix, name string) string {
return fmt.Sprintf("%s-rig-%s", prefix, name)
}
// RigBeadID generates a rig identity bead ID using "gt" prefix.
// For non-gastown rigs, use RigBeadIDWithPrefix with the rig's configured prefix.
func RigBeadID(name string) string {
return RigBeadIDWithPrefix("gt", name)
}

View File

@@ -3,6 +3,7 @@ package beads
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
@@ -141,6 +142,17 @@ func TestIntegration(t *testing.T) {
b := New(dir)
// Sync database with JSONL before testing to avoid "Database out of sync" errors.
// This can happen when JSONL is updated (e.g., by git pull) but the SQLite database
// hasn't been imported yet. Running sync --import-only ensures we test against
// consistent data and prevents flaky test failures.
syncCmd := exec.Command("bd", "--no-daemon", "sync", "--import-only")
syncCmd.Dir = dir
if err := syncCmd.Run(); err != nil {
// If sync fails (e.g., no database exists), just log and continue
t.Logf("bd sync --import-only failed (may not have db): %v", err)
}
// Test List
t.Run("List", func(t *testing.T) {
issues, err := b.List(ListOptions{Status: "open"})
@@ -1490,3 +1502,253 @@ func TestDelegationTerms(t *testing.T) {
t.Errorf("parsed.CreditShare = %d, want %d", parsed.CreditShare, terms.CreditShare)
}
}
// TestSetupRedirect tests the beads redirect setup for worktrees.
func TestSetupRedirect(t *testing.T) {
t.Run("crew worktree with local beads", func(t *testing.T) {
// Setup: town/rig/.beads (local, no redirect)
townRoot := t.TempDir()
rigRoot := filepath.Join(townRoot, "testrig")
rigBeads := filepath.Join(rigRoot, ".beads")
crewPath := filepath.Join(rigRoot, "crew", "max")
// Create rig structure
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatalf("mkdir rig beads: %v", err)
}
if err := os.MkdirAll(crewPath, 0755); err != nil {
t.Fatalf("mkdir crew: %v", err)
}
// Run SetupRedirect
if err := SetupRedirect(townRoot, crewPath); err != nil {
t.Fatalf("SetupRedirect failed: %v", err)
}
// Verify redirect was created
redirectPath := filepath.Join(crewPath, ".beads", "redirect")
content, err := os.ReadFile(redirectPath)
if err != nil {
t.Fatalf("read redirect: %v", err)
}
want := "../../.beads\n"
if string(content) != want {
t.Errorf("redirect content = %q, want %q", string(content), want)
}
})
t.Run("crew worktree with tracked beads", func(t *testing.T) {
// Setup: town/rig/.beads/redirect -> mayor/rig/.beads (tracked)
townRoot := t.TempDir()
rigRoot := filepath.Join(townRoot, "testrig")
rigBeads := filepath.Join(rigRoot, ".beads")
mayorRigBeads := filepath.Join(rigRoot, "mayor", "rig", ".beads")
crewPath := filepath.Join(rigRoot, "crew", "max")
// Create rig structure with tracked beads
if err := os.MkdirAll(mayorRigBeads, 0755); err != nil {
t.Fatalf("mkdir mayor/rig beads: %v", err)
}
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatalf("mkdir rig beads: %v", err)
}
// Create rig-level redirect to mayor/rig/.beads
if err := os.WriteFile(filepath.Join(rigBeads, "redirect"), []byte("mayor/rig/.beads\n"), 0644); err != nil {
t.Fatalf("write rig redirect: %v", err)
}
if err := os.MkdirAll(crewPath, 0755); err != nil {
t.Fatalf("mkdir crew: %v", err)
}
// Run SetupRedirect
if err := SetupRedirect(townRoot, crewPath); err != nil {
t.Fatalf("SetupRedirect failed: %v", err)
}
// Verify redirect goes directly to mayor/rig/.beads (no chain - bd CLI doesn't support chains)
redirectPath := filepath.Join(crewPath, ".beads", "redirect")
content, err := os.ReadFile(redirectPath)
if err != nil {
t.Fatalf("read redirect: %v", err)
}
want := "../../mayor/rig/.beads\n"
if string(content) != want {
t.Errorf("redirect content = %q, want %q", string(content), want)
}
// Verify redirect resolves correctly
resolved := ResolveBeadsDir(crewPath)
// crew/max -> ../../mayor/rig/.beads (direct, no chain)
if resolved != mayorRigBeads {
t.Errorf("resolved = %q, want %q", resolved, mayorRigBeads)
}
})
t.Run("polecat worktree", func(t *testing.T) {
townRoot := t.TempDir()
rigRoot := filepath.Join(townRoot, "testrig")
rigBeads := filepath.Join(rigRoot, ".beads")
polecatPath := filepath.Join(rigRoot, "polecats", "worker1")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatalf("mkdir rig beads: %v", err)
}
if err := os.MkdirAll(polecatPath, 0755); err != nil {
t.Fatalf("mkdir polecat: %v", err)
}
if err := SetupRedirect(townRoot, polecatPath); err != nil {
t.Fatalf("SetupRedirect failed: %v", err)
}
redirectPath := filepath.Join(polecatPath, ".beads", "redirect")
content, err := os.ReadFile(redirectPath)
if err != nil {
t.Fatalf("read redirect: %v", err)
}
want := "../../.beads\n"
if string(content) != want {
t.Errorf("redirect content = %q, want %q", string(content), want)
}
})
t.Run("refinery worktree", func(t *testing.T) {
townRoot := t.TempDir()
rigRoot := filepath.Join(townRoot, "testrig")
rigBeads := filepath.Join(rigRoot, ".beads")
refineryPath := filepath.Join(rigRoot, "refinery", "rig")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatalf("mkdir rig beads: %v", err)
}
if err := os.MkdirAll(refineryPath, 0755); err != nil {
t.Fatalf("mkdir refinery: %v", err)
}
if err := SetupRedirect(townRoot, refineryPath); err != nil {
t.Fatalf("SetupRedirect failed: %v", err)
}
redirectPath := filepath.Join(refineryPath, ".beads", "redirect")
content, err := os.ReadFile(redirectPath)
if err != nil {
t.Fatalf("read redirect: %v", err)
}
want := "../../.beads\n"
if string(content) != want {
t.Errorf("redirect content = %q, want %q", string(content), want)
}
})
t.Run("cleans runtime files but preserves tracked files", func(t *testing.T) {
townRoot := t.TempDir()
rigRoot := filepath.Join(townRoot, "testrig")
rigBeads := filepath.Join(rigRoot, ".beads")
crewPath := filepath.Join(rigRoot, "crew", "max")
crewBeads := filepath.Join(crewPath, ".beads")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatalf("mkdir rig beads: %v", err)
}
// Simulate worktree with both runtime and tracked files
if err := os.MkdirAll(crewBeads, 0755); err != nil {
t.Fatalf("mkdir crew beads: %v", err)
}
// Runtime files (should be removed)
if err := os.WriteFile(filepath.Join(crewBeads, "beads.db"), []byte("fake db"), 0644); err != nil {
t.Fatalf("write fake db: %v", err)
}
if err := os.WriteFile(filepath.Join(crewBeads, "issues.jsonl"), []byte("{}"), 0644); err != nil {
t.Fatalf("write issues.jsonl: %v", err)
}
// Tracked files (should be preserved)
if err := os.WriteFile(filepath.Join(crewBeads, "config.yaml"), []byte("prefix: test"), 0644); err != nil {
t.Fatalf("write config: %v", err)
}
if err := os.WriteFile(filepath.Join(crewBeads, "README.md"), []byte("# Beads"), 0644); err != nil {
t.Fatalf("write README: %v", err)
}
if err := SetupRedirect(townRoot, crewPath); err != nil {
t.Fatalf("SetupRedirect failed: %v", err)
}
// Verify runtime files were cleaned up
if _, err := os.Stat(filepath.Join(crewBeads, "beads.db")); !os.IsNotExist(err) {
t.Error("beads.db should have been removed")
}
if _, err := os.Stat(filepath.Join(crewBeads, "issues.jsonl")); !os.IsNotExist(err) {
t.Error("issues.jsonl should have been removed")
}
// Verify tracked files were preserved
if _, err := os.Stat(filepath.Join(crewBeads, "config.yaml")); err != nil {
t.Errorf("config.yaml should have been preserved: %v", err)
}
if _, err := os.Stat(filepath.Join(crewBeads, "README.md")); err != nil {
t.Errorf("README.md should have been preserved: %v", err)
}
// Verify redirect was created
redirectPath := filepath.Join(crewBeads, "redirect")
if _, err := os.Stat(redirectPath); err != nil {
t.Errorf("redirect file should exist: %v", err)
}
})
t.Run("rejects mayor/rig canonical location", func(t *testing.T) {
townRoot := t.TempDir()
rigRoot := filepath.Join(townRoot, "testrig")
rigBeads := filepath.Join(rigRoot, ".beads")
mayorRigPath := filepath.Join(rigRoot, "mayor", "rig")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatalf("mkdir rig beads: %v", err)
}
if err := os.MkdirAll(mayorRigPath, 0755); err != nil {
t.Fatalf("mkdir mayor/rig: %v", err)
}
err := SetupRedirect(townRoot, mayorRigPath)
if err == nil {
t.Error("SetupRedirect should reject mayor/rig location")
}
if err != nil && !strings.Contains(err.Error(), "canonical") {
t.Errorf("error should mention canonical location, got: %v", err)
}
})
t.Run("rejects path too shallow", func(t *testing.T) {
townRoot := t.TempDir()
rigRoot := filepath.Join(townRoot, "testrig")
if err := os.MkdirAll(rigRoot, 0755); err != nil {
t.Fatalf("mkdir rig: %v", err)
}
err := SetupRedirect(townRoot, rigRoot)
if err == nil {
t.Error("SetupRedirect should reject rig root (too shallow)")
}
})
t.Run("fails if rig beads missing", func(t *testing.T) {
townRoot := t.TempDir()
rigRoot := filepath.Join(townRoot, "testrig")
crewPath := filepath.Join(rigRoot, "crew", "max")
// No rig/.beads created
if err := os.MkdirAll(crewPath, 0755); err != nil {
t.Fatalf("mkdir crew: %v", err)
}
err := SetupRedirect(townRoot, crewPath)
if err == nil {
t.Error("SetupRedirect should fail if rig .beads missing")
}
})
}

View File

@@ -20,6 +20,7 @@ type AttachmentFields struct {
AttachedMolecule string // Root issue ID of the attached molecule
AttachedAt string // ISO 8601 timestamp when attached
AttachedArgs string // Natural language args passed via gt sling --args (no-tmux mode)
DispatchedBy string // Agent ID that dispatched this work (for completion notification)
}
// ParseAttachmentFields extracts attachment fields from an issue's description.
@@ -61,6 +62,9 @@ func ParseAttachmentFields(issue *Issue) *AttachmentFields {
case "attached_args", "attached-args", "attachedargs":
fields.AttachedArgs = value
hasFields = true
case "dispatched_by", "dispatched-by", "dispatchedby":
fields.DispatchedBy = value
hasFields = true
}
}
@@ -88,6 +92,9 @@ func FormatAttachmentFields(fields *AttachmentFields) string {
if fields.AttachedArgs != "" {
lines = append(lines, "attached_args: "+fields.AttachedArgs)
}
if fields.DispatchedBy != "" {
lines = append(lines, "dispatched_by: "+fields.DispatchedBy)
}
return strings.Join(lines, "\n")
}
@@ -107,6 +114,9 @@ func SetAttachmentFields(issue *Issue, fields *AttachmentFields) string {
"attached_args": true,
"attached-args": true,
"attachedargs": true,
"dispatched_by": true,
"dispatched-by": true,
"dispatchedby": true,
}
// Collect non-attachment lines from existing description
@@ -499,7 +509,7 @@ func FormatSynthesisFields(fields *SynthesisFields) string {
type RoleConfig struct {
// SessionPattern defines how to derive tmux session name.
// Supports placeholders: {rig}, {name}, {role}
// Examples: "gt-mayor", "gt-{rig}-{role}", "gt-{rig}-{name}"
// Examples: "hq-mayor", "hq-deacon", "gt-{rig}-{role}", "gt-{rig}-{name}"
SessionPattern string
// WorkDirPattern defines the working directory relative to town root.

View File

@@ -57,7 +57,12 @@ func LoadRoutes(beadsDir string) ([]Route, error) {
// If the prefix already exists, it updates the path.
func AppendRoute(townRoot string, route Route) error {
beadsDir := filepath.Join(townRoot, ".beads")
return AppendRouteToDir(beadsDir, route)
}
// AppendRouteToDir appends a route to routes.jsonl in the given beads directory.
// If the prefix already exists, it updates the path.
func AppendRouteToDir(beadsDir string, route Route) error {
// Load existing routes
routes, err := LoadRoutes(beadsDir)
if err != nil {
@@ -185,3 +190,60 @@ func FindConflictingPrefixes(beadsDir string) (map[string][]string, error) {
return conflicts, nil
}
// ExtractPrefix extracts the prefix from a bead ID.
// For example, "ap-qtsup.16" returns "ap-", "hq-cv-abc" returns "hq-".
// Returns empty string if no valid prefix found (empty input, no hyphen,
// or hyphen at position 0 which would indicate an invalid prefix).
func ExtractPrefix(beadID string) string {
if beadID == "" {
return ""
}
idx := strings.Index(beadID, "-")
if idx <= 0 {
return ""
}
return beadID[:idx+1]
}
// GetRigPathForPrefix returns the rig path for a given bead ID prefix.
// The townRoot should be the Gas Town root directory (e.g., ~/gt).
// Returns the full absolute path to the rig directory, or empty string if not found.
// For town-level beads (path="."), returns townRoot.
func GetRigPathForPrefix(townRoot, prefix string) string {
beadsDir := filepath.Join(townRoot, ".beads")
routes, err := LoadRoutes(beadsDir)
if err != nil || routes == nil {
return ""
}
for _, r := range routes {
if r.Prefix == prefix {
if r.Path == "." {
return townRoot // Town-level beads
}
return filepath.Join(townRoot, r.Path)
}
}
return ""
}
// ResolveHookDir determines the directory for running bd update on a bead.
// Since bd update doesn't support routing or redirects, we must resolve the
// actual rig directory from the bead's prefix. hookWorkDir is only used as
// a fallback if prefix resolution fails.
func ResolveHookDir(townRoot, beadID, hookWorkDir string) string {
// Always try prefix resolution first - bd update needs the actual rig dir
prefix := ExtractPrefix(beadID)
if rigPath := GetRigPathForPrefix(townRoot, prefix); rigPath != "" {
return rigPath
}
// Fallback to hookWorkDir if provided
if hookWorkDir != "" {
return hookWorkDir
}
return townRoot
}

View File

@@ -52,6 +52,143 @@ func TestGetPrefixForRig_NoRoutesFile(t *testing.T) {
}
}
func TestExtractPrefix(t *testing.T) {
tests := []struct {
beadID string
expected string
}{
{"ap-qtsup.16", "ap-"},
{"hq-cv-abc", "hq-"},
{"gt-mol-xyz", "gt-"},
{"bd-123", "bd-"},
{"", ""},
{"nohyphen", ""},
{"-startswithhyphen", ""}, // Leading hyphen = invalid prefix
{"-", ""}, // Just hyphen = invalid
{"a-", "a-"}, // Trailing hyphen is valid
}
for _, tc := range tests {
t.Run(tc.beadID, func(t *testing.T) {
result := ExtractPrefix(tc.beadID)
if result != tc.expected {
t.Errorf("ExtractPrefix(%q) = %q, want %q", tc.beadID, result, tc.expected)
}
})
}
}
func TestGetRigPathForPrefix(t *testing.T) {
// Create a temporary directory with routes.jsonl
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
routesContent := `{"prefix": "ap-", "path": "ai_platform/mayor/rig"}
{"prefix": "gt-", "path": "gastown/mayor/rig"}
{"prefix": "hq-", "path": "."}
`
if err := os.WriteFile(filepath.Join(beadsDir, "routes.jsonl"), []byte(routesContent), 0644); err != nil {
t.Fatal(err)
}
tests := []struct {
prefix string
expected string
}{
{"ap-", filepath.Join(tmpDir, "ai_platform/mayor/rig")},
{"gt-", filepath.Join(tmpDir, "gastown/mayor/rig")},
{"hq-", tmpDir}, // Town-level beads return townRoot
{"unknown-", ""}, // Unknown prefix returns empty
{"", ""}, // Empty prefix returns empty
}
for _, tc := range tests {
t.Run(tc.prefix, func(t *testing.T) {
result := GetRigPathForPrefix(tmpDir, tc.prefix)
if result != tc.expected {
t.Errorf("GetRigPathForPrefix(%q, %q) = %q, want %q", tmpDir, tc.prefix, result, tc.expected)
}
})
}
}
func TestGetRigPathForPrefix_NoRoutesFile(t *testing.T) {
tmpDir := t.TempDir()
// No routes.jsonl file
result := GetRigPathForPrefix(tmpDir, "ap-")
if result != "" {
t.Errorf("Expected empty string when no routes file, got %q", result)
}
}
func TestResolveHookDir(t *testing.T) {
// Create a temporary directory with routes.jsonl
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
routesContent := `{"prefix": "ap-", "path": "ai_platform/mayor/rig"}
{"prefix": "hq-", "path": "."}
`
if err := os.WriteFile(filepath.Join(beadsDir, "routes.jsonl"), []byte(routesContent), 0644); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
beadID string
hookWorkDir string
expected string
}{
{
name: "prefix resolution takes precedence over hookWorkDir",
beadID: "ap-test",
hookWorkDir: "/custom/path",
expected: filepath.Join(tmpDir, "ai_platform/mayor/rig"),
},
{
name: "resolves rig path from prefix",
beadID: "ap-test",
hookWorkDir: "",
expected: filepath.Join(tmpDir, "ai_platform/mayor/rig"),
},
{
name: "town-level bead returns townRoot",
beadID: "hq-test",
hookWorkDir: "",
expected: tmpDir,
},
{
name: "unknown prefix uses hookWorkDir as fallback",
beadID: "xx-unknown",
hookWorkDir: "/fallback/path",
expected: "/fallback/path",
},
{
name: "unknown prefix without hookWorkDir falls back to townRoot",
beadID: "xx-unknown",
hookWorkDir: "",
expected: tmpDir,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
result := ResolveHookDir(tmpDir, tc.beadID, tc.hookWorkDir)
if result != tc.expected {
t.Errorf("ResolveHookDir(%q, %q, %q) = %q, want %q",
tmpDir, tc.beadID, tc.hookWorkDir, result, tc.expected)
}
})
}
}
func TestAgentBeadIDsWithPrefix(t *testing.T) {
tests := []struct {
name string

View File

@@ -16,9 +16,9 @@ import (
)
// SessionName is the tmux session name for Boot.
// Note: We use "gt-boot" instead of "gt-deacon-boot" to avoid tmux prefix
// matching collisions. Tmux matches session names by prefix, so "gt-deacon-boot"
// would match when checking for "gt-deacon", causing HasSession("gt-deacon")
// Note: We use "gt-boot" instead of "hq-deacon-boot" to avoid tmux prefix
// matching collisions. Tmux matches session names by prefix, so "hq-deacon-boot"
// would match when checking for "hq-deacon", causing HasSession("hq-deacon")
// to return true when only Boot is running.
const SessionName = "gt-boot"

View File

@@ -9,7 +9,7 @@
"hooks": [
{
"type": "command",
"command": "gt prime && gt mail check --inject && gt nudge deacon session-started"
"command": "export PATH=\"$HOME/go/bin:$HOME/bin:$PATH\" && gt prime && gt mail check --inject && gt nudge deacon session-started"
}
]
}
@@ -20,7 +20,7 @@
"hooks": [
{
"type": "command",
"command": "gt prime"
"command": "export PATH=\"$HOME/go/bin:$HOME/bin:$PATH\" && gt prime"
}
]
}
@@ -31,7 +31,7 @@
"hooks": [
{
"type": "command",
"command": "gt mail check --inject"
"command": "export PATH=\"$HOME/go/bin:$HOME/bin:$PATH\" && gt mail check --inject"
}
]
}
@@ -42,7 +42,7 @@
"hooks": [
{
"type": "command",
"command": "gt costs record"
"command": "export PATH=\"$HOME/go/bin:$HOME/bin:$PATH\" && gt costs record"
}
]
}

View File

@@ -9,7 +9,7 @@
"hooks": [
{
"type": "command",
"command": "gt prime && gt nudge deacon session-started"
"command": "export PATH=\"$HOME/go/bin:$HOME/bin:$PATH\" && gt prime && gt nudge deacon session-started"
}
]
}
@@ -20,7 +20,7 @@
"hooks": [
{
"type": "command",
"command": "gt prime"
"command": "export PATH=\"$HOME/go/bin:$HOME/bin:$PATH\" && gt prime"
}
]
}
@@ -31,7 +31,7 @@
"hooks": [
{
"type": "command",
"command": "gt mail check --inject"
"command": "export PATH=\"$HOME/go/bin:$HOME/bin:$PATH\" && gt mail check --inject"
}
]
}
@@ -42,7 +42,7 @@
"hooks": [
{
"type": "command",
"command": "gt costs record"
"command": "export PATH=\"$HOME/go/bin:$HOME/bin:$PATH\" && gt costs record"
}
]
}

View File

@@ -27,7 +27,7 @@ const (
// RoleTypeFor returns the RoleType for a given role name.
func RoleTypeFor(role string) RoleType {
switch role {
case "polecat", "witness", "refinery":
case "polecat", "witness", "refinery", "deacon":
return Autonomous
default:
return Interactive
@@ -35,8 +35,8 @@ func RoleTypeFor(role string) RoleType {
}
// EnsureSettings ensures .claude/settings.json exists in the given directory.
// If the file doesn't exist, it copies the appropriate template based on role type.
// If the file already exists, it's left unchanged.
// For worktrees, we use sparse checkout to exclude source repo's .claude/ directory,
// so our settings.json is the only one Claude Code sees.
func EnsureSettings(workDir string, roleType RoleType) error {
claudeDir := filepath.Join(workDir, ".claude")
settingsPath := filepath.Join(claudeDir, "settings.json")

View File

@@ -127,24 +127,29 @@ func init() {
// categorizeSession determines the agent type from a session name.
func categorizeSession(name string) *AgentSession {
// Must start with gt- prefix
session := &AgentSession{Name: name}
// Town-level agents use hq- prefix: hq-mayor, hq-deacon
if strings.HasPrefix(name, "hq-") {
suffix := strings.TrimPrefix(name, "hq-")
if suffix == "mayor" {
session.Type = AgentMayor
return session
}
if suffix == "deacon" {
session.Type = AgentDeacon
return session
}
return nil // Unknown hq- session
}
// Rig-level agents use gt- prefix
if !strings.HasPrefix(name, "gt-") {
return nil
}
session := &AgentSession{Name: name}
suffix := strings.TrimPrefix(name, "gt-")
// Town-level agents: gt-mayor, gt-deacon (simple format, one per machine)
if suffix == "mayor" {
session.Type = AgentMayor
return session
}
if suffix == "deacon" {
session.Type = AgentDeacon
return session
}
// Witness sessions: legacy format gt-witness-<rig> (fallback)
if strings.HasPrefix(suffix, "witness-") {
session.Type = AgentWitness

View File

@@ -443,6 +443,73 @@ func TestBeadsRemoveRoute(t *testing.T) {
}
}
// TestSlingCrossRigRoutingResolution verifies that sling can resolve rig paths
// for cross-rig bead hooking using ExtractPrefix and GetRigPathForPrefix.
// This is the fix for https://github.com/steveyegge/gastown/issues/148
func TestSlingCrossRigRoutingResolution(t *testing.T) {
townRoot := setupRoutingTestTown(t)
tests := []struct {
beadID string
expectedPath string // Relative to townRoot, or "." for town-level
}{
{"gt-mol-abc", "gastown/mayor/rig"},
{"tr-task-xyz", "testrig/mayor/rig"},
{"hq-cv-123", "."}, // Town-level beads
}
for _, tc := range tests {
t.Run(tc.beadID, func(t *testing.T) {
// Step 1: Extract prefix from bead ID
prefix := beads.ExtractPrefix(tc.beadID)
if prefix == "" {
t.Fatalf("ExtractPrefix(%q) returned empty", tc.beadID)
}
// Step 2: Resolve rig path from prefix
rigPath := beads.GetRigPathForPrefix(townRoot, prefix)
if rigPath == "" {
t.Fatalf("GetRigPathForPrefix(%q, %q) returned empty", townRoot, prefix)
}
// Step 3: Verify the path is correct
var expectedFull string
if tc.expectedPath == "." {
expectedFull = townRoot
} else {
expectedFull = filepath.Join(townRoot, tc.expectedPath)
}
if rigPath != expectedFull {
t.Errorf("GetRigPathForPrefix resolved to %q, want %q", rigPath, expectedFull)
}
// Step 4: Verify the .beads directory exists at that path
beadsDir := filepath.Join(rigPath, ".beads")
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
t.Errorf(".beads directory doesn't exist at resolved path: %s", beadsDir)
}
})
}
}
// TestSlingCrossRigUnknownPrefix verifies behavior for unknown prefixes.
func TestSlingCrossRigUnknownPrefix(t *testing.T) {
townRoot := setupRoutingTestTown(t)
// An unknown prefix should return empty string
unknownBeadID := "xx-unknown-123"
prefix := beads.ExtractPrefix(unknownBeadID)
if prefix != "xx-" {
t.Fatalf("ExtractPrefix(%q) = %q, want %q", unknownBeadID, prefix, "xx-")
}
rigPath := beads.GetRigPathForPrefix(townRoot, prefix)
if rigPath != "" {
t.Errorf("GetRigPathForPrefix for unknown prefix returned %q, want empty", rigPath)
}
}
// TestBeadsGetPrefixForRig verifies prefix lookup by rig name.
func TestBeadsGetPrefixForRig(t *testing.T) {
tmpDir := t.TempDir()

Some files were not shown because too many files have changed in this diff Show More