heartbeat

package
v0.5.3 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	AutomationEventBatchLimit   = 20
	AutomationEventBatchBytes   = 8 << 10
	AutomationEventSummaryBytes = 2 << 10
)
View Source
const (
	// TriageTitleMaxRunes bounds a proposal title.
	TriageTitleMaxRunes = 120
	// TriageBodyMaxRunes bounds a proposal body.
	TriageBodyMaxRunes = 500
)
View Source
const AutomationEventReadableBytes = 280

AutomationEventReadableBytes bounds the operator-facing line an event-derived proposal shows.

View Source
const (
	// FileName is the canonical authored wake-policy filename.
	FileName = "HEARTBEAT.md"
)
View Source
const ReasonTriageConfigUnavailable = "triage_config_unavailable"

ReasonTriageConfigUnavailable marks a check whose provider rejected the configured triage model or runtime options. It is a configuration diagnostic, not a check failure, so it never advances the failure streak that pauses an instance.

View Source
const (
	// ResourceKind is the canonical desired-state kind for package-owned HEARTBEAT.md content.
	ResourceKind resources.ResourceKind = "agent.heartbeat"
)
View Source
const (
	// SyntheticReasonHeartbeatWake marks daemon-owned prompts emitted by the Heartbeat wake service.
	SyntheticReasonHeartbeatWake = "agent_heartbeat_wake"
)

Variables

View Source
var (
	// ErrAuthoringConflict reports a stale or missing expected digest.
	ErrAuthoringConflict = errors.New("heartbeat: authoring conflict")
	// ErrAuthoringAgentNotFound reports a target agent that cannot be resolved.
	ErrAuthoringAgentNotFound = errors.New("heartbeat: authoring agent not found")
	// ErrAuthoringPathRejected reports a managed HEARTBEAT.md path that is unsafe to mutate.
	ErrAuthoringPathRejected = errors.New("heartbeat: authoring path rejected")
	// ErrAuthoringNoPolicy reports a mutation request for an absent HEARTBEAT.md.
	ErrAuthoringNoPolicy = errors.New("heartbeat: authored policy missing")
)
View Source
var (
	// ErrInvalid reports a HEARTBEAT.md file that exists but cannot be accepted.
	ErrInvalid = errors.New("heartbeat: invalid HEARTBEAT.md")
	// ErrPathEscape reports a HEARTBEAT.md path outside its configured workspace root.
	ErrPathEscape = errors.New("heartbeat: path escapes workspace root")
)
View Source
var (
	// ErrSnapshotNotFound reports a missing persisted Heartbeat snapshot.
	ErrSnapshotNotFound = errors.New("heartbeat: snapshot not found")
	// ErrRevisionNotFound reports a missing persisted Heartbeat authoring revision.
	ErrRevisionNotFound = errors.New("heartbeat: revision not found")
	// ErrSessionHealthNotFound reports a missing persisted session health row.
	ErrSessionHealthNotFound = errors.New("heartbeat: session health not found")
	// ErrWakeStateNotFound reports a missing persisted Heartbeat wake state row.
	ErrWakeStateNotFound = errors.New("heartbeat: wake state not found")
	// ErrWakeEventNotFound reports a missing persisted Heartbeat wake event row.
	ErrWakeEventNotFound = errors.New("heartbeat: wake event not found")
	// ErrInvalidSnapshot reports a malformed persisted Heartbeat snapshot.
	ErrInvalidSnapshot = errors.New("heartbeat: invalid snapshot")
	// ErrInvalidRevision reports a malformed Heartbeat authoring revision.
	ErrInvalidRevision = errors.New("heartbeat: invalid revision")
	// ErrInvalidSessionHealth reports a malformed persisted session health row.
	ErrInvalidSessionHealth = errors.New("heartbeat: invalid session health")
	// ErrInvalidWakeState reports a malformed persisted Heartbeat wake state row.
	ErrInvalidWakeState = errors.New("heartbeat: invalid wake state")
	// ErrInvalidWakeEvent reports a malformed persisted Heartbeat wake event row.
	ErrInvalidWakeEvent = errors.New("heartbeat: invalid wake event")
)
View Source
var (
	// ErrSyntheticPromptBusy reports that the session prompt gate rejected a no-queue wake.
	ErrSyntheticPromptBusy = errors.New("heartbeat: synthetic prompt busy")
)
View Source
var ErrTriageOutputInvalid = errors.New("triage_output_invalid")

Functions

func AppendSourceDigest

func AppendSourceDigest(digest *CheckDigest, batch PollBatch, threshold int) error

func BoundAutomationEventSummary

func BoundAutomationEventSummary(summary string) string

func CheckBackoff

func CheckBackoff(interval, maximum time.Duration, streak int64) time.Duration

func CompactAutomationEventSummary

func CompactAutomationEventSummary(raw string) string

CompactAutomationEventSummary shrinks a JSON event envelope structurally to fit the stored summary limit, so storage never cuts it into unparseable text. It drops the transport's duplicate `payload` copy, then halves the longest strings. Non-JSON input is returned unchanged.

func DiagnosticsJSON

func DiagnosticsJSON(diagnostics []Diagnostic) (json.RawMessage, error)

DiagnosticsJSON encodes redacted validation diagnostics for snapshot and revision storage.

func NewResourceCodec

func NewResourceCodec() (resources.KindCodec[ResourceSpec], error)

NewResourceCodec builds the typed codec for agent.heartbeat records.

func NextCheckTime

func NextCheckTime(now time.Time, cadence time.Duration, id string) time.Time

func ProposalFingerprint

func ProposalFingerprint(proposal TriageProposal) string

func ReadableAutomationEventSummary

func ReadableAutomationEventSummary(raw string) string

ReadableAutomationEventSummary turns a stored event body into one short plain line for the operator: the event's own scalar fields as "key: value", without delivery identifiers, raw JSON or nested structures. The result is untrusted event text and must be shown as plain text only. A body that is not a JSON object reads as its first line, collapsed and bounded.

func SourceResultStatus

func SourceResultStatus(err *source.Error) string

func ValidActorKind

func ValidActorKind(kind ActorKind) bool

ValidActorKind reports whether kind is a supported authoring actor enum member.

func ValidRevisionOperation

func ValidRevisionOperation(operation RevisionOperation) bool

ValidRevisionOperation reports whether operation is a supported revision enum member.

func ValidSessionHealthIneligibilityReason

func ValidSessionHealthIneligibilityReason(reason string) bool

ValidSessionHealthIneligibilityReason reports whether reason is a supported session-health reason.

func ValidSessionHealthState

func ValidSessionHealthState(state SessionHealthState) bool

ValidSessionHealthState reports whether state is a supported session health state.

func ValidSessionHealthStatus

func ValidSessionHealthStatus(health SessionHealthStatus) bool

ValidSessionHealthStatus reports whether health is a supported session health enum member.

func ValidWakeReason

func ValidWakeReason(reason WakeReason) bool

ValidWakeReason reports whether reason is a supported wake reason enum member.

func ValidWakeResult

func ValidWakeResult(result WakeResult) bool

ValidWakeResult reports whether result is a supported wake result enum member.

func ValidWakeSource

func ValidWakeSource(source WakeSource) bool

ValidWakeSource reports whether source is a supported wake source enum member.

func WarnUntrustedScripts

func WarnUntrustedScripts(policy *ResolvedPolicy)

Types

type ActorKind

type ActorKind string

ActorKind describes the redacted authoring actor class.

const (
	ActorKindUser      ActorKind = "user"
	ActorKindAgent     ActorKind = "agent"
	ActorKindExtension ActorKind = "extension"
	ActorKindSystem    ActorKind = "system"
)

type AdmitRequest

type AdmitRequest struct {
	ExpectedDue              string
	Sources                  []PolledSource
	EventIDs                 []string
	InstanceID, OccurrenceID string
	Now, NextWakeAt          time.Time
	ManualCheck              bool
	MaxConcurrent            int
}

type AuthoringError

type AuthoringError struct {
	Code        string
	Diagnostics []Diagnostic
	// contains filtered or unexported fields
}

AuthoringError carries deterministic redacted diagnostics for authoring failures.

func (*AuthoringError) Error

func (e *AuthoringError) Error() string

func (*AuthoringError) Unwrap

func (e *AuthoringError) Unwrap() error

Unwrap exposes the sentinel cause for errors.Is callers.

type AuthoringIdentity

type AuthoringIdentity struct {
	Kind string
	Ref  string
}

AuthoringIdentity records actor metadata for revision rows.

type AuthoringOption

type AuthoringOption func(*ManagedHeartbeatAuthoringService)

AuthoringOption customizes managed Heartbeat authoring service dependencies.

func WithHeartbeatAuthoringClock

func WithHeartbeatAuthoringClock(clock func() time.Time) AuthoringOption

WithHeartbeatAuthoringClock injects deterministic timestamps.

func WithHeartbeatAuthoringIDGenerator

func WithHeartbeatAuthoringIDGenerator(generator func(prefix string) (string, error)) AuthoringOption

WithHeartbeatAuthoringIDGenerator injects deterministic snapshot and revision ids.

type AuthoringService

type AuthoringService interface {
	Validate(ctx context.Context, req ValidateRequest) (ValidateResult, error)
	Put(ctx context.Context, req PutRequest) (MutationResult, error)
	Delete(ctx context.Context, req DeleteRequest) (MutationResult, error)
	History(ctx context.Context, req HistoryRequest) (HistoryResult, error)
	Rollback(ctx context.Context, req RollbackRequest) (MutationResult, error)
}

AuthoringService is the only managed mutation boundary for HEARTBEAT.md.

type AuthoringStore

type AuthoringStore interface {
	UpsertHeartbeatSnapshot(ctx context.Context, snapshot Snapshot) (Snapshot, error)
	AppendHeartbeatRevision(ctx context.Context, revision Revision) (Revision, error)
	ListHeartbeatRevisions(ctx context.Context, query RevisionListQuery) ([]Revision, error)
	FindHeartbeatRevisionForRollback(ctx context.Context, query RollbackLookup) (Revision, error)
	FindHeartbeatSnapshotByDigest(
		ctx context.Context,
		workspaceID string,
		agentName string,
		digest string,
		profileID string,
	) (Snapshot, bool, error)
	DeleteHeartbeatAgentHistory(
		ctx context.Context, workspaceID string, agentName string, sourcePath string, profileID string,
	) error
}

AuthoringStore is the persistence boundary used by managed Heartbeat authoring.

type AuthoringTarget

type AuthoringTarget struct {
	WorkspaceID   string
	WorkspaceRoot string
	ProfileID     string
	ProfileName   string
	AgentName     string
	AgentPath     string
	Config        compozyconfig.HeartbeatConfig
}

AuthoringTarget identifies the workspace and agent whose HEARTBEAT.md is managed.

type AutomationEventFact

type AutomationEventFact struct {
	ID, InstanceID, Summary, ReceivedAt string
	Instruction                         string
	TriggerName, Event                  string
	TriggerID, RunID                    string
}

type AutomationEventSource

type AutomationEventSource struct {
	SourceID    string `json:"source_id,omitempty"`
	SourceRef   string `json:"source_ref,omitempty"`
	ItemKey     string `json:"item_key,omitempty"`
	URL         string `json:"url,omitempty"`
	TriggerName string `json:"trigger_name"`
	Event       string `json:"event"`
	// Summary is the operator-facing readable line, set only on report sources, never in the check digest.
	Summary    string `json:"summary,omitempty"`
	Kind       string `json:"kind"`
	EventID    string `json:"event_id"`
	TriggerID  string `json:"trigger_id"`
	RunID      string `json:"run_id"`
	ReceivedAt string `json:"received_at"`
}

type AutomationFact

type AutomationFact struct {
	ID, ProfileID, WorkspaceID, Status, Cursor string
}

type CheckConfig

type CheckConfig struct {
	Sources                                                compozyconfig.HeartbeatSourcesConfig
	UnattendedTurnLimit                                    int64
	QuietBackoffCap                                        time.Duration
	FatigueLimit                                           int
	Enabled                                                bool
	Interval, MinInterval, MaxInterval, Retention, Timeout time.Duration
	MaxConcurrent, BatchSize                               int
}

type CheckDigest

type CheckDigest struct {
	SourceMore       bool         `json:"-"`
	EventIDs         []string     `json:"event_ids,omitempty"`
	Items            []DigestItem `json:"items"`
	Fingerprint      string       `json:"fingerprint"`
	AutomationCursor string       `json:"automation_cursor"`
	Diagnostics      []string     `json:"diagnostics,omitempty"`
}

func CollectDigest

func CollectDigest(
	scope CollectorScope,
	facts CollectorFacts,
	include []string,
	policyDigest, instructions string,
) (CheckDigest, error)

CollectDigest accepts daemon-owned facts; callers must fetch complete eligible populations before applying caps.

type CheckEnvironment

type CheckEnvironment interface {
	ResolveCheck(context.Context, string) (CheckTarget, error)
	BeforeCheck(context.Context, *CheckTarget, string) (string, error)
	Collect(context.Context, string, CollectorScope, []string, string, string) (CheckDigest, error)
}

type CheckResult

type CheckResult struct {
	Sources      []SourceOutcome `json:"sources,omitempty"`
	Gate         string          `json:"gate,omitempty"`
	Digest       *CheckDigest    `json:"digest,omitempty"`
	OccurrenceID string          `json:"occurrence_id,omitempty"`
}

type CheckService

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

func NewCheckService

func NewCheckService(
	ctx context.Context,
	storage InstanceWakeStore,
	environment CheckEnvironment,
	dispatcher TriageDispatcher,
	config CheckConfig,
	now func() time.Time,
) (*CheckService, error)

func (*CheckService) CancelInstance

func (s *CheckService) CancelInstance(ctx context.Context, id string) error

CancelInstance stops the check owned by the instance after its pause commits.

func (*CheckService) Check

func (s *CheckService) Check(ctx context.Context, id string, dryRun bool) (CheckResult, error)

func (*CheckService) Recover

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

Recover runs before traffic and preserves already committed outcomes.

func (*CheckService) SetChecks

func (s *CheckService) SetChecks(ctx context.Context, id string, enabled bool) (agentinstance.Instance, error)

func (*CheckService) SetPauseHandler

func (s *CheckService) SetPauseHandler(handler func(context.Context, agentinstance.Instance) error)

func (*CheckService) Shutdown

func (s *CheckService) Shutdown(context.Context) error

func (*CheckService) SourceMetrics

func (s *CheckService) SourceMetrics() map[string]any

func (*CheckService) SourceStatuses

func (s *CheckService) SourceStatuses(ctx context.Context, id string) ([]HeartbeatSourceStatus, error)

func (*CheckService) Tick

func (s *CheckService) Tick(ctx context.Context) error

type CheckSettingsStore

type CheckSettingsStore interface {
	SetChecks(context.Context, string, bool, time.Duration) (agentinstance.Instance, error)
}

type CheckTarget

type CheckTarget struct {
	DefinitionDir, RootDir string
	UntrustedScripts       bool
	Instance               agentinstance.Instance
	Policy                 ResolvedPolicy
	Scope                  CollectorScope
	Gate                   string
	MainPrompting          bool
}

type CollectorFacts

type CollectorFacts struct {
	AutomationEvents []AutomationEventFact
	EventsOmitted    int64
	Tasks            []TaskFact
	Sessions         []SessionFact
	Automations      []AutomationFact
	Monitors         []MonitorFact
	WorkLog          []WorkLogFact
	WorkLogTruncated bool
}

type CollectorScope

type CollectorScope struct {
	InstanceID          string
	ProfileID           string
	WorkspaceID         string
	Unrestricted        bool
	ReachableWorkspaces []string
	MainSessionID       string
	ChainSessionIDs     []string
	LastCompletedAt     time.Time
	AutomationCursor    string
	Now                 time.Time
}

CollectorScope is resolved by the daemon from the instance's effective reach.

type ConfigProvenance

type ConfigProvenance struct {
	Digest string       `json:"digest"`
	Subset ConfigSubset `json:"subset"`
}

ConfigProvenance records the resolved config subset that shaped a policy.

func ConfigProvenanceFor

func ConfigProvenanceFor(cfg compozyconfig.HeartbeatConfig) (ConfigProvenance, error)

ConfigProvenanceFor returns the canonical config subset and digest used by Heartbeat.

type ConfigSubset

type ConfigSubset struct {
	Enabled                      bool   `json:"enabled"`
	MaxBodyBytes                 int64  `json:"max_body_bytes"`
	ContextProjectionBytes       int64  `json:"context_projection_bytes"`
	MinInterval                  string `json:"min_interval"`
	DefaultInterval              string `json:"default_interval"`
	WakeCooldown                 string `json:"wake_cooldown"`
	MaxWakesPerCycle             int    `json:"max_wakes_per_cycle"`
	ActiveSessionOnly            bool   `json:"active_session_only"`
	AllowActiveHoursPreferences  bool   `json:"allow_active_hours_preferences"`
	WakeEventRetention           string `json:"wake_event_retention"`
	SessionHealthStaleAfter      string `json:"session_health_stale_after"`
	SessionHealthHookMinInterval string `json:"session_health_hook_min_interval"`
}

ConfigSubset is the canonical config authority subset included in digests.

type ContextProjection

type ContextProjection struct {
	Sources []SourceDecl `json:"sources,omitempty"`
	Include []string     `json:"include,omitzero"`
}

type DeleteRequest

type DeleteRequest struct {
	Target         AuthoringTarget
	ExpectedDigest string
	Actor          AuthoringIdentity
}

DeleteRequest removes HEARTBEAT.md through managed authoring.

type Diagnostic

type Diagnostic struct {
	Code       string `json:"code"`
	Severity   string `json:"severity"`
	Message    string `json:"message"`
	Field      string `json:"field,omitempty"`
	Section    string `json:"section,omitempty"`
	SourcePath string `json:"source_path,omitempty"`
	Line       int    `json:"line,omitzero"`
	Column     int    `json:"column,omitzero"`
}

Diagnostic describes a closed, redacted HEARTBEAT.md validation problem.

type DiagnosticError

type DiagnosticError struct {
	Diagnostics []Diagnostic
	// contains filtered or unexported fields
}

DiagnosticError carries structured diagnostics for invalid authored content.

func (*DiagnosticError) Error

func (e *DiagnosticError) Error() string

func (*DiagnosticError) Unwrap

func (e *DiagnosticError) Unwrap() error

Unwrap exposes the validation sentinel for errors.Is callers.

type DigestItem

type DigestItem struct {
	Instruction string                 `json:"instruction,omitempty"`
	Source      *AutomationEventSource `json:"source,omitempty"`
	Key         string                 `json:"key"`
	Summary     string                 `json:"summary,omitempty"`
}

type FinishRequest

type FinishRequest struct {
	HasSources, SourceMore                                   bool
	MinInterval                                              time.Duration
	UnattendedTurnLimit                                      int64
	QuietBackoffCap                                          time.Duration
	FatigueLimit                                             int64
	Interval, MaxInterval                                    time.Duration
	InstanceID, OccurrenceID, Source, Result, Reason, Detail string
	Digest, AutomationCursor                                 string
	DeniedCalls                                              int64
	Now, NextWakeAt, ExpiresAt                               time.Time
	Report                                                   *agentinstance.ReportInput
}

type FinishResult

type FinishResult struct {
	Changed bool
	Paused  *agentinstance.Instance
}

type Frontmatter

type Frontmatter struct {
	Version     int                    `json:"version"`
	Enabled     bool                   `json:"enabled"`
	Summary     string                 `json:"summary,omitempty"`
	Preferences FrontmatterPreferences `json:"preferences"`
	Context     ContextProjection      `json:"context"`
}

Frontmatter is the allowlisted strict HEARTBEAT.md metadata.

type FrontmatterPreferences

type FrontmatterPreferences struct {
	MinInterval  string       `json:"min_interval,omitempty"`
	ActiveHours  []TimeWindow `json:"active_hours,omitempty"`
	QuietWindows []TimeWindow `json:"quiet_windows,omitempty"`
}

FrontmatterPreferences captures authored preference hints before config bounds.

type HeartbeatSourceStatus

type HeartbeatSourceStatus struct {
	ID            string        `json:"id"`
	Kind          string        `json:"kind,omitempty"`
	Script        string        `json:"script,omitempty"`
	Status        string        `json:"status"`
	LastPolledAt  string        `json:"last_polled_at,omitempty"`
	LastSuccessAt string        `json:"last_success_at,omitempty"`
	LastItemCount int64         `json:"last_item_count"`
	FailureStreak int64         `json:"failure_streak"`
	Error         *source.Error `json:"error,omitempty"`
	NextPollAt    string        `json:"next_poll_at,omitempty"`
	// ScriptSHA256 is a script source's current content hash, read without polling it.
	ScriptSHA256 string `json:"script_sha256,omitempty"`
	// ScriptPath is the script's resolved file path, which with the profile identifies its approval.
	ScriptPath string `json:"script_path,omitempty"`
	// AwaitingApproval holds while those bytes are not approved, whether or not a check ran:
	// a new or paused source is never polled, so the poll status alone can't say it waits.
	AwaitingApproval bool `json:"awaiting_approval,omitempty"`
}

type HistoryRequest

type HistoryRequest struct {
	Target AuthoringTarget
	Limit  int
}

HistoryRequest lists managed HEARTBEAT.md authoring revisions.

type HistoryResult

type HistoryResult struct {
	Revisions []Revision
}

HistoryResult returns managed authoring history in newest-first order.

type InspectRequest

type InspectRequest struct {
	Target AuthoringTarget
}

InspectRequest identifies the policy source to inspect.

type InspectResult

type InspectResult struct {
	AgentName string
	Policy    ResolvedPolicy
	Snapshot  *Snapshot
}

InspectResult returns the resolved policy and matching stored snapshot, when present.

type InstanceWakeState

type InstanceWakeState struct {
	UnattendedTurns                                                                int64
	RotationDueSession                                                             string
	InstanceID, NextWakeAt, LastWakeAt, LastDigest, LastDigestAt, AutomationCursor string
	OccurrenceID, TriageSessionID, OccurrenceStartedAt                             string
	QuietStreak, FailureStreak                                                     int64
	Canceled                                                                       bool
	Deferred                                                                       bool
}

type ManagedHeartbeatAuthoringService

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

ManagedHeartbeatAuthoringService coordinates validation, filesystem mutation, and revision storage.

func NewManagedHeartbeatAuthoringService

func NewManagedHeartbeatAuthoringService(
	persistence AuthoringStore,
	options ...AuthoringOption,
) (*ManagedHeartbeatAuthoringService, error)

NewManagedHeartbeatAuthoringService creates the managed HEARTBEAT.md authoring service.

func (*ManagedHeartbeatAuthoringService) Delete

Delete removes HEARTBEAT.md through CAS-protected managed authoring.

func (*ManagedHeartbeatAuthoringService) History

History lists managed HEARTBEAT.md revision history.

func (*ManagedHeartbeatAuthoringService) PurgeAgentHistory

func (s *ManagedHeartbeatAuthoringService) PurgeAgentHistory(
	ctx context.Context,
	ref WorkspaceRef,
	agentName string,
	sourcePath string,
) error

PurgeAgentHistory removes managed revisions owned by one effective definition.

func (*ManagedHeartbeatAuthoringService) Put

Put creates or updates HEARTBEAT.md through CAS-protected managed authoring.

func (*ManagedHeartbeatAuthoringService) Rollback

Rollback restores a prior revision or snapshot body through the same validation and CAS path as Put.

func (*ManagedHeartbeatAuthoringService) Validate

Validate validates current or proposed HEARTBEAT.md content without mutating files or storage.

type ManagedHeartbeatStatusService

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

ManagedHeartbeatStatusService composes read-only Heartbeat policy status.

func NewManagedHeartbeatStatusService

func NewManagedHeartbeatStatusService(
	persistence StatusStore,
	options ...StatusOption,
) (*ManagedHeartbeatStatusService, error)

NewManagedHeartbeatStatusService creates the managed Heartbeat status service.

func (*ManagedHeartbeatStatusService) Inspect

Inspect resolves the current policy source and attaches the persisted snapshot if it exists.

func (*ManagedHeartbeatStatusService) Status

Status composes current policy status with wake state and requested session health.

type ManagedWakeService

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

ManagedWakeService is the production Heartbeat wake decision engine.

func NewManagedWakeService

func NewManagedWakeService(
	store WakeStore,
	healthReader SessionHealthReader,
	prompter SyntheticWakePrompter,
	config compozyconfig.HeartbeatConfig,
	options ...WakeOption,
) (*ManagedWakeService, error)

NewManagedWakeService creates the production Heartbeat wake service.

func (*ManagedWakeService) Wake

Wake evaluates one policy/health decision and emits a synthetic prompt only when eligible.

func (*ManagedWakeService) WakeMany

func (s *ManagedWakeService) WakeMany(ctx context.Context, requests []WakeRequest) ([]WakeDecision, error)

WakeMany evaluates a scheduler cycle and applies the configured max wake bound.

type MonitorFact

type MonitorFact struct {
	ID, SessionID  string
	NeedsAttention bool
}

type MutationResult

type MutationResult struct {
	Policy   ResolvedPolicy
	Snapshot Snapshot
	Revision Revision
}

MutationResult returns the resolved post-mutation state and audit row.

type ParseRequest

type ParseRequest struct {
	SourcePath    string
	WorkspaceRoot string
	Content       []byte
	Config        compozyconfig.HeartbeatConfig
}

ParseRequest describes in-memory HEARTBEAT.md content to validate and project.

type PolicyResolver

type PolicyResolver interface {
	ResolveHeartbeatPolicy(ctx context.Context, target AuthoringTarget) (ResolvedPolicy, bool, error)
}

PolicyResolver resolves non-filesystem Heartbeat policies, such as package-owned agent resources.

type PollBatch

type PollBatch struct {
	Token   string
	Sources []PolledSource
}

func (PollBatch) DigestItems

func (b PollBatch) DigestItems(threshold int) []DigestItem

func (PollBatch) HasMore

func (b PollBatch) HasMore() bool

func (PollBatch) Outcomes

func (b PollBatch) Outcomes() []SourceOutcome

type PolledSource

type PolledSource struct {
	Polled        bool
	Ref           source.Ref
	RefDigest     string
	Generation    int64
	Result        source.Result
	Err           *source.Error
	FailureStreak int64
	DurationMS    int64
}

type Preferences

type Preferences struct {
	MinInterval  time.Duration     `json:"min_interval"`
	ActiveHours  []TimeWindow      `json:"active_hours,omitempty"`
	QuietWindows []TimeWindow      `json:"quiet_windows,omitempty"`
	Context      ContextProjection `json:"context"`
}

Preferences captures config-bound resolved wake-policy hints.

func (Preferences) AllowsAt

func (p Preferences) AllowsAt(now time.Time) (bool, error)

AllowsAt evaluates active-hours allow windows minus quiet-window deny windows.

type PromptContribution

type PromptContribution struct {
	Active           bool              `json:"active"`
	Digest           string            `json:"digest,omitempty"`
	ConfigDigest     string            `json:"config_digest,omitempty"`
	SourcePath       string            `json:"source_path,omitempty"`
	Summary          string            `json:"summary,omitempty"`
	GuidanceMarkdown string            `json:"guidance_markdown,omitempty"`
	Preferences      Preferences       `json:"preferences"`
	Truncated        bool              `json:"truncated"`
	MaxBytes         int64             `json:"max_bytes"`
	MaxBodyBytes     int64             `json:"max_body_bytes"`
	Diagnostics      []Diagnostic      `json:"diagnostics,omitempty"`
	Context          ContextProjection `json:"context"`
}

PromptContribution is the bounded synthetic-wake prompt contribution.

type PutRequest

type PutRequest struct {
	Target         AuthoringTarget
	Body           string
	ExpectedDigest string
	Actor          AuthoringIdentity
}

PutRequest creates or updates HEARTBEAT.md through managed authoring.

type ResolveRequest

type ResolveRequest struct {
	AgentPath     string
	WorkspaceRoot string
	Config        compozyconfig.HeartbeatConfig
}

ResolveRequest describes a HEARTBEAT.md file located beside an AGENT.md file.

type ResolvedPolicy

type ResolvedPolicy struct {
	Enabled          bool
	Present          bool
	Active           bool
	Valid            bool
	SourcePath       string
	Digest           string
	ConfigDigest     string
	SchemaVersion    int
	Summary          string
	GuidanceMarkdown string
	Frontmatter      Frontmatter
	Preferences      Preferences
	ConfigProvenance ConfigProvenance
	Prompt           PromptContribution
	Status           StatusData
	Diagnostics      []Diagnostic
	// contains filtered or unexported fields
}

ResolvedPolicy is the normalized wake policy later runtime surfaces consume.

func Empty

func Empty(config compozyconfig.HeartbeatConfig, sourcePath string) (ResolvedPolicy, error)

Empty returns a valid absent HEARTBEAT.md resolution for non-filesystem agent sources.

func Parse

func Parse(ctx context.Context, req ParseRequest) (ResolvedPolicy, error)

Parse validates and normalizes in-memory HEARTBEAT.md content.

func Resolve

func Resolve(ctx context.Context, req ResolveRequest) (ResolvedPolicy, error)

Resolve reads and resolves HEARTBEAT.md beside the provided agent path.

type ResourceSpec

type ResourceSpec struct {
	AgentName       string `json:"agent_name"`
	AgentResourceID string `json:"agent_resource_id"`
	SourcePath      string `json:"source_path"`
	Body            string `json:"body"`
}

ResourceSpec stores read-only packaged HEARTBEAT.md content for one resource-backed agent.

type Revision

type Revision struct {
	ProfileID      string
	ID             string
	WorkspaceID    string
	AgentName      string
	SourcePath     string
	Operation      RevisionOperation
	PreviousDigest string
	NewDigest      string
	NewSnapshotID  string
	Body           string
	ActorKind      ActorKind
	ActorID        string
	CreatedAt      time.Time
}

Revision is one append-only managed HEARTBEAT.md authoring history row.

func (Revision) Normalize

func (r Revision) Normalize() Revision

Normalize trims revision metadata fields.

func (Revision) Validate

func (r Revision) Validate() error

Validate ensures the revision is append-only authoring history.

type RevisionListQuery

type RevisionListQuery struct {
	ProfileID   string
	WorkspaceID string
	AgentName   string
	SourcePath  string
	NewDigest   string
	Operation   RevisionOperation
	Limit       int
}

RevisionListQuery filters managed Heartbeat authoring revision history.

func (RevisionListQuery) Validate

func (q RevisionListQuery) Validate() error

Validate ensures the revision query uses sane bounds and operation filters.

type RevisionOperation

type RevisionOperation string

RevisionOperation describes a managed HEARTBEAT.md authoring mutation.

const (
	// RevisionOperationWrite records a create or update mutation.
	RevisionOperationWrite RevisionOperation = "write"
	// RevisionOperationDelete records a managed delete mutation.
	RevisionOperationDelete RevisionOperation = "delete"
	// RevisionOperationRollback records a managed rollback mutation.
	RevisionOperationRollback RevisionOperation = "rollback"
)

type RollbackLookup

type RollbackLookup struct {
	ProfileID   string
	WorkspaceID string
	AgentName   string
	SourcePath  string
	RevisionID  string
}

RollbackLookup selects the prior revision body used by managed rollback.

func (RollbackLookup) Validate

func (q RollbackLookup) Validate() error

Validate ensures rollback lookup identifiers are complete.

type RollbackRequest

type RollbackRequest struct {
	Target         AuthoringTarget
	RevisionID     string
	TargetDigest   string
	ExpectedDigest string
	Actor          AuthoringIdentity
}

RollbackRequest restores a prior revision or snapshot body through managed authoring.

type SessionFact

type SessionFact struct {
	ID, ProfileID, WorkspaceID, Health string
	Hidden                             bool
	LastEventAt                        time.Time
	LastSeq                            int64
}

type SessionHealth

type SessionHealth struct {
	SessionID           string
	WorkspaceID         string
	AgentName           string
	State               SessionHealthState
	Health              SessionHealthStatus
	ActivePrompt        bool
	Attachable          bool
	EligibleForWake     bool
	IneligibilityReason string
	LastActivityAt      time.Time
	LastPresenceAt      time.Time
	LastError           string
	UpdatedAt           time.Time
}

SessionHealth is the metadata-only runtime health row for one session.

func (SessionHealth) Normalize

func (h SessionHealth) Normalize() SessionHealth

Normalize trims session health metadata fields.

func (SessionHealth) Validate

func (h SessionHealth) Validate() error

Validate ensures session health remains metadata-only runtime state.

type SessionHealthIneligibilityReason

type SessionHealthIneligibilityReason string

SessionHealthIneligibilityReason is a closed reason for wake-ineligible health rows.

const (
	SessionHealthReasonPromptActive  SessionHealthIneligibilityReason = "session_prompt_active"
	SessionHealthReasonNotAttachable SessionHealthIneligibilityReason = "session_not_attachable"
	SessionHealthReasonUnhealthy     SessionHealthIneligibilityReason = "session_unhealthy"
	SessionHealthReasonStale         SessionHealthIneligibilityReason = "session_health_stale"
	SessionHealthReasonHung          SessionHealthIneligibilityReason = "session_health_hung"
	SessionHealthReasonDead          SessionHealthIneligibilityReason = "session_health_dead"
	SessionHealthReasonUnknown       SessionHealthIneligibilityReason = "session_health_unknown"
)

type SessionHealthListQuery

type SessionHealthListQuery struct {
	WorkspaceID     string
	AgentName       string
	SessionID       string
	State           SessionHealthState
	Health          SessionHealthStatus
	EligibleForWake *bool
	Limit           int
}

SessionHealthListQuery filters persisted session health rows.

func (SessionHealthListQuery) Validate

func (q SessionHealthListQuery) Validate() error

Validate ensures the health query uses sane bounds and enum filters.

type SessionHealthReader

type SessionHealthReader interface {
	GetSessionHealth(ctx context.Context, sessionID string) (SessionHealth, error)
}

SessionHealthReader provides metadata-only session health for status reads.

type SessionHealthState

type SessionHealthState string

SessionHealthState describes daemon-owned session runtime state for wake eligibility.

const (
	SessionHealthStateIdle      SessionHealthState = "idle"
	SessionHealthStatePrompting SessionHealthState = "prompting"
	SessionHealthStateStopped   SessionHealthState = "stopped"
	SessionHealthStateDetached  SessionHealthState = "detached"
)

type SessionHealthStatus

type SessionHealthStatus string

SessionHealthStatus classifies metadata-only session health.

const (
	SessionHealthHealthy  SessionHealthStatus = "healthy"
	SessionHealthDegraded SessionHealthStatus = "degraded"
	SessionHealthStale    SessionHealthStatus = "stale"
	SessionHealthDead     SessionHealthStatus = "dead"
	SessionHealthUnknown  SessionHealthStatus = "unknown"
)

type SkipRequest

type SkipRequest struct {
	Deferred                                bool
	Sources                                 []PolledSource
	ManualCheck                             bool
	InstanceID, ExpectedDue, Reason, Detail string
	Now, NextWakeAt, ExpiresAt              time.Time
}

type Snapshot

type Snapshot struct {
	ProfileID       string
	ID              string
	WorkspaceID     string
	AgentName       string
	SourcePath      string
	SchemaVersion   int
	Digest          string
	ConfigDigest    string
	Body            string
	FrontmatterJSON json.RawMessage
	ResolvedJSON    json.RawMessage
	DiagnosticsJSON json.RawMessage
	CreatedAt       time.Time
}

Snapshot is the immutable storage row for a resolved HEARTBEAT.md policy.

func SnapshotFromResolved

func SnapshotFromResolved(
	id string,
	workspaceID string,
	agentName string,
	resolved *ResolvedPolicy,
	createdAt time.Time,
	profileID string,
) (Snapshot, error)

SnapshotFromResolved creates a persistence row from a resolved Heartbeat policy.

func (Snapshot) Normalize

func (s Snapshot) Normalize() Snapshot

Normalize trims metadata fields and applies JSON defaults.

func (Snapshot) ResolvedEnvelope

func (s Snapshot) ResolvedEnvelope() (SnapshotEnvelope, error)

ResolvedEnvelope decodes the structured JSON envelope stored with the snapshot.

func (Snapshot) Validate

func (s Snapshot) Validate() error

Validate ensures the snapshot can be stored as immutable provenance.

type SnapshotEnvelope

type SnapshotEnvelope struct {
	SchemaVersion    int                `json:"schema_version"`
	Present          bool               `json:"present"`
	Active           bool               `json:"active"`
	Valid            bool               `json:"valid"`
	Summary          string             `json:"summary,omitempty"`
	GuidanceMarkdown string             `json:"guidance_markdown,omitempty"`
	Preferences      Preferences        `json:"preferences"`
	ConfigProvenance ConfigProvenance   `json:"config_provenance"`
	Prompt           PromptContribution `json:"prompt"`
	Status           StatusData         `json:"status"`
	Diagnostics      []Diagnostic       `json:"diagnostics,omitempty"`
}

SnapshotEnvelope is the structured JSON envelope stored in Snapshot.ResolvedJSON.

type SnapshotListQuery

type SnapshotListQuery struct {
	ProfileID   string
	WorkspaceID string
	AgentName   string
	Digest      string
	Limit       int
}

SnapshotListQuery filters persisted Heartbeat snapshot rows.

func (SnapshotListQuery) Validate

func (q SnapshotListQuery) Validate() error

Validate ensures the snapshot query uses sane bounds.

type SourceDecl

type SourceDecl = source.Ref

ContextProjection captures authored context projection hints.

type SourceOutcome

type SourceOutcome struct {
	ID         string        `json:"id"`
	Result     string        `json:"result"`
	Items      int           `json:"items"`
	More       bool          `json:"more"`
	DurationMS int64         `json:"duration_ms"`
	Error      *source.Error `json:"error,omitempty"`
}

type SourceState

type SourceState struct {
	ID, RefDigest               string
	Generation                  int64
	State                       jsontext.Value
	FailureStreak               int64
	NextPollAt                  time.Time
	Error                       *source.Error
	LastPolledAt, LastSuccessAt string
	LastItemCount               int64
}

type StatusData

type StatusData struct {
	Enabled                      bool               `json:"enabled"`
	Present                      bool               `json:"present"`
	Active                       bool               `json:"active"`
	Valid                        bool               `json:"valid"`
	SourcePath                   string             `json:"source_path,omitempty"`
	Digest                       string             `json:"digest,omitempty"`
	ConfigDigest                 string             `json:"config_digest,omitempty"`
	SchemaVersion                int                `json:"schema_version"`
	Summary                      string             `json:"summary,omitempty"`
	Preferences                  Preferences        `json:"preferences"`
	Diagnostics                  []Diagnostic       `json:"diagnostics,omitempty"`
	MaxBodyBytes                 int64              `json:"max_body_bytes"`
	ContextProjectionBytes       int64              `json:"context_projection_bytes"`
	ActiveSessionOnly            bool               `json:"active_session_only"`
	AllowActiveHoursPreferences  bool               `json:"allow_active_hours_preferences"`
	WakeCooldown                 time.Duration      `json:"wake_cooldown"`
	MaxWakesPerCycle             int                `json:"max_wakes_per_cycle"`
	WakeEventRetention           time.Duration      `json:"wake_event_retention"`
	SessionHealthStaleAfter      time.Duration      `json:"session_health_stale_after"`
	SessionHealthHookMinInterval time.Duration      `json:"session_health_hook_min_interval"`
	ConfigProvenance             ConfigProvenance   `json:"config_provenance"`
	Prompt                       PromptContribution `json:"prompt"`
}

StatusData is the compact inspect/status read model for policy diagnostics.

type StatusError

type StatusError struct {
	Code        string
	Diagnostics []Diagnostic
	// contains filtered or unexported fields
}

StatusError carries deterministic redacted diagnostics for status composition failures.

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) Unwrap

func (e *StatusError) Unwrap() error

Unwrap exposes the sentinel cause for errors.Is callers.

type StatusOption

type StatusOption func(*ManagedHeartbeatStatusService)

StatusOption customizes managed Heartbeat status service dependencies.

func WithHeartbeatStatusPolicyResolver

func WithHeartbeatStatusPolicyResolver(resolver PolicyResolver) StatusOption

WithHeartbeatStatusPolicyResolver injects an agent-aware policy resolver.

func WithHeartbeatStatusSessionHealthReader

func WithHeartbeatStatusSessionHealthReader(reader SessionHealthReader) StatusOption

WithHeartbeatStatusSessionHealthReader injects the session health read model.

type StatusRequest

type StatusRequest struct {
	Target               AuthoringTarget
	SessionID            string
	IncludeSessionHealth bool
}

StatusRequest identifies the policy and optional session health to compose.

type StatusResult

type StatusResult struct {
	AgentName        string
	SourcePath       string
	Enabled          bool
	Present          bool
	Active           bool
	Valid            bool
	Digest           string
	ConfigDigest     string
	SnapshotID       string
	Summary          string
	Preferences      Preferences
	Diagnostics      []Diagnostic
	ConfigProvenance ConfigProvenance
	Policy           StatusData
	WakeState        *WakeState
	SessionHealth    *SessionHealth
}

StatusResult is the transport-neutral heartbeat status payload.

type StatusService

type StatusService interface {
	Inspect(ctx context.Context, req InspectRequest) (InspectResult, error)
	Status(ctx context.Context, req StatusRequest) (StatusResult, error)
}

StatusService composes policy, wake state, and optional session health reads.

type StatusStore

type StatusStore interface {
	FindHeartbeatSnapshotByDigest(
		ctx context.Context,
		workspaceID string,
		agentName string,
		digest string,
		profileID string,
	) (Snapshot, bool, error)
	GetHeartbeatWakeState(
		ctx context.Context,
		workspaceID string,
		agentName string,
		sessionID string,
	) (WakeState, error)
	ListHeartbeatWakeState(ctx context.Context, query WakeStateListQuery) ([]WakeState, error)
}

StatusStore provides persisted Heartbeat snapshots and wake state for status reads.

type SyntheticWakePromptRequest

type SyntheticWakePromptRequest struct {
	SessionID            string
	Message              string
	TurnID               string
	WakeEventID          string
	PolicySnapshotID     string
	PolicyDigest         string
	ConfigDigest         string
	Summary              string
	SyntheticCorrelation WakeSyntheticCorrelation
}

SyntheticWakePromptRequest carries the prompt input and stable Heartbeat correlation metadata.

type SyntheticWakePromptResult

type SyntheticWakePromptResult struct {
	SyntheticPromptID string
}

SyntheticWakePromptResult reports the session prompt turn selected for a sent wake.

type SyntheticWakePrompter

type SyntheticWakePrompter interface {
	PromptHeartbeatWake(ctx context.Context, req SyntheticWakePromptRequest) (SyntheticWakePromptResult, error)
}

SyntheticWakePrompter injects one daemon-owned synthetic wake prompt through the session path.

type TaskFact

type TaskFact struct {
	ID, RunID, ProfileID, WorkspaceID, OwnerKind, OwnerSessionID, Status string
}

type TimeWindow

type TimeWindow struct {
	Timezone string `json:"timezone"`
	Start    string `json:"start"`
	End      string `json:"end"`
}

TimeWindow is one local wall-clock active or quiet window.

func (TimeWindow) Contains

func (w TimeWindow) Contains(now time.Time) (bool, error)

Contains reports whether now falls inside this local wall-clock window.

type TriageDispatcher

type TriageDispatcher interface {
	Dispatch(context.Context, *CheckTarget, CheckDigest, func(string) error) (TriageOutcome, error)
	Stop(context.Context, string) error
}

type TriageOutcome

type TriageOutcome struct {
	Result, Reason, Detail string
	DeniedCalls            int64
	Report                 *agentinstance.ReportInput
}

func ConfigUnavailableTriage

func ConfigUnavailableTriage(detail string) TriageOutcome

ConfigUnavailableTriage reports a provider configuration rejection with its diagnostic.

func TriageReplyOutcome

func TriageReplyOutcome(reply string, digest CheckDigest, limit int) TriageOutcome

TriageReplyOutcome converts provider output to a finalization that satisfies the report contract.

type TriageProposal

type TriageProposal struct {
	Sources  []AutomationEventSource `json:"sources,omitempty"`
	Title    string                  `json:"title"`
	Body     string                  `json:"body"`
	ItemKeys []string                `json:"item_keys"`
}

func ParseTriageReply

func ParseTriageReply(reply string, digest CheckDigest, limit int) ([]TriageProposal, error)

ParseTriageReply consumes only the final assistant message selected by the dispatcher.

type ValidateRequest

type ValidateRequest struct {
	Target AuthoringTarget
	Body   *string
}

ValidateRequest validates either the current HEARTBEAT.md or the provided body.

type ValidateResult

type ValidateResult struct {
	Policy ResolvedPolicy
}

ValidateResult is the transport-neutral validation response.

type WakeDecision

type WakeDecision struct {
	WakeEventID       string
	Result            WakeResult
	Reason            WakeReason
	PolicySnapshotID  string
	PolicyDigest      string
	ConfigDigest      string
	SyntheticPromptID string
	Diagnostics       []Diagnostic
}

WakeDecision reports the auditable result of one Heartbeat wake decision.

type WakeEvent

type WakeEvent struct {
	ID                string
	WorkspaceID       string
	AgentName         string
	SessionID         string
	PolicySnapshotID  string
	Source            WakeSource
	Result            WakeResult
	Reason            WakeReason
	Detail            string
	SyntheticPromptID string
	CreatedAt         time.Time
	ExpiresAt         time.Time
}

WakeEvent is one retained Heartbeat wake audit row.

func (WakeEvent) Normalize

func (e WakeEvent) Normalize() WakeEvent

Normalize trims wake event metadata fields.

func (WakeEvent) Validate

func (e WakeEvent) Validate() error

Validate ensures the wake event is retained audit state, not claimable work.

type WakeEventListQuery

type WakeEventListQuery struct {
	WorkspaceID string
	ProfileID   string
	AgentName   string
	SessionID   string
	Source      WakeSource
	Result      WakeResult
	Reason      WakeReason
	Limit       int
}

WakeEventListQuery filters retained Heartbeat wake audit rows.

func (WakeEventListQuery) Validate

func (q WakeEventListQuery) Validate() error

Validate ensures the wake event query uses sane bounds and enum filters.

type WakeOption

type WakeOption func(*ManagedWakeService)

WakeOption customizes the managed Heartbeat wake service.

func WithWakeClock

func WithWakeClock(clock func() time.Time) WakeOption

WithWakeClock injects deterministic time for wake decisions.

func WithWakeIDGenerator

func WithWakeIDGenerator(generator func(prefix string) (string, error)) WakeOption

WithWakeIDGenerator injects deterministic wake event and prompt turn IDs.

type WakeReason

type WakeReason string

WakeReason is a closed deterministic reason for Heartbeat wake state and audit.

const (
	WakeReasonSourcePollInFlight    WakeReason = "source_poll_in_flight"
	WakeReasonSent                  WakeReason = "wake_sent"
	WakeReasonHeartbeatDisabled     WakeReason = "heartbeat_disabled"
	WakeReasonHeartbeatInvalid      WakeReason = "heartbeat_invalid"
	WakeReasonHeartbeatNoPolicy     WakeReason = "heartbeat_no_policy"
	WakeReasonHeartbeatRateLimited  WakeReason = "heartbeat_rate_limited"
	WakeReasonHeartbeatNoEligible   WakeReason = "heartbeat_no_eligible_session"
	WakeReasonCooldownActive        WakeReason = "cooldown_active"
	WakeReasonQuietWindow           WakeReason = "quiet_window"
	WakeReasonSessionNotFound       WakeReason = "session_not_found"
	WakeReasonSessionUnhealthy      WakeReason = "session_unhealthy"
	WakeReasonSessionNotAttachable  WakeReason = "session_not_attachable"
	WakeReasonSessionPromptActive   WakeReason = "session_prompt_active"
	WakeReasonSessionPromptRace     WakeReason = "session_prompt_active_race"
	WakeReasonSyntheticPromptFailed WakeReason = "synthetic_prompt_failed"
	WakeReasonCoalesced             WakeReason = "wake_coalesced"
)

type WakeRequest

type WakeRequest struct {
	ProfileID            string
	WorkspaceID          string
	AgentName            string
	SessionID            string
	Source               WakeSource
	DryRun               bool
	SyntheticCorrelation WakeSyntheticCorrelation
}

WakeRequest identifies one advisory Heartbeat wake decision.

type WakeResult

type WakeResult string

WakeResult classifies the outcome of one advisory Heartbeat wake attempt.

const (
	WakeResultSent        WakeResult = "sent"
	WakeResultSkipped     WakeResult = "skipped"
	WakeResultCoalesced   WakeResult = "coalesced"
	WakeResultRateLimited WakeResult = "rate_limited"
	WakeResultFailed      WakeResult = "failed"
)

type WakeService

type WakeService interface {
	Wake(ctx context.Context, req WakeRequest) (WakeDecision, error)
	WakeMany(ctx context.Context, requests []WakeRequest) ([]WakeDecision, error)
}

WakeService evaluates Heartbeat policy and session health before issuing advisory wakes.

type WakeSource

type WakeSource string

WakeSource classifies who requested an advisory Heartbeat wake.

const (
	WakeSourceScheduler      WakeSource = "scheduler"
	WakeSourceManual         WakeSource = "manual"
	WakeSourceHarnessReentry WakeSource = "harness_reentry"
)

type WakeState

type WakeState struct {
	WorkspaceID      string
	AgentName        string
	SessionID        string
	PolicySnapshotID string
	LastWakeAt       time.Time
	NextAllowedAt    time.Time
	CoalescedCount   int
	LastResult       WakeResult
	LastReason       WakeReason
	UpdatedAt        time.Time
}

WakeState is the per-session cooldown/coalescing summary for Heartbeat wakes.

func (WakeState) Normalize

func (s WakeState) Normalize() WakeState

Normalize trims wake state metadata fields.

func (WakeState) Validate

func (s WakeState) Validate() error

Validate ensures wake state cannot become claimable work.

type WakeStateListQuery

type WakeStateListQuery struct {
	WorkspaceID string
	ProfileID   string
	AgentName   string
	SessionID   string
	Limit       int
}

WakeStateListQuery filters Heartbeat wake state rows.

func (WakeStateListQuery) Validate

func (q WakeStateListQuery) Validate() error

Validate ensures the wake state query uses sane bounds.

type WakeStore

type WakeStore interface {
	GetLatestValidHeartbeatSnapshot(
		ctx context.Context, workspaceID string, agentName string, profileID string,
	) (Snapshot, error)
	GetHeartbeatWakeState(
		ctx context.Context,
		workspaceID string,
		agentName string,
		sessionID string,
	) (WakeState, error)
	UpsertHeartbeatWakeState(ctx context.Context, state WakeState) (WakeState, error)
	AppendHeartbeatWakeEvent(ctx context.Context, event WakeEvent) (WakeEvent, error)
	RecordHeartbeatWakeDecision(ctx context.Context, event WakeEvent, state WakeState) (WakeEvent, WakeState, error)
}

WakeStore provides persisted Heartbeat policy, wake state, and wake audit rows.

type WakeSyntheticCorrelation

type WakeSyntheticCorrelation struct {
	TaskID               string
	TaskRunID            string
	WorkflowID           string
	ClaimTokenHash       string
	CoordinatorSessionID string
}

WakeSyntheticCorrelation carries optional claimed-run lineage for synthetic wake prompts emitted through the heartbeat path.

func (WakeSyntheticCorrelation) Normalize

Normalize returns a trimmed copy of the wake synthetic correlation fields.

type WorkLogFact

type WorkLogFact struct {
	ID         string
	AcceptedAt time.Time
}

func ParseWorkLog

func ParseWorkLog(content string) ([]WorkLogFact, []int)

ParseWorkLog returns accepted entries and malformed line numbers for daemon logging.

type WorkspaceRef

type WorkspaceRef struct {
	ProfileID   string
	WorkspaceID string
}

WorkspaceRef identifies the workspace scope that owns managed authoring history.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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