cmd

package
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 99 Imported by: 0

Documentation

Overview

Package cmd provides CLI commands for the gt tool.

Package cmd provides CLI commands for the gt tool.

Package cmd provides CLI commands for the gt tool.

Package cmd provides CLI commands for the gt tool.

Package cmd provides polecat spawning utilities for gt sling.

Package cmd provides CLI commands for the gt tool.

Package cmd provides CLI commands for the gt tool. This file implements the gt rig config commands for viewing and manipulating rig configuration across property layers.

Package cmd provides CLI commands for the gt tool. This file implements the gt rig settings commands for viewing and manipulating rig settings/config.json files.

Package cmd provides CLI commands for the gt tool.

Index

Constants

View Source
const (
	ExitCompleted = "COMPLETED"
	ExitEscalated = "ESCALATED"
	ExitDeferred  = "DEFERRED"
)

Valid exit types for gt done

View Source
const (
	// NudgeModeImmediate sends directly via tmux send-keys (current behavior).
	// This interrupts in-flight work but guarantees immediate delivery.
	NudgeModeImmediate = "immediate"
	// NudgeModeQueue writes to a file queue; agent picks up via hook at next
	// turn boundary. Zero interruption but delivery depends on agent turn frequency.
	NudgeModeQueue = "queue"
	// NudgeModeWaitIdle waits for the agent to become idle (prompt visible),
	// then delivers directly. Falls back to queue on timeout. Best of both worlds.
	NudgeModeWaitIdle = "wait-idle"
)

Nudge delivery modes.

View Source
const (
	EnvGTRole     = "GT_ROLE"
	EnvGTRoleHome = "GT_ROLE_HOME"
)

Environment variables for role detection

View Source
const (
	GroupWork      = "work"
	GroupAgents    = "agents"
	GroupComm      = "comm"
	GroupServices  = "services"
	GroupWorkspace = "workspace"
	GroupConfig    = "config"
	GroupDiag      = "diag"
)

Command group IDs - used by subcommands to organize help output

View Source
const BranchProtectionMarker = "Gas Town branch protection"

BranchProtectionMarker identifies our branch protection code in post-checkout.

View Source
const BranchProtectionScript = `` /* 1408-byte string literal not displayed */

BranchProtectionScript is the code to prepend to post-checkout hook. It auto-reverts to main if a non-main branch was checked out in the town root.

NOTE: Git does NOT support "pre-checkout" hooks. We use post-checkout to detect and auto-revert bad checkouts immediately after they happen.

View Source
const DefaultAgentEmailDomain = "gastown.local"

DefaultAgentEmailDomain is the default domain for agent git emails.

View Source
const HQGitignore = `` /* 3022-byte string literal not displayed */

HQGitignore is the standard .gitignore for Gas Town HQs

View Source
const RigDockedLabel = "status:docked"

RigDockedLabel is the label set on rig identity beads when docked.

View Source
const RigStatusKey = "status"

RigStatusKey is the wisp config key for rig operational status.

View Source
const RigStatusParked = "parked"

RigStatusParked is the value indicating a rig is parked.

Variables

View Source
var (
	Version = "0.9.0"
	// Build can be set via ldflags at compile time
	Build = "dev"
	// Commit and Branch - the git revision the binary was built from (optional ldflag)
	Commit = ""
	Branch = ""
	// BuiltProperly is set to "1" by `make build`. If empty, the binary was built
	// with raw `go build` and is likely unsigned (will be killed on macOS).
	BuiltProperly = ""
)

Version information - set at build time via ldflags

View Source
var AgentTypeColors = map[AgentType]string{
	AgentMayor:    "#[fg=red,bold]",
	AgentDeacon:   "#[fg=yellow,bold]",
	AgentWitness:  "#[fg=cyan]",
	AgentRefinery: "#[fg=blue]",
	AgentCrew:     "#[fg=green]",
	AgentPolecat:  "#[fg=white,dim]",
	AgentPersonal: "#[fg=magenta]",
	AgentTest:     "#[fg=yellow,dim]",
}

AgentTypeColors maps agent types to tmux color codes.

AgentTypeIcons maps agent types to display icons. Uses centralized emojis from constants package.

Functions

func BdCmd added in v0.8.0

func BdCmd(args ...string) *bdCmd

BdCmd creates a new bd command builder with the given arguments. The command will execute "bd" with the provided arguments.

Example:

err := cmd.BdCmd("show", beadID, "--json").
    Dir(workDir).
    Run()

func CheckBeadsVersion added in v0.2.2

func CheckBeadsVersion() error

CheckBeadsVersion verifies that the installed beads version meets the minimum requirement. Returns nil if the version is sufficient, or an error with details if not. The check is performed only once per process execution.

func CheckSynthesisReady

func CheckSynthesisReady(convoyID string) (bool, error)

CheckSynthesisReady checks if a convoy is ready for synthesis. Returns true if all tracked legs are complete.

func CookFormula added in v0.5.0

func CookFormula(formulaName, workDir, townRoot string) error

CookFormula cooks a formula to ensure its proto exists. This is useful for batch mode where we cook once before processing multiple beads. townRoot is required for GT_ROOT so bd can find town-level formulas. Falls back to embedded formula extraction if bd can't find the formula on disk.

func EmitEvent added in v0.8.0

func EmitEvent(channel, eventType string, payloadPairs []string) (string, error)

EmitEvent creates an event file in the channel directory. This is the programmatic API used by both the CLI command and internal callers (e.g., nudgeRefinery). Returns the path to the created event file.

func EmitEventToTown added in v0.8.0

func EmitEventToTown(townRoot, channel, eventType string, payloadPairs []string) (string, error)

EmitEventToTown creates an event file using an explicit town root. Used by internal callers that already know the town root (e.g., nudgeRefinery).

func Execute

func Execute() int

Execute runs the root command and returns an exit code. The caller (main) should call os.Exit with this code.

func GetRigLED added in v0.8.0

func GetRigLED(hasWitness, hasRefinery bool, opState string) string

GetRigLED returns the LED indicator for a rig based on session and operational state. Used by both rig list and statusline for consistent indicators:

  • 🟢 = both witness and refinery running (fully active)
  • 🟡 = one session running (partially active)
  • ⚫ = nothing running (stopped)
  • 🅿️ = parked (intentionally paused)
  • 🛑 = docked (global shutdown)

func InitGitForHarness

func InitGitForHarness(hqRoot string, github string, private bool) error

InitGitForHarness is the shared implementation for git initialization. It can be called from both 'gt git-init' and 'gt install --git'. Note: Function name kept for backwards compatibility.

func InstallBranchProtection added in v0.6.0

func InstallBranchProtection(hqRoot string) error

InstallBranchProtection adds branch protection to the post-checkout hook. If a non-main branch is checked out in the town root, it auto-reverts to main.

func InstallPreCheckoutHook added in v0.2.4

func InstallPreCheckoutHook(hqRoot string) error

InstallPreCheckoutHook installs branch protection in the post-checkout hook. This auto-reverts accidental branch switches that can break gt commands.

NOTE: The function name is kept for backwards compatibility, but it now installs protection in post-checkout (git doesn't support pre-checkout).

func IsBranchProtectionInstalled added in v0.6.0

func IsBranchProtectionInstalled(hqRoot string) bool

IsBranchProtectionInstalled checks if branch protection is in post-checkout.

func IsDogTarget

func IsDogTarget(target string) (dogName string, isDog bool)

IsDogTarget checks if target is a dog target pattern. Returns the dog name (or empty for pool dispatch) and true if it's a dog target. Patterns:

  • "deacon/dogs" -> ("", true) - dispatch to any idle dog
  • "deacon/dogs/alpha" -> ("alpha", true) - dispatch to specific dog
  • "dog:" -> ("", true) - dispatch to any idle dog (shorthand)
  • "dog:alpha" -> ("alpha", true) - dispatch to specific dog (shorthand)

func IsPreCheckoutHookInstalled added in v0.2.4

func IsPreCheckoutHookInstalled(hqRoot string) bool

IsPreCheckoutHookInstalled checks if branch protection is installed. NOTE: Function name kept for backwards compatibility.

func IsRigDocked added in v0.2.2

func IsRigDocked(townRoot, rigName, prefix string) bool

IsRigDocked checks if a rig is docked by checking for the status:docked label on the rig identity bead. This function is exported for use by the daemon.

func IsRigName

func IsRigName(target string) (string, bool)

IsRigName checks if a target string is a rig name (not a role or path). Returns the rig name and true if it's a valid rig.

func IsRigParked added in v0.2.2

func IsRigParked(townRoot, rigName string) bool

IsRigParked checks if a rig is parked. Checks the wisp layer (ephemeral) first, then falls back to the rig identity bead's status:parked label (persistent). This ensures parked state survives wisp cleanup. (Fixes upstream #2079)

func IsRigParkedOrDocked added in v0.9.0

func IsRigParkedOrDocked(townRoot, rigName string) (bool, string)

IsRigParkedOrDocked checks if a rig is parked or docked by any mechanism (wisp ephemeral state or persistent bead labels). Returns (blocked, reason). This is the single entry point for all dispatch paths (sling, convoy launch, convoy stage) to check rig availability.

Parked vs docked asymmetry: parked state is checked in both the wisp layer (ephemeral, set by "gt rig park") and bead labels (persistent fallback for when wisp state is lost during cleanup). Docked state is bead-label only because "gt rig dock" never writes to wisp — it persists exclusively via the rig identity bead's status:docked label.

func IsSilentExit

func IsSilentExit(err error) (int, bool)

IsSilentExit checks if an error is a SilentExitError and returns its code. Uses errors.As to properly handle wrapped errors. Returns 0 and false if err is nil or not a SilentExitError.

func LogCrash

func LogCrash(townRoot, agent, reason string) error

LogCrash logs a crash event.

func LogDone

func LogDone(townRoot, agent, issueID string) error

LogDone logs a done event.

func LogEvent

func LogEvent(eventType townlog.EventType, agent, context string) error

LogEvent is a helper that logs an event from anywhere in the codebase. It finds the town root and logs the event.

func LogEventWithRoot

func LogEventWithRoot(townRoot string, eventType townlog.EventType, agent, context string) error

LogEventWithRoot logs an event when the town root is already known.

func LogHandoff

func LogHandoff(townRoot, agent, context string) error

LogHandoff logs a handoff event.

func LogKill

func LogKill(townRoot, agent, reason string) error

LogKill logs a kill event.

func LogNudge

func LogNudge(townRoot, agent, message string) error

LogNudge logs a nudge event.

func LogSpawn

func LogSpawn(townRoot, agent, issueID string) error

LogSpawn logs a spawn event.

func LogWake

func LogWake(townRoot, agent, context string) error

LogWake logs a wake event.

func ReadPersistedSessionID added in v0.2.0

func ReadPersistedSessionID() string

ReadPersistedSessionID reads a previously persisted session ID. Checks cwd first, then town root. Returns empty string if not found.

func TriggerSynthesisIfReady

func TriggerSynthesisIfReady(convoyID, targetRig string) error

TriggerSynthesisIfReady checks convoy status and starts synthesis if ready. This can be called by the witness when a leg completes.

func ValidateTarget added in v0.7.0

func ValidateTarget(target string) error

ValidateTarget performs lightweight pre-checks on a sling target string, catching common mistakes before resolveTarget can trigger side-effects like polecat spawning. It returns a non-nil error with a helpful message when the target is clearly malformed.

It intentionally does NOT duplicate the full resolution logic — valid targets that pass this check are still resolved by resolveTarget.

Types

type AccountListItem

type AccountListItem struct {
	Handle      string `json:"handle"`
	Email       string `json:"email"`
	Description string `json:"description,omitempty"`
	ConfigDir   string `json:"config_dir"`
	IsDefault   bool   `json:"is_default"`
}

AccountListItem represents an account in list output.

type AgentHookInfo

type AgentHookInfo struct {
	Agent    string `json:"agent"`              // Agent address (e.g., "greenplace/toast", "greenplace/witness")
	Role     string `json:"role"`               // Role type (polecat, crew, witness, refinery)
	HasWork  bool   `json:"has_work"`           // Whether agent has pinned work
	Molecule string `json:"molecule,omitempty"` // Attached molecule ID
	Title    string `json:"title,omitempty"`    // Pinned bead title
}

AgentHookInfo represents an agent's hook (pinned work) status.

type AgentListItem added in v0.2.1

type AgentListItem struct {
	Name     string `json:"name"`
	Command  string `json:"command"`
	Args     string `json:"args,omitempty"`
	Type     string `json:"type"` // "built-in" or "custom"
	IsCustom bool   `json:"is_custom"`
}

AgentListItem represents an agent in list output.

type AgentRuntime

type AgentRuntime struct {
	Name         string `json:"name"`                    // Display name (e.g., "mayor", "witness")
	Address      string `json:"address"`                 // Full address (e.g., "greenplace/witness")
	Session      string `json:"session"`                 // tmux session name
	Role         string `json:"role"`                    // Role type
	Running      bool   `json:"running"`                 // Is tmux session running?
	HasWork      bool   `json:"has_work"`                // Has pinned work?
	WorkTitle    string `json:"work_title,omitempty"`    // Title of pinned work
	HookBead     string `json:"hook_bead,omitempty"`     // Pinned bead ID from agent bead
	State        string `json:"state,omitempty"`         // Agent state from agent bead
	UnreadMail   int    `json:"unread_mail"`             // Number of unread messages
	FirstSubject string `json:"first_subject,omitempty"` // Subject of first unread message
	AgentAlias   string `json:"agent_alias,omitempty"`   // Configured agent name (e.g., "opus-46", "pi")
	AgentInfo    string `json:"agent_info,omitempty"`    // Runtime summary (e.g., "claude/opus", "pi/kimi-k2p5")
}

AgentRuntime represents the runtime state of an agent.

type AgentSession

type AgentSession struct {
	Name      string
	Type      AgentType
	Rig       string // For rig-specific agents
	AgentName string // e.g., crew name, polecat name
	Socket    string // tmux socket name this session lives on
}

AgentSession represents a categorized tmux session.

type AgentType

type AgentType int

AgentType represents the type of Gas Town agent.

const (
	AgentMayor AgentType = iota
	AgentDeacon
	AgentWitness
	AgentRefinery
	AgentCrew
	AgentPolecat
	AgentPersonal // Non-GT session (user's terminal session)
	AgentTest     // Session on a gt-test-* socket (integration tests)
)

type AuditEntry

type AuditEntry struct {
	Timestamp time.Time `json:"timestamp"`
	Source    string    `json:"source"` // "git", "beads", "townlog", "events"
	Type      string    `json:"type"`   // "commit", "bead_created", "bead_closed", "spawn", etc.
	Actor     string    `json:"actor"`
	Summary   string    `json:"summary"`
	Details   string    `json:"details,omitempty"`
	ID        string    `json:"id,omitempty"` // commit hash, bead ID, etc.
}

AuditEntry represents a single entry in the audit log.

type AwaitEventResult added in v0.8.0

type AwaitEventResult struct {
	Reason     string        `json:"reason"`                // "event" or "timeout"
	Elapsed    time.Duration `json:"elapsed"`               // how long we waited
	Events     []EventFile   `json:"events,omitempty"`      // event files found
	IdleCycles int           `json:"idle_cycles,omitempty"` // current idle cycle count
}

AwaitEventResult is the result of an await-event operation.

type AwaitSignalResult

type AwaitSignalResult struct {
	Reason     string        `json:"reason"`                // "signal" or "timeout"
	Elapsed    time.Duration `json:"elapsed"`               // how long we waited
	Signal     string        `json:"signal,omitempty"`      // the line that woke us (if signal)
	IdleCycles int           `json:"idle_cycles,omitempty"` // current idle cycle count (after update)
}

AwaitSignalResult is the result of an await-signal operation.

type BackupHealth added in v0.9.0

type BackupHealth struct {
	DoltFreshness   string `json:"dolt_freshness,omitempty"`
	DoltAgeSeconds  int    `json:"dolt_age_seconds,omitempty"`
	DoltStale       bool   `json:"dolt_stale"`
	JSONLFreshness  string `json:"jsonl_freshness,omitempty"`
	JSONLAgeSeconds int    `json:"jsonl_age_seconds,omitempty"`
	JSONLStale      bool   `json:"jsonl_stale"`
}

type BeadEntry added in v0.3.0

type BeadEntry struct {
	ID        string    `json:"id"`
	Title     string    `json:"title"`
	Status    string    `json:"status"`
	Agent     string    `json:"agent,omitempty"`
	UpdatedAt time.Time `json:"updated_at"`
	UpdateRel string    `json:"updated_relative"`
}

BeadEntry represents a bead for output.

type BeadInfo added in v0.8.0

type BeadInfo struct {
	ID     string
	Title  string
	Type   string // "epic", "task", "bug", etc.
	Status string
	Rig    string // resolved rig name
}

BeadInfo represents raw bead data from bd show output.

type BrowseFilter added in v0.8.0

type BrowseFilter struct {
	Status   string
	Project  string
	Type     string
	Priority int
	Limit    int
}

BrowseFilter holds filter parameters for building a browse query.

type CVSummary added in v0.3.0

type CVSummary struct {
	Identity         string           `json:"identity"`
	Created          string           `json:"created,omitempty"`
	Sessions         int              `json:"sessions"`
	IssuesCompleted  int              `json:"issues_completed"`
	IssuesFailed     int              `json:"issues_failed"`
	IssuesAbandoned  int              `json:"issues_abandoned"`
	Languages        map[string]int   `json:"languages,omitempty"`
	WorkTypes        map[string]int   `json:"work_types,omitempty"`
	AvgCompletionMin int              `json:"avg_completion_minutes,omitempty"`
	FirstPassRate    float64          `json:"first_pass_rate,omitempty"`
	RecentWork       []RecentWorkItem `json:"recent_work,omitempty"`
}

CVSummary represents the CV/work history summary for a polecat.

type CallbackResult

type CallbackResult struct {
	MessageID    string
	CallbackType CallbackType
	From         string
	Subject      string
	Handled      bool
	Action       string
	Error        error
}

CallbackResult tracks the result of processing a callback.

type CallbackType

type CallbackType string

CallbackType identifies the type of callback message.

const (
	CallbackPolecatDone    CallbackType = "polecat_done"
	CallbackMergeRejected  CallbackType = "merge_rejected"
	CallbackMergeCompleted CallbackType = "merge_completed"
	CallbackHelp           CallbackType = "help"
	CallbackEscalation     CallbackType = "escalation"
	CallbackSling          CallbackType = "sling"
	CallbackUnknown        CallbackType = "unknown"
)

type CollisionIssue

type CollisionIssue struct {
	Type      string `json:"type"` // "stale", "collision", "orphaned"
	WorkerDir string `json:"worker_dir"`
	Message   string `json:"message"`
	PID       int    `json:"pid,omitempty"`
	SessionID string `json:"session_id,omitempty"`
}

CollisionIssue describes a single collision or lock issue.

type CollisionReport

type CollisionReport struct {
	TotalSessions int                       `json:"total_sessions"`
	TotalLocks    int                       `json:"total_locks"`
	Collisions    int                       `json:"collisions"`
	StaleLocks    int                       `json:"stale_locks"`
	Issues        []CollisionIssue          `json:"issues,omitempty"`
	Locks         map[string]*lock.LockInfo `json:"locks,omitempty"`
}

CollisionReport holds the results of a collision check.

type CommitEntry added in v0.3.0

type CommitEntry struct {
	Hash      string    `json:"hash"`
	ShortHash string    `json:"short_hash"`
	Author    string    `json:"author"`
	Email     string    `json:"email"`
	Date      time.Time `json:"date"`
	DateRel   string    `json:"date_relative"`
	Subject   string    `json:"subject"`
	IsAgent   bool      `json:"is_agent"`
}

CommitEntry represents a git commit for output.

type ConvoyDAG added in v0.8.0

type ConvoyDAG struct {
	Nodes map[string]*ConvoyDAGNode
}

ConvoyDAG represents an in-memory dependency graph for convoy staging.

type ConvoyDAGNode added in v0.8.0

type ConvoyDAGNode struct {
	ID        string
	Title     string
	Type      string // "epic", "task", "bug", etc.
	Status    string
	Rig       string
	BlockedBy []string // IDs of beads that block this one (execution edges)
	Blocks    []string // IDs of beads this one blocks
	Children  []string // parent-child children (hierarchy only, not execution)
	Parent    string   // parent-child parent
}

ConvoyDAGNode represents a single bead in the DAG.

type ConvoyInfo added in v0.7.0

type ConvoyInfo struct {
	ID            string // Convoy bead ID (e.g., "hq-cv-abc")
	Owned         bool   // true if convoy has gt:owned label
	MergeStrategy string // "direct", "mr", "local", or "" (default = mr)
}

ConvoyInfo holds convoy details for an issue's tracking convoy.

func (*ConvoyInfo) IsOwnedDirect added in v0.7.0

func (c *ConvoyInfo) IsOwnedDirect() bool

IsOwnedDirect returns true if the convoy is owned with direct merge strategy. This is the key check for skipping witness/refinery merge pipeline.

type ConvoyMeta

type ConvoyMeta struct {
	ID          string   `json:"id"`
	Title       string   `json:"title"`
	Status      string   `json:"status"`
	Formula     string   `json:"formula,omitempty"`      // Formula name
	FormulaPath string   `json:"formula_path,omitempty"` // Path to formula file
	ReviewID    string   `json:"review_id,omitempty"`    // Review ID for output paths
	LegIssues   []string `json:"leg_issues,omitempty"`   // Tracked leg issue IDs
}

ConvoyMeta holds metadata about a convoy including its formula.

type CostDigest added in v0.2.3

type CostDigest struct {
	Date         string             `json:"date"`
	TotalUSD     float64            `json:"total_usd"`
	SessionCount int                `json:"session_count"`
	Sessions     []CostEntry        `json:"sessions,omitempty"`
	ByRole       map[string]float64 `json:"by_role"`
	ByRig        map[string]float64 `json:"by_rig,omitempty"`
}

CostDigest represents the aggregated daily cost report.

type CostDigestPayload added in v0.7.0

type CostDigestPayload struct {
	Date         string             `json:"date"`
	TotalUSD     float64            `json:"total_usd"`
	SessionCount int                `json:"session_count"`
	ByRole       map[string]float64 `json:"by_role"`
	ByRig        map[string]float64 `json:"by_rig,omitempty"`
}

CostDigestPayload is the compact payload stored in the bead. It excludes per-session details to avoid exceeding Dolt column size limits.

type CostEntry added in v0.2.0

type CostEntry struct {
	SessionID string    `json:"session_id"`
	Role      string    `json:"role"`
	Rig       string    `json:"rig,omitempty"`
	Worker    string    `json:"worker,omitempty"`
	CostUSD   float64   `json:"cost_usd"`
	StartedAt time.Time `json:"started_at"`
	EndedAt   time.Time `json:"ended_at"`
	WorkItem  string    `json:"work_item,omitempty"`
}

CostEntry is a ledger entry for historical cost tracking.

type CostLogEntry added in v0.6.0

type CostLogEntry struct {
	SessionID string    `json:"session_id"`
	Role      string    `json:"role"`
	Rig       string    `json:"rig,omitempty"`
	Worker    string    `json:"worker,omitempty"`
	CostUSD   float64   `json:"cost_usd"`
	EndedAt   time.Time `json:"ended_at"`
	WorkItem  string    `json:"work_item,omitempty"`
}

CostLogEntry represents a single entry in the costs.jsonl log file.

type CostsOutput added in v0.2.0

type CostsOutput struct {
	Sessions []SessionCost      `json:"sessions,omitempty"`
	Total    float64            `json:"total_usd"`
	ByRole   map[string]float64 `json:"by_role,omitempty"`
	ByRig    map[string]float64 `json:"by_rig,omitempty"`
	Period   string             `json:"period,omitempty"`
}

CostsOutput is the JSON output structure.

type CrewListItem

type CrewListItem struct {
	Name       string `json:"name"`
	Rig        string `json:"rig"`
	Branch     string `json:"branch"`
	Path       string `json:"path"`
	HasSession bool   `json:"has_session"`
	GitClean   bool   `json:"git_clean"`
}

CrewListItem represents a crew worker in list output.

type CrewStatusItem

type CrewStatusItem struct {
	Name         string   `json:"name"`
	Rig          string   `json:"rig"`
	Path         string   `json:"path"`
	Branch       string   `json:"branch"`
	HasSession   bool     `json:"has_session"`
	SessionID    string   `json:"session_id,omitempty"`
	GitClean     bool     `json:"git_clean"`
	GitModified  []string `json:"git_modified,omitempty"`
	GitUntracked []string `json:"git_untracked,omitempty"`
	MailTotal    int      `json:"mail_total"`
	MailUnread   int      `json:"mail_unread"`
}

CrewStatusItem represents detailed status for a crew worker.

type DAGInfo added in v0.6.0

type DAGInfo struct {
	RootID       string              `json:"root_id"`
	RootTitle    string              `json:"root_title"`
	TotalNodes   int                 `json:"total_nodes"`
	Tiers        int                 `json:"tiers"`
	CriticalPath []string            `json:"critical_path,omitempty"`
	Nodes        map[string]*DAGNode `json:"nodes"`
	TierGroups   [][]string          `json:"tier_groups"` // Nodes grouped by tier
}

DAGInfo contains the full DAG information for a molecule.

type DAGNode added in v0.6.0

type DAGNode struct {
	ID           string     `json:"id"`
	Title        string     `json:"title"`
	Status       string     `json:"status"`
	Parallel     bool       `json:"parallel,omitempty"`
	Dependencies []string   `json:"dependencies,omitempty"`
	Dependents   []string   `json:"dependents,omitempty"`
	Tier         int        `json:"tier"` // Execution tier (0 = root, higher = later)
	Children     []*DAGNode `json:"children,omitempty"`
}

DAGNode represents a node in the dependency graph.

type DatabaseHealth added in v0.9.0

type DatabaseHealth struct {
	Name       string `json:"name"`
	Issues     int    `json:"issues"`
	OpenIssues int    `json:"open_issues"`
	Wisps      int    `json:"wisps"`
	OpenWisps  int    `json:"open_wisps"`
	Commits    int    `json:"commits"`
}

type DeaconStatusOutput added in v0.7.0

type DeaconStatusOutput struct {
	Running   bool             `json:"running"`
	Paused    bool             `json:"paused"`
	Session   string           `json:"session"`
	Heartbeat *HeartbeatStatus `json:"heartbeat,omitempty"`
}

DeaconStatusOutput is the JSON-serializable status of the Deacon.

type DepInfo added in v0.8.0

type DepInfo struct {
	IssueID     string // the dependent bead
	DependsOnID string // the bead it depends on
	Type        string // "blocks", "parent-child", "waits-for", "conditional-blocks", "tracks", "related", etc.
}

DepInfo represents a raw dependency from bd dep list output.

type DependencyInfo

type DependencyInfo struct {
	ID       string `json:"id"`
	Title    string `json:"title"`
	Status   string `json:"status"`
	Priority int    `json:"priority"`
	Type     string `json:"type"`
}

DependencyInfo represents a dependency or blocker.

type DirectoryEntry added in v0.8.0

type DirectoryEntry struct {
	Address string `json:"address"`
	Type    string `json:"type"`
}

DirectoryEntry represents an address in the directory.

type DispatchResult added in v0.8.0

type DispatchResult struct {
	BeadID  string
	Rig     string
	Success bool
	Error   error
}

DispatchResult records the outcome of dispatching a single task.

type DogDispatchInfo

type DogDispatchInfo struct {
	DogName string // Name of the dog
	AgentID string // Agent ID format (deacon/dogs/<name>)
	Pane    string // Tmux pane (empty if session start was delayed)
	Spawned bool   // True if dog was spawned (new)
	// contains filtered or unexported fields
}

DogDispatchInfo contains information about a dog dispatch.

func DispatchToDog

func DispatchToDog(dogName string, opts DogDispatchOptions) (*DogDispatchInfo, error)

DispatchToDog finds or spawns a dog for work dispatch. If dogName is empty, finds an idle dog from the pool. If opts.Create is true and no dogs exist, creates one. opts.WorkDesc is recorded in the dog's state so we know what it's working on. If opts.DelaySessionStart is true, the session is not started (caller must call StartDelayedSession).

func (*DogDispatchInfo) StartDelayedSession added in v0.6.0

func (d *DogDispatchInfo) StartDelayedSession() (string, error)

StartDelayedSession starts the dog session after bead setup is complete. This should only be called when DelaySessionStart was true during dispatch.

type DogDispatchOptions added in v0.6.0

type DogDispatchOptions struct {
	Create            bool   // Create dog if it doesn't exist
	WorkDesc          string // Work description (formula or bead ID)
	DelaySessionStart bool   // If true, don't start session (caller will start later)
	AgentOverride     string // Agent override (e.g., "codex", "gemini")
}

DogDispatchOptions contains options for dispatching work to a dog.

type DoltInfo added in v0.9.0

type DoltInfo struct {
	Running       bool   `json:"running"`
	PID           int    `json:"pid,omitempty"`
	Port          int    `json:"port"`
	Remote        bool   `json:"remote,omitempty"`
	DataDir       string `json:"data_dir,omitempty"`
	PortConflict  bool   `json:"port_conflict,omitempty"`  // Port taken by another town's Dolt
	ConflictOwner string `json:"conflict_owner,omitempty"` // --data-dir of the process holding the port
}

DoltInfo represents the Dolt server status.

type DoneCheckpoint added in v0.7.0

type DoneCheckpoint string

DoneCheckpoint represents a checkpoint stage in the gt done flow (gt-aufru). Checkpoints are stored as labels on the agent bead, enabling resume after process interruption (context exhaustion, SIGTERM, etc.).

const (
	CheckpointPushed          DoneCheckpoint = "pushed"
	CheckpointMRCreated       DoneCheckpoint = "mr-created"
	CheckpointWitnessNotified DoneCheckpoint = "witness-notified"
)

type EmitEventResult added in v0.8.0

type EmitEventResult struct {
	Path    string `json:"path"`
	Channel string `json:"channel"`
	Type    string `json:"type"`
}

EmitEventResult is returned when an event is emitted.

type EventFile added in v0.8.0

type EventFile struct {
	Path    string          `json:"path"`
	Content json.RawMessage `json:"content"`
}

EventFile represents a single event file.

type EventListItem added in v0.2.0

type EventListItem struct {
	ID string `json:"id"`
}

EventListItem represents an event from bd list (minimal fields).

type FindingJSON added in v0.8.0

type FindingJSON struct {
	Category     string   `json:"category"`
	BeadIDs      []string `json:"bead_ids"`
	Message      string   `json:"message"`
	SuggestedFix string   `json:"suggested_fix,omitempty"`
}

FindingJSON is the JSON representation of a StagingFinding.

type FormulaOnBeadResult added in v0.5.0

type FormulaOnBeadResult struct {
	WispRootID string // The wisp root ID (compound root after bonding)
	BeadToHook string // The bead ID to hook (BASE bead, not wisp - lifecycle fix)
}

FormulaOnBeadResult contains the result of instantiating a formula on a bead.

func InstantiateFormulaOnBead added in v0.5.0

func InstantiateFormulaOnBead(formulaName, beadID, title, hookWorkDir, townRoot string, skipCook bool, extraVars []string) (_ *FormulaOnBeadResult, retErr error)

InstantiateFormulaOnBead creates a wisp from a formula, bonds it to a bead. This is the formula-on-bead pattern used by issue #288 for auto-applying mol-polecat-work.

Parameters:

  • formulaName: the formula to instantiate (e.g., "mol-polecat-work")
  • beadID: the base bead to bond the wisp to
  • title: the bead title (used for --var feature=<title>)
  • hookWorkDir: working directory for bd commands (polecat's worktree)
  • townRoot: the town root directory
  • skipCook: if true, skip cooking (for batch mode optimization where cook happens once)
  • extraVars: additional --var values supplied by the user

Returns the wisp root ID which should be hooked.

type GitState

type GitState struct {
	Clean            bool     `json:"clean"`
	UncommittedFiles []string `json:"uncommitted_files"`
	UnpushedCommits  int      `json:"unpushed_commits"`
	StashCount       int      `json:"stash_count"`
}

GitState represents the git state of a polecat's worktree.

type HealthReport added in v0.9.0

type HealthReport struct {
	Timestamp string            `json:"timestamp"`
	Server    *ServerHealth     `json:"server"`
	Databases []DatabaseHealth  `json:"databases"`
	Pollution []PollutionRecord `json:"pollution,omitempty"`
	Backups   *BackupHealth     `json:"backups"`
	Processes *ProcessHealth    `json:"processes"`
	Orphans   []OrphanDB        `json:"orphans,omitempty"`
}

HealthReport is the machine-readable output of gt health --json.

type HeartbeatStatus added in v0.7.0

type HeartbeatStatus struct {
	Timestamp  time.Time `json:"timestamp"`
	AgeSec     float64   `json:"age_seconds"`
	Cycle      int64     `json:"cycle"`
	LastAction string    `json:"last_action,omitempty"`
	Fresh      bool      `json:"fresh"`
	Stale      bool      `json:"stale"`
	VeryStale  bool      `json:"very_stale"`
}

HeartbeatStatus is the JSON-serializable heartbeat info.

type HookDefinition added in v0.5.0

type HookDefinition struct {
	Description string   `toml:"description"`
	Event       string   `toml:"event"`
	Matchers    []string `toml:"matchers"`
	Command     string   `toml:"command"`
	Roles       []string `toml:"roles"`
	Scope       string   `toml:"scope"`
	Enabled     bool     `toml:"enabled"`
}

HookDefinition represents a single hook definition in the registry.

type HookEntry added in v0.6.0

type HookEntry struct {
	Type      string    `json:"type"`
	Actor     string    `json:"actor"`
	Bead      string    `json:"bead,omitempty"`
	Timestamp time.Time `json:"timestamp"`
	TimeRel   string    `json:"time_relative"`
}

HookEntry represents a hook/unhook event for output.

type HookInfo

type HookInfo struct {
	Type     string   `json:"type"`     // Hook type (SessionStart, etc.)
	Location string   `json:"location"` // Path to the settings file
	Agent    string   `json:"agent"`    // Agent that owns this hook (e.g., "polecat/nux")
	Matcher  string   `json:"matcher"`  // Pattern matcher (empty = all)
	Commands []string `json:"commands"` // Hook commands
	Status   string   `json:"status"`   // "active" or "disabled"
}

HookInfo contains information about a discovered hook.

type HookRegistry added in v0.5.0

type HookRegistry struct {
	Hooks map[string]HookDefinition `toml:"hooks"`
}

HookRegistry represents the hooks/registry.toml structure.

func LoadRegistry added in v0.5.0

func LoadRegistry(townRoot string) (*HookRegistry, error)

LoadRegistry loads the hook registry from the town's hooks directory.

type HooksOutput

type HooksOutput struct {
	TownRoot string     `json:"town_root"`
	Hooks    []HookInfo `json:"hooks"`
	Count    int        `json:"count"`
}

HooksOutput is the JSON output structure.

type IdentityDetails added in v0.2.6

type IdentityDetails struct {
	IdentityInfo
	Title       string   `json:"title"`
	Description string   `json:"description,omitempty"`
	CreatedAt   string   `json:"created_at,omitempty"`
	UpdatedAt   string   `json:"updated_at,omitempty"`
	CVBeads     []string `json:"cv_beads,omitempty"`
}

IdentityDetails holds detailed identity information for show command.

type IdentityInfo added in v0.2.6

type IdentityInfo struct {
	Rig            string `json:"rig"`
	Name           string `json:"name"`
	BeadID         string `json:"bead_id"`
	AgentState     string `json:"agent_state,omitempty"`
	HookBead       string `json:"hook_bead,omitempty"`
	CleanupStatus  string `json:"cleanup_status,omitempty"`
	WorktreeExists bool   `json:"worktree_exists"`
	SessionRunning bool   `json:"session_running"`
}

IdentityInfo holds identity bead information for display.

type IntegrationStatusMRSummary

type IntegrationStatusMRSummary struct {
	ID     string `json:"id"`
	Title  string `json:"title"`
	Status string `json:"status,omitempty"`
}

IntegrationStatusMRSummary represents a merge request in the integration status output.

type IntegrationStatusOutput

type IntegrationStatusOutput struct {
	Epic            string                       `json:"epic"`
	Branch          string                       `json:"branch"`
	BaseBranch      string                       `json:"base_branch"`
	Created         string                       `json:"created,omitempty"`
	AheadOfBase     int                          `json:"ahead_of_base"`
	MergedMRs       []IntegrationStatusMRSummary `json:"merged_mrs"`
	PendingMRs      []IntegrationStatusMRSummary `json:"pending_mrs"`
	ReadyToLand     bool                         `json:"ready_to_land"`
	AutoLandEnabled bool                         `json:"auto_land_enabled"`
	ChildrenTotal   int                          `json:"children_total"`
	ChildrenClosed  int                          `json:"children_closed"`
}

IntegrationStatusOutput is the JSON output structure for integration status.

type IssueInfo added in v0.3.0

type IssueInfo struct {
	ID      string `json:"id"`
	Title   string `json:"title"`
	Type    string `json:"issue_type"`
	Status  string `json:"status"`
	Updated string `json:"updated_at"`
}

IssueInfo holds basic issue information for CV queries.

type LegOutput

type LegOutput struct {
	LegID    string `json:"leg_id"`
	Title    string `json:"title"`
	Status   string `json:"status"`
	FilePath string `json:"file_path,omitempty"`
	Content  string `json:"content,omitempty"`
	HasFile  bool   `json:"has_file"`
}

LegOutput represents collected output from a convoy leg.

type MQSummary

type MQSummary struct {
	Pending  int    `json:"pending"`   // Open MRs ready to merge (no blockers)
	InFlight int    `json:"in_flight"` // MRs currently being processed
	Blocked  int    `json:"blocked"`   // MRs waiting on dependencies
	State    string `json:"state"`     // idle, processing, or blocked
	Health   string `json:"health"`    // healthy, stale, or empty
}

MQSummary represents the merge queue status for a rig.

type MRStatusOutput

type MRStatusOutput struct {
	// Core issue fields
	ID        string `json:"id"`
	Title     string `json:"title"`
	Status    string `json:"status"`
	Priority  int    `json:"priority"`
	Type      string `json:"type"`
	Assignee  string `json:"assignee,omitempty"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
	ClosedAt  string `json:"closed_at,omitempty"`

	// MR-specific fields
	Branch      string `json:"branch,omitempty"`
	Target      string `json:"target,omitempty"`
	SourceIssue string `json:"source_issue,omitempty"`
	Worker      string `json:"worker,omitempty"`
	Rig         string `json:"rig,omitempty"`
	MergeCommit string `json:"merge_commit,omitempty"`
	CloseReason string `json:"close_reason,omitempty"`

	// Dependencies
	DependsOn []DependencyInfo `json:"depends_on,omitempty"`
	Blocks    []DependencyInfo `json:"blocks,omitempty"`
}

MRStatusOutput is the JSON output structure for gt mq status.

type MoleculeCurrentInfo

type MoleculeCurrentInfo struct {
	Identity      string `json:"identity"`
	HandoffID     string `json:"handoff_id,omitempty"`
	HandoffTitle  string `json:"handoff_title,omitempty"`
	MoleculeID    string `json:"molecule_id,omitempty"`
	MoleculeTitle string `json:"molecule_title,omitempty"`
	StepsComplete int    `json:"steps_complete"`
	StepsTotal    int    `json:"steps_total"`
	CurrentStepID string `json:"current_step_id,omitempty"`
	CurrentStep   string `json:"current_step,omitempty"`
	Status        string `json:"status"` // "working", "naked", "complete", "blocked"
}

MoleculeCurrentInfo contains info about what an agent should be working on.

type MoleculeCurrentOutput

type MoleculeCurrentOutput struct {
	MoleculeID    string `json:"molecule_id"`
	MoleculeTitle string `json:"molecule_title"`
	NextStep      *struct {
		ID          string `json:"id"`
		Title       string `json:"title"`
		Description string `json:"description"`
		Status      string `json:"status"`
	} `json:"next_step"`
	Completed int `json:"completed"`
	Total     int `json:"total"`
}

MoleculeCurrentOutput represents the JSON output of bd mol current.

type MoleculeProgressInfo

type MoleculeProgressInfo struct {
	RootID       string   `json:"root_id"`
	RootTitle    string   `json:"root_title"`
	MoleculeID   string   `json:"molecule_id,omitempty"`
	TotalSteps   int      `json:"total_steps"`
	DoneSteps    int      `json:"done_steps"`
	InProgress   int      `json:"in_progress_steps"`
	ReadySteps   []string `json:"ready_steps"`
	BlockedSteps []string `json:"blocked_steps"`
	Percent      int      `json:"percent_complete"`
	Complete     bool     `json:"complete"`
}

MoleculeProgressInfo contains progress information for a molecule instance.

type MoleculeStatusInfo

type MoleculeStatusInfo struct {
	Target           string                `json:"target"`
	Role             string                `json:"role"`
	AgentBeadID      string                `json:"agent_bead_id,omitempty"` // The agent bead if found
	HasWork          bool                  `json:"has_work"`
	PinnedBead       *beads.Issue          `json:"pinned_bead,omitempty"`
	AttachedMolecule string                `json:"attached_molecule,omitempty"`
	AttachedAt       string                `json:"attached_at,omitempty"`
	AttachedArgs     string                `json:"attached_args,omitempty"`
	IsWisp           bool                  `json:"is_wisp"`
	Progress         *MoleculeProgressInfo `json:"progress,omitempty"`
	NextAction       string                `json:"next_action,omitempty"`
}

MoleculeStatusInfo contains status information for an agent's work.

type OrphanBranch added in v0.8.0

type OrphanBranch struct {
	Polecat        string // Polecat name
	Branch         string // Branch name
	AheadCount     int    // Commits ahead of default branch
	LatestSubject  string // Subject of the latest commit
	HasUncommitted bool   // Whether the worktree has uncommitted changes
	WorktreePath   string // Actual resolved worktree path
}

OrphanBranch represents a polecat worktree with unmerged work.

type OrphanCommit

type OrphanCommit struct {
	SHA     string
	Date    time.Time
	Author  string
	Subject string
}

OrphanCommit represents an unreachable commit

type OrphanDB added in v0.9.0

type OrphanDB struct {
	Name string `json:"name"`
	Size string `json:"size,omitempty"`
}

type OrphanProcess added in v0.3.0

type OrphanProcess struct {
	PID  int
	Args string
}

OrphanProcess represents a Claude process that has become orphaned (PPID=1)

type OverseerInfo

type OverseerInfo struct {
	Name       string `json:"name"`
	Email      string `json:"email,omitempty"`
	Username   string `json:"username,omitempty"`
	Source     string `json:"source"`
	UnreadMail int    `json:"unread_mail"`
}

OverseerInfo represents the human operator's identity and status.

type PatrolConfig

type PatrolConfig struct {
	RoleName      string       // "deacon", "witness", "refinery"
	PatrolMolName string       // "mol-deacon-patrol", etc.
	BeadsDir      string       // where to look for beads
	Assignee      string       // agent identity for pinning
	HeaderEmoji   string       // display emoji
	HeaderTitle   string       // "Patrol Status", etc.
	WorkLoopSteps []string     // role-specific instructions
	ExtraVars     []string     // additional --var key=value args for wisp creation
	Beads         *beads.Beads // optional injected beads instance (for test isolation)
}

PatrolConfig holds role-specific patrol configuration.

type PatrolCycleEntry added in v0.3.1

type PatrolCycleEntry struct {
	ID          string    `json:"id"`
	Role        string    `json:"role"` // deacon, witness, refinery
	Title       string    `json:"title"`
	Description string    `json:"description"`
	CreatedAt   time.Time `json:"created_at"`
	ClosedAt    time.Time `json:"closed_at,omitempty"`
}

PatrolCycleEntry represents a single patrol cycle in the digest.

type PatrolDigest added in v0.3.1

type PatrolDigest struct {
	Date        string             `json:"date"`
	TotalCycles int                `json:"total_cycles"`
	ByRole      map[string]int     `json:"by_role"` // deacon, witness, refinery
	Cycles      []PatrolCycleEntry `json:"cycles"`
}

PatrolDigest represents the aggregated daily patrol report.

type PolecatListItem

type PolecatListItem struct {
	Rig            string        `json:"rig"`
	Name           string        `json:"name"`
	State          polecat.State `json:"state"`
	Issue          string        `json:"issue,omitempty"`
	SessionRunning bool          `json:"session_running"`
	Zombie         bool          `json:"zombie,omitempty"`
	SessionName    string        `json:"session_name,omitempty"`
}

PolecatListItem represents a polecat in list output.

type PolecatStatus

type PolecatStatus struct {
	Rig            string        `json:"rig"`
	Name           string        `json:"name"`
	State          polecat.State `json:"state"`
	Issue          string        `json:"issue,omitempty"`
	ClonePath      string        `json:"clone_path"`
	Branch         string        `json:"branch"`
	SessionRunning bool          `json:"session_running"`
	SessionID      string        `json:"session_id,omitempty"`
	Attached       bool          `json:"attached,omitempty"`
	Windows        int           `json:"windows,omitempty"`
	CreatedAt      string        `json:"created_at,omitempty"`
	LastActivity   string        `json:"last_activity,omitempty"`
}

PolecatStatus represents detailed polecat status for JSON output.

type PollutionRecord added in v0.9.0

type PollutionRecord struct {
	Database string `json:"database"`
	ID       string `json:"id"`
	Title    string `json:"title"`
	Pattern  string `json:"pattern"`
}

type ProcessHealth added in v0.9.0

type ProcessHealth struct {
	ZombieCount int   `json:"zombie_count"`
	ZombiePIDs  []int `json:"zombie_pids,omitempty"`
}

type QuotaStatusItem added in v0.8.0

type QuotaStatusItem struct {
	Handle    string `json:"handle"`
	Email     string `json:"email"`
	Status    string `json:"status"`
	LimitedAt string `json:"limited_at,omitempty"`
	ResetsAt  string `json:"resets_at,omitempty"`
	LastUsed  string `json:"last_used,omitempty"`
	IsDefault bool   `json:"is_default"`
}

QuotaStatusItem represents an account in status output.

type ReadyResult added in v0.3.0

type ReadyResult struct {
	Sources  []ReadySource `json:"sources"`
	Summary  ReadySummary  `json:"summary"`
	TownRoot string        `json:"town_root,omitempty"`
}

ReadyResult is the aggregated result of gt ready.

type ReadySource added in v0.3.0

type ReadySource struct {
	Name   string         `json:"name"`   // "town" or rig name
	Issues []*beads.Issue `json:"issues"` // Ready issues from this source
	Error  string         `json:"error,omitempty"`
}

ReadySource represents ready items from a single source (town or rig).

type ReadySummary added in v0.3.0

type ReadySummary struct {
	Total    int            `json:"total"`
	BySource map[string]int `json:"by_source"`
	P0Count  int            `json:"p0_count"`
	P1Count  int            `json:"p1_count"`
	P2Count  int            `json:"p2_count"`
	P3Count  int            `json:"p3_count"`
	P4Count  int            `json:"p4_count"`
}

ReadySummary provides counts for the ready report.

type RecentWorkItem added in v0.3.0

type RecentWorkItem struct {
	ID        string `json:"id"`
	Title     string `json:"title"`
	Type      string `json:"type,omitempty"`
	Completed string `json:"completed"`
	Ago       string `json:"ago"`
}

RecentWorkItem represents a recent work item in the CV.

type RecoveryStatus

type RecoveryStatus struct {
	Rig           string                `json:"rig"`
	Polecat       string                `json:"polecat"`
	CleanupStatus polecat.CleanupStatus `json:"cleanup_status"`
	NeedsRecovery bool                  `json:"needs_recovery"`
	Verdict       string                `json:"verdict"` // SAFE_TO_NUKE, NEEDS_RECOVERY, or NEEDS_MQ_SUBMIT
	Branch        string                `json:"branch,omitempty"`
	Issue         string                `json:"issue,omitempty"`
	MQStatus      string                `json:"mq_status,omitempty"` // "submitted", "not_submitted", "unknown"
}

RecoveryStatus represents whether a polecat needs recovery or is safe to nuke.

type RefineryStatusOutput added in v0.5.0

type RefineryStatusOutput struct {
	Running     bool   `json:"running"`
	RigName     string `json:"rig_name"`
	Session     string `json:"session,omitempty"`
	QueueLength int    `json:"queue_length"`
}

RefineryStatusOutput is the JSON output format for refinery status.

type ResolveTargetOptions added in v0.6.0

type ResolveTargetOptions struct {
	DryRun     bool
	Force      bool
	Create     bool
	Account    string
	Agent      string
	NoBoot     bool
	HookBead   string // Bead ID to set atomically during polecat spawn (empty = skip)
	BeadID     string // For cross-rig guard checks (empty = skip guard)
	TownRoot   string
	WorkDesc   string // Description for dog dispatch (defaults to HookBead if empty)
	BaseBranch string // Override base branch for polecat worktree
}

ResolveTargetOptions controls target resolution behavior.

type ResolvedTarget added in v0.6.0

type ResolvedTarget struct {
	Agent             string
	Pane              string
	WorkDir           string
	HookSetAtomically bool
	DelayedDogInfo    *DogDispatchInfo
	NewPolecatInfo    *SpawnedPolecatInfo
	IsSelfSling       bool
}

ResolvedTarget holds the results of target resolution.

type RigStatus

type RigStatus struct {
	Name         string          `json:"name"`
	Polecats     []string        `json:"polecats"`
	PolecatCount int             `json:"polecat_count"`
	Crews        []string        `json:"crews"`
	CrewCount    int             `json:"crew_count"`
	HasWitness   bool            `json:"has_witness"`
	HasRefinery  bool            `json:"has_refinery"`
	Hooks        []AgentHookInfo `json:"hooks,omitempty"`
	Agents       []AgentRuntime  `json:"agents,omitempty"` // Runtime state of all agents in rig
	MQ           *MQSummary      `json:"mq,omitempty"`     // Merge queue summary
}

RigStatus represents status of a single rig.

type Role

type Role string

Role represents a detected agent role.

const (
	RoleMayor    Role = "mayor"
	RoleDeacon   Role = "deacon"
	RoleBoot     Role = "boot"
	RoleWitness  Role = "witness"
	RoleRefinery Role = "refinery"
	RolePolecat  Role = "polecat"
	RoleCrew     Role = "crew"
	RoleDog      Role = "dog"
	RoleUnknown  Role = "unknown"
)

type RoleContext

type RoleContext = RoleInfo

RoleContext is an alias for RoleInfo for backward compatibility. New code should use RoleInfo directly.

type RoleInfo

type RoleInfo struct {
	Role          Role   `json:"role"`
	Source        string `json:"source"` // "env", "cwd", or "explicit"
	Home          string `json:"home"`
	Rig           string `json:"rig,omitempty"`
	Polecat       string `json:"polecat,omitempty"`
	EnvRole       string `json:"env_role,omitempty"`       // Value of GT_ROLE if set
	CwdRole       Role   `json:"cwd_role,omitempty"`       // Role detected from cwd
	Mismatch      bool   `json:"mismatch,omitempty"`       // True if env != cwd detection
	EnvIncomplete bool   `json:"env_incomplete,omitempty"` // True if env was set but missing rig/polecat, filled from cwd
	TownRoot      string `json:"town_root,omitempty"`
	WorkDir       string `json:"work_dir,omitempty"` // Current working directory
}

RoleInfo contains information about a role and its detection source. This is the canonical struct for role detection - used by both GetRole() and detectRole() functions.

func GetRole

func GetRole() (RoleInfo, error)

GetRole returns the current role, checking GT_ROLE first then falling back to cwd. This is the canonical function for role detection.

func GetRoleWithContext

func GetRoleWithContext(cwd, townRoot string) (RoleInfo, error)

GetRoleWithContext returns role info given explicit cwd and town root.

func (RoleInfo) ActorString

func (info RoleInfo) ActorString() string

ActorString returns the actor identity string for beads attribution. Format matches beads created_by convention:

  • Simple roles: "mayor", "deacon"
  • Dog roles: "deacon-boot" (hyphenated, matching BD_ACTOR)
  • Rig-specific: "gastown/witness", "gastown/refinery"
  • Workers: "gastown/crew/max", "gastown/polecats/Toast"

type SafetyCheckResult added in v0.2.4

type SafetyCheckResult struct {
	Polecat       string
	Blocked       bool
	Reasons       []string
	CleanupStatus polecat.CleanupStatus
	HookBead      string
	HookStale     bool // true if hooked bead is closed
	OpenMR        string
	GitState      *GitState
}

SafetyCheckResult holds the result of safety checks for a polecat.

type ScheduleOptions added in v0.8.0

type ScheduleOptions struct {
	Formula     string   // Formula to apply at dispatch time (e.g., "mol-polecat-work")
	Args        string   // Natural language args for executor
	Vars        []string // Formula variables (key=value)
	Merge       string   // Merge strategy: direct/mr/local
	BaseBranch  string   // Override base branch for polecat worktree
	NoConvoy    bool     // Skip auto-convoy creation
	Owned       bool     // Mark auto-convoy as caller-managed lifecycle
	DryRun      bool     // Show what would be done without acting
	Force       bool     // Force schedule even if bead is hooked/in_progress
	NoMerge     bool     // Skip merge queue on completion
	Account     string   // Claude Code account handle
	Agent       string   // Agent override (e.g., "gemini", "codex")
	HookRawBead bool     // Hook raw bead without default formula
	Ralph       bool     // Ralph Wiggum loop mode
}

ScheduleOptions holds options for scheduling a bead.

type ServerHealth added in v0.9.0

type ServerHealth struct {
	Running        bool   `json:"running"`
	PID            int    `json:"pid,omitempty"`
	Port           int    `json:"port,omitempty"`
	LatencyMs      int64  `json:"latency_ms,omitempty"`
	Connections    int    `json:"connections,omitempty"`
	MaxConnections int    `json:"max_connections,omitempty"`
	DiskUsageBytes int64  `json:"disk_usage_bytes,omitempty"`
	DiskUsageHuman string `json:"disk_usage_human,omitempty"`
}

type ServiceInfo added in v0.9.0

type ServiceInfo struct {
	Running bool `json:"running"`
	PID     int  `json:"pid,omitempty"`
}

ServiceInfo represents a background service status.

type ServiceStatus added in v0.8.0

type ServiceStatus struct {
	Name   string `json:"name"`
	Type   string `json:"type"` // daemon, deacon, mayor, witness, refinery, crew, polecat
	Rig    string `json:"rig,omitempty"`
	OK     bool   `json:"ok"`
	Detail string `json:"detail"`
}

ServiceStatus represents the status of a single service.

type SessionCost added in v0.2.0

type SessionCost struct {
	Session string  `json:"session"`
	Role    string  `json:"role"`
	Rig     string  `json:"rig,omitempty"`
	Worker  string  `json:"worker,omitempty"`
	Cost    float64 `json:"cost_usd"`
	Running bool    `json:"running"`
}

SessionCost represents cost info for a single session.

type SessionEvent added in v0.2.0

type SessionEvent struct {
	ID        string    `json:"id"`
	Title     string    `json:"title"`
	Status    string    `json:"status"`
	CreatedAt time.Time `json:"created_at"`
	EventKind string    `json:"event_kind"`
	Actor     string    `json:"actor"`
	Target    string    `json:"target"`
	Payload   string    `json:"payload"`
}

SessionEvent represents a session.ended event from beads.

type SessionListItem

type SessionListItem struct {
	Rig       string `json:"rig"`
	Polecat   string `json:"polecat"`
	SessionID string `json:"session_id"`
	Running   bool   `json:"running"`
}

SessionListItem represents a session in list output.

type SessionPayload added in v0.2.0

type SessionPayload struct {
	CostUSD   float64 `json:"cost_usd"`
	SessionID string  `json:"session_id"`
	Role      string  `json:"role"`
	Rig       string  `json:"rig"`
	Worker    string  `json:"worker"`
	EndedAt   string  `json:"ended_at"`
}

SessionPayload represents the JSON payload of a session event.

type SessionState added in v0.2.4

type SessionState struct {
	State         string `json:"state"`                    // normal, post-handoff, crash-recovery, autonomous
	Role          Role   `json:"role"`                     // detected role
	PrevSession   string `json:"prev_session,omitempty"`   // for post-handoff
	CheckpointAge string `json:"checkpoint_age,omitempty"` // for crash-recovery
	HookedBead    string `json:"hooked_bead,omitempty"`    // for autonomous
}

SessionState represents the detected session state for observability.

type SilentExitError

type SilentExitError struct {
	Code int
}

SilentExitError signals that the command should exit with a specific code without printing an error message. This is used for scripting purposes where exit codes convey status (e.g., "no mail" = exit 1).

func NewSilentExit

func NewSilentExit(code int) *SilentExitError

NewSilentExit creates a SilentExitError with the given exit code.

func (*SilentExitError) Error

func (e *SilentExitError) Error() string

type SlingParams added in v0.8.0

type SlingParams struct {
	// What to sling
	BeadID      string // Base bead
	FormulaName string // Formula to apply ("mol-polecat-work", user formula, or "")
	RigName     string // Target rig (always a rig for queue)

	// CLI flag passthrough
	Args        string   // --args
	Vars        []string // --var (key=value pairs)
	Merge       string   // --merge (convoy strategy)
	BaseBranch  string   // --base-branch
	Account     string   // --account
	Agent       string   // --agent
	NoConvoy    bool     // --no-convoy
	Owned       bool     // --owned
	NoMerge     bool     // --no-merge
	Force       bool     // --force
	HookRawBead bool     // --hook-raw-bead
	NoBoot      bool     // --no-boot
	Mode        string   // --ralph: "" (normal) or "ralph"

	// Execution behavior (set by caller, not serialized to queue)
	SkipCook         bool   // Batch optimization: formula already cooked
	FormulaFailFatal bool   // true=rollback+error (single/queue), false=hook raw bead (batch)
	CallerContext    string // Identifies the caller for shutdown messages (e.g., "queue-dispatch", "batch-sling")
	TownRoot         string
	BeadsDir         string
}

SlingParams captures everything needed to sling one bead to a rig. This is the serialization boundary for queue dispatch: at enqueue time, these fields are stored as queue metadata; at dispatch time, they are reconstructed into a SlingParams and passed to executeSling().

type SlingResult added in v0.8.0

type SlingResult struct {
	BeadID           string
	PolecatName      string
	SpawnInfo        *SpawnedPolecatInfo
	Success          bool
	ErrMsg           string
	AttachedMolecule string
}

SlingResult captures the outcome of executeSling for caller-level tracking.

type SlingSpawnOptions

type SlingSpawnOptions struct {
	Force      bool   // Force spawn even if polecat has uncommitted work
	Account    string // Claude Code account handle to use
	Create     bool   // Create polecat if it doesn't exist (currently always true for sling)
	HookBead   string // Bead ID to set as hook_bead at spawn time (atomic assignment)
	Agent      string // Agent override for this spawn (e.g., "gemini", "codex", "claude-haiku")
	BaseBranch string // Override base branch for polecat worktree (e.g., "develop", "release/v2")
}

SlingSpawnOptions contains options for spawning a polecat via sling.

type SpawnedPolecatInfo

type SpawnedPolecatInfo struct {
	RigName     string // Rig name (e.g., "gastown")
	PolecatName string // Polecat name (e.g., "Toast")
	ClonePath   string // Path to polecat's git worktree
	SessionName string // Tmux session name (e.g., "gt-gastown-p-Toast")
	Pane        string // Tmux pane ID (empty until StartSession is called)
	BaseBranch  string // Effective base branch (e.g., "main", "integration/epic-id")
	Branch      string // Git branch name (for cleanup on rollback)
	// contains filtered or unexported fields
}

SpawnedPolecatInfo contains info about a spawned polecat session.

func SpawnPolecatForSling

func SpawnPolecatForSling(rigName string, opts SlingSpawnOptions) (*SpawnedPolecatInfo, error)

SpawnPolecatForSling creates a fresh polecat and optionally starts its session. This is used by gt sling when the target is a rig name. The caller (sling) handles hook attachment and nudging.

func (*SpawnedPolecatInfo) AgentID

func (s *SpawnedPolecatInfo) AgentID() string

AgentID returns the agent identifier (e.g., "gastown/polecats/Toast")

func (*SpawnedPolecatInfo) SessionStarted added in v0.6.0

func (s *SpawnedPolecatInfo) SessionStarted() bool

SessionStarted returns true if the tmux session has been started.

func (*SpawnedPolecatInfo) StartSession added in v0.6.0

func (s *SpawnedPolecatInfo) StartSession() (string, error)

StartSession starts the tmux session for a spawned polecat. This is called after the molecule/bead is attached, so the polecat sees its work when gt prime runs on session start. Returns the pane ID after session start.

type StageInput added in v0.8.0

type StageInput struct {
	Kind    StageInputKind
	IDs     []string // bead IDs to process
	RawArgs []string // original args for error messages
}

StageInput represents parsed and validated input for gt convoy stage.

type StageInputKind added in v0.8.0

type StageInputKind int

StageInputKind identifies the type of input provided to gt convoy stage.

const (
	StageInputEpic   StageInputKind = iota // single epic ID → walk children
	StageInputTasks                        // one or more task IDs → analyze as-is
	StageInputConvoy                       // single convoy ID → read tracked beads
)

type StageResult added in v0.8.0

type StageResult struct {
	Status   string         `json:"status"`    // "staged_ready", "staged_warnings", or "error"
	ConvoyID string         `json:"convoy_id"` // empty if errors prevented creation
	Restaged bool           `json:"restaged"`  // true if an existing convoy was updated in place
	Errors   []FindingJSON  `json:"errors"`
	Warnings []FindingJSON  `json:"warnings"`
	Waves    []WaveJSON     `json:"waves"`
	Tree     []TreeNodeJSON `json:"tree"`
}

StageResult is the top-level JSON output for gt convoy stage --json.

type StagingFinding added in v0.8.0

type StagingFinding struct {
	Severity     string   // "error" or "warning"
	Category     string   // "cycle", "no-rig", "orphan", "blocked-rig", "cross-rig", "capacity", "missing-branch"
	BeadIDs      []string // affected bead IDs
	Message      string   // human-readable description
	SuggestedFix string   // actionable fix suggestion
}

StagingFinding represents an error or warning found during convoy staging analysis.

type StaleOutput added in v0.2.6

type StaleOutput struct {
	Stale         bool   `json:"stale"`
	BinaryCommit  string `json:"binary_commit"`
	RepoCommit    string `json:"repo_commit"`
	CommitsBehind int    `json:"commits_behind,omitempty"`
	Error         string `json:"error,omitempty"`
}

StaleOutput represents the JSON output structure.

type StatusSum

type StatusSum struct {
	RigCount      int `json:"rig_count"`
	PolecatCount  int `json:"polecat_count"`
	CrewCount     int `json:"crew_count"`
	WitnessCount  int `json:"witness_count"`
	RefineryCount int `json:"refinery_count"`
	ActiveHooks   int `json:"active_hooks"`
}

StatusSum provides summary counts.

type StepDoneResult

type StepDoneResult struct {
	StepID        string   `json:"step_id"`
	MoleculeID    string   `json:"molecule_id"`
	StepClosed    bool     `json:"step_closed"`
	NextStepID    string   `json:"next_step_id,omitempty"`
	NextStepTitle string   `json:"next_step_title,omitempty"`
	ParallelSteps []string `json:"parallel_steps,omitempty"` // Multiple ready steps for fan-out
	Complete      bool     `json:"complete"`
	Action        string   `json:"action"` // "continue", "parallel", "done", "no_more_ready"
}

StepDoneResult is the result of a step done operation.

type TaskJSON added in v0.8.0

type TaskJSON struct {
	ID        string   `json:"id"`
	Title     string   `json:"title"`
	Type      string   `json:"type"`
	Rig       string   `json:"rig"`
	BlockedBy []string `json:"blocked_by,omitempty"`
}

TaskJSON is the JSON representation of a task within a wave.

type TmuxInfo added in v0.9.0

type TmuxInfo struct {
	Socket       string `json:"socket"`                // Socket name (e.g., "mytown" or "default")
	SocketPath   string `json:"socket_path,omitempty"` // Full socket path
	Running      bool   `json:"running"`               // Is the tmux server running?
	SessionCount int    `json:"session_count"`         // Number of sessions
}

TmuxInfo represents the tmux server status.

type TokenUsage added in v0.6.0

type TokenUsage struct {
	Model                    string
	InputTokens              int
	CacheCreationInputTokens int
	CacheReadInputTokens     int
	OutputTokens             int
}

TokenUsage aggregates token usage across a session.

type TownStatus

type TownStatus struct {
	Name     string         `json:"name"`
	Location string         `json:"location"`
	Overseer *OverseerInfo  `json:"overseer,omitempty"` // Human operator
	Daemon   *ServiceInfo   `json:"daemon,omitempty"`   // Daemon status
	Dolt     *DoltInfo      `json:"dolt,omitempty"`     // Dolt server status
	Tmux     *TmuxInfo      `json:"tmux,omitempty"`     // Tmux server status
	Agents   []AgentRuntime `json:"agents"`             // Global agents (Mayor, Deacon)
	Rigs     []RigStatus    `json:"rigs"`
	Summary  StatusSum      `json:"summary"`
}

TownStatus represents the overall status of the workspace.

type TranscriptMessage added in v0.6.0

type TranscriptMessage struct {
	Type      string                 `json:"type"`
	SessionID string                 `json:"sessionId"`
	CWD       string                 `json:"cwd"`
	Message   *TranscriptMessageBody `json:"message,omitempty"`
}

TranscriptMessage represents a message from a Claude Code transcript file.

type TranscriptMessageBody added in v0.6.0

type TranscriptMessageBody struct {
	Model string           `json:"model"`
	Role  string           `json:"role"`
	Usage *TranscriptUsage `json:"usage,omitempty"`
}

TranscriptMessageBody contains the message content and usage info.

type TranscriptUsage added in v0.6.0

type TranscriptUsage struct {
	InputTokens              int `json:"input_tokens"`
	CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
	CacheReadInputTokens     int `json:"cache_read_input_tokens"`
	OutputTokens             int `json:"output_tokens"`
}

TranscriptUsage contains token usage information.

type TreeNodeJSON added in v0.8.0

type TreeNodeJSON struct {
	ID       string         `json:"id"`
	Title    string         `json:"title"`
	Type     string         `json:"type"`
	Status   string         `json:"status"`
	Rig      string         `json:"rig,omitempty"`
	Children []TreeNodeJSON `json:"children,omitempty"`
}

TreeNodeJSON is the JSON representation of a DAG node in a nested tree.

type UpOutput added in v0.8.0

type UpOutput struct {
	Success  bool            `json:"success"`
	Services []ServiceStatus `json:"services"`
	Summary  UpSummary       `json:"summary"`
}

UpOutput represents the JSON output of the up command.

type UpSummary added in v0.8.0

type UpSummary struct {
	Total   int `json:"total"`
	Started int `json:"started"`
	Failed  int `json:"failed"`
}

UpSummary provides counts for the up command output.

type VersionChange added in v0.2.0

type VersionChange struct {
	Version string   `json:"version"`
	Date    string   `json:"date"`
	Changes []string `json:"changes"`
}

VersionChange represents agent-relevant changes for a specific version

type Warrant added in v0.6.0

type Warrant struct {
	ID         string     `json:"id"`
	Target     string     `json:"target"` // e.g., "gastown/polecats/alpha", "deacon/dogs/bravo"
	Reason     string     `json:"reason"`
	FiledBy    string     `json:"filed_by"`
	FiledAt    time.Time  `json:"filed_at"`
	Executed   bool       `json:"executed,omitempty"`
	ExecutedAt *time.Time `json:"executed_at,omitempty"`
}

Warrant represents a death warrant for an agent

type Wave added in v0.8.0

type Wave struct {
	Number int
	Tasks  []string // bead IDs, sorted for determinism
}

Wave represents a group of tasks that can execute in parallel.

type WaveJSON added in v0.8.0

type WaveJSON struct {
	Number int        `json:"number"`
	Tasks  []TaskJSON `json:"tasks"`
}

WaveJSON is the JSON representation of a Wave with task details.

type WitnessStatusOutput added in v0.5.0

type WitnessStatusOutput struct {
	Running           bool     `json:"running"`
	RigName           string   `json:"rig_name"`
	Session           string   `json:"session,omitempty"`
	MonitoredPolecats []string `json:"monitored_polecats,omitempty"`
}

WitnessStatusOutput is the JSON output format for witness status.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL