agent

package
v0.0.0-...-3921fd5 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package agent orchestrates the high-level agent lifecycle by composing the IRC client, protocol handler, dependency coordinator, context sharing, health monitoring, metrics collection, and web dashboard into a single runnable unit.

Index

Constants

View Source
const (
	RoleArchitectureReviewer = "architecture-reviewer"
	RoleSecurityReviewer     = "security-reviewer"
	RoleMonitoringGuardian   = "monitoring-guardian"
	RoleTestCoverageEnforcer = "test-coverage-enforcer"
	RoleMergeCoordinator     = "merge-coordinator"
	RoleReleaseCoordinator   = "release-coordinator"
	RoleCleanupAgent         = "cleanup-agent"
	RoleIncidentResponder    = "incident-responder"
	RoleTechDebtTracker      = "tech-debt-tracker"
)

Role constants for built-in agent roles.

Variables

This section is empty.

Functions

func DefaultNotificationFormatter

func DefaultNotificationFormatter(event NotificationEvent, msg *protocol.Message) string

DefaultNotificationFormatter formats notifications in a human-readable style.

func FormatUnblockMessage

func FormatUnblockMessage(unblockedTask, completedTask string) string

FormatUnblockMessage returns the default unblock notification string.

func IsFederatedMessage

func IsFederatedMessage(msg string) bool

IsFederatedMessage returns true if the message has a [fed:...] prefix.

Types

type ACLEngine

type ACLEngine struct {
	// contains filtered or unexported fields
}

ACLEngine evaluates authorization rules for protocol messages. Rules are evaluated in order; first match wins. No match = allow (backward compatible).

func NewACLEngine

func NewACLEngine(rules []config.ACLRule) *ACLEngine

NewACLEngine creates an ACLEngine with the given rules.

func (*ACLEngine) Check

func (e *ACLEngine) Check(nick, channel string, action protocol.Action) bool

Check returns true if the given nick/channel/action is allowed. First matching rule wins; no match = allow.

func (*ACLEngine) SetRules

func (e *ACLEngine) SetRules(rules []config.ACLRule)

SetRules replaces the rule set (hot-reload).

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

Agent orchestrates the IRC client, event handlers, and lifecycle management.

func New

func New(cfg *config.AppConfig) (*Agent, error)

New creates an Agent from an AppConfig.

func NewWithClient

func NewWithClient(cfg *config.AppConfig, client ircclient.Client) *Agent

NewWithClient creates an Agent using a pre-built Client (useful for testing).

func (*Agent) AcceptTask

func (a *Agent) AcceptTask(channel, task string) error

AcceptTask sends an ACCEPT message for an assigned task.

func (*Agent) AddNotificationRule

func (a *Agent) AddNotificationRule(rule NotificationRule)

AddNotificationRule adds a rule for routing protocol events to notification channels.

func (*Agent) AgentNotifier

func (a *Agent) AgentNotifier() *Notifier

AgentNotifier returns the agent's notifier for direct configuration.

func (*Agent) AnnounceBlocked

func (a *Agent) AnnounceBlocked(channel, task, waitingFor string, tags ...string) error

AnnounceBlocked sends a BLOCKED message for a task.

func (*Agent) AnnounceCapabilities

func (a *Agent) AnnounceCapabilities(channel string) error

AnnounceCapabilities sends this agent's CAPABILITIES to a specific channel.

func (*Agent) AnnounceCompleted

func (a *Agent) AnnounceCompleted(channel, task string, tags ...string) error

AnnounceCompleted sends a COMPLETED message for a task.

func (*Agent) AnnounceStarted

func (a *Agent) AnnounceStarted(channel, task, priority string, tags ...string) error

AnnounceStarted sends a STARTED message for a task.

func (*Agent) AssignTask

func (a *Agent) AssignTask(channel, task, to string) error

AssignTask sends an ASSIGN message delegating a task to another agent.

func (*Agent) Checkpoint

func (a *Agent) Checkpoint(channel, task string, progress int, summary string) error

Checkpoint sends a CHECKPOINT message reporting progress on a task.

func (*Agent) ClaimTask

func (a *Agent) ClaimTask(channel, task string, load int) error

ClaimTask sends a CLAIM message for a task.

func (*Agent) CompleteReview

func (a *Agent) CompleteReview(channel, task, pr string, verdict ReviewVerdict, details string) error

CompleteReview sends a REVIEW-COMPLETE message with a verdict.

func (*Agent) ConsensusStore

func (a *Agent) ConsensusStore() *ConsensusStore

ConsensusStore returns the agent's consensus store.

func (*Agent) ContextEntries

func (a *Agent) ContextEntries() *ContextStore

ContextEntries returns the agent's context store for read access.

func (*Agent) DeclineTask

func (a *Agent) DeclineTask(channel, task, reason string) error

DeclineTask sends a DECLINE message for an assigned task.

func (*Agent) Discover

func (a *Agent) Discover(channel, expertise string) error

Discover sends a DISCOVER request to a channel for agents with specific expertise.

func (*Agent) Escalate

func (a *Agent) Escalate(channel, task, to, reason, severity string) error

Escalate sends an ESCALATE message to a human operator.

func (*Agent) GateCheck

func (a *Agent) GateCheck(channel, task, gate string, status GateStatus, details string) error

GateCheck sends a GATE-CHECK message reporting a gate status.

func (*Agent) Handoff

func (a *Agent) Handoff(channel, task, to, contextID string) error

Handoff sends a HANDOFF message transferring a task to another agent.

func (*Agent) HandoffStore

func (a *Agent) HandoffStore() *HandoffStore

HandoffStore returns the agent's handoff store.

func (*Agent) Health

func (a *Agent) Health() *HealthMonitor

Health returns the agent's health monitor.

func (*Agent) Inspector

func (a *Agent) Inspector() *DebugInspector

Inspector returns the agent's debug inspector.

func (*Agent) KnownAgents

func (a *Agent) KnownAgents() []*AgentCapability

KnownAgents returns all non-expired agent capabilities from the discovery store.

func (*Agent) Metrics

func (a *Agent) Metrics() *MetricsCollector

Metrics returns the agent's metrics collector.

func (*Agent) NotifyBlockedTo

func (a *Agent) NotifyBlockedTo(channel string)

NotifyBlockedTo adds a rule to send task blocked notifications to a channel.

func (*Agent) NotifyCompletionsTo

func (a *Agent) NotifyCompletionsTo(channel string)

NotifyCompletionsTo adds a rule to send task completion notifications to a channel.

func (*Agent) NotifyHelpTo

func (a *Agent) NotifyHelpTo(channel string)

NotifyHelpTo adds a rule to send help-needed notifications to a channel.

func (*Agent) OfferTask

func (a *Agent) OfferTask(channel, task, priority, scope string, tags ...string) error

OfferTask sends an OFFER message for a task.

func (*Agent) OnProtocolMessage

func (a *Agent) OnProtocolMessage(handler ProtocolHandler) int

OnProtocolMessage registers a handler for incoming protocol messages.

func (*Agent) PendingContextRequests

func (a *Agent) PendingContextRequests() []*ContextRequest

PendingContextRequests returns all unfulfilled context requests.

func (*Agent) RequestContext

func (a *Agent) RequestContext(channel, component string) error

RequestContext sends a REQUEST-CONTEXT message for a component.

func (*Agent) RequestHelp

func (a *Agent) RequestHelp(channel, task, expertise string, tags ...string) error

RequestHelp sends a HELP-NEEDED message for a task.

func (*Agent) RequestReview

func (a *Agent) RequestReview(channel, task, pr, reviewType string) error

RequestReview sends a REVIEW-REQUEST message for a task.

func (*Agent) ReviewStore

func (a *Agent) ReviewStore() *ReviewStore

ReviewStore returns the agent's review store.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context) error

Run blocks until the agent is shut down (via signal or context cancellation).

func (*Agent) SendProtocolMessage

func (a *Agent) SendProtocolMessage(target string, msg *protocol.Message) error

SendProtocolMessage sends a protocol message to a target channel or user. The message is sanitized before sending. It also updates the local state store so the agent tracks its own actions (the dispatcher skips self-echo).

func (*Agent) ShareContext

func (a *Agent) ShareContext(channel, component, project, status string) error

ShareContext sends a CONTEXT announcement message.

func (*Agent) Shutdown

func (a *Agent) Shutdown()

Shutdown performs a graceful shutdown: stops dashboard, parts channels, disconnects.

func (*Agent) Start

func (a *Agent) Start(ctx context.Context) error

Start connects the agent to the IRC server and optionally starts the dashboard.

func (*Agent) State

func (a *Agent) State() *StateStore

State returns the agent's task state store for read access.

func (*Agent) SubscribeContext

func (a *Agent) SubscribeContext(component string, handler func(*ContextEntry)) int

SubscribeContext registers a callback for context updates on a component.

func (*Agent) TaskBoard

func (a *Agent) TaskBoard() *TaskBoard

TaskBoard returns the agent's task board store.

func (*Agent) UnsubscribeContext

func (a *Agent) UnsubscribeContext(id int)

UnsubscribeContext removes a context subscription.

func (*Agent) Vote

func (a *Agent) Vote(channel, topic, choice string) error

Vote sends a VOTE message on a topic.

func (*Agent) WorkflowEngine

func (a *Agent) WorkflowEngine() *WorkflowEngine

WorkflowEngine returns the agent's workflow engine.

func (*Agent) YieldTask

func (a *Agent) YieldTask(channel, task, reason string) error

YieldTask sends a YIELD message returning a task to the pool.

type AgentActivitySummary

type AgentActivitySummary struct {
	Nick      string    `json:"nick"`
	Channel   string    `json:"channel"`
	TaskName  string    `json:"task"`
	UpdatedAt time.Time `json:"updated_at"`
}

AgentActivitySummary represents a summary of an agent's current activity.

type AgentCapability

type AgentCapability struct {
	Nick        string    `json:"nick"`
	Expertise   []string  `json:"expertise"`
	Channels    []string  `json:"channels"`
	CurrentTask string    `json:"current_task"`
	UpdatedAt   time.Time `json:"updated_at"`
	ExpiresAt   time.Time `json:"expires_at"`
	Role        string    `json:"role,omitempty"`
	Load        int       `json:"load,omitempty"`
	MaxLoad     int       `json:"max_load,omitempty"`
	ActiveTasks []string  `json:"active_tasks,omitempty"`
}

AgentCapability describes an agent's advertised capabilities.

type AgentStatus

type AgentStatus struct {
	Nick      string
	Channel   string
	TaskName  string
	UpdatedAt time.Time
}

AgentStatus tracks what an agent is currently doing.

type BlockedChainEntry

type BlockedChainEntry struct {
	TaskName string `json:"task"`
	Status   string `json:"status"`
	Resolved bool   `json:"resolved"`
}

BlockedChainEntry represents a single entry in a blocked dependency chain.

type CheckpointRecord

type CheckpointRecord struct {
	Task      string
	Nick      string
	Progress  int
	Summary   string
	Channel   string
	Timestamp time.Time
}

CheckpointRecord tracks an incremental progress report for a task.

type ClaimEntry

type ClaimEntry struct {
	Nick      string
	Load      int
	ClaimedAt time.Time
}

ClaimEntry records an agent's claim on an offered task.

type ConsensusStore

type ConsensusStore struct {
	// contains filtered or unexported fields
}

ConsensusStore tracks votes and escalations.

func NewConsensusStore

func NewConsensusStore() *ConsensusStore

NewConsensusStore creates a new ConsensusStore.

func (*ConsensusStore) ListEscalations

func (cs *ConsensusStore) ListEscalations() []*EscalationRecord

ListEscalations returns all escalation records.

func (*ConsensusStore) ListTopics

func (cs *ConsensusStore) ListTopics() []TopicSummary

ListTopics returns summaries for all voted-on topics.

func (*ConsensusStore) RecordEscalation

func (cs *ConsensusStore) RecordEscalation(task, toNick, reason, severity, escalatedBy, channel string)

RecordEscalation records an escalation event.

func (*ConsensusStore) RecordVote

func (cs *ConsensusStore) RecordVote(topic, nick, choice, channel string)

RecordVote records or updates a vote. Last vote per nick wins.

func (*ConsensusStore) ResolveEscalation

func (cs *ConsensusStore) ResolveEscalation(task string)

ResolveEscalation marks the most recent escalation for a task as resolved.

func (*ConsensusStore) TopicSummaryFor

func (cs *ConsensusStore) TopicSummaryFor(topic string) TopicSummary

TopicSummaryFor returns a summary of votes for a topic.

type ContextEntry

type ContextEntry struct {
	Component string
	Project   string
	Status    string
	Payload   string
	SharedBy  string
	UpdatedAt time.Time
}

ContextEntry holds shared context for a component.

type ContextRequest

type ContextRequest struct {
	Component   string
	RequestedBy string
	Channel     string
	RequestedAt time.Time
	Fulfilled   bool
	FulfilledAt time.Time
}

ContextRequest tracks an incoming REQUEST-CONTEXT message.

type ContextStore

type ContextStore struct {
	// contains filtered or unexported fields
}

ContextStore tracks context announcements and payloads. It is thread-safe and keyed by component name.

func NewContextStore

func NewContextStore() *ContextStore

NewContextStore creates an empty ContextStore.

func (*ContextStore) FulfillRequest

func (cs *ContextStore) FulfillRequest(component string)

FulfillRequest marks all pending requests for the given component as fulfilled.

func (*ContextStore) Get

func (cs *ContextStore) Get(component string) *ContextEntry

Get returns the context entry for a component, or nil if not found.

func (*ContextStore) HandleContextRequest

func (cs *ContextStore) HandleContextRequest(msg *protocol.Message, client ircclient.Client)

HandleContextRequest responds to a REQUEST-CONTEXT message by sending the stored context for the requested component.

func (*ContextStore) ListEntries

func (cs *ContextStore) ListEntries() []*ContextEntry

ListEntries returns all stored context entries.

func (*ContextStore) PendingRequests

func (cs *ContextStore) PendingRequests() []*ContextRequest

PendingRequests returns all unfulfilled context requests.

func (*ContextStore) Store

func (cs *ContextStore) Store(msg *protocol.Message)

Store records a CONTEXT announcement message. It also fulfills pending requests for the component and fires subscription callbacks.

func (*ContextStore) StorePayload

func (cs *ContextStore) StorePayload(msg *protocol.Message)

StorePayload records a SHARING-CONTEXT payload, associating it with the most recently requested component from the sender.

func (*ContextStore) Subscribe

func (cs *ContextStore) Subscribe(component string, handler func(*ContextEntry)) int

Subscribe registers a callback that fires when context for the given component is stored. Returns a subscription ID for later removal.

func (*ContextStore) TimedOutRequests

func (cs *ContextStore) TimedOutRequests(timeout time.Duration) []*ContextRequest

TimedOutRequests returns unfulfilled requests older than the given timeout.

func (*ContextStore) TrackRequest

func (cs *ContextStore) TrackRequest(msg *protocol.Message)

TrackRequest records an incoming REQUEST-CONTEXT message.

func (*ContextStore) Unsubscribe

func (cs *ContextStore) Unsubscribe(id int)

Unsubscribe removes a previously registered subscription.

type Dashboard

type Dashboard struct {
	// contains filtered or unexported fields
}

Dashboard provides an HTTP server with JSON APIs and an HTML dashboard for monitoring agent health, metrics, tasks, and messages.

func NewDashboard

func NewDashboard(
	addr string,
	health *HealthMonitor,
	metrics *MetricsCollector,
	inspector *DebugInspector,
	state *StateStore,
	context *ContextStore,
	discovery *DiscoveryStore,
	taskBoard *TaskBoard,
	handoff *HandoffStore,
	review *ReviewStore,
	consensus *ConsensusStore,
) *Dashboard

NewDashboard creates a Dashboard wired to the given components.

func (*Dashboard) ListenAddr

func (d *Dashboard) ListenAddr() string

ListenAddr returns the address the dashboard is actually listening on.

func (*Dashboard) Shutdown

func (d *Dashboard) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the dashboard HTTP server.

func (*Dashboard) Start

func (d *Dashboard) Start() error

Start begins serving the HTTP dashboard in a background goroutine.

type DebugInspector

type DebugInspector struct {
	// contains filtered or unexported fields
}

DebugInspector provides debugging and inspection capabilities for the agent. It maintains a ring buffer of recent messages and provides methods to query the task graph and dependency chains.

func NewDebugInspector

func NewDebugInspector(state *StateStore, context *ContextStore, maxLogEntries int) *DebugInspector

NewDebugInspector creates a DebugInspector with the given ring buffer capacity.

func (*DebugInspector) AgentActivity

func (d *DebugInspector) AgentActivity() []AgentActivitySummary

AgentActivity returns a summary of all known agent activity.

func (*DebugInspector) BlockedChain

func (d *DebugInspector) BlockedChain(taskName string) []BlockedChainEntry

BlockedChain returns the transitive dependency chain for a task. Each entry includes the task name, its status, and whether the dependency is resolved.

func (*DebugInspector) RecentMessages

func (d *DebugInspector) RecentMessages(n int) []MessageLogEntry

RecentMessages returns the most recent n messages from the ring buffer, ordered from oldest to newest.

func (*DebugInspector) RecordMessage

func (d *DebugInspector) RecordMessage(entry MessageLogEntry)

RecordMessage adds a message to the ring buffer.

func (*DebugInspector) TaskGraph

func (d *DebugInspector) TaskGraph() []TaskGraphNode

TaskGraph returns all tasks with their dependency edges.

type DependencyEdge

type DependencyEdge struct {
	Blocked    string // task name that is blocked
	BlockedBy  string // task name that is blocking
	Resolved   bool
	ResolvedAt time.Time
}

DependencyEdge represents a dependency between two tasks.

type DependencyStatsInfo

type DependencyStatsInfo struct {
	TotalEdges      int
	ResolvedEdges   int
	UnresolvedEdges int
	BlockedTasks    int
	UnblockedTasks  int
}

DependencyStatsInfo holds aggregate statistics about the dependency graph.

type DiscoveryStore

type DiscoveryStore struct {
	// contains filtered or unexported fields
}

DiscoveryStore tracks known agents and their capabilities with TTL-based expiry.

func NewDiscoveryStore

func NewDiscoveryStore(ttl time.Duration) *DiscoveryStore

NewDiscoveryStore creates a DiscoveryStore with the given entry TTL.

func (*DiscoveryStore) FindByExpertise

func (ds *DiscoveryStore) FindByExpertise(tag string) []*AgentCapability

FindByExpertise returns all non-expired agents with a matching expertise tag.

func (*DiscoveryStore) Get

func (ds *DiscoveryStore) Get(nick string) *AgentCapability

Get returns a copy of the capability for the given nick, or nil if unknown/expired.

func (*DiscoveryStore) ListActive

func (ds *DiscoveryStore) ListActive() []*AgentCapability

ListActive returns all non-expired agent capabilities.

func (*DiscoveryStore) Prune

func (ds *DiscoveryStore) Prune()

Prune removes expired entries.

func (*DiscoveryStore) Update

func (ds *DiscoveryStore) Update(cap *AgentCapability)

Update adds or refreshes an agent's capability entry.

type EscalationRecord

type EscalationRecord struct {
	Task        string
	ToNick      string
	Reason      string
	Severity    string
	EscalatedBy string
	Channel     string
	EscalatedAt time.Time
	Resolved    bool
}

EscalationRecord tracks an escalation to a human operator.

type FederationLink struct {
	Name     string
	Client   ircclient.Client
	Channels []string
}

FederationLink represents a connection to a remote IRC server.

type FederationManager

type FederationManager struct {
	// contains filtered or unexported fields
}

FederationManager relays messages between the local IRC server and remote servers. Loop prevention is achieved via a [fed:<origin>] prefix on relayed messages.

func NewFederationManager

func NewFederationManager(localClient ircclient.Client, localNick func() string) *FederationManager

NewFederationManager creates a FederationManager.

func (fm *FederationManager) AddLink(name string, client ircclient.Client, channels []string)

AddLink registers a remote server link.

func (*FederationManager) AddMapping

func (fm *FederationManager) AddMapping(m config.ChannelMapping)

AddMapping adds a channel mapping for relay.

func (*FederationManager) Shutdown

func (fm *FederationManager) Shutdown()

Shutdown disconnects all remote links.

func (*FederationManager) Start

func (fm *FederationManager) Start(ctx context.Context) error

Start connects all remote links and registers message relay handlers.

type GateRecord

type GateRecord struct {
	Task      string
	Gate      string
	Status    GateStatus
	Details   string
	CheckedBy string
	Channel   string
	CheckedAt time.Time
}

GateRecord tracks a single gate check result.

type GateStatus

type GateStatus string

GateStatus is the result of a gate check.

const (
	GatePassed  GateStatus = "passed"
	GateFailed  GateStatus = "failed"
	GatePending GateStatus = "pending"
)

type HandoffRecord

type HandoffRecord struct {
	Task      string
	From      string
	To        string
	ContextID string
	Channel   string
	Progress  int
	Accepted  bool
	CreatedAt time.Time
}

HandoffRecord tracks a task handoff between agents.

type HandoffStore

type HandoffStore struct {
	// contains filtered or unexported fields
}

HandoffStore tracks checkpoints and handoffs.

func NewHandoffStore

func NewHandoffStore() *HandoffStore

NewHandoffStore creates a new HandoffStore.

func (*HandoffStore) AcceptHandoff

func (hs *HandoffStore) AcceptHandoff(task, nick string)

AcceptHandoff marks a handoff as accepted by the target agent.

func (*HandoffStore) Checkpoints

func (hs *HandoffStore) Checkpoints(task string) []CheckpointRecord

Checkpoints returns the checkpoint history for a task.

func (*HandoffStore) GetHandoff

func (hs *HandoffStore) GetHandoff(task string) *HandoffRecord

GetHandoff returns a copy of the latest handoff for a task, or nil.

func (*HandoffStore) ListHandoffs

func (hs *HandoffStore) ListHandoffs() []*HandoffRecord

ListHandoffs returns all tracked handoffs.

func (*HandoffStore) RecordCheckpoint

func (hs *HandoffStore) RecordCheckpoint(task, nick string, progress int, summary, channel string)

RecordCheckpoint records an incremental progress checkpoint.

func (*HandoffStore) RecordHandoff

func (hs *HandoffStore) RecordHandoff(task, from, to, contextID, channel string)

RecordHandoff records a task handoff.

type HealthMonitor

type HealthMonitor struct {
	// contains filtered or unexported fields
}

HealthMonitor provides pull-based health checks for an agent. No background goroutine — Check() computes status on demand.

func NewHealthMonitor

func NewHealthMonitor(client ircclient.Client, state *StateStore) *HealthMonitor

NewHealthMonitor creates a HealthMonitor.

func (*HealthMonitor) Check

func (h *HealthMonitor) Check() HealthStatus

Check returns the current health status of the agent.

type HealthStatus

type HealthStatus struct {
	Connected       bool                `json:"connected"`
	Healthy         bool                `json:"healthy"`
	Nick            string              `json:"nick"`
	Channels        []string            `json:"channels"`
	Uptime          time.Duration       `json:"uptime_ns"`
	UptimeHuman     string              `json:"uptime"`
	StartedAt       time.Time           `json:"started_at"`
	TaskStats       TaskStatsInfo       `json:"task_stats"`
	DependencyStats DependencyStatsInfo `json:"dependency_stats"`
}

HealthStatus represents the current health state of an agent.

type Lifecycle

type Lifecycle struct {
	// contains filtered or unexported fields
}

Lifecycle manages the agent's startup, signal handling, and graceful shutdown.

func NewLifecycle

func NewLifecycle(a *Agent) *Lifecycle

NewLifecycle creates a Lifecycle bound to the given Agent.

func (*Lifecycle) Wait

func (lc *Lifecycle) Wait(ctx context.Context) error

Wait blocks until the context is cancelled or a termination signal is received, then performs a graceful shutdown.

type MessageLogEntry

type MessageLogEntry struct {
	Timestamp time.Time `json:"timestamp"`
	Direction string    `json:"direction"` // "in" or "out"
	Channel   string    `json:"channel"`
	Nick      string    `json:"nick"`
	Action    string    `json:"action"`
	Raw       string    `json:"raw"`
}

MessageLogEntry represents a single logged protocol message.

type MetricsCollector

type MetricsCollector struct {
	// contains filtered or unexported fields
}

MetricsCollector tracks agent activity counters using lock-free atomic operations.

func NewMetricsCollector

func NewMetricsCollector() *MetricsCollector

NewMetricsCollector creates a new MetricsCollector.

func (*MetricsCollector) HandleProtocolMessage

func (mc *MetricsCollector) HandleProtocolMessage(msg *protocol.Message)

HandleProtocolMessage inspects an incoming protocol message and increments the appropriate counters. Suitable for use as a ProtocolHandler.

func (*MetricsCollector) RecordMessageSent

func (mc *MetricsCollector) RecordMessageSent()

RecordMessageSent increments the outgoing message counters.

func (*MetricsCollector) RecordNotificationSent

func (mc *MetricsCollector) RecordNotificationSent()

RecordNotificationSent increments the notifications sent counter.

func (*MetricsCollector) RecordRawMessageReceived

func (mc *MetricsCollector) RecordRawMessageReceived()

RecordRawMessageReceived increments the raw messages received counter.

func (*MetricsCollector) RegisterOTelMetrics

func (mc *MetricsCollector) RegisterOTelMetrics(meter metric.Meter)

RegisterOTelMetrics creates OTel counter instruments mirroring the atomic counters. If meter is nil, this is a no-op.

func (*MetricsCollector) Snapshot

func (mc *MetricsCollector) Snapshot() MetricsSnapshot

Snapshot returns a point-in-time snapshot of all metrics.

type MetricsSnapshot

type MetricsSnapshot struct {
	MessagesReceived     int64     `json:"messages_received"`
	MessagesSent         int64     `json:"messages_sent"`
	ProtocolMessagesIn   int64     `json:"protocol_messages_in"`
	ProtocolMessagesOut  int64     `json:"protocol_messages_out"`
	TasksStarted         int64     `json:"tasks_started"`
	TasksCompleted       int64     `json:"tasks_completed"`
	TasksBlocked         int64     `json:"tasks_blocked"`
	DependenciesResolved int64     `json:"dependencies_resolved"`
	ContextRequests      int64     `json:"context_requests"`
	ContextShared        int64     `json:"context_shared"`
	NotificationsSent    int64     `json:"notifications_sent"`
	HelpRequested        int64     `json:"help_requested"`
	TasksOffered         int64     `json:"tasks_offered"`
	TasksClaimed         int64     `json:"tasks_claimed"`
	TasksAssigned        int64     `json:"tasks_assigned"`
	TasksDeclined        int64     `json:"tasks_declined"`
	TasksYielded         int64     `json:"tasks_yielded"`
	Checkpoints          int64     `json:"checkpoints"`
	Handoffs             int64     `json:"handoffs"`
	ReviewsRequested     int64     `json:"reviews_requested"`
	ReviewsCompleted     int64     `json:"reviews_completed"`
	GatesPassed          int64     `json:"gates_passed"`
	GatesFailed          int64     `json:"gates_failed"`
	VotesRecorded        int64     `json:"votes_recorded"`
	EscalationsRaised    int64     `json:"escalations_raised"`
	CollectedAt          time.Time `json:"collected_at"`
}

MetricsSnapshot holds a point-in-time snapshot of agent metrics.

type NotificationEvent

type NotificationEvent string

NotificationEvent identifies the type of event that triggers a notification.

const (
	NotifyTaskCompleted   NotificationEvent = "task_completed"
	NotifyTaskBlocked     NotificationEvent = "task_blocked"
	NotifyTaskStarted     NotificationEvent = "task_started"
	NotifyHelpNeeded      NotificationEvent = "help_needed"
	NotifyContextUpdate   NotificationEvent = "context_update"
	NotifyUnblocked       NotificationEvent = "unblocked"
	NotifyTaskOffered     NotificationEvent = "task_offered"
	NotifyTaskClaimed     NotificationEvent = "task_claimed"
	NotifyTaskAssigned    NotificationEvent = "task_assigned"
	NotifyTaskYielded     NotificationEvent = "task_yielded"
	NotifyCheckpoint      NotificationEvent = "checkpoint"
	NotifyHandoff         NotificationEvent = "handoff"
	NotifyReviewRequested NotificationEvent = "review_requested"
	NotifyReviewCompleted NotificationEvent = "review_completed"
	NotifyGatePassed      NotificationEvent = "gate_passed"
	NotifyGateFailed      NotificationEvent = "gate_failed"
	NotifyVote            NotificationEvent = "vote"
	NotifyEscalation      NotificationEvent = "escalation"
)

type NotificationFormatter

type NotificationFormatter func(event NotificationEvent, msg *protocol.Message) string

NotificationFormatter formats a notification event and protocol message into a string.

type NotificationRule

type NotificationRule struct {
	Event     NotificationEvent
	Channel   string
	Formatter NotificationFormatter // nil uses default
}

NotificationRule defines when and where to send a notification.

type Notifier

type Notifier struct {
	// contains filtered or unexported fields
}

Notifier routes protocol messages to notification channels based on configured rules.

func NewNotifier

func NewNotifier(client ircclient.Client) *Notifier

NewNotifier creates a Notifier that sends notifications via the given client.

func (*Notifier) AddRule

func (n *Notifier) AddRule(rule NotificationRule)

AddRule registers a notification rule.

func (*Notifier) HandleMessage

func (n *Notifier) HandleMessage(msg *protocol.Message)

HandleMessage maps an incoming protocol message to notification events and sends formatted messages to configured channels. This method can be registered as a ProtocolHandler on the dispatcher.

func (*Notifier) RemoveRulesForChannel

func (n *Notifier) RemoveRulesForChannel(channel string)

RemoveRulesForChannel removes all rules targeting the given channel.

func (*Notifier) RemoveRulesForEvent

func (n *Notifier) RemoveRulesForEvent(event NotificationEvent)

RemoveRulesForEvent removes all rules matching the given event type.

func (*Notifier) Rules

func (n *Notifier) Rules() []NotificationRule

Rules returns a copy of all configured rules.

type OfferInfo

type OfferInfo struct {
	Task      string
	Channel   string
	OfferedBy string
	Priority  string
	Scope     string
	OfferedAt time.Time
	ClaimedBy string
}

OfferInfo tracks a task that has been offered for claiming.

type PersistedState

type PersistedState struct {
	Tasks        map[string]*TaskInfo    `json:"tasks"`
	Dependencies []DependencyEdge        `json:"dependencies"`
	Agents       map[string]*AgentStatus `json:"agents"`
	SavedAt      time.Time               `json:"saved_at"`
}

PersistedState is a serializable snapshot of the StateStore.

type ProtocolDispatcher

type ProtocolDispatcher struct {
	// contains filtered or unexported fields
}

ProtocolDispatcher wires the protocol parser into the IRC client's OnMessage handler. It dispatches parsed protocol messages to registered handlers and updates the state and context stores.

func NewProtocolDispatcher

func NewProtocolDispatcher(client ircclient.Client, state *StateStore, context *ContextStore) *ProtocolDispatcher

NewProtocolDispatcher creates a dispatcher wired to the given stores and client.

func (*ProtocolDispatcher) OnProtocolMessage

func (pd *ProtocolDispatcher) OnProtocolMessage(handler ProtocolHandler) int

OnProtocolMessage registers a handler for parsed protocol messages. Returns an ID for later removal.

func (*ProtocolDispatcher) Register

func (pd *ProtocolDispatcher) Register() ircclient.HandlerID

Register hooks the dispatcher into the client's OnMessage handler. Returns the HandlerID for later removal.

func (*ProtocolDispatcher) RemoveProtocolHandler

func (pd *ProtocolDispatcher) RemoveProtocolHandler(id int)

RemoveProtocolHandler removes a previously registered protocol handler.

type ProtocolHandler

type ProtocolHandler func(*protocol.Message)

ProtocolHandler is a callback for incoming protocol messages.

type ReviewRecord

type ReviewRecord struct {
	Task        string
	PR          string
	ReviewType  string
	RequestedBy string
	Reviewer    string
	Verdict     ReviewVerdict
	Details     string
	Channel     string
	RequestedAt time.Time
	CompletedAt time.Time
	Iteration   int
}

ReviewRecord tracks a single review request/response.

type ReviewStore

type ReviewStore struct {
	// contains filtered or unexported fields
}

ReviewStore tracks reviews and gates by task.

func NewReviewStore

func NewReviewStore(maxIterations int) *ReviewStore

NewReviewStore creates a ReviewStore. maxIterations of 0 means unlimited.

func (*ReviewStore) AllGatesPassed

func (rs *ReviewStore) AllGatesPassed(task string) bool

AllGatesPassed returns true if all gates for a task have passed.

func (*ReviewStore) Gates

func (rs *ReviewStore) Gates(task string) []*GateRecord

Gates returns all gate records for a task.

func (*ReviewStore) ListReviews

func (rs *ReviewStore) ListReviews() []*ReviewRecord

ListReviews returns all tracked review records across all tasks.

func (*ReviewStore) RecordComplete

func (rs *ReviewStore) RecordComplete(task, pr, reviewer string, verdict ReviewVerdict, details, channel string)

RecordComplete records a review completion with a verdict.

func (*ReviewStore) RecordGate

func (rs *ReviewStore) RecordGate(task, gate string, status GateStatus, details, checkedBy, channel string)

RecordGate records a gate check result.

func (*ReviewStore) RecordRequest

func (rs *ReviewStore) RecordRequest(task, pr, reviewType, requestedBy, channel string)

RecordRequest records a new review request.

func (*ReviewStore) Reviews

func (rs *ReviewStore) Reviews(task string) []*ReviewRecord

Reviews returns all review records for a task.

func (*ReviewStore) Summary

func (rs *ReviewStore) Summary(task string) ReviewSummary

Summary returns an aggregate review summary for a task.

type ReviewSummary

type ReviewSummary struct {
	Task            string
	TotalReviews    int
	PendingReviews  int
	ApprovedReviews int
	AllGatesPassed  bool
	IterationCount  int
	NeedsEscalation bool
}

ReviewSummary provides an aggregate view of reviews for a task.

type ReviewVerdict

type ReviewVerdict string

ReviewVerdict is the outcome of a code review.

const (
	ReviewApproved         ReviewVerdict = "approved"
	ReviewChangesRequested ReviewVerdict = "changes-requested"
	ReviewRejected         ReviewVerdict = "rejected"
)

type RoleBehavior

type RoleBehavior struct {
	Role           string
	TriggerActions []protocol.Action
	Handler        func(msg *protocol.Message) []*protocol.Message
}

RoleBehavior defines an auto-response behavior triggered by specific actions.

func BuiltinBehavior

func BuiltinBehavior(role string) *RoleBehavior

BuiltinBehavior returns a built-in RoleBehavior for the given role name, or nil if no built-in behavior exists.

func (*RoleBehavior) Matches

func (rb *RoleBehavior) Matches(msg *protocol.Message) bool

Matches returns true if this behavior should trigger for the given message.

type RoleEngine

type RoleEngine struct {
	// contains filtered or unexported fields
}

RoleEngine manages agent roles and their auto-response behaviors.

func NewRoleEngine

func NewRoleEngine(roles []string) *RoleEngine

NewRoleEngine creates a RoleEngine with the given roles.

func (*RoleEngine) ExpertiseTags

func (re *RoleEngine) ExpertiseTags() []string

ExpertiseTags returns expertise tags derived from roles for discovery.

func (*RoleEngine) HandleMessage

func (re *RoleEngine) HandleMessage(msg *protocol.Message) []*protocol.Message

HandleMessage checks all registered behaviors against the message and returns any auto-response messages.

func (*RoleEngine) HasRole

func (re *RoleEngine) HasRole(role string) bool

HasRole returns true if the engine has the given role.

func (*RoleEngine) RegisterBehavior

func (re *RoleEngine) RegisterBehavior(behavior *RoleBehavior)

RegisterBehavior adds a behavior to the engine.

func (*RoleEngine) Roles

func (re *RoleEngine) Roles() []string

Roles returns the configured roles.

type StatePersistence

type StatePersistence struct {
	// contains filtered or unexported fields
}

StatePersistence handles saving and loading StateStore to a JSON file. It supports debounced writes and atomic file replacement.

func NewStatePersistence

func NewStatePersistence(path string, state *StateStore, debounce time.Duration) *StatePersistence

NewStatePersistence creates a StatePersistence that saves state to path. An empty path disables persistence entirely.

func (*StatePersistence) Close

func (sp *StatePersistence) Close()

Close flushes any pending save and stops the timer.

func (*StatePersistence) Load

func (sp *StatePersistence) Load() error

Load reads the state file and restores the state store. A nonexistent file is treated as a fresh start (no error).

func (*StatePersistence) MarkDirty

func (sp *StatePersistence) MarkDirty()

MarkDirty resets the debounce timer; Save is called when the timer fires.

func (*StatePersistence) Save

func (sp *StatePersistence) Save() error

Save writes the current state to disk atomically (write temp, rename).

type StateStore

type StateStore struct {
	// contains filtered or unexported fields
}

StateStore tracks task status, dependencies, and agent activity. It is thread-safe and keyed by task name.

func NewStateStore

func NewStateStore() *StateStore

NewStateStore creates an empty StateStore.

func (*StateStore) AddDependency

func (s *StateStore) AddDependency(edge DependencyEdge)

AddDependency adds a dependency edge explicitly.

func (*StateStore) AllDependencies

func (s *StateStore) AllDependencies() []DependencyEdge

AllDependencies returns a copy of all dependency edges.

func (*StateStore) BlockedBy

func (s *StateStore) BlockedBy(taskName string, includeResolved bool) []DependencyEdge

BlockedBy returns the dependency edges where taskName is the blocker. If includeResolved is false, only unresolved edges are returned.

func (*StateStore) BlockersOf

func (s *StateStore) BlockersOf(taskName string, includeResolved bool) []DependencyEdge

BlockersOf returns the dependency edges where taskName is the blocked task. If includeResolved is false, only unresolved edges are returned.

func (*StateStore) DependencyStats

func (s *StateStore) DependencyStats() DependencyStatsInfo

DependencyStats returns aggregate statistics about the dependency graph.

func (*StateStore) GetAgentStatus

func (s *StateStore) GetAgentStatus(nick string) *AgentStatus

GetAgentStatus returns the current status of an agent, or nil if unknown.

func (*StateStore) GetTask

func (s *StateStore) GetTask(name string) *TaskInfo

GetTask returns the tracked info for a task, or nil if unknown.

func (*StateStore) HasCycle

func (s *StateStore) HasCycle(blocked, blockedBy string) bool

HasCycle returns true if adding an edge blocked→blockedBy would create a cycle.

func (*StateStore) ListAgents

func (s *StateStore) ListAgents() []*AgentStatus

ListAgents returns all tracked agent statuses.

func (*StateStore) ListTasks

func (s *StateStore) ListTasks() []*TaskInfo

ListTasks returns all tracked tasks.

func (*StateStore) ResolvedDependencies

func (s *StateStore) ResolvedDependencies() []DependencyEdge

ResolvedDependencies returns all resolved dependency edges.

func (*StateStore) Restore

func (s *StateStore) Restore(ps *PersistedState)

Restore populates the state store from a persisted snapshot. Must be called before any dispatchers are wired.

func (*StateStore) Snapshot

func (s *StateStore) Snapshot() *PersistedState

Snapshot returns a deep copy of the state store suitable for serialization.

func (*StateStore) TasksByStatus

func (s *StateStore) TasksByStatus(status TaskStatus) []*TaskInfo

TasksByStatus returns tasks matching the given status.

func (*StateStore) TransitiveDependencies

func (s *StateStore) TransitiveDependencies(taskName string) []string

TransitiveDependencies returns all tasks that taskName transitively depends on (i.e., all transitive blockers). Uses BFS over unresolved edges.

func (*StateStore) UnblockedTasks

func (s *StateStore) UnblockedTasks() []*TaskInfo

UnblockedTasks returns tasks that were blocked but now have all dependencies resolved.

func (*StateStore) UpdateAgentStatus

func (s *StateStore) UpdateAgentStatus(nick, channel, taskName string)

UpdateAgentStatus records what an agent is currently working on.

func (*StateStore) UpdateTask

func (s *StateStore) UpdateTask(msg *protocol.Message)

UpdateTask updates the state store based on a protocol message.

type TaskBoard

type TaskBoard struct {
	// contains filtered or unexported fields
}

TaskBoard tracks offered tasks, pending claims, and claim arbitration.

func NewTaskBoard

func NewTaskBoard(state *StateStore, claimJitter time.Duration) *TaskBoard

NewTaskBoard creates a TaskBoard with the given claim jitter window. If claimJitter is 0, first-claim-wins (instant arbitration).

func (*TaskBoard) GetOffer

func (tb *TaskBoard) GetOffer(task string) *OfferInfo

GetOffer returns a copy of the offer info for a task, or nil.

func (*TaskBoard) ListOffers

func (tb *TaskBoard) ListOffers() []*OfferInfo

ListOffers returns all tracked offers.

func (*TaskBoard) PendingClaims

func (tb *TaskBoard) PendingClaims(task string) []ClaimEntry

PendingClaims returns the pending claims for a task.

func (*TaskBoard) RecordAssign

func (tb *TaskBoard) RecordAssign(task, to, assignedBy, channel string)

RecordAssign records a direct task assignment.

func (*TaskBoard) RecordClaim

func (tb *TaskBoard) RecordClaim(task, nick string, load int) string

RecordClaim records a claim on an offered task. Returns the winning nick if arbitration completes immediately (claimJitter==0), or empty string if the claim is queued for deferred arbitration.

func (*TaskBoard) RecordDecline

func (tb *TaskBoard) RecordDecline(task string)

RecordDecline removes ownership from a task.

func (*TaskBoard) RecordOffer

func (tb *TaskBoard) RecordOffer(task, channel, offeredBy, priority, scope string)

RecordOffer records a new task offer.

func (*TaskBoard) RecordYield

func (tb *TaskBoard) RecordYield(task string)

RecordYield puts a task back into offered state.

func (*TaskBoard) Winner

func (tb *TaskBoard) Winner(task string) string

Winner returns the winning claimant for a task, or empty string if unresolved.

type TaskGraphNode

type TaskGraphNode struct {
	Task      *TaskInfo        `json:"task"`
	BlockedBy []DependencyEdge `json:"blocked_by"`
	Blocking  []DependencyEdge `json:"blocking"`
}

TaskGraphNode represents a task and its dependency edges in the task graph.

type TaskInfo

type TaskInfo struct {
	Name       string
	Status     TaskStatus
	Priority   string
	WaitingFor string
	Tags       []string
	LastAgent  string
	UpdatedAt  time.Time
	Owner      string `json:"owner,omitempty"`
	Scope      string `json:"scope,omitempty"`
	Progress   int    `json:"progress,omitempty"`
	Summary    string `json:"summary,omitempty"`
}

TaskInfo holds the tracked state of a task.

type TaskStatsInfo

type TaskStatsInfo struct {
	Total     int `json:"total"`
	Started   int `json:"started"`
	Completed int `json:"completed"`
	Blocked   int `json:"blocked"`
}

TaskStatsInfo holds aggregate task statistics.

type TaskStatus

type TaskStatus string

TaskStatus represents the current status of a tracked task.

const (
	TaskStatusStarted   TaskStatus = "started"
	TaskStatusCompleted TaskStatus = "completed"
	TaskStatusBlocked   TaskStatus = "blocked"
	TaskStatusOffered   TaskStatus = "offered"
	TaskStatusClaimed   TaskStatus = "claimed"
	TaskStatusAssigned  TaskStatus = "assigned"
	TaskStatusYielded   TaskStatus = "yielded"
)

type TopicSummary

type TopicSummary struct {
	Topic      string
	Votes      map[string]int // choice → count
	TotalVotes int
	Resolved   bool
	Resolution string
}

TopicSummary provides an aggregate view of votes on a topic.

type UnblockNotifier

type UnblockNotifier struct {
	// contains filtered or unexported fields
}

UnblockNotifier watches for COMPLETED messages and automatically sends ACKNOWLEDGED messages for tasks that become unblocked as a result.

func NewUnblockNotifier

func NewUnblockNotifier(state *StateStore, client ircclient.Client, selfNick func() string) *UnblockNotifier

NewUnblockNotifier creates an UnblockNotifier wired to the given state store and client.

func (*UnblockNotifier) NotifiedTasks

func (n *UnblockNotifier) NotifiedTasks() []string

NotifiedTasks returns the set of task names that have been auto-acknowledged.

func (*UnblockNotifier) OnTaskCompleted

func (n *UnblockNotifier) OnTaskCompleted(msg *protocol.Message)

OnTaskCompleted is called by the dispatcher after UpdateTask for COMPLETED messages. It checks for newly unblocked tasks and sends auto-acknowledgement messages.

func (*UnblockNotifier) Reset

func (n *UnblockNotifier) Reset()

Reset clears the notified set. Useful for testing.

type VoteRecord

type VoteRecord struct {
	Topic   string
	Nick    string
	Choice  string
	Channel string
	VotedAt time.Time
}

VoteRecord tracks a single vote on a topic.

type WorkflowDefinition

type WorkflowDefinition struct {
	Name   string           `json:"name"`
	Stages []*WorkflowStage `json:"stages"`
}

WorkflowDefinition defines a named sequence of stages.

func CollaborativeHandoffWorkflow

func CollaborativeHandoffWorkflow() *WorkflowDefinition

CollaborativeHandoffWorkflow returns the built-in collaborative handoff workflow. Stages: implement → checkpoint → handoff → continue → complete

func GatedPipelineWorkflow

func GatedPipelineWorkflow() *WorkflowDefinition

GatedPipelineWorkflow returns the built-in gated pipeline workflow definition. Stages: implement → review → merge → release → cleanup

type WorkflowEngine

type WorkflowEngine struct {
	// contains filtered or unexported fields
}

WorkflowEngine manages workflow definitions and active instances.

func NewWorkflowEngine

func NewWorkflowEngine() *WorkflowEngine

NewWorkflowEngine creates a new WorkflowEngine with built-in templates.

func (*WorkflowEngine) AdvanceStage

func (we *WorkflowEngine) AdvanceStage(task string) string

AdvanceStage moves a workflow instance to the next stage. Returns the new stage name, or empty string if workflow is complete.

func (*WorkflowEngine) CurrentStage

func (we *WorkflowEngine) CurrentStage(task string) *WorkflowStage

CurrentStage returns the current stage definition for a task's workflow, or nil.

func (*WorkflowEngine) GetDefinition

func (we *WorkflowEngine) GetDefinition(name string) *WorkflowDefinition

GetDefinition returns a workflow definition by name, or nil.

func (*WorkflowEngine) GetInstance

func (we *WorkflowEngine) GetInstance(task string) *WorkflowInstance

GetInstance returns a copy of the workflow instance for a task, or nil.

func (*WorkflowEngine) ListDefinitions

func (we *WorkflowEngine) ListDefinitions() []*WorkflowDefinition

ListDefinitions returns all registered workflow definitions.

func (*WorkflowEngine) ListInstances

func (we *WorkflowEngine) ListInstances() []*WorkflowInstance

ListInstances returns all active workflow instances.

func (*WorkflowEngine) RegisterDefinition

func (we *WorkflowEngine) RegisterDefinition(def *WorkflowDefinition)

RegisterDefinition adds or replaces a workflow definition.

func (*WorkflowEngine) StartWorkflow

func (we *WorkflowEngine) StartWorkflow(workflowName, task string) *WorkflowInstance

StartWorkflow creates a new workflow instance for a task.

type WorkflowInstance

type WorkflowInstance struct {
	Name         string `json:"name"`
	Task         string `json:"task"`
	CurrentStage string `json:"current_stage"`
	Completed    bool   `json:"completed"`
}

WorkflowInstance tracks the current state of a workflow execution.

type WorkflowStage

type WorkflowStage struct {
	Name            string   `json:"name"`
	RequiredGates   []string `json:"required_gates,omitempty"`
	RequiredReviews []string `json:"required_reviews,omitempty"`
	NextStage       string   `json:"next_stage,omitempty"`
}

WorkflowStage defines a stage in a workflow with required gates and reviews.

Jump to

Keyboard shortcuts

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