heartbeat

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package heartbeat resolves optional HEARTBEAT.md wake-policy artifacts.

Index

Constants

View Source
const (
	// FileName is the canonical authored wake-policy filename.
	FileName = "HEARTBEAT.md"
)
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")
)

Functions

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 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.

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 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) 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,
	) (Snapshot, bool, error)
}

AuthoringStore is the persistence boundary used by managed Heartbeat authoring.

type AuthoringTarget

type AuthoringTarget struct {
	WorkspaceID   string
	WorkspaceRoot string
	AgentName     string
	AgentPath     string
	Config        aghconfig.HeartbeatConfig
}

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

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 aghconfig.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 {
	Include []string `json:"include,omitempty"`
}

ContextProjection captures authored context projection hints.

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,omitempty"`
	Column     int    `json:"column,omitempty"`
}

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 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 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 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) 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 aghconfig.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 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        aghconfig.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 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        aghconfig.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 aghconfig.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 {
	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 {
	WorkspaceID string
	AgentName   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 {
	WorkspaceID string
	AgentName   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 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 Snapshot

type Snapshot struct {
	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,
) (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 {
	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 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,
	) (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 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 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
	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
	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) 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 (
	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 {
	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
	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) (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.

Jump to

Keyboard shortcuts

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