core

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: AGPL-3.0 Imports: 69 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 (
	MsgGradeStatus      = "status"
	MsgGradeReport      = "report"
	MsgGradeArtifactRef = "artifact_ref"
	// MsgGradeSteer marks a user inject (steer.go): the note is delivered by
	// the round loop as the next round's leading directive, not folded as a
	// board line — the drain skips it so the text never lands twice.
	MsgGradeSteer = "steer"
)

Message grades are the payload-size contract a sender picks from — the board's analogue of choosing a compression level: a status line is cheap and always lands, a report is a structured summary, an artifact_ref is a pointer the consumer pulls through the data plane only if it needs the tree behind it.

View Source
const (
	PairStateReady     = "ready"     // keys exchanged, SAS displayed, waiting for the human
	PairStateConfirmed = "confirmed" // operator confirmed the code — daemon may send the secret
	PairStateDone      = "done"      // secret delivered; session complete
	PairStateRejected  = "rejected"  // operator said no
	PairStateExpired   = "expired"   // confirm window elapsed / conn died
)

Pair session row states (pair_sessions.state).

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"
	// EvAgentSwitch records the same swap the moment it happens inside
	// execAgent — exec_agent_start names the plan's primary, and without a
	// live correction the task card attributes a long fallback run to an
	// agent that never launched.
	EvAgentSwitch = "agent_switch"
	// 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"

	// EvTrustPolicy records the trust-zone accept policy's verdict for an
	// inbound delegate: the tier judged, the policy_llm setting, and the
	// classifier's answer when one ran. Shadow mode exists so the operator can
	// diff model verdicts against rule outcomes before enforcing them.
	EvTrustPolicy = "trust_policy"

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

	// EvRouteFallback records that routing chose a peer but the task ran
	// locally anyway — the link to the intended executor failed at send
	// time. Without this event the timeline only shows the corrective
	// retarget to self, and "meant for the Mac, ran here" is invisible.
	EvRouteFallback = "route_fallback"

	// EvContractSet records the acceptance contract a task will be judged
	// against. It is written once before execution so the timeline can answer
	// "what did this run promise?" even after the spec is amended.
	EvContractSet = "contract_set"
	// EvCheckResult records one acceptance check's outcome, per phase. The
	// baseline phase runs before the agent touches the tree; the final phase
	// runs after it claims done. The pair is what separates "was already
	// broken" from "this run broke it".
	EvCheckResult = "check_result"
	// EvVerdict records the contract's combined judgment (verified / failed /
	// partial) and the checks that drove it.
	EvVerdict = "verdict"
)

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 (
	ExpiryFailed   = "failed"   // terminal verdict recorded on the row
	ExpiryRerouted = "rerouted" // re-queued under a fresh attempt
	ExpirySkipped  = "skipped"  // a concurrent transition settled it first
)

Expiry outcomes reported by SettleExpired.

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 → action=compact_retry re-runs on a shrunken prompt + fresh session; action=parked means even that could not fit → review
	EvSubagentEvent    = "subagent_event"     // agent spawned a sub-agent (Claude Task tool) → note
	// EvAgentEvent records one structured activity block the adapter
	// streamed back ({"type":"event"} NDJSON): assistant text, thinking,
	// tool_use/tool_result pairs, and sub-agent blocks carrying the parent
	// tool_use id — the transcript the display layer nests into the
	// delegation tree. Payload keys mirror commander.AgentEvent:
	// ev/id/parent/name/tool_use_id/text/thinking/content/input/is_error.
	EvAgentEvent = "agent_event"
	// EvClarification records an agent parking the task on a PANDA_QUESTION
	// marker (§4.3): the question and the round it surfaced in.
	EvClarification = "clarification"
	// EvUserMsg records a user message delivered into a task (steer.go) —
	// mode=queue (next-round context) or mode=inject (leads the next round,
	// interrupting the in-flight one when live).
	EvUserMsg = "user_msg"
	// EvUserMsgConsumed records the other half of that delivery: the round that
	// actually folded the note into its prompt. Without it the trace says a
	// message was posted and nothing says whether the model ever saw it — the
	// gap a "queued forever" console cannot distinguish from "queued, read next
	// round".
	EvUserMsgConsumed = "user_msg_consumed"
)

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")
	// ErrAlreadyRunning reports that run() found the task already executing
	// under another goroutine (a duplicated resume/context_ack raced in). It
	// wraps ErrCancelled so every caller treats it as a quiet non-error: the
	// first runner owns execution and reports the outcome, and this
	// invocation must neither re-execute nor disturb the live row.
	ErrAlreadyRunning = fmt.Errorf("%w: already running on this node", ErrCancelled)
	// ErrApprovalNeedsChangedInput reports that a reviewed task cannot be
	// approved as-is. Its input, scope, or context must change before a new
	// run. The message doubles as user-facing copy, so it names the action.
	ErrApprovalNeedsChangedInput = errors.New("approval requires changed input — resubmit the task with a corrected prompt instead")
)

State-machine errors. Callers should wrap them with %w to preserve errors.Is checks.

View Source
var ErrAuthRejected = errors.New("peer rejected our hello")

ErrAuthRejected wraps the reason a peer sent in hello_reject: the link itself worked but our credential did not. maintainPeerLoop treats it like any dial failure (exponential backoff, sparse logging) — the distinct error keeps the log line saying "rejected", not "unreachable".

View Source
var ErrHelloBinding = fmt.Errorf("%w: binding", ErrAuthRejected)

ErrHelloBinding is the reject reason "binding": the peer has verified a bound hello from us before and now refuses the unbound form. That is not a secret mismatch — the remedy is to run a build that binds, or to clear the peer (`nodes remove`, re-pair) if it was deliberately rolled back. It wraps ErrAuthRejected so the backoff and custody behavior stay identical.

View Source
var ErrJoinCodeMismatch = errors.New("join: pairing code mismatch")

ErrJoinCodeMismatch marks a derived pairing code that does not match the URI's c= value. This is the MITM detection firing: the DH exchange completed but the far end is not the party whose code the operator was given, so no secret may move.

View Source
var ErrJoinWrongIntroducer = errors.New("join: contact point is not the pinned introducer")

ErrJoinWrongIntroducer marks a contact point that answered with an identity other than the one the URI pinned. It is not necessarily an attack — any member may be listed as a contact point — so the caller may try the next bootstrap; only a code mismatch is a stop.

View Source
var ErrSelfMergeDisabled = fmt.Errorf("self_evolution is not enabled on this node")

ErrSelfMergeDisabled is the fail-closed answer when a merge action reaches a node that never opted into self-evolution.

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 AnswerPairSession added in v0.0.11

func AnswerPairSession(db *sql.DB, idPrefix, state string) error

AnswerPairSession flips a ready session to confirmed or rejected — the responder CLI's side of the human decision. ID may be a unique prefix so the operator can answer with the displayed short id.

func BoardScopes added in v0.0.11

func BoardScopes(t Task) []string

BoardScopes lists the boards a task drains at round boundaries: its own scope plus the board of the child set it spawns (a parent reads its children's task:<self> board without being a sibling of it). Exported for the `panda task board` inspector.

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 CleartextDialError added in v0.0.10

func CleartextDialError(addr string, allowCleartext bool, allowFor []string) error

CleartextDialError surfaces the dial-time gate to code paths that only *record* a peer address (nodes add/admit, pair): they can warn at write time instead of letting the refusal surface days later inside keepalive logs. Non-nil means the daemon would refuse to dial addr under the given cleartext settings; the error text already names the escape hatches.

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 LoadNodeKey added in v0.0.10

func LoadNodeKey(db *sql.DB) (ed25519.PublicKey, ed25519.PrivateKey, bool)

func NewSignedAudit added in v0.0.11

func NewSignedAudit(db *sql.DB) *security.Audit

LoadNodeKey reads this node's persisted Ed25519 identity from an open store, without generating one (generation is the daemon's job). Callers that only verify — `panda audit verify`, the CLI task store — get !ok on a node that has never run a daemon rather than silently minting a key the mesh never advertised. NewSignedAudit returns an audit recorder bound to this node's Ed25519 signing key when one already exists in settings — entries then land on the hash chain with the node's attestation and cannot be rewritten without breaking `panda audit verify`. Keyless installs record unsigned rows.

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 NodeRowLastSeen added in v0.1.0

func NodeRowLastSeen(ctx context.Context, db *sql.DB, nodeID string) int64

NodeRowLastSeen reads the directory row's heartbeat stamp — 0 when the row is absent. Snapshot it BEFORE the engine's own Register: that upsert always rewrites last_seen, so a post-register read cannot tell our write from a real owner's heartbeat without the pre-register value to compare against.

func NormalizeDialAddr added in v0.0.11

func NormalizeDialAddr(addr string) string

NormalizeDialAddr canonicalizes a configured peer address for the addr→node_id binding (peer_addrs): scheme and trailing slash off, so the config's "ws://host:7836/" and a bare "host:7836" compare equal. Shared with `panda status`, whose configured-peer-online count joins the same strings against the same table.

func NoteProse added in v0.1.0

func NoteProse(body string) string

NoteProse returns the user's own words from a note body — everything before the attachment block. The block itself stays in the stored body because the agent reads bodies, never chip lists; surfaces that show the note to its author want the prose back.

func PairCode added in v0.0.11

func PairCode(initX, respX, initPub, respPub, initNonce, respNonce, dh []byte) string

PairCode exposes the initiator-side SAS derivation for the CLI.

func PairDeriveKey added in v0.0.11

func PairDeriveKey(dh, initNonce, respNonce []byte) ([]byte, error)

PairDeriveKey exposes the initiator side of the box key derivation.

func PairOpen added in v0.0.11

func PairOpen(key, box []byte) ([]byte, error)

PairOpen unseals a pair box — exported for the initiator CLI.

func PairSessionState added in v0.0.11

func PairSessionState(db *sql.DB, idPrefix string) (string, error)

PairSessionState reads one session's state — the confirm CLI polls it to show "the daemon finished the join" feedback.

func PanelReachable added in v0.0.11

func PanelReachable(addr string) bool

PanelReachable dials the panel bind address. A wildcard host probes loopback (the listener is local by definition); the fallback range mirrors listenPanel, which slips forward a few ports when the configured one is taken — a console on 7841 is still a live consumer.

func PinnedNode added in v0.0.11

func PinnedNode(t Task) string

PinnedNode exposes the hard pin a task carries (spec.node), for callers outside this package that render or reason about where the task is allowed to run. "" means unpinned — normal scored routing applies.

func QueueConsumerAlive added in v0.0.11

func QueueConsumerAlive(cfg *config.Config) bool

QueueConsumerAlive reports whether some local process can drain this node's task queue: the daemon holds the node identity lock (the same probe `panda status` uses to mark the local row running), and `panda web` (or the standalone sidecar) accepts TCP connections on the panel address.

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 SelfMergeSpec added in v0.1.0

func SelfMergeSpec(specJSON string) (selfMergeSpec, bool)

SelfMergeSpec decodes a task row's merge envelope; ok=false on any row that is not a self-merge proposal.

func StoreConsumerFresh added in v0.1.0

func StoreConsumerFresh(ctx context.Context, db *sql.DB, nodeID string, lastForeign, selfWriteAt int64) bool

StoreConsumerFresh reports whether an owner heartbeats nodeID's row in db. QueueConsumerAlive answers "is a consumer process running on this machine" — the identity lock and the panel port cannot see which database that process actually drains. This probe is store-bound: a daemon that holds the lock but opened a different db_path never refreshes this store's row, so enqueues here would dead-letter even though the process check reports a consumer alive.

lastForeign/selfWriteAt separate the caller's own Register writes from a real consumer's beats: selfWriteAt is the unix time of our most recent register (0 if the engine never wrote); lastForeign is the newest last_seen observed strictly above it — i.e. a stamp nobody in this process wrote. Alive means the row moved past our write, or the last foreign stamp is still inside the heartbeat window. Our own stamp alone proves nothing, and a re-register must not let it age into "fresh foreign evidence".

func StoreRowHeartbeating added in v0.1.0

func StoreRowHeartbeating(ctx context.Context, db *sql.DB, nodeID string) bool

StoreRowHeartbeating reports whether nodeID's row in db carries a live heartbeat — the plain-freshness half of StoreConsumerFresh for callers that never wrote the row themselves (e.g. a scheduler-less panel checking whether ANY consumer beats the store it serves). The writer case needs StoreConsumerFresh's lastForeign/selfWriteAt split instead.

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.

func WithTaskObserver added in v0.1.0

func WithTaskObserver(ctx context.Context, fn func(Task)) context.Context

WithTaskObserver installs fn to be called once for every task row created under ctx — the only point at which a caller learns the id of a task that is about to run synchronously. A surface needs it before execution starts: by the time Submit returns, the work is over and there is nothing left to steer.

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"
	// ApprovalAdmissionReview marks a task parked before any work by THIS
	// node's inbound admission gate (trust-zone accept review). It resumes
	// on a local approve like resume_execution, but unlike it a wire
	// task_resume may never un-park it: the gate belongs to this node's
	// operator, and the delegator — who is also the suspect the gate exists
	// for — must not talk the executor out of its own review.
	ApprovalAdmissionReview ApprovalDisposition = "admission_review"
	// ApprovalSelfMerge marks a review row carrying a self-evolution patch-set
	// merge proposal (design §4.2). Approving it runs the merge pipeline —
	// worktree apply, gate, build, StageLocal, Apply — never agent execution,
	// so it deliberately does NOT appear in resumesOnApprove: the queue
	// scheduler must never pick the row up as ordinary work, and a bare
	// store.Approve (no pipeline in the process) is refused outright.
	ApprovalSelfMerge ApprovalDisposition = "self_merge"
)

type Beacon added in v0.0.10

type Beacon struct {
	Panda string `json:"panda"` // beaconMagic
	ID    string `json:"id"`
	Addr  string `json:"addr"` // WS listen addr as configured (host may be empty)
	Ver   string `json:"ver"`
	Pub   string `json:"pub"`           // Ed25519 pub hex — display hint, not auth
	TS    int64  `json:"ts,omitempty"`  // announce time; bound into Sig
	Sig   string `json:"sig,omitempty"` // Ed25519 over id:addr:ver:pub:ts
}

Beacon is the discovery datagram's payload. Every field is self-asserted: Pub exists so the pending list can show a fingerprint the operator can compare BEFORE pairing, not so the receiver can trust it. Sig, when present, is the broadcaster's Ed25519 signature over the asserted fields — it makes the fingerprint unfakeable without claiming membership (the signing key is self-asserted too: anyone can mint one, nobody can mint someone else's). TS is signed display metadata, not a freshness gate — nodes without reliable clocks must not lose discovery over it.

type CheckRow added in v0.1.2

type CheckRow struct {
	Phase      string `json:"phase"`
	CheckID    string `json:"check_id"`
	Kind       string `json:"kind"`
	Command    string `json:"command,omitempty"`
	Status     string `json:"status"`
	ExitCode   int    `json:"exit_code"`
	DurationMS int64  `json:"duration_ms"`
	OutputHead string `json:"output_head,omitempty"`
	OutputTail string `json:"output_tail,omitempty"`
	Reason     string `json:"reason,omitempty"`
	CreatedAt  int64  `json:"created_at"`
}

CheckRow is one persisted acceptance check result: the evidence behind a verification verdict, readable by `panda task verdict` and the panel long after the run.

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) ApplyNetworkConfig added in v0.0.11

func (c *Core) ApplyNetworkConfig(ctx context.Context, n config.NetworkConfig)

ApplyNetworkConfig hot-applies the mutable half of network.* — the daemon's SIGHUP path and the engine's config-mutation path share it, so a `nodes add`, `pair`, or secret/cleartext edit lands on the running mesh without a restart. Secrets and cleartext policy land first: a peer loop spawned by SyncPeers right after reads them at dial time, and a live conn's framed cipher state is per-connection — it does not re-run the hello. ListenAddr and the discovery binding stay boot-time decisions: re-binding a socket hot is a restart-shaped operation.

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) ContinueReviewed added in v0.1.0

func (c *Core) ContinueReviewed(ctx context.Context, taskID, note string) (Task, error)

ContinueReviewed requeues a task whose round budget ran out mid-work: the supervisor parked it in review with needs_followup, and the operator's answer is neither "accept the half" (approve) nor "throw it away" (reject) but "keep going". The continuation is expressed as a requeue — the same review→queued+scheduled=1 transition an approved resume records — so the store's scheduler adopts it and the call returns immediately instead of blocking on another full execution budget. That is also what makes the action cross-process: a CLI or console marks the row, the queue-owning daemon does the running.

The operator's note lands as a steer-grade board note BEFORE the requeue, so the scheduler's first continued round sees it lead the intent even when the claim lands in the same tick. With no note the steer carries a plain "keep going" directive — the resumed agent session supplies the rest of the context.

Scope is deliberately local: a task whose last dispatch went to a peer is refused rather than silently re-routed — the remote continue deserves the task_resume wire path a follow-up change can add, not a quiet re-execution on the wrong machine.

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.

The ctx bounds the DIAL, not the connection. A caller that wants a short dial budget (the reachability ladder) must not hand that budget to the read loop: cancelling it the moment the dial returns would close the connection before the peer's hello reply was ever read, and the edge would die on arrival. See dialPeerWithLife.

func (*Core) DispatchChild added in v0.0.9

func (c *Core) DispatchChild(ctx context.Context, child Task, in TaskInput) error

DispatchChild routes a spawned child the way Submit routes a root task (§4.2): the best-scored capable peer wins, with this node as an ordinary candidate. A forwarded child is a normal delegation — its result returns here via handleResult, where it both completes the local copy and unblocks whatever spawned it. A local/declined child lands on the queue scheduler, which runs it here (or re-routes via forwardScheduled on the next pass).

func (*Core) Enqueue added in v0.0.2

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) EnsureNodeKey added in v0.0.10

func (c *Core) EnsureNodeKey()

EnsureNodeKey materializes the identity keypair eagerly — daemon startup calls it so a node that has never dialed anyone still carries its own fingerprint in the directory. Without it, `panda nodes` would show "—" on the self row of a peerless node, which is exactly the row the operator compares a discovery fingerprint against.

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) EvaluateLinkState added in v0.0.9

func (c *Core) EvaluateLinkState(ctx context.Context, targetNode string) LinkState

EvaluateLinkState calculates the link state towards targetNode based on live connection status and heartbeat exponential freshness discount (whitepaper §8.1).

func (*Core) FetchArtifact added in v0.0.6

func (c *Core) FetchArtifact(ctx context.Context, source, taskID, hash string) (artifact.Manifest, error)

FetchArtifact pulls the artifact named by hash from source into this node's pool and returns its manifest. An artifact the node already holds is returned without any bytes on the wire — the hash is proof enough, which is what makes re-delegating a stage to a node that ran an earlier one nearly free.

The thin wrapper exists so every exit path — the local-hit fast return, every abort inside the transfer loop, and success — lands one artifact_transfer trace event without sprinkling emissions through the loop.

func (*Core) FetchArtifactRef added in v0.0.9

func (c *Core) FetchArtifactRef(ctx context.Context, source, taskID string, ref bus.ArtifactRef) (artifact.Manifest, error)

FetchArtifactRef is FetchArtifact with the full input reference: a ref that carries the orchestrator's OfTask/Grant/Issuer asks the producer to serve on the strength of the signed grant rather than on the consumer's own task row — the difference that makes direct stage-to-stage handoff possible when the producer never saw the consumer's task.

func (*Core) HasPendingCustody added in v0.0.11

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

HasPendingCustody reports whether any outbox holds undelivered rows — a parked task, result, cancel or approval waiting on a peer's next contact. The daemon's redial loops use it to tighten their cadence: with custody in hand, probing the contact opportunity is the priority, and the usual steady-state backoff would leave a parked task waiting out half-minute retry gaps on a link that is ready to carry it.

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) ImportFatBundleArtifacts added in v0.0.9

func (c *Core) ImportFatBundleArtifacts(ctx context.Context, artifacts []bus.FatBundleArtifact) ([]artifact.Manifest, error)

ImportFatBundleArtifacts imports an array of proactive bundled artifacts directly into the node's local artifact pool, verifying SHA256 integrity and eliminating round-trip pulls (whitepaper §8.3).

func (*Core) InjectUserMessage added in v0.1.0

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

InjectUserMessage posts the steer note AND aborts the running agent round when one is live. Returns "interrupted" when a running turn was aborted, "queued" when the steer waits for the next round boundary (or the task's first run — the note is durable either way).

func (*Core) InjectUserNote added in v0.1.0

func (c *Core) InjectUserNote(ctx context.Context, taskID, text string, attachments []string) (TaskMessage, string, error)

InjectUserNote is InjectUserMessage carrying files. The slot is returned so a surface can keep addressing the note it just sent.

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) ListenAddr added in v0.1.1

func (c *Core) ListenAddr() string

ListenAddr reports the address this node's WebSocket listener is bound to, or the configured address before the bind has happened. It is what the capability summary and discovery beacons advertise.

func (*Core) ListenUDP added in v0.0.9

func (c *Core) ListenUDP(ctx context.Context, addr string, stunServers []string) error

ListenUDP starts the datagram plane on addr. The shared secret is required — it derives both the AEAD key and the punch signer, and an unkeyed UDP socket would accept nothing anyway. The listener and its keepalive loop stop with ctx.

func (*Core) MaintainPeer

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) MeshMetrics added in v0.1.0

func (c *Core) MeshMetrics() MeshMetrics

MeshMetrics returns a consistent-enough read of the counters. Each field is read atomically on its own; a snapshot taken mid-flight may see one counter a few microseconds ahead of another, which is exactly what monotonic counters are for.

func (*Core) Negotiate added in v0.0.9

func (c *Core) Negotiate(ctx context.Context, target string, p bus.AgentNegotiatePayload) (bus.AgentGrantPayload, error)

Negotiate sends one scope request to a peer and waits synchronously for its grant/deny verdict — the caller-side half of §5.1 that turns the wire messages into an arbitration primitive.

func (*Core) NodeID added in v0.1.0

func (c *Core) NodeID() string

NodeID returns this core's stable node identity — the employee_cache row its heartbeat (when it owns the row) and queue claims are keyed on.

func (*Core) OwnsNodeRow added in v0.0.11

func (c *Core) OwnsNodeRow() bool

OwnsNodeRow reports the same: false marks a borrowed engine whose daemon holds the identity lock — such a core must never write liveness or run a second work consumer for the identity.

func (*Core) PromoteUserNote added in v0.1.0

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

PromoteUserNote turns an already-queued note into an inject without posting a second row: the same slot is re-written with the steer grade, so the next round carries the user's words exactly once, as a directive instead of context. Returns "interrupted" when a live round was aborted here, "queued" when the steer waits for the round boundary.

This is the second-Enter escalation: a surface that queued a note on the first Enter must not send a duplicate on the second.

func (*Core) ProposeSelfMerge added in v0.1.0

func (c *Core) ProposeSelfMerge(ctx context.Context, patchSetID string) (Task, error)

ProposeSelfMerge turns a queued patch set into a review-gated merge task (design §4.2): a human approve runs the pipeline, a reject archives the set. The proposal carries the manifest's recomputed critical flag so the review UI can highlight what the patch touches.

func (*Core) PunchPeer added in v0.0.9

func (c *Core) PunchPeer(ctx context.Context, peerID string) error

PunchPeer initiates a pinhole toward peerID: it sends a punch_offer envelope through the mesh (directly if a conn exists, relayed along the link-state graph otherwise) and sprays signed punch frames at every candidate it already knows for the peer. The ready reply starts the peer spraying back; the first verified datagram from either direction binds the route. Safe to call while a WS conn exists — the datagram route simply becomes an additional path and sendTo keeps preferring the conn.

func (*Core) QueueUserMessage added in v0.1.0

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

QueueUserMessage posts a durable advisory note to the task's own board scope. The next round (or the first, for a task that has not started) folds it into the agent's intent; a finished task refuses.

func (*Core) QueueUserNote added in v0.1.0

func (c *Core) QueueUserNote(ctx context.Context, taskID, text string, attachments []string) (TaskMessage, error)

QueueUserNote is QueueUserMessage carrying files, returning the slot it landed so the caller can edit or promote that exact note afterwards.

func (*Core) Recover

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

Recover normalizes tasks left active by a previous process instance, then re-arms the upstream hold on any remote-origin row still parked in review — the keepalive is in-memory and does not survive the restart that left those rows.

func (*Core) Register

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

Register upserts this node in the local ledger.

func (*Core) RejectTree added in v0.0.11

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

RejectTree is the local-entry reject: fail the reviewed row, then notify the downstream executor holding the delegated review copy. Reject without the forward left the executor's copy parked in review — a local approve on that copy would run work the origin explicitly denied. The kill rides the same task_cancel/cancel_outbox path as CancelTree: the executor's handleCancel cascades it out of review, and an unreachable executor gets it parked for its next hello.

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) RendezvousDegraded added in v0.1.0

func (c *Core) RendezvousDegraded() bool

RendezvousDegraded reports whether zero rendezvous candidates exist — the honest "mesh is the connected component" signal for doctor and status.

func (*Core) RendezvousPeers added in v0.1.0

func (c *Core) RendezvousPeers() []string

RendezvousPeers reports the currently elected rendezvous set (status/ doctor surfaces).

func (*Core) ReputationEnabled added in v0.0.11

func (c *Core) ReputationEnabled() bool

ReputationEnabled reports whether routing scores include the local delegation-metrics term.

func (*Core) ResumeApproved added in v0.0.7

func (c *Core) ResumeApproved(ctx context.Context, taskID string, answers ...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) RunDiscovery added in v0.0.10

func (c *Core) RunDiscovery(ctx context.Context, bindAddr, advertiseAddr string, autoDial bool)

RunDiscovery owns the LAN-discovery socket: one ListenUDP serves both the beacon announcer (a ticker WriteToUDP to the subnet broadcast) and the listener feeding pending_nodes. bindAddr supplies only the port — the socket binds the wildcard address regardless, because a socket bound to a single interface address cannot hear broadcasts aimed at the others. advertiseAddr is this node's WS listen address as configured — receivers substitute the source IP when its host is not routable. autoDial enables the zero-config half of discovery: src-pinned beacons get an outbound DialPeer so same-secret nodes connect without `nodes admit` — the hello's shared secret remains the only admission proof. Runs until ctx ends; socket or broadcast failure degrades to warn-and-idle, never daemon death — discovery is convenience, not substrate. IPv4 only: broadcast is an IPv4 concept (v6 multicast discovery is a later track).

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 runs the full monitor tick — the task-lifecycle sweeps plus the peer-directory duties that only make sense on the node owning the peer connections. It returns when ctx is done.

func (*Core) RunReconcile added in v0.0.9

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

RunReconcile runs only the local-work reconcile — the minimal monitor for surfaces that submit inline (REPL, TUI, one-shot ask): they never own the queue, but a task they execute can still be cancelled or force-failed by another process, and this pass is what stops the orphaned execution instead of letting it run to the agent hard timeout.

func (*Core) RunTaskMonitor added in v0.0.9

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

RunTaskMonitor runs the task-lifecycle half of the monitor for an embedded surface — the web panel, `panda web`, any long-lived process that executes tasks off the shared store without owning the peer connections. Without it that process's tasks stall silently: a parked waiting_context never times out, a queued-remotely orphan is never rescued, an expired lease is never enforced, and the store alone cannot tell queued work why nothing moved. The peer-directory sweeps stay daemon-only: a second process marking peers offline from a connection set it does not own would fight the real node's heartbeats.

func (*Core) SelfManager added in v0.1.0

func (c *Core) SelfManager() *self.Manager

SelfManager exposes the wired manager for read surfaces (status, queue).

func (*Core) SelfRebaseSweep added in v0.1.0

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

SelfRebaseSweep carries queued patch sets onto the repo's current HEAD after an official update moved the base out from under them (design §7 q3, phase 4 coexistence). Each stale set is rebased and re-signed with THIS node's key — the node doing the rebase is the one whose operator will review it — while a conflict marks the set conflicted and leaves it for the operator (or the producing task) to regenerate. Runs on the daemon at startup; a no-op when nothing is queued or every base is already current.

func (*Core) SendNegotiation added in v0.0.9

func (c *Core) SendNegotiation(ctx context.Context, target string, p bus.AgentNegotiatePayload) error

SendNegotiation sends a horizontal conflict negotiation signal to target peer (whitepaper §5.1).

func (*Core) SetAcceptanceConfig added in v0.1.2

func (c *Core) SetAcceptanceConfig(a config.AcceptanceConfig)

SetAcceptanceConfig applies execution.acceptance: the per-check and per-phase budgets for the delivery-contract checks this node runs.

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) SetAllowCleartext added in v0.0.10

func (c *Core) SetAllowCleartext(allow bool)

SetAllowCleartext lifts the outbound plaintext gate (network.allow_cleartext). See cleartextOK for what it opts back into.

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) SetCleartextAllowlist added in v0.0.11

func (c *Core) SetCleartextAllowlist(entries []string)

SetCleartextAllowlist scopes plaintext dialing to extra hosts/nets (network.allow_cleartext_for). Entries are CIDRs, literal IPs, or exact hostnames — validated at config load, stored verbatim here.

func (*Core) SetContacts added in v0.0.9

func (c *Core) SetContacts(contacts []ledger.Contact)

SetContacts installs this node's advertised contact plan (§8.4). Call it after NewCore, before the serving goroutines start — the slice is read unsynchronized afterward. The plan gossips out in every heartbeat and lands in the local directory row via refreshSelfNeighbors.

func (*Core) SetDelegationLimits added in v0.1.0

func (c *Core) SetDelegationLimits(d config.DelegationConfig)

SetDelegationLimits applies the configured sub-agent bounds (the delegation: section). Call after NewCore, before serving starts — the fields are read unsynchronized afterward, like the other config installs.

func (*Core) SetEdgeAuthority added in v0.0.11

func (c *Core) SetEdgeAuthority(v bool)

SetEdgeAuthority marks whether this process holds the node identity lock for its lifetime (the daemon entry point does; engines only probe-and- release it at init, so they must leave this false). The claim rides every hello and lets a same-id arbitration prefer the lock-holding process when a stray sibling holds a peer edge hostage.

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) SetMessageBudget added in v0.0.11

func (c *Core) SetMessageBudget(n int)

SetMessageBudget bounds sibling-board posts per task episode (§inter-task messages). A value <= 0 resets to defaultMsgBudget.

func (*Core) SetNetworkPolicy added in v0.1.0

func (c *Core) SetNetworkPolicy(n config.NetworkConfig)

SetNetworkPolicy installs the resolved cross-network policy. Called from the boot path and from ApplyNetworkConfig on a hot reload; it is a single swap so a reader never sees half of one policy and half of another.

func (*Core) SetOwnsNodeRow added in v0.0.11

func (c *Core) SetOwnsNodeRow(owns bool)

SetOwnsNodeRow declares whether this process owns the node's directory row. Call it after NewCore, before serving starts. See the field comment.

func (*Core) SetPackProtectedPaths added in v0.1.0

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

SetPackProtectedPaths records the node's own never-ship files — the config (mesh secret, API keys) and the capability card — so artifact packs prune them wherever a tree happens to contain them, and extracts refuse to let an incoming tree overwrite them. Kept separate from hostStatePaths because the drift detector must still flag a task that rewrites the live config.

func (*Core) SetPairJoinHook added in v0.0.11

func (c *Core) SetPairJoinHook(h PairJoinHook)

SetPairJoinHook installs the responder-side "write the join into config" callback (see PairJoinHook).

func (*Core) SetPeerTrustHints added in v0.0.11

func (c *Core) SetPeerTrustHints(hints map[string]string)

SetPeerTrustHints installs the configured addr→tier map (network.peers entries carrying a trust: field). Keys are normalized dial addresses so a configured "ws://host:7836/" and the recorded "host:7836" binding compare equal.

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) SetReputationEnabled added in v0.0.11

func (c *Core) SetReputationEnabled(on bool)

SetReputationEnabled toggles the local track-record term in routing scores (routing.reputation). Default off: scoring is a mainline behavior, so the term only enters when the operator opts in.

func (*Core) SetRetentionDays added in v0.0.11

func (c *Core) SetRetentionDays(days int)

SetRetentionDays installs the settled-task age limit (config storage.task_retention_days). Zero disables the sweep — the task table then grows without bound, which is the pre-knob behaviour an operator can still choose explicitly.

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) SetScratchRoot added in v0.1.0

func (c *Core) SetScratchRoot(root string)

SetScratchRoot pins where the node's runtime scratch lives — workDir/tasks, workDir/plans and workDir/projects all derive from it. The empty-string default keeps scratch directly under workDir, which is right when workDir IS the node's data dir (the default layout, where these dirs sit beside openpanda.db). A workDir that is a user-facing workspace — an adopted launch directory or an explicit storage.work_path pointing at a checkout — should pass workDir/.openpanda so panda-owned scratch hides in one git-ignorable directory instead of three visible ones.

The root is host state — scratch churn (a stage unpacking inputs, a peer's project tree landing) is the node's own bookkeeping, not agent scope drift, and must never ride out inside an artifact pack. hostState() unions it in at read time so wiring order can never drop it.

func (*Core) SetSelfConfigPath added in v0.0.9

func (c *Core) SetSelfConfigPath(path string)

SetSelfConfigPath forwards the daemon's --config path to the router so the .mcp.json it materializes can pass it to `panda mcp`. Remembered like the passthrough so a ReloadCard rebuild re-applies it.

func (*Core) SetSelfEvolution added in v0.1.0

func (c *Core) SetSelfEvolution(mgr *self.Manager, oneShot bool, producers string)

SetSelfEvolution wires the self-evolution manager into the core. oneShot says the process is a CLI helper (panda approve), not the daemon — the merge's binary Apply then skips the in-process re-exec, leaving the service restart to install.RestartDaemon. producers is the config's self_evolution.producers: "self" (default) admits only sets signed by this node's own key, "mesh" admits any signer (reserved for phase 5).

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. Hot-reloadable: readers take netMu via sharedSecretValue, so a settings save is safe against in-flight hellos, discovery and DTN traffic.

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) SetTrustConfig added in v0.0.11

func (c *Core) SetTrustConfig(cfg config.TrustConfig)

SetTrustConfig installs the operator's per-tier policy tables (network.trust.*). An empty config is valid and means "every tier at its built-in defaults".

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) SpawnChildTask added in v0.0.9

func (c *Core) SpawnChildTask(ctx context.Context, parentID string, in TaskInput) (Task, error)

SpawnChildTask creates a child task under parentID, implementing the Sub-MainAgent recursive delegation model (whitepaper §4.2). The executing node promotes itself to Sub-MainAgent, spawning child causal tasks with bounded depth.

The child inherits the parent's causal chain verbatim — the chain records the delegation path, and its tail is already this node (the Sub-MainAgent that received the parent). Appending self again would forge an immediate self-loop; resetting it would launder the mesh-wide loop history. The next hop is appended by whoever forwards the child, and the parent's remaining mesh budget carries over (§6.1): the budget is spent at dispatchDelegated, not here, so a locally-run child costs nothing.

func (*Core) StartPlan added in v0.0.6

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) SyncPeers added in v0.0.11

func (c *Core) SyncPeers(ctx context.Context, addrs []string)

SyncPeers reconciles the running peer-keepalive set with the wanted list: new addresses get a keepalive loop, removed ones are cancelled and their live conns closed, untouched ones keep running. Safe to call at boot and on every config reload. ctx is the process lifetime — the loops die with it.

func (*Core) TaskStore

func (c *Core) TaskStore() *TaskStore

TaskStore exposes the store for CLI/queue views.

func (*Core) UDPPort added in v0.0.9

func (c *Core) UDPPort() int

UDPPort reports the bound datagram port (0 when the plane is off); the hello advertises it so peers know where to punch.

func (*Core) UDPRoute added in v0.0.9

func (c *Core) UDPRoute(peer string) *net.UDPAddr

UDPRoute returns the confirmed datagram endpoint for peer, or nil — the punch-maintain loop uses it to decide whether another offer is due.

func (*Core) WaitArtifacts added in v0.1.0

func (c *Core) WaitArtifacts()

WaitArtifacts blocks until every detached artifact adoption has finished writing. Transfers carry their own budget (artifactTransferBudget), so the wait is bounded: a wedged fetch fails its own deadline and drops out of the group rather than pinning the caller.

func (*Core) WaitQueue added in v0.1.0

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

WaitQueue blocks until the queue scheduler's in-flight runners have returned, bounded by ctx. Cancelling the scheduler's context stops its dispatch loop but does NOT interrupt a runner already inside Run — and a runner that finishes after the owner closed the store writes into a closed database. Shutdown paths call this before closing.

type DeclineRecord added in v0.0.11

type DeclineRecord struct {
	By     string
	Reason string
	Code   string
}

DeclineRecord is one refusal on a task's audit trail: the declining executor and the reason it stated ("capacity full", "node draining"). Code is the machine-readable refusal class (DeclineCodeTrust* and friends) when the wire payload carried one — empty for legacy peers.

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
	// Sig/SigPub are the P2-9 attestation: the Ed25519 signature over this
	// row's chain hash and the public key that produced it (both hex). Empty
	// on rows recorded before event signing or by a store without a key.
	Sig    string
	SigPub string
}

Event is one task_events row.

type ExpiredRow added in v0.1.0

type ExpiredRow struct {
	TaskID string
	State  string
	Owner  string
	// AttemptID is the dispensation whose lease lapsed — the settle-time
	// downstream cancel carries it so a copy already superseded by a newer
	// delegation survives the kill order.
	AttemptID string
	// Deadline marks an absolute-lifetime expiry (§8.2 DTN bound): those
	// settle terminally regardless of retry budget — the bundle outlived
	// its lifetime and re-running cannot extend it.
	Deadline bool
	// Rerouted is the settle outcome: the row re-queued for another run
	// rather than recording a terminal verdict.
	Rerouted bool
}

ExpiredRow is one active row whose lease or absolute deadline has lapsed. The scan returns it without acting so the caller can first release whatever execution resources the row still holds — a local agent subprocess, a parked-context reservation, a downstream executor still burning tokens — before SettleExpired decides the row's fate.

type JoinSpec added in v0.1.0

type JoinSpec struct {
	// Bootstraps are contact addresses, dialable in their bare host:port or
	// ws(s):// form.
	Bootstraps []string
	// Introducer is the expected responder Ed25519 pubkey in hex, "" when
	// the URI pinned none.
	Introducer string
	// Code is the expected SAS digits (dash optional), "" when absent.
	Code string
}

Join URI — the cold-start kernel of the cross-network design (§2). Zero information means zero discovery, and that is physics rather than a defect: a node that has never heard of the mesh needs one address to knock on.

panda://join?b=203.0.113.5:7836&b=node.example.com:7836&c=482913&k=k:<pub>

b  repeatable contact addresses. ANY online member can serve as one —
   there is no privileged bootstrap server, and the list is tried in
   order until one answers.
k  the introducer's stable Ed25519 identity (`k:<hex>` or bare hex).
   Optional but strongly recommended: the joiner refuses to accept a
   secret from a responder whose pair_ready pub does not match, which
   turns a poisoned bootstrap list into "wrong number" instead of
   "joined the attacker's mesh".
c  the expected pairing code (the SAS the introducer's console shows,
   with or without its dash). When present the joiner checks it
   automatically — a mismatch IS the MITM detection, so there is no
   human comparison left to skip.

The scheme accepts both "panda" and "openpanda" (the design's open question §12.4); parsing is deliberately tolerant so a URI outlives a rename.

func ParseJoinURI added in v0.1.0

func ParseJoinURI(raw string) (*JoinSpec, error)

ParseJoinURI parses the join form. It validates addresses the same way the peer list does, so a URI cannot introduce an address `nodes add` would refuse.

func (*JoinSpec) CodeMatches added in v0.1.0

func (s *JoinSpec) CodeMatches(sas string) bool

CodeMatches reports whether a derived pairing code matches the URI's c= value. Unpinned means it matches — the operator then compares by eye.

func (*JoinSpec) IntroducerMatches added in v0.1.0

func (s *JoinSpec) IntroducerMatches(pub string) bool

IntroducerMatches reports whether a responder's identity is the one the URI pinned. Unpinned means every responder matches.

func (*JoinSpec) URI added in v0.1.0

func (s *JoinSpec) URI() string

URI renders the spec back to the wire form — the other half of `panda nodes invite --uri`, so what one node prints is exactly what the other parses.

func (*JoinSpec) VerifyPeer added in v0.1.0

func (s *JoinSpec) VerifyPeer(pub, sas string) error

VerifyPeer runs both pins in one call: pub is the responder's Ed25519 identity (hex) from pair_ready, sas the derived pairing code.

type LinkState added in v0.0.9

type LinkState string

LinkState represents the 3-state link classification (whitepaper §8.1): Live, Opportunistic, or Offline.

const (
	LinkLive          LinkState = "live"
	LinkOpportunistic LinkState = "opportunistic"
	LinkOffline       LinkState = "offline"
)

type MeshMetrics added in v0.1.0

type MeshMetrics struct {
	TransitBytesTx int64 `json:"transit_bytes_tx"`
	TransitBytesRx int64 `json:"transit_bytes_rx"`
	TransitRelayed int64 `json:"transit_relayed"`
	TransitRefused int64 `json:"transit_refused"`
	DirRowsIn      int64 `json:"dir_rows_in"`
	DirRowsOut     int64 `json:"dir_rows_out"`
	DirPulls       int64 `json:"dir_pulls"`
	PunchAttempts  int64 `json:"punch_attempts"`
	PunchSuccess   int64 `json:"punch_success"`
	DialCheckOK    int64 `json:"dial_check_ok"`
	DialCheckFail  int64 `json:"dial_check_fail"`
}

MeshMetrics is the exported snapshot (`panda metrics`, the console's mesh page). Names match the design's §8 list where it has one.

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 PairClient added in v0.0.11

type PairClient struct {
	Session string // initiator-minted session id
	Code    string // SAS both screens must show
	// PeerPub is the responder's Ed25519 identity (hex) from pair_ready.
	// A join URI's k= field is checked against it before any secret moves —
	// that check is what makes a bootstrap address a contact point rather
	// than a trusted introducer.
	PeerPub string
	// contains filtered or unexported fields
}

PairClient is the initiator half of the pairing ceremony, shared by `panda pair <target>` and the web console: DialPair performs the key exchange and leaves the session waiting on the responder's human; WaitSecret blocks until the sealed secret arrives or the answer is no.

func DialPair added in v0.0.11

func DialPair(ctx context.Context, dialAddr, selfID, name, listenAddr string, pub ed25519.PublicKey) (*PairClient, error)

DialPair dials dialAddr (bare host:port or ws(s):// URL), sends pair_hello, and reads the responder's pair_ready. pub is this node's Ed25519 identity (an ephemeral one is fine — it only binds the SAS). selfID/name/listenAddr are the display fields the responder's operator sees next to the confirm prompt.

func DialPairTo added in v0.1.0

func DialPairTo(ctx context.Context, dialAddr, target, selfID, name, listenAddr string, pub ed25519.PublicKey) (*PairClient, error)

DialPairTo is DialPair with a forwarding target (P4b): when target is non-empty the contact point is asked to relay the handshake to that stable identity instead of answering it, and the answers come back the same way. The contact point never sees a secret — pair_secret is already boxed to the DH the two pairing ends derived.

func (*PairClient) Close added in v0.0.11

func (c *PairClient) Close()

Close drops the pairing conn — the responder treats it as an abandoned session and expires the row.

func (*PairClient) WaitSecret added in v0.0.11

func (c *PairClient) WaitSecret(ctx context.Context) (string, error)

WaitSecret blocks on the responder's human answer: pair_secret returns the mesh secret in plaintext bytes; pair_reject returns *PairRejected; ctx cancellation or a dropped conn returns the underlying error. The responder's session TTL bounds the wait on its side, so the caller's ctx only needs a margin past it.

type PairJoinHook added in v0.0.11

type PairJoinHook func(peerAddr string) error

PairJoinHook is called by the responder when a pairing completes: it is where "join the network" lands in configuration — persist the peer (and, if this node had no secret yet, the generated one) and hot-apply the change. Implemented by the daemon's config writer; embedded engines may leave it nil, in which case the peer is added in memory only.

type PairRejected added in v0.0.11

type PairRejected struct{ Reason string }

PairRejected reports a pair_reject frame as an error — the typed Reason token ("rejected", "expired", "busy", "already_joined", …) lets callers render the cause without parsing prose.

func (*PairRejected) Error added in v0.0.11

func (e *PairRejected) Error() string

type PairSessionRow added in v0.0.11

type PairSessionRow struct {
	ID        string
	PeerAddr  string
	PeerName  string
	PeerPub   string
	SAS       string
	State     string
	CreatedAt time.Time
	ExpiresAt time.Time
}

PairSessionRow is the operator-facing view of an inbound pairing request.

func ListPairSessions added in v0.0.11

func ListPairSessions(db *sql.DB) ([]PairSessionRow, error)

ListPairSessions reads pair_sessions for `panda pair` — newest first, expired/terminal rows included so the display can say what happened.

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 ProbeResult added in v0.0.11

type ProbeResult struct {
	PeerID    string
	Encrypted bool
}

ProbeResult is what a `nodes add`/`pair` self-check learned from the peer: the id its hello reply announced and whether session encryption armed.

func ProbePeer added in v0.0.11

func ProbePeer(ctx context.Context, nodeID string, card ledger.Card, model config.ModelConfig, n config.NetworkConfig, addr string, pub ed25519.PublicKey, priv ed25519.PrivateKey) (*ProbeResult, error)

ProbePeer runs the real outbound handshake against addr once — WS dial, signed hello, reply verification, session-AEAD negotiation, cleartext policy — on a throwaway core backed by an in-memory store, then closes. It answers "will this peer actually link?" synchronously at admit time instead of leaving the operator to grep keepalive logs. pub/priv are the node's persisted identity (LoadNodeKey on the real store); a nil priv falls back to an unsigned legacy hello — still a valid reachability check. Six seconds is the handshake budget: a peer that answers slower than that is a peer the keepalive would spend its whole first backoff on anyway.

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
	// Authorized carries the submitter's tier-2 consent into the created
	// task. Enqueue callers resolve it through the approval policy (the
	// askengine's verdict gate); plan stages reuse it so a plan submitted
	// under approval.mode "never" grants the same consent an equivalent
	// `task add` would — without it, every remote stage ran restricted and
	// agents without a read-only face refused outright.
	Authorized bool
}

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
	// Verification is the contract verdict: "verified", "failed", "partial",
	// "skipped", or "" when the task carried no acceptance checks. It is a
	// property of the outcome, not a state: a task can be done and unverified
	// (the user forced it) and the two must stay distinguishable.
	Verification string
	ContextType  string
	ContextHash  string
	Complexity   float64
	Risk         string
	ResourceJSON string
	// ApprovalDisposition is persisted whenever the task enters review. Empty is
	// reserved for legacy rows and is classified conservatively from their audit
	// trail; new rows use one of the stable Approval* protocol strings.
	ApprovalDisposition ApprovalDisposition
	// OperationDecisionJSON carries the concrete pre-operation decision/evidence
	// that caused a review. V17 reserves the durable field; the typed arbitration
	// layer populates it when an adapter can report the operation before execution.
	OperationDecisionJSON string
	// Authorized records whether the user consented to executing tier-2
	// (irreversible) commands. It is server-side state (design §16 / P0-1), not
	// wire-carried, so a delegated task cannot forge authorization.
	Authorized bool
	// AuthSig/AuthPub/AuthTs persist the origin node's Ed25519 consent grant
	// alongside the flag, so a relay re-dispatching this task re-emits the
	// signed consent instead of degrading it to the bare flag (P2-8).
	AuthSig string
	AuthPub string
	AuthTs  int64
	// Requires is the capability set the task was routed with. Persisted so a
	// decline can be re-routed to the next-best node without the original wire
	// payload (P1-5).
	Requires     []string
	LeaseExpires int64
	CreatedAt    int64
	UpdatedAt    int64

	// Queue-scheduling metadata (panel queue redesign). Priority/Seq order the
	// board and the local scheduler (seq>0 = user-dragged, wins over priority);
	// SessionID links the task to its panel conversation; ResourceKeys declare
	// the resources the task occupies for conflict detection; WorkDir pins
	// execution to a session worktree; Scheduled marks tasks owned by the local
	// queue scheduler (never the delegation re-routing path).
	Priority     int
	Seq          int64
	SessionID    string
	ResourceKeys []string
	WorkDir      string
	// ExecWorkDir is the workspace the run ACTUALLY used, persisted when the
	// run starts (SetExecWorkDir). WorkDir above is a submitter pin and is
	// empty for ordinary tasks; this one answers "where did it run?" on the
	// queue board, `task show`, and the panel.
	ExecWorkDir string
	Scheduled   bool
	// AgentSessionID is the adapter's own conversation handle, persisted each
	// round so an interrupted run (yield, restart, redelegation back here)
	// resumes the agent's session instead of cold-starting (§5.2). The handle
	// only means something to the node that minted it — AgentSessionNode —
	// so a delegator may offer it back to that node (ResumeSessionID on the
	// wire) but must never adopt it for its own adapter or hand it onward.
	AgentSessionID   string
	AgentSessionNode string
	// AgentSessionAdapter is the adapter file that minted AgentSessionID
	// ("opencode.py") — the handle's second affinity axis alongside the node.
	// A retry or fallback that lands on a different adapter must not resume
	// the foreign handle: the adapter cannot parse it (opencode rejects
	// non-"ses" ids outright), the attempt dies on a provider error, and a
	// bounded retry loop re-burns a whole cold-start run per round.
	AgentSessionAdapter string

	// Plan-plane metadata (v0.0.6). A stage of a plan is an ordinary task, so
	// these are the only things it carries beyond one: PlanID/StageID name its
	// place in the plan, Needs is the stage_ids it waits for, and the artifacts
	// are the data plane — Inputs are the trees this stage starts from (each with
	// a node known to hold it), OutputArtifact the tree it produced for its
	// successors. All empty on a standalone task.
	PlanID         string
	StageID        string
	Needs          []string
	Inputs         []bus.ArtifactRef
	OutputArtifact string
	// ScreenOutput marks a task whose run drove a screen_sensing actuator —
	// its produced artifact IS display content. The executor stamps it at
	// claim time (its card is authoritative for operator-defined actuator
	// ids) and every delegator hop re-stamps it from the task_result flag,
	// so every node holding the row recognizes the output's sensitivity
	// without needing the producer's card.
	ScreenOutput bool

	// Remote is stamped at intake when this row was created by the delegate
	// handler — i.e. the intent text arrived over the wire — versus a local
	// submit. It is the authoritative provenance bit: chain[0] is
	// peer-supplied and can be written to claim local origin, so provenance
	// cannot be re-derived from Chain.
	Remote bool

	// UserLocale is the user's language preference ("en", "zh-CN", etc.).
	UserLocale string

	// Transport marks the transport mode for this task ("live" or "dtn").
	Transport string
	// DeadlineUnix is the absolute TTL expiration timestamp for DTN tasks (§8.2).
	DeadlineUnix int64
	// DelegationBudget is the remaining mesh-wide delegation quota (§6.1):
	// each forward hop decrements it, and a task that runs out may no longer
	// be delegated — the mesh-wide convergence bound alongside MaxChainDepth.
	DelegationBudget int
	// SpawnDepth is the sub-agent generation this task sits at in its causal
	// tree: a user-submitted root is 0, its PANDA_DELEGATE children 1, their
	// children 2, and so on. It rides the wire's Depth field (whose §6.1
	// comment already meant this) and persists here so every node a subtree
	// walks through enforces the same delegation.max_depth — refusing a
	// spawn needs the row's truth, not the spawning process's memory.
	SpawnDepth int
	// SpawnCap is the tightest delegation.max_depth seen anywhere along this
	// task's delegation path: 0 means "no inherited bound — the local node's
	// config applies". A delegate payload advertises the effective cap the
	// sender enforced (its own config tightened by whatever ITS parent
	// carried), the receiver persists min(its config, the wire value), and
	// the subtree thereafter enforces the most conservative bound any hop's
	// operator configured — so a permissive origin cannot launder children
	// through a strict node.
	SpawnCap int
	// TokenBudget is the remaining LLM token quota the task may spend across
	// the mesh (§6.1): 0 means unbounded (a legacy wire or a pre-budget row),
	// a positive value is the spendable remainder, and -1 is the persisted
	// exhaustion marker — an exhausted task may neither execute another
	// metered round nor be delegated onward, since either would launder the
	// bound into fresh budget on the next hop.
	TokenBudget int64
	// ScopePaths is the project-relative directory set a delegated child
	// declared it owns. It persists so every later hop and requeue re-derives
	// the same scope leaf locks (disjoint siblings run in parallel, the
	// whole-project fallback stays for undeclared rows) instead of silently
	// widening the child's claim to the entire worktree.
	ScopePaths []string
	// Isolate marks a delegated child that runs in a private copy of the
	// project tree instead of the shared one. It persists for the same
	// reason ScopePaths does: a requeue, forward or restart must keep
	// executing isolated — dropping the flag would run the child against
	// the shared tree with a lock set that protects nothing.
	Isolate bool
}

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.

func (Task) NeedsFollowup added in v0.1.0

func (t Task) NeedsFollowup() bool

NeedsFollowup reports whether this row parked in review with the supervisor's "more work remains" flag — the signal that makes "continue" an honest third answer alongside approve and reject. The flag lives in the stored result JSON, not a column, because it describes the result, not the task's identity.

type TaskDayHour added in v0.1.0

type TaskDayHour struct {
	Day   string // YYYY-MM-DD, local time
	Hour  int    // 0–23, local time
	Count int
}

TaskDayHour is one (local day, local hour) bucket of task creations.

type TaskDetail

type TaskDetail struct {
	ContextType  string
	ContextHash  string
	Intent       string
	SpecJSON     string
	Complexity   float64
	Risk         string
	ResourceJSON string
	// Requires carries the routing capability set so it survives past the
	// original delegate payload (decline re-routing, P1-5).
	Requires []string
	// UserLocale carries the user's language preference.
	UserLocale string
	// Transport carries the preferred transport mode ("live" or "dtn").
	Transport string
	// DeadlineUnix carries the absolute TTL expiration timestamp for DTN tasks.
	DeadlineUnix int64
}

TaskDetail is the entry-model-derived task metadata (design doc §6.1 tasks schema). It is written once, shortly after creation, by SetDetail; the fields stay zero/empty for tasks that predate the entry model or arrived via a Phase 0 payload without detail. model_tier is intentionally absent — it is a Phase 3 feature (model-tier selection) and will be added when that lands.

type TaskInput

type TaskInput struct {
	Title        string
	ParentID     string // causal parent task ID for subtasks / sub-DAGs
	Project      string
	ContextType  string
	ContextHash  string // pre-packed snapshot hash; empty means "pack if applicable"
	ContextLevel string // pointer|summary|full; empty is derived by packContext
	RepoPath     string // file-type repo root for auto-packing (wired by askengine from WorkDir)
	// 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
	// Paths declares the project-relative directories the task owns inside a
	// shared worktree — a delegate child's scope claim. Non-empty turns the
	// monolithic project lock into leaf keys so siblings on disjoint paths
	// run in parallel; empty keeps the whole-project serialization.
	Paths []string
	// Isolate gives a delegate child a private copy of the project tree (a
	// git worktree when the project is a repository) instead of the shared
	// one: nothing shared is locked, any number of isolated siblings run
	// concurrently, and the child's changes merge back into the project tree
	// when it finishes. Ignored for tasks without a project.
	Isolate bool
	// PreferredNode is a soft routing hint: the scorer's user-priority term
	// and RouteAtP's capable-match shortcut both weigh it, but an incapable
	// or unavailable node simply loses — the task still lands somewhere.
	PreferredNode string
	// TargetNode is a hard pin: the task runs on the named node, waits for
	// its link, or fails with the reason — it never silently reroutes to a
	// higher-scored candidate. Any user-specified destination (spec.node,
	// --nodes, --preferred, a plan stage's node, an agent's delegate target)
	// lands here, because "on Mac" is an instruction, not a suggestion.
	TargetNode   string
	Complexity   float64
	Risk         string
	ResourceJSON string
	Authorized   bool // user consented to executing tier-2 (irreversible) commands
	// ClassifyKind carries the entry model's classification ("task") for trace
	// emission. Empty means the input did not come from a classified ask (a
	// direct CLI submission, a delegated peer task): no classify_result event
	// fires for those, matching the pre-trace behavior.
	ClassifyKind string
	// UserLocale records the user's language preference ("en", "zh-CN", etc.).
	UserLocale i18n.Locale
	// Transport specifies the transport mode ("live" or "dtn", whitepaper §8.2).
	Transport string
	// DeadlineUnix is an optional absolute deadline timestamp for DTN tasks.
	DeadlineUnix int64
}

TaskInput is the local-entry form of a task: the structured task the entry model emitted, translated into the fields the core persists and executes. It mirrors the wire TaskDelegatePayload but originates locally rather than over the bus. The caller (cmd/panda) owns the translation from entry.TaskSpec.

type TaskMessage added in v0.0.11

type TaskMessage struct {
	Scope       string `json:"scope"`
	Sender      string `json:"sender"` // sender task_id
	Rcpt        string `json:"rcpt"`   // recipient task_id, "" = broadcast
	SenderSeq   int64  `json:"sender_seq"`
	SenderLabel string `json:"sender_label"` // stage id or title, resolved by the owner
	Grade       string `json:"grade"`
	Body        string `json:"body"`
	SentAt      int64  `json:"sent_at"`
	RecvAt      int64  `json:"recv_at"`
	// ConsumedAt is when the recipient's round loop folded this slot into its
	// prompt; 0 = still waiting. RecvAt cannot answer that: it is stamped on
	// arrival, so a just-posted note already reads "received". Surfaces use
	// this one to draw "waiting for the next round" apart from "already read".
	ConsumedAt int64 `json:"consumed_at"`
	// Attachments are the files a user note rode along with, as
	// workspace-relative paths. The body already names them (`@path`); this
	// keeps the prose separable so a console can show chips and edit the text
	// without touching the attachment block. Empty on agent-authored slots.
	Attachments []string `json:"attachments,omitempty"`
	ExpiresAt   int64    `json:"expires_at"`
}

TaskMessage is one board slot: a sender's latest note toward one recipient (Rcpt=="" = broadcast to the scope) within a scope.

type TaskStamp added in v0.0.10

type TaskStamp struct {
	ID        string
	State     string
	UpdatedAt int64
}

TaskStamp is the minimal per-task triple a change-detection digest needs: identity, lifecycle state, and the mutation clock. Pulling the full row for this (spec_json, result_json, intent…) would read every task's payload on every poll.

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 NewSigningTaskStore added in v0.0.10

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

NewSigningTaskStore wraps NewTaskStore and, when a node identity is persisted in settings, wires the event signer (P2-9). Every caller that writes events — daemon, ask-engine helpers, CLI verbs — gets the same attestation without re-plumbing the key through each constructor. The key lookup runs here, before any of the store's transactions, so the single-connection pool never sees a nested read.

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, expectAttempt ...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 by ANY TaskStore sharing this database handle — see eventHub. Returns an unsubscribe function that removes the listener.

func (*TaskStore) AdoptAttempt

func (s *TaskStore) AdoptAttempt(ctx context.Context, taskID, expectAttempt, 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. The write is fenced on expectAttempt: the blind UPDATE it replaces could overwrite a rotation that landed between the caller's read and its write — a lease-rerouted row back in queue would silently wear the wire-reported (older) attempt over the fresh one and then authenticate stale results.

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) ArtifactIndexedFor added in v0.0.9

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

ArtifactIndexedFor reports whether the local pool's index ties hash to taskID — i.e. this node recorded the artifact while packing it for, or pulling it under, that task. artifactPeerAuthorized consults it so a peer can only fetch artifacts the task it quotes actually owns: participation alone must not open the whole pool to one known hash.

func (*TaskStore) Cancel

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. When the cancelled row is a plan stage, its sibling stages are cancelled too — stages carry no parent_id, so without the plan sweep a stage cancel would strand the rest of the plan mid-flight, blocked stages waiting forever on predecessors that can now never complete. The returned slice lists the tasks actually transitioned to cancelled — already-terminal tasks are skipped, not included.

func (*TaskStore) CancelStaleRemoteSubmits added in v0.1.0

func (s *TaskStore) CancelStaleRemoteSubmits(ctx context.Context, cutoff int64) (int, error)

CancelStaleRemoteSubmits terminalizes the remote half of the submitted stranding class: an inbound delegate whose handler died between row creation and its admission outcome (dispatch, forward, decline, or the trust-zone review park) can never legitimately resume here — the delegator is already timing the wait on its own copy and will re-route when it expires. Requeueing instead would run work the admission gate never admitted, so the verdict is cancelled: honest, terminal, and visible in the audit chain.

func (*TaskStore) CheckpointRetries added in v0.1.0

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

CheckpointRetries counts resumable-checkpoint retries — EvRetry events flagged checkpoint — recorded since the task's most recent review park. A checkpoint is a run that hit its wall-clock bound with a live session: interrupted progress, not a failure, so it draws a budget separate from RetryCount's hard-failure one. Counting only post-review events is the semantics a human re-queue implies: "keep going" grants a fresh set of resumed rounds, while S2-6's all-time hard-failure count stays untouched.

func (*TaskStore) Checks added in v0.1.2

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

Checks returns a task's check rows in execution order.

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) ClearLease added in v0.0.11

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

ClearLease drops a task's lease deadline entirely. A task parked in the outbox waiting on a peer link holds no executor, so nothing it could measure would fire legitimately — the DTN deadline (or a human cancel) is its bound instead.

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) CompleteAttempt added in v0.1.0

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

CompleteAttempt is Complete scoped to one attempt — the split-brain fence for runner-side verdicts. A runner whose row was rotated (lease-expiry reroute -> requeue -> re-run) still holds its old attempt id; without the check its deferred Complete would read state=running on the FRESH attempt's row and stamp the stale run's result onto work it no longer owns.

func (*TaskStore) CompleteFromRemote

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

CompleteFromRemote records a remote executor's final result on the delegator's copy. The delegator may be in submitted/queued/dispatched/ running — or parked in a consent/question review, which the remote verdict resolves. An accept-work review stays protected (reviewProtected), 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) CountByState added in v0.0.11

func (s *TaskStore) CountByState(ctx context.Context, state string) (int, error)

CountByState counts tasks filtered by state ("" = all) — the shape count-only consumers (status summaries, clear-confirmations) should use instead of hydrating every row just to len() it.

func (*TaskStore) CountScheduledActive added in v0.0.2

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

CountScheduledActive counts execution slots this node is actually spending: every row running or waiting_context under this node's ownership (scheduled or not — a delegated task accepted here burns the same CPU a queued one does, and a queue scheduler blind to it would over-admit past the card's MaxConcurrent), plus queued claims still in the dispatched window below. Rows may be owned by any submitter and adopted across process instances (e.g. a restarted panel sidecar), which is why owner_node, not scheduled, is the "executing here" test.

A row running with owner_node=<peer> is the DELEGATOR'S copy of work the peer executes (handleAccept stamps the executor as owner): it must not count — the peer's own budget covers the execution, and counting it here would park this node's queue for the whole remote run.

A dispatched row occupies a LOCAL slot only while its dispatch target is this node: forwardScheduled re-targets the claim to a peer (RetargetDelegation records the new EvDelegate target) and the peer then runs it, so the row sits 'dispatched' while the work happens elsewhere. Counting it anyway double-books capacity — the executor charges the slot on its own CountActive, and this node would refuse fresh claims on a budget the peer is spending. The latest delegate event is the authority: a corrective retarget back to self after a failed send restores the row to locally-claimed, which is exactly what it is.

func (*TaskStore) Create

func (s *TaskStore) Create(ctx context.Context, parentID, project, title, owner string, chain []string) (Task, error)

Create inserts a new task in submitted state with a fresh UUIDv7 id.

func (*TaskStore) CreateFromRemote

func (s *TaskStore) CreateFromRemote(ctx context.Context, taskID, title, owner string, attemptID string, chain []string) (Task, error)

CreateFromRemote inserts a task owned by this delegator, adopting the executor's attempt_id so a follow-up result (with the same attempt) is not mistaken for a stale write. Used when a delegator hears a result for a task it never persisted locally.

func (*TaskStore) CreateWithID

func (s *TaskStore) CreateWithID(ctx context.Context, taskID, parentID, project, title, owner string, chain []string, remote bool) (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. remote is stamped into the row so executor-side policy can tell wire-authored intent apart from a local submit regardless of what the chain claims. Returns ErrConflict if the id already exists.

func (*TaskStore) Decline

func (s *TaskStore) Decline(ctx context.Context, taskID, parent, reason, code, by string, expectAttempt ...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) DeclineTrail added in v0.0.11

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

DeclineTrail returns every refusal this task collected, oldest first.

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) DelegationMetricsFor added in v0.0.10

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

DelegationMetricsFor returns one task's delegation metric rows, oldest first — the per-hop executor timings `panda task <id> --trace` pairs with the event log's hop boundaries (Track 3).

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) DeleteSettledBefore added in v0.0.11

func (s *TaskStore) DeleteSettledBefore(ctx context.Context, cutoff int64) (int, error)

DeleteSettledBefore removes settled tasks (done/failed/cancelled/expired) whose updated_at predates cutoff, together with their satellite rows — the retention sweep's delete path. Returns the number of task rows removed. The delete re-checks state and age inside the transaction, so a task a user requeued between batches is never swept out from under them.

func (*TaskStore) DeleteTerminal added in v0.1.0

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

DeleteTerminal drops a row that reached a closed verdict (done/failed/cancelled/expired). It exists for one purpose: an expiry re-route can land back on a node whose stale copy of the task already closed — replace the dead row so the fresh attempt can run. Active and review-parked rows refuse: a live execution or a pending human decision owns the identity. The task_events audit trail is keyed by task_id and is deliberately left in place — it keeps the previous attempt's history under the same id.

func (*TaskStore) DeleteUserNote added in v0.1.0

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

DeleteUserNote drops a pending note from the board. Guarded by the same "already read" rule as Edit: a note the round consumed is part of the transcript's history, and removing the row would only make the board lie.

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) EditUserNote added in v0.1.0

func (s *TaskStore) EditUserNote(ctx context.Context, taskID, sender, text string, attachments []string, localNodeID string) (TaskMessage, error)

EditUserNote rewrites a pending note in place, keeping its slot and grade. The seq is bumped so the store's stale-write guard accepts the update, and SentAt moves to now so the edited note re-sorts to the tail of the board — an edit is the user saying "this is what I mean now".

A note the round already read is refused: rewriting history would leave the agent's prompt and the board disagreeing about what was said.

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) EventsSince added in v0.0.11

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

EventsSince returns the events recorded for taskID after the given event id, oldest first — the incremental read a poll loop uses to follow a task timeline without re-reading it whole. A cursor of 0 reads the full history (the same rows Events returns); callers then advance their cursor to the last row's ID.

func (*TaskStore) EvictedExecutors added in v0.1.0

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

EvictedExecutors returns the nodes whose custody of this task lapsed — the "executor" stamped on each expiry-reroute retry event. The re-router excludes them so a task does not get handed straight back to a node that already went silent once, while a hard pin (which bypasses scoring) still names its own destination.

func (*TaskStore) ExecLockBlockers added in v0.1.0

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

ExecLockBlockers reports which live runs currently hold keys contending with the caller's wanted set — a read-only diagnostic for the wait heartbeat's "who am I behind" note. Self-held rows are excluded (they are the waiter's own restart artifacts, due for a steal inside the acquire tx, not blockers worth naming). Best-effort: anything read here may change by the next acquire pass, which is exactly why it is diagnostics, not policy.

func (*TaskStore) ExistingTaskIDs added in v0.0.11

func (s *TaskStore) ExistingTaskIDs(ctx context.Context, ids []string) (map[string]bool, error)

ExistingTaskIDs reports which of the given ids still have a row — one batched IN query instead of a Get per id. The dir-reaping sweep uses it to tell orphaned workdirs from live ones without paying a SELECT per dir, and the PK index keeps each batch cheap however large the table grows. Batches of 500 stay well inside SQLite's bound-variable limit.

func (*TaskStore) ExpireTasks

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

ExpireTasks settles every expired row in one shot — the simple path for callers that hold no per-task runtime state to release (a fresh process at startup owns no running executions). The daemon monitor instead scans, settles, then cancels exactly the runs that held the lapsed leases, so a dying runner's deferred verdict never beats the settle to the row.

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) FailAttempt added in v0.1.0

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

FailAttempt is Fail scoped to one attempt — see CompleteAttempt. Runner verdict paths use it so a superseded attempt's late write returns ErrConflict instead of failing the fresh attempt's live row.

func (*TaskStore) FailFromRemote

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

FailFromRemote records a remote executor's failure on the delegator's copy. Mirrors CompleteFromRemote — including the same review rule: an accept-work park keeps its pending human verdict, while a consent/question park converges on the executor's actual outcome.

func (*TaskStore) FailStaleLeaseless added in v0.1.0

func (s *TaskStore) FailStaleLeaseless(ctx context.Context, owner string, cutoff int64) (int, error)

FailStaleLeaseless fails running rows owned by this node that carry no lease and no deadline — Recover's "interrupted" verdict applied mid-life. renewLease stamps a lease the moment a run starts and keeps stamping it (each stamp bumps updated_at), so a self-owned running row with a NULL lease untouched this long is an execution whose supervisor died before the first renewal — and the lease-expiry path that normally reaps runs requires lease_expires_at > 0, so nothing else ever engages. waiting_context stays out: a context pull can legitimately outlast the window while the delegator pushes a large snapshot, and the wait's bound is the delegation's own lease/outbox machinery, not this sweep. Lease- exempt DTN runs carry deadline_unix and are excluded; remote-executed copies are owned by their executor and never match owner.

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) ForceFailAttempt added in v0.1.0

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

ForceFailAttempt is the dispensation-scoped form of ForceFail: the admin verdict (a context fetch declined, an artifact push gone bad) stands down only the attempt it was raised against. A row that rotated past that attempt mid-wait keeps its fresh dispensation; an empty attemptID degenerates to ordinary ForceFail semantics for pre-attempt rows.

func (*TaskStore) Get

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

Get loads one task.

func (*TaskStore) HardRetries added in v0.1.0

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

HardRetries counts the EvRetry events that are NOT resumable checkpoints — the population the persisted failure budget (S2-6) actually bounds. A checkpoint retry resumes a timed-out session rather than re-attempting a failure, so it must not draw down the allowance meant for "this keeps failing": counting it here would let five checkpoint slices exhaust a budget the hard failures beneath them never used.

func (*TaskStore) HeartbeatWait added in v0.1.0

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

HeartbeatWait refreshes a task row's liveness while its run sits blocked acquiring execution leases: the row is still dispatched and the stranded sweeps must see the process is alive. updated_at always moves — the stale-claim requeue keys on it — while lease_expires_at only pushes where a lease already exists: a queued claim carries none, and stamping one would turn a dead waiter's "orphaned claim → requeue" outcome into a wrongful "expired → fail" for work that never ran.

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) ListActive added in v0.0.11

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

ListActive returns the tasks that can still move — everything outside the terminal set (done/cancelled/expired). Unlike the archive it is naturally small: the completed history a daemon accumulates never enters it, which is what makes it the right read for a poll loop watching for stalls.

func (*TaskStore) ListByProject added in v0.0.11

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

ListByProject returns the tasks of one project, newest first. Filtering in SQL keeps a project listing from reading every other project's rows.

func (*TaskStore) ListBySession added in v0.1.0

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

ListBySession returns the tasks one conversation spawned, newest first. The chat's orchestration card reads this: the question is "what did THIS thread start, and what is still moving", which neither the state nor the project filter can answer — a thread can span states, and a project spans threads. Uncapped on purpose: filtering a capped board read would silently drop the oldest rows of the very list the card claims is complete, and a single thread's task count stays small by construction.

func (*TaskStore) ListByState

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

ListByState returns tasks filtered by state ("" = all), newest first. Callers that display a bounded view should use ListByStateLimit so a long task history cannot make one listing read the whole table.

func (*TaskStore) ListByStateLimit added in v0.0.11

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

ListByStateLimit is ListByState capped at limit rows; limit <= 0 reads the full set. The cap exists because a daemon's task table only grows — the board/listing surfaces want the newest rows, not the archive.

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) ListReadySummaries added in v0.0.10

func (s *TaskStore) ListReadySummaries(ctx context.Context) ([]queue.ReadyTask, error)

ListReadySummaries is the scheduler's polling projection: the six columns a ReadyTask actually reads, not the forty-odd of a full row. The queue poll used to drag spec_json/intent/result_json blobs through the wire for every queued task every 400ms–2s; a 100KB spec now stays on disk until the task is claimed and the runner loads it for real.

func (*TaskStore) ListRecentByState added in v0.0.11

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

ListRecentByState orders by updated_at — the "recent activity" ordering the queue board and watch loops sort to client-side anyway — and caps the read.

func (*TaskStore) MarkExpired added in v0.0.9

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

MarkExpired moves a non-terminal task straight to expired, bypassing the ordinary transition table: a deadline reached while dispatched or queued is not a failure of the work, it is the bundle's lifetime ending — the distinction the 'expired' state exists to carry.

func (*TaskStore) MarkExpiredAttempt added in v0.1.0

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

MarkExpiredAttempt is MarkExpired bound to one dispensation: a parked-custody expiry (outbox TTL, a bundle that fails verification) convicts the attempt that custody was taken on — a row that rotated since is a fresh custody the stale verdict must not kill. An empty attempt degenerates to MarkExpired.

func (*TaskStore) MarkTaskMessageConsumed added in v0.1.0

func (s *TaskStore) MarkTaskMessageConsumed(ctx context.Context, scope, sender string, seq int64) error

MarkTaskMessageConsumed records that the recipient folded this slot into a prompt. Best-effort: the round has already read the note, so a failed write costs one stale "waiting" badge, never a lost message — callers log at debug and carry on. Guarded by (scope, sender, sender_seq) so a slow write can never mark a newer post as read.

func (*TaskStore) NextMsgSeq added in v0.0.11

func (s *TaskStore) NextMsgSeq(ctx context.Context, scope, sender string) int64

NextMsgSeq returns the seq a sender's next post on this scope should carry: one past the highest current slot, or 1 for a first post. The local read is authoritative for the sender's own slots — only the sender increments them.

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) PauseAttempt added in v0.1.0

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

func (*TaskStore) PauseDrift added in v0.0.11

func (s *TaskStore) PauseDrift(ctx context.Context, taskID, owner, reason string, files []string) error

PauseDrift parks a running task whose agent overstepped its declared scope. The drift message and the strayed paths are preserved as the result so the human reviewing sees exactly what left the scope, and the disposition is AcceptWork: approving accepts the work as done (the reviewer saw the diff), rejecting fails it. The old NeedsChangedInput disposition made approve error out — a finished task with no route to done.

ok:true in the stored result: the agent's run succeeded and drift is a policy intercept, not an execution failure — an approving human accepts the work, so the approve receipt must not report (and exit) as a failure.

func (*TaskStore) PauseDriftAttempt added in v0.1.0

func (s *TaskStore) PauseDriftAttempt(ctx context.Context, taskID, owner, attemptID, reason string, files []string) error

func (*TaskStore) PauseForAnswer added in v0.0.10

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

PauseForAnswer parks a running task in review on an agent's clarification question (Q4): the partial result is preserved like PauseWithResult, but the disposition resumes execution — the user's answer travels back on task_resume and folds into the re-run's intent.

func (*TaskStore) PauseForAnswerAttempt added in v0.1.0

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

func (*TaskStore) PauseWithDisposition added in v0.0.8

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

func (*TaskStore) PauseWithDispositionAttempt added in v0.1.0

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

PauseWithDispositionAttempt is PauseWithDisposition scoped to one attempt — see ReviewWithDispositionAttempt.

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) PauseWithResultAttempt added in v0.1.0

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

Attempt-scoped runner variants — see CompleteAttempt.

func (*TaskStore) PendingNoteCounts added in v0.1.0

func (s *TaskStore) PendingNoteCounts(ctx context.Context) (map[string]int, error)

PendingNoteCounts reports, per task id, how many user notes on that task's own board are still waiting for a round. One grouped query over live boards rather than a probe per row: the queue picker and the board card both need this for every row they paint, and a per-row round trip is the N+1 that makes a 50-row list feel slow. Grades are not filtered — a status note and a steer both sit there unread until a round folds them, and both are what the user typed.

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) PostUserMessage added in v0.1.0

func (s *TaskStore) PostUserMessage(ctx context.Context, taskID, text, grade, localNodeID string) error

PostUserMessage lands a user message on the task's own board scope. The state guard refuses terminal tasks; the board's per-sender slot keeps the newest message, so a user who sends twice carries the second one — the same semantics as every other board sender. This is the scheduler-less delivery path too: a note needs the store, not the execution core.

localNodeID is the runtime identity of the node this store belongs to; it backs the owner guard — a task dispatched to another node reads ITS store's board, not ours, so a note landed here would never reach the agent. The guard refuses honestly instead of accepting a message nobody will read. The comparison is runtime identity, not literal equality: a CLI engine's ephemeral id and the daemon's base id resolve to the same store-owning node. An empty localNodeID skips the check (callers that cannot name the store's owner degrade to the state guard alone).

func (*TaskStore) PostUserNote added in v0.1.0

func (s *TaskStore) PostUserNote(ctx context.Context, taskID, text string, attachments []string, grade, localNodeID string) (TaskMessage, error)

PostUserNote is PostUserMessage returning the slot it landed, so a sender can address that exact note afterwards (edit / delete / promote). The returned Sender is the row's board id (`user:<seq>`), not "user".

func (*TaskStore) ProjectStateCounts added in v0.1.0

func (s *TaskStore) ProjectStateCounts(ctx context.Context) (map[string]map[string]int, error)

ProjectStateCounts counts tasks grouped by project and state — one GROUP BY for the whole listing, so a per-project work summary (the console's project cards) does not cost a COUNT query per project row. Only named projects appear; tasks outside a project are nobody's summary.

func (*TaskStore) PutTaskMessage added in v0.0.11

func (s *TaskStore) PutTaskMessage(ctx context.Context, m TaskMessage) error

PutTaskMessage upserts one slot on a scope board. Stale arrivals (a fan-out copy landing after the sender already posted newer) lose to the seq guard.

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) ReclaimClaimed added in v0.1.0

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

ReclaimClaimed moves a queued row this node owns back to dispatched.

The queue scheduler's claim→run window is one goroutine (ClaimLocal → runScheduled → Accept). Task recovery can land inside that window: its dispatched → queued branch moves the row back under the runner, and the runner's run() refuses a row that is not in a runnable state ("cannot run task in state queued") — the task is then lost, which is exactly what recovery was supposed to prevent.

The claim is still ours — the scheduler's resource-key registry holds the task's keys for the run's duration, so no other runner can take it — so the row is restored to the state the run expects instead of being dropped.

The guard is the same shape ClaimLocal uses, plus the owner: state=queued AND owner=this node. A row owned by someone else is never touched, and a row this node does not own cannot be stolen by the reclaim.

func (*TaskStore) ReconcileDone added in v0.0.11

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

ReconcileDone lands a late remote done on a row a timeout path already closed — lease expiry, deadline expiry, a resume window — where the close was about silence, not about the work. The executor's real product trumps the monitor's pessimistic verdict, but the row keeps its honesty: the audit event carries `reconciled: "<from>→done"` so the timeline shows this task did not succeed normally, it was overturned by evidence.

The reconcile is only reachable for failed/expired rows whose last word was NOT a human decision — failureWasRejected gates the caller. A row concurrently closed another way (cancel, a second timeout) wins: the CAS keeps first-close semantics.

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) RecordCheck added in v0.1.2

func (s *TaskStore) RecordCheck(ctx context.Context, taskID string, r contract.Result) error

RecordCheck persists one acceptance check outcome. Recording is best-effort relative to the verdict: a failed insert must not hide the verdict itself, so callers log the error and continue.

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, selfNode string) (int, error)

Recover normalizes tasks left in an active state by a previous process instance. Running/waiting_context rows carrying a session checkpoint minted on this node return to queued — the retry's session affinity resumes the same agent conversation, so a daemon restart costs a re-dispatch instead of the whole interrupted exploration. The remainder become failed (execution was interrupted and nothing consumable survived); 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.

selfNode is this node's runtime identity — it gates the resume predicate because an agent session handle is only consumable on the node whose adapter minted it: a checkpoint learned from a peer (agent_session_node = env.From) must still take the interrupted path rather than queuing a run that cannot resume.

Resume is only safe HERE, at startup: the node-identity lock proves the previous executor process is gone before Recover runs, so no zombie runner can race the requeued clone. The mid-life twin (FailStaleLeaseless) cannot make that assumption and keeps failing.

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) ReleaseExecLocks added in v0.1.0

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

ReleaseExecLocks drops every exec_locks row held by taskID for this run. Release is by owner id AND run nonce, not by key set: a key the task no longer holds was stolen after going stale and must not be deleted from under its new owner — and neither may the fresh rows a re-execution of the same task took under a different run_id (see the file header).

func (*TaskStore) ReleaseExecLocksKeys added in v0.1.0

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

ReleaseExecLocksKeys drops just the named rows held by this run — the delegate wait frees its worktree keys while the actuator key (and anything else outside the set) stays held for the run.

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) RequeueForContinue added in v0.1.0

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

RequeueForContinue atomically returns a follow-up-parked review to the schedulable queue — the same review→queued+scheduled=1 transition an approved resume uses, gated on the accept_work disposition. The queue scheduler (this process's or the daemon sharing the store) then claims and runs it like any queued row, which is what makes continue work cross-process: a CLI or console marks the row, the executor's scheduler does the running. The caller is responsible for the needs_followup check (it lives in the parked result, not the row).

func (*TaskStore) RequeueForRetry added in v0.0.9

func (s *TaskStore) RequeueForRetry(ctx context.Context, taskID, owner string, checkpoint bool, expectAttempt ...string) (string, error)

RequeueForRetry is the atomic form of the retry loop's three-step move (RotateAttempt -> Requeue -> Dispatch to self): mint a fresh attempt_id, move the task failed -> dispatched, and append both the EvRetry and EvDelegate audit events in ONE transaction. Splitting those steps (the old retryOnce) left the row in queued or carried the stale attempt_id if the node crashed or lost the owner guard mid-sequence — a half-retry the audit trail could not distinguish from a completed one. The state+owner guard keeps the same exactly-once semantics as the separate calls; on conflict nothing is written. Returns the new attempt id.

func (*TaskStore) RequeueStaleClaims added in v0.1.0

func (s *TaskStore) RequeueStaleClaims(ctx context.Context, owner string, cutoff int64) (int, error)

RequeueStaleClaims requeues dispatched rows this node claimed for the local queue scheduler and never accepted — the claim-orphan class. The claim→run window is one goroutine (ClaimLocal → runScheduled → Accept), so a row still dispatched, self-owned, lease-free and untouched past the cutoff is a claim whose process died before the run began: ExpireTasks never sees it (lease_expires_at IS NULL), ListReady never sees it (state moved off queued), and Recover only runs at restart. Same guard set as the submitted requeue plus the outbox custody exclusion — a parked forward's delivery is owed by the flush, not the scheduler.

func (*TaskStore) RequeueStaleSubmitted added in v0.1.0

func (s *TaskStore) RequeueStaleSubmitted(ctx context.Context, cutoff int64) (int, error)

RequeueStaleSubmitted is Recover's submitted branch narrowed to rows that sat untouched past cutoff — the mid-life backstop for the startup pass. A submitted row still moves while its submitter lives (create → route → dispatch all write it); one whose process died between create and dispatch stays visible to nobody until the next restart (observed: a panda ask killed mid-route left a row parked for hours — scheduled=0, no plan, no route event). Requeueing stamps scheduled=1 so ListReady picks the work up exactly like a post-restart recovery, and the cutoff keeps a healthy submit — whose routing prep is seconds, not minutes — out of the batch. remote=0 is deliberate: an inbound delegate that died mid-admission must not be slipped past the trust-zone review gate by a requeue — it is cancelled instead (CancelStaleRemoteSubmits) and the delegator re-routes on its own timeout.

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 RequeueForRetry). 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) ReviewAttempt added in v0.1.0

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

func (*TaskStore) ReviewFromRemote added in v0.0.4

func (s *TaskStore) ReviewFromRemote(ctx context.Context, taskID, owner string, result any, disposition ApprovalDisposition, wireAttempt ...string) 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) ReviewWithDispositionAttempt added in v0.1.0

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

ReviewWithDispositionAttempt is ReviewWithDisposition scoped to one attempt: the run loop's verdict paths carry the runner's captured attempt_id so a superseded run parks nothing on the fresh attempt's row.

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) RouteFallbackPeer added in v0.0.11

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

RouteFallbackPeer returns the peer named by the newest route_fallback event — the node routing intended before the link failed and the task ran locally. "" means the task went exactly where routing decided.

func (*TaskStore) ScanExpired added in v0.1.0

func (s *TaskStore) ScanExpired(ctx context.Context) ([]ExpiredRow, error)

ScanExpired returns every active row past its lease or absolute deadline. review is deliberately absent from the lease scan: a task paused for human analysis has no deadline pressure, and the monitor must never kill it out from under the reviewer (P1-8).

func (*TaskStore) SetAgentSession added in v0.0.9

func (s *TaskStore) SetAgentSession(ctx context.Context, taskID, sessionID, node, adapter string) error

SetAgentSession writes the handle together with the node and adapter that minted it. The executor passes its own id and the adapter file that ran; a delegator learning a remote session from a task_result passes through the reported pair — which is what lets a later re-dispatch offer ResumeSessionID only to a run that can actually consume it.

func (*TaskStore) SetAgentSessionID added in v0.0.9

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

SetAgentSessionID persists the adapter conversation handle for the task (§5.2 breakpoint mooring). Written every round as the session evolves and cleared when the run ends, so a task that is interrupted mid-flight resumes its agent session while a finished one never drags a dead handle into a re-run.

func (*TaskStore) SetAuthorized

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) SetAuthorizedGrant added in v0.0.9

func (s *TaskStore) SetAuthorizedGrant(ctx context.Context, taskID, sig, pub string, ts int64) error

SetAuthorizedGrant is SetAuthorized plus the signed consent the delegate carried: the grant persists so a later re-dispatch (queue forward, decline re-route) re-emits the origin's Ed25519 signature instead of degrading the consent to the bare flag on the next hop (P2-8).

func (*TaskStore) SetDeadlineIfUnset added in v0.1.0

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

SetDeadlineIfUnset stamps an absolute deadline on a task that has none. The store-and-forward paths use it: a DTN/parked copy holds no lease, so this deadline is its only bound (§8.2) — and it doubles as the marker that tells RequeueStaleClaims a dispatched, lease-less row is legitimate in-flight custody, not a claim whose process died before the run began. An explicit task deadline is never overwritten.

func (*TaskStore) SetDelegationBudget added in v0.0.9

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

SetDelegationBudget persists the remaining mesh-wide delegation budget the task carries (whitepaper §6.1). Stamped on creation — locally at submit, remotely when a delegate envelope adopts the payload's budget — so a restarted node cannot re-mint budget the mesh already spent.

func (*TaskStore) SetDetail

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) SetEventSigner added in v0.0.10

func (s *TaskStore) SetEventSigner(pub ed25519.PublicKey, priv ed25519.PrivateKey)

SetEventSigner installs the node identity used to sign recorded events (P2-9). The key must be resolved BEFORE any transaction opens — a lazy settings read from inside recordEventTx would run on a different pooled connection (or deadlock outright on a single-conn :memory: store), seeing committed state rather than the tx's own view. Signing is pure-CPU once the key is in memory.

func (*TaskStore) SetExecWorkDir added in v0.0.11

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

SetExecWorkDir records the workspace a task actually executed in — the effective directory (node work dir, stage dir, project dir) derived at run start, which the row had no field for: work_dir is a submitter PIN and stays empty for ordinary tasks. Observability metadata for the queue board and task show ("where did this run?").

func (*TaskStore) SetIsolate added in v0.1.0

func (s *TaskStore) SetIsolate(ctx context.Context, taskID string, isolate bool) error

SetIsolate persists the isolated-execution mode of a delegated child: true keeps every later run (requeue, resume, restart) on a private copy of the project tree with nothing shared locked. Stamped at spawn from the delegate request and adopted at delegate-accept from the payload.

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) SetLeaseAttempt added in v0.1.0

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

SetLeaseAttempt is SetLease fenced on the row's attempt: a progress beat from a superseded dispensation — the gate checked attempt, but a rotation landed before this write — must not extend the fresh attempt's lease and keep a dead run alive for another lease period.

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) SetResourceKeys added in v0.1.0

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

SetResourceKeys persists a task's queue/exec resource keys without the scheduled flag SetQueueMeta carries. It exists for delegated rows whose lock set is derived at accept time (a scoped child's leaf keys) — those rows are already dispatched and must not be marked queue-owned.

func (*TaskStore) SetScopePaths added in v0.1.0

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

SetScopePaths persists the project-relative directories a delegated child declared it owns. Stamped at spawn from the delegate request and adopted at delegate-accept from the payload, so a later requeue/forward re-derives the same scope leaf locks instead of widening the claim to the whole project.

func (*TaskStore) SetScreenOutput added in v0.0.11

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

SetScreenOutput marks the task as having produced display content: its output artifact rides the mesh-only rule on every node that holds this row. Stamped by the executor when its run resolves a screen_sensing actuator, and by each delegator hop adopting a flagged task_result.

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) SetSpawnCap added in v0.1.0

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

SetSpawnCap persists the tightest delegation.max_depth the task inherited (0 = none — local config applies). Stamped at spawn from the parent's effective cap and adopted at delegate-accept from the payload's max_depth.

func (*TaskStore) SetSpawnDepth added in v0.1.0

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

SetSpawnDepth persists the task's sub-agent generation (§6.1 Depth on the wire). Stamped at spawn on the parent side and adopted from the payload on a delegate accept — never recomputed from the chain, which records routing hops, not spawn generations.

func (*TaskStore) SetStage added in v0.0.6

func (s *TaskStore) SetStage(ctx context.Context, taskID, planID, stageID string, needs []string) error

SetStage stamps a task's place in a plan: the plan it belongs to, its stage id within that plan, and the stage ids it waits for. Called once at StartPlan, before the stage is released.

func (*TaskStore) SetStageInputs added in v0.0.6

func (s *TaskStore) SetStageInputs(ctx context.Context, taskID string, inputs []bus.ArtifactRef) error

SetStageInputs records the artifacts a stage starts from. Written by the plan node the moment the last predecessor finishes — that is the first point at which every input hash, and a node known to hold it, are both known.

func (*TaskStore) SetTokenBudget added in v0.0.9

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

SetTokenBudget persists the remaining mesh-wide token quota the task carries (whitepaper §6.1). Stamped on creation — locally at submit when the caller declared one, remotely when a delegate envelope adopts the wire's remainder — so a restarted node cannot re-mint quota the mesh already spent.

func (*TaskStore) SetVerification added in v0.1.2

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

SetVerification stamps the contract verdict on the task row. Empty clears it (a retried task starts without a verdict).

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) SettleExpired added in v0.1.0

func (s *TaskStore) SettleExpired(ctx context.Context, r ExpiredRow, selfNode string) (string, error)

SettleExpired gives one scanned row its expiry verdict.

A deadline expiry is terminal outright: the task's lifetime is over and no re-queue can extend it (running rows fail like a lease so the monitor kills the subprocess; anything earlier is marked expired — the distinction the 'expired' state exists to carry).

A lease expiry means the supervising executor stopped renewing — process dead, link partitioned, supervisor goroutine lost — while the work itself was never adjudicated. With retry budget left the row re-queues under a fresh attempt so the scheduler re-decides where it runs: a dead executor's task re-routes to a live peer instead of dying on the lease; a self-owned run re-runs locally and can resume its minted session. The persisted retry budget bounds the loop — once spent, the row fails exactly as before.

func (*TaskStore) SpendTokens added in v0.0.9

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

SpendTokens atomically bills n tokens against the task's remaining quota and returns what is left: 0 means the task is unbounded (legacy), a positive value is the spendable remainder, and -1 marks exhaustion. The decrement is a single UPDATE so a concurrent judge charge and adapter charge cannot both spend the same remainder; crossing zero lands on the -1 sentinel instead of wrapping back to "unbounded".

func (*TaskStore) StoreRowHeartbeating added in v0.1.0

func (s *TaskStore) StoreRowHeartbeating(ctx context.Context, nodeID string) bool

StoreRowHeartbeating reports whether nodeID's row in this store carries a live heartbeat, for callers that hold only a TaskStore — the engine-less panel and REPL send paths probe the store they actually post to, not a separately wired DB handle that an embedder may have left nil. The predicate is the package-level StoreRowHeartbeating.

func (*TaskStore) TaskActivityByDay added in v0.0.9

func (s *TaskStore) TaskActivityByDay(ctx context.Context) (map[string]int, error)

TaskActivityByDay counts tasks per local calendar day, keyed "2006-01-02". It backs the /heatmap usage view: one point per day a task entered the system, no matter how the task ended. The 'localtime' modifier keeps day boundaries where the operator perceives them — a task created at 23:58 belongs to today, not to tomorrow's UTC.

func (*TaskStore) TaskActivityByDayHour added in v0.1.0

func (s *TaskStore) TaskActivityByDayHour(ctx context.Context) ([]TaskDayHour, error)

TaskActivityByDayHour buckets task creations by local day AND local hour in one pass. The panel's usage endpoint needs both shapes from the same rows — a day series for the calendar and an hour histogram for "peak hour" — and two separate scans of the same table would be two chances to disagree.

func (*TaskStore) TaskMessages added in v0.0.11

func (s *TaskStore) TaskMessages(ctx context.Context, scope string) ([]TaskMessage, error)

TaskMessages returns every live slot on a scope board, oldest post first so a rendered board reads chronologically.

func (*TaskStore) TaskOutboxPending added in v0.0.11

func (s *TaskStore) TaskOutboxPending(ctx context.Context, taskID string) bool

TaskOutboxPending reports whether a parked outbox delivery exists for taskID — the "waiting for peer link" sub-state of a dispatched row: the task is not running anywhere, it is in this node's custody awaiting the target's next connect. Both dispatch (task_outbox) and approval (resume_outbox) custody count — a parked resume is the same parked delivery from the user's point of view. Callers that render task state use it to stop showing "dispatched" for work sitting in a mailbox.

func (*TaskStore) TaskStamps added in v0.0.10

func (s *TaskStore) TaskStamps(ctx context.Context) ([]TaskStamp, error)

TaskStamps lists the digest input for every task — the panel's SSE change detector calls this once per poll window instead of scanning the full task rows. Ordered by id so the digest is order-stable.

func (*TaskStore) TerminalSessionTasksWithoutEvent added in v0.0.10

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

TerminalSessionTasksWithoutEvent returns the terminal tasks that are linked to a session and lack an event of the given type — the exact set the panel's session finalizer turns into assistant turns. The finalizer runs every few seconds, and the former shape (load every task row, then load every task's full event timeline to look for the marker) re-read a board's worth of payloads on every pass, forever: already-summarized tasks never leave the terminal set. One NOT EXISTS probe per candidate — over the existing task_events(task_id) index — replaces it, and the marker type stays the caller's constant (the panel owns it).

func (*TaskStore) TryAcquireExecLocks added in v0.1.0

func (s *TaskStore) TryAcquireExecLocks(ctx context.Context, taskID, nodeID, runID string, keys []string) (bool, error)

func (*TaskStore) UserNotes added in v0.1.0

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

UserNotes lists the user's unconsumed notes on a task board, oldest first — what a console draws as the pending strip above its composer. Consumed notes are excluded: the round already folded them into a prompt, so there is nothing left to edit, drop, or promote.

func (*TaskStore) VerifyTaskEventChain

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

VerifyTaskEventChain verifies the per-task hash chain for taskID: every row's prev_hash links correctly, every signature verifies under the key this verifier trusts, and no unsigned row follows a signed one. It returns nil if the chain is intact, or an error describing the first break.

Two rules bind the signatures to a trust anchor rather than to themselves (P2-9 hardening):

  • Expected key: when the store knows this node's identity (the daemon's signing store, or a CLI store built by NewSigningTaskStore), a signature must be BY THAT KEY. Verifying against whatever key a row names would let anyone with DB write access re-sign the whole chain with a keypair of their own — the signature would prove "some key attested this", which is exactly what a forger can arrange.
  • No gap: once a signed row exists, every later row must be signed, so stripping signatures off the tail of the chain is detected. Rows recorded before this node ever had a key form a legacy unsigned prefix — there is nothing to check them against — but the boundary between the two may not move.

The residual is inherent to an in-DB anchor: a writer who rewrites the ENTIRE legacy prefix (or a database that never had a key) leaves nothing to contradict, which is why external notarization of the chain head stays on the roadmap.

Jump to

Keyboard shortcuts

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