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 Deletable(s string) bool
- func EphemeralNodeID(base string) string
- func FilterSensitiveData(s string) string
- func HasSensitiveData(s string) bool
- func IsTaskState(s string) bool
- func NodeID(cfgName string) string
- func RuntimeNodeID(name, kind, identity string) string
- func TaskStates() []string
- func Terminal(s string) bool
- type AmbiguousTaskIDError
- type ApprovalDisposition
- type Core
- func (c *Core) AdvancePlan(ctx context.Context, planID string) error
- func (c *Core) Artifacts() *artifact.Store
- func (c *Core) AttachSupervisor(model config.ModelConfig)
- func (c *Core) CancelTree(ctx context.Context, taskID string) ([]string, error)
- func (c *Core) Card() ledger.Card
- func (c *Core) DialPeer(ctx context.Context, addr string) error
- func (c *Core) DispatchChild(ctx context.Context, child Task, in TaskInput) error
- func (c *Core) Enqueue(ctx context.Context, in TaskInput, q QueueSpec) (Task, error)
- func (c *Core) EvTrace(ctx context.Context, taskID, typ string, data map[string]any)
- func (c *Core) EvaluateLinkState(ctx context.Context, targetNode string) LinkState
- func (c *Core) FetchArtifact(ctx context.Context, source, taskID, hash string) (artifact.Manifest, error)
- func (c *Core) FetchArtifactRef(ctx context.Context, source, taskID string, ref bus.ArtifactRef) (artifact.Manifest, error)
- func (c *Core) Idle(ctx context.Context) bool
- func (c *Core) ImportFatBundleArtifacts(ctx context.Context, artifacts []bus.FatBundleArtifact) ([]artifact.Manifest, error)
- func (c *Core) List(status, name string) ([]ledger.Node, error)
- func (c *Core) Listen(ctx context.Context, addr string) error
- func (c *Core) ListenUDP(ctx context.Context, addr string, stunServers []string) error
- func (c *Core) MaintainPeer(ctx context.Context, addr string) error
- func (c *Core) Negotiate(ctx context.Context, target string, p bus.AgentNegotiatePayload) (bus.AgentGrantPayload, error)
- func (c *Core) PunchPeer(ctx context.Context, peerID string) error
- func (c *Core) QueueScheduler() *queue.Scheduler
- func (c *Core) Recover(ctx context.Context) (int, error)
- func (c *Core) Register(ctx context.Context) error
- func (c *Core) ReloadCard(ctx context.Context, path string) error
- func (c *Core) ResumeApproved(ctx context.Context, taskID string) (Task, bus.TaskResultPayload, error)
- func (c *Core) RunHeartbeat(ctx context.Context)
- func (c *Core) RunMonitor(ctx context.Context)
- func (c *Core) RunReconcile(ctx context.Context)
- func (c *Core) RunTaskMonitor(ctx context.Context)
- func (c *Core) SendNegotiation(ctx context.Context, target string, p bus.AgentNegotiatePayload) error
- func (c *Core) SetAgentMCPPassthrough(command string)
- func (c *Core) SetArtifactStore(s *artifact.Store)
- func (c *Core) SetContacts(contacts []ledger.Contact)
- 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) SetProjectStores(store *projects.Store, projectsRoot string)
- func (c *Core) SetRouterPolicy(injection config.InjectionConfig, routing config.RoutingConfig)
- func (c *Core) SetSelfConfigPath(path string)
- func (c *Core) SetSharedSecret(secret string)
- func (c *Core) SetSuperviseRounds(n int)
- func (c *Core) SetSupervisor(client *entry.Client)
- func (c *Core) SetTimeouts(t config.TimeoutsConfig)
- func (c *Core) SetWorkDir(dir string)
- func (c *Core) Shutdown(ctx context.Context)
- func (c *Core) SpawnChildTask(ctx context.Context, parentID string, in TaskInput) (Task, error)
- func (c *Core) StartPlan(ctx context.Context, p plan.Plan, q QueueSpec) (string, error)
- func (c *Core) StartQueueScheduler(ctx context.Context) *queue.Scheduler
- 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
- func (c *Core) UDPPort() int
- func (c *Core) UDPRoute(peer string) *net.UDPAddr
- type DelegationMetric
- type Event
- type LinkState
- type Node
- type Peer
- type PlanSummary
- type PromptLanguagePolicy
- type QueueSpec
- type Task
- type TaskDetail
- type TaskInput
- type TaskStore
- func (s *TaskStore) Accept(ctx context.Context, taskID, owner string) error
- func (s *TaskStore) AddOnEvent(fn func(taskID, typ string, data any)) func()
- func (s *TaskStore) AdoptAttempt(ctx context.Context, taskID, attemptID string) error
- func (s *TaskStore) ApprovalDisposition(ctx context.Context, taskID string) (ApprovalDisposition, error)
- func (s *TaskStore) Approve(ctx context.Context, taskID string) error
- func (s *TaskStore) ArtifactIndexedFor(ctx context.Context, hash, taskID string) (bool, 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) ClaimApproved(ctx context.Context, taskID, expectedOwner, newOwner, target string) error
- func (s *TaskStore) ClaimLocal(ctx context.Context, taskID, node string) error
- func (s *TaskStore) ClearQueue(ctx context.Context) (cancelled, deleted int, err 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) CountScheduledActive(ctx context.Context, self 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) Delete(ctx context.Context, taskID string) (int, 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) Idle(ctx context.Context) bool
- 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) ListPlans(ctx context.Context) ([]PlanSummary, error)
- func (s *TaskStore) ListReady(ctx context.Context) ([]Task, error)
- func (s *TaskStore) MarkExpired(ctx context.Context, taskID, reason string) error
- func (s *TaskStore) Pause(ctx context.Context, taskID, owner, reason string) error
- func (s *TaskStore) PauseWithDisposition(ctx context.Context, taskID, owner, reason string, ...) error
- func (s *TaskStore) PauseWithResult(ctx context.Context, taskID, owner string, result any) error
- func (s *TaskStore) PendingPlans(ctx context.Context) ([]string, error)
- func (s *TaskStore) PlanStages(ctx context.Context, planID string) ([]Task, error)
- func (s *TaskStore) Queue(ctx context.Context, taskID, owner string) error
- func (s *TaskStore) QueuedDelegatedRemotely(ctx context.Context, self string) ([]Task, error)
- func (s *TaskStore) RecordArtifact(ctx context.Context, hash string, size int64, taskID, manifestJSON string) error
- func (s *TaskStore) RecordDelegationMetric(ctx context.Context, taskID, delegator, executor string, abilities []string, ...) error
- func (s *TaskStore) RecordEvent(ctx context.Context, taskID, typ string, data any) error
- func (s *TaskStore) Recover(ctx context.Context) (int, error)
- func (s *TaskStore) Reject(ctx context.Context, taskID, reason string) error
- func (s *TaskStore) RenameProject(ctx context.Context, oldName, newName string) (int64, error)
- func (s *TaskStore) Requeue(ctx context.Context, taskID, owner string) error
- func (s *TaskStore) RequeueForRetry(ctx context.Context, taskID, owner string) (string, error)
- func (s *TaskStore) ResolveTaskID(ctx context.Context, ref string) (string, error)
- func (s *TaskStore) Resume(ctx context.Context, taskID, owner string) error
- func (s *TaskStore) RetargetDelegation(ctx context.Context, taskID, target string) error
- func (s *TaskStore) RetryCount(ctx context.Context, taskID string) (int, error)
- func (s *TaskStore) Review(ctx context.Context, taskID, owner, reason string) error
- func (s *TaskStore) ReviewFromRemote(ctx context.Context, taskID, owner string, result any, ...) error
- func (s *TaskStore) ReviewWithDisposition(ctx context.Context, taskID, owner, reason string, ...) error
- func (s *TaskStore) RotateAttempt(ctx context.Context, taskID, owner string) (string, error)
- func (s *TaskStore) SetAgentSession(ctx context.Context, taskID, sessionID, node string) error
- func (s *TaskStore) SetAgentSessionID(ctx context.Context, taskID, sessionID string) error
- func (s *TaskStore) SetAuthorized(ctx context.Context, taskID string, authorized bool) error
- func (s *TaskStore) SetAuthorizedGrant(ctx context.Context, taskID, sig, pub string, ts int64) error
- func (s *TaskStore) SetDelegationBudget(ctx context.Context, taskID string, budget int) 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) SetOnEvent(fn func(taskID, typ string, data any))
- func (s *TaskStore) SetOnReview(fn func(Task))
- func (s *TaskStore) SetOutputArtifact(ctx context.Context, taskID, hash string) error
- func (s *TaskStore) SetPriority(ctx context.Context, taskID string, priority int) error
- func (s *TaskStore) SetQueueMeta(ctx context.Context, taskID string, priority int, sessionID, workDir string, ...) error
- func (s *TaskStore) SetSeq(ctx context.Context, taskID string, seq int64) error
- func (s *TaskStore) SetSessionID(ctx context.Context, taskID, sessionID string) error
- func (s *TaskStore) SetStage(ctx context.Context, taskID, planID, stageID string, needs []string) error
- func (s *TaskStore) SetStageInputs(ctx context.Context, taskID string, inputs []bus.ArtifactRef) error
- func (s *TaskStore) SetTokenBudget(ctx context.Context, taskID string, budget int64) error
- func (s *TaskStore) SetWaitingContext(ctx context.Context, taskID, owner string) error
- func (s *TaskStore) SetWorkDir(ctx context.Context, taskID, workDir string) error
- func (s *TaskStore) SpendTokens(ctx context.Context, taskID string, n int64) (int64, error)
- func (s *TaskStore) TaskActivityByDay(ctx context.Context) (map[string]int, 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" // EvModelInjection records that panda injected its model endpoint into // the agent subprocess (injection visibility, A1): the Web task detail // replays it like any other lifecycle event. EvModelInjection = "model_injection" // EvAgentFallback records that the scored primary agent was unavailable // and execution fell back to a runner-up (A2 fallback chain). EvAgentFallback = "agent_fallback" // EvMemoryPromotion records that the Dreaming engine promoted an entry // into MEMORY.md (A4 visibility): the console shows what was memorized // — and whether it came through the repeated-emphasis whitelist channel — // so the user can correct or delete it via the memory API. EvMemoryPromotion = "memory_promotion" // EvSupervise records one round of the execute → judge → re-delegate loop: // whether the reviewing model judged an agent's result complete ("done") or // in need of more work ("continue"), plus the follow-up instruction on a // "continue". The Web task detail replays it so the user can see the // superior's reasoning behind a re-delegation or a review parking. EvSupervise = "supervise" // EvRecover records that a daemon restart normalized a task left in an // active state by the previous process instance: running/waiting_context // become failed (their execution is gone), dispatched/submitted return to // queued. Written per task so the audit chain explains a state change that // no user or peer requested. review is never recovered — see // TaskStore.Recover. EvRecover = "recover" // EvContextDegraded records that a task's context (e.g. project memory pack, // work tree artifact) failed to attach or land, running in a degraded state // instead of failing silently. EvContextDegraded = "context_degraded" )
Task event types recorded in task_events.
const ( PriorityHigh = 0 PriorityNormal = 1 PriorityLow = 2 )
Task priority levels for the panel queue (smaller runs first). The DB column defaults to PriorityNormal so pre-redesign rows keep FIFO behavior.
const ( EvReasoning = "reasoning" // model thought/reasoning chain → thought EvClassifyResult = "classify_result" // entry.Classify success → kind/note/stages EvRouteDecision = "route_decision" // scheduler.Route → action/target/reason/score_breakdown/candidates EvDelegationHop = "delegation_hop" // handleTaskAccept/Result → from/to/via/chain/attempt_id EvExecAgentStart = "exec_agent_start" // router.Execute before agent run → agent/adapter/injected EvJudgeStart = "judge_start" // supervision loop right before the judge call → round/budget; the CLI's reviewing stage starts here EvSupervisionRound = "supervision_round" // supervise loop each round → round/budget/verdict/judge_summary EvTier2Triggered = "tier2_triggered" // defense.Authorize tier≥2 result → operations/parked_in_review // EvProjectSync records that a project task's tree came back from the // executor and was extracted into this node's copy of the project → what // changed, and where it landed. EvProjectSync = "project_sync" EvPlanStageChanged = "plan_stage_changed" // plan stage unlock/start/complete → plan_id/stage_id/transition EvArtifactTransfer = "artifact_transfer" // artifact fetch → from/to/hash/size/ok/elapsed EvAgentUsage = "agent_usage" // adapter's structured token breakdown → agent/input/output/cache_* EvContextOverflow = "context_overflow" // agent failed on its context window → parked in review, retry cannot help EvSubagentEvent = "subagent_event" // agent spawned a sub-agent (Claude Task tool) → note )
Trace event types for decision-orbit visibility. These are written to task_events alongside the existing lifecycle events; the panel's SSE feed forwards them in real time to the orbit component, and GET /api/tasks/{id} aggregates them for a replay when a client opens the detail mid-run.
Best-effort only: a write failure is logged and otherwise ignored. The scheduling/delegation/supervision machines must never stall on visibility.
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") // ErrAlreadyRunning reports that run() found the task already executing // under another goroutine (a duplicated resume/context_ack raced in). It // wraps ErrCancelled so every caller treats it as a quiet non-error: the // first runner owns execution and reports the outcome, and this // invocation must neither re-execute nor disturb the live row. ErrAlreadyRunning = fmt.Errorf("%w: already running on this node", ErrCancelled) // ErrApprovalNeedsChangedInput reports that a reviewed task cannot be // approved as-is. Its input, scope, or context must change before a new run. ErrApprovalNeedsChangedInput = errors.New("approval requires changed input") )
State-machine errors. Callers should wrap them with %w to preserve errors.Is checks.
var ErrTaskActive = errors.New("task is active")
ErrTaskActive reports a delete attempted on a task that is still executing (dispatched / running / waiting_context / review). Those rows must be cancelled first: deleting one out from under a live executor would strand its result handling and lease renewals against a task that no longer exists.
Functions ¶
func CanTransition ¶
CanTransition reports whether from -> to is legal per the Phase 0 state table (design doc §5.3.1).
func Deletable ¶ added in v0.0.8
Deletable reports whether a task in state s may be removed from the store: anything not yet claimed (submitted/queued) and every terminal state. The active states refuse with ErrTaskActive — see Delete.
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.
func FilterSensitiveData ¶ added in v0.0.8
FilterSensitiveData replaces credential-shaped substrings in s with [REDACTED]. Only safe on text — see the note on sensitivePatterns.
func HasSensitiveData ¶ added in v0.0.8
HasSensitiveData reports whether s contains anything credential-shaped.
func IsTaskState ¶ added in v0.0.8
IsTaskState reports whether s names a task state.
func NodeID ¶
NodeID is this node's stable identifier. Phase 0 uses the configured name; a generated UUID may be preferred once remote discovery exists.
func RuntimeNodeID ¶ added in v0.0.4
RuntimeNodeID keeps legacy physical node IDs stable while preventing a VM configured with the same display name from colliding with its host node.
func TaskStates ¶ added in v0.0.8
func TaskStates() []string
TaskStates lists every state a task row can hold, in lifecycle order. The constants above are the vocabulary; this is that vocabulary as data, for the callers that have to check a state they did not produce — `panda queue --state <s>` validating a typed filter is the reason it exists. Keeping it next to the constants is what keeps the two from drifting.
Types ¶
type AmbiguousTaskIDError ¶ added in v0.0.8
AmbiguousTaskIDError reports that a task-id prefix matched more than one task. It carries the candidates so a CLI can show the user what to disambiguate between instead of only saying that it could not decide.
func (*AmbiguousTaskIDError) Error ¶ added in v0.0.8
func (e *AmbiguousTaskIDError) Error() string
type ApprovalDisposition ¶ added in v0.0.8
type ApprovalDisposition string
ApprovalDisposition describes what approving a reviewed task must do. AcceptWork accepts work that already ran; ResumeExecution grants consent to a task that parked before producing work and must be executed exactly once.
const ( ApprovalAcceptWork ApprovalDisposition = "accept_work" ApprovalResumeExecution ApprovalDisposition = "resume_execution" ApprovalNeedsChangedInput ApprovalDisposition = "needs_changed_input" )
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) AdvancePlan ¶ added in v0.0.6
AdvancePlan releases every stage whose dependencies are now satisfied. It is idempotent and safe to call from any completion path: a stage already released is no longer in submitted, and a concurrent release loses the CAS.
Readiness is computed by rebuilding the plan from the task rows and asking plan.Ready, rather than re-deriving the rule here: the rows are the plan, and one implementation of "ready" is easier to trust than two.
func (*Core) Artifacts ¶ added in v0.0.6
Artifacts returns the node's artifact pool, or nil if none is configured.
func (*Core) AttachSupervisor ¶ added in v0.0.3
func (c *Core) AttachSupervisor(model config.ModelConfig)
AttachSupervisor builds a supervisor client from the model config and attaches it — but only when the model is actually configured (an API key is present), so a model-less node keeps single-shot agent execution instead of burning a wasted judge call per task. A build failure is non-fatal: agent tasks then finish in one shot exactly as before. The supervisor also gets the disk cache over the node database: identical (intent, result) pairs reuse the previous verdict without an LLM call.
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. The cancelled id set is the store cascade's, so a caller can still report how many tasks it touched.
func (*Core) Card ¶ added in v0.0.7
Card snapshots the current capability card (guarding the swap a reload may be performing concurrently).
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) DispatchChild ¶ added in v0.0.9
DispatchChild routes a spawned child the way Submit routes a root task (§4.2): the best-scored capable peer wins, with this node as an ordinary candidate. A forwarded child is a normal delegation — its result returns here via handleResult, where it both completes the local copy and unblocks whatever spawned it. A local/declined child lands on the queue scheduler, which runs it here (or re-routes via forwardScheduled on the next pass).
func (*Core) Enqueue ¶ added in v0.0.2
Enqueue creates a task and hands it to the local queue scheduler instead of executing it inline: the task lands in queued state (marked scheduled) and returns immediately; the scheduler starts it when its resources are free and an execution slot is available. It is the panel's task-submission path (queue redesign), contrasting Submit/SubmitLocal which block until done.
func (*Core) EvTrace ¶ added in v0.0.7
EvTrace records one trace event. Errors are downgraded to a warning log: a visibility layer outage must never mask the actual execution path.
func (*Core) EvaluateLinkState ¶ added in v0.0.9
EvaluateLinkState calculates the link state towards targetNode based on live connection status and heartbeat exponential freshness discount (whitepaper §8.1).
func (*Core) FetchArtifact ¶ added in v0.0.6
func (c *Core) FetchArtifact(ctx context.Context, source, taskID, hash string) (artifact.Manifest, error)
FetchArtifact pulls the artifact named by hash from source into this node's pool and returns its manifest. An artifact the node already holds is returned without any bytes on the wire — the hash is proof enough, which is what makes re-delegating a stage to a node that ran an earlier one nearly free.
The thin wrapper exists so every exit path — the local-hit fast return, every abort inside the transfer loop, and success — lands one artifact_transfer trace event without sprinkling emissions through the loop.
func (*Core) FetchArtifactRef ¶ added in v0.0.9
func (c *Core) FetchArtifactRef(ctx context.Context, source, taskID string, ref bus.ArtifactRef) (artifact.Manifest, error)
FetchArtifactRef is FetchArtifact with the full input reference: a ref that carries the orchestrator's OfTask/Grant/Issuer asks the producer to serve on the strength of the signed grant rather than on the consumer's own task row — the difference that makes direct stage-to-stage handoff possible when the producer never saw the consumer's task.
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) ImportFatBundleArtifacts ¶ added in v0.0.9
func (c *Core) ImportFatBundleArtifacts(ctx context.Context, artifacts []bus.FatBundleArtifact) ([]artifact.Manifest, error)
ImportFatBundleArtifacts imports an array of proactive bundled artifacts directly into the node's local artifact pool, verifying SHA256 integrity and eliminating round-trip pulls (whitepaper §8.3).
func (*Core) Listen ¶
Listen starts the WebSocket server and accepts connections. Blocks until ctx is done.
func (*Core) ListenUDP ¶ added in v0.0.9
ListenUDP starts the datagram plane on addr. The shared secret is required — it derives both the AEAD key and the punch signer, and an unkeyed UDP socket would accept nothing anyway. The listener and its keepalive loop stop with ctx.
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) Negotiate ¶ added in v0.0.9
func (c *Core) Negotiate(ctx context.Context, target string, p bus.AgentNegotiatePayload) (bus.AgentGrantPayload, error)
Negotiate sends one scope request to a peer and waits synchronously for its grant/deny verdict — the caller-side half of §5.1 that turns the wire messages into an arbitration primitive.
func (*Core) PunchPeer ¶ added in v0.0.9
PunchPeer initiates a pinhole toward peerID: it sends a punch_offer envelope through the mesh (directly if a conn exists, relayed along the link-state graph otherwise) and sprays signed punch frames at every candidate it already knows for the peer. The ready reply starts the peer spraying back; the first verified datagram from either direction binds the route. Safe to call while a WS conn exists — the datagram route simply becomes an additional path and sendTo keeps preferring the conn.
func (*Core) QueueScheduler ¶ added in v0.0.2
QueueScheduler exposes the running scheduler (nil before StartQueueScheduler). Used by tests and diagnostics.
func (*Core) ReloadCard ¶ added in v0.0.7
ReloadCard swaps the capability card at runtime: load + validate the file, prune native abilities this host cannot run, swap the card and rebuild the router from it, re-register this node in the local directory, then announce the change to every connected peer with a card-carrying heartbeat. Until now a card edit required a daemon restart before the network saw the new abilities; this is the "改卡热生效" half of the equation.
func (*Core) ResumeApproved ¶ added in v0.0.7
func (c *Core) ResumeApproved(ctx context.Context, taskID string) (Task, bus.TaskResultPayload, error)
ResumeApproved grants tier-2 consent to a task parked in review by an authorization refusal and re-runs it, returning the final row and result. It is the inline approval closure: when the user approves a tier-2 agent at the ask/repl prompt, the task that just refused runs to completion in the same round-trip — no background scheduler required (the ask/repl process runs none). This is the cost-efficient path: the tier-2 refusal is raised before the agent subprocess ever spawns, so the first Submit spent no agent tokens and the resume is the sole execution.
Where the re-run happens follows the task: a task this node executed runs here; a task a peer executed re-runs on that peer (task_resume), because this node may lack the capability that routed the task away in the first place, and the executor's review-parked copy is the one holding the work.
The task must be in review; its intent and requirements are read from the persisted row (the entry model's distilled intent, plus the appended user prompt, both stored at submit). Approval and dispatch are guarded state transitions: one concurrent approver wins, while every other caller gets a conflict instead of starting the agent a second time.
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 runs the full monitor tick — the task-lifecycle sweeps plus the peer-directory duties that only make sense on the node owning the peer connections. It returns when ctx is done.
func (*Core) RunReconcile ¶ added in v0.0.9
RunReconcile runs only the local-work reconcile — the minimal monitor for surfaces that submit inline (REPL, TUI, one-shot ask): they never own the queue, but a task they execute can still be cancelled or force-failed by another process, and this pass is what stops the orphaned execution instead of letting it run to the agent hard timeout.
func (*Core) RunTaskMonitor ¶ added in v0.0.9
RunTaskMonitor runs the task-lifecycle half of the monitor for an embedded surface — the web panel, `panda web`, any long-lived process that executes tasks off the shared store without owning the peer connections. Without it that process's tasks stall silently: a parked waiting_context never times out, a queued-remotely orphan is never rescued, an expired lease is never enforced, and the store alone cannot tell queued work why nothing moved. The peer-directory sweeps stay daemon-only: a second process marking peers offline from a connection set it does not own would fight the real node's heartbeats.
func (*Core) SendNegotiation ¶ added in v0.0.9
func (c *Core) SendNegotiation(ctx context.Context, target string, p bus.AgentNegotiatePayload) error
SendNegotiation sends a horizontal conflict negotiation signal to target peer (whitepaper §5.1).
func (*Core) SetAgentMCPPassthrough ¶ added in v0.0.7
SetAgentMCPPassthrough sets the stdio MCP server (mcp.command argv string, empty disables) that extended-policy agent runs expose to the delegated agent CLI via a work-dir .mcp.json. Remembered like the router policy so a ReloadCard rebuild re-applies it.
func (*Core) SetArtifactStore ¶ added in v0.0.6
SetArtifactStore attaches the node's artifact pool. Nil leaves the node without a data plane: it can still delegate and execute, but a stage whose input is an artifact hash will fail rather than silently run on missing input.
func (*Core) SetContacts ¶ added in v0.0.9
SetContacts installs this node's advertised contact plan (§8.4). Call it after NewCore, before the serving goroutines start — the slice is read unsynchronized afterward. The plan gossips out in every heartbeat and lands in the local directory row via refreshSelfNeighbors.
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 Hermes injector (entry-model conversation context; no longer used for agent-prompt injection since A1), 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) SetProjectStores ¶ added in v0.0.8
SetProjectStores attaches the project plane: the metadata table (which knows a project's work tree) and the root of the project memory directories. Both are needed to make a delegated project task mean anything on the receiving machine — one supplies the tree to send, the other the directory to land memory in. Either may be zero, which leaves project-aware delegation off.
func (*Core) SetRouterPolicy ¶ added in v0.0.2
func (c *Core) SetRouterPolicy(injection config.InjectionConfig, routing config.RoutingConfig)
SetRouterPolicy applies the configured injection/routing policy to the commander router (injection.model and routing.preferred_agents). Call it after NewCore with the loaded config sections; a nil router (empty card) makes it a no-op. The sections are also remembered so ReloadCard can rebuild the router with the same policy.
func (*Core) SetSelfConfigPath ¶ added in v0.0.9
SetSelfConfigPath forwards the daemon's --config path to the router so the .mcp.json it materializes can pass it to `panda mcp`. Remembered like the passthrough so a ReloadCard rebuild re-applies it.
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) SetSuperviseRounds ¶ added in v0.0.3
SetSuperviseRounds bounds the execute → judge → re-delegate loop for agent tasks. A value <= 0 resets to defaultSuperviseRounds.
func (*Core) SetSupervisor ¶ added in v0.0.3
SetSupervisor attaches the entry model client that judges agent task completeness (上级完成度判定). A nil client disables supervision: agent tasks then finish in one shot exactly as before, so minimal nodes and tests are unaffected.
func (*Core) SetTimeouts ¶ added in v0.0.6
func (c *Core) SetTimeouts(t config.TimeoutsConfig)
SetTimeouts applies the configured execution timeouts: the agent-adapter budget (process-global, in commander) and this node's task lease.
It enforces the ordering the two constants used to violate: the lease is raised, if necessary, to sit clearly past the agent's hard wall-clock limit. With a 600s adapter budget (630s hard limit) against a 600s lease, every long agent run outlived its own lease — the monitor force-failed it, the parent re-routed the same work to another node, and two agents then edited the same repository at once. The lease bounds *silence* from an executor, not total runtime: renewLease heartbeats it while execution is live.
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) SpawnChildTask ¶ added in v0.0.9
SpawnChildTask creates a child task under parentID, implementing the Sub-MainAgent recursive delegation model (whitepaper §4.2). The executing node promotes itself to Sub-MainAgent, spawning child causal tasks with bounded depth.
The child inherits the parent's causal chain verbatim — the chain records the delegation path, and its tail is already this node (the Sub-MainAgent that received the parent). Appending self again would forge an immediate self-loop; resetting it would launder the mesh-wide loop history. The next hop is appended by whoever forwards the child, and the parent's remaining mesh budget carries over (§6.1): the budget is spent at dispatchDelegated, not here, so a locally-run child costs nothing.
func (*Core) StartPlan ¶ added in v0.0.6
StartPlan validates a plan, creates one task per stage, and releases the stages that have no dependencies. It returns the plan id, which is how the caller follows the whole run (PlanStages) rather than one task at a time.
Every stage is created as a queued-scheduler task with no work dir: a path from the machine that wrote the plan is meaningless on the machine that runs the stage, so each executor derives its own (stageWorkDir). No stage carries tier-2 consent either — an irreversible stage parks in review for the user, which is exactly the pending-approval behaviour a plan should have.
func (*Core) StartQueueScheduler ¶ added in v0.0.2
StartQueueScheduler starts the node-local queue scheduler loop: it adopts queued-and-scheduled tasks in policy order (drag seq → priority → FIFO), enforcing resource conflicts and the card's MaxConcurrent budget. Idempotent within one Core; runs until ctx ends.
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
Cost sql.NullFloat64
CreatedAt int64
}
DelegationMetric is one row of the delegation_metrics table.
type LinkState ¶ added in v0.0.9
type LinkState string
LinkState represents the 3-state link classification (whitepaper §8.1): Live, Opportunistic, or Offline.
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 PlanSummary ¶ added in v0.0.8
type PlanSummary struct {
PlanID string `json:"plan_id"`
Stages int `json:"stages"`
Done int `json:"done"`
Failed int `json:"failed"`
Running int `json:"running"`
Review int `json:"review"`
Goal string `json:"goal,omitempty"`
StageIDs []string `json:"stage_ids,omitempty"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
PlanSummary is one plan as a listing row: how many stages it has, how many have finished, and when it was last active. It is what a plan board needs before the user picks one to open, and it is derived rather than stored — a plan has no row of its own, only the stages that carry its id.
type PromptLanguagePolicy ¶ added in v0.0.8
type PromptLanguagePolicy struct {
UserLocale i18n.Locale
ModelGeoRegion providers.GeoRegion
ForceEnglish bool // User explicitly requested English prompts
ForceChinese bool // User explicitly requested Chinese prompts
}
PromptLanguagePolicy determines the prompt and output language strategy based on user locale, provider origin, and explicit overrides.
func (PromptLanguagePolicy) RecommendedOutputLang ¶ added in v0.0.8
func (p PromptLanguagePolicy) RecommendedOutputLang() i18n.Locale
RecommendedOutputLang returns the recommended language for final human-facing outputs. User output language strictly respects the user's locale.
func (PromptLanguagePolicy) RecommendedPromptLang ¶ added in v0.0.8
func (p PromptLanguagePolicy) RecommendedPromptLang() i18n.Locale
RecommendedPromptLang returns the recommended language for constructing prompts.
type QueueSpec ¶ added in v0.0.2
QueueSpec carries the queue-scheduling metadata for an Enqueued task. Priority must be one of PriorityHigh/Normal/Low; use DefaultQueueSpec for the normal-priority defaults so a zero struct is never submitted by accident (PriorityHigh is 0).
func DefaultQueueSpec ¶ added in v0.0.2
func DefaultQueueSpec() QueueSpec
DefaultQueueSpec returns a spec with normal priority and no session/ resource bindings.
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
// ApprovalDisposition is persisted whenever the task enters review. Empty is
// reserved for legacy rows and is classified conservatively from their audit
// trail; new rows use one of the stable Approval* protocol strings.
ApprovalDisposition ApprovalDisposition
// OperationDecisionJSON carries the concrete pre-operation decision/evidence
// that caused a review. V17 reserves the durable field; the typed arbitration
// layer populates it when an adapter can report the operation before execution.
OperationDecisionJSON 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
// AuthSig/AuthPub/AuthTs persist the origin node's Ed25519 consent grant
// alongside the flag, so a relay re-dispatching this task re-emits the
// signed consent instead of degrading it to the bare flag (P2-8).
AuthSig string
AuthPub string
AuthTs int64
// 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
// Queue-scheduling metadata (panel queue redesign). Priority/Seq order the
// board and the local scheduler (seq>0 = user-dragged, wins over priority);
// SessionID links the task to its panel conversation; ResourceKeys declare
// the resources the task occupies for conflict detection; WorkDir pins
// execution to a session worktree; Scheduled marks tasks owned by the local
// queue scheduler (never the delegation re-routing path).
Priority int
Seq int64
SessionID string
ResourceKeys []string
WorkDir string
Scheduled bool
// AgentSessionID is the adapter's own conversation handle, persisted each
// round so an interrupted run (yield, restart, redelegation back here)
// resumes the agent's session instead of cold-starting (§5.2). The handle
// only means something to the node that minted it — AgentSessionNode —
// so a delegator may offer it back to that node (ResumeSessionID on the
// wire) but must never adopt it for its own adapter or hand it onward.
AgentSessionID string
AgentSessionNode string
// Plan-plane metadata (v0.0.6). A stage of a plan is an ordinary task, so
// these are the only things it carries beyond one: PlanID/StageID name its
// place in the plan, Needs is the stage_ids it waits for, and the artifacts
// are the data plane — Inputs are the trees this stage starts from (each with
// a node known to hold it), OutputArtifact the tree it produced for its
// successors. All empty on a standalone task.
PlanID string
StageID string
Needs []string
Inputs []bus.ArtifactRef
OutputArtifact string
// UserLocale is the user's language preference ("en", "zh-CN", etc.).
UserLocale string
// Transport marks the transport mode for this task ("live" or "dtn").
Transport string
// DeadlineUnix is the absolute TTL expiration timestamp for DTN tasks (§8.2).
DeadlineUnix int64
// DelegationBudget is the remaining mesh-wide delegation quota (§6.1):
// each forward hop decrements it, and a task that runs out may no longer
// be delegated — the mesh-wide convergence bound alongside MaxChainDepth.
DelegationBudget int
// TokenBudget is the remaining LLM token quota the task may spend across
// the mesh (§6.1): 0 means unbounded (a legacy wire or a pre-budget row),
// a positive value is the spendable remainder, and -1 is the persisted
// exhaustion marker — an exhausted task may neither execute another
// metered round nor be delegated onward, since either would launder the
// bound into fresh budget on the next hop.
TokenBudget int64
}
Task is the persisted task row (Phase 0 subset of the schema).
func (Task) GetUserLocale ¶ added in v0.0.8
GetUserLocale returns the task's language preference as an i18n.Locale, checking UserLocale first, then parsing SpecJSON, falling back to English.
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
// UserLocale carries the user's language preference.
UserLocale string
// Transport carries the preferred transport mode ("live" or "dtn").
Transport string
// DeadlineUnix carries the absolute TTL expiration timestamp for DTN tasks.
DeadlineUnix int64
}
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
ParentID string // causal parent task ID for subtasks / sub-DAGs
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)
// WorkDir pins execution to the originating workspace. It is persisted before
// routing/execution so concurrent callers never swap the Core's ambient work dir.
WorkDir string
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
// ClassifyKind carries the entry model's classification ("task") for trace
// emission. Empty means the input did not come from a classified ask (a
// direct CLI submission, a delegated peer task): no classify_result event
// fires for those, matching the pre-trace behavior.
ClassifyKind string
// UserLocale records the user's language preference ("en", "zh-CN", etc.).
UserLocale i18n.Locale
// Transport specifies the transport mode ("live" or "dtn", whitepaper §8.2).
Transport string
// DeadlineUnix is an optional absolute deadline timestamp for DTN tasks.
DeadlineUnix int64
}
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) AddOnEvent ¶ added in v0.0.8
AddOnEvent registers a concurrent-safe per-event observer fired after every task event is appended. Returns an unsubscribe function that removes the listener.
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) ApprovalDisposition ¶ added in v0.0.8
func (s *TaskStore) ApprovalDisposition(ctx context.Context, taskID string) (ApprovalDisposition, error)
ApprovalDisposition classifies the latest review parking without exposing the audit-event encoding to callers.
func (*TaskStore) Approve ¶
Approve accepts a reviewed task. A task that parked before execution moves to an unscheduled queued state carrying consent; Core.ResumeApproved claims it immediately. Work that already ran is accepted directly into done.
func (*TaskStore) ArtifactIndexedFor ¶ added in v0.0.9
ArtifactIndexedFor reports whether the local pool's index ties hash to taskID — i.e. this node recorded the artifact while packing it for, or pulling it under, that task. artifactPeerAuthorized consults it so a peer can only fetch artifacts the task it quotes actually owns: participation alone must not open the whole pool to one known hash.
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).
The pre-check and the guarded UPDATE below are not atomic, so a cancel can race the execute loop's own transitions (dispatched→running on accept, queued→dispatched on re-dispatch). A zero-row update used to fail with ErrConflict right there — silently dropping a cancel that was fully legal a millisecond later and letting the task run to completion under nodes that believed it cancelled (the cancel-propagation CI flake). Instead, re-read and retry: a task that reached a terminal state wins (done keeps its recorded result, a concurrent cancel is idempotent success); a task that merely moved between active states is still cancellable, and the loop lands the cancel on the fresh state.
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. When the cancelled row is a plan stage, its sibling stages are cancelled too — stages carry no parent_id, so without the plan sweep a stage cancel would strand the rest of the plan mid-flight, blocked stages waiting forever on predecessors that can now never complete. The returned slice lists the tasks actually transitioned to cancelled — already-terminal tasks are skipped, not included.
func (*TaskStore) ClaimApproved ¶ added in v0.0.8
func (s *TaskStore) ClaimApproved(ctx context.Context, taskID, expectedOwner, newOwner, target string) error
ClaimApproved atomically grants consent and claims a resume-required review for foreground execution. expectedOwner is the exact persisted owner used by the SQL compare-and-swap; newOwner is the current participant taking the lease. Keeping those identities separate permits an authorized restart to transfer ownership without weakening the exactly-once guard.
func (*TaskStore) ClaimLocal ¶ added in v0.0.2
ClaimLocal moves a queued task to dispatched-to-self for the queue scheduler. Unlike Dispatch it does not require the caller to already own the task: scheduled tasks are a node-local pool any running scheduler instance may adopt (e.g. after a panel restart left them queued). The state-guarded UPDATE is the race arbiter — exactly one claimant wins.
func (*TaskStore) ClearQueue ¶ added in v0.0.8
ClearQueue empties the board: every non-terminal task is cancelled first (the same local-row semantics as CancelCascade — a remote executor is told through the engine's cancel path, not here), then every task row and its satellites are deleted in one transaction. Returns how many tasks were cancelled and how many rows were deleted.
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; review is intentionally protected, 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) CountScheduledActive ¶ added in v0.0.2
CountScheduledActive counts execution slots occupied by locally-scheduled tasks, regardless of owner: the queue scheduler may adopt queued tasks left behind by another process instance (e.g. a restarted panel sidecar), so its concurrency budget must count what is actually running, not just rows that already carry its own node id.
A dispatched row occupies a LOCAL slot only while its dispatch target is this node: forwardScheduled re-targets the claim to a peer (RetargetDelegation records the new EvDelegate target) and the peer then runs it, so the row sits 'dispatched' while the work happens elsewhere. Counting it anyway double-books capacity — the executor charges the slot on its own CountActive, and this node would refuse fresh claims on a budget the peer is spending. running and waiting_context are unambiguous (only the executor ever reaches them), so the exclusion applies to 'dispatched' alone. The latest delegate event is the authority: a corrective retarget back to self after a failed send restores the row to locally-claimed, which is exactly what it is.
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) Delete ¶ added in v0.0.8
Delete removes a task and its whole subtree from the store: the tasks rows, their event timelines, delegation metrics and any parked outbox deliveries. Only deletable states go (see Deletable); an active task anywhere in the subtree refuses with ErrTaskActive so a running executor never has its row pulled out from under it — cancel first, then delete. Returns how many task rows were removed.
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, while preserving a task already parked for human review.
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) Idle ¶ added in v0.0.3
Idle reports whether the store has no in-flight tasks (running, dispatched, or waiting for context). It mirrors Core.Idle so callers that only hold a *TaskStore (the web panel) can gate on the same condition without a Core.
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) ListPlans ¶ added in v0.0.8
func (s *TaskStore) ListPlans(ctx context.Context) ([]PlanSummary, error)
ListPlans summarizes every plan this node knows, most recently active first.
There is no plans table: a plan is exactly the set of tasks sharing a plan_id (that is what makes a stage an ordinary task, with the CAS state machine, the lease and the audit chain it already had). So the listing is an aggregate over tasks, served by idx_tasks_plan.
func (*TaskStore) ListReady ¶ added in v0.0.2
ListReady returns every task waiting for the local queue scheduler: queued and marked scheduled. Ordering happens in the scheduler's policy, not here.
func (*TaskStore) MarkExpired ¶ added in v0.0.9
MarkExpired moves a non-terminal task straight to expired, bypassing the ordinary transition table: a deadline reached while dispatched or queued is not a failure of the work, it is the bundle's lifetime ending — the distinction the 'expired' state exists to carry.
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) PauseWithDisposition ¶ added in v0.0.8
func (*TaskStore) PauseWithResult ¶ added in v0.0.3
PauseWithResult transitions a running task to review while preserving the execution result, so the human reviewer sees what was done as well as why it needs sign-off (supervision loop terminal: an irreversible task, or one that exhausted its round budget without satisfying the success criteria).
func (*TaskStore) PendingPlans ¶ added in v0.0.6
PendingPlans returns the plans that still hold an unreleased stage. Cheap enough to ask on every monitor tick: idx_tasks_plan covers it, and a node with no plans answers from the index without touching a row.
func (*TaskStore) PlanStages ¶ added in v0.0.6
PlanStages returns every stage of one plan, ordered by stage id so the listing is stable across calls. This is the orchestrator's hot query — asked each time a stage finishes to decide what became ready — and idx_tasks_plan serves it.
func (*TaskStore) QueuedDelegatedRemotely ¶ added in v0.0.7
QueuedDelegatedRemotely lists this node's queued tasks whose most recent dispatch targeted a DIFFERENT node: delegations handed to a peer that came back to queued (a restart's Recover, a decline) with nobody left to drive them. Left alone they are orphans — no local scheduler adopts a row whose work belongs on another device, and the upstream nodes only notice when their own leases expire. The orphan sweep (rescueOrphanedForwards) re-routes or fails them; see it for the full lifecycle.
func (*TaskStore) RecordArtifact ¶ added in v0.0.6
func (s *TaskStore) RecordArtifact(ctx context.Context, hash string, size int64, taskID, manifestJSON string) error
RecordArtifact indexes an artifact this node holds. The row is the pool's catalogue, not its content: the archive itself lives in the artifact store under its hash, because a trained model is measured in gigabytes and has no business inside SQLite. A re-recorded hash is an update, not a conflict — content addressing means the bytes cannot have changed.
func (*TaskStore) RecordDelegationMetric ¶
func (s *TaskStore) RecordDelegationMetric( ctx context.Context, taskID, delegator, executor string, abilities []string, success bool, latencyMs int64, tokens int, cost ...float64, ) 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) RecordEvent ¶ added in v0.0.2
RecordEvent is the exported recordEvent for collaborators outside core (the panel's session finalizer marks summary turns this way).
func (*TaskStore) Recover ¶
Recover normalizes tasks left in an active state by a previous process instance. Running/waiting_context become failed (execution was interrupted); dispatched/submitted return to queued for re-dispatch. Returns the number of tasks touched.
review is deliberately excluded: a task parked for human sign-off has no executing process to lose, so a restart must not discard the queue of things waiting on a person — every other path in this file protects that invariant (CompleteFromRemote / FailFromRemote / ReviewFromRemote return early on StateReview, ExpireTasks excludes it), and Recover runs unconditionally on every daemon start. The interrupted rows also keep their result_json so the evidence of what ran survives, and each transition is written to the audit chain rather than mutating state_version silently.
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) RenameProject ¶ added in v0.0.8
RenameProject moves every task from one project name to another and reports how many moved. A project's name appears on its tasks as data, so renaming the project without renaming them would leave the tasks pointing at a project that no longer exists — visible immediately as an empty `panda queue --project`.
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) RequeueForRetry ¶ added in v0.0.9
RequeueForRetry is the atomic form of the retry loop's three-step move (RotateAttempt -> Requeue -> Dispatch to self): mint a fresh attempt_id, move the task failed -> dispatched, and append both the EvRetry and EvDelegate audit events in ONE transaction. Splitting those steps (the old retryOnce) left the row in queued or carried the stale attempt_id if the node crashed or lost the owner guard mid-sequence — a half-retry the audit trail could not distinguish from a completed one. The state+owner guard keeps the same exactly-once semantics as the separate calls; on conflict nothing is written. Returns the new attempt id.
func (*TaskStore) ResolveTaskID ¶ added in v0.0.8
ResolveTaskID turns a user-typed task reference into a full task id. An exact id is returned unchanged (a full id always wins, so a prefix that happens to be another task's whole id is never surprising); otherwise the ref is matched as a prefix.
This exists because every listing surface abbreviates a task id to its first UUID group — that is the only way a row fits a terminal — and an id a user can read but not type is not an id. Prefixes do collide: UUIDv7 puts a millisecond timestamp in exactly those leading bytes, so two tasks submitted in the same second share the group. That is why the ambiguous case is an error with candidates rather than a newest-wins guess: acting on the wrong task is worse than asking.
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) RetargetDelegation ¶ added in v0.0.5
RetargetDelegation records a new delegation target for a task that is already dispatched — e.g. the local queue scheduler forwarding its claim to a capable peer. State and owner stay unchanged; only the EvDelegate audit event is appended, which is what DispatchTarget and isCurrentExecutor authenticate the peer's result/decline against.
func (*TaskStore) RetryCount ¶ added in v0.0.7
RetryCount returns the number of retries recorded on a task's audit trail (one EvRetry event per Requeue). Unlike the in-memory loop detector — whose counters reset with the process — this count survives daemon restarts, so a deterministically failing task cannot earn an unbounded number of attempts by crashing and restarting its node between retries (S2-6).
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) ReviewFromRemote ¶ added in v0.0.4
func (s *TaskStore) ReviewFromRemote(ctx context.Context, taskID, owner string, result any, disposition ApprovalDisposition) error
ReviewFromRemote records that a remote executor parked the task for human review. Unlike Review, which is the local retry-loop transition from failed, a remote result may arrive while the delegator's copy is submitted, queued, dispatched, or running. The state is still guarded so a concurrent terminal transition wins and cannot be overwritten by a late result.
func (*TaskStore) ReviewWithDisposition ¶ added in v0.0.8
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) SetAgentSession ¶ added in v0.0.9
SetAgentSession writes the handle together with the node that minted it. The executor passes its own id; a delegator learning a remote session from a task_result passes the executor's — which is what lets a later re-dispatch offer ResumeSessionID only to the node it belongs to.
func (*TaskStore) SetAgentSessionID ¶ added in v0.0.9
SetAgentSessionID persists the adapter conversation handle for the task (§5.2 breakpoint mooring). Written every round as the session evolves and cleared when the run ends, so a task that is interrupted mid-flight resumes its agent session while a finished one never drags a dead handle into a re-run.
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) SetAuthorizedGrant ¶ added in v0.0.9
func (s *TaskStore) SetAuthorizedGrant(ctx context.Context, taskID, sig, pub string, ts int64) error
SetAuthorizedGrant is SetAuthorized plus the signed consent the delegate carried: the grant persists so a later re-dispatch (queue forward, decline re-route) re-emits the origin's Ed25519 signature instead of degrading the consent to the bare flag on the next hop (P2-8).
func (*TaskStore) SetDelegationBudget ¶ added in v0.0.9
SetDelegationBudget persists the remaining mesh-wide delegation budget the task carries (whitepaper §6.1). Stamped on creation — locally at submit, remotely when a delegate envelope adopts the payload's budget — so a restarted node cannot re-mint budget the mesh already spent.
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) SetOnEvent ¶ added in v0.0.7
SetOnEvent installs (or clears, with nil) the per-event observer fired after every task event is appended. It is a best-effort, display-only feed: the callback must not touch the store or block, since it runs synchronously on the recording goroutine. The ask engine uses it to surface live route/exec/ judge progress while a synchronous Submit blocks (P0 §1.4).
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) SetOutputArtifact ¶ added in v0.0.6
SetOutputArtifact records the hash of the tree a stage produced. On the executor it is written when the work-dir is packed; on the plan node when the result arrives — both ends keep the same fact so either can serve the pull.
func (*TaskStore) SetPriority ¶ added in v0.0.2
SetPriority changes a task's queue priority. Only meaningful before the task finishes; the board and scheduler read it on their next tick.
func (*TaskStore) SetQueueMeta ¶ added in v0.0.2
func (s *TaskStore) SetQueueMeta(ctx context.Context, taskID string, priority int, sessionID, workDir string, resourceKeys []string) error
SetQueueMeta stamps the queue-scheduling metadata on a task and marks it scheduled (owned by the local queue scheduler). Called once by Enqueue before the task enters queued state.
func (*TaskStore) SetSeq ¶ added in v0.0.2
SetSeq sets the manual (drag) ordering value. 0 clears it back to pure priority/FIFO placement.
func (*TaskStore) SetSessionID ¶ added in v0.0.2
SetSessionID links a task to a panel conversation after the fact (session asks learn the task id only once the engine returns it).
func (*TaskStore) SetStage ¶ added in v0.0.6
func (s *TaskStore) SetStage(ctx context.Context, taskID, planID, stageID string, needs []string) error
SetStage stamps a task's place in a plan: the plan it belongs to, its stage id within that plan, and the stage ids it waits for. Called once at StartPlan, before the stage is released.
func (*TaskStore) SetStageInputs ¶ added in v0.0.6
func (s *TaskStore) SetStageInputs(ctx context.Context, taskID string, inputs []bus.ArtifactRef) error
SetStageInputs records the artifacts a stage starts from. Written by the plan node the moment the last predecessor finishes — that is the first point at which every input hash, and a node known to hold it, are both known.
func (*TaskStore) SetTokenBudget ¶ added in v0.0.9
SetTokenBudget persists the remaining mesh-wide token quota the task carries (whitepaper §6.1). Stamped on creation — locally at submit when the caller declared one, remotely when a delegate envelope adopts the wire's remainder — so a restarted node cannot re-mint quota the mesh already spent.
func (*TaskStore) SetWaitingContext ¶
SetWaitingContext moves dispatched -> waiting_context.
func (*TaskStore) SetWorkDir ¶ added in v0.0.8
SetWorkDir pins a task to its originating workspace without assigning queue ownership. Inline asks use it before returning a review result so detached approval can resume in the same session worktree.
func (*TaskStore) SpendTokens ¶ added in v0.0.9
SpendTokens atomically bills n tokens against the task's remaining quota and returns what is left: 0 means the task is unbounded (legacy), a positive value is the spendable remainder, and -1 marks exhaustion. The decrement is a single UPDATE so a concurrent judge charge and adapter charge cannot both spend the same remainder; crossing zero lands on the -1 sentinel instead of wrapping back to "unbounded".
func (*TaskStore) TaskActivityByDay ¶ added in v0.0.9
TaskActivityByDay counts tasks per local calendar day, keyed "2006-01-02". It backs the /heatmap usage view: one point per day a task entered the system, no matter how the task ended. The 'localtime' modifier keeps day boundaries where the operator perceives them — a task created at 23:58 belongs to today, not to tomorrow's UTC.