core

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

View Source
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"
)

Task event types recorded in task_events.

View Source
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.

Variables

View Source
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

func CanTransition(from, to string) bool

CanTransition reports whether from -> to is legal per the Phase 0 state table (design doc §5.3.1).

func EphemeralNodeID

func EphemeralNodeID(base string) string

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 NodeID

func NodeID(cfgName string) string

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

func RuntimeNodeID(name, kind, identity string) string

RuntimeNodeID keeps legacy physical node IDs stable while preventing a VM configured with the same display name from colliding with its host node.

func Terminal

func Terminal(s string) bool

Terminal reports whether s has no valid outgoing transition.

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) 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

func (c *Core) CancelTree(ctx context.Context, taskID string) error

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

func (c *Core) DialPeer(ctx context.Context, addr string) error

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) Enqueue added in v0.0.2

func (c *Core) Enqueue(ctx context.Context, in TaskInput, q QueueSpec) (Task, error)

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) Idle

func (c *Core) Idle(ctx context.Context) bool

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) List

func (c *Core) List(status, name string) ([]ledger.Node, error)

List returns the local capability directory.

func (*Core) Listen

func (c *Core) Listen(ctx context.Context, addr string) error

Listen starts the WebSocket server and accepts connections. Blocks until ctx is done.

func (*Core) MaintainPeer

func (c *Core) MaintainPeer(ctx context.Context, addr string) error

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) QueueScheduler added in v0.0.2

func (c *Core) QueueScheduler() *queue.Scheduler

QueueScheduler exposes the running scheduler (nil before StartQueueScheduler). Used by tests and diagnostics.

func (*Core) Recover

func (c *Core) Recover(ctx context.Context) (int, error)

Recover normalizes tasks left active by a previous process instance.

func (*Core) Register

func (c *Core) Register(ctx context.Context) error

Register upserts this node in the local ledger.

func (*Core) RunHeartbeat

func (c *Core) RunHeartbeat(ctx context.Context)

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

func (c *Core) RunMonitor(ctx context.Context)

RunMonitor scans for expired leases and fails them. It returns when ctx is done.

func (*Core) SetHostStatePaths

func (c *Core) SetHostStatePaths(paths []string)

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

func (c *Core) SetLimits(maxConns, maxConnsPerIP int)

SetLimits configures the global and per-IP inbound connection limits. A limit <= 0 disables that limit.

func (*Core) SetMemoryStores

func (c *Core) SetMemoryStores(inj *memory.Injector, daily *memory.Daily, sk *skills.Store)

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) 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.

func (*Core) SetSharedSecret

func (c *Core) SetSharedSecret(secret string)

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

func (c *Core) SetSuperviseRounds(n int)

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

func (c *Core) SetSupervisor(client *entry.Client)

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) SetWorkDir

func (c *Core) SetWorkDir(dir string)

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) Shutdown

func (c *Core) Shutdown(ctx context.Context)

Shutdown marks the node offline and closes peers.

func (*Core) StartQueueScheduler added in v0.0.2

func (c *Core) StartQueueScheduler(ctx context.Context) *queue.Scheduler

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

func (c *Core) Submit(ctx context.Context, in TaskInput) (Task, bus.TaskResultPayload, error)

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

func (c *Core) SubmitLocal(ctx context.Context, in TaskInput) (Task, bus.TaskResultPayload, error)

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.

func (*Core) TaskStore

func (c *Core) TaskStore() *TaskStore

TaskStore exposes the store for CLI/queue views.

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 Event

type Event struct {
	ID       int64
	TaskID   string
	TS       int64
	Type     string
	DataJSON string
	PrevHash string
}

Event is one task_events row.

type Node

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

Node owns this process's ledger identity.

func NewNode

func NewNode(db *sql.DB, id string, card ledger.Card, tier int, logger *slog.Logger) *Node

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

func (n *Node) List(status, name string) ([]ledger.Node, error)

List returns the local capability directory, filtered by status/name ("" matches all).

func (*Node) Register

func (n *Node) Register(ctx context.Context) error

Register writes this node into the local capability directory.

func (*Node) RunHeartbeat

func (n *Node) RunHeartbeat(ctx context.Context)

RunHeartbeat starts a ticker that updates last_seen + capacity until ctx is done. It is safe to call concurrently with other core loops.

func (*Node) Shutdown

func (n *Node) Shutdown(ctx context.Context)

Shutdown marks the node offline. Idempotent.

type Peer

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

Peer is an established connection to another node.

type QueueSpec added in v0.0.2

type QueueSpec struct {
	Priority     int
	SessionID    string
	WorkDir      string
	ResourceKeys []string
}

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
	// 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

	// 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
}

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

func NewTaskStore(db *sql.DB, logger *slog.Logger) *TaskStore

NewTaskStore wraps a DB. now may be nil (defaults to Unix time).

func (*TaskStore) Accept

func (s *TaskStore) Accept(ctx context.Context, taskID, owner string) error

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

func (s *TaskStore) AdoptAttempt(ctx context.Context, taskID, attemptID string) error

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

func (s *TaskStore) Approve(ctx context.Context, taskID string) error

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

func (s *TaskStore) Cancel(ctx context.Context, taskID string) error

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

func (s *TaskStore) CancelCascade(ctx context.Context, taskID string) ([]string, error)

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) Children

func (s *TaskStore) Children(ctx context.Context, parentID string) ([]Task, error)

Children lists direct children of taskID.

func (*TaskStore) ClaimLocal added in v0.0.2

func (s *TaskStore) ClaimLocal(ctx context.Context, taskID, node string) error

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) Complete

func (s *TaskStore) Complete(ctx context.Context, taskID, owner string, result any) error

Complete transitions running -> done and stores the result.

func (*TaskStore) CompleteFromRemote

func (s *TaskStore) CompleteFromRemote(ctx context.Context, taskID, owner string, result any) error

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

func (s *TaskStore) CountActive(ctx context.Context, owner string) (int, error)

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

func (s *TaskStore) CountScheduledActive(ctx context.Context) (int, error)

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.

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

func (s *TaskStore) Decline(ctx context.Context, taskID, parent, reason, by string) error

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

func (s *TaskStore) DeclinedBy(ctx context.Context, taskID string) ([]string, error)

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) Dispatch

func (s *TaskStore) Dispatch(ctx context.Context, taskID, owner, target string) error

Dispatch transitions queued -> dispatched and records the target node.

func (*TaskStore) DispatchTarget

func (s *TaskStore) DispatchTarget(ctx context.Context, taskID string) (string, error)

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) Events

func (s *TaskStore) Events(ctx context.Context, taskID string) ([]Event, error)

Events returns the event timeline for a task, oldest first.

func (*TaskStore) ExpireTasks

func (s *TaskStore) ExpireTasks(ctx context.Context) ([]string, error)

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

func (s *TaskStore) Fail(ctx context.Context, taskID, owner, reason string) error

Fail transitions a task to failed. Allowed from running/dispatched/ waiting_context/review.

func (*TaskStore) FailFromRemote

func (s *TaskStore) FailFromRemote(ctx context.Context, taskID, owner, reason string) error

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

func (s *TaskStore) ForceFail(ctx context.Context, taskID, reason string) error

ForceFail fails an active task regardless of owner. Used by the timeout monitor and restart recovery when the owner may be gone.

func (*TaskStore) Get

func (s *TaskStore) Get(ctx context.Context, taskID string) (Task, error)

Get loads one task.

func (*TaskStore) Idle added in v0.0.3

func (s *TaskStore) Idle(ctx context.Context) bool

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

func (s *TaskStore) LastDelegateTime(ctx context.Context, taskID string) (int64, error)

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

func (s *TaskStore) ListByState(ctx context.Context, state string) ([]Task, error)

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) ListReady added in v0.0.2

func (s *TaskStore) ListReady(ctx context.Context) ([]Task, error)

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) Pause

func (s *TaskStore) Pause(ctx context.Context, taskID, owner, reason string) error

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) PauseWithResult added in v0.0.3

func (s *TaskStore) PauseWithResult(ctx context.Context, taskID, owner string, result any) error

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) Queue

func (s *TaskStore) Queue(ctx context.Context, taskID, owner string) error

Queue transitions submitted -> queued.

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) RecordEvent added in v0.0.2

func (s *TaskStore) RecordEvent(ctx context.Context, taskID, typ string, data any) error

RecordEvent is the exported recordEvent for collaborators outside core (the panel's session finalizer marks summary turns this way).

func (*TaskStore) Recover

func (s *TaskStore) Recover(ctx context.Context) (int, error)

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

func (s *TaskStore) Reject(ctx context.Context, taskID, reason string) error

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

func (s *TaskStore) Requeue(ctx context.Context, taskID, owner string) error

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

func (s *TaskStore) Resume(ctx context.Context, taskID, owner string) error

Resume moves waiting_context -> running once the context snapshot has been fetched and verified. Only the lease holder (executor) may resume.

func (*TaskStore) Review

func (s *TaskStore) Review(ctx context.Context, taskID, owner, reason string) error

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) 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) RotateAttempt

func (s *TaskStore) RotateAttempt(ctx context.Context, taskID, owner string) (string, error)

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

func (s *TaskStore) SetAuthorized(ctx context.Context, taskID string, authorized bool) error

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

func (s *TaskStore) SetDetail(ctx context.Context, taskID string, d TaskDetail) error

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

func (s *TaskStore) SetLease(ctx context.Context, taskID string, durationMS int64) error

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

func (s *TaskStore) SetOnReview(fn func(Task))

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) SetPriority added in v0.0.2

func (s *TaskStore) SetPriority(ctx context.Context, taskID string, priority int) error

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

func (s *TaskStore) SetSeq(ctx context.Context, taskID string, seq int64) error

SetSeq sets the manual (drag) ordering value. 0 clears it back to pure priority/FIFO placement.

func (*TaskStore) SetSessionID added in v0.0.2

func (s *TaskStore) SetSessionID(ctx context.Context, taskID, sessionID string) error

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) SetWaitingContext

func (s *TaskStore) SetWaitingContext(ctx context.Context, taskID, owner string) error

SetWaitingContext moves dispatched -> waiting_context.

func (*TaskStore) VerifyTaskEventChain

func (s *TaskStore) VerifyTaskEventChain(ctx context.Context, taskID string) error

VerifyTaskEventChain verifies the per-task hash chain for taskID. It returns nil if the chain is intact, or an error describing the first break.

Jump to

Keyboard shortcuts

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