Documentation
¶
Overview ¶
Package daemon is the resident process behind the serve command: it runs the collector and the sweep on a schedule and serves the API on a Unix socket and on a token-guarded localhost port.
Index ¶
- Constants
- Variables
- func BadRequest(msg string) error
- func BriefMissing(ctx context.Context) string
- func CheckInputs(reg *dintent.Registry, d dintent.Def, in map[string]any, ...) (map[string]any, error)
- func LockFile(path string, busy error) (unlock func(), err error)
- func LoopHeld(ctx context.Context) bool
- func NotOffered(action string, u unit.Unit) string
- func ReadInfo(path string) (api.Info, error)
- func StoreWarning(st api.StoreStatus) string
- type Actions
- type AheadReader
- type AppState
- type BriefHealth
- type BriefQueue
- type BriefReads
- type Budget
- type Call
- type CardsJob
- type Collector
- type Deps
- type Drafts
- type EventLog
- type Explained
- type Explainer
- type Explorer
- type GitAccessLog
- type Headless
- type Implemented
- type IngestJob
- type ItemsLedger
- type Metas
- type Notices
- type Overrides
- type Pauses
- type Placer
- type Plan
- type PluginJob
- type PluginRuntime
- type PullRequests
- type Records
- type Refusal
- type Server
- func (s *Server) AuthHandler() http.Handler
- func (s *Server) BriefReady(ctx context.Context, u unit.Unit) (intake.Readiness, error)
- func (s *Server) Handler() http.Handler
- func (s *Server) OpenIntakes(ctx context.Context) ([]intake.Intake, error)
- func (s *Server) RecheckHomes(ctx context.Context)
- func (s *Server) Run(ctx context.Context) error
- func (s *Server) RunJob(name string) bool
- type StoreWait
- type SweepFunc
- type Sweeper
- type Unblocker
Constants ¶
const ( ProbeOwner = "loop-e2e" ProbeRepo = "probe" )
ProbeOwner and ProbeRepo name the pull request of every probe: one that exists nowhere, so no inventory holds it and no view has a role for it.
const FailureDays = 14
FailureDays is how long after a merge a fix or a revert of the same files counts as that change failing.
const HomesMaxAge = 10 * time.Minute
HomesMaxAge is how old the last check of the agent homes may be before a health read starts another in the background.
const (
ReadModelCheckEnv = "LOOP_READMODEL_CHECK"
)
const ReconcileWait = 30 * time.Second
ReconcileWait is how long UserAPI waits for the start-up reconcile before it serves anyway.
const RecordFileSlack = 2 * time.Second
RecordFileSlack is how much older than its turn's start a record file may be.
const ShutdownGrace = 5 * time.Second
ShutdownGrace is how long the daemon waits for open requests to finish when it stops.
Variables ¶
var ErrAlreadyRunning = errors.New("daemon already running")
Functions ¶
func BadRequest ¶
BadRequest is an error the daemon answers with 400.
func BriefMissing ¶
BriefMissing is why the turn an intake starts under ctx goes without a brief; "" when it has one or ctx is no intake's.
func CheckInputs ¶
func CheckInputs(reg *dintent.Registry, d dintent.Def, in map[string]any, surface, source string, automated bool) (map[string]any, error)
CheckInputs validates a request's inputs against the intent's definition and normalizes them to their types; surface is where the request comes from, "" for a client that sends no inputs.
func LockFile ¶
LockFile takes an exclusive flock on path without waiting; busy is the error when another process holds it.
func LoopHeld ¶
LoopHeld tells a context whose caller holds the daemon's loop mutex, as an intake's start does: what runs under it must not take the mutex again.
func NotOffered ¶
NotOffered is the conflict of an action the row does not offer.
func StoreWarning ¶ added in v0.2.0
func StoreWarning(st api.StoreStatus) string
StoreWarning is st as one line: the message and the command to run.
Types ¶
type Actions ¶
type Actions interface {
Open(ctx context.Context, u unit.Unit, c Call) error // Focus the workspace, else the PR in the browser
Adopt(ctx context.Context, u unit.Unit, c Call) error
// Intent runs a round of the named intent; Call.Inputs holds the
// request's inputs and those its prepare filled.
Intent(ctx context.Context, name string, u unit.Unit, c Call) error
Run(ctx context.Context, u unit.Unit, c Call) error // sends the held round now; never counts against the cap
// Remove deletes the local workspace of a merged or closed pull request,
// or answers a Refusal when it would lose work.
Remove(ctx context.Context, u unit.Unit, c Call) error
}
Actions are the operations with side effects outside the store. The daemon runs each one but Open under its loop mutex.
type AheadReader ¶
type AheadReader interface {
ReadAhead(ctx context.Context, u unit.Unit, full bool) context.Context
}
AheadReader is Actions that reads, before an action takes the loop mutex, what the action asks GitHub, so that it asks nothing while holding it; full also reads the pull request in full.
type AppState ¶
type AppState struct {
// contains filtered or unexported fields
}
AppState holds the app's last report; nil until the app reports.
type BriefHealth ¶
type BriefHealth interface {
Status(ctx context.Context) (brief.Status, error)
// Breaker is the brief breaker; open is false while briefs run.
Breaker() (open bool, since time.Time, lastErr string, next time.Time)
}
BriefHealth is the brief queue as health reads it.
type BriefQueue ¶
type BriefQueue interface {
Run(ctx context.Context) (string, error)
// Touched wakes the queue for pull requests whose brief inputs changed.
Touched(refs []pr.Ref)
// Due is signaled when followed pull requests are due a background brief.
Due() <-chan struct{}
// Forget drops a pull request's brief, so the next run makes it again.
Forget(ctx context.Context, ref pr.Ref) error
}
BriefQueue is the brief queue the daemon runs as a job.
type BriefReads ¶
type BriefReads interface {
prrow.Briefs
Views(ctx context.Context, prs ...dinv.PR) (map[pr.Ref]*brief.View, error)
RefreshIfStale(ctx context.Context, pr dinv.PR) error
// Attempt is the brief attempt a first turn of ref waits on.
Attempt(ctx context.Context, ref pr.Ref) (int, error)
}
BriefReads are the briefs as the rows, the detail panel and the intakes read them.
type Call ¶
type Call struct {
Guidance string
// AgentHome is the caller's agent home; empty means the one the
// project's settings name.
AgentHome string
// Out receives what the action reports, sent back to the caller.
Out io.Writer
// WorkspaceID is the workspace the inventory links to the pull request,
// "" when none; remove acts on exactly that one.
WorkspaceID string
// Force lets remove past the workspace manager's terminal check.
Force bool
// Inputs are the intent's inputs, normalized to their types.
Inputs map[string]any
// Items are the unit's item ids and Entry the GTD entry the action was asked from; the turn's
// drafts are tied to them.
Items []string
Entry string
}
Call is what a delegated action gets besides the pull request.
type CardsJob ¶
type CardsJob interface {
// Changed must not block: the read model's publish waits on it.
Changed(c api.Change)
Run(ctx context.Context, rows cards.Rows)
}
CardsJob keeps the cards and derived items current with the rows.
type Collector ¶
Collector rebuilds GitHub's scope and catches what the searches no longer return on the slow job; skipped holds truncation and warnings, which surface in health without failing the job.
type Deps ¶
type Deps struct {
// Units parses the keys of the unit routes; the providers it knows are
// the daemon's.
Units *unit.Registry
// Ingest are the sources' ingestion jobs.
Ingest []IngestJob
// RowProviders build the read model's providers with the daemon's row
// deps, one per source.
RowProviders []func(readmodel.RowDeps) readmodel.Provider
// The inventory, one field per role; a nil role answers as a daemon
// with no store does.
Rows prrow.Store
PRs PullRequests
Events EventLog
Overrides Overrides
Meta Metas
Records Records
// GitAccess keeps how git network operations went per host; nil keeps
// them in Store.
GitAccess *GitAccessLog
Meter *meter.Registry // nil counts nothing
// Fallbacks is how many workspace manager calls went to its CLI because
// its runtime drifted; nil when it does not count them.
Fallbacks func() int64
Pauses Pauses // nil reads as not paused and refuses a pause
// Collector runs the slow job; nil registers no fast and slow jobs.
Collector Collector
// Track reads a pull request about to be tracked, wrapping a failed read
// in port.ErrNotFound or port.ErrGitHub when it can tell which; nil
// tracks without reading.
Track func(ctx context.Context, u unit.Unit) (port.TrackRead, error)
// Follows says whether a provider's source keeps its own follows: track
// and untrack of its units go to Track and Untrack, never to the pull
// request overrides. Nil follows none.
Follows func(unit.ProviderID) bool
Untrack func(ctx context.Context, u unit.Unit) error
Sweep Sweeper // nil registers no sweep job
Actions Actions // nil answers 503 to delegated actions
// Intents is the registry as the profile defines it now, read on every
// rows rebuild and action; nil serves the bundled intents.
Intents func() *intentload.Loaded
// Plan is the workflows' plan; nil answers 503 to the plan routes.
Plan Plan
// Pending are the pending automatic rounds the rows show; nil shows none.
Pending readmodel.Pending
Changes *change.Log // nil notes nothing
// Snapshot pins the read model's loads to one read transaction; nil
// loads without one.
Snapshot readmodel.Snapshotter
// Brief, BriefStatus and BriefViews are the brief queue's roles; nil
// when brief.enabled is false.
Brief BriefQueue
BriefStatus BriefHealth
BriefViews BriefReads
Usage *coreusage.Service // nil registers no usage job
Explorer Explorer // nil answers 503 to explore
// Retain drops the store's rows past their retention and says what it
// dropped; nil registers no retain job.
Retain func(ctx context.Context) (summary string, err error)
// Budget is the GitHub client's budget; nil reads as unknown.
Budget Budget
// Turns, Sessions and Views are the turn and view use cases and the
// sessions turns are typed into; nil answers 503 from the routes that
// need them.
Turns *turns.Service
Sessions turns.Sessions
Views *coreviews.Service
// Agents are the agents' states as the workspace snapshot last read
// them, never a call to the manager; nil reads as unknown, so a started
// turn's session is never told waiting.
Agents readmodel.Agents
// Activity reads what the loop spent on each provider's units for their
// rows; nil shows none.
Activity readmodel.Activities
// TurnByHand runs a turn the user asked for in the handle's session, ""
// outside Orca; nil answers 503 to AgentAPI's by-hand turns.
TurnByHand func(ctx context.Context, r api.ByHandRequest, handle string) (api.ByHandResult, error)
// Intakes keeps the turns users ask for: review, address and run are
// accepted at once and start once the first turn's brief is ready. nil
// runs them at once and answers when they end.
Intakes intake.Store
// IntakeBriefs tells an intake whether its brief is ready; nil starts
// every intake without one, as with briefs off.
IntakeBriefs intake.Briefs
// ByHandRef is the pull request a turn by hand is about; with Intakes
// it takes the turn through an intake, nil runs it at once.
ByHandRef func(ctx context.Context, r api.ByHandRequest, handle string) (unit.Unit, error)
// cannot run them; "" when it can or they are off.
BriefsUnavailable string
// Facts reads what a pull request's guide is matched against, for
// profile show <pr-url>; nil answers 503.
Facts func(ctx context.Context, u unit.Unit) (api.Facts, error)
// SessionWait is how long a turn by hand waits for its brief; 0 is
// brief.SessionWait.
SessionWait time.Duration
// LoopMu serializes every loop write: sweep, review, take over, address, run.
// Shared across restarts of the server in one process; nil makes one.
LoopMu *sync.Mutex
// App is the menu bar's status, shared across restarts of the server
// like LoopMu; nil makes one.
App *AppState
Cfg config.Config
Viewer func(ctx context.Context) (login string, teams []string, err error)
// Forge is the plugin of the pull requests the daemon's viewer,
// explorer, intakes and budget serve.
Forge unit.ProviderID
Now func() time.Time
Version string
Log func(format string, args ...any)
StateDir string
Socket string
LockPath string
InfoPath string
// Restart is the command that restarts the daemon, which a refused
// client of another API major is told to run.
Restart string
// Store is the open store's version and last backup, for the health.
Store *api.StoreStatus
// ConfigWarning is the health warning about config.json drifting from the
// running config, "" for none; nil never warns.
ConfigWarning func() string
// WorkspaceManager names the workspace managers in messages, such as
// "Claude Desktop or Orca".
WorkspaceManager string
// WorkspaceManagers name the enabled managers for the health answer, as
// displayed; ManagerNames are their registry names, and a hook naming
// another one is refused.
WorkspaceManagers []string
ManagerNames []string
// NotifierStart is the command that starts the menu bar; "" when this
// daemon expects none, and then its absence is no warning.
NotifierStart string
// Notices are what the workflows raise for the user, streamed to the
// event subscribers as they come; nil raises none.
Notices Notices
// FailedSteps names the failed steps of a GitHub Actions job; nil names
// none.
FailedSteps func(ctx context.Context, owner, repo string, jobID int64) ([]string, error)
// MCP serves agents' MCP sessions on 127.0.0.1:MCPPort; nil listens on
// no MCP port.
MCP http.Handler
MCPPort int
// Startup reconciles the store and the views; Run holds
// UserAPI until it returns. nil serves at once with no report.
Startup func(ctx context.Context) (api.ReconcileReport, error)
// Homes checks the agent homes; Run checks them at start, the slow job,
// doctor, a session home no check covered and a health read of a result
// older than HomesMaxAge check them again, and health reads the last
// result. nil reports none.
Homes func(ctx context.Context) ([]api.HomeFinding, error)
// DryRunTurn stores the review turn of a profile try; nil answers 503.
DryRunTurn func(ctx context.Context, r api.DryRunTurnRequest) (api.DryRunTurn, error)
// Doctor runs doctor's checks that read the loop's state; nil runs none
// but the reconcile's.
Doctor func(ctx context.Context, q api.DoctorQuery) (api.DoctorReport, error)
// Plugins are every compiled-in plugin; PluginEnabled nil: all enabled.
Plugins []api.Plugin
PluginEnabled func(unit.ProviderID) bool
// Runtimes are the enabled plugins' streams, jobs and health.
Runtimes []PluginRuntime
// Items is the items ledger; nil answers 503 to the items routes.
Items ItemsLedger
// Cards are the units' stored cards; nil serves none.
Cards card.Store
// CardsJob is told each published row change; nil runs none.
CardsJob CardsJob
// GTD is the entries service; nil answers 503 to the entries routes and runs no Sync. Messages are the
// Inbox messages, whose entries' verbs it registers on GTD.
GTD *coregtd.Service
Messages *messages.Service
// Drafts are the outbox's drafts the notifications read; nil: no draft notifies.
Drafts Drafts
// GTDMe resolves the user's identity over the enabled plugins and sets it on GTD, saying whether it grew;
// the Sync worker calls it before each batch until it succeeds. nil: GTD's identity stands.
GTDMe func(ctx context.Context) (grew bool, err error)
// GTDUnits are the units a full Sync covers: those with an open item or a live entry; nil: none.
GTDUnits func(ctx context.Context) ([]unit.Unit, error)
// Outbox keeps the drafts; nil answers 503 to the draft routes. SendDrafts runs its sender, which
// publishes the approved drafts.
Outbox *outbox.Service
SendDrafts bool
// Headless starts headless turns; nil answers 503 to the act route.
Headless Headless
// Placer says where a session on a unit of a provider other than GitHub runs; nil offers the
// session mode unchecked.
Placer Placer
}
type EventLog ¶
type EventLog interface {
Events(ctx context.Context, u unit.Unit) ([]dinv.Event, error)
RecentActivity(ctx context.Context, limit int) ([]dinv.ActivityEvent, error)
RecordEvent(ctx context.Context, ev dinv.Event) error
RecordSituations(ctx context.Context, sits []dinv.Situation) error
}
EventLog reads and records pull request events.
type Explained ¶
type Explained struct {
Unit unit.Unit
Items []workflow.Item
Workflows []api.UnitWorkflow
Errors []string
}
Explained is a unit's decisions: its items, and a line per workflow that gives none.
type Explainer ¶
Explainer is an optional capability of Plan: what every workflow of a unit's provider decides for that unit now, those that give no item included.
type GitAccessLog ¶
type GitAccessLog struct {
Store Metas
// contains filtered or unexported fields
}
GitAccessLog keeps, per host, the latest git network operation and the latest success, in the store's meta table.
func (*GitAccessLog) Record ¶
func (l *GitAccessLog) Record(ctx context.Context, r api.GitAccessRecord) error
type Headless ¶
Headless starts headless turns; Start returns once the turn is stored, and its call runs on.
type Implemented ¶ added in v0.2.0
type Implemented struct{ Prepares, Effects []string }
Implemented are the builtins the daemon implements: the prepares a role binds and the turn effects it applies.
type IngestJob ¶
type IngestJob struct {
ID unit.ProviderID
Job ingest.Job
}
IngestJob is a source's ingestion job; the daemon runs it as the job "ingest:<ID>".
type ItemsLedger ¶
ItemsLedger is the items ledger as the unit card reads it.
type Metas ¶
type Metas interface {
Meta(ctx context.Context, key string) (string, error)
MetaPrefixed(ctx context.Context, prefix string) (map[string]string, error)
SetMeta(ctx context.Context, key, value string) error
}
Metas keeps the daemon's small values by key.
type Notices ¶
type Notices interface {
// Follow calls fn with each notice raised until stop is called.
Follow(fn func(api.Notice)) (stop func())
}
Notices are the notifications the workflows raise for the user.
type Overrides ¶
type Overrides interface {
Override(ctx context.Context, u unit.Unit) (dinv.Override, error)
Overrides(ctx context.Context) (map[unit.Unit]dinv.Override, error)
// SetOverrideIf writes o only while the stored override is was.
SetOverrideIf(ctx context.Context, was, o dinv.Override) (written bool, err error)
ClearMute(ctx context.Context, u unit.Unit, kind, waitingOn string) (cleared bool, err error)
// SetNextGuidance keeps guidance for u's next automatic round.
SetNextGuidance(ctx context.Context, u unit.Unit, guidance string) error
}
Overrides reads and writes the user's overrides.
type Pauses ¶
type Pauses interface {
Pause(ctx context.Context) (round.Pause, error)
SetPause(ctx context.Context, p round.Pause) error
}
Pauses keeps the pause of every workflow that does not observe and of board moves.
type Plan ¶
type Plan interface {
// Evaluate is what the workflows of trigger t would decide now; it
// writes nothing and notes nothing.
Evaluate(ctx context.Context, t workflow.TriggerKind) (automation.Plan, error)
// Items are the stored plan's items f selects.
Items(ctx context.Context, f automation.Filter) ([]workflow.Item, error)
// Act carries the user's action on item id; the caller holds the loop
// lock.
Act(ctx context.Context, id string, a workflow.Action, guidance string) (workflow.Item, error)
// Drop discards u's pending items without marking them handled.
Drop(ctx context.Context, u unit.Unit, why string) error
// DueRun runs the pending items whose window ended; the caller holds the
// loop lock.
DueRun(ctx context.Context) error
}
Plan is the workflows' plan and the user's actions on it.
type PluginJob ¶
type PluginJob struct {
Name string
Every time.Duration
Timeout time.Duration // a run's limit; 0 is pluginTimeout
Run func(ctx context.Context) (summary, skipped string, err error)
}
PluginJob is a plugin's daemon job, named as the plugin names it.
type PluginRuntime ¶
type PluginRuntime struct {
ID unit.ProviderID
// Run is a long-running stream, run until the daemon stops and started
// again streamRestart after it returns.
Run func(ctx context.Context) error
Jobs []PluginJob
Health func(ctx context.Context) (api.SourceHealth, error)
// WebAssets are served under /plugins/<id>/.
WebAssets fs.FS
}
PluginRuntime is what an enabled plugin runs in the daemon; a nil field is absent.
type PullRequests ¶
type PullRequests interface {
PR(ctx context.Context, u unit.Unit) (dinv.PR, bool, error)
PRs(ctx context.Context, units []unit.Unit) (map[unit.Unit]dinv.PR, error)
ListPRs(ctx context.Context, open bool) ([]dinv.PR, error)
Tracked(ctx context.Context) ([]unit.Unit, error)
SetWorkspace(ctx context.Context, u unit.Unit, ws dinv.Workspace) error
}
PullRequests reads the stored pull requests and sets the workspace linked to one.
type Records ¶
type Records interface {
Turn(ctx context.Context, id string) (dinv.StoredTurn, bool, error)
BriefRecord(ctx context.Context, u unit.Unit) (dinv.BriefRecord, bool, error)
BriefRun(ctx context.Context, id int64) (dinv.BriefRun, bool, error)
Timings(ctx context.Context, since time.Time) (dinv.TimingsData, error)
// UnitlessEvents are the events of no pull request, oldest first.
UnitlessEvents(ctx context.Context) ([]dinv.Event, error)
}
Records reads what turns and briefs left behind.
type Refusal ¶
type Refusal struct {
Reason, Detail string
// Source names the tool whose message Detail is, "" for the loop's own.
Source string
Forceable bool
}
Refusal is an action that would do harm, with the reason and its detail. Forceable marks a refusal that asking again with force would get past.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
func (*Server) AuthHandler ¶
AuthHandler is Handler behind the token check, for the TCP port, which serves no AgentAPI and no AdminAPI.
func (*Server) BriefReady ¶
BriefReady is the brief queue's answer for a round the sweep is about to propose or send on the pull request.
func (*Server) OpenIntakes ¶
OpenIntakes lists the open intakes but the session ones nobody asks for; none when the daemon keeps no intakes.
func (*Server) RecheckHomes ¶
RecheckHomes checks the agent homes now; concurrent calls share one check.
type StoreWait ¶ added in v0.2.0
type StoreWait struct {
Version string
StateDir string
Socket string
LockPath string
InfoPath string
// HTTPPort is the cockpit's configured port; 0 reuses the earlier one.
HTTPPort int
// Status is the store's state, read on each request.
Status func() api.StoreStatus
// Ready is asked every Every; true ends the wait.
Ready func() bool
Every time.Duration
}
StoreWait is the daemon while it cannot open its store: it answers its health with the store's state, refuses every other request with that state's message and fix, and returns once Ready says the store may open. It holds the daemon's lock and socket meanwhile, so clients reach it, not a second daemon.
type SweepFunc ¶
SweepFunc is a Sweeper with no deadline that reads no snapshot and runs whole under the loop lock.
func (SweepFunc) Seen ¶
func (SweepFunc) Seen() port.Generation
type Sweeper ¶
type Sweeper interface {
// Sweep plans without loop and takes loop only to act on the plan.
Sweep(ctx context.Context, loop sync.Locker) (summary, skipped string, err error)
// Due is the earliest instant a decision of the last sweep changes with
// no input changing: conflict window end, start block day, cap rollover
// with a capped step, a review turn reaching the 30-day cutoff. Zero
// when none.
Due() time.Time
// Seen is the change log generation the last sweep's workspace snapshot
// read was current at; zero when it read none.
Seen() port.Generation
}
Sweeper is the sweep job's port.
type Unblocker ¶
type Unblocker interface {
// TrustAndRun trusts the folder the round's start block names, in the
// agent home the round ran with or, unknown, in every agent home the
// loop knows, lifts the block and sends the round now.
TrustAndRun(ctx context.Context, u unit.Unit, c Call) error
// Unblock marks the trigger of the round a start block holds handled,
// so the round waits for a new one; the caller records the block lifted.
Unblock(ctx context.Context, u unit.Unit, c Call) error
}
Unblocker is Actions that lifts the start block of a round.
Source Files
¶
- actions.go
- admin.go
- agent.go
- api.go
- attention_entries.go
- briefs.go
- builtins.go
- cards.go
- catalog.go
- checks.go
- daemon.go
- digest.go
- drafts.go
- entries.go
- explore.go
- facts.go
- gitaccess.go
- headless.go
- intake.go
- intents.go
- items.go
- jobs.go
- keys.go
- lock_unix.go
- messages.go
- meter.go
- offers.go
- outbox_view.go
- owner_unix.go
- perms.go
- plan.go
- plan_unit.go
- pluginassets.go
- plugins.go
- ports.go
- probe.go
- refs.go
- reply.go
- review.go
- rows.go
- situationlog.go
- sse.go
- storewait.go
- timings.go
- timings_derive.go
- unitactions.go
- wire.go