monitor

package
v0.7.6 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package monitor owns daemon-native session monitors: durable-for-the-daemon watches that wake their owning agent session when a terminal exits, a terminal prints a pattern, a timer elapses, other sessions reach a state, or a pull request changes. Only a pull_request monitor fires more than once: it stays armed across wakes. Provider-internal background mechanisms (Claude Code Monitor/run_in_background, Codex background terminals) cannot start a Compozy turn, so the daemon owns the wake.

Index

Constants

View Source
const (
	UntilExit  = "exit"
	UntilMatch = "match"
)

Terminal wait conditions accepted by terminal monitors.

View Source
const (
	UntilAny = "any"
	UntilAll = "all"
)

Session wait conditions accepted by session monitors.

View Source
const (
	ReasonExit           = "exit"
	ReasonMatch          = "match"
	ReasonTimeout        = "timeout"
	ReasonStalled        = "stalled"
	ReasonTimerElapsed   = "timer_elapsed"
	ReasonTerminalFailed = "terminal_unavailable"
	// ReasonConditionMet marks a session monitor whose any or all condition held.
	ReasonConditionMet = "condition_met"
	// ReasonSessionStopped marks a monitor canceled because its owner was stopped on purpose.
	ReasonSessionStopped = "session_stopped"
	// ReasonCancelRequested marks a monitor its owner canceled explicitly; no wake was lost.
	ReasonCancelRequested = "cancel_requested"
	// ReasonOwnerPrefix prefixes the restart-eligibility reason that kept an owner from resuming.
	ReasonOwnerPrefix = "owner_"
	// Pull request wake reasons. A timed-out pull_request monitor reports ReasonTimeout.
	ReasonPullRequestChanged = "pull_request_changed"
	ReasonPullRequestMerged  = "pull_request_merged"
	ReasonPullRequestClosed  = "pull_request_closed"
	ReasonForgeUnavailable   = "forge_unavailable"
	ReasonFireCapReached     = "fire_cap_reached"
)

Outcome reasons reported to the woken agent.

View Source
const (
	MaxDescriptionRunes    = 200
	MaxPatternRunes        = 512
	MaxActivePerSession    = 8
	MaxActivePerTerminal   = 4
	MaxActiveTotal         = 256
	DefaultTerminalTimeout = 30 * time.Minute
	MaxTerminalTimeout     = 6 * time.Hour
	// DefaultPullRequestTimeout and MaxPullRequestTimeout bound a pull_request watch.
	DefaultPullRequestTimeout = 6 * time.Hour
	MaxPullRequestTimeout     = 24 * time.Hour
	MinTimerDelay             = 5 * time.Second
	MaxTimerDelay             = 24 * time.Hour
	MaxSessionTargets         = 32
	DefaultSessionTimeout     = 2 * time.Hour
	MaxSessionTimeout         = 6 * time.Hour

	// Wakes pending for one session coalesce into a single queue row, outside the input capacity pools.
	// Past MaxCoalescedWakeBytes a wake keeps its outcome and drops its output tail; past
	// MaxCoalescedWakes it stays delivering and retries like any other refusal, until the row is
	// delivered or deliveryRetryWindow leaves it undelivered.
	CoalescedWakeKey      = "monitor"
	MaxCoalescedWakes     = 64
	MaxCoalescedWakeBytes = 64 << 10
)

Bounds keep monitors cheap and prevent runaway wake loops.

View Source
const (
	TargetStateIdle            = "idle"
	TargetStateDone            = "done"
	TargetStateWaitingForInput = "waiting-for-input"
	TargetStateWaitingForAuth  = "waiting-for-auth"
	TargetStateNeedsAttention  = "needs-attention"
	TargetStateHung            = "hung"
	TargetStateStopped         = "stopped"
	TargetStateFailed          = "failed"
	// TargetStateInterrupted marks a target a daemon restart stopped and did not resume. It says nothing
	// about the target's work, so it ends an all condition but satisfies any only if stopped was selected.
	TargetStateInterrupted = "interrupted"
	// TargetStateGone marks a target that was deleted or superseded.
	TargetStateGone = "gone"
	// TargetStateUnknown marks a target whose state could not be read; it never satisfies a condition.
	TargetStateUnknown = "unknown"
)

Target states reported for a session monitor. Conditions read the state a target is in now: a target that passed through a state and moved on has not reached it. Failed, stopped and gone are final: a target in one of them can never change on its own, so it always counts toward the condition.

View Source
const (

	// MaxPullRequestFires caps the wakes of one monitor; the last one says so and ends it.
	MaxPullRequestFires = 64
)

Pull request watches poll one forge read per target per interval and coalesce what they see into wakes.

Variables

View Source
var (
	// ErrInvalid reports a monitor spec that fails validation.
	ErrInvalid = errors.New("monitor: invalid spec")
	// ErrLimit reports that the owning session already has the maximum active monitors.
	ErrLimit = errors.New("monitor: active monitor limit reached")
	// ErrNotFound reports an unknown monitor id for the session.
	ErrNotFound = errors.New("monitor: not found")
	// ErrStopped reports that the service is shutting down.
	ErrStopped = errors.New("monitor: service stopped")
	// ErrSessionGone reports a permanent wake refusal: the owning session is stopped or removed.
	ErrSessionGone = errors.New("monitor: owning session is not active")
)
View Source
var ErrOwnerStopped = errors.New("monitor: owner was stopped on purpose")

ErrOwnerStopped reports that the owner was stopped on purpose (an operator or agent decision), so its monitors must not outlive that decision.

View Source
var ErrSessionHasMonitors = errors.New("monitor: session has live monitors")

Functions

func InvalidSpec

func InvalidSpec(message string) error

InvalidSpec reports a refused monitor request whose static message guides the caller to correct it.

Types

type Kind

type Kind string

Kind selects what a monitor watches.

const (
	// KindTerminal watches one integrated terminal for exit or an output match.
	KindTerminal Kind = "terminal"
	// KindTimer fires once after a delay.
	KindTimer Kind = "timer"
	// KindPullRequest watches a branch's pull request through the forge and fires on each meaningful change.
	KindPullRequest Kind = "pull_request"
	// KindSession watches other sessions until any or all of them reach a state.
	KindSession Kind = "session"
)

type Monitor

type Monitor struct {
	ID          string    `json:"monitor_id"`
	SessionID   string    `json:"session_id"`
	Kind        Kind      `json:"kind"`
	Description string    `json:"description"`
	TerminalID  string    `json:"terminal_id,omitempty"`
	Until       string    `json:"until,omitempty"`
	Pattern     string    `json:"pattern,omitempty"`
	Branch      string    `json:"branch,omitempty"`
	Status      Status    `json:"status"`
	CreatedAt   time.Time `json:"created_at"`
	DeadlineAt  time.Time `json:"deadline_at"`
	FiredAt     time.Time `json:"fired_at,omitzero"`
	Reason      string    `json:"reason,omitempty"`
	ExitCode    *int      `json:"exit_code,omitempty"`
	// FireCount and LastFiredAt track a repeating monitor's wakes; FiredAt stays the moment it ended.
	FireCount   int       `json:"fire_count,omitempty"`
	LastFiredAt time.Time `json:"last_fired_at,omitzero"`
	// TargetSessionIDs and States define a session monitor.
	TargetSessionIDs []string `json:"target_session_ids,omitempty"`
	States           []string `json:"states,omitempty"`
	// Targets is each target's state when a session monitor fired. It is stored with the monitor, so
	// a wake re-delivered after a restart reports what fired it.
	Targets      []TargetStatus `json:"targets,omitempty"`
	TargetScopes []TargetScope  `json:"-"`
	// Reused marks a Create that returned an already-active identical terminal
	// monitor instead of registering a duplicate wake. It is not part of the wire shape.
	Reused bool `json:"-"`
}

Monitor is the observable state of one monitor.

type Notification

type Notification struct {
	Monitor Monitor
	Outcome Outcome
	// PullRequest is what a pull_request wake reports; nil for other kinds.
	PullRequest *PullRequestChanges
}

Notification is one fired monitor delivered to its owning session.

func (Notification) CompactMessage

func (n Notification) CompactMessage() string

CompactMessage renders the same outcome without its output tail, for a coalesced wake that has spent its size budget. The agent still learns the outcome and can read the terminal.

func (Notification) Message

func (n Notification) Message() string

Message renders the wake prompt the woken agent receives. It mirrors the provider conventions agents already follow for background-task wakes: an explicit not-user-input header, a structured block, then the next action.

func (Notification) WakeMessageID

func (n Notification) WakeMessageID() string

WakeMessageID is the stable queue identity of this wake. A repeating monitor needs one per fire, or the ledger would swallow every wake after the first as already admitted.

type Option

type Option func(*Service)

Option configures a Service.

func WithClock

func WithClock(now func() time.Time) Option

WithClock overrides the wall clock used for timestamps and retention.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the service logger.

func WithObserver

func WithObserver(observe func(ctx context.Context, sessionID string)) Option

WithObserver registers a callback for every change to a session's monitors: one starts, fires, is canceled, delivered, or abandoned. Calls run one at a time on a service-owned goroutine with a bounded context, never on the caller's path, and stop when the service shuts down. Changes that arrive while a session's refresh is still pending coalesce into that one call.

func WithOwners

func WithOwners(owners Owners) Option

WithOwners lets the service capture owner bindings and resume owners during recovery.

func WithPullRequests

func WithPullRequests(source PullRequestSource) Option

WithPullRequests enables pull_request monitors.

func WithSessionTargets

func WithSessionTargets(targets SessionTargets) Option

WithSessionTargets enables session monitors.

func WithSessionWatchGate

func WithSessionWatchGate(gate <-chan struct{}) Option

WithSessionWatchGate holds session watches until gate closes. The daemon closes it once restarted sessions are resumed and supervised, because a target read before that reports a false state.

func WithStore

func WithStore(store Store) Option

WithStore makes monitors durable across daemon restarts.

type Outcome

type Outcome struct {
	Reason   string
	ExitCode *int
	// Output is untrusted terminal text; empty for timers.
	Output string
	// OutputLost marks a wake re-delivered after a restart: the terminal output it carried was not retained.
	OutputLost bool
	// Targets is each target's state for a session monitor.
	Targets []TargetStatus
}

Outcome is what a fired monitor observed.

type OwnerIneligibleError

type OwnerIneligibleError struct{ Reason string }

OwnerIneligibleError reports that a restart-stopped owner may not be resumed automatically. Reason is the session restart-eligibility reason.

func (*OwnerIneligibleError) Error

func (e *OwnerIneligibleError) Error() string

type Owners

type Owners interface {
	Binding(ctx context.Context, sessionID string) (string, error)
	Resume(ctx context.Context, sessionID, binding string) error
}

Owners resolves the session that owns a monitor. Binding captures the owner's restart-eligibility snapshot while it is live; Resume makes a restart-stopped owner able to receive a wake, or returns ErrOwnerStopped, ErrSessionGone, or an *OwnerIneligibleError.

type PullRequestChanges

type PullRequestChanges struct {
	Wake         bool                `json:"wake,omitempty"`
	Number       int                 `json:"number,omitempty"`
	URL          string              `json:"url,omitempty"`
	State        string              `json:"state,omitempty"`
	Head         string              `json:"head,omitempty"`
	Base         string              `json:"base,omitempty"`
	Conflict     bool                `json:"conflict,omitzero"`
	ChecksKnown  bool                `json:"checks_known,omitempty"`
	Passed       int                 `json:"passed,omitempty"`
	Failed       int                 `json:"failed,omitempty"`
	Pending      int                 `json:"pending,omitempty"`
	FailedNames  []string            `json:"failed_names,omitempty"`
	NewlyFailed  []string            `json:"newly_failed,omitempty"`
	FailureRose  bool                `json:"failure_rose,omitempty"`
	AllFinished  bool                `json:"all_finished,omitempty"`
	ReviewsKnown bool                `json:"reviews_known,omitempty"`
	Truncated    bool                `json:"truncated,omitempty"`
	Reviews      []PullRequestReview `json:"reviews,omitempty"`
	NewThreads   int                 `json:"new_threads,omitempty"`
	Unresolved   int                 `json:"unresolved,omitempty"`
	Terminal     string              `json:"terminal,omitempty"`
	ForgeDown    bool                `json:"forge_down,omitempty"`
	Cause        string              `json:"cause,omitempty"`
	TimedOut     bool                `json:"timed_out,omitempty"`
	FireCapHit   bool                `json:"fire_cap_hit,omitempty"`
	// ReviewsFailed says this read of reviews failed; ReviewsDown says they stayed unreadable past the grace.
	ReviewsFailed bool `json:"reviews_failed,omitempty"`
	ReviewsDown   bool `json:"reviews_down,omitempty"`
	// EndedNumber names a pull request that had already ended when a timed-out watch saw it.
	EndedNumber int `json:"ended_number,omitempty"`

	ConflictCleared bool `json:"conflict_cleared,omitzero"`
}

PullRequestChanges is what one wake tells the agent.

type PullRequestChecks

type PullRequestChecks struct {
	Passed, Failed, Pending int
	FailedNames             []string
}

PullRequestChecks are the check facts of one head.

type PullRequestLookup

type PullRequestLookup string

PullRequestLookup says what one forge read established.

const (
	// PullRequestFound means the read succeeded and names a pull request.
	PullRequestFound PullRequestLookup = "found"
	// PullRequestAbsent means no pull request is known for the branch yet, which is a wait.
	PullRequestAbsent PullRequestLookup = "absent"
	// PullRequestFailed means the read failed; it says nothing about checks or reviews.
	PullRequestFailed PullRequestLookup = "failed"
)

type PullRequestObservation

type PullRequestObservation struct {
	Lookup PullRequestLookup
	// Cause says why a lookup failed.
	Cause     string
	Number    int
	URL       string
	State     string
	Head      string
	Base      string
	Mergeable string
	Checks    *PullRequestChecks
	Reviews   *PullRequestReviews
	// ReviewsFailed marks a forge that serves reviews but could not read them this time.
	ReviewsFailed bool
}

PullRequestObservation is one forge read. Checks is nil when the forge could not establish them. Reviews is nil when the forge cannot observe them, or, with ReviewsFailed, when this read of them failed.

type PullRequestReview

type PullRequestReview struct {
	ID     string `json:"id"`
	Author string `json:"author,omitempty"`
	IsBot  bool   `json:"is_bot,omitempty"`
	State  string `json:"state"`
	Commit string `json:"commit,omitempty"`
}

PullRequestReview is one submitted review. Author is untrusted forge text.

type PullRequestReviews

type PullRequestReviews struct {
	Items             []PullRequestReview
	Threads           []PullRequestThread
	UnresolvedThreads int
	Truncated         bool
}

PullRequestReviews is review activity. Threads lists unresolved threads; UnresolvedThreads is their total.

type PullRequestSource

type PullRequestSource interface {
	ResolvePullRequest(ctx context.Context, spec Spec) (PullRequestTarget, error)
	ReadPullRequest(ctx context.Context, target PullRequestTarget) (PullRequestObservation, error)
}

PullRequestSource reads pull requests through the daemon's forge. ResolvePullRequest binds a spec to its target, defaulting the branch to the session's, and refuses an unusable one with InvalidSpec.

type PullRequestTarget

type PullRequestTarget struct {
	WorkspaceID string
	RepoKey     string
	Branch      string
}

PullRequestTarget identifies the watched pull request. Watches of one target share reads.

type PullRequestThread

type PullRequestThread struct {
	ID     string
	Commit string
}

PullRequestThread is one unresolved review thread and the commit it was opened on.

type Record

type Record struct {
	Monitor      Monitor
	WorkspaceID  string
	ProfileID    string
	Timeout      time.Duration
	OwnerBinding string
	// OwnerCheckFailedAt is when a recovering monitor's owner check first failed transiently; zero
	// otherwise. It anchors the retry horizon across restarts.
	OwnerCheckFailedAt time.Time
	// RepoKey and Cursor restore a pull_request watch; Cursor is JSON owned by this package.
	RepoKey string
	Cursor  string
	Version int64
}

Record is the durable form of one monitor. It carries the definition and lifecycle state needed to restore a watch after a daemon restart; terminal output is never stored. Version orders writes made without holding the service lock, so a stale write can never overwrite a newer one.

type Service

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

Service owns every live monitor and the goroutines that watch them. State is indexed by owning session; active monitors are capped per session, per terminal, and per daemon, and finished ones expire after finishedRetention.

func NewService

func NewService(ctx context.Context, terminals TerminalWatcher, waker Waker, opts ...Option) (*Service, error)

NewService builds a monitor service bound to a daemon lifetime context.

func (*Service) ActiveCounts

func (s *Service) ActiveCounts(sessionIDs []string) map[string]int

ActiveCounts reports, per requested session, how many monitors still hold a slot (active or delivering). Sessions without one are omitted.

func (*Service) Cancel

func (s *Service) Cancel(sessionID, id string) (Monitor, error)

Cancel stops one active or delivering monitor owned by sessionID without waking the session. The monitor is canceled in memory at once and can no longer wake; the call reports an error until the cancellation is durable, and the service keeps retrying the write in the background, so a failed write never depends on a later caller.

func (*Service) CancelSession

func (s *Service) CancelSession(sessionID string) int

CancelSession stops every monitor of a stopped or removed session and drops its history; nothing it registered may wake a later incarnation.

func (*Service) Create

func (s *Service) Create(ctx context.Context, spec Spec) (Monitor, error)

Create validates spec, starts watching, and returns the active monitor.

func (*Service) List

func (s *Service) List(sessionID string) []Monitor

List returns the session's monitors, active first, newest first within each group.

func (*Service) QuiesceSessionWatches

func (s *Service) QuiesceSessionWatches()

QuiesceSessionWatches stops evaluating session monitors. The daemon calls it before stopping sessions for a shutdown, so a target stopped by the shutdown cannot fire a monitor. Monitors stay active and durable, and the next boot re-evaluates them.

func (*Service) Recover

func (s *Service) Recover(ctx context.Context) error

Recover restores durable monitors after a daemon restart. It never reruns a command: a timer resumes on its original deadline, a monitor that had already fired is re-delivered under its stable message id, and a terminal that no longer exists fires terminal_unavailable. A monitor whose owner was stopped on purpose is canceled; one whose owner cannot be resumed is recorded as interrupted, visibly, without a wake.

func (*Service) RetireSession

func (s *Service) RetireSession(sessionID string, publish func() error) error

RetireSession serializes publication with monitor creation and refuses later monitors for the predecessor.

func (*Service) Shutdown

func (s *Service) Shutdown(ctx context.Context) error

Shutdown cancels every monitor and waits for watcher goroutines.

func (*Service) SuspendSession

func (s *Service) SuspendSession(sessionID string) int

SuspendSession stops the in-memory watches of an owner the daemon is interrupting for a restart, keeping every monitor durable so Recover can restore it. Each monitor keeps the owner binding captured while the owner was live: a stopped session no longer carries a complete route, so a snapshot taken at stop time would be degraded.

type SessionTargets

type SessionTargets interface {
	// ReadTargets returns the current state of every target in spec. A target that cannot be read
	// is reported with TargetStateUnknown.
	ReadTargets(ctx context.Context, spec Spec) []TargetStatus
	// TargetChanges returns a best-effort signal for changes to spec's targets and a function that
	// stops it. The channel closes if the signal ends; the sweep then keeps the monitor correct.
	TargetChanges(ctx context.Context, spec Spec) (<-chan struct{}, func(), error)
}

SessionTargets reads and follows the sessions a monitor watches. The daemon implements it so this package never depends on the session manager.

type Spec

type Spec struct {
	WorkspaceID string
	ProfileID   string
	SessionID   string
	Kind        Kind
	Description string
	TerminalID  string
	Until       string
	Pattern     string
	// Branch selects a pull_request monitor's pull request; empty means the session's branch.
	Branch string
	// Timeout bounds terminal and pull_request monitors; on expiry the monitor still fires with ReasonTimeout.
	Timeout time.Duration
	// Delay is the timer monitor duration.
	Delay time.Duration
	// Targets are the sessions a session monitor watches.
	Targets []string
	// TargetScopes captures immutable ownership for access rechecks after a target is removed.
	TargetScopes []TargetScope
	// States are the target states that satisfy a session monitor. Empty selects the default set.
	States []string
}

Spec describes one monitor request from an agent session.

type Status

type Status string

Status is the lifecycle state of one monitor.

const (
	StatusActive Status = "active"
	// StatusDelivering means the monitor fired and its wake is retrying a transient refusal.
	StatusDelivering Status = "delivering"
	// StatusFired means the final wake was admitted to the owning session's input queue. A pull_request
	// monitor returns to active after every other admitted wake.
	StatusFired    Status = "fired"
	StatusCanceled Status = "canceled"
	// StatusUndelivered means the monitor fired but its owning session could not be woken.
	StatusUndelivered Status = "undelivered"
	// StatusInterrupted means a daemon restart ended the watch and the owner could not be
	// resumed, so no wake was sent. Reason says why.
	StatusInterrupted Status = "interrupted"
)

type Store

type Store interface {
	// SaveMonitor upserts the record; a write whose Version is not newer than the stored one is ignored.
	SaveMonitor(ctx context.Context, record Record) error
	// LoadMonitors returns every persisted monitor.
	LoadMonitors(ctx context.Context) ([]Record, error)
	// PruneFinishedMonitors deletes finished monitors that fired before cutoff.
	PruneFinishedMonitors(ctx context.Context, cutoff time.Time) error
}

Store persists monitors so they survive a daemon restart.

type TargetScope

type TargetScope struct {
	SessionID   string `json:"session_id"`
	WorkspaceID string `json:"workspace_id"`
	ProfileID   string `json:"profile_id"`
}

TargetScope is the immutable owner resolved when a session watch is authorized. It is persisted privately, never returned on public monitor surfaces.

type TargetStatus

type TargetStatus struct {
	OccurrenceID string `json:"occurrence_id,omitempty"`
	SessionID    string `json:"session_id"`
	Name         string `json:"name,omitempty"`
	State        string `json:"state"`
	// Matched reports that this target counts toward the monitor's condition.
	Matched bool `json:"matched"`
}

TargetStatus is the state of one watched session.

type TerminalWatcher

type TerminalWatcher interface {
	WatchTerminal(ctx context.Context, spec Spec) (Watch, error)
}

TerminalWatcher resolves a terminal at creation time and returns the blocking watch.

type Waker

type Waker interface {
	WakeSession(ctx context.Context, notification Notification) error
}

Waker admits one fired monitor to its owning session. It returns as soon as the wake is queued; ErrSessionGone marks a permanent refusal, and any other error is retried as transient.

type Watch

type Watch func(ctx context.Context) (Outcome, error)

Watch blocks until the watched terminal condition resolves or ctx ends.

Jump to

Keyboard shortcuts

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