daemon

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 30, 2026 License: MIT Imports: 51 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrDocumentMissing reports a canonical workflow document missing on disk.
	ErrDocumentMissing = errors.New("daemon: document missing")
	// ErrStaleDocumentReference reports an opaque file id that no longer resolves.
	ErrStaleDocumentReference = errors.New("daemon: stale document reference")
	// ErrReviewIssueNotFound reports a missing review issue within a known round.
	ErrReviewIssueNotFound = errors.New("daemon: review issue not found")
)
View Source
var ErrAlreadyRunning = errors.New("daemon: already running")

Functions

func ProbeReady

func ProbeReady(ctx context.Context, info Info) error

ProbeReady verifies that one daemon info record points at a healthy transport.

func ProcessAlive

func ProcessAlive(pid int) bool

ProcessAlive reports whether a process with pid is currently alive.

func RemoveInfo

func RemoveInfo(path string) error

RemoveInfo removes daemon.json if it exists.

func Run

func Run(ctx context.Context, opts RunOptions) (retErr error)

Run starts the singleton daemon host, including persistence, transports, and services.

func WriteInfo

func WriteInfo(path string, info Info) error

WriteInfo writes daemon.json atomically via temp file and rename.

Types

type DocumentMissingError

type DocumentMissingError struct {
	Kind         string
	WorkflowSlug string
	RelativePath string
}

DocumentMissingError reports a missing canonical workflow document.

func (DocumentMissingError) Error

func (e DocumentMissingError) Error() string

func (DocumentMissingError) Is

func (e DocumentMissingError) Is(target error) bool

type Host

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

Host owns one daemon bootstrap instance and its singleton lock.

func (*Host) Close

func (h *Host) Close(_ context.Context) error

Close removes daemon discovery state and releases singleton ownership.

func (*Host) Info

func (h *Host) Info() Info

Info returns the current persisted daemon discovery info for this host.

func (*Host) MarkReady

func (h *Host) MarkReady(_ context.Context) error

MarkReady persists the ready state once startup preparation is complete.

func (*Host) Paths

func (h *Host) Paths() productizeconfig.HomePaths

Paths returns the home-scoped daemon paths for this host.

type Info

type Info struct {
	PID        int        `json:"pid"`
	Version    string     `json:"version,omitempty"`
	SocketPath string     `json:"socket_path,omitempty"`
	StartedAt  time.Time  `json:"started_at"`
	State      ReadyState `json:"state"`
}

Info is the persisted daemon discovery record written to daemon.json.

func ReadInfo

func ReadInfo(path string) (Info, error)

ReadInfo loads daemon.json from disk.

func (Info) Validate

func (i Info) Validate() error

Validate ensures the persisted daemon info is usable for discovery and readiness checks.

type Lock

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

Lock owns the singleton daemon file lock.

func AcquireLock

func AcquireLock(path string, pid int) (*Lock, error)

AcquireLock acquires the singleton daemon lock and records the current PID in the lock file.

func (*Lock) Path

func (l *Lock) Path() string

Path reports the on-disk daemon lock path.

func (*Lock) Release

func (l *Lock) Release() error

Release clears the lock file contents and releases the advisory file lock.

func (*Lock) StalePID

func (l *Lock) StalePID() int

StalePID reports the recovered stale daemon PID, if any.

type MarkdownDocument

type MarkdownDocument struct {
	ID        string
	Kind      string
	Title     string
	UpdatedAt time.Time
	Markdown  string
	Metadata  map[string]any
}

MarkdownDocument is the normalized daemon-side markdown payload.

type ProbeOptions

type ProbeOptions struct {
	ProcessAlive func(int) bool
	Healthy      func(context.Context, Info) error
}

ProbeOptions control readiness checks for an existing daemon instance.

type QueryService

type QueryService interface {
	WorkflowOverview(ctx context.Context, workspaceRef string, workflowSlug string) (WorkflowOverviewPayload, error)
	TaskBoard(ctx context.Context, workspaceRef string, workflowSlug string) (TaskBoardPayload, error)
	WorkflowSpec(ctx context.Context, workspaceRef string, workflowSlug string) (WorkflowSpecDocument, error)
	WorkflowMemoryIndex(ctx context.Context, workspaceRef string, workflowSlug string) (WorkflowMemoryIndex, error)
	WorkflowMemoryFile(
		ctx context.Context,
		workspaceRef string,
		workflowSlug string,
		fileID string,
	) (MarkdownDocument, error)
	TaskDetail(ctx context.Context, workspaceRef string, workflowSlug string, taskID string) (TaskDetailPayload, error)
	ReviewDetail(
		ctx context.Context,
		workspaceRef string,
		workflowSlug string,
		round int,
		issueRef string,
	) (ReviewDetailPayload, error)
	RunDetail(ctx context.Context, runID string) (RunDetailPayload, error)
}

QueryService exposes the daemon-side read-model assembly required by the web UI.

func NewQueryService

func NewQueryService(cfg QueryServiceConfig) QueryService

NewQueryService constructs the daemon-side read-model query layer.

type QueryServiceConfig

type QueryServiceConfig struct {
	GlobalDB   *globaldb.GlobalDB
	RunManager *RunManager
}

QueryServiceConfig wires the daemon read-model service.

type ReadyState

type ReadyState string

ReadyState is the persisted daemon readiness state.

const (
	ReadyStateStarting ReadyState = "starting"
	ReadyStateReady    ReadyState = "ready"
	ReadyStateStopped  ReadyState = "stopped"
)

type ReconcileConfig

type ReconcileConfig struct {
	HomePaths    productizeconfig.HomePaths
	Now          func() time.Time
	OpenGlobalDB func(context.Context, string) (*globaldb.GlobalDB, error)
	OpenRunDB    func(context.Context, string) (*rundb.RunDB, error)
}

ReconcileConfig controls startup crash reconciliation.

type ReconcileResult

type ReconcileResult struct {
	ReconciledRuns      int
	CrashEventAppended  int
	CrashEventFailures  int
	LastReconciledRunID string
}

ReconcileResult summarizes one startup reconciliation pass.

func ReconcileStartup

func ReconcileStartup(ctx context.Context, cfg ReconcileConfig) (ReconcileResult, error)

ReconcileStartup marks interrupted runs as crashed before the daemon reports ready. Missing or corrupt per-run databases do not block readiness; their failure is folded into the durable global error summary instead.

type ReviewDetailPayload

type ReviewDetailPayload struct {
	Workspace   apicore.Workspace
	Workflow    apicore.WorkflowSummary
	Round       apicore.ReviewRound
	Issue       ReviewIssueDetail
	Document    MarkdownDocument
	RelatedRuns []apicore.Run
}

ReviewDetailPayload captures the daemon-side review issue detail read model.

type ReviewIssueDetail

type ReviewIssueDetail struct {
	ID          string
	IssueNumber int
	Severity    string
	Status      string
	UpdatedAt   time.Time
}

ReviewIssueDetail captures the detail metadata for one review issue.

type ReviewIssueNotFoundError

type ReviewIssueNotFoundError struct {
	WorkflowSlug string
	Round        int
	IssueRef     string
}

ReviewIssueNotFoundError reports a missing issue inside a known review round.

func (ReviewIssueNotFoundError) Error

func (e ReviewIssueNotFoundError) Error() string

func (ReviewIssueNotFoundError) Is

func (e ReviewIssueNotFoundError) Is(target error) bool

type ReviewWatchGit

type ReviewWatchGit interface {
	State(ctx context.Context, workspaceRoot string) (ReviewWatchGitState, error)
	Push(ctx context.Context, workspaceRoot string, remote string, branch string) error
}

ReviewWatchGit is the narrow git boundary used by daemon review-watch runs.

type ReviewWatchGitState

type ReviewWatchGitState struct {
	Branch          string
	HeadSHA         string
	UpstreamRemote  string
	UpstreamBranch  string
	Dirty           bool
	UnpushedCommits int
}

ReviewWatchGitState captures read-only repository state relevant to watch push safety.

type RunDetailPayload

type RunDetailPayload struct {
	Run          apicore.Run
	Snapshot     apicore.RunSnapshot
	JobCounts    RunJobCounts
	Runtime      RunRuntimeSummary
	Timeline     []eventspkg.Event
	ArtifactSync []rundb.ArtifactSyncRow
}

RunDetailPayload captures the daemon-side run detail read model.

type RunJobCounts

type RunJobCounts struct {
	Queued    int
	Running   int
	Retrying  int
	Completed int
	Failed    int
	Canceled  int
}

RunJobCounts summarizes per-status job counts for one run snapshot.

type RunLifecycleSettings

type RunLifecycleSettings struct {
	KeepTerminalDays     int
	KeepMax              int
	ShutdownDrainTimeout time.Duration
}

RunLifecycleSettings captures the daemon-owned retention and shutdown bounds resolved from the effective home-scoped config.

func LoadRunLifecycleSettings

func LoadRunLifecycleSettings(ctx context.Context) (RunLifecycleSettings, string, error)

LoadRunLifecycleSettings reads the home-scoped config and resolves the daemon run lifecycle defaults required for retention and forced shutdown behavior.

type RunManager

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

RunManager owns daemon-backed task, review, and exec runs.

func NewRunManager

func NewRunManager(cfg RunManagerConfig) (*RunManager, error)

NewRunManager constructs a daemon-owned run manager.

func (*RunManager) ACPStallTotalsByMode

func (m *RunManager) ACPStallTotalsByMode() map[string]uint64

ACPStallTotalsByMode reports daemon-lifetime ACP stall counts keyed by mode.

func (*RunManager) ActiveRunCount

func (m *RunManager) ActiveRunCount() int

ActiveRunCount returns the number of runs still owned by the live daemon.

func (*RunManager) ActiveRunCountsByMode

func (m *RunManager) ActiveRunCountsByMode() map[string]int

ActiveRunCountsByMode returns the current active-run breakdown by run mode.

func (*RunManager) Cancel

func (m *RunManager) Cancel(ctx context.Context, runID string) error

Cancel requests cancellation for one active run.

func (*RunManager) Events

func (m *RunManager) Events(
	ctx context.Context,
	runID string,
	query apicore.RunEventPageQuery,
) (apicore.RunEventPage, error)

Events returns persisted run events after the supplied cursor.

func (*RunManager) Get

func (m *RunManager) Get(ctx context.Context, runID string) (apicore.Run, error)

Get returns one durable run summary.

func (*RunManager) IncompleteRunCount

func (m *RunManager) IncompleteRunCount() int

IncompleteRunCount reports how many runs this daemon has observed with sticky persisted integrity issues.

func (*RunManager) JournalSubmitDropTotals

func (m *RunManager) JournalSubmitDropTotals() (uint64, uint64)

JournalSubmitDropTotals reports daemon-lifetime journal submit drop counts grouped by dropped event kind.

func (*RunManager) List

func (m *RunManager) List(ctx context.Context, query apicore.RunListQuery) ([]apicore.Run, error)

List returns durable run summaries filtered by workspace, mode, or status.

func (*RunManager) OpenStream

func (m *RunManager) OpenStream(
	ctx context.Context,
	runID string,
	after apicore.StreamCursor,
) (apicore.RunStream, error)

OpenStream returns a replay-plus-live run stream.

func (*RunManager) OpenWorkspaceStream

func (m *RunManager) OpenWorkspaceStream(
	ctx context.Context,
	workspaceRef string,
) (apicore.WorkspaceEventStream, error)

func (*RunManager) Purge

Purge deletes terminal run directories and their durable index rows according to the configured oldest-first retention policy.

func (*RunManager) RunDetail

func (m *RunManager) RunDetail(ctx context.Context, runID string) (apicore.RunDetailPayload, error)

RunDetail returns the richer browser-facing run detail payload.

func (*RunManager) Shutdown

func (m *RunManager) Shutdown(ctx context.Context, force bool) error

Shutdown applies the daemon stop semantics for active runs. Without force it returns a conflict while active runs exist. With force it cancels every run and waits only up to the configured drain timeout for their terminal cleanup.

func (*RunManager) Snapshot

func (m *RunManager) Snapshot(ctx context.Context, runID string) (apicore.RunSnapshot, error)

Snapshot returns the dense attach snapshot for one run.

func (*RunManager) StartExecRun

func (m *RunManager) StartExecRun(
	ctx context.Context,
	req apicore.ExecRequest,
) (apicore.Run, error)

StartExecRun starts one daemon-owned exec run.

func (*RunManager) StartReviewRun

func (m *RunManager) StartReviewRun(
	ctx context.Context,
	workspaceRef string,
	workflowSlug string,
	round int,
	req apicore.ReviewRunRequest,
) (apicore.Run, error)

StartReviewRun starts one daemon-owned review-fix run.

func (*RunManager) StartReviewWatch

func (m *RunManager) StartReviewWatch(
	ctx context.Context,
	workspaceRef string,
	workflowSlug string,
	req apicore.ReviewWatchRequest,
) (apicore.Run, error)

StartReviewWatch starts one daemon-owned review-watch parent run.

func (*RunManager) StartTaskRun

func (m *RunManager) StartTaskRun(
	ctx context.Context,
	workspaceRef string,
	workflowSlug string,
	req apicore.TaskRunRequest,
) (apicore.Run, error)

StartTaskRun starts one daemon-owned task workflow run.

func (*RunManager) TerminalTotalsByModeAndStatus

func (m *RunManager) TerminalTotalsByModeAndStatus() map[string]map[string]uint64

TerminalTotalsByModeAndStatus reports daemon-lifetime terminal outcome totals keyed by mode then status.

func (*RunManager) Transcript

func (m *RunManager) Transcript(ctx context.Context, runID string) (apicore.RunTranscript, error)

Transcript returns the canonical structured transcript for one run.

type RunManagerConfig

type RunManagerConfig struct {
	GlobalDB               *globaldb.GlobalDB
	LifecycleContext       context.Context
	ShutdownDrainTimeout   time.Duration
	Now                    func() time.Time
	BuildRunID             func(*model.RuntimeConfig) (string, error)
	OpenRunScope           func(context.Context, *model.RuntimeConfig, model.OpenRunScopeOptions) (model.RunScope, error)
	Prepare                func(context.Context, *model.RuntimeConfig, model.RunScope) (*model.SolvePreparation, error)
	Execute                func(context.Context, *model.SolvePreparation, *model.RuntimeConfig) error
	ExecuteExec            func(context.Context, *model.RuntimeConfig, model.RunScope) error
	OpenRunDB              func(context.Context, string) (*rundb.RunDB, error)
	LoadProjectConfig      func(context.Context, string) (workspacecfg.ProjectConfig, error)
	ReviewProviderRegistry reviewProviderRegistryFactory
	ReviewWatchGit         ReviewWatchGit
	WatcherDebounce        time.Duration
	RunDBCacheTTL          time.Duration
	LookupWorkflowSlugs    func(context.Context, []string) (map[string]string, error)
	GetWorkflow            func(context.Context, string) (globaldb.Workflow, error)
}

RunManagerConfig wires the daemon-owned run manager dependencies.

type RunMode

type RunMode string

RunMode controls daemon signal and logging ownership.

const (
	RunModeForeground RunMode = "foreground"
	RunModeDetached   RunMode = "detached"
)

type RunOptions

type RunOptions struct {
	Version string
	Mode    RunMode
}

RunOptions control the long-lived daemon host process.

type RunPurgeResult

type RunPurgeResult struct {
	PurgedRunIDs []string
}

RunPurgeResult captures the terminal runs removed by one purge operation.

func PurgeTerminalRuns

func PurgeTerminalRuns(
	ctx context.Context,
	db *globaldb.GlobalDB,
	settings RunLifecycleSettings,
) (RunPurgeResult, error)

PurgeTerminalRuns deletes terminal run directories and durable index rows using the configured retention policy without requiring a live run manager.

type RunRuntimeSummary

type RunRuntimeSummary struct {
	IDEs              []string
	Models            []string
	ReasoningEfforts  []string
	AccessModes       []string
	PresentationModes []string
}

RunRuntimeSummary captures the distinct runtime settings observed in the run snapshot.

type Service

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

Service implements the shared transport-facing daemon control surface.

func NewService

func NewService(cfg ServiceConfig) *Service

NewService constructs the daemon-wide control service.

func (*Service) Health

func (s *Service) Health(ctx context.Context) (apicore.DaemonHealth, error)

Health reports readiness and any degraded state known to the daemon.

func (*Service) Metrics

func (s *Service) Metrics(ctx context.Context) (apicore.MetricsPayload, error)

Metrics returns the minimal daemon metrics required by the current transport contract and lifecycle task set.

func (*Service) Status

func (s *Service) Status(ctx context.Context) (apicore.DaemonStatus, error)

Status returns the current daemon status snapshot.

func (*Service) Stop

func (s *Service) Stop(ctx context.Context, force bool) error

Stop enforces the daemon stop contract, delegating active-run ownership to the daemon run manager and then invoking the host stop callback.

type ServiceConfig

type ServiceConfig struct {
	Host              *Host
	GlobalDB          *globaldb.GlobalDB
	RunManager        *RunManager
	RequestStop       func(context.Context) error
	ReconcileResult   ReconcileResult
	LifecycleSettings RunLifecycleSettings
	Now               func() time.Time
}

ServiceConfig wires the daemon-wide status, health, metrics, and stop surface exposed to transports.

type StaleDocumentReferenceError

type StaleDocumentReferenceError struct {
	Kind         string
	WorkflowSlug string
	Reference    string
}

StaleDocumentReferenceError reports an opaque memory file identifier that no longer resolves.

func (StaleDocumentReferenceError) Error

func (StaleDocumentReferenceError) Is

func (e StaleDocumentReferenceError) Is(target error) bool

type StartOptions

type StartOptions struct {
	HomePaths    productizeconfig.HomePaths
	Version      string
	PID          int
	Now          func() time.Time
	ProcessAlive func(int) bool
	Healthy      func(context.Context, Info) error
	Prepare      func(context.Context, *Host) error
}

StartOptions control daemon bootstrap behavior.

type StartOutcome

type StartOutcome string

StartOutcome describes the bootstrap result for one daemon start attempt.

const (
	StartOutcomeStarted        StartOutcome = "started"
	StartOutcomeAlreadyRunning StartOutcome = "already_running"
)

type StartResult

type StartResult struct {
	Outcome StartOutcome
	Paths   productizeconfig.HomePaths
	Info    Info
	Host    *Host
}

StartResult captures the result of a daemon bootstrap attempt.

func Start

func Start(ctx context.Context, opts StartOptions) (_ StartResult, retErr error)

Start bootstraps the daemon home layout, acquires singleton ownership, and marks readiness.

type Status

type Status struct {
	Paths   productizeconfig.HomePaths
	State   ReadyState
	Healthy bool
	Info    *Info
}

Status captures the last known daemon readiness view.

func QueryStatus

func QueryStatus(ctx context.Context, paths productizeconfig.HomePaths, opts ProbeOptions) (Status, error)

QueryStatus reports the current daemon readiness without guessing from the filesystem layout.

type TaskBoardPayload

type TaskBoardPayload struct {
	Workspace  apicore.Workspace
	Workflow   apicore.WorkflowSummary
	TaskCounts WorkflowTaskCounts
	Lanes      []TaskLane
}

TaskBoardPayload captures the kanban/list task read model.

type TaskCard

type TaskCard struct {
	TaskNumber int
	TaskID     string
	Title      string
	Status     string
	Type       string
	DependsOn  []string
	UpdatedAt  time.Time
}

TaskCard is the transport-neutral task row used by workflow and detail views.

type TaskDetailPayload

type TaskDetailPayload struct {
	Workspace         apicore.Workspace
	Workflow          apicore.WorkflowSummary
	Task              TaskCard
	Document          MarkdownDocument
	MemoryEntries     []WorkflowMemoryEntry
	RelatedRuns       []apicore.Run
	LiveTailAvailable bool
}

TaskDetailPayload captures the daemon-side task detail read model.

type TaskLane

type TaskLane struct {
	Status string
	Title  string
	Items  []TaskCard
}

TaskLane groups task cards by normalized status.

type WorkflowMemoryEntry

type WorkflowMemoryEntry struct {
	FileID      string
	DisplayPath string
	Kind        string
	Title       string
	SizeBytes   int64
	UpdatedAt   time.Time
}

WorkflowMemoryEntry describes one memory file without exposing a raw source path.

type WorkflowMemoryIndex

type WorkflowMemoryIndex struct {
	Workspace apicore.Workspace
	Workflow  apicore.WorkflowSummary
	Entries   []WorkflowMemoryEntry
}

WorkflowMemoryIndex lists memory files using opaque IDs.

type WorkflowOverviewPayload

type WorkflowOverviewPayload struct {
	Workspace       apicore.Workspace
	Workflow        apicore.WorkflowSummary
	TaskCounts      WorkflowTaskCounts
	LatestReview    *apicore.ReviewSummary
	RecentRuns      []apicore.Run
	ArchiveEligible bool
	ArchiveReason   string
}

WorkflowOverviewPayload is the daemon-side workflow summary aggregate.

type WorkflowSpecDocument

type WorkflowSpecDocument struct {
	Workspace apicore.Workspace
	Workflow  apicore.WorkflowSummary
	PRD       *MarkdownDocument
	TechSpec  *MarkdownDocument
	ADRs      []MarkdownDocument
}

WorkflowSpecDocument captures the canonical workflow spec artifacts.

type WorkflowTaskCounts

type WorkflowTaskCounts struct {
	Total     int
	Completed int
	Pending   int
}

WorkflowTaskCounts summarizes task state for one workflow.

Jump to

Keyboard shortcuts

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