Documentation
¶
Overview ¶
Package core hosts the node lifecycle: registration, heartbeat loop, and graceful shutdown. Message routing and task state live alongside it in later phases.
Package core hosts the node lifecycle and the task state machine.
Index ¶
- Constants
- Variables
- func CanTransition(from, to string) bool
- func EphemeralNodeID(base string) string
- func NodeID(cfgName string) string
- func Terminal(s string) bool
- type Core
- func (c *Core) CancelTree(ctx context.Context, taskID string) error
- func (c *Core) DialPeer(ctx context.Context, addr string) error
- func (c *Core) Idle(ctx context.Context) bool
- func (c *Core) List(status, name string) ([]ledger.Node, error)
- func (c *Core) Listen(ctx context.Context, addr string) error
- func (c *Core) MaintainPeer(ctx context.Context, addr string) error
- func (c *Core) Recover(ctx context.Context) (int, error)
- func (c *Core) Register(ctx context.Context) error
- func (c *Core) RunHeartbeat(ctx context.Context)
- func (c *Core) RunMonitor(ctx context.Context)
- func (c *Core) SetHostStatePaths(paths []string)
- func (c *Core) SetLimits(maxConns, maxConnsPerIP int)
- func (c *Core) SetMemoryStores(inj *memory.Injector, daily *memory.Daily, sk *skills.Store)
- func (c *Core) SetSharedSecret(secret string)
- func (c *Core) SetWorkDir(dir string)
- func (c *Core) Shutdown(ctx context.Context)
- func (c *Core) Submit(ctx context.Context, in TaskInput) (Task, bus.TaskResultPayload, error)
- func (c *Core) SubmitLocal(ctx context.Context, in TaskInput) (Task, bus.TaskResultPayload, error)
- func (c *Core) TaskStore() *TaskStore
- type DelegationMetric
- type Event
- type Node
- type Peer
- type Task
- type TaskDetail
- type TaskInput
- type TaskStore
- func (s *TaskStore) Accept(ctx context.Context, taskID, owner string) error
- func (s *TaskStore) AdoptAttempt(ctx context.Context, taskID, attemptID string) error
- func (s *TaskStore) Approve(ctx context.Context, taskID string) error
- func (s *TaskStore) Cancel(ctx context.Context, taskID string) error
- func (s *TaskStore) CancelCascade(ctx context.Context, taskID string) ([]string, error)
- func (s *TaskStore) Children(ctx context.Context, parentID string) ([]Task, error)
- func (s *TaskStore) Complete(ctx context.Context, taskID, owner string, result any) error
- func (s *TaskStore) CompleteFromRemote(ctx context.Context, taskID, owner string, result any) error
- func (s *TaskStore) CountActive(ctx context.Context, owner string) (int, error)
- func (s *TaskStore) Create(ctx context.Context, parentID, project, title, owner string, chain []string) (Task, error)
- func (s *TaskStore) CreateFromRemote(ctx context.Context, taskID, title, owner string, attemptID string, ...) (Task, error)
- func (s *TaskStore) CreateWithID(ctx context.Context, taskID, parentID, project, title, owner string, ...) (Task, error)
- func (s *TaskStore) Decline(ctx context.Context, taskID, parent, reason, by string) error
- func (s *TaskStore) DeclinedBy(ctx context.Context, taskID string) ([]string, error)
- func (s *TaskStore) Dispatch(ctx context.Context, taskID, owner, target string) error
- func (s *TaskStore) DispatchTarget(ctx context.Context, taskID string) (string, error)
- func (s *TaskStore) Events(ctx context.Context, taskID string) ([]Event, error)
- func (s *TaskStore) ExpireTasks(ctx context.Context) ([]string, error)
- func (s *TaskStore) Fail(ctx context.Context, taskID, owner, reason string) error
- func (s *TaskStore) FailFromRemote(ctx context.Context, taskID, owner, reason string) error
- func (s *TaskStore) ForceFail(ctx context.Context, taskID, reason string) error
- func (s *TaskStore) Get(ctx context.Context, taskID string) (Task, error)
- func (s *TaskStore) LastDelegateTime(ctx context.Context, taskID string) (int64, error)
- func (s *TaskStore) ListByState(ctx context.Context, state string) ([]Task, error)
- func (s *TaskStore) ListDelegationMetrics(ctx context.Context) ([]DelegationMetric, error)
- func (s *TaskStore) Pause(ctx context.Context, taskID, owner, reason string) error
- func (s *TaskStore) Queue(ctx context.Context, taskID, owner string) error
- func (s *TaskStore) RecordDelegationMetric(ctx context.Context, taskID, delegator, executor string, abilities []string, ...) error
- func (s *TaskStore) Recover(ctx context.Context) (int, error)
- func (s *TaskStore) Reject(ctx context.Context, taskID, reason string) error
- func (s *TaskStore) Requeue(ctx context.Context, taskID, owner string) error
- func (s *TaskStore) Resume(ctx context.Context, taskID, owner string) error
- func (s *TaskStore) Review(ctx context.Context, taskID, owner, reason string) error
- func (s *TaskStore) RotateAttempt(ctx context.Context, taskID, owner string) (string, error)
- func (s *TaskStore) SetAuthorized(ctx context.Context, taskID string, authorized bool) error
- func (s *TaskStore) SetDetail(ctx context.Context, taskID string, d TaskDetail) error
- func (s *TaskStore) SetLease(ctx context.Context, taskID string, durationMS int64) error
- func (s *TaskStore) SetOnReview(fn func(Task))
- func (s *TaskStore) SetWaitingContext(ctx context.Context, taskID, owner string) error
- func (s *TaskStore) VerifyTaskEventChain(ctx context.Context, taskID string) error
Constants ¶
const ( StateSubmitted = "submitted" StateQueued = "queued" StateDispatched = "dispatched" StateWaitingCtx = "waiting_context" StateRunning = "running" StateReview = "review" StateDone = "done" StateFailed = "failed" StateCancelled = "cancelled" StateExpired = "expired" )
Task states. These strings are part of the wire protocol across nodes, so treat them as stable identifiers.
const ( EvSubmit = "submit" EvQueue = "queue" EvDelegate = "delegate" EvAccept = "accept" EvDecline = "decline" EvProgress = "progress" EvResult = "result" EvReview = "review" EvRetry = "retry" EvTransfer = "transfer" EvCancel = "cancel" EvExpire = "expire" )
Task event types recorded in task_events.
Variables ¶
var ( // ErrIllegal reports a transition not present in the state table. ErrIllegal = errors.New("illegal state transition") // ErrConflict reports a state/owner/version mismatch (stale write). ErrConflict = errors.New("state conflict") // ErrCancelled reports that execution finished after the task was // cancelled; callers should not report a result for a cancelled task. ErrCancelled = errors.New("task cancelled") )
State-machine errors. Callers should wrap them with %w to preserve errors.Is checks.
Functions ¶
func CanTransition ¶
CanTransition reports whether from -> to is legal per the Phase 0 state table (design doc §5.3.1).
func EphemeralNodeID ¶
EphemeralNodeID derives a short-lived identity from base for processes that dial peers but are not the long-running daemon (e.g. `panda ask`). It appends a random suffix so a concurrent daemon and ask session never share a node id in the grid — a collision would cause ensurePeer to drop the second connection and misroute replies.
Types ¶
type Core ¶
type Core struct {
// contains filtered or unexported fields
}
Core wires the node lifecycle, task store, and WebSocket transport into a running daemon. It is the root type for the Phase 0 loop.
func NewCore ¶
func NewCore(db *sql.DB, nodeID string, card ledger.Card, tier int, logger *slog.Logger, model config.ModelConfig) *Core
NewCore constructs a Core. The card may be zero for a minimal node. The model config is forwarded to the commander for agent adapter subprocesses.
func (*Core) CancelTree ¶
CancelTree is the local-entry cancel: cascade locally, then notify downstream executors. The CLI and any in-process caller share the exact post-cancel behaviour of the wire handler.
func (*Core) DialPeer ¶
DialPeer connects outbound to addr, sends hello, and starts reading in the background. It returns once the connection is established (or fails); the read loop keeps the connection alive. Short-lived schedulers (the ask CLI) use this so they can dial every peer and then proceed to routing. A daemon that must hold the connection and reconnect on drop should use MaintainPeer.
func (*Core) Idle ¶
Idle reports whether the node has no active (running, dispatched, or waiting-for-context) tasks. The Dreaming scheduler uses it to run consolidation only when the node is free, so dreaming never competes with real work.
func (*Core) Listen ¶
Listen starts the WebSocket server and accepts connections. Blocks until ctx is done.
func (*Core) MaintainPeer ¶
MaintainPeer connects outbound to addr and blocks serving the connection until the peer EDGE is down, not just our conn: after a mutual-dial dedup (see ensurePeer) our outbound conn may be the loser while the peer's own inbound conn keeps the edge alive — redialing then would only recreate the one-second flap the dedup exists to stop. A nil return means the edge dropped (or ctx is done) and the caller may redial; a non-nil return means the dial (or hello) failed.
func (*Core) RunHeartbeat ¶
RunHeartbeat starts the heartbeat loop: each tick updates the local ledger (last_seen + live capacity) and broadcasts a wire heartbeat to every connected peer, so a peer's TMB freshness weight and DCPS capacity signals are fed by real traffic instead of going stale after the initial hello.
func (*Core) RunMonitor ¶
RunMonitor scans for expired leases and fails them. It returns when ctx is done.
func (*Core) SetHostStatePaths ¶
SetHostStatePaths records the node's own bookkeeping paths — its SQLite/memory trees and the agent CLI's own config dir — so scope-drift detection never flags the host's side-effect writes as agent drift. Paths may be relative to the working directory; they are normalized to absolute on entry.
func (*Core) SetLimits ¶
SetLimits configures the global and per-IP inbound connection limits. A limit <= 0 disables that limit.
func (*Core) SetMemoryStores ¶
SetMemoryStores attaches the memory layer (design §17/§8): the injector for project memory, the daily log writer feeding the Dreaming engine, and the skill store for progressive loading. Any may be nil to disable its layer.
func (*Core) SetSharedSecret ¶
SetSharedSecret sets the shared secret used to authenticate inbound hello messages (design §16 / P0-1). An empty secret is fail-closed: no peer can authenticate, so the WebSocket listener accepts no hello until a secret is configured.
func (*Core) SetWorkDir ¶
SetWorkDir pins the directory agents execute in and scope drift is measured against. Empty resets to the default (the daemon's working directory).
func (*Core) Submit ¶
Submit creates a task from the entry model and routes it to the best node: locally if this node matches, otherwise forwarded to a capable peer (P2P per-edge delegation). It is the root-scheduler entry point used by the ask CLI. A forwarded task blocks until the peer's result arrives (or ctx is done); a local task returns immediately with the execution result.
func (*Core) SubmitLocal ¶
SubmitLocal creates and executes a task on this node — no delegation. It is the Phase 1 local closed loop: the entry model's task output lands here, is persisted with full detail, then runs through the same execute pipeline used for inbound delegated tasks. It returns the final task row and the execution result payload.
On an execution error the task is failed (not left queued) so a local task always ends in a terminal state. ErrCancelled is not an error to the caller: the task was cancelled mid-run and the result payload reflects that outcome.
type DelegationMetric ¶
type DelegationMetric struct {
ID int64
TaskID string
Delegator string
Executor string
AbilitiesJSON string
Success bool
LatencyMs int64
Tokens sql.NullInt64
CreatedAt int64
}
DelegationMetric is one row of the delegation_metrics table.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node owns this process's ledger identity.
func NewNode ¶
NewNode builds a Node with an optional card. A nil card is allowed for a minimal core that only manages its own heartbeat.
func (*Node) List ¶
List returns the local capability directory, filtered by status/name ("" matches all).
func (*Node) RunHeartbeat ¶
RunHeartbeat starts a ticker that updates last_seen + capacity until ctx is done. It is safe to call concurrently with other core loops.
type Peer ¶
type Peer struct {
// contains filtered or unexported fields
}
Peer is an established connection to another node.
type Task ¶
type Task struct {
TaskID string
ParentID string
Project string
Title string
State string
OwnerNode string
AttemptID string
StateVersion int
Chain []string
Intent string
SpecJSON string
ResultJSON string
ContextType string
ContextHash string
Complexity float64
Risk string
ResourceJSON string
// Authorized records whether the user consented to executing tier-2
// (irreversible) commands. It is server-side state (design §16 / P0-1), not
// wire-carried, so a delegated task cannot forge authorization.
Authorized bool
// Requires is the capability set the task was routed with. Persisted so a
// decline can be re-routed to the next-best node without the original wire
// payload (P1-5).
Requires []string
LeaseExpires int64
CreatedAt int64
UpdatedAt int64
}
Task is the persisted task row (Phase 0 subset of the schema).
type TaskDetail ¶
type TaskDetail struct {
ContextType string
ContextHash string
Intent string
SpecJSON string
Complexity float64
Risk string
ResourceJSON string
// Requires carries the routing capability set so it survives past the
// original delegate payload (decline re-routing, P1-5).
Requires []string
}
TaskDetail is the entry-model-derived task metadata (design doc §6.1 tasks schema). It is written once, shortly after creation, by SetDetail; the fields stay zero/empty for tasks that predate the entry model or arrived via a Phase 0 payload without detail. model_tier is intentionally absent — it is a Phase 3 feature (model-tier selection) and will be added when that lands.
type TaskInput ¶
type TaskInput struct {
Title string
Project string
ContextType string
ContextHash string // pre-packed snapshot hash; empty means "pack if applicable"
ContextLevel string // pointer|summary|full; empty is derived by packContext
RepoPath string // file-type repo root for auto-packing (MVP: CLI not yet wired)
Intent string
SpecJSON string
Requires []string
PreferredNode string // user-named node (task spec scope); routing prefers it when it can match
Complexity float64
Risk string
ResourceJSON string
Authorized bool // user consented to executing tier-2 (irreversible) commands
}
TaskInput is the local-entry form of a task: the structured task the entry model emitted, translated into the fields the core persists and executes. It mirrors the wire TaskDelegatePayload but originates locally rather than over the bus. The caller (cmd/panda) owns the translation from entry.TaskSpec.
type TaskStore ¶
type TaskStore struct {
// contains filtered or unexported fields
}
TaskStore manages the tasks and task_events tables. It enforces the state machine, attempt lifecycle, idempotency, and cascade cancellation.
All mutating methods take an owner: the node that currently holds (or is claiming) the task lease. Transitions are rejected if owner does not match the stored owner_node, except for the terminal cancel that the parent may force downward.
func NewTaskStore ¶
NewTaskStore wraps a DB. now may be nil (defaults to Unix time).
func (*TaskStore) Accept ¶
Accept transitions dispatched -> running and transfers the lease to the executor (owner). The UPDATE carries a state guard (P1-3): without it a concurrent cancel/timeout between the pre-check and the write could be overwritten, resurrecting a closed task. The wire handler additionally authenticates the sender against the recorded dispatch target.
func (*TaskStore) AdoptAttempt ¶
AdoptAttempt stamps taskID with an attempt_id minted upstream. A delegated task carries its attempt along the chain so every node's copy reports the same attempt; downstream nodes adopt it instead of minting their own.
func (*TaskStore) Approve ¶
Approve accepts a reviewed task, moving it review -> done. Approval is a human override (design §14.2 Layer 4), so — like Cancel — it requires only that the task be in review, not that the caller hold the lease.
func (*TaskStore) Cancel ¶
Cancel marks a task cancelled if it is still active. Cancellation is the one transition the parent may force regardless of lease ownership, to support cascade from a cancelled parent — but it still must be a legal move per the state machine, so a stale caller cannot force a task into a state the table does not allow. Callers authorizing the *source* of the cancel do so upstream (see Core.handleCancel).
func (*TaskStore) CancelCascade ¶
CancelCascade cancels taskID and every descendant. Descendants are found by parent_id links; the walk recurses so multi-level trees behave. A visited set guards against a parent_id cycle, which would otherwise recurse forever. The returned slice lists the tasks actually transitioned to cancelled — already- terminal tasks are skipped, not included.
func (*TaskStore) CompleteFromRemote ¶
CompleteFromRemote records a remote executor's final result on the delegator's copy. The delegator may be in submitted/queued/dispatched/ running; any non-terminal state is accepted, and the owner is moved to the delegator (who holds the parent-side lease).
func (*TaskStore) CountActive ¶
CountActive returns the number of this node's tasks currently occupying an execution slot (running or waiting_context). The capacity-driven accept/decline check (DCPS τ_adp mapping, design §2.4) compares it against the card's MaxConcurrent before accepting delegated work.
func (*TaskStore) Create ¶
func (s *TaskStore) Create(ctx context.Context, parentID, project, title, owner string, chain []string) (Task, error)
Create inserts a new task in submitted state with a fresh UUIDv7 id.
func (*TaskStore) CreateFromRemote ¶
func (s *TaskStore) CreateFromRemote(ctx context.Context, taskID, title, owner string, attemptID string, chain []string) (Task, error)
CreateFromRemote inserts a task owned by this delegator, adopting the executor's attempt_id so a follow-up result (with the same attempt) is not mistaken for a stale write. Used when a delegator hears a result for a task it never persisted locally.
func (*TaskStore) CreateWithID ¶
func (s *TaskStore) CreateWithID(ctx context.Context, taskID, parentID, project, title, owner string, chain []string) (Task, error)
CreateWithID inserts a task with an explicit id. The id is the cross-node idempotency key, so delegated tasks keep the delegator's id. Returns ErrConflict if the id already exists.
func (*TaskStore) Decline ¶
Decline rejects a dispatched task, moving it back to queued and releasing the lease so the parent can route elsewhere. Only a dispatched task may be declined; this prevents overriding a task that already started running. by is the declining executor (the wire sender): while the task is dispatched the stored owner is still the delegator, so the decliner must be passed explicitly — the re-router (P1-5) excludes it from future candidacy.
func (*TaskStore) DeclinedBy ¶
DeclinedBy returns every node that has declined this task, read from the task_events audit trail (Decline records the declining executor as "by"). The re-router (P1-5) excludes them so a task cannot bounce back to a node that already refused it — that is what bounds the decline/re-route loop.
func (*TaskStore) DispatchTarget ¶
DispatchTarget returns the node this task was most recently dispatched to, read from the task_events audit trail (Dispatch records the target on its EvDelegate event). "" means the task was never dispatched. Wire handlers use it to authenticate result/decline/accept senders before acceptance moves the lease (P1-1/2/3).
func (*TaskStore) ExpireTasks ¶
ExpireTasks fails any active task whose lease has expired. It returns the task IDs actually failed, so the caller can clean up per-task state. Called periodically by the monitor.
func (*TaskStore) Fail ¶
Fail transitions a task to failed. Allowed from running/dispatched/ waiting_context/review.
func (*TaskStore) FailFromRemote ¶
FailFromRemote records a remote executor's failure on the delegator's copy. Mirrors CompleteFromRemote: any non-terminal state is accepted.
func (*TaskStore) ForceFail ¶
ForceFail fails an active task regardless of owner. Used by the timeout monitor and restart recovery when the owner may be gone.
func (*TaskStore) LastDelegateTime ¶
LastDelegateTime returns the timestamp (Unix seconds) of the most recent EvDelegate event for a task. It is used to compute delegation latency.
func (*TaskStore) ListByState ¶
ListByState returns tasks filtered by state ("" = all), newest first.
func (*TaskStore) ListDelegationMetrics ¶
func (s *TaskStore) ListDelegationMetrics(ctx context.Context) ([]DelegationMetric, error)
ListDelegationMetrics returns all recorded delegation metrics, newest first.
func (*TaskStore) Pause ¶
Pause transitions a running task to review, pausing it for human analysis after a deterministic intercept such as scope drift (design §14.2 "拦截 → 暂停 → 分析"). It is the running-state counterpart of Review (which pauses a failed task after its retry budget is spent) and never enters the retry loop, because a deterministic intercept will not improve on retry.
func (*TaskStore) RecordDelegationMetric ¶
func (s *TaskStore) RecordDelegationMetric( ctx context.Context, taskID, delegator, executor string, abilities []string, success bool, latencyMs int64, tokens int, ) error
RecordDelegationMetric writes a delegation outcome for later scheduling analysis. It is intentionally best-effort on the hot path: failures are returned so the caller can log them without aborting the result flow.
func (*TaskStore) Recover ¶
Recover normalizes tasks left in an active state by a previous process instance. Running/waiting_context/review become failed (execution was interrupted); dispatched returns to queued for re-dispatch. Returns the number of tasks touched.
func (*TaskStore) Reject ¶
Reject fails a reviewed task, moving it review -> failed. Like Approve, it is a human override and does not require the lease.
func (*TaskStore) Requeue ¶
Requeue transitions a failed task back to queued for a retry. It is the retry loop's entry: after a failed attempt the task returns to the queue to be re-dispatched. Only the owner may requeue.
func (*TaskStore) Resume ¶
Resume moves waiting_context -> running once the context snapshot has been fetched and verified. Only the lease holder (executor) may resume.
func (*TaskStore) Review ¶
Review transitions a failed task to review, pausing a task that has spent its retry budget for human analysis (design §14.2 "pause → analyze"). A reviewer may later send it back to queued, mark it done, or fail it.
func (*TaskStore) RotateAttempt ¶
RotateAttempt mints a new attempt_id for a retry/transfer. The caller must hold the lease (owner); the update is owner-guarded like every other mutating method, so a stale node cannot rotate another owner's attempt.
func (*TaskStore) SetAuthorized ¶
SetAuthorized persists whether the task's tier-2 (irreversible) commands were consented to by the user. It is server-side state (design §16 / P0-1): only the local entry path sets it, and a delegated task cannot forge authorization on the wire because the wire payload no longer carries it.
func (*TaskStore) SetDetail ¶
SetDetail persists the entry-model-derived task metadata (design doc §6.1 tasks schema): context type, intent, spec, complexity, risk, and resource profile. Called once after creation; the fields default to zero/empty until then. A zero TaskDetail clears the fields.
func (*TaskStore) SetLease ¶
SetLease stamps lease_expires_at = now + durationMS for a task. The timeout monitor fails tasks whose lease expires while still active. A non-positive duration is a no-op. The duration is rounded up to a whole second so a sub-second lease does not collapse to zero and expire instantly.
func (*TaskStore) SetOnReview ¶
SetOnReview installs the callback fired when a task transitions into review. The callback is invoked on its own goroutine so a slow consumer (e.g. a push send) never stalls the state machine.
func (*TaskStore) SetWaitingContext ¶
SetWaitingContext moves dispatched -> waiting_context.