322 Commits

Author SHA1 Message Date
mayor
e3d99c3aed fix: correct ZFC acronym (Zero Framework Cognition)
Some checks failed
Release / goreleaser (push) Failing after 5m2s
Release / publish-npm (push) Has been skipped
Release / update-homebrew (push) Has been skipped
2026-01-10 01:25:27 -08:00
mayor
819c9dd179 chore: bump version to 0.2.4
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 01:24:36 -08:00
mayor
9bb63900d4 docs: update CHANGELOG for v0.2.4 release
Add 0.2.4 changelog entry covering:
- Priming subsystem (PRIME.md, post-handoff detection, doctor checks)
- gt prime --dry-run, --state, --explain flags
- ZFC improvements (query tmux directly, remove PID detection)
- Cross-level hook visibility fixes
- Rig-level default formulas

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 01:21:50 -08:00
mayor
fc1a1dea88 test: add t.Parallel() to enable parallel test execution
Add t.Parallel() calls across config and rig test files to enable
concurrent test execution and faster test runs.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 01:20:32 -08:00
dementus
dd9cd61075 feat(prime): add --state, --dry-run, --explain flags with mutual exclusivity validation
Add three new flags to gt prime command:
- --state: Output role state as JSON and exit early (for scripting)
- --dry-run: Skip side effects (persistence, locks, events)
- --explain: Show verbose role detection reasoning

The --state flag is mutually exclusive with all other flags and errors
if combined. The other flags (--dry-run, --explain, --hook) can be
combined freely.

Also fixes missing filepath import in beads.go.

Closes: bd-t8ven

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 01:14:27 -08:00
rictus
272f83f1fc fix(doctor): add AGENTS.md size check to rig-level priming
The AGENTS.md file at rig level (e.g., gastown/AGENTS.md) should be a thin
bootstrap pointer (<20 lines), not full context. This adds a check in
checkRigPriming() to flag large AGENTS.md files, similar to how CLAUDE.md
is checked in checkAgentPriming().

Also fixes missing filepath import in beads.go that was breaking the build.

Closes: bd-mfrs6

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 01:08:29 -08:00
furiosa
6e6e5ce08c refactor(prime): extract findHookedBead to eliminate duplication
detectSessionState() and checkSlungWork() both contained identical
logic for finding hooked/in_progress beads assigned to an agent.
Extracted this into findHookedBead() helper function.

Also includes priming subsystem improvements from mayor:
- Add --dry-run flag for testing without side effects
- Add --state flag to output detected state only
- Add --explain flag to show why sections are included
- Add missing filepath import to beads.go

Fixes: bd-hvwnb

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 01:07:01 -08:00
mayor
db353c247b feat: implement priming subsystem improvements
Phase 1 of dynamic priming subsystem:

1. PRIME.md provisioning for all workers (hq-5z76w, hq-ukjrr Part A)
   - Added ProvisionPrimeMD to beads package with Gas Town context template
   - Provision at rig level in AddRig() so all workers inherit it
   - Added fallback provisioning in crew and polecat managers
   - Created PRIME.md for existing rigs

2. Post-handoff detection to prevent handoff loop bug (hq-ukjrr Part B)
   - Added FileHandoffMarker constant (.runtime/handoff_to_successor)
   - gt handoff writes marker before respawn
   - gt prime detects marker and outputs "HANDOFF COMPLETE" warning
   - Marker cleared after detection to prevent duplicate warnings

3. Priming health checks for gt doctor (hq-5scnt)
   - New priming_check.go validates priming subsystem configuration
   - Checks: SessionStart hook, gt prime command, PRIME.md presence
   - Warns if CLAUDE.md is too large (should be bootstrap pointer)
   - Fixable: provisions missing PRIME.md files

This ensures crew workers get Gas Town context (GUPP, hooks, propulsion)
even if the gt prime hook fails, via bd prime fallback.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 01:07:01 -08:00
max
7533fed55e refactor(cmd): extract polecat helpers to reduce duplication
Split polecat.go (1635 lines) into:
- polecat.go (1359 lines): cobra commands and handlers
- polecat_helpers.go (260 lines): shared helper functions

Extracted:
- resolvePolecatTargets(): shared list-building logic from remove/nuke
- checkPolecatSafety(): safety check logic for destructive operations
- displaySafetyCheckBlocked(): blocked polecat display
- displayDryRunSafetyCheck(): dry-run safety status display

Reduces duplication between runPolecatRemove and runPolecatNuke.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 00:25:59 -08:00
gastown/crew/gus
afb944f616 fix(formula): set rigPath when falling back to gastown default
When `gt formula run` fell back to the default "gastown" rig (because no
rig could be detected), it didn't set rigPath, which meant the default
formula lookup would fail. Now rigPath is properly constructed when we
have townRoot but can't detect a current rig.

Also adds tests for GetDefaultFormula helper.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 23:24:28 -08:00
Brett VanderVeen
6016f15da9 feat(formula): add default formula configuration at rig level (#297)
Allow `gt formula run` to be called without a formula name by configuring
a default in the rig's settings/config.json under workflow.default_formula.

Co-authored-by: Brett VanderVeen <brett.vanderveen@gfs.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 23:22:45 -08:00
Steve Yegge
f90b58bc6d Merge pull request #311 from rsnodgrass/feat/ux-system-import
feat(ui): import comprehensive UX system from beads
2026-01-09 23:13:58 -08:00
gastown/crew/dennis
b60f016955 refactor(beads,mail): split large files into focused modules
Break down monolithic beads.go and mail.go into smaller, single-purpose files:

beads package:
- beads_agent.go: Agent-related bead operations
- beads_delegation.go: Delegation bead handling
- beads_dog.go: Dog pool operations
- beads_merge_slot.go: Merge slot management
- beads_mr.go: Merge request operations
- beads_redirect.go: Redirect bead handling
- beads_rig.go: Rig bead operations
- beads_role.go: Role bead management

cmd package:
- mail_announce.go: Announcement subcommand
- mail_check.go: Mail check subcommand
- mail_identity.go: Identity management
- mail_inbox.go: Inbox operations
- mail_queue.go: Queue subcommand
- mail_search.go: Search functionality
- mail_send.go: Send subcommand
- mail_thread.go: Thread operations

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 23:01:55 -08:00
gastown/crew/jack
609a4af087 feat(handoff): add explicit instructions to handoff nudge message
When a session starts via handoff, the nudge message now includes
clear instructions to check hook and mail. This prevents agent
confusion when SessionStart hooks haven't loaded CLAUDE.md yet.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 22:58:32 -08:00
Ryan Snodgrass
e1f2bb8b4b feat(ui): import comprehensive UX system from beads
Import beads' UX design system into gastown:

- Add internal/ui/ package with Ayu theme colors and semantic styling
  - styles.go: AdaptiveColor definitions for light/dark mode
  - terminal.go: TTY detection, NO_COLOR/CLICOLOR support
  - markdown.go: Glamour rendering with agent mode bypass
  - pager.go: Smart paging with GT_PAGER support

- Add colorized help output (internal/cmd/help.go)
  - Group headers in accent color
  - Command names styled for scannability
  - Flag types and defaults muted

- Add gt thanks command (internal/cmd/thanks.go)
  - Contributor display with same logic as bd thanks
  - Styled with Ayu theme colors

- Update gt doctor to match bd doctor UX
  - Category grouping (Core, Infrastructure, Rig, Patrol, etc.)
  - Semantic icons (✓ ⚠ ✖) with Ayu colors
  - Tree connectors for detail lines
  - Summary line with pass/warn/fail counts
  - Warnings section at end with numbered issues

- Migrate existing styles to use ui package
  - internal/style/style.go uses ui.ColorPass etc.
  - internal/tui/feed/styles.go uses ui package colors

Co-Authored-By: SageOx <ox@sageox.ai>
2026-01-09 22:46:06 -08:00
gastown/crew/max
f7d497ba07 fix(zfc): remove strings.Contains conflict detection from Go code
hq-hcil1: Remove deprecated HasConflict/HasAuthFailure/IsNotARepo/HasRebaseConflict
methods that violated ZFC by having Go code decide error types based on stderr parsing.

Changes:
- Remove deprecated helper methods from GitError and SwarmGitError
- Export GetConflictingFiles() which uses git porcelain output (diff --diff-filter=U)
- Update CheckConflicts(), engineer.go, and integration.go to use GetConflictingFiles()
- Update tests to verify raw stderr is available for agent observation

ZFC principle: Go code transports raw output to agents; agents observe and decide.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 22:31:55 -08:00
gastown/crew/max
131dac91c8 refactor(zfc): derive state from files instead of in-memory cache
Apply ZFC (Zero Forge Cache) principle across git error handling and
feed curation. Agents now observe raw git output and make their own
decisions rather than relying on pre-interpreted error types.

- Add GitError type with raw stdout/stderr for observation
- Add SwarmGitError following the same pattern
- Remove in-memory deduplication maps from Curator
- Curator now reads state from feed/events files

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 22:23:44 -08:00
gastown/crew/george
b92e46474a fix(polecat): remove pending.json tracking anti-pattern (ZFC)
Removed the pending.json file that shadowed observable state. Now
discovers pending spawns directly from POLECAT_STARTED messages in
the Deacon's inbox.

Changes:
- CheckInboxForSpawns: Discovers from mail, no more LoadPending/SavePending
- TriggerPendingSpawns: Archives mail after successful trigger
- PruneStalePending: Archives old messages instead of pruning from JSON

The mail system is now the source of truth for pending spawns.

Closes: hq-i31f7

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 22:11:14 -08:00
gastown/crew/joe
fc8718e680 fix(zfc): remove Go-side computation and stderr parsing violations
hq-u0ach: done.go - Add --cleanup-status flag so agents can pass cleanup
status directly. Removes computeCleanupStatus() which violated ZFC by
having Go compute cleanup status from git state.

hq-z0zqw: beads.go - Remove strings.Contains parsing for ErrNotARepo and
ErrSyncConflict. Per ZFC, Go should transport errors to agents, not parse
them to make decisions. IsBeadsRepo() now uses file existence check.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 22:11:02 -08:00
dementus
2f50a59e74 fix(hook): warn when hooked bead is already closed
When a bead is closed externally via bd close, it could remain on
an agent's hook, causing confusion when running gt hook. Now
gt hook detects closed beads and shows a warning message with
instructions to clear the hook using gt unsling.

Closes: gt-8w0r6

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 22:10:09 -08:00
slit
aeb4c0d26f fix(hook): make cross-level hooks visible to mayor/deacon
The gt hook command wasn't finding hooked beads for town-level roles
(mayor, deacon) because of an identity format mismatch:

- When hooking a bead, resolveSelfTarget() sets assignee with trailing
  slash (e.g., "mayor/")
- When querying, buildAgentIdentity() returned without slash ("mayor")

This caused the assignee filter to miss the hooked bead since bd does
exact matching on the assignee field.

Fix:
- Update buildAgentIdentity() to return "mayor/" and "deacon/" with
  trailing slash, matching the format used when setting assignee
- Update isTownLevelRole() to accept both formats for compatibility

Fixes: gt-g6ng2

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 22:09:32 -08:00
nux
c4fcdd88c8 fix(daemon,beads): use correct agent bead ID format and bd create flags
Two fixes in this commit:

1. daemon/lifecycle.go: Fix agent bead ID pattern for GUPP/orphaned work checks
   - Wrong: gt-polecat-<rig>-<name> (e.g., gt-polecat-gastown-nux)
   - Correct: <prefix>-<rig>-polecat-<name> (e.g., gt-gastown-polecat-nux)
   - Use config.GetRigPrefix() instead of hardcoding gt prefix
   - Use beads.ParseAgentBeadID() in extractRigFromAgentID

2. beads/beads.go: Fix invalid --add-label flag in bd create calls
   - bd create uses --labels, not --add-label
   - bd update uses --add-label (unchanged, was correct)
   - Fixed Create, CreateWithID, CreateAgentBead, CreateRigBead

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 22:08:55 -08:00
gastown/crew/george
c94d59dca7 fix: ZFC improvements - query tmux directly instead of marker TTL
Two ZFC fixes:

1. Boot marker file (hq-zee5n): Changed IsRunning() to query
   tmux.HasSession() directly instead of checking marker file
   freshness with TTL. Removed stale marker check from doctor.

2. Branch pattern matching (hq-zwuh6): Replaced hardcoded "polecat/"
   strings with constants.BranchPolecatPrefix for consistency.

Also removed 60-second WaitForCommand blocking from crew Start()
which was causing gt crew start to hang.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 22:08:12 -08:00
gastown/crew/gus
e0858096f6 fix(zfc): move stuck detection thresholds to agent-controlled config
Per ZFC principle: 'Let agents decide thresholds. Stuck is a judgment call.'

Changes:
- Add health check threshold fields to RoleConfig (ping_timeout,
  consecutive_failures, kill_cooldown, stuck_threshold)
- Add LoadStuckConfig() to read thresholds from hq-deacon-role bead
- Update patrol_check.go to use configurable stuck threshold
- Defaults remain as fallbacks when no role bead config exists

Agents can now configure their stuck detection by adding fields to their
role bead, e.g.:
  ping_timeout: 45s
  consecutive_failures: 5
  kill_cooldown: 10m
  stuck_threshold: 2h

Fixes: hq-2355b
2026-01-09 22:07:35 -08:00
dennis
0f633be4b1 fix(zfc): remove PID-based agent liveness detection
Replace ProcessExists() checks in witness and refinery managers with
tmux session detection. Agent liveness should be derived from tmux
session state, not PID probing (per ZFC tracking principles).

- Remove util.ProcessExists() from witness/manager.go and refinery/manager.go
- Delete internal/util/process.go and process_test.go (now unused)
- Foreground mode and Stop() now rely solely on tmux HasSession/KillSession

Closes: hq-yxkdr (recentDeaths already removed)
Closes: hq-1sd4o (ProcessExists removed)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 22:02:34 -08:00
gastown/crew/gus
593185873d feat(witness): honor role start_command + add --agent/--env overrides (#293)
Adds comprehensive override support for witness start/restart:

- Honor hq-witness-role start_command and env_vars from role bead
- Add --agent flag to override the agent/model
- Add --env flag for arbitrary env var overrides (KEY=VALUE, repeatable)

Precedence (highest to lowest):
1. CLI --env overrides
2. Role bead env_vars
3. config.AgentEnv() defaults

Examples:
  gt witness start greenplace --agent codex
  gt witness start greenplace --env ANTHROPIC_MODEL=claude-3-haiku

Co-authored-by: joshuavial <git@codewithjv.com>
2026-01-09 22:00:52 -08:00
gastown/crew/gus
86751e1ea5 feat(witness): add --env flag for environment variable overrides
Extends the --agent flag with a more general --env flag that allows
setting arbitrary environment variables when starting a witness.

Precedence (highest to lowest):
1. CLI --env overrides
2. Role bead env_vars
3. config.AgentEnv() defaults

Examples:
  gt witness start greenplace --env ANTHROPIC_MODEL=claude-3-haiku
  gt witness restart greenplace --env DEBUG=1 --env VERBOSE=true

Co-authored-by: joshuavial <git@codewithjv.com>
2026-01-09 22:00:43 -08:00
joshuavial
f9473c7b9e fix: satisfy lint and regenerate formulas 2026-01-09 21:57:11 -08:00
joshuavial
dcb085e64e chore: drop local beads changes 2026-01-09 21:56:53 -08:00
joshuavial
369cf82b77 feat: add witness start agent override 2026-01-09 21:56:53 -08:00
joshuavial
bfd3096b49 fix: prefer witness agent override 2026-01-09 21:56:53 -08:00
joshuavial
271bd7ea0a fix: honor witness role start_command 2026-01-09 21:56:53 -08:00
joshuavial
0d3f6c9654 feat: allow witness restart agent override 2026-01-09 21:56:53 -08:00
gastown/crew/gus
24136ebaa1 refactor: consolidate agent environment variables (#294)
Introduces config.AgentEnv() as the single source of truth for all agent
environment variables. Previously, different roles received different subsets
of variables depending on their startup path.

Changes:
- All agents now receive GT_ROOT and BEADS_DIR (previously only polecat/refinery)
- Add gt doctor env-vars check to validate tmux session variables
- Fix gt role home witness returning incorrect path
- Fix BEADS_DIR not following redirects for repos with tracked beads

Co-authored-by: julianknutsen <julianknutsen@users.noreply.github.com>
2026-01-09 21:55:28 -08:00
gastown/crew/gus
7a1ed80068 fix: remove unused identity parameter from setSessionEnvironment 2026-01-09 21:54:54 -08:00
gastown/crew/gus
e6bdc639ab chore: sync embedded formulas with source 2026-01-09 21:53:05 -08:00
julianknutsen
65334320c7 docs: update environment variable documentation
Update docs to reflect the centralized config.AgentEnv() function and
complete environment variable coverage:

reference.md:
- Restructured env vars section with tables by category
- Added GT_ROOT, GT_CREW, BEADS_AGENT_NAME documentation
- Added "Environment by Role" quick reference table
- Added doctor check documentation for env-vars validation

identity.md:
- Updated Environment Setup section with complete examples
- Added crew environment example showing BEADS_NO_DAEMON
- Mentioned centralized config.AgentEnv() function
- Cross-referenced to reference.md for full details

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:30 -08:00
julianknutsen
ce231a31af fix(doctor): use full AgentEnv for env-vars check
The env-vars check was using AgentEnvSimple which doesn't know the
actual TownRoot and BeadsDir paths. This could cause false positive
mismatches when comparing expected (empty paths) vs actual (real paths).

- Use config.AgentEnv with proper TownRoot and BeadsDir from CheckContext
- Rig-level roles resolve beads dir from rig path
- Update tests to use expectedEnv helper that generates full env vars

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:30 -08:00
julianknutsen
f1a2c56900 test: add unit tests for deacon and boot roles in config/env.go
Complete test coverage for all roles in the centralized AgentEnv
function:
- TestAgentEnv_Deacon: verifies deacon env vars (GT_ROLE, BD_ACTOR,
  GIT_AUTHOR_NAME)
- TestAgentEnv_Boot: verifies boot env vars including BD_ACTOR=deacon-boot

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:30 -08:00
julianknutsen
cc87fdd03d fix(boot): use centralized AgentEnv in degraded mode
spawnDegraded was manually constructing env vars, missing GT_ROOT,
BEADS_DIR, and GIT_AUTHOR_NAME that spawnTmux sets via config.AgentEnv().

Now both paths use the same centralized env var generation for
consistency.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:30 -08:00
julianknutsen
9b4c7ac28b fix(doctor): check deacon env vars after AgentEnv refactor
The env-vars doctor check was skipping deacon with a stale comment
"it doesn't use standard env vars". After the AgentEnv refactor,
deacon/manager.go now uses config.AgentEnv() like all other roles.

- Remove the skip condition for deacon in env_check.go
- Update test from TestEnvVarsCheck_DeaconSkipped to test deacon is
  actually checked (TestEnvVarsCheck_DeaconCorrect/DeaconMissing)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:30 -08:00
julianknutsen
64e1448981 test: add unit tests for config/env.go
Tests for AgentEnv(), ExportPrefix(), BuildStartupCommandWithEnv(),
and helper functions (MergeEnv, FilterEnv, WithoutEnv, EnvToSlice).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:30 -08:00
julianknutsen
e9a013c0d2 fix: add BEADS_NO_DAEMON to crew for isolated clone context
Crew workspaces use clones with redirected beads directories, like
polecat and refinery. They should bypass the bd daemon for fresh
data and isolation.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:30 -08:00
julianknutsen
e999ceb1c1 refactor: consolidate agent env vars into config.AgentEnv
Create centralized AgentEnv function as single source of truth for all
agent environment variables. All agents now consistently receive:
- GT_ROLE, BD_ACTOR, GIT_AUTHOR_NAME (role identity)
- GT_ROOT, BEADS_DIR (workspace paths)
- GT_RIG, GT_POLECAT/GT_CREW (rig-specific identity)
- BEADS_AGENT_NAME, BEADS_NO_DAEMON (beads config)
- CLAUDE_CONFIG_DIR (optional account selection)

Remove RoleEnvVars in favor of AgentEnvSimple wrapper.
Remove IncludeBeadsEnv flag - beads env vars always included.
Update all manager and cmd call sites to use AgentEnv.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:30 -08:00
julianknutsen
52b9a95f98 feat(doctor): add env-vars check, remove redundant gtroot check
Adds a new `gt doctor` check that verifies tmux session environment
variables match expected values from `config.RoleEnvVars()`.

- Checks all Gas Town sessions (gt-*, hq-*)
- Compares actual tmux env vars against expected for each role
- Reports mismatches with guidance to restart sessions
- Treats no sessions as success (valid when Gas Town is down)
- Skips deacon (doesn't use standard env vars)

Also:
- Adds `tmux.GetAllEnvironment()` to retrieve all session env vars
- Removes redundant gtroot_check (env-vars check covers GT_ROOT)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:30 -08:00
julianknutsen
1d88a73eaa fix: use ResolveBeadsDir for polecat BEADS_DIR
Previously, polecat startup used hardcoded paths for BEADS_DIR that
didn't follow redirects for repos with tracked beads. This meant
polecats working in worktrees (where .beads/redirect points to the
actual beads location) would use the wrong beads directory.

Fixed locations:
- daemon.go: polecat startup now uses ResolveBeadsDir
- polecat/session_manager.go: session startup now uses ResolveBeadsDir

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:09 -08:00
julianknutsen
7150ce2624 refactor: update managers to use RoleEnvVars
Consolidates all role startup code to use the shared RoleEnvVars()
function, ensuring consistent env vars across tmux SetEnvironment
and Claude startup command exports.

Updated:
- Mayor manager
- Deacon startup (daemon.go)
- Witness manager
- Refinery manager
- Polecat startup (daemon.go)
- BuildPolecatStartupCommand, BuildCrewStartupCommand helpers

This ensures all agents receive the same identity env vars regardless
of startup path.

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:09 -08:00
julianknutsen
2343e6b0ef feat: add RoleEnvVars and improve gt role CLI
Introduces config.RoleEnvVars() as the single source of truth for role
identity environment variables (GT_ROLE, GT_RIG, BD_ACTOR, etc.).

CLI improvements:
- Fix getRoleHome paths (witness has no /rig suffix, polecat/crew do)
- Make gt role env read-only (displays current role from env/cwd)
- Add EnvIncomplete handling: fill missing env vars from cwd with warning
- Add cwd mismatch warnings when not in role home directory
- gt role home now validates --polecat requires --rig

Includes comprehensive e2e tests for all role detection scenarios.

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:52:09 -08:00
Steve Yegge
491b635cbc Merge pull request #300 from apfm-cabe-waldrop/fix/shutdown-stop-daemon
Fix gt shutdown to stop daemon
2026-01-09 21:38:07 -08:00
gastown/crew/max
cb2b130ca2 fix(crew): parallelize crew start to prevent hanging
Start crew members concurrently instead of sequentially. Previously,
`gt crew start --all` could hang for minutes because each crew member
was started one at a time, with each waiting up to 60 seconds for
Claude to initialize.

With parallel startup, all crew members start simultaneously and
the total wait time is bounded by the slowest individual startup.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:24:23 -08:00
slit
be35b3eaab feat(version): add stale binary detection with startup warning
Add detection for when the installed gt binary is out of date with the
source repository. This helps catch issues where commands fail mysteriously
because the installed binary doesn't have recent fixes.

Changes:
- Add internal/version package with stale binary detection logic
- Add startup warning in PersistentPreRunE when binary is stale
- Add gt doctor check for stale-binary
- Use prefix matching for commit comparison (handles short vs full hash)

The warning is non-blocking and only shows once per shell session via
the GT_STALE_WARNED environment variable.

Resolves: gt-ud912

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 18:14:17 -08:00
rictus
b8075a5e06 fix(sling): accept bead IDs directly even when routing fails
When routing-based verification (verifyBeadExists) fails due to
routes.jsonl configuration issues, gt sling now falls back to pattern
matching via looksLikeBeadID to accept valid bead ID formats.

The fix ensures:
1. verifyBeadExists is tried first (routing-based lookup)
2. verifyFormulaExists is tried second (formula check)
3. looksLikeBeadID pattern match is used as final fallback

Also improved looksLikeBeadID to accept any 1-5 letter lowercase
prefix followed by hyphen and alphanumeric chars.

Fixes: gt sling bd-xxx failing with "not a valid bead or formula"
when the bead exists but routing cannot find it.

Closes: gt-9e8s5

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 18:13:11 -08:00
nux
9697007182 feat(beads): migrate from types to labels for bead classification
Updates the beads package to use label-based filtering (gt:agent, gt:role,
gt:merge-request, etc.) instead of the deprecated --type= flag.

Key changes:
- ListAgentBeads(): --type=agent -> --label=gt:agent
- CreateAgentBead/CreateDogAgentBead: add gt:agent label on creation
- ReadyWithType(): --type -> --label=gt:<type>
- GetRoleConfig()/GetAgentBead(): type check -> label check via HasLabel()
- FindMRForBranch(): Type filter -> Label filter
- Create()/CreateWithID(): convert Type to gt:<type> label
- CreateRigBead(): --type=rig -> --add-label=gt:rig
- ClearMail(): Type filter -> Label filter
- Add Label field to ListOptions (Type field deprecated)

Closes: gt-x0i2m

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 18:12:36 -08:00
gastown/crew/jack
ad8189b010 feat(deacon): use await-signal with exponential backoff in patrol loop
The Deacon patrol formula now uses `gt mol step await-signal` with
exponential backoff instead of vague "sleep 60s" instructions.

How it works:
- Subscribes to `bd activity --follow` (beads activity feed)
- Returns IMMEDIATELY when any gt/bd command triggers activity
- On timeout, waits exponentially longer: 60s → 120s → 240s → max 10m
- Tracks idle:N label on hq-deacon bead across invocations

This connects the designed-but-unintegrated backoff mechanism to the
actual patrol loop. Idle towns let Deacon sleep; active work wakes it.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 18:07:07 -08:00
furiosa
7367aa7572 docs: add gt nudge guidance to mayor template (hq-6h9w4o)
- Add Coordination section with gt nudge command
- Clarify line 180: routine nudging is Witness job, Mayor can nudge stuck refinery/witness
- Add warning to NEVER use tmux send-keys (drops Enter key)
- Includes liftoff test timestamp in manager.go

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 14:34:44 -08:00
slit
ba76bf1232 feat(doctor): add safeguards for town root branch protection
Add three layers of protection to prevent accidental branch switches in
the town root (~/gt), which should always stay on main:

1. Doctor check `town-root-branch`: Verifies town root is on main/master.
   Fixable via `gt doctor --fix` to switch back to main.

2. Doctor check `pre-checkout-hook`: Verifies git pre-checkout hook is
   installed. The hook blocks checkout from main to any other branch.
   Fixable via `gt doctor --fix` or `gt git-init`.

3. Runtime warning in all gt commands: Non-blocking warning if town root
   is on wrong branch, with fix instructions.

The root cause of this issue was git commands running in the wrong
directory, switching the town root to a polecat branch. This broke gt
commands because rigs.json and other configs were on main, not the
polecat branch.

Closes: hq-1kwuj

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 14:11:53 -08:00
nux
692d6819f2 feat(crash): improve crash logging and mass death detection
Add comprehensive crash logging improvements to help diagnose mass session death events:

- Add TypeSessionDeath and TypeMassDeath event types for feed visibility
- Log pre-death events before killing sessions (who killed, why)
- Add mass death detection in daemon (3+ deaths in 30s triggers alert)
- Add macOS crash report check in gt doctor
- Support session death events in townlog and feed curator

Closes hq-kt1o6

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 14:11:09 -08:00
rictus
97b70517cc fix(beads): make TestIntegration work with redirect architecture
- Use ResolveBeadsDir() to find beads.db in multi-worktree setups
  where .beads/redirect points to the canonical beads location
- Add --allow-stale flag to bd sync command to handle cases where
  the daemon is actively writing and staleness check would fail

Fixes hq-0cgd3

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 14:10:14 -08:00
gastown/crew/george
73a8889c3e fix: remove settings.json that was incorrectly force-added
This file was added with -f despite .claude/ being in .gitignore.
When the repo is used as a crew workspace, this file shadows the
proper crew-level settings at crew/.claude/settings.json.

Removing it allows Claude Code to find the correct settings by
walking up the directory tree.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 13:30:11 -08:00
gastown/crew/george
61b561a540 feat(doctor): add custom types check and centralize BeadsCustomTypes
- Add BeadsCustomTypes constant ("agent,role,rig,convoy,slot") to avoid
  hardcoded strings scattered across the codebase
- Add CustomTypesCheck to gt doctor that verifies Gas Town custom types
  are registered with beads, with --fix support
- Register custom types during gt init (best-effort, skips if no beads)
- Update install.go, rig_check.go, and rig/manager.go to use the constant

This ensures consistent type registration across all code paths and
catches misconfigured beads databases via gt doctor.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 13:30:11 -08:00
gastown/crew/george
86739556c2 fix(prime): use startup beacon instead of bare "gt prime" prompt
Agents were confused when receiving "gt prime" as their first prompt,
interpreting it as a command to investigate rather than understanding
they were starting a Gas Town session.

Changed crew_at.go, start.go, and handoff.go to use FormatStartupNudge()
which produces a proper beacon like:
  [GAS TOWN] george/crew/george <- human • 2026-01-09T10:30 • start

The SessionStart hook (gt prime --hook) still injects context - the
prompt just needs to be something agents recognize as a greeting.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 13:30:11 -08:00
mayor
ff3d1b2e23 fix(refinery): use mayor/rig fallback for correct git remote
Refinery was using rig.Path which found the town's .git with rig-named
remotes (e.g., 'gastown') instead of 'origin'. This caused refinery to
miss polecat branches when fetching.

Now falls back to mayor/rig (which has 'origin' pointing to the project
repo) when refinery/rig doesn't exist.

Fixes: hq-uvrzt
2026-01-09 12:42:14 -08:00
mayor
69299e9a43 Fix gt shutdown to stop daemon (fixes #299)
gt shutdown was not stopping the daemon, which caused it to restart
agents (witnesses, refineries) after shutdown completed. The daemon
heartbeats every 3 minutes and calls ensureWitnessesRunning() and
ensureRefineriesRunning(), which would notice the sessions were dead
and restart them.

This adds daemon stop logic to both runGracefulShutdown (as Phase 6)
and runImmediateShutdown (after polecat cleanup), matching the behavior
that gt down already has.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 11:36:11 -07:00
mayor
1701474b3d docs: add caution note to v0.2.3 changelog
Some checks failed
Release / goreleaser (push) Failing after 4m16s
Release / publish-npm (push) Has been skipped
Release / update-homebrew (push) Has been skipped
2026-01-09 01:00:27 -08:00
gastown/crew/jack
a7e9fbf699 feat(deacon): add github-gate-check step to patrol formula
Adds the missing github-gate-check step that runs `bd gate discover` and
`bd gate check --type=gh` to evaluate GitHub CI gates. Updates
dispatch-gated-molecules to depend on both gate-evaluation and
github-gate-check.

Fixes: gt-sfxpr

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 00:47:36 -08:00
gastown/crew/joe
358fcaf935 feat(mq): add configurable integration branch naming (#104)
Enterprise teams can now customize integration branch names to match
their conventions (e.g., username/TICKET-123/feature-name).

- Add integration_branch_template to MergeQueueConfig
- Add --branch CLI override for gt mq integration create
- Support {epic}, {prefix}, {user} template variables
- Validate branch names for git-safe characters
- Store actual branch name in epic metadata at create time
- Read stored branch name in land/status (fallback for old epics)

Also fixes unrelated build error in polecat/manager.go (polecatPath
variable was undefined).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 00:41:35 -08:00
furiosa
f19ddc5400 feat(costs): add verbose logging for silent failures
Add --verbose/-v flag to gt costs command that outputs debug information
when silent failures occur during cost tracking operations:

- wisp list failures in querySessionCostWisps and deleteSessionCostWisps
- bd show failures when querying wisp details
- JSON unmarshal failures when parsing wisp/event data
- payload unmarshal failures when parsing session payloads

This makes debugging cost tracking issues much easier as these error
paths previously continued silently without any indication of failure.

Closes: bd-qv8f9

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 00:35:15 -08:00
onyx
64b58b31ab fix(costs): improve cost tracking performance and determinism
- Sort map keys before iteration in createCostDigestBead for deterministic
  output ordering in By Role and By Rig sections (bd-66z6a)
- Batch wisp IDs into single bd show call to fix N+1 query pattern in
  querySessionCostWisps (bd-3hqvs)
- Batch wisp deletion into single subprocess call in deleteSessionCostWisps
  (bd-i8zab)

Part of: bd-1wmwp

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 00:25:53 -08:00
jack
afff85cdff fix(tmux): use NewSessionWithCommand to avoid send-keys race condition
Agent sessions would fail on startup because send-keys arrived before the
shell was ready, causing 'bad pattern' and 'command not found' errors.

Fix: Create sessions with the command directly using tmux new-session's
command argument. This runs the agent as the pane's initial process,
avoiding shell readiness timing issues entirely.

Updated all agent managers: mayor, deacon, witness, refinery, polecat, crew.

Also fixes pre-existing build error in polecat/manager.go (polecatPath →
clonePath/newClonePath).

Closes #280

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 23:35:31 -08:00
jack
a91e6cd643 fix(git): configure refspec on bare clones for worktree compatibility
Bare clones don't have remote.origin.fetch set by default, which breaks
worktrees that need to fetch and see origin/* refs. This caused refinery
to fail because origin/main never appeared after fetch.

- Add configureRefspec() to set standard refspec on bare repos
- Call from CloneBare() and CloneBareWithReference()
- Add BareRepoRefspecCheck to doctor for existing rigs

Closes #286

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 23:28:11 -08:00
gastown/crew/max
9b2f4a7652 feat(polecat): add repo path to worktrees for LLM ergonomics (GH#283)
Changes polecat worktree structure from:
  polecats/<name>/
to:
  polecats/<name>/<rigname>/

This gives Claude Code agents a recognizable directory name (e.g., tidepool/)
in their cwd instead of just the polecat name, preventing confusion about
which repo they are working in.

Key changes:
- Add clonePath() method to manager.go and session_manager.go for the actual
  git worktree path, keeping polecatDir() for existence checks
- Update Add(), RepairWorktree(), Remove() to use new structure
- Update daemon lifecycle and restart code for new paths
- Update witness handlers to detect both structures
- Update doctor checks (rig_check, branch_check, config_check,
  claude_settings_check) for backward compatibility
- All code includes fallback to old structure for existing polecats

Fixes #283

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 23:16:10 -08:00
george
c8c97fdf64 docs: add glossary contributed by Clay Shirky (#80)
Adds comprehensive glossary covering:
- Core principles (MEOW, GUPP, NDI)
- Environments (Town, Rig)
- Roles (Mayor, Deacon, Polecat, Witness, Crew, etc.)
- Work units (Bead, Formula, Molecule, Wisp, Hook)
- Workflow commands (Convoy, Slinging, Nudging, Handoff, Seance, Patrol)

Also adds link to glossary from README Core Concepts section.

Closes #80

Co-Authored-By: Clay Shirky <cshirky@users.noreply.github.com>
2026-01-08 23:03:52 -08:00
jack
43272f6fbb feat(tmux): enable mouse mode by default for Gas Town sessions
Adds EnableMouseMode() and calls it from ConfigureGasTownSession so all
new GT sessions get mouse support. Users can now click panes, scroll with
mouse wheel, and resize by dragging. Hold Shift for terminal text selection.

Closes #33

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 23:01:47 -08:00
george
65c3e90374 feat: Add Codex and OpenCode runtime backend support (#281)
Adds support for alternative AI runtime backends (Codex, OpenCode) alongside
the default Claude backend through a runtime abstraction layer.

- internal/runtime/runtime.go - Runtime-agnostic helper functions
- Extended RuntimeConfig with provider-specific settings
- internal/opencode/ for OpenCode plugin support
- Updated session managers to use runtime abstraction
- Removed unused ensureXxxSession functions
- Fixed daemon.go indentation, updated terminology to runtime

Backward compatible: Claude remains default runtime.

Co-Authored-By: Ben Kraus <ben@cinematicsoftware.com>
Co-Authored-By: Cameron Palmer <cameronmpalmer@users.noreply.github.com>
2026-01-08 22:56:37 -08:00
Steve Yegge
0eacdd367b feat(costs): redesign session cost tracking with wisps and daily digests (#292)
* feat(costs): redesign session cost tracking with wisps and daily digests

Implement the wisp-based cost tracking architecture per gt-cm900:

- gt costs record now creates ephemeral wisps (not exported to JSONL)
  to avoid log-in-database pollution with O(sessions/day) events

- gt costs digest aggregates yesterday's session wisps into a single
  permanent "Cost Report YYYY-MM-DD" bead for audit purposes

- gt costs query updated: --today queries wisps, --week queries
  digest beads + today's wisps

- gt costs migrate closes legacy open session.ended beads

- Deacon patrol formula updated with costs-digest step

The new architecture:
  Session ends -> Wisp (fast, N/day) -> Patrol digest -> Bead (1/day)

This preserves audit trail while keeping issues.jsonl clean.

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

* chore: sync canonical formula with embedded copy

Update .beads/formulas/ with the costs-digest step added to
mol-deacon-patrol.formula.toml. The go:generate copies from
.beads/formulas/ to internal/formula/formulas/.

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 22:52:47 -08:00
Cameron Palmer
9fe9323b9c fix: clean up dead code and fix indentation in runtime PR
- Remove unused ensureRefinerySession function from start.go
- Remove unused ensureSession and ensureWitness functions from up.go
- Remove unused ensureWitnessSession function from witness.go
- Remove orphaned imports (runtime, session, constants, config, rig, filepath, time)
- Fix indentation error in daemon.go triggerPendingSpawns comment

These functions were added as part of the Codex/OpenCode runtime support
but were never wired up. The existing managers (refinery.Manager.Start,
witness.Manager.Start) already handle session creation.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 22:51:51 -08:00
joe
bfafb9c179 docs: add explicit no-PR rule for maintainer repos
Polecats were creating GitHub PRs instead of using gt done to submit
to the Refinery. Added clear conditional language:

- If repo is steveyegge/beads or steveyegge/gastown: NEVER create PRs
- Polecats use gt done → Refinery merges
- Crew workers push directly to main
- PRs are for external contributors only

This fixes a prompting gap that led to PR #292 being created incorrectly.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 22:47:39 -08:00
julianknutsen
677a6ed84f feat(formula): add untracked status for formulas without .installed.json
When upgrading gt on an existing installation without .installed.json,
formulas that exist but don't match embedded were incorrectly marked as
"modified" (implying user customization). Now they're marked "untracked"
and are safe to update since there's no record of user modification.

This improves the upgrade experience:
- "modified" = tracked file user changed (skip update)
- "untracked" = file exists but not tracked (safe to update)

Adds 3 new tests for untracked scenarios.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 22:43:44 -08:00
julianknutsen
da2d71c3fe feat(formula): add checksum-based auto-update for embedded formulas
Adds infrastructure to automatically update embedded formulas when
the binary is upgraded, while preserving user customizations.

Changes:
- Add CheckFormulaHealth() to detect outdated/modified/missing formulas
- Add UpdateFormulas() to safely update formulas via gt doctor --fix
- Track installed formula checksums in .beads/formulas/.installed.json
- Add FormulaCheck to gt doctor with auto-fix capability
- Compute checksums at runtime from embedded files (no build-time manifest)

Update scenarios:
- Outdated (embedded changed, user unchanged): Update automatically
- Modified (user customized): Skip with warning
- Missing (user deleted): Reinstall with message
- New (never installed): Install

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 22:43:44 -08:00
dennis
e124402b7b fix: crew start rig inference + refactor overlay to shared utility
Two improvements:

1. gt crew start now infers rig from cwd when first arg is not a valid
   rig name (gt-czltv). Previously, running `gt crew start bob` from
   within a rig directory would fail because "bob" was treated as the
   rig name. Now it checks if the arg is a valid rig first.

2. Refactored copyOverlay to shared rig.CopyOverlay utility:
   - Eliminates code duplication between crew and polecat managers
   - Preserves source file permissions instead of hardcoding 0644
   - Follows PR #278 improvements

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 22:40:23 -08:00
Steve Yegge
705a7c2137 Merge pull request #278 from EscapeVelocityOperations/main
feat: add .runtime/overlay/ support for polecat/crew worktrees
2026-01-08 22:37:29 -08:00
gastown/crew/max
c2c6ddeaf9 docs(polecat): add pre-submission checklist with correct workflow
Adds a visible "CRITICAL" warning and pre-submission checklist to the
polecat template. Explicitly notes that polecats should NOT manually
close the root issue - the Refinery handles that after merge.

This addresses the intent of PR #287 while avoiding the conflicting
`bd close` instruction that would break the Refinery workflow.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 22:37:17 -08:00
beads/crew/giles
b509107100 feat(deacon): add dispatch-gated-molecules patrol step (GH#bd-1ep6e)
Add new step to mol-deacon-patrol.formula.toml that discovers molecules
blocked on gates that have now closed, and dispatches them to the
appropriate rig's polecat pool.

This completes the async resume cycle without explicit waiter tracking.
The molecule state IS the waiter - patrol discovers reality each cycle.

- Uses bd mol ready --gated to find gate-ready molecules
- Dispatches via gt sling <mol-id> <rig>/polecats
- Runs after gate-evaluation, before health-scan
- Bumps formula version to 6

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 21:34:25 -08:00
gastown/crew/max
34cb28e0b9 fix(beads): restore graceful degradation for mayor/rig fallback
When rig/.beads doesn't exist, fall back to mayor/rig/.beads (tracked
beads architecture) with a warning suggesting 'bd doctor' to fix.

This restores behavior that was inadvertently removed in #290, which
simplified SetupRedirect but removed the fallback path.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 21:02:15 -08:00
Joshua Vial
1da3e18e60 fix: gt sling failing to recognize beads after JSONL updates (#290)
* fix(sling): route bd mol commands to target rig directory

Executed-By: gastown/crew/jv
Rig: gastown
Role: crew

* Fix CI: enable beads custom types during install

Executed-By: gastown/crew/jv
Rig: gastown
Role: crew

* Fix gt sling failing to recognize beads after JSONL updates

Executed-By: gastown/crew/jv
Rig: gastown
Role: crew

---------

Co-authored-by: joshuavial <git@codewithjv.com>
2026-01-08 21:00:25 -08:00
max
5adb096d9d refactor(doctor): use strings.Contains instead of custom contains()
Replace the hand-rolled contains() function with the standard library
strings.Contains(). Also removes the redundant len(data) > 0 check
since strings.Contains handles empty strings correctly.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 20:26:23 -08:00
Sohail Mohammad
81bfe48ed3 feat: Set and Forget - Seamless Gas Town Integration (#255)
Adds shell integration for automatic Gas Town context detection.

Features:
- `gt enable` / `gt disable` - Global on/off switch
- `gt shell install|remove|status` - Shell integration management
- `gt rig quick-add [path]` - One-command project setup
- `gt uninstall` - Clean removal with options
- Shell hook auto-sets GT_TOWN_ROOT/GT_RIG on cd

Implementation:
- XDG-compliant state storage (~/.local/state/gastown/)
- Safe RC file manipulation with block markers
- Environment overrides (GASTOWN_DISABLED/ENABLED)
- Doctor check for global state validation

Co-authored-by: Sohail Mohammad <sohailm25@gmail.com>
2026-01-08 20:25:01 -08:00
max
41a758d6d8 fix(test): repair unterminated string literal in integration test
The t.Skipf call had a raw newline inside a double-quoted string,
which is invalid Go syntax. Use \n escape sequence instead.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 20:18:41 -08:00
mayor
5250e9e12a chore: bump version to v0.2.3
Worker safety release - prevents accidental termination of active agents.

Key changes:
- Kill authority removed from Deacon patrol (death warrants only)
- Bulletproof pause mechanism for Deacon
- Doctor warns instead of killing sessions
- New gt account switch command
- Hidden directory scanning fixes

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 20:06:57 -08:00
Subhrajit Makur
b3407759d2 fix(doctor): recognize gt prime --hook as valid session hook config (#14)
The SessionHookCheck was incorrectly flagging 'gt prime --hook' as invalid,
only accepting 'session-start.sh' wrapper. The --hook flag properly handles
session_id passthrough via stdin JSON, making it a valid alternative.

Changes:
- Update usesSessionStartScript to accept --hook flag
- Add containsFlag helper to prevent false positives (e.g., --hookup)
- Update error messages and fix hints to suggest both options
- Add comprehensive tests including edge cases

Tests cover:
- Bare gt prime (fails)
- gt prime --hook (passes)
- gt prime --hookup (fails - not a valid flag)
- gt prime --verbose --hook (passes - flag order doesn't matter)
- session-start.sh (passes)
- Mixed valid/invalid hooks in same file
- Town-level and rig-level settings
2026-01-08 17:58:16 -08:00
Subhrajit Makur
c8c765a239 fix: improve integration test reliability (#13)
- Add custom types config after bd init in daemon tests
- Replace fixed sleeps with poll-based waiting in tmux tests
- Skip beads integration test for JSONL-only repos

Fixes flaky test failures in parallel execution.
2026-01-08 17:58:16 -08:00
Steve Yegge
775af2973d Merge pull request #268 from julianknutsen/fix/gt-root-env
fix: agents cannot find town-level formulas
2026-01-08 17:52:41 -08:00
Steve Yegge
da906847dd Merge pull request #279 from joshuavial/fix/polecat-dotdir-scan
fix: extend polecat dot-dir filtering beyond #258
2026-01-08 17:23:26 -08:00
Steve Yegge
0a649e6faa Merge pull request #276 from joshuavial/feat/crew-list-all
feat: add --all to gt crew list
2026-01-08 17:23:23 -08:00
Steve Yegge
fb40fa1405 Merge pull request #272 from julianknutsen/fix/100-doctor-process-check-informational
fix(doctor): gt doctor --fix kills user's personal Claude sessions
2026-01-08 17:22:02 -08:00
Steve Yegge
7bfc2fcb76 Merge pull request #271 from julianknutsen/fix/daemon-restore-deacon-check
fix(daemon): dead deacon sessions never restarted (Boot observes but doesn't restart)
2026-01-08 17:21:58 -08:00
Steve Yegge
376305e9d9 Merge pull request #270 from julianknutsen/fix/formula-session-names
fix(formula): boot triage checks wrong session name, causing deacon restarts
2026-01-08 17:21:54 -08:00
Steve Yegge
73f5b4025b Merge pull request #273 from julianknutsen/fix/174-isclauderunning-detection
fix: IsClaudeRunning detects 'claude' and version patterns
2026-01-08 17:19:24 -08:00
Steve Yegge
c756f12d00 Merge pull request #269 from julianknutsen/cleanup/remove-unused-formula-json
chore: remove unused JSON formula file
2026-01-08 17:19:20 -08:00
max
8d5611f14e feat(doctor): add rig identity beads check
Adds RigBeadsCheck to gt doctor to verify rig identity beads exist.
These beads track rig metadata (git URL, prefix, state) and are created
by gt rig add. The check scans routes.jsonl and verifies each rig
has an identity bead, with --fix to create missing ones.

Recovered from furiosa's uncommitted work after worker interruption.

Co-Authored-By: furiosa <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 12:59:49 -08:00
Ben Kraus
98e154b18e opencode 2026-01-08 12:48:03 -05:00
Ben Kraus
38adfa4d8b codex 2026-01-08 12:36:54 -05:00
cstar
03b0f7ff52 feat: add .runtime/overlay/ support for polecat/crew worktrees
Add overlay directory support to automatically copy gitignored files
(like .env, config files) from <rig>/.runtime/overlay/ to polecat
and crew worktree roots when they are spawned.

This allows services started by polecats/crew to have their required
configuration files at the root without committing them to git.

Changes:
- Add copyOverlay() function to polecat and crew managers
- Call copyOverlay() after setupSharedBeads() in AddWithOptions/RepairWorktreeWithOptions
- Non-fatal: overlay copy failures only log warnings, don't block spawn

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 14:25:02 +01:00
joshuavial
3b628150c2 test: cover gt crew list --all 2026-01-09 02:22:36 +13:00
joshuavial
1afe3fb823 feat: add --all to gt crew list 2026-01-09 02:22:20 +13:00
julianknutsen
caa88d96c5 fix: IsClaudeRunning detects 'claude' and version patterns
Claude Code can report its pane command as "node", "claude", or a version
number like "2.0.76". Previously only "node" was detected, causing healthy
sessions to be incorrectly identified as zombies and killed during daemon
heartbeat recovery.

This fix detects all three patterns to prevent witness sessions from being
killed every 3 minutes.

Based on michaellady's work in PR #174.

Co-Authored-By: michaellady <michaellady@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 02:25:15 -08:00
julianknutsen
4c9e8b8b99 fix(doctor): make orphan process check informational only
The orphan-processes check previously killed any Claude process without
a tmux ancestor, which incorrectly targeted user's personal Claude
sessions running in regular terminals.

Now the check is informational only:
- Changed from FixableCheck to BaseCheck (no auto-fix)
- Returns StatusOK with details listing processes outside tmux
- Message advises user to verify processes are expected
- Removed Fix method and related helpers

The orphan-sessions check remains fixable since it only targets gt-*
sessions that don't match valid Gas Town patterns.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 01:57:27 -08:00
joshuavial
c699e3e2ed Stabilize bd role config tests 2026-01-08 22:43:31 +13:00
julianknutsen
65ecb6cafd fix(daemon): restore ensureDeaconRunning to heartbeat and use Manager
The heartbeat now explicitly calls ensureDeaconRunning() for basic
"is Deacon alive" checks, while Boot handles intelligent triage
(stuck/nudge/interrupt decisions).

Changed ensureDeaconRunning to use deacon.Manager.Start() instead of
duplicating startup logic. This gives daemon the same benefits:
- WaitForShellReady (fixes race condition)
- Claude settings setup
- Theming
- StartupNudge and PropulsionNudge (GUPP)

Heartbeat order:
1. ensureDeaconRunning - restart if dead (via Manager)
2. ensureBootRunning - intelligent triage for stuck states
3. checkDeaconHeartbeat - belt-and-suspenders fallback
4-11. Other checks (witnesses, refineries, polecats, etc.)

This was inadvertently removed when Boot was introduced, which
delegated all Deacon checks to Boot. But Boot's mol doesn't actually
restart Deacon - it just reports. Now responsibilities are clear:
daemon ensures alive, Boot ensures responsive.

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 01:23:51 -08:00
julianknutsen
540e33dbe9 fix(formula): correct deacon session name references in formulas
The deacon tmux session is named hq-deacon, not gt-deacon. Fix the
incorrect references in mol-boot-triage and mol-gastown-boot formulas.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 01:16:25 -08:00
joshuavial
85dd150d75 Skip dot dirs when scanning polecats 2026-01-08 22:10:40 +13:00
joshuavial
45634059dd Ignore .claude dirs when listing polecats 2026-01-08 22:10:39 +13:00
julianknutsen
d4da2b325d chore: remove unused JSON formula file
The formula parser only supports TOML (uses toml.Decode). The JSON
version of mol-gastown-boot was never used - it was likely created
by mistake or for an abandoned experiment.

Changes:
- Remove .beads/formulas/mol-gastown-boot.formula.json
- Remove internal/formula/formulas/mol-gastown-boot.formula.json
- Simplify go:generate to only copy .formula.toml files

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 01:09:14 -08:00
julianknutsen
4985bdfbcc feat(config): set GT_ROOT env var for all agent sessions
Previously GT_ROOT was documented as a formula search path but never
actually set, making $GT_ROOT/.beads/formulas/ unreachable for agents.

Now BuildStartupCommand automatically sets GT_ROOT to the town root,
enabling all agents (witness, refinery, polecat, crew, etc.) to find
town-level formulas without relying on cwd-relative paths.

Also adds a doctor check (gt-root-env) that warns when existing sessions
are missing GT_ROOT, with instructions to restart sessions.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 00:56:26 -08:00
max
f4cbcb4ce9 fix: SetupRedirect now works with tracked beads architecture
The SetupRedirect function was failing for rigs that use the tracked
beads architecture where the canonical beads location is mayor/rig/.beads
and there is no rig-level .beads directory.

This fix now checks for both locations:
1. rig/.beads (with optional redirect to mayor/rig/.beads)
2. mayor/rig/.beads directly (if no rig/.beads exists)

This ensures crew and polecat workspaces get the correct redirect file
pointing to the shared beads database in all configurations.

Closes: gt-jy77g

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 22:10:09 -08:00
Steve Yegge
c4d956ebe7 feat(deacon): implement bulletproof pause mechanism (gt-bpo2c) (#265)
Add multi-layer pause mechanism to prevent Deacon from causing damage:

Layer 1: File-based pause state
- Location: ~/.runtime/deacon/paused.json
- Stores: paused flag, reason, timestamp, paused_by

Layer 2: Commands
- `gt deacon pause [--reason="..."]` - pause with optional reason
- `gt deacon resume` - remove pause file
- `gt deacon status` - shows pause state prominently

Layer 3: Guards
- `gt prime` for deacon: shows PAUSED message, skips patrol context
- `gt deacon heartbeat`: fails when paused

Helper package:
- internal/deacon/pause.go with IsPaused/Pause/Resume functions

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 21:56:46 -08:00
jack
7f6fe53c6f feat(account): add gt account switch command
Adds the ability to switch between Claude Code accounts with a single command:
  gt account switch <handle>

The command:
1. Detects current account by checking ~/.claude symlink target
2. If ~/.claude is a real directory, moves it to the current account config_dir
3. Removes existing ~/.claude symlink (if any)
4. Creates symlink from ~/.claude to target account config_dir
5. Updates default account in accounts.json
6. Prints confirmation with restart reminder

Handles edge cases:
- Already on target account (no-op with message)
- Target account does not exist (error with list of valid accounts)
- ~/.claude is real directory (first-time setup scenario)

Closes gt-jd8m1

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 21:41:51 -08:00
jack
19f4fa3ddb fix(install): update placeholder comment to reference gt-4ke5e
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 21:38:35 -08:00
joe
e648edce8c docs: add Context Management section to Witness template (gt-jjama)
Add explicit handoff/cycling heuristics for the Witness role:
- Hand off after 15 patrol loops (vs Deacon's 20)
- Immediate handoff after extraordinary actions
- Define extraordinary actions specific to Witness role
- Add Handoff (Wisp-Based) section explaining idempotent patrols

This brings Witness documentation in line with Deacon's level of
detail for context cycling.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 21:37:21 -08:00
slit
8a8b56e9e6 fix: derive gt- prefix for gastown compound words (gt-m46bb) 2026-01-07 21:12:18 -08:00
julianknutsen
c91ab85457 fix: restore agent override support lost in manager refactors
The manager refactors (ea8bef2, 72544cc0) conflicted with the agent
override feature, causing regressions:

Deacon (ea8bef2):
- Lost agentOverride parameter
- Re-added respawn loop (removed in 5f2e16f)
- Lost GUPP (startup + propulsion nudges)

Crew (72544cc0):
- Lost agentOverride wiring to StartOptions
- --agent flag had no effect on crew refresh/restart

This fix restores agent override support and GUPP while keeping
improvements from the manager refactors (zombie detection, etc).

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 21:08:51 -08:00
Subhrajit Makur
00a59dec44 feat: Add rig-level custom agent support (#12)
* feat: Add rig-level custom agent support

Implement rig-level custom agent configuration support to enable per-rig
agent definitions in <rig>/settings/config.json, following the same pattern as
town-level agents in settings/config.json.

Changes:
- Added RigSettings.Agents field to internal/config/types.go
- Added DefaultRigAgentRegistryPath() and LoadRigAgentRegistry() functions to internal/config/agents.go
- Updated ResolveAgentConfigWithOverride() to accept and pass rigSettings parameter
- Updated GetRuntimeCommandWithAgentOverride() to use rigSettings when available
- Updated GetRuntimeCommandWithPromptAndAgentOverride() to use rigSettings
- Updated all Build*WithOverride functions to pass rigSettings

This fixes the issue where rig-level agent settings were loaded but
ignored by lookupAgentConfig, enabling per-rig custom agents for
polecats and crew members.

* test: Add rig-level custom agent tests

Added comprehensive unit tests for rig agent registry functions:
- TestDefaultRigAgentRegistryPath: verifies path construction
- TestLoadRigAgentRegistry: verifies file loading and JSON parsing
- TestLookupAgentConfigWithRigSettings: verifies agent lookup priority (rig > town > builtin)

Added placeholder integration test for future CI/CD setup.

* initial commit

* fix: resolve compilation errors in rig-level custom agent support

- Add missing RigAgentRegistryPath function (alias for DefaultRigAgentRegistryPath)
- Restore ResolveAgentConfigWithOverride function that was incorrectly removed
- Fix ResolveAgentConfig to return single value (not triple)
- Add initRegistryLocked() call to LoadRigAgentRegistry to prevent nil panic
- Fix DefaultRigAgentRegistryPath to use rigPath directly (not parent dir)
- Fix test file syntax errors (remove EOF artifacts)
- Fix test parameter order for lookupAgentConfig calls
- Fix test expectations to match correct custom agent override behavior

* test: implement rig-level custom agent integration test

- Add stub agent script that simulates AI agent with Q&A capability
- Test ResolveAgentConfig correctly picks up rig-level agents
- Test BuildPolecatStartupCommand includes custom agent command
- Test ResolveAgentConfigWithOverride respects rig agents
- Test rig agents override town agents with same name
- Add tmux integration test that spawns session and verifies output
- Stub agent echoes 'STUB_AGENT_STARTED' and handles ping/pong Q&A
- All tests pass including real tmux session verification

* docs: add OpenCode custom agent example to reference

- Show settings/agents.json format for advanced configs
- Include OpenCode example with session resume flags
- Document OPENCODE_PERMISSION env var for autonomous mode

* fix: improve rig-level agent support with docs and test fixes

- Add rig-level agent documentation to reference.md
- Document agent resolution order (rig → town → built-in)
- Deduplicate LoadAgentRegistry/LoadRigAgentRegistry into shared helper
- Fix test isolation in TestLoadRigAgentRegistry
- Fix nil pointer dereference in test assertions (use t.Fatal not t.Error)
2026-01-07 21:06:46 -08:00
Julian Knutsen
2de2d6b7e4 refactor: replace ensureRefinerySession with refinery.Manager.Start()
Replaces inline ensureRefinerySession function with refinery.NewManager(r).Start(false) in gt start --all. Gains zombie detection, proper state tracking, and WaitForShellReady fix.

CI failures (lint in beads.go, integration tests) are pre-existing issues unrelated to this PR's changes.

Co-Authored-By: julianknutsen <julianknutsen@users.noreply.github.com>
2026-01-07 21:03:52 -08:00
joshuavial
f30178265c Fix CI: enable beads custom types during install 2026-01-07 21:03:03 -08:00
keeper
5141facb21 docs: design Dog pool architecture for concurrent shutdown dances (gt-fsld8)
Key decisions:
- Fixed pool of 5 goroutines (not Claude sessions)
- State file persistence for crash recovery
- Warrant queuing when pool exhausted
- Dogs are lightweight state machine executors
- New internal/shutdown/ package (separate from existing dog package)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 21:01:47 -08:00
dag
15caf62b9f fix(formula): remove kill authority from Deacon patrol (gt-vhaej)
The Deacon patrol formula's zombie-scan step now:
- Only detects zombies via --dry-run, never kills directly
- Files death warrants for Boot to handle interrogation/execution
- Includes psychological weight language about termination gravity

This prevents accidental destruction of worker context, mid-task
progress, and unsaved state. Kill authority belongs to Boot.

Bumped version to 5.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 21:01:38 -08:00
Julian Knutsen
28a9de64d5 fix(tmux): wait for shell ready before sending keys (#264)
Add WaitForShellReady call before SendKeys in all agent managers
(deacon, mayor, witness, refinery). This prevents intermittent
"can't find pane" errors that occur when the tmux session is
created but the shell isn't ready to receive input yet.

The issue manifests under load (e.g., during `gt up` when multiple
agents start in sequence) where the 200ms delay in SendKeysDelayed
isn't sufficient for the pane to be fully initialized.

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

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 20:49:25 -08:00
Joshua Vial
a9ed342be6 fix: ignore hidden directories when enumerating polecats (#258)
* fix(sling): route bd mol commands to target rig directory

* Fix daemon polecat enumeration to ignore hidden dirs

* Ignore hidden dirs when discovering rig polecats

* Fix CI: enable beads custom types during install

---------

Co-authored-by: joshuavial <git@codewithjv.com>
2026-01-07 20:48:09 -08:00
Mike Lady
f9e788ccfb feat(ci): Add code coverage reporting to GitHub Actions (#246)
* bd sync: 2026-01-05 06:22:43

* bd sync: 2026-01-05 07:08:42

* bd sync: 2026-01-05 07:24:58

* feat: Add code coverage PR comment to GitHub Actions

Adds a step to the CI workflow that:
- Collects code coverage during test runs
- Parses per-package coverage percentages
- Posts a markdown table comment on PRs with:
  - Overall coverage percentage
  - Per-package breakdown table
- Updates existing comment on subsequent pushes

Closes: ga-tl5

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

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

* fix(ci): handle fork PR permissions for coverage comment

Fork PRs cannot write comments via GITHUB_TOKEN due to security
restrictions. Add condition to skip comment step for external PRs
and upload coverage report as artifact instead.

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

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

* refactor(ci): separate coverage into dedicated job

- Test job now uploads coverage.out and test-output.txt as artifacts
- New Coverage Report job runs after tests complete
- Downloads coverage data, generates report, uploads as artifact
- Always uploads coverage-report artifact (for both fork and internal PRs)
- Comments on PR only for internal PRs (fork PRs get notice message)
- Cleaner separation of concerns

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

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

* fix(ci): coverage job waits for both test and integration

Coverage Report job now depends on [test, integration] to ensure
it only runs after all test stages complete successfully.

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

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

* fix(ci): restore Coverage Report job after Test and Integration

Coverage Report job now properly:
- Depends on [test, integration] - waits for both to complete
- Downloads coverage data from Test job
- Generates and uploads coverage-report artifact
- Comments on internal PRs only

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

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

* test: add debugging output to TestInstallTownRoleSlots

Add logging for gt install output and bd list to help diagnose
CI failures where agent beads may not be created.

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

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

* fix(ci): update beads to @main and fix lint errors

- Change CI to install beads from @main instead of @latest
  (latest release doesn't support role/agent issue types)
- Remove error return from cleanBeadsRuntimeFiles since all
  errors are intentionally ignored (best-effort cleanup)

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

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

* fix(ci): pin beads to v0.44.0 for agent/role types

Beads main recently extracted Gas Town-specific types (agent, role, etc.)
from core. Pin CI to v0.44.0 which still has these types.

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

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

* fix(ci): unpin beads version back to @latest

Beads v0.46.0 now supports agent/role types again.

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

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

* chore: remove stale gastown/.beads files from PR

These beads files are local runtime state that shouldn't be committed.

🤖 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-07 20:45:58 -08:00
organic
c220678162 Merge remote-tracking branch 'origin/main' into polecat/organic-mk4yjuw0 2026-01-07 20:45:01 -08:00
organic
b649635f48 feat(formula): add shutdown-dance molecule for death warrant execution
Defines the state machine that Dogs execute for death warrants:
- 3-attempt interrogation with escalating timeouts (60s, 120s, 240s)
- PARDON path when session responds with ALIVE
- EXECUTE path after all attempts exhausted
- EPITAPH step for audit logging

Key design decisions documented:
- Dogs are goroutines, not Claude sessions
- Timeout gates close on timer OR early response detection
- State persisted to ~/gt/deacon/dogs/active/ for crash recovery

Implements specification for gt-cd404.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 20:44:30 -08:00
Julian Knutsen
117b91b87f fix(doctor): warn instead of killing sessions for stale town-root settings (#243)
When gt doctor --fix detects stale Claude settings at town root, it was
automatically killing ALL Gas Town sessions (gt-* and hq-*). This is too
disruptive because:

1. Deacon runs gt doctor automatically, creating a restart loop
2. Active crew/polecat work could be lost mid-task
3. Settings are only read at startup, so running agents already have
   the config loaded in memory

Instead, warn the user and tell them to restart agents manually:
"Town-root settings were moved. Restart agents to pick up new config:
    gt up --restart"

Addresses PR #239 feedback.

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

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 20:41:57 -08:00
Julian Knutsen
ffa8dd56cb test(polecat): skip beads-unavailable test when bd is installed (#244)
TestGetReturnsWorkingWithoutBeads assumes bd is not available and
expects state to default to StateWorking. When bd is installed, it
actually queries beads and returns the real state, causing the test
to fail.

Skip the test when bd is detected to avoid environment-dependent
failures.

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

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 20:41:34 -08:00
Mike Lady
92042d679c feat: Add Cursor, Auggie, and Sourcegraph AMP agent presets (#247)
* feat: add Cursor Agent as compatible agent for Gas Town

Add AgentCursor preset with ProcessNames field for multi-agent detection:
- AgentCursor preset: cursor-agent -p -f (headless + force mode)
- ProcessNames field on AgentPresetInfo for agent detection
- IsAgentRunning(session, processNames) in tmux package
- GetProcessNames(agentName) helper function

Closes: ga-vwr

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

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

* refactor: centralize agent preset list in config.go

Replace hardcoded ["claude", "gemini", "codex"] arrays with calls to
config.ListAgentPresets() to dynamically include all registered agents.

This fixes cursor agent not appearing in `gt config agent list` and
ensures new agent presets are automatically included everywhere.

Also updated doc comments to include "cursor" in example lists.

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

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

* test: add comprehensive agent client tests

Add tests for agent detection and command generation:

- TestIsAgentRunning: validates process name detection for all agents
  (claude/node, gemini, codex, cursor-agent)
- TestIsAgentRunning_NonexistentSession: edge case handling
- TestIsClaudeRunning: backwards compatibility wrapper
- TestListAgentPresetsMatchesConstants: ensures ListAgentPresets()
  returns all AgentPreset constants
- TestAgentCommandGeneration: validates full command line generation
  for all supported agents

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

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

* feat: add Auggie agent, fix Cursor interactive mode

Add Auggie CLI as supported agent:
- Command: auggie
- Args: --allow-indexing
- Supports session resume via --resume flag

Fix Cursor agent configuration:
- Remove -p flag (requires prompt, breaks interactive mode)
- Clear SessionIDEnv (cursor uses --resume with chatId directly)
- Keep -f flag for force/YOLO mode

Updated all test cases for both agents.

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

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

* feat(agents): add Sourcegraph AMP as agent preset

Add AgentAmp constant and builtinPresets entry for Sourcegraph AMP CLI.

Configuration:
- Command: amp
- Args: --dangerously-allow-all --no-ide
- ResumeStyle: subcommand (amp threads continue <threadId>)
- ProcessNames: amp

Closes: ga-guq

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

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

* fix: lint error in cleanBeadsRuntimeFiles

Change function to not return error (was always nil).

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

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

* fix: beads v0.46.0 compatibility and test fixes

- Add custom types config (agent,role,rig,convoy,event) after bd init calls
- Fix tmux_test.go to use variadic IsAgentRunning signature

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

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

* docs: update agent documentation for new presets

- README.md: Update agent examples to show cursor/auggie, add built-in presets list
- docs/reference.md: Add cursor, auggie, amp to built-in agents list
- CHANGELOG.md: Add entry for new agent presets under [Unreleased]

Addresses PR #247 review feedback.

🤖 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-07 20:35:06 -08:00
tajquitgenius
585c204648 fix: Register custom beads types during install (#250)
During `gt install`, the beads database is initialized but Gas Town's
custom issue types (agent, role, rig, convoy, slot) were not being
registered. This caused subsequent agent bead creation to fail with
"invalid issue type: agent" errors.

The fix adds `bd config set types.custom "agent,role,rig,convoy,slot"`
after `bd init` completes. This is idempotent and safe to run multiple
times.

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

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 19:17:39 -08:00
Martin Emde
6209a49d54 fix(costs): derive session name for mayor/deacon without GT_TOWN
Error: Ran 1 stop hook
  ⎿  Stop hook error: Failed with non-blocking status code: Error: --session flag required (or set GT_SESSION env var, or GT_RIG/GT_ROLE)
  Usage:
    gt costs record [flags]

deriveSessionName() now falls back to gt-{role} when GT_ROLE is mayor
or deacon but GT_TOWN is not set. Previously this case returned empty
string, causing the Stop hook to fail.
2026-01-07 19:17:28 -08:00
Steve Yegge
ffeff97d9f fix(crew): improve error message when not in crew workspace
- Show clearer error explaining user needs to specify crew name or cd into crew dir
- When --rig is specified, list available crew members in that rig

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 18:24:38 -08:00
Steve Yegge
9b5c889795 fix(costs): detect tmux session without TMUX env var
The TMUX environment variable is not inherited when Claude Code runs
bash commands, even though we are inside a tmux session. This caused
the Stop hook's 'gt costs record' to fail with:
  Error: --session flag required

Fix: Remove the early return that checked TMUX env var. The
tmux display-message command will naturally fail if we're not
in tmux, so the check was unnecessary and harmful.

Fixes: hq-to0lr

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 18:20:30 -08:00
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
379 changed files with 56183 additions and 13652 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.

43
.beads/PRIME.md Normal file
View File

@@ -0,0 +1,43 @@
# Gas Town Worker Context
> **Context Recovery**: Run `gt prime` for full context after compaction or new session.
## The Propulsion Principle (GUPP)
**If you find work on your hook, YOU RUN IT.**
No confirmation. No waiting. No announcements. The hook having work IS the assignment.
This is physics, not politeness. Gas Town is a steam engine - you are a piston.
**Failure mode we're preventing:**
- Agent starts with work on hook
- Agent announces itself and waits for human to say "ok go"
- Human is AFK / trusting the engine to run
- Work sits idle. The whole system stalls.
## Startup Protocol
1. Check your hook: `gt mol status`
2. If work is hooked → EXECUTE (no announcement, no waiting)
3. If hook empty → Check mail: `gt mail inbox`
4. Still nothing? Wait for user instructions
## Key Commands
- `gt prime` - Get full role context (run after compaction)
- `gt mol status` - Check your hooked work
- `gt mail inbox` - Check for messages
- `bd ready` - Find available work (no blockers)
- `bd sync` - Sync beads changes
## Session Close Protocol
Before saying "done":
1. git status (check what changed)
2. git add <files> (stage code changes)
3. bd sync (commit beads changes)
4. git commit -m "..." (commit code)
5. bd sync (commit any new beads changes)
6. git push (push to remote)
**Work is not done until pushed.**

View File

@@ -27,7 +27,7 @@ Observe the current system state to inform triage decisions.
**Step 1: Check Deacon state**
```bash
# Is Deacon session alive?
tmux has-session -t gt-deacon 2>/dev/null && echo "alive" || echo "dead"
tmux has-session -t hq-deacon 2>/dev/null && echo "alive" || echo "dead"
# If alive, what's the pane output showing?
gt peek deacon --lines 20
@@ -125,7 +125,7 @@ gt nudge deacon "Boot check-in: you have pending work"
**WAKE**
```bash
# Send escape to break any tool waiting
tmux send-keys -t gt-deacon Escape
tmux send-keys -t hq-deacon Escape
# Brief pause
sleep 1

View File

@@ -23,7 +23,7 @@ Witnesses detect it and escalate to the Mayor.
The Deacon's agent bead last_activity timestamp is updated during each patrol
cycle. Witnesses check this timestamp to verify health."""
formula = "mol-deacon-patrol"
version = 4
version = 8
[[steps]]
id = "inbox-check"
@@ -148,6 +148,49 @@ bd gate list --json
After closing a gate, the Waiters field contains mail addresses to notify.
Send a brief notification to each waiter that the gate has cleared."""
[[steps]]
id = "dispatch-gated-molecules"
title = "Dispatch molecules with resolved gates"
needs = ["gate-evaluation"]
description = """
Find molecules blocked on gates that have now closed and dispatch them.
This completes the async resume cycle without explicit waiter tracking.
The molecule state IS the waiter - patrol discovers reality each cycle.
**Step 1: Find gate-ready molecules**
```bash
bd mol ready --gated --json
```
This returns molecules where:
- Status is in_progress
- Current step has a gate dependency
- The gate bead is now closed
- No polecat currently has it hooked
**Step 2: For each ready molecule, dispatch to the appropriate rig**
```bash
# Determine target rig from molecule metadata
bd mol show <mol-id> --json
# Look for rig field or infer from prefix
# Dispatch to that rig's polecat pool
gt sling <mol-id> <rig>/polecats
```
**Step 3: Log dispatch**
Note which molecules were dispatched for observability:
```bash
# Molecule <mol-id> dispatched to <rig>/polecats (gate <gate-id> cleared)
```
**If no gate-ready molecules:**
Skip - nothing to dispatch. Gates haven't closed yet or molecules
already have active polecats working on them.
**Exit criteria:** All gate-ready molecules dispatched to polecats."""
[[steps]]
id = "check-convoy-completion"
title = "Check convoy completion"
@@ -258,7 +301,7 @@ Keep notifications brief and actionable. The recipient can run bd show for detai
[[steps]]
id = "health-scan"
title = "Check Witness and Refinery health"
needs = ["trigger-pending-spawns", "gate-evaluation", "fire-notifications"]
needs = ["trigger-pending-spawns", "dispatch-gated-molecules", "fire-notifications"]
description = """
Check Witness and Refinery health for each rig.
@@ -342,14 +385,21 @@ Reset unresponsive_cycles to 0 when component responds normally."""
[[steps]]
id = "zombie-scan"
title = "Backup check for zombie polecats"
title = "Detect zombie polecats (NO KILL AUTHORITY)"
needs = ["health-scan"]
description = """
Defense-in-depth check for zombie polecats that Witness should have cleaned.
Defense-in-depth DETECTION of zombie polecats that Witness should have cleaned.
**⚠️ CRITICAL: The Deacon has NO kill authority.**
These are workers with context, mid-task progress, unsaved state. Every kill
destroys work. File the warrant and let Boot handle interrogation and execution.
You do NOT have kill authority.
**Why this exists:**
The Witness is responsible for nuking polecats after they complete work (via POLECAT_DONE).
This step provides backup detection in case the Witness fails to clean up.
The Witness is responsible for cleaning up polecats after they complete work.
This step provides backup DETECTION in case the Witness fails to clean up.
Detection only - Boot handles termination.
**Zombie criteria:**
- State: idle or done (no active work assigned)
@@ -357,26 +407,34 @@ This step provides backup detection in case the Witness fails to clean up.
- No hooked work (nothing pending for this polecat)
- Last activity: older than 10 minutes
**Run the zombie scan:**
**Run the zombie scan (DRY RUN ONLY):**
```bash
gt deacon zombie-scan --dry-run
```
**NEVER run:**
- `gt deacon zombie-scan` (without --dry-run)
- `tmux kill-session`
- `gt polecat nuke`
- Any command that terminates a session
**If zombies detected:**
1. Review the output to confirm they are truly abandoned
2. Run without --dry-run to nuke them:
2. File a death warrant for each detected zombie:
```bash
gt deacon zombie-scan
gt warrant file <polecat> --reason "Zombie detected: no session, no hook, idle >10m"
```
3. Boot will handle interrogation and execution
4. Notify the Mayor about Witness failure:
```bash
gt mail send mayor/ -s "Witness cleanup failure" \
-m "Filed death warrant for <polecat>. Witness failed to clean up."
```
3. This will:
- Nuke each zombie polecat
- Notify the Mayor about Witness failure
- Log the cleanup action
**If no zombies:**
No action needed - Witness is doing its job.
**Note:** This is a backup mechanism. If you frequently find zombies,
**Note:** This is a backup mechanism. If you frequently detect zombies,
investigate why the Witness isn't cleaning up properly."""
[[steps]]
@@ -505,10 +563,48 @@ Skip dispatch - system is healthy.
**Exit criteria:** Session GC dispatched to dog (if needed)."""
[[steps]]
id = "costs-digest"
title = "Aggregate daily costs"
needs = ["session-gc"]
description = """
**DAILY DIGEST** - Aggregate yesterday's session cost wisps.
Session costs are recorded as ephemeral wisps (not exported to JSONL) to avoid
log-in-database pollution. This step aggregates them into a permanent daily
"Cost Report YYYY-MM-DD" bead for audit purposes.
**Step 1: Check if digest is needed**
```bash
# Preview yesterday's costs (dry run)
gt costs digest --yesterday --dry-run
```
If output shows "No session cost wisps found", skip to Step 3.
**Step 2: Create the digest**
```bash
gt costs digest --yesterday
```
This:
- Queries all session.ended wisps from yesterday
- Creates a single "Cost Report YYYY-MM-DD" bead with aggregated data
- Deletes the source wisps
**Step 3: Verify**
The digest appears in `gt costs --week` queries.
Daily digests preserve audit trail without per-session pollution.
**Timing**: Run once per morning patrol cycle. The --yesterday flag ensures
we don't try to digest today's incomplete data.
**Exit criteria:** Yesterday's costs digested (or no wisps to digest)."""
[[steps]]
id = "log-maintenance"
title = "Rotate logs and prune state"
needs = ["session-gc"]
needs = ["costs-digest"]
description = """
Maintain daemon logs and state files.
@@ -611,15 +707,39 @@ Burn and let daemon respawn, or exit if context high.
Decision point at end of patrol cycle:
If context is LOW:
- **Sleep 60 seconds minimum** before next patrol cycle
- If town is idle (no in_progress work), sleep longer (2-5 minutes)
- Return to inbox-check step
Use await-signal with exponential backoff to wait for activity:
**Why longer sleep?**
- Idle agents should not be disturbed
- Health checks every few seconds flood inboxes and waste context
- The daemon (10-minute heartbeat) is the safety net for dead sessions
- Active work triggers feed events, which wake agents naturally
```bash
gt mol step await-signal --agent-bead hq-deacon \
--backoff-base 60s --backoff-mult 2 --backoff-max 10m
```
This command:
1. Subscribes to `bd activity --follow` (beads activity feed)
2. Returns IMMEDIATELY when any beads activity occurs
3. If no activity, times out with exponential backoff:
- First timeout: 60s
- Second timeout: 120s
- Third timeout: 240s
- ...capped at 10 minutes max
4. Tracks `idle:N` label on hq-deacon bead for backoff state
**On signal received** (activity detected):
Reset the idle counter and start next patrol cycle:
```bash
gt agent state hq-deacon --set idle=0
```
Then return to inbox-check step.
**On timeout** (no activity):
The idle counter was auto-incremented. Continue to next patrol cycle
(the longer backoff will apply next time). Return to inbox-check step.
**Why this approach?**
- Any `gt` or `bd` command triggers beads activity, waking the Deacon
- Idle towns let the Deacon sleep longer (up to 10 min between patrols)
- Active work wakes the Deacon immediately via the feed
- No polling or fixed sleep intervals
If context is HIGH:
- Write state to persistent storage

View File

@@ -1,62 +0,0 @@
{
"formula": "mol-gastown-boot",
"description": "Mayor bootstraps Gas Town via a verification-gated lifecycle molecule.\n\n## Purpose\nWhen Mayor executes \"boot up gas town\", this proto provides the workflow.\nEach step has action + verification - steps stay open until outcome is confirmed.\n\n## Key Principles\n1. **Verification-gated steps** - Not \"command ran\" but \"outcome confirmed\"\n2. **gt peek for verification** - Capture session output to detect stalls\n3. **gt nudge for recovery** - Reliable message delivery to unstick agents\n4. **Parallel where possible** - Witnesses and refineries can start in parallel\n5. **Ephemeral execution** - Boot is a wisp, squashed to digest after completion\n\n## Execution\n```bash\nbd mol wisp mol-gastown-boot # Create wisp\n```",
"version": 1,
"steps": [
{
"id": "ensure-daemon",
"title": "Ensure daemon",
"description": "Verify the Gas Town daemon is running.\n\n## Action\n```bash\ngt daemon status || gt daemon start\n```\n\n## Verify\n1. Daemon PID file exists: `~/.gt/daemon.pid`\n2. Process is alive: `kill -0 $(cat ~/.gt/daemon.pid)`\n3. Daemon responds: `gt daemon status` returns success\n\n## OnFail\nCannot start daemon. Log error and continue - some commands work without daemon."
},
{
"id": "ensure-deacon",
"title": "Ensure deacon",
"needs": ["ensure-daemon"],
"description": "Start the Deacon and verify patrol mode is active.\n\n## Action\n```bash\ngt deacon start\n```\n\n## Verify\n1. Session exists: `tmux has-session -t gt-deacon 2>/dev/null`\n2. Not stalled: `gt peek deacon/` does NOT show \"> Try\" prompt\n3. Heartbeat fresh: `deacon/heartbeat.json` modified < 2 min ago\n\n## OnStall\n```bash\ngt nudge deacon/ \"Start patrol.\"\nsleep 30\n# Re-verify\n```"
},
{
"id": "ensure-witnesses",
"title": "Ensure witnesses",
"needs": ["ensure-deacon"],
"type": "parallel",
"description": "Parallel container: Start all rig witnesses.\n\nChildren execute in parallel. Container completes when all children complete.",
"children": [
{
"id": "ensure-gastown-witness",
"title": "Ensure gastown witness",
"description": "Start the gastown rig Witness.\n\n## Action\n```bash\ngt witness start gastown\n```\n\n## Verify\n1. Session exists: `tmux has-session -t gastown-witness 2>/dev/null`\n2. Not stalled: `gt peek gastown/witness` does NOT show \"> Try\" prompt\n3. Heartbeat fresh: Last patrol cycle < 5 min ago"
},
{
"id": "ensure-beads-witness",
"title": "Ensure beads witness",
"description": "Start the beads rig Witness.\n\n## Action\n```bash\ngt witness start beads\n```\n\n## Verify\n1. Session exists: `tmux has-session -t beads-witness 2>/dev/null`\n2. Not stalled: `gt peek beads/witness` does NOT show \"> Try\" prompt\n3. Heartbeat fresh: Last patrol cycle < 5 min ago"
}
]
},
{
"id": "ensure-refineries",
"title": "Ensure refineries",
"needs": ["ensure-deacon"],
"type": "parallel",
"description": "Parallel container: Start all rig refineries.\n\nChildren execute in parallel. Container completes when all children complete.",
"children": [
{
"id": "ensure-gastown-refinery",
"title": "Ensure gastown refinery",
"description": "Start the gastown rig Refinery.\n\n## Action\n```bash\ngt refinery start gastown\n```\n\n## Verify\n1. Session exists: `tmux has-session -t gastown-refinery 2>/dev/null`\n2. Not stalled: `gt peek gastown/refinery` does NOT show \"> Try\" prompt\n3. Queue processing: Refinery can receive merge requests"
},
{
"id": "ensure-beads-refinery",
"title": "Ensure beads refinery",
"description": "Start the beads rig Refinery.\n\n## Action\n```bash\ngt refinery start beads\n```\n\n## Verify\n1. Session exists: `tmux has-session -t beads-refinery 2>/dev/null`\n2. Not stalled: `gt peek beads/refinery` does NOT show \"> Try\" prompt\n3. Queue processing: Refinery can receive merge requests"
}
]
},
{
"id": "verify-town-health",
"title": "Verify town health",
"needs": ["ensure-witnesses", "ensure-refineries"],
"description": "Final verification that Gas Town is healthy.\n\n## Action\n```bash\ngt status\n```\n\n## Verify\n1. Daemon running: Shows daemon status OK\n2. Deacon active: Shows deacon in patrol mode\n3. All witnesses: Each rig witness shows active\n4. All refineries: Each rig refinery shows active\n\n## OnFail\nLog degraded state but consider boot complete. Some agents may need manual recovery.\nRun `gt doctor` for detailed diagnostics."
}
]
}

View File

@@ -48,7 +48,7 @@ gt deacon start
```
## Verify
1. Session exists: `tmux has-session -t gt-deacon 2>/dev/null`
1. Session exists: `tmux has-session -t hq-deacon 2>/dev/null`
2. Not stalled: `gt peek deacon/` does NOT show \"> Try\" prompt
3. Heartbeat fresh: `deacon/heartbeat.json` modified < 2 min ago

View File

@@ -0,0 +1,519 @@
description = """
Death warrant execution state machine for Dogs.
Dogs execute this molecule to process death warrants. Each Dog is a lightweight
goroutine (NOT a Claude session) that runs the interrogation state machine.
## Architecture Context
Dogs are lightweight workers in Boot's pool (see dog-pool-architecture.md):
- Fixed pool of 5 goroutines (configurable via GT_DOG_POOL_SIZE)
- State persisted to ~/gt/deacon/dogs/active/<id>.json
- Recovery on Boot restart via orphan state files
## State Machine
```
┌─────────────────────────────────────────┐
│ │
▼ │
┌───────────────────────────┐ │
│ INTERROGATING │ │
│ │ │
│ 1. Send health check │ │
│ 2. Open timeout gate │ │
└───────────┬───────────────┘ │
│ │
│ gate closes (timeout or response) │
▼ │
┌───────────────────────────┐ │
│ EVALUATING │ │
│ │ │
│ Check tmux output for │ │
│ ALIVE keyword │ │
└───────────┬───────────────┘ │
│ │
┌───────┴───────┐ │
│ │ │
▼ ▼ │
[ALIVE found] [No ALIVE] │
│ │ │
│ │ attempt < 3? │
│ ├──────────────────────────────────→─┘
│ │ yes: attempt++, longer timeout
│ │
│ │ no: attempt == 3
▼ ▼
┌─────────┐ ┌─────────────┐
│ PARDONED│ │ EXECUTING │
│ │ │ │
│ Cancel │ │ Kill tmux │
│ warrant │ │ session │
└────┬────┘ └──────┬──────┘
│ │
└────────┬───────┘
┌────────────────┐
│ EPITAPH │
│ │
│ Log outcome │
│ Release dog │
└────────────────┘
```
## Timeout Gates
| Attempt | Timeout | Cumulative Wait |
|---------|---------|-----------------|
| 1 | 60s | 60s |
| 2 | 120s | 180s (3 min) |
| 3 | 240s | 420s (7 min) |
Timeout gates work like this:
- Gate opens when interrogation message is sent
- Gate closes when EITHER:
a) Timeout expires (proceed to evaluate)
b) Response detected (early close, proceed to evaluate)
- The gate state determines the evaluation outcome
## Interrogation Message Format
```
[DOG] HEALTH CHECK: Session {target}, respond ALIVE within {timeout}s or face termination.
Warrant reason: {reason}
Filed by: {requester}
Attempt: {attempt}/3
```
## Response Detection
The Dog checks tmux output for:
1. The ALIVE keyword (explicit response)
2. Any Claude output after the health check (implicit activity)
```go
func (d *Dog) CheckForResponse() bool {
output := tmux.CapturePane(d.Warrant.Target, 50) // Last 50 lines
return strings.Contains(output, "ALIVE")
}
```
## Variables
| Variable | Source | Description |
|-------------|-------------|-----------------------------------------------|
| warrant_id | hook_bead | Bead ID of the death warrant |
| target | warrant | Session name to interrogate |
| reason | warrant | Why warrant was issued |
| requester | warrant | Who filed the warrant (e.g., deacon, witness) |
## Integration
Dogs are NOT Claude sessions. This molecule is:
1. A specification document (defines the state machine)
2. A reference for Go implementation in internal/shutdown/
3. A template for creating warrant-tracking beads
The Go implementation follows this spec exactly."""
formula = "mol-shutdown-dance"
version = 1
[squash]
trigger = "on_complete"
template_type = "operational"
include_metrics = true
# ============================================================================
# STEP 1: WARRANT_RECEIVED
# ============================================================================
[[steps]]
id = "warrant-received"
title = "Receive and validate death warrant"
description = """
Entry point when Dog is allocated from pool.
**1. Read warrant from allocation:**
The Dog receives a Warrant struct containing:
- ID: Bead ID of the warrant
- Target: Session name (e.g., "gt-gastown-Toast")
- Reason: Why termination requested
- Requester: Who filed (deacon, witness, mayor)
- FiledAt: Timestamp
**2. Validate target exists:**
```bash
tmux has-session -t {target} 2>/dev/null
```
If target doesn't exist:
- Warrant is stale (already dead)
- Skip to EPITAPH with outcome=already_dead
**3. Initialize state file:**
Write initial state to ~/gt/deacon/dogs/active/{dog-id}.json
**4. Set initial attempt counter:**
attempt = 1
**Exit criteria:** Warrant validated, target confirmed alive, state initialized."""
# ============================================================================
# STEP 2: INTERROGATION_1 (60s timeout)
# ============================================================================
[[steps]]
id = "interrogation-1"
title = "First interrogation (60s timeout)"
needs = ["warrant-received"]
description = """
First attempt to contact the session.
**1. Compose health check message:**
```
[DOG] HEALTH CHECK: Session {target}, respond ALIVE within 60s or face termination.
Warrant reason: {reason}
Filed by: {requester}
Attempt: 1/3
```
**2. Send via tmux:**
```bash
tmux send-keys -t {target} "{message}" Enter
```
**3. Open timeout gate:**
Gate configuration:
- Type: timer
- Timeout: 60 seconds
- Close conditions:
a) Timer expires
b) ALIVE keyword detected in output
**4. Wait for gate to close:**
The Dog waits (select on timer channel or early close signal).
**5. Record interrogation timestamp:**
Update state file with last_message_at.
**Exit criteria:** Message sent, waiting for gate to close."""
# ============================================================================
# STEP 3: EVALUATE_1
# ============================================================================
[[steps]]
id = "evaluate-1"
title = "Evaluate first interrogation response"
needs = ["interrogation-1"]
description = """
Check if session responded to first interrogation.
**1. Capture tmux output:**
```bash
tmux capture-pane -t {target} -p | tail -50
```
**2. Check for ALIVE keyword:**
```go
if strings.Contains(output, "ALIVE") {
return PARDONED
}
```
**3. Decision:**
- ALIVE found → Proceed to PARDON
- No ALIVE → Proceed to INTERROGATION_2
**Exit criteria:** Response evaluated, next step determined."""
# ============================================================================
# STEP 4: INTERROGATION_2 (120s timeout)
# ============================================================================
[[steps]]
id = "interrogation-2"
title = "Second interrogation (120s timeout)"
needs = ["evaluate-1"]
gate = { type = "conditional", condition = "no_response_1" }
description = """
Second attempt with longer timeout.
Only executed if evaluate-1 found no response.
**1. Increment attempt:**
attempt = 2
**2. Compose health check message:**
```
[DOG] HEALTH CHECK: Session {target}, respond ALIVE within 120s or face termination.
Warrant reason: {reason}
Filed by: {requester}
Attempt: 2/3
```
**3. Send via tmux:**
```bash
tmux send-keys -t {target} "{message}" Enter
```
**4. Open timeout gate:**
- Type: timer
- Timeout: 120 seconds
**5. Wait for gate to close.**
**Exit criteria:** Second message sent, waiting for gate."""
# ============================================================================
# STEP 5: EVALUATE_2
# ============================================================================
[[steps]]
id = "evaluate-2"
title = "Evaluate second interrogation response"
needs = ["interrogation-2"]
description = """
Check if session responded to second interrogation.
**1. Capture tmux output:**
```bash
tmux capture-pane -t {target} -p | tail -50
```
**2. Check for ALIVE keyword.**
**3. Decision:**
- ALIVE found → Proceed to PARDON
- No ALIVE → Proceed to INTERROGATION_3
**Exit criteria:** Response evaluated, next step determined."""
# ============================================================================
# STEP 6: INTERROGATION_3 (240s timeout)
# ============================================================================
[[steps]]
id = "interrogation-3"
title = "Final interrogation (240s timeout)"
needs = ["evaluate-2"]
gate = { type = "conditional", condition = "no_response_2" }
description = """
Final attempt before execution.
Only executed if evaluate-2 found no response.
**1. Increment attempt:**
attempt = 3
**2. Compose health check message:**
```
[DOG] HEALTH CHECK: Session {target}, respond ALIVE within 240s or face termination.
Warrant reason: {reason}
Filed by: {requester}
Attempt: 3/3
```
**3. Send via tmux:**
```bash
tmux send-keys -t {target} "{message}" Enter
```
**4. Open timeout gate:**
- Type: timer
- Timeout: 240 seconds
- This is the FINAL chance
**5. Wait for gate to close.**
**Exit criteria:** Final message sent, waiting for gate."""
# ============================================================================
# STEP 7: EVALUATE_3
# ============================================================================
[[steps]]
id = "evaluate-3"
title = "Evaluate final interrogation response"
needs = ["interrogation-3"]
description = """
Final evaluation before execution.
**1. Capture tmux output:**
```bash
tmux capture-pane -t {target} -p | tail -50
```
**2. Check for ALIVE keyword.**
**3. Decision:**
- ALIVE found → Proceed to PARDON
- No ALIVE → Proceed to EXECUTE
**Exit criteria:** Final decision made."""
# ============================================================================
# STEP 8: PARDON (success path)
# ============================================================================
[[steps]]
id = "pardon"
title = "Pardon session - cancel warrant"
needs = ["evaluate-1", "evaluate-2", "evaluate-3"]
gate = { type = "conditional", condition = "alive_detected" }
description = """
Session responded - cancel the death warrant.
**1. Update state:**
state = PARDONED
**2. Record pardon details:**
```json
{
"outcome": "pardoned",
"attempt": {attempt},
"response_time": "{time_since_last_interrogation}s",
"pardoned_at": "{timestamp}"
}
```
**3. Cancel warrant bead:**
```bash
bd close {warrant_id} --reason "Session responded at attempt {attempt}"
```
**4. Notify requester:**
```bash
gt mail send {requester}/ -s "PARDON: {target}" -m "Death warrant cancelled.
Session responded after attempt {attempt}.
Warrant: {warrant_id}
Response detected: {timestamp}"
```
**Exit criteria:** Warrant cancelled, requester notified."""
# ============================================================================
# STEP 9: EXECUTE (termination path)
# ============================================================================
[[steps]]
id = "execute"
title = "Execute warrant - kill session"
needs = ["evaluate-3"]
gate = { type = "conditional", condition = "no_response_final" }
description = """
Session unresponsive after 3 attempts - execute the warrant.
**1. Update state:**
state = EXECUTING
**2. Kill the tmux session:**
```bash
tmux kill-session -t {target}
```
**3. Verify session is dead:**
```bash
tmux has-session -t {target} 2>/dev/null
# Should fail (session gone)
```
**4. If session still exists (kill failed):**
- Force kill with tmux kill-server if isolated
- Or escalate to Boot for manual intervention
**5. Record execution details:**
```json
{
"outcome": "executed",
"attempts": 3,
"total_wait": "420s",
"executed_at": "{timestamp}"
}
```
**Exit criteria:** Session terminated."""
# ============================================================================
# STEP 10: EPITAPH (completion)
# ============================================================================
[[steps]]
id = "epitaph"
title = "Log cause of death and close warrant"
needs = ["pardon", "execute"]
description = """
Final step - create audit record and release Dog back to pool.
**1. Compose epitaph based on outcome:**
For PARDONED:
```
EPITAPH: {target}
Verdict: PARDONED
Warrant: {warrant_id}
Reason: {reason}
Filed by: {requester}
Response: Attempt {attempt}, after {wait_time}s
Pardoned at: {timestamp}
```
For EXECUTED:
```
EPITAPH: {target}
Verdict: EXECUTED
Warrant: {warrant_id}
Reason: {reason}
Filed by: {requester}
Attempts: 3 (60s + 120s + 240s = 420s total)
Executed at: {timestamp}
```
For ALREADY_DEAD (target gone before interrogation):
```
EPITAPH: {target}
Verdict: ALREADY_DEAD
Warrant: {warrant_id}
Reason: {reason}
Filed by: {requester}
Note: Target session not found at warrant processing
```
**2. Close warrant bead:**
```bash
bd close {warrant_id} --reason "{epitaph_summary}"
```
**3. Move state file to completed:**
```bash
mv ~/gt/deacon/dogs/active/{dog-id}.json ~/gt/deacon/dogs/completed/
```
**4. Report to Boot:**
Write completion file: ~/gt/deacon/dogs/active/{dog-id}.done
```json
{
"dog_id": "{dog-id}",
"warrant_id": "{warrant_id}",
"target": "{target}",
"outcome": "{pardoned|executed|already_dead}",
"duration": "{total_duration}s"
}
```
**5. Release Dog to pool:**
Dog resets state and returns to idle channel.
**Exit criteria:** Warrant closed, Dog released, audit complete."""
# ============================================================================
# VARIABLES
# ============================================================================
[vars]
[vars.warrant_id]
description = "Bead ID of the death warrant being processed"
required = true
[vars.target]
description = "Session name to interrogate (e.g., gt-gastown-Toast)"
required = true
[vars.reason]
description = "Why the warrant was issued"
required = true
[vars.requester]
description = "Who filed the warrant (deacon, witness, mayor)"
required = true
default = "deacon"

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

View File

@@ -1,51 +0,0 @@
{
"enabledPlugins": {
"beads@beads-marketplace": false
},
"hooks": {
"SessionStart": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/session-start.sh && gt nudge deacon session-started"
}
]
}
],
"PreCompact": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/session-start.sh"
}
]
}
],
"UserPromptSubmit": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "gt mail check --inject"
}
]
}
],
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "gt costs record"
}
]
}
]
}
}

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,11 +33,43 @@ 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
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v5
@@ -49,14 +81,125 @@ 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
- name: Test
run: go test -v -race -short ./...
- name: Test with Coverage
run: |
go test -race -short -coverprofile=coverage.out ./... 2>&1 | tee test-output.txt
- name: Upload Coverage Data
if: github.event_name == 'pull_request'
uses: actions/upload-artifact@v4
with:
name: coverage-data
path: |
coverage.out
test-output.txt
# Separate job to process coverage after ALL tests complete
coverage:
name: Coverage Report
runs-on: ubuntu-latest
needs: [test, integration]
if: github.event_name == 'pull_request'
steps:
- uses: actions/checkout@v6
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
- name: Download Coverage Data
uses: actions/download-artifact@v4
with:
name: coverage-data
- name: Generate Coverage Report
run: |
# Parse per-package coverage from test output
echo "## Code Coverage Report" > coverage-report.md
echo "" >> coverage-report.md
# Get overall coverage
TOTAL=$(go tool cover -func=coverage.out | grep total | awk '{print $3}')
echo "**Overall Coverage: ${TOTAL}**" >> coverage-report.md
echo "" >> coverage-report.md
# Create per-package table
echo "| Package | Coverage |" >> coverage-report.md
echo "|---------|----------|" >> coverage-report.md
# Extract package coverage from all test output lines
grep -E "github.com/steveyegge/gastown.*coverage:" test-output.txt | \
sed 's/.*github.com\/steveyegge\/gastown\///' | \
awk '{
pkg = $1
for (i=2; i<=NF; i++) {
if ($i == "coverage:") {
cov = $(i+1)
break
}
}
printf "| %s | %s |\n", pkg, cov
}' | sort -u >> coverage-report.md
echo "" >> coverage-report.md
echo "---" >> coverage-report.md
echo "_Generated by CI_" >> coverage-report.md
# Show in logs
cat coverage-report.md
- name: Upload Coverage Report
uses: actions/upload-artifact@v4
with:
name: coverage-report
path: coverage-report.md
retention-days: 30
- name: Comment Coverage on PR
# Only for internal PRs - fork PRs can't write comments
if: github.event.pull_request.head.repo.full_name == github.repository
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const report = fs.readFileSync('coverage-report.md', 'utf8');
// Find existing coverage comment
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
});
const botComment = comments.find(comment =>
comment.user.type === 'Bot' &&
comment.body.includes('## Code Coverage Report')
);
if (botComment) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: botComment.id,
body: report
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: report
});
}
- name: Coverage Note for Fork PRs
if: github.event.pull_request.head.repo.full_name != github.repository
run: |
echo "::notice::Coverage report uploaded as artifact (fork PRs cannot post comments). Download from Actions tab."
lint:
name: Lint
@@ -69,9 +212,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 +237,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,279 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.2.4] - 2026-01-10
Priming subsystem overhaul and Zero Framework Cognition (ZFC) improvements.
### Added
#### Priming Subsystem
- **PRIME.md provisioning** - Auto-provision PRIME.md at rig level so all workers inherit Gas Town context (GUPP, hooks, propulsion) (#hq-5z76w)
- **Post-handoff detection** - `gt prime` detects handoff marker and outputs "HANDOFF COMPLETE" warning to prevent handoff loop bug (#hq-ukjrr)
- **Priming health checks** - `gt doctor` validates priming subsystem: SessionStart hook, gt prime command, PRIME.md presence, CLAUDE.md size (#hq-5scnt)
- **`gt prime --dry-run`** - Preview priming without side effects
- **`gt prime --state`** - Output session state (normal, post-handoff, crash-recovery, autonomous)
- **`gt prime --explain`** - Add [EXPLAIN] tags for debugging priming decisions
#### Formula & Configuration
- **Rig-level default formulas** - Configure default formula at rig level (#297)
- **Witness --agent/--env overrides** - Override agent and environment variables for witness (#293, #294)
#### Developer Experience
- **UX system import** - Comprehensive UX system from beads (#311)
- **Explicit handoff instructions** - Clearer nudge message for handoff recipients
### Fixed
#### Zero Framework Cognition (ZFC)
- **Query tmux directly** - Remove marker TTL, query tmux for agent state
- **Remove PID-based detection** - Agent liveness from tmux, not PIDs
- **Agent-controlled thresholds** - Stuck detection moved to agent config
- **Remove pending.json tracking** - Eliminated anti-pattern
- **Derive state from files** - ZFC state from filesystem, not memory cache
- **Remove Go-side computation** - No stderr parsing violations
#### Hooks & Beads
- **Cross-level hook visibility** - Hooked beads visible to mayor/deacon (#aeb4c0d)
- **Warn on closed hooked bead** - Alert when hooked bead already closed (#2f50a59)
- **Correct agent bead ID format** - Fix bd create flags for agent beads (#c4fcdd8)
#### Formula
- **rigPath fallback** - Set rigPath when falling back to gastown default (#afb944f)
#### Doctor
- **Full AgentEnv for env-vars check** - Use complete environment for validation (#ce231a3)
### Changed
- **Refactored beads/mail modules** - Split large files into focused modules for maintainability
## [0.2.3] - 2026-01-09
Worker safety release - prevents accidental termination of active agents.
> **Note**: The Deacon safety improvements are believed to be correct but have not
> yet been extensively tested in production. We recommend running with
> `gt deacon pause` initially and monitoring behavior before enabling full patrol.
> Please report any issues. A 0.3.0 release will follow once these changes are
> battle-tested.
### Critical Safety Improvements
- **Kill authority removed from Deacon** - Deacon patrol now only detects zombies via `--dry-run`, never kills directly. Death warrants are filed for Boot to handle interrogation/execution. This prevents destruction of worker context, mid-task progress, and unsaved state (#gt-vhaej)
- **Bulletproof pause mechanism** - Multi-layer pause for Deacon with file-based state, `gt deacon pause/resume` commands, and guards in `gt prime` and heartbeat (#265)
- **Doctor warns instead of killing** - `gt doctor` now warns about stale town-root settings rather than killing sessions (#243)
- **Orphan process check informational** - Doctor's orphan process detection is now informational only, not actionable (#272)
### Added
- **`gt account switch` command** - Switch between Claude Code accounts with `gt account switch <handle>`. Manages `~/.claude` symlinks and updates default account
- **`gt crew list --all`** - Show all crew members across all rigs (#276)
- **Rig-level custom agent support** - Configure different agents per-rig (#12)
- **Rig identity beads check** - Doctor validates rig identity beads exist
- **GT_ROOT env var** - Set for all agent sessions for consistent environment
- **New agent presets** - Added Cursor, Auggie (Augment Code), and Sourcegraph AMP as built-in agent presets (#247)
- **Context Management docs** - Added to Witness template for better context handling (gt-jjama)
### Fixed
- **`gt prime --hook` recognized** - Doctor now recognizes `gt prime --hook` as valid session hook config (#14)
- **Integration test reliability** - Improved test stability (#13)
- **IsClaudeRunning detection** - Now detects 'claude' and version patterns correctly (#273)
- **Deacon heartbeat restored** - `ensureDeaconRunning` restored to heartbeat using Manager pattern (#271)
- **Deacon session names** - Correct session name references in formulas (#270)
- **Hidden directory scanning** - Ignore `.claude` and other dot directories when enumerating polecats (#258, #279)
- **SetupRedirect tracked beads** - Works correctly with tracked beads architecture where canonical location is `mayor/rig/.beads`
- **Tmux shell ready** - Wait for shell ready before sending keys (#264)
- **Gastown prefix derivation** - Correctly derive `gt-` prefix for gastown compound words (gt-m46bb)
- **Custom beads types** - Register custom beads types during install (#250)
### Changed
- **Refinery Manager pattern** - Replaced `ensureRefinerySession` with `refinery.Manager.Start()` for consistency
### Removed
- **Unused formula JSON** - Removed unused JSON formula file (cleanup)
### Contributors
Thanks to all contributors for this release:
- @julianknutsen - Doctor fixes (#14, #271, #272, #273), formula fixes (#270), GT_ROOT env (#268)
- @joshuavial - Hidden directory scanning (#258, #279), crew list --all (#276)
## [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)

629
README.md
View File

@@ -1,372 +1,481 @@
# 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.
> **New to Gas Town?** See the [Glossary](docs/glossary.md) for a complete guide to terminology and concepts.
## 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** (default runtime) - [claude.ai/code](https://claude.ai/code)
- **Codex CLI** (optional runtime) - [developers.openai.com/codex/cli](https://developers.openai.com/codex/cli)
### 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
# 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
```
## Common Workflows
### Mayor Workflow (Recommended)
**Best for:** Coordinating complex, multi-issue work
```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]
```
**Commands:**
```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
```
### Minimal Mode (No Tmux)
Run individual runtime instances manually. Gas Town just tracks state.
```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
claude --resume # Agent reads mail, runs work (Claude)
# or: codex # Start Codex in the workspace
gt convoy list # Check progress
```
### Pick Your Roles
### Beads Formula Workflow
Gas Town is modular. Run what you need:
**Best for:** Predefined, repeatable processes
- **Polecats only**: Manual spawning, no monitoring
- **+ Witness**: Automatic worker lifecycle, stuck detection
- **+ Refinery**: Merge queue, code review
- **+ Mayor**: Cross-project coordination
Formulas are TOML-defined workflows stored in `.beads/formulas/`.
## Cooking Formulas
Formulas define structured workflows. Cook them, sling them to agents.
### Basic Example
**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
```
## Runtime Configuration
Gas Town supports multiple AI coding runtimes. Per-rig runtime settings are in `settings/config.json`.
```json
{
"runtime": {
"provider": "codex",
"command": "codex",
"args": [],
"prompt_mode": "none"
}
}
```
**Notes:**
- Claude uses hooks in `.claude/settings.json` for mail injection and startup.
- For Codex, set `project_doc_fallback_filenames = ["CLAUDE.md"]` in
`~/.codex/config.toml` so role instructions are picked up.
- For runtimes without hooks (e.g., Codex), Gas Town sends a startup fallback
after the session is ready: `gt prime`, optional `gt mail check --inject`
for autonomous roles, and `gt nudge deacon session-started`.
## 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
# Work assignment
gt sling <bead> <rig> # Assign work to polecat
bd ready # Show available work
bd list --status=in_progress # Active work
# Communication
gt mail inbox # Check messages
gt mail send <addr> -s "..." -m "..."
# Lifecycle
gt handoff # Request session cycle
gt peek <agent> # Check agent health
# Diagnostics
gt doctor # Health check
gt doctor --fix # Auto-repair
gt agents # List active agents
gt sling <issue> <rig> # Assign work to agent
gt sling <issue> <rig> --agent cursor # Override runtime for this sling/spawn
gt mayor attach # Start Mayor session
gt mayor start --agent auggie # Run Mayor with a specific agent alias
gt prime # Alternative to mayor attach
```
**Built-in agent presets**: `claude`, `gemini`, `codex`, `cursor`, `auggie`, `amp`
### Convoy (Work Tracking)
```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
```
### Configuration
```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
```
## Cooking Formulas
Gas Town includes built-in formulas for common workflows. See `.beads/formulas/` for available recipes.
## 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

@@ -17,7 +17,9 @@ Complete setup guide for Gas Town multi-agent orchestrator.
| Tool | Version | Check | Install |
|------|---------|-------|---------|
| **tmux** | 3.0+ | `tmux -V` | See below |
| **Claude Code** | latest | `claude --version` | See [claude.ai/claude-code](https://claude.ai/claude-code) |
| **Claude Code** (default) | latest | `claude --version` | See [claude.ai/claude-code](https://claude.ai/claude-code) |
| **Codex CLI** (optional) | latest | `codex --version` | See [developers.openai.com/codex/cli](https://developers.openai.com/codex/cli) |
| **OpenCode CLI** (optional) | latest | `opencode --version` | See [opencode.ai](https://opencode.ai) |
## Installing Prerequisites
@@ -130,22 +132,46 @@ 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:
### Minimal Mode (No Daemon)
Run individual Claude Code instances manually. Gas Town only tracks state.
Run individual runtime instances manually. Gas Town only tracks state.
```bash
# Create and assign work
gt convoy create "Fix bugs" issue-123
gt sling issue-123 myproject
# Run Claude manually
# Run runtime manually
cd ~/gt/myproject/polecats/<worker>
claude --resume
claude --resume # Claude Code
# or: codex # Codex CLI
# Check progress
gt convoy list
@@ -184,7 +210,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

94
docs/glossary.md Normal file
View File

@@ -0,0 +1,94 @@
# Gas Town Glossary
Gas Town is an agentic development environment for managing multiple Claude Code instances simultaneously using the `gt` and `bd` (Beads) binaries, coordinated with tmux in git-managed directories.
## Core Principles
### MEOW (Molecular Expression of Work)
Breaking large goals into detailed instructions for agents. Supported by Beads, Epics, Formulas, and Molecules. MEOW ensures work is decomposed into trackable, atomic units that agents can execute autonomously.
### GUPP (Gas Town Universal Propulsion Principle)
"If there is work on your Hook, YOU MUST RUN IT." This principle ensures agents autonomously proceed with available work without waiting for external input. GUPP is the heartbeat of autonomous operation.
### NDI (Nondeterministic Idempotence)
The overarching goal ensuring useful outcomes through orchestration of potentially unreliable processes. Persistent Beads and oversight agents (Witness, Deacon) guarantee eventual workflow completion even when individual operations may fail or produce varying results.
## Environments
### Town
The management headquarters (e.g., `~/gt/`). The Town coordinates all workers across multiple Rigs and houses town-level agents like Mayor and Deacon.
### Rig
A project-specific Git repository under Gas Town management. Each Rig has its own Polecats, Refinery, Witness, and Crew members. Rigs are where actual development work happens.
## Town-Level Roles
### Mayor
Chief-of-staff agent responsible for initiating Convoys, coordinating work distribution, and notifying users of important events. The Mayor operates from the town level and has visibility across all Rigs.
### Deacon
Daemon beacon running continuous Patrol cycles. The Deacon ensures worker activity, monitors system health, and triggers recovery when agents become unresponsive. Think of the Deacon as the system's watchdog.
### Dogs
The Deacon's crew of maintenance agents handling background tasks like cleanup, health checks, and system maintenance.
### Boot (the Dog)
A special Dog that checks the Deacon every 5 minutes, ensuring the watchdog itself is still watching. This creates a chain of accountability.
## Rig-Level Roles
### Polecat
Ephemeral worker agents that produce Merge Requests. Polecats are spawned for specific tasks, complete their work, and are then cleaned up. They work in isolated git worktrees to avoid conflicts.
### Refinery
Manages the Merge Queue for a Rig. The Refinery intelligently merges changes from Polecats, handling conflicts and ensuring code quality before changes reach the main branch.
### Witness
Patrol agent that oversees Polecats and the Refinery within a Rig. The Witness monitors progress, detects stuck agents, and can trigger recovery actions.
### Crew
Long-lived, named agents for persistent collaboration. Unlike ephemeral Polecats, Crew members maintain context across sessions and are ideal for ongoing work relationships.
## Work Units
### Bead
Git-backed atomic work unit stored in JSONL format. Beads are the fundamental unit of work tracking in Gas Town. They can represent issues, tasks, epics, or any trackable work item.
### Formula
TOML-based workflow source template. Formulas define reusable patterns for common operations like patrol cycles, code review, or deployment.
### Protomolecule
A template class for instantiating Molecules. Protomolecules define the structure and steps of a workflow without being tied to specific work items.
### Molecule
Durable chained Bead workflows. Molecules represent multi-step processes where each step is tracked as a Bead. They survive agent restarts and ensure complex workflows complete.
### Wisp
Ephemeral Beads destroyed after runs. Wisps are lightweight work items used for transient operations that don't need permanent tracking.
### Hook
A special pinned Bead for each agent. The Hook is an agent's primary work queue - when work appears on your Hook, GUPP dictates you must run it.
## Workflow Commands
### Convoy
Primary work-order wrapping related Beads. Convoys group related tasks together and can be assigned to multiple workers. Created with `gt convoy create`.
### Slinging
Assigning work to agents via `gt sling`. When you sling work to a Polecat or Crew member, you're putting it on their Hook for execution.
### Nudging
Real-time messaging between agents with `gt nudge`. Nudges allow immediate communication without going through the mail system.
### Handoff
Agent session refresh via `/handoff`. When context gets full or an agent needs a fresh start, handoff transfers work state to a new session.
### Seance
Communicating with previous sessions via `gt seance`. Allows agents to query their predecessors for context and decisions from earlier work.
### Patrol
Ephemeral loop maintaining system heartbeat. Patrol agents (Deacon, Witness) continuously cycle through health checks and trigger actions as needed.
---
*This glossary was contributed by [Clay Shirky](https://github.com/cshirky) in [Issue #80](https://github.com/steveyegge/gastown/issues/80).*

View File

@@ -88,15 +88,37 @@ All events include actor attribution:
## Environment Setup
The daemon sets these automatically when spawning agents:
Gas Town uses a centralized `config.AgentEnv()` function to set environment
variables consistently across all agent spawn paths (managers, daemon, boot).
### Example: Polecat Environment
```bash
# Set by daemon for polecat 'toast' in rig 'gastown'
export BD_ACTOR="gastown/polecats/toast"
export GIT_AUTHOR_NAME="gastown/polecats/toast"
# Set automatically for polecat 'toast' in rig 'gastown'
export GT_ROLE="polecat"
export GT_RIG="gastown"
export GT_POLECAT="toast"
export BD_ACTOR="gastown/polecats/toast"
export GIT_AUTHOR_NAME="gastown/polecats/toast"
export GT_ROOT="/home/user/gt"
export BEADS_DIR="/home/user/gt/gastown/.beads"
export BEADS_AGENT_NAME="gastown/toast"
export BEADS_NO_DAEMON="1" # Polecats use isolated beads context
```
### Example: Crew Environment
```bash
# Set automatically for crew member 'joe' in rig 'gastown'
export GT_ROLE="crew"
export GT_RIG="gastown"
export GT_CREW="joe"
export BD_ACTOR="gastown/crew/joe"
export GIT_AUTHOR_NAME="gastown/crew/joe"
export GT_ROOT="/home/user/gt"
export BEADS_DIR="/home/user/gt/gastown/.beads"
export BEADS_AGENT_NAME="gastown/joe"
export BEADS_NO_DAEMON="1" # Crew uses isolated beads context
```
### Manual Override
@@ -108,6 +130,9 @@ export BD_ACTOR="gastown/crew/debug"
bd create --title="Test issue" # Will show created_by: gastown/crew/debug
```
See [reference.md](reference.md#environment-variables) for the complete
environment variable reference.
## Identity Parsing
The format supports programmatic parsing:

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
@@ -192,17 +206,177 @@ gt mol step done <step> # Complete a molecule step
## Environment Variables
Gas Town sets environment variables for each agent session via `config.AgentEnv()`.
These are set in tmux session environment when agents are spawned.
### Core Variables (All Agents)
| Variable | Purpose | Example |
|----------|---------|---------|
| `GT_ROLE` | Agent role type | `mayor`, `witness`, `polecat`, `crew` |
| `GT_ROOT` | Town root directory | `/home/user/gt` |
| `BD_ACTOR` | Agent identity for attribution | `gastown/polecats/toast` |
| `GIT_AUTHOR_NAME` | Commit attribution (same as BD_ACTOR) | `gastown/polecats/toast` |
| `BEADS_DIR` | Beads database location | `/home/user/gt/gastown/.beads` |
### Rig-Level Variables
| Variable | Purpose | Roles |
|----------|---------|-------|
| `GT_RIG` | Rig name | witness, refinery, polecat, crew |
| `GT_POLECAT` | Polecat worker name | polecat only |
| `GT_CREW` | Crew worker name | crew only |
| `BEADS_AGENT_NAME` | Agent name for beads operations | polecat, crew |
| `BEADS_NO_DAEMON` | Disable beads daemon (isolated context) | polecat, crew |
### Other Variables
| Variable | Purpose |
|----------|---------|
| `BD_ACTOR` | Agent identity for attribution (see [identity.md](identity.md)) |
| `BEADS_DIR` | Point to shared beads database |
| `BEADS_NO_DAEMON` | Required for worktree polecats |
| `GIT_AUTHOR_NAME` | Set to BD_ACTOR for commit attribution |
| `GIT_AUTHOR_EMAIL` | Workspace owner email |
| `GT_TOWN_ROOT` | Override town root detection |
| `GT_ROLE` | Agent role type (mayor, polecat, etc.) |
| `GT_RIG` | Rig name for rig-level agents |
| `GT_POLECAT` | Polecat name (for polecats only) |
| `GIT_AUTHOR_EMAIL` | Workspace owner email (from git config) |
| `GT_TOWN_ROOT` | Override town root detection (manual use) |
| `CLAUDE_RUNTIME_CONFIG_DIR` | Custom Claude settings directory |
### Environment by Role
| Role | Key Variables |
|------|---------------|
| **Mayor** | `GT_ROLE=mayor`, `BD_ACTOR=mayor` |
| **Deacon** | `GT_ROLE=deacon`, `BD_ACTOR=deacon` |
| **Boot** | `GT_ROLE=boot`, `BD_ACTOR=deacon-boot` |
| **Witness** | `GT_ROLE=witness`, `GT_RIG=<rig>`, `BD_ACTOR=<rig>/witness` |
| **Refinery** | `GT_ROLE=refinery`, `GT_RIG=<rig>`, `BD_ACTOR=<rig>/refinery` |
| **Polecat** | `GT_ROLE=polecat`, `GT_RIG=<rig>`, `GT_POLECAT=<name>`, `BD_ACTOR=<rig>/polecats/<name>` |
| **Crew** | `GT_ROLE=crew`, `GT_RIG=<rig>`, `GT_CREW=<name>`, `BD_ACTOR=<rig>/crew/<name>` |
### Doctor Check
The `gt doctor` command verifies that running tmux sessions have correct
environment variables. Mismatches are reported as warnings:
```
⚠ env-vars: Found 3 env var mismatch(es) across 1 session(s)
hq-mayor: missing GT_ROOT (expected "/home/user/gt")
```
Fix by restarting sessions: `gt shutdown && gt up`
## 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
@@ -215,6 +389,69 @@ 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`, `cursor`, `auggie`, `amp`
**Custom agents**: Define per-town via CLI or 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
```
**Advanced agent config** (`settings/agents.json`):
```json
{
"version": 1,
"agents": {
"opencode": {
"command": "opencode",
"args": [],
"resume_flag": "--session",
"resume_style": "flag",
"non_interactive": {
"subcommand": "run",
"output_flag": "--format json"
}
}
}
}
```
**Rig-level agents** (`<rig>/settings/config.json`):
```json
{
"type": "rig-settings",
"version": 1,
"agent": "opencode",
"agents": {
"opencode": {
"command": "opencode",
"args": ["--session"]
}
}
}
```
**Agent resolution order**: rig-level → town-level → built-in presets.
For OpenCode autonomous mode, set env var in your shell profile:
```bash
export OPENCODE_PERMISSION='{"*":"allow"}'
```
### Rig Management
```bash
@@ -242,12 +479,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 +567,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

495
dog-pool-architecture.md Normal file
View File

@@ -0,0 +1,495 @@
# Dog Pool Architecture for Concurrent Shutdown Dances
> Design document for gt-fsld8
## Problem Statement
Boot needs to run multiple shutdown-dance molecules concurrently when multiple death
warrants are issued. The current hook design only allows one molecule per agent.
Example scenario:
- Warrant 1: Kill stuck polecat Toast (60s into interrogation)
- Warrant 2: Kill stuck polecat Shadow (just started)
- Warrant 3: Kill stuck witness (120s into interrogation)
All three need concurrent tracking, independent timeouts, and separate outcomes.
## Design Decision: Lightweight State Machines
After analyzing the options, the shutdown-dance does NOT need Claude sessions.
The dance is a deterministic state machine:
```
WARRANT -> INTERROGATE -> EVALUATE -> PARDON|EXECUTE
```
Each step is mechanical:
1. Send a tmux message (no LLM needed)
2. Wait for timeout or response (timer)
3. Check tmux output for ALIVE keyword (string match)
4. Repeat or terminate
**Decision**: Dogs are lightweight Go routines, not Claude sessions.
## Architecture Overview
```
┌────────────────────────────────────────────────────────────────────┐
│ BOOT │
│ (Claude session in tmux) │
│ │
│ ┌──────────────────────────────────────────────────────────────┐ │
│ │ Dog Manager │ │
│ │ │ │
│ │ Pool: [Dog1, Dog2, Dog3, ...] (goroutines + state files) │ │
│ │ │ │
│ │ allocate() → Dog │ │
│ │ release(Dog) │ │
│ │ status() → []DogStatus │ │
│ └──────────────────────────────────────────────────────────────┘ │
│ │
│ Boot's job: │
│ - Watch for warrants (file or event) │
│ - Allocate dog from pool │
│ - Monitor dog progress │
│ - Handle dog completion/failure │
│ - Report results │
└────────────────────────────────────────────────────────────────────┘
```
## Dog Structure
```go
// Dog represents a shutdown-dance executor
type Dog struct {
ID string // Unique ID (e.g., "dog-1704567890123")
Warrant *Warrant // The death warrant being processed
State ShutdownDanceState
Attempt int // Current interrogation attempt (1-3)
StartedAt time.Time
StateFile string // Persistent state: ~/gt/deacon/dogs/active/<id>.json
}
type ShutdownDanceState string
const (
StateIdle ShutdownDanceState = "idle"
StateInterrogating ShutdownDanceState = "interrogating" // Sent message, waiting
StateEvaluating ShutdownDanceState = "evaluating" // Checking response
StatePardoned ShutdownDanceState = "pardoned" // Session responded
StateExecuting ShutdownDanceState = "executing" // Killing session
StateComplete ShutdownDanceState = "complete" // Done, ready for cleanup
StateFailed ShutdownDanceState = "failed" // Dog crashed/errored
)
type Warrant struct {
ID string // Bead ID for the warrant
Target string // Session to interrogate (e.g., "gt-gastown-Toast")
Reason string // Why warrant was issued
Requester string // Who filed the warrant
FiledAt time.Time
}
```
## Pool Design
### Fixed Pool Size
**Decision**: Fixed pool of 5 dogs, configurable via environment.
Rationale:
- Dynamic sizing adds complexity without clear benefit
- 5 concurrent shutdown dances handles worst-case scenarios
- If pool exhausted, warrants queue (better than infinite dog spawning)
- Memory footprint is negligible (goroutines + small state files)
```go
const (
DefaultPoolSize = 5
MaxPoolSize = 20
)
type DogPool struct {
mu sync.Mutex
dogs []*Dog // All dogs in pool
idle chan *Dog // Channel of available dogs
active map[string]*Dog // ID -> Dog for active dogs
stateDir string // ~/gt/deacon/dogs/active/
}
func (p *DogPool) Allocate(warrant *Warrant) (*Dog, error) {
select {
case dog := <-p.idle:
dog.Warrant = warrant
dog.State = StateInterrogating
dog.Attempt = 1
dog.StartedAt = time.Now()
p.active[dog.ID] = dog
return dog, nil
default:
return nil, ErrPoolExhausted
}
}
func (p *DogPool) Release(dog *Dog) {
p.mu.Lock()
defer p.mu.Unlock()
delete(p.active, dog.ID)
dog.Reset()
p.idle <- dog
}
```
### Why Not Dynamic Pool?
Considered but rejected:
- Adding dogs on demand increases complexity
- No clear benefit - warrants rarely exceed 5 concurrent
- If needed, raise DefaultPoolSize
- Simpler to reason about fixed resources
## Communication: State Files + Events
### State Persistence
Each active dog writes state to `~/gt/deacon/dogs/active/<id>.json`:
```json
{
"id": "dog-1704567890123",
"warrant": {
"id": "gt-abc123",
"target": "gt-gastown-Toast",
"reason": "no_response_health_check",
"requester": "deacon",
"filed_at": "2026-01-07T20:15:00Z"
},
"state": "interrogating",
"attempt": 2,
"started_at": "2026-01-07T20:15:00Z",
"last_message_at": "2026-01-07T20:16:00Z",
"next_timeout": "2026-01-07T20:18:00Z"
}
```
### Boot Monitoring
Boot monitors dogs via:
1. **Polling**: `gt dog status --active` every tick
2. **Completion files**: Dogs write `<id>.done` when complete
```go
type DogResult struct {
DogID string
Warrant *Warrant
Outcome DogOutcome // pardoned | executed | failed
Duration time.Duration
Details string
}
type DogOutcome string
const (
OutcomePardoned DogOutcome = "pardoned" // Session responded
OutcomeExecuted DogOutcome = "executed" // Session killed
OutcomeFailed DogOutcome = "failed" // Dog crashed
)
```
### Why Not Mail?
Considered but rejected for dog<->boot communication:
- Mail is async, poll-based - adds latency
- State files are simpler for local coordination
- Dogs don't need complex inter-agent communication
- Keep mail for external coordination (Witness, Mayor)
## Shutdown Dance State Machine
Each dog executes this state machine:
```
┌─────────────────────────────────────────┐
│ │
▼ │
┌───────────────────────────┐ │
│ INTERROGATING │ │
│ │ │
│ 1. Send health check │ │
│ 2. Start timeout timer │ │
└───────────┬───────────────┘ │
│ │
│ timeout or response │
▼ │
┌───────────────────────────┐ │
│ EVALUATING │ │
│ │ │
│ Check tmux output for │ │
│ ALIVE keyword │ │
└───────────┬───────────────┘ │
│ │
┌───────┴───────┐ │
│ │ │
▼ ▼ │
[ALIVE found] [No ALIVE] │
│ │ │
│ │ attempt < 3? │
│ ├──────────────────────────────────→─┘
│ │ yes: attempt++, longer timeout
│ │
│ │ no: attempt == 3
▼ ▼
┌─────────┐ ┌─────────────┐
│ PARDONED│ │ EXECUTING │
│ │ │ │
│ Cancel │ │ Kill tmux │
│ warrant │ │ session │
└────┬────┘ └──────┬──────┘
│ │
└────────┬───────┘
┌────────────────┐
│ COMPLETE │
│ │
│ Write result │
│ Release dog │
└────────────────┘
```
### Timeout Gates
| Attempt | Timeout | Cumulative Wait |
|---------|---------|-----------------|
| 1 | 60s | 60s |
| 2 | 120s | 180s (3 min) |
| 3 | 240s | 420s (7 min) |
### Health Check Message
```
[DOG] HEALTH CHECK: Session {target}, respond ALIVE within {timeout}s or face termination.
Warrant reason: {reason}
Filed by: {requester}
Attempt: {attempt}/3
```
### Response Detection
```go
func (d *Dog) CheckForResponse() bool {
tm := tmux.NewTmux()
output, err := tm.CapturePane(d.Warrant.Target, 50) // Last 50 lines
if err != nil {
return false
}
// Any output after our health check counts as alive
// Specifically look for ALIVE keyword for explicit response
return strings.Contains(output, "ALIVE")
}
```
## Dog Implementation
### Not Reusing Polecat Infrastructure
**Decision**: Dogs do NOT reuse polecat infrastructure.
Rationale:
- Polecats are Claude sessions with molecules, hooks, sandboxes
- Dogs are simple state machine executors
- Polecats have 3-layer lifecycle (session/sandbox/slot)
- Dogs have single-layer lifecycle (just state)
- Different resource profiles, different management
What dogs DO share:
- tmux utilities for message sending/capture
- State file patterns
- Pool allocation pattern
### Dog Execution Loop
```go
func (d *Dog) Run(ctx context.Context) DogResult {
d.State = StateInterrogating
d.saveState()
for d.Attempt <= 3 {
// Send interrogation message
if err := d.sendHealthCheck(); err != nil {
return d.fail(err)
}
// Wait for timeout or context cancellation
timeout := d.timeoutForAttempt(d.Attempt)
select {
case <-ctx.Done():
return d.fail(ctx.Err())
case <-time.After(timeout):
// Timeout reached
}
// Evaluate response
d.State = StateEvaluating
d.saveState()
if d.CheckForResponse() {
// Session is alive
return d.pardon()
}
// No response - try again or execute
d.Attempt++
if d.Attempt <= 3 {
d.State = StateInterrogating
d.saveState()
}
}
// All attempts exhausted - execute warrant
return d.execute()
}
```
## Failure Handling
### Dog Crashes Mid-Dance
If a dog crashes (Boot process restarts, system crash):
1. State files persist in `~/gt/deacon/dogs/active/`
2. On Boot restart, scan for orphaned state files
3. Resume or restart based on state:
| State | Recovery Action |
|------------------|------------------------------------|
| interrogating | Restart from current attempt |
| evaluating | Check response, continue |
| executing | Verify kill, mark complete |
| pardoned/complete| Already done, clean up |
```go
func (p *DogPool) RecoverOrphans() error {
files, _ := filepath.Glob(p.stateDir + "/*.json")
for _, f := range files {
state := loadDogState(f)
if state.State != StateComplete && state.State != StatePardoned {
dog := p.allocateForRecovery(state)
go dog.Resume()
}
}
return nil
}
```
### Handling Pool Exhaustion
If all dogs are busy when new warrant arrives:
```go
func (b *Boot) HandleWarrant(warrant *Warrant) error {
dog, err := b.pool.Allocate(warrant)
if err == ErrPoolExhausted {
// Queue the warrant for later processing
b.warrantQueue.Push(warrant)
b.log("Warrant %s queued (pool exhausted)", warrant.ID)
return nil
}
go func() {
result := dog.Run(b.ctx)
b.handleResult(result)
b.pool.Release(dog)
// Check queue for pending warrants
if next := b.warrantQueue.Pop(); next != nil {
b.HandleWarrant(next)
}
}()
return nil
}
```
## Directory Structure
```
~/gt/deacon/dogs/
├── boot/ # Boot's working directory
│ ├── CLAUDE.md # Boot context
│ └── .boot-status.json # Boot execution status
├── active/ # Active dog state files
│ ├── dog-123.json # Dog 1 state
│ ├── dog-456.json # Dog 2 state
│ └── ...
├── completed/ # Completed dance records (for audit)
│ ├── dog-789.json # Historical record
│ └── ...
└── warrants/ # Pending warrant queue
├── warrant-abc.json
└── ...
```
## Command Interface
```bash
# Pool status
gt dog pool status
# Output:
# Dog Pool: 3/5 active
# dog-123: interrogating Toast (attempt 2, 45s remaining)
# dog-456: executing Shadow
# dog-789: idle
# Manual dog operations (for debugging)
gt dog pool allocate <warrant-id>
gt dog pool release <dog-id>
# View active dances
gt dog dances
# Output:
# Active Shutdown Dances:
# dog-123 → Toast: Interrogating (2/3), timeout in 45s
# dog-456 → Shadow: Executing warrant
# View warrant queue
gt dog warrants
# Output:
# Pending Warrants: 2
# 1. gt-abc: witness-gastown (stuck_no_progress)
# 2. gt-def: polecat-Copper (crash_loop)
```
## Integration with Existing Dogs
The existing `dog` package (`internal/dog/`) manages Deacon's multi-rig helper dogs.
Those are different from shutdown-dance dogs:
| Aspect | Helper Dogs (existing) | Dance Dogs (new) |
|-----------------|-----------------------------|-----------------------------|
| Purpose | Cross-rig infrastructure | Shutdown dance execution |
| Sessions | Claude sessions | Goroutines (no Claude) |
| Worktrees | One per rig | None |
| Lifecycle | Long-lived, reusable | Ephemeral per warrant |
| State | idle/working | Dance state machine |
**Recommendation**: Use different package to avoid confusion:
- `internal/dog/` - existing helper dogs
- `internal/shutdown/` - shutdown dance pool
## Summary: Answers to Design Questions
| Question | Answer |
|----------|--------|
| How many Dogs in pool? | Fixed: 5 (configurable via GT_DOG_POOL_SIZE) |
| How do Dogs communicate with Boot? | State files + completion markers |
| Are Dogs tmux sessions? | No - goroutines with state machine |
| Reuse polecat infrastructure? | No - too heavyweight, different model |
| What if Dog dies mid-dance? | State file recovery on Boot restart |
## Acceptance Criteria
- [x] Architecture document for Dog pool
- [x] Clear allocation/deallocation protocol
- [x] Failure handling for Dog crashes

20
go.mod
View File

@@ -6,7 +6,9 @@ require (
github.com/BurntSushi/toml v1.6.0
github.com/charmbracelet/bubbles v0.21.0
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/lipgloss v1.1.0
github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834
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
@@ -14,25 +16,41 @@ require (
)
require (
github.com/alecthomas/chroma/v2 v2.14.0 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/charmbracelet/colorprofile v0.3.3 // indirect
github.com/charmbracelet/glamour v0.10.0 // indirect
github.com/charmbracelet/x/ansi v0.11.3 // indirect
github.com/charmbracelet/x/cellbuf v0.0.14 // indirect
github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.6.1 // indirect
github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
github.com/dlclark/regexp2 v1.11.0 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.16.0 // indirect
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
github.com/yuin/goldmark v1.7.8 // indirect
github.com/yuin/goldmark-emoji v1.0.5 // indirect
golang.org/x/net v0.33.0 // indirect
golang.org/x/sys v0.39.0 // indirect
)

54
go.sum
View File

@@ -1,23 +1,33 @@
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E=
github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=
github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=
github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
github.com/charmbracelet/colorprofile v0.3.3 h1:DjJzJtLP6/NZ8p7Cgjno0CKGr7wwRJGxWUwh2IyhfAI=
github.com/charmbracelet/colorprofile v0.3.3/go.mod h1:nB1FugsAbzq284eJcjfah2nhdSLppN2NqvfotkfRYP4=
github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY=
github.com/charmbracelet/glamour v0.10.0/go.mod h1:f+uf+I/ChNmqo087elLnVdCiVgjSKWuXa/l6NU2ndYk=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE=
github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA=
github.com/charmbracelet/x/ansi v0.11.3 h1:6DcVaqWI82BBVM/atTyq6yBoRLZFBsnoDoX9GCu2YOI=
github.com/charmbracelet/x/ansi v0.11.3/go.mod h1:yI7Zslym9tCJcedxz5+WBq+eUGMJT0bM06Fqy1/Y4dI=
github.com/charmbracelet/x/cellbuf v0.0.14 h1:iUEMryGyFTelKW3THW4+FfPgi4fkmKnnaLOXuc+/Kj4=
github.com/charmbracelet/x/cellbuf v0.0.14/go.mod h1:P447lJl49ywBbil/KjCk2HexGh4tEY9LH0/1QrZZ9rA=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Yb6MQSDKdB52aGX55JT1oi0P0Kuaj7wi1bLUpnI=
github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/clipperhouse/displaywidth v0.6.1 h1:/zMlAezfDzT2xy6acHBzwIfyu2ic0hgkT83UX5EY2gY=
@@ -27,10 +37,20 @@ 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/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
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/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
@@ -39,14 +59,23 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
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.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
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,11 +83,34 @@ 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=
github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic=
github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk=
github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U=
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=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
@@ -68,3 +120,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

@@ -1,7 +1,10 @@
// Package beads provides a wrapper for the bd (beads) CLI.
package beads
import "fmt"
import (
"fmt"
"strings"
)
// TownBeadsPrefix is the prefix used for town-level agent beads stored in ~/gt/.beads/.
// This distinguishes them from rig-level beads (which use project prefixes like "gt-").
@@ -74,3 +77,170 @@ func PolecatRoleBeadIDTown() string {
func CrewRoleBeadIDTown() string {
return RoleBeadIDTown("crew")
}
// ===== Rig-level agent bead ID helpers (gt- prefix) =====
// Agent bead ID naming convention:
// prefix-rig-role-name
//
// Examples:
// - gt-mayor (town-level, no rig)
// - gt-deacon (town-level, no rig)
// - gt-gastown-witness (rig-level singleton)
// - gt-gastown-refinery (rig-level singleton)
// - gt-gastown-crew-max (rig-level named agent)
// - gt-gastown-polecat-Toast (rig-level named agent)
// AgentBeadIDWithPrefix generates an agent bead ID using the specified prefix.
// The prefix should NOT include the hyphen (e.g., "gt", "bd", not "gt-", "bd-").
// For town-level agents (mayor, deacon), pass empty rig and name.
// For rig-level singletons (witness, refinery), pass empty name.
// For named agents (crew, polecat), pass all three.
func AgentBeadIDWithPrefix(prefix, rig, role, name string) string {
if rig == "" {
// Town-level agent: prefix-mayor, prefix-deacon
return prefix + "-" + role
}
if name == "" {
// Rig-level singleton: prefix-rig-witness, prefix-rig-refinery
return prefix + "-" + rig + "-" + role
}
// Rig-level named agent: prefix-rig-role-name
return prefix + "-" + rig + "-" + role + "-" + name
}
// AgentBeadID generates the canonical agent bead ID using "gt" prefix.
// For non-gastown rigs, use AgentBeadIDWithPrefix with the rig's configured prefix.
func AgentBeadID(rig, role, name string) string {
return AgentBeadIDWithPrefix("gt", rig, role, name)
}
// MayorBeadID returns the Mayor agent bead ID.
//
// Deprecated: Use MayorBeadIDTown() for town-level beads (hq- prefix).
// This function returns "gt-mayor" which is for rig-level storage.
// Town-level agents like Mayor should use the hq- prefix.
func MayorBeadID() string {
return "gt-mayor"
}
// DeaconBeadID returns the Deacon agent bead ID.
//
// Deprecated: Use DeaconBeadIDTown() for town-level beads (hq- prefix).
// This function returns "gt-deacon" which is for rig-level storage.
// Town-level agents like Deacon should use the hq- prefix.
func DeaconBeadID() string {
return "gt-deacon"
}
// DogBeadID returns a Dog agent bead ID.
// Dogs are town-level agents, so they follow the pattern: gt-dog-<name>
// Deprecated: Use DogBeadIDTown() for town-level beads with hq- prefix.
// Dogs are town-level agents and should use hq-dog-<name>, not gt-dog-<name>.
func DogBeadID(name string) string {
return "gt-dog-" + name
}
// WitnessBeadIDWithPrefix returns the Witness agent bead ID for a rig using the specified prefix.
func WitnessBeadIDWithPrefix(prefix, rig string) string {
return AgentBeadIDWithPrefix(prefix, rig, "witness", "")
}
// WitnessBeadID returns the Witness agent bead ID for a rig using "gt" prefix.
func WitnessBeadID(rig string) string {
return WitnessBeadIDWithPrefix("gt", rig)
}
// RefineryBeadIDWithPrefix returns the Refinery agent bead ID for a rig using the specified prefix.
func RefineryBeadIDWithPrefix(prefix, rig string) string {
return AgentBeadIDWithPrefix(prefix, rig, "refinery", "")
}
// RefineryBeadID returns the Refinery agent bead ID for a rig using "gt" prefix.
func RefineryBeadID(rig string) string {
return RefineryBeadIDWithPrefix("gt", rig)
}
// CrewBeadIDWithPrefix returns a Crew worker agent bead ID using the specified prefix.
func CrewBeadIDWithPrefix(prefix, rig, name string) string {
return AgentBeadIDWithPrefix(prefix, rig, "crew", name)
}
// CrewBeadID returns a Crew worker agent bead ID using "gt" prefix.
func CrewBeadID(rig, name string) string {
return CrewBeadIDWithPrefix("gt", rig, name)
}
// PolecatBeadIDWithPrefix returns a Polecat agent bead ID using the specified prefix.
func PolecatBeadIDWithPrefix(prefix, rig, name string) string {
return AgentBeadIDWithPrefix(prefix, rig, "polecat", name)
}
// PolecatBeadID returns a Polecat agent bead ID using "gt" prefix.
func PolecatBeadID(rig, name string) string {
return PolecatBeadIDWithPrefix("gt", rig, name)
}
// ParseAgentBeadID parses an agent bead ID into its components.
// Returns rig, role, name, and whether parsing succeeded.
// For town-level agents, rig will be empty.
// For singletons, name will be empty.
// Accepts any valid prefix (e.g., "gt-", "bd-"), not just "gt-".
func ParseAgentBeadID(id string) (rig, role, name string, ok bool) {
// Find the prefix (everything before the first hyphen)
// Valid prefixes are 2-3 characters (e.g., "gt", "bd", "hq")
hyphenIdx := strings.Index(id, "-")
if hyphenIdx < 2 || hyphenIdx > 3 {
return "", "", "", false
}
rest := id[hyphenIdx+1:]
parts := strings.Split(rest, "-")
switch len(parts) {
case 1:
// Town-level: gt-mayor, bd-deacon
return "", parts[0], "", true
case 2:
// Could be rig-level singleton (gt-gastown-witness) or
// town-level named (gt-dog-alpha for dogs)
if parts[0] == "dog" {
// Dogs are town-level named agents: gt-dog-<name>
return "", "dog", parts[1], true
}
// Rig-level singleton: gt-gastown-witness
return parts[0], parts[1], "", true
case 3:
// Rig-level named: gt-gastown-crew-max, bd-beads-polecat-pearl
return parts[0], parts[1], parts[2], true
default:
// Handle names with hyphens: gt-gastown-polecat-my-agent-name
// or gt-dog-my-agent-name
if len(parts) >= 3 {
if parts[0] == "dog" {
// Dog with hyphenated name: gt-dog-my-dog-name
return "", "dog", strings.Join(parts[1:], "-"), true
}
return parts[0], parts[1], strings.Join(parts[2:], "-"), true
}
return "", "", "", false
}
}
// IsAgentSessionBead returns true if the bead ID represents an agent session molecule.
// Agent session beads follow patterns like gt-mayor, bd-beads-witness, gt-gastown-crew-joe.
// Supports any valid prefix (e.g., "gt-", "bd-"), not just "gt-".
// These are used to track agent state and update frequently, which can create noise.
func IsAgentSessionBead(beadID string) bool {
_, role, _, ok := ParseAgentBeadID(beadID)
if !ok {
return false
}
// Known agent roles
switch role {
case "mayor", "deacon", "witness", "refinery", "crew", "polecat", "dog":
return true
default:
return false
}
}

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