core

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: MIT Imports: 41 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"

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

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.

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

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

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

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 Deletable added in v0.0.8

func Deletable(s string) bool

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

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 FilterSensitiveData added in v0.0.8

func FilterSensitiveData(s string) string

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

func HasSensitiveData(s string) bool

HasSensitiveData reports whether s contains anything credential-shaped.

func IsTaskState added in v0.0.8

func IsTaskState(s string) bool

IsTaskState reports whether s names a task state.

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

func Terminal

func Terminal(s string) bool

Terminal reports whether s has no valid outgoing transition.

Types

type AmbiguousTaskIDError added in v0.0.8

type AmbiguousTaskIDError struct {
	Ref        string
	Candidates []string
}

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

func (c *Core) AdvancePlan(ctx context.Context, planID string) error

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

func (c *Core) Artifacts() *artifact.Store

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

func (c *Core) CancelTree(ctx context.Context, taskID string) ([]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. 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

func (c *Core) Card() ledger.Card

Card snapshots the current capability card (guarding the swap a reload may be performing concurrently).

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) EvTrace added in v0.0.7

func (c *Core) EvTrace(ctx context.Context, taskID, typ string, data map[string]any)

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) 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) 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) ReloadCard added in v0.0.7

func (c *Core) ReloadCard(ctx context.Context, path string) error

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

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) SetAgentMCPPassthrough added in v0.0.7

func (c *Core) SetAgentMCPPassthrough(command string)

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

func (c *Core) SetArtifactStore(s *artifact.Store)

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) 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) SetProjectStores added in v0.0.8

func (c *Core) SetProjectStores(store *projects.Store, projectsRoot string)

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

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) StartPlan added in v0.0.6

func (c *Core) StartPlan(ctx context.Context, p plan.Plan, q QueueSpec) (string, error)

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

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
	Cost          sql.NullFloat64
	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) SetCard added in v0.0.7

func (n *Node) SetCard(card ledger.Card)

SetCard swaps the card a reload just installed, so the next Register or capacity snapshot reflects it. The daemon serializes reloads; this method is only the node-local half of Core.ReloadCard.

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

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

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

Task is the persisted task row (Phase 0 subset of the schema).

func (Task) GetUserLocale added in v0.0.8

func (t Task) GetUserLocale() i18n.Locale

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
}

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

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) AddOnEvent added in v0.0.8

func (s *TaskStore) AddOnEvent(fn func(taskID, typ string, data any)) func()

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

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

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

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

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

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

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) ClearQueue added in v0.0.8

func (s *TaskStore) ClearQueue(ctx context.Context) (cancelled, deleted int, err error)

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) 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) Delete added in v0.0.8

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

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

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) PauseWithDisposition added in v0.0.8

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

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) PendingPlans added in v0.0.6

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

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

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

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

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

Queue transitions submitted -> queued.

func (*TaskStore) QueuedDelegatedRemotely added in v0.0.7

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

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

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

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) RenameProject added in v0.0.8

func (s *TaskStore) RenameProject(ctx context.Context, oldName, newName string) (int64, error)

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

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) ResolveTaskID added in v0.0.8

func (s *TaskStore) ResolveTaskID(ctx context.Context, ref string) (string, error)

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

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) RetargetDelegation added in v0.0.5

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

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

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

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

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, 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 (s *TaskStore) ReviewWithDisposition(ctx context.Context, taskID, owner, reason string, disposition ApprovalDisposition) error

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) SetOnEvent added in v0.0.7

func (s *TaskStore) SetOnEvent(fn func(taskID, typ string, data any))

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

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) SetOutputArtifact added in v0.0.6

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

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

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

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

SetWaitingContext moves dispatched -> waiting_context.

func (*TaskStore) SetWorkDir added in v0.0.8

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

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