advruntime

package
v0.0.0-...-c863b29 Latest Latest
Warning

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

Go to latest
Published: May 9, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package advruntime contains read-only ADV runtime health models used by doctor, session preflight, recovery planning, and dashboard surfaces.

Index

Constants

View Source
const (
	DefaultAddress   = "127.0.0.1:7233"
	DefaultNamespace = "default"
)

Variables

View Source
var ErrProviderClosed = errors.New("temporal client provider closed")

Functions

func DefaultADVStateRoot

func DefaultADVStateRoot() string

DefaultADVStateRoot returns the default ADV plugin state root directory. If XDG_DATA_HOME is set, it wins. If home directory cannot be resolved, returns empty string.

func DefaultOpenCodeDBPath

func DefaultOpenCodeDBPath() string

DefaultOpenCodeDBPath returns the default path to OpenCode's SQLite database. If XDG_DATA_HOME is set, it wins. If home directory cannot be resolved, returns empty string.

func DefaultWorktreeRoot

func DefaultWorktreeRoot() string

DefaultWorktreeRoot returns the default OCA worktree root directory. If XDG_DATA_HOME is set, it wins. If home directory cannot be resolved, returns empty string.

func RequiredSearchAttributes

func RequiredSearchAttributes() map[string]enumspb.IndexedValueType

Types

type ApplyDeletionOptions

type ApplyDeletionOptions struct {
	// BackupDir is required. ApplyDeletion refuses to run without it.
	BackupDir string
}

ApplyDeletionOptions controls the deletion behavior.

type BackupManifest

type BackupManifest struct {
	SourcePath    string    `json:"source_path"`
	BackupPath    string    `json:"backup_path"`
	ManifestError string    `json:"manifest_error,omitempty"`
	Timestamp     time.Time `json:"timestamp"`
	Threshold     string    `json:"threshold"`
	DeletedIDs    []string  `json:"deleted_ids"`
	FileCount     int       `json:"file_count"`
}

BackupManifest records what was backed up and deleted.

type ClientProvider

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

func NewTemporalClientProvider

func NewTemporalClientProvider(config Config, dial DialFunc) *ClientProvider

func (*ClientProvider) Client

func (*ClientProvider) Close

func (p *ClientProvider) Close()

type Config

type Config struct {
	Address            string        `json:"address"`
	Namespace          string        `json:"namespace"`
	ProjectID          string        `json:"project_id,omitempty"`
	ChangeID           string        `json:"change_id,omitempty"`
	MaxWorkflows       int           `json:"max_workflows"`
	WorkflowStaleAfter time.Duration `json:"workflow_stale_after"`
	SessionStaleAfter  time.Duration `json:"session_stale_after"`
	WorktreeStaleAfter time.Duration `json:"worktree_stale_after"`
	TaskQueueNoPoller  time.Duration `json:"task_queue_no_poller"`
}

Config captures runtime scan inputs and threshold overrides. Zero values are normalized through WithDefaults before use.

func (Config) WithDefaults

func (c Config) WithDefaults() Config

type DialFunc

type DialFunc func(context.Context, client.Options) (TemporalClient, error)

type EnrichedSession

type EnrichedSession struct {
	Name     string `json:"name"`
	Attached bool   `json:"attached"`
	Path     string `json:"path"`

	// ADV workspace projection (empty when ADV unavailable)
	WorkspaceStatus     string `json:"workspaceStatus,omitempty"`
	WorkspaceChangeID   string `json:"workspaceChangeId,omitempty"`
	WorkspaceBranch     string `json:"workspaceBranch,omitempty"`
	WorkspaceSetupReady bool   `json:"workspaceSetupReady,omitempty"`
	WorkspaceFailure    string `json:"workspaceFailure,omitempty"`
}

EnrichedSession enriches an OCA session with projected ADV workspace state when available. Fields are informational only — OCA never writes them.

func EnrichSessionsWithWorkspaceState

func EnrichSessionsWithWorkspaceState(
	sessions []SessionView,
	projection *WorkspaceProjection,
) []EnrichedSession

EnrichSessionsWithWorkspaceState enriches OCA session data with ADV workspace projection states. Returns enriched sessions; when the ADV projection is unavailable, sessions are returned with empty workspace fields (graceful degradation).

type FakeClientProvider

type FakeClientProvider struct {
	ClientValue TemporalClient
	Err         error
}

func NewFakeTemporalClientProvider

func NewFakeTemporalClientProvider(client TemporalClient, err error) *FakeClientProvider

func (*FakeClientProvider) Client

func (*FakeClientProvider) Close

func (p *FakeClientProvider) Close()

type Finding

type Finding struct {
	Code     string   `json:"code"`
	Severity Severity `json:"severity"`
	Message  string   `json:"message"`
	Hint     string   `json:"hint,omitempty"`
}

type OperatorService

OperatorService is the narrow Temporal operator service surface used by the search-attribute checker. operatorservice.OperatorServiceClient satisfies it.

type RecoveryPlanSynthesizer

type RecoveryPlanSynthesizer struct{}

RecoveryPlanSynthesizer turns a runtime report into an ordered list of dry-run recovery steps. It does not mutate the report or execute any commands.

func NewRecoveryPlanSynthesizer

func NewRecoveryPlanSynthesizer() *RecoveryPlanSynthesizer

NewRecoveryPlanSynthesizer creates a synthesizer.

func (*RecoveryPlanSynthesizer) Synthesize

func (s *RecoveryPlanSynthesizer) Synthesize(report Report) []RecoveryStep

Synthesize produces recovery steps from the given report. The report is not modified. Steps are ordered by priority: search attributes → queues → session debt → worktree debt.

type RecoveryStep

type RecoveryStep struct {
	Order       int      `json:"order"`
	Title       string   `json:"title"`
	Command     []string `json:"command,omitempty"`
	DryRunOnly  bool     `json:"dry_run_only"`
	Destructive bool     `json:"destructive"`
	Reason      string   `json:"reason,omitempty"`
}

type Report

type Report struct {
	GeneratedAt      time.Time               `json:"generated_at"`
	Config           Config                  `json:"config"`
	Summary          Summary                 `json:"summary"`
	WorkflowQueues   []WorkflowQueueStatus   `json:"workflow_queues"`
	SearchAttributes []SearchAttributeStatus `json:"search_attributes"`
	SessionDebt      []SessionDebtFinding    `json:"session_debt"`
	Worktrees        []WorktreeFinding       `json:"worktrees"`
	Findings         []Finding               `json:"findings"`
	RecoveryPlan     []RecoveryStep          `json:"recovery_plan,omitempty"`
}

func NewReport

func NewReport(config Config) Report

type SearchAttributeChecker

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

func NewSearchAttributeChecker

func NewSearchAttributeChecker(service OperatorService, config Config) *SearchAttributeChecker

func (*SearchAttributeChecker) Check

type SearchAttributeStatus

type SearchAttributeStatus struct {
	Name     string `json:"name"`
	Expected string `json:"expected"`
	Actual   string `json:"actual,omitempty"`
	Status   Status `json:"status"`
	Message  string `json:"message,omitempty"`
	Hint     string `json:"hint,omitempty"`
}

type SessionDebtFinding

type SessionDebtFinding struct {
	Path       string        `json:"path"`
	Status     Status        `json:"status"`
	Repairable int           `json:"repairable"`
	Ignored    int           `json:"ignored"`
	OldestAge  time.Duration `json:"oldest_age,omitempty"`
	Message    string        `json:"message,omitempty"`
	Hint       string        `json:"hint,omitempty"`
}

type SessionDebtScanner

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

SessionDebtScanner classifies and optionally cleans up stale blank assistant messages from OpenCode's SQLite session database.

Safety: Scan is read-only. ApplyDeletion requires a backup directory and only deletes rows identified as repairable in the same scan run.

func NewSessionDebtScanner

func NewSessionDebtScanner(db *sql.DB, config Config) *SessionDebtScanner

NewSessionDebtScanner creates a scanner for the given SQLite database handle. The db handle must be open and point to a valid OpenCode database. dbPath is the filesystem path to the database file (used for backup).

func (*SessionDebtScanner) ApplyDeletion

ApplyDeletion scans for repairable rows, backs up the database, and deletes them. It refuses to run without a backup directory.

func (*SessionDebtScanner) Scan

Scan inspects the database for session debt and returns a finding. It is read-only and does not modify the database.

type SessionView

type SessionView struct {
	Name     string
	Attached bool
	Path     string
}

SessionView is a minimal session interface that OCA session structs satisfy. Defined here to avoid importing the session package (which requires tmux).

type Severity

type Severity string
const (
	SeverityInfo  Severity = "info"
	SeverityWarn  Severity = "warn"
	SeverityError Severity = "error"
)

type Status

type Status string
const (
	StatusPass    Status = "pass"
	StatusWarn    Status = "warn"
	StatusFail    Status = "fail"
	StatusUnknown Status = "unknown"
)

type Summary

type Summary struct {
	Status                  Status `json:"status"`
	Projects                int    `json:"projects"`
	WorkflowQueues          int    `json:"workflow_queues"`
	StaleWorkflowQueues     int    `json:"stale_workflow_queues"`
	MissingSearchAttributes int    `json:"missing_search_attributes"`
	SessionDebt             int    `json:"session_debt"`
	WorktreeDebt            int    `json:"worktree_debt"`
	Findings                int    `json:"findings"`
}

type TemporalClient

type TemporalClient interface {
	WorkflowService() workflowservice.WorkflowServiceClient
	OperatorService() operatorservice.OperatorServiceClient
	Close()
}

TemporalClient is the narrow subset of Temporal SDK client.Client used by ADV runtime health. Keeping this interface small makes classifier tests pure Go and avoids requiring a live Temporal server.

func DefaultTemporalDialer

func DefaultTemporalDialer(ctx context.Context, opts client.Options) (TemporalClient, error)

type Thresholds

type Thresholds struct {
	MaxWorkflows       int           `json:"max_workflows"`
	WorkflowStaleAfter time.Duration `json:"workflow_stale_after"`
	SessionStaleAfter  time.Duration `json:"session_stale_after"`
	WorktreeStaleAfter time.Duration `json:"worktree_stale_after"`
	TaskQueueNoPoller  time.Duration `json:"task_queue_no_poller"`
}

Thresholds are tunable cutoffs for runtime debt classification. They are intentionally conservative and mutation-free; callers decide how to render warnings or recovery hints.

func DefaultThresholds

func DefaultThresholds() Thresholds

type WorkerLockFinding

type WorkerLockFinding struct {
	ProjectID string        `json:"project_id"`
	Path      string        `json:"path"`
	PID       int           `json:"pid,omitempty"`
	WorkerID  string        `json:"worker_id,omitempty"`
	Status    Status        `json:"status"`
	Age       time.Duration `json:"age,omitempty"`
	Message   string        `json:"message,omitempty"`
	Hint      string        `json:"hint,omitempty"`
}

WorkerLockFinding reports read-only observations about ADV worker singleton locks. OCA never mutates or reclaims these locks; Advance owns worker lifecycle and recovery.

type WorkerLockScanner

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

func NewWorkerLockScanner

func NewWorkerLockScanner(advRoot string, staleAfter time.Duration) *WorkerLockScanner

func (*WorkerLockScanner) Scan

type WorkflowClassifier

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

func NewWorkflowClassifier

func NewWorkflowClassifier(service WorkflowService, config Config, now func() time.Time) *WorkflowClassifier

func (*WorkflowClassifier) Classify

func (c *WorkflowClassifier) Classify(ctx context.Context) (Report, error)

type WorkflowQueueStatus

type WorkflowQueueStatus struct {
	ProjectID        string        `json:"project_id,omitempty"`
	TaskQueue        string        `json:"task_queue"`
	Status           Status        `json:"status"`
	Pollers          int           `json:"pollers"`
	Backlog          int64         `json:"backlog"`
	RunningWorkflows int           `json:"running_workflows"`
	OldestRunAge     time.Duration `json:"oldest_run_age,omitempty"`
	Message          string        `json:"message,omitempty"`
	Hint             string        `json:"hint,omitempty"`
}

type WorkflowService

WorkflowService is the narrow Temporal workflow service surface used by the classifier. workflowservice.WorkflowServiceClient satisfies this interface.

type WorkspaceProjection

type WorkspaceProjection struct {
	ProjectID string                   `json:"projectId"`
	Worktrees []WorktreeWorkspaceState `json:"worktrees"`
}

WorkspaceProjection holds all projected workspace states for a project.

func ProjectWorkspaceStates

func ProjectWorkspaceStates(projectID string) (*WorkspaceProjection, error)

ProjectWorkspaceStates reads the ADV worktree registry projection for the given projectID. Returns an empty projection (never nil) when the registry is unavailable or empty — OCA degrades gracefully.

The registry lives in the ADV Temporal state store at:

$XDG_DATA_HOME/opencode/plugins/advance/{projectID}/

OCA reads the cached project state snapshot if available, or returns empty. This is intentionally non-authoritative: ADV Temporal is the source of truth.

type WorktreeCensus

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

WorktreeCensus scans OCA worktree roots and ADV project state roots, classifying worktrees as active or stale. It never deletes anything.

func NewWorktreeCensus

func NewWorktreeCensus(worktreeRoot, advRoot string, config Config) *WorktreeCensus

NewWorktreeCensus creates a census scanner for the given root directories.

func (*WorktreeCensus) Scan

Scan discovers worktrees across all project roots and returns findings. Returns an empty slice (not nil) if no worktrees are found.

type WorktreeFinding

type WorktreeFinding struct {
	Path    string        `json:"path"`
	Branch  string        `json:"branch,omitempty"`
	Status  Status        `json:"status"`
	Age     time.Duration `json:"age,omitempty"`
	Message string        `json:"message,omitempty"`
	Hint    string        `json:"hint,omitempty"`
}

type WorktreeWorkspaceState

type WorktreeWorkspaceState struct {
	Branch             string `json:"branch"`
	Path               string `json:"path,omitempty"`
	Materialized       bool   `json:"materialized"`
	ChangeID           string `json:"changeId,omitempty"`
	Status             string `json:"status"` // active, idle, setup_failed, materializing, pending_delete, merged, stale, deleted
	SetupReady         bool   `json:"setupReady"`
	SetupFailureReason string `json:"setupFailureReason,omitempty"`
	BaseRef            string `json:"baseRef,omitempty"`
	HeadSha            string `json:"headSha,omitempty"`
	Source             string `json:"source,omitempty"`
}

WorktreeWorkspaceState represents the projected workspace state of a single ADV worktree as read from the ADV Temporal-backed worktree registry. OCA reads this as a non-authoritative, rebuildable projection — OCA never writes to the registry.

Jump to

Keyboard shortcuts

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