delegate

package
v0.207.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 42 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

intent.go — the delegator-death durability half of the consolidated-queue decision (operator-approved Option A, 2026-08-27): each delegator PERSISTS its remote-dispatch intent before work leaves the box, and a later process RECOVERS results for jobs whose delegator died mid-poll. Push placement is unchanged — this is a ledger and one recovery path, not a queue inversion (Option B stays parked until real delegation volume argues for it).

The ledger answers exactly one question after a crash: WHICH job ids were acked by WHICH nodes and never observed reaching a terminal state? Everything else (contract bytes, placements, retries) stays where it always lived — the node still holds the job in its in-memory store, so recovery is one poll, not a re-run. A node that restarted loses that store; recovery then records the loss honestly instead of pretending.

File shape: <state-root>/delegate-intent.jsonl, append-only events —

{"e":"d","job":"agd-…","base":"http://…","goal":"…","ts":170…,"pid":1234}   acked dispatch
{"e":"ok","job":"agd-…","note":"…","ts":170…,"pid":1234}                     closed

Every event carries the unix second it was written and the pid of the process that wrote it (ADR 0064): the `ok` events used to carry neither, so the ledger could not say which process closed a job, or when. The close notes in use: "terminal observed" (this process saw the job end), "withdrawn" (the node confirmed the job was taken back before it started), "never started: …" (the node's own terminal record says it never ran the job — reaped, withdrawn, or marked never-started when the node shut down with it queued — read by a live poll or by the recovery pass), "recovered to …" (the recovery pass filed the result), "node no longer holds the job …", and "expired unrecovered after …".

A job is OPEN when its newest event is "d". Recovered results land as <state-root>/delegate-recovered/<job>.json for the operator (surfaced by a log line per recovery); the poll happened, the work is not lost.

lint.go — warn-at-intake acceptance lint (delegator-side, both surfaces).

Acceptance is the lane's verifiability gate: it decides failed_verification vs success AND whether the cross-seat retry fires. Three authoring pathologies, every one MEASURED in the standing corpus before this existed, let that gate pass garbage while reading as "verified":

  • shape-only — nonempty:/min_items: with no content check. Measured: "The docs directory does not exist" passed nonempty:summary; a seat once passed nonempty:q1 by echoing the questions back verbatim.
  • parrot-passable — every content check is ALSO satisfied by the goal text itself, so a model that repeats the question back passes the whole contract (and the retry that would have fixed the answer never fires, because nothing failed). Measured: 5/5 of the first organic contracts.
  • ungrounded — a contains:/regex: whose pattern appears nowhere in the contract's own context docs cannot distinguish a wrong answer from a defective contract. Measured: a contains: check on a name the context docs never wrote failed BOTH seats on a task both did right.

WARN-ONLY by decision: the lint never blocks, never changes placement or evaluation. It rides the response per-subtask (acceptance_lint) so the CALLER — usually a model mid-session — sees it beside the results and can fix the acceptance and resubmit. Blocking was rejected because a linted contract still produces a usable (if weakly verified) result, and because grounding is heuristic: an answer-side synonym for doc content is legal.

Kept in LOCKSTEP with the Python analyzer's A3 classifier (memory-frontier bench/seat-quality-pilot.py); change both or neither.

Package delegate is the DELEGATOR side of multi-node agent delegation (docs/specs/2026-08-16-multi-node-agent-delegation.md, §S3): it turns /fleet/health answers into NodeViews and decides PLACEMENT — which node runs a delegation contract — through the hard capability gate in gate.go. It performs no dispatch itself; the Phase T surfaces (MCP agent_delegate, the CLI verb) consume Place's decision and drive the fleet wire.

placement_reason.go: D-105 (PR-5 item 8, the operator's "one word why") — placement_reason names EVERY reachable remote considered for a subtask with a ONE-WORD verdict and the number behind it, so an operator reading one line can tell "the fleet chose correctly" from "this node was wrongly passed over" without re-deriving the gate by hand.

Vocabulary: chosen | queue | backlog | cap | slow | lease | cold | probe | private | hop | unfit(ctx) | noschema | layer. Each word names the FIRST reason (in the EXACT order gate.go's eligibilityVerdict checks it — see that function's own doc; the two are read-only narration over ONE predicate sequence and cannot diverge) a node is not the one running the subtask:

probe      AgentEnabled false, seat not resident/served on this node's
           cached roster, OR the node's health probe itself failed —
           three shapes of "this node did not prove it can serve the
           seat", the third one carrying the dial/cache detail
private    SF-40: the node is declared public in delegate_remote_classes and
           the contract is not public-data work (dataclass.go) - the
           detail names the door and the context documents that made it
           private
lease      leaseFenceReason: an exclusive or draining hold, or a busy
           lease that is not a plain text reservation (fenced — W-14)
noschema   the CONTRACT carries no output_schema — a subtask-level fact,
           true for every node alike, named once per node for symmetry
hop        the CONTRACT's depth != 0 (only an origin contract may
           travel — hop limit 1) — a subtask-level fact, like noschema
slow       feasibleFinal excluded it: one tool step and a minimal answer
           do not fit the contract's effective wall at its rate (W-05)
layer      a composite node's placement table refused or would wait
           (ADR 0052); detail is the table's own Reason
unfit(ctx) the contract's estimate + reserve does not fit the advertised
           ceiling
queue      saturated(): the node's own admission ceiling says the next
           dispatch is refused right now
backlog    ADR 0063: the node cannot START this contract inside the wait the
           caller gave it - printed as "backlog (a new job would wait ~444 s
           to start (<arithmetic>), past the 300 s this contract will wait
           for a start)". A placement FEASIBILITY refusal in the same class
           as slow (feasibleFinal), never a preference for a faster seat: the
           capacity wait re-reads the node every tick and asks it the moment
           its backlog fits
faulted    ADR 0096: every seat of the node this contract could run on sits on
           a card with a live driver-fault repeat (gpu_faults) - printed as
           "faulted (nvlddmkm 153 x5 on 65:00, last burst 10-11 10:05Z)".
           A demotion, never an exclusion: the node ran it when nothing
           better was left
cap        W-06: this DEAL has already committed as many subtasks to the
           node as its headroom (max_concurrent_jobs − jobs_running)
           allows — printed as "cap (running/max running, headroom N,
           dealt N)"
cold       eligible, has headroom, not saturated — simply outranked by a
           better candidate (W-11's ranking), named "cold" because the
           overwhelmingly common reason one otherwise-adequate seat loses
           to another is a worse (colder/slower) expected completion
chosen     the one that ran it, with its own eta breakdown

This file never changes ELIGIBILITY — it is a read-only narration over gate.go/fit.go/eta.go's existing decisions, called after placement, not consulted by it. The `eligible`/`word`/`detail` triple for every EXCLUDING reason comes from gate.go's eligibilityVerdict, the SAME function remoteEligible calls — this file adds only the RANKING-based words (queue/cap/cold) for a node eligibilityVerdict already admitted.

queue.go — the delegator side of the Option B pull queue (ADR 0030, dark by default): route:"queue" SUBMITS every subtask to the config-elected holder and polls the holder for results; which NODE runs each job is the claim loops' decision, not the delegator's. Durability is the holder's (bbolt), so this route deliberately does not write the push path's intent ledger — a delegator that dies mid-poll re-polls the holder, which still has both the job and its result.

withdraw.go — the delegator's half of taking an unstarted job back from a fleet node (ADR 0064): where runRemote gives an acked job up, it asks the node to withdraw it (DELETE /fleet/jobs/{id}). Only a CONFIRMED withdrawal changes what the delegator does next; every other answer leaves today's behaviour as it was — but says, on the row, what the node answered instead.

Index

Constants

View Source
const (
	// PinPrivacy: the material may not leave this box (credentials, unreleased or brand-isolated data). Local only.
	PinPrivacy = "privacy"
	// PinLocality: the work needs something only this box has (a local service, files the contract cannot carry
	// inline, this box's own seat as the thing under comparison). Local only.
	PinLocality = "locality"
	// PinMeasurement: the call measures a specific place (a benchmark, a bake, a seat A/B). Local or remote.
	PinMeasurement = "measurement"
	// PinOperator: the operator named this placement for this call. Local or remote.
	PinOperator = "operator"
)

The closed set of pin reasons (ADR 0078). A reason says why a caller may not let placement choose.

View Source
const (

	// MaxSubtasks is the same bound, exported for callers that size a call against RunWith's.
	MaxSubtasks = maxSubtasks

	// MaxBatchSubtasks is the same bound, exported for callers that batch (RunBatched).
	MaxBatchSubtasks = maxBatchSubtasks
)
View Source
const (
	RanOnLocal = "local"
	RanOnNode  = "node"
)

The values of ResultWire.RanOn.

View Source
const DefaultQuarantineTTL = 30 * time.Minute

DefaultQuarantineTTL: long enough to keep one bad node out of a working session's remaining runs, short enough that a node fixed mid-day comes back without a restart.

View Source
const ForecastTask = "forecast"

ForecastTask is the fleet task_type of the forecast lane: a node lists it in supported_task_types only when it binds a forecast_model and the lane is safely reachable (fleetnode.ForecastLaneAdmissible).

View Source
const MediaRouteConfigured = "CONFIGURED"

MediaRouteConfigured is the state string of a route that can run right now.

View Source
const STTUploadTask = "stt-upload"

STTUploadTask is the fleet task_type of the stt upload door (ADR 0072): a node lists it in supported_task_types when its whisper model is bound and the door is safely reachable (fleetnode.STTUploadAdmissible). The legacy "stt" task, which every node with a whisper model lists, takes only a path on the NODE's disk and cannot be sent bytes.

View Source
const TextTask = "text"

TextTask is the fleet task_type of the text lane (0.154.0): a node lists it in supported_task_types only when its tier declares text tasks (config text_tasks) and the lane is safely reachable (fleetnode.taskConfiguredFor).

View Source
const VisionTask = "vision"

VisionTask is the fleet task_type of the vision lane (0.116.0): a node lists it in supported_task_types when its vision_model is bound and the lane is safely reachable (fleetnode.taskConfiguredFor).

Variables

View Source
var ErrCallDeadline = errors.New("call deadline reached")

ErrCallDeadline is the cause the call's context carries when the whole-call deadline passed (context.Cause), so an error that wraps it names the deadline. It is a label, not the gate: whether an outcome is the deadline's is decided by the clock (callDeadline.reached) at the moment the outcome is produced. A caller that cancels for any other reason before the deadline — the client going away, a test tearing down — is NOT the call deadline: reached() is false, and its subtasks report their own "canceled" outcomes exactly as before.

Functions

func BrokenStackDefer

func BrokenStackDefer(class string) bool

BrokenStackDefer reports whether a defer_class means an OPERATOR, not a bigger model, has to act: the stack failed (infrastructure) or the node/config combination can never work as configured (config). An empty class — a pre-0.65 node, which cannot classify — is deliberately NOT broken: assuming the worst about an older peer would fail every mixed-version fleet.

core.DeferClassContract is explicitly NOT a broken stack. It was split out of `config` for exactly this line: three of the placement gate's five conditions are properties of the CALLER'S CONTRACT (no output_schema — legal per Validate; a non-origin depth; a token estimate no advertised ceiling can hold), and lumping them in here made `--route remote` exit non-zero, on a run where every node was healthy, with a message telling the delegating model a node was broken or misconfigured. Nobody has to touch a box to fix those.

func CanonicalRosterRemotes

func CanonicalRosterRemotes(cfg config.Config, named []string) ([]string, error)

CanonicalRosterRemotes is CheckRosterRemotes that also hands back what it accepted: each entry spelled as the roster spells it, in the order the caller named them, a node named twice (or in two spellings of one base) kept once.

The respelling is not cosmetic. The check compares entries loosely (case, a trailing slash), but everything after it keys a node by the string it was given: the process-wide in-flight gate (processGate) counts open dispatches per dial base, and "http://Node-A:18811/" and "http://node-a:18811" would be two bases for one node, each admitted up to the node's ceiling, so a model that spelled the roster's node differently could hold twice the in-flight limit the node's admission was sized for. With the roster's own spelling, one node is one key. An empty named list returns nil (the roster is used as configured).

func CheckPinReason

func CheckPinReason(route, reason string) error

CheckPinReason refuses a pin_reason that is not in the closed set, one given with the wrong route, and one given with a route that is not a pin at all, before any placement is made. route is the call's route after its door's default ("" is auto). An empty reason is always fine here: whether a bare local or remote is a hint is the door's business (RunOptions.PinNeedsReason), not a validation error.

The error lists the valid set, because a model that guesses a reason needs the list and not a bare refusal. The MCP doors and the CLI verbs call it before they spend anything (a research call's page fetch, a delegate call's context_paths reads), and runWith calls it again as the engine's own guard.

func CheckResearchPinReason

func CheckResearchPinReason(reason string) error

CheckResearchPinReason refuses the pin reasons that cannot be true of a research call: its pages are public (the fetch refuses non-public hosts) and travel inline in the contract, so neither the material (privacy) nor the work (locality) is tied to this box. measurement and operator stay valid. Both research doors call it after CheckPinReason.

func CheckRosterRemotes

func CheckRosterRemotes(cfg config.Config, named []string) error

CheckRosterRemotes is the rule for the doors where a MODEL names the remotes of a call (the MCP agent_delegate tool): the list may only NARROW the configured fleet, never add a node to it. Every entry must be one of cfg.DelegateRemotes, and a box that configures none accepts none.

Fleet membership is configuration: the operator lists the nodes this box delegates to in delegate_remotes, and a node that is not listed is not part of the fleet. A call's own list already REPLACED the roster rather than merging with it (so one node can be targeted deliberately), and before this rule the only check on an entry was its SHAPE (netguard.TailnetURL: loopback, the tailnet's address range or zone, a dotless name). Any tailnet host therefore passed, and was dialled, with the fleet's bearer token on its health read; the operator's standing rule that a box never delegates to the standalone machine, and is never a delegator for it, held by habit alone. A caller-named URL outside the roster is now refused with a message that says why, before anything is dialled.

An entry is compared as the roster spells it, without a trailing slash and without regard to case ("http://Node-A:18811/" is "http://node-a:18811"); a node the roster lists by address is not reachable under another name for it, because the roster is what the operator vetted.

The operator's own CLI verbs (`delegate --remote`, `fleet-smoke --remote`) keep naming any tailnet node, which is how a node that has not joined the roster yet is smoke-tested: the engine applies this rule only when RunOptions.RosterOnly says the list came from a model.

func CheckSubtaskCount

func CheckSubtaskCount(n int) error

CheckSubtaskCount is the subtask cap of a plain call (MaxSubtasks, 8) read off the number of subtasks the caller SENT: the same refusal, in the same words, RunWith gives for a call over the cap. A surface that prepares subtasks one by one calls it first, so that a call of nine with one bad subtask is refused for its size, as a call of nine good ones is.

func DefaultTenant

func DefaultTenant() string

DefaultTenant is the tenant id a delegator process identifies itself with when the caller supplies none: host, pid and the process start second — one MCP server (one Claude session) or one CLI invocation is one tenant, which is the granularity the node's round-robin exists for. LOCAL_OFFLOAD_TENANT overrides it (a gate script emulating K sessions names them).

func EstimateTokens

func EstimateTokens(c core.AgentContract) int

EstimateTokens is the v1 token ESTIMATE for a contract: ceil(chars/3) over every part the remote node will hold in context — goal, each context doc (name AND text: both are materialized for the sub-agent to read), the raw output schema bytes (echoed into the constrained final step), and each acceptance string (echoed to the sub-agent).

WHY chars/3, stated honestly (roast delta 5 requires the label): this is a DELIBERATE conservative bound, not a tokenizer. The house lesson is "tokenize, don't estimate" — chars/4 was measured 2x off on Gemma — but at placement time v1 has no remote tokenizer to ask, so the estimate leans the safe direction instead: /3 overshoots typical English prose (~4 chars/token ⇒ ~33% inflation), and the cases where even /3 undershoots (tokenizer-dense content) are backstopped by specReserve's padding and the 12-step remote cap. It is used ONLY as an upper-bound GATE — never to claim a fit — and a real-tokenizer count replacing it is the recorded v2 upgrade.

The arithmetic lives in placetable.EstimateTokens since ADR 0052 so the delegator, the placement table and the node size a contract identically; this is the delegate's name for it.

func EvalAcceptance

func EvalAcceptance(contract core.AgentContract, wire core.AgentWireResult) []string

EvalAcceptance runs every contract acceptance check against the result — DELEGATOR-side, before merge (roast delta 3). An unparseable check fails closed with the parse error as the failure: Validate should have caught it, and an unmet precondition is a failed check, never a skipped one.

Exported (package-private until askjob) so the single-seat offload_ask lane, which runs its contract through Pipeline.RunAgentContract instead of delegate.Run, evaluates acceptance by the SAME rules rather than a second copy of them. An acceptance check nothing evaluates is decoration.

func EvalAcceptanceGraded

func EvalAcceptanceGraded(contract core.AgentContract, wire core.AgentWireResult) (failures []string, closedAt core.Authority)

EvalAcceptanceGraded is EvalAcceptance plus the authority the contract closed at, from the same grading (so the two cannot disagree about what passed). closedAt is core.ClosedAt over the graded checks: the weakest authority among them, and only when every check passed. It is stated only for a result that was accepted whole: any failure (an unknown, a list-fidelity failure included), a check that was excused instead of passed, and a single unqualified check all leave it core.AuthNone, which says nothing. A weaker authority never closes a stronger claim, so a contract mixing a grounded check with an answer check closes at answer, and one that also carries a plain check closes at none.

func Fenced

func Fenced(info gpulease.Info) (bool, string)

Fenced reports whether a lease REFUSES A NEW RUN on the local seat, and names the fence for the note that has to explain it. It is the placement-side reading of modelaffinity.BlocksNewRun — the admission rule the run would meet — and it delegates to that function rather than restating it, so the two can never drift into a placement that dials a seat its own gate will refuse.

Three holds fence: an EXCLUSIVE text lease (the holder cleared the cards and a model loaded now would land on top of a measurement), a DRAINING text lease (the seat is cordoned while in-flight work finishes), and a MEDIA lease (a render owns the VRAM). A plain text reservation does NOT fence: it steers placement (Reserved) but the affinity gate still admits the load, so treating it as a fence here would refuse work the box can actually do.

Fenced is what a RETRY must consult. Register D-94 (2026-09-14): a retry was placed on the local seat under an exclusive lease, waited the whole `gpu-lease timeout after 5m0s` at the cordon and deferred as capacity, while an idle remote sat unused. The verdict was on disk before the dial.

A retry asks Reserved after Fenced as well (register C-81), for the one hold Fenced leaves alone: a plain reservation does not refuse a run at the gate, but a first placement on route auto or spread never takes the seat under one, and neither may a retry.

With card-scoped leases the question is asked of each live lease (Info.Each) and the reason names the first one that fences.

func FencedFor

func FencedFor(info gpulease.Info, pins []string) (bool, string)

FencedFor is Fenced asked on behalf of a seat on the cards pins name.

func FinalToolCallDefer

func FinalToolCallDefer(r core.AgentWireResult) bool

FinalToolCallDefer reports whether a result is the forced-final tool-call defer: a `budget` defer whose reason carries core.ForcedFinalToolCallReason, i.e. the run reached its last step, which offers no tools and asks for the answer, and the seat wrote a tool call instead, again after the loop re-asked it once with the offence quoted.

It is the fifth defer worth a second placement, and for the same reason as the seat-down one: the fault is a property of THIS seat (one seat family did it in 35 of 106 forced finals; the seats of every other family in none of 241) and the contract is sound, so the same contract on another node is the cure. Unlike a plain step-budget defer (a task too large, which another seat does not fix), the run had read what it needed and its wall was mostly unspent. It is a node-filed defer, an OBSERVED terminal, so nothing still runs the contract. It matches on the CONSTANT the loop writes (the phrase sits behind the "step budget exhausted (N steps): " grep key, so Contains and not HasPrefix), never on other prose.

func ForeignFence

func ForeignFence(info gpulease.Info) (bool, string)

ForeignFence is Fenced asked on behalf of a caller that is NOT the holder: true only when the fence would refuse THIS process's next run. It exists because "the seat is fenced" and "the seat is fenced against me" are different questions, and a lane that routes work off the box must ask the second one.

The holder's own child is exempt for exactly the reason Reserved documents: `gpu reserve --drain --unload-seat -- <session>` runs the delegate under GPU_LEASE_EPOCH, and the measured work the lease was taken FOR must keep running on the cards it cleared — routing it to a fleet node would defeat the reservation. The epoch is compared, never presence-checked, so a stale variable from a lease since handed on exempts nothing.

Register D-110: offload_review_diff built its local loop unconditionally, so a review under a peer's lease waited the whole cordon bound and was filed as a capacity defer for the lease's entire length. The verdict was on disk before the dial — the same sentence D-94 wrote about the retry path.

The exemption is PER LEASE. With card-scoped leases several are live at once; a child of lease A is exempt from A's fence and from no other lease's, so one device lease's child cannot walk through the fence another lease holds on other cards. (Until the consumers compare device sets, plan P4, a foreign lease fences whatever its cards: over-fencing, never under-fencing.)

func ForeignFenceFor

func ForeignFenceFor(info gpulease.Info, pins []string) (bool, string)

ForeignFenceFor is ForeignFence asked on behalf of a seat on the cards pins name.

func GradeAcceptance

func GradeAcceptance(contract core.AgentContract, wire core.AgentWireResult) []core.AcceptanceOutcome

GradeAcceptance is EvalAcceptance's per-check reading: one outcome per acceptance string, in order, each pass, fail or unknown, with the authority the check demanded. It is the same grading EvalAcceptance runs (gradeCheck), without the document-fingerprint excuse and the list-fidelity read that EvalAcceptance adds, so it is the raw verdicts. The authority a contract closed at, as the delegator publishes it, is EvalAcceptanceGraded's: it applies the excuse and the fidelity read before it states one, which core.ClosedAt over these raw outcomes does not.

func HolderLine

func HolderLine(info gpulease.Info) string

HolderLine names a lease holder for a placement reason: class, pid, the reason/origin the holder stamped (when it did), and the expiry — what the deferred caller needs to decide whether to wait, route elsewhere, or ask.

func HonestAbsence

func HonestAbsence(structured json.RawMessage) bool

HonestAbsence reports whether a structured digest makes no claim about any document: it is an object, and every string in it, at any depth (a list entry as much as a field), is empty or is a short statement that the page does not carry what was asked ("not on page", "the page does not address it", "not documented in this text"), with at least one such statement. A number or a boolean is a claim, so is any other sentence, and so is a statement of failure to read the file. An absence says nothing about any document, so it cannot be about the wrong one; a digest that says anything else is judged as it always was.

It reads STRUCTURE (the decoded fields), never the loop's prose and never a phrase somewhere in a text: one stock phrase beside a claim does not make the claim an absence, and the goal echoed back as a field is far over maxAbsenceWords.

func IncoherentSeatDefer

func IncoherentSeatDefer(r core.AgentWireResult) bool

IncoherentSeatDefer reports whether a result is the admission-time coherence defer: an `infrastructure` defer whose reason carries core.IncoherentSeatReason, i.e. the executing node asked its freshly loaded seat one bounded question and the seat answered with the NaN shape (a run of one repeated byte, an unparsable tool call, or nothing at all at the cap with no hidden reasoning reported), or the same verdict remembered about a seat it already caught.

It matches on the CONSTANT the producer writes, never on prose: pipeline (and the MCP door) build the reason from core.IncoherentSeatReason, so the two sides cannot drift. A pre-D-118 node never emits it and is unaffected.

Why it is worth a retry when no other infrastructure defer is: the contract spent seconds, not its wall, and the fault is a property of THIS seat — the same contract on another node is the cure, and re-placing it is the whole reason the probe fires before the wall instead of after it.

func InlineContextPaths

func InlineContextPaths(paths []string, readRoot string) ([]core.ContextDoc, error)

InlineContextPaths reads each path into a ContextDoc named by its base name. Containment follows the house idiom (internal/agent ReadOnlyTools): OS-ENFORCED via os.Root — `..`, absolute escapes, and reparse points (symlinks / Windows junctions) are rejected by the kernel-level traversal, failing CLOSED. An absolute path is first re-rooted via filepath.Rel so a caller may name files either way; anything that lands outside readRoot is a hard error, never a silent skip.

Exported (it was package-private until askjob) because it is the ONE delegator-side confined reader: internal/askjob needs the same os.Root containment and the same per-file cap, but owns its own doc NAMING (it de-collides duplicate base names instead of letting Validate reject the pair), so it cannot go through PrepareContract's context_paths. A second reader would be a second place to get containment wrong.

func LeaseForContract

func LeaseForContract(cfg config.Config, info gpulease.Info, c core.AgentContract) gpulease.Info

LeaseForContract narrows a read of the local lease to what stands between a contract and a local seat (plan P4): the delegator is busy for a contract only when EVERY local agent seat it could run on sits on a held card, because the placement table falls back to the next layer whose cards are free. The seats are placement.AgentChain's, the same list the table walks, so the two cannot disagree. A contract that names its layer is asked of that layer's seat alone. The result is the first seat's leases when every seat is held (the holder a defer names), and the zero Info as soon as one seat is free of every lease.

Unchanged, whole-node: a box that declares no layers, a long-context contract (it runs on a long seat the agent chain does not describe), and a contract no agent seat's window can hold. Nothing narrows on a guess.

func LintAcceptance

func LintAcceptance(c core.AgentContract) []string

LintAcceptance returns human-readable warnings for the measured acceptance pathologies. Empty slice = nothing to warn about. Unparseable checks are skipped here — Validate already rejects them upstream with a hard error, and double-reporting would drown the lint's signal.

func LocalBusy

func LocalBusy(gpuLockPath, stateDir string) bool

LocalBusy reports whether the machine-wide GPU lease is currently held — either class: a media render in flight or a text reservation both mean the local GPU is spoken for, which is Place's trigger for considering remotes.

Mechanism (deliberately the LEAST invasive one gpulease offers): resolve the lease dir through gpulease.LeaseDir — THE one resolver; a second resolution order is how the lease silently splits, per docs/systems/gpu-lease.md — then read it with gpulease.InspectDir, the read-only inspection path built for consumers that do not own a Manager (the vision gate uses the same one). No Manager is opened (Open probes writability and mkdirs), nothing is acquired, no epoch is bumped: a placement probe must never CONTEND for the card it is asking about. InspectDir already applies the full reclaim rule, so a crashed holder's stale lease reads as not held.

gpuLockPath/stateDir are the config's gpu_lock_path/state_dir, threaded by the caller (the plan sketched a zero-arg LocalBusy, but resolving the lease dir WITHOUT the config's overrides would re-create the split-lease defect on any box that sets them). Any resolution failure reads as NOT busy: Place then keeps the work local, which is always the safe placement.

func LocalBusyFor

func LocalBusyFor(gpuLockPath, stateDir string, pins []string) bool

LocalBusyFor is LocalBusy asked on behalf of a seat on the cards pins name: true only when a live lease sits on one of them. A render on card 2 leaves the card-0 seat idle; an unknown pin is every card, so the answer is LocalBusy's.

func LocalLease

func LocalLease(gpuLockPath, stateDir string) gpulease.Info

LocalLease is LocalBusy's underlying read: the machine-wide lease's Info, resolved and inspected exactly as LocalBusy documents (never acquired, never contended). Any resolution failure returns the zero Info — Held=false, the same fail-toward-idle direction. Callers that need the CLASS or the holder (Reserved, the wait/defer path in run.go) use this; a caller that only asks "is the card spoken for?" keeps the boolean.

func LocalLeaseFor

func LocalLeaseFor(gpuLockPath, stateDir string, pins []string) gpulease.Info

LocalLeaseFor is LocalLease narrowed to the leases that sit on the cards pins name (a layer seat's Device, split by DeviceList): a render on card 2 is not a lease on the card-0 seat. No pins is an unknown seat, which is every card, so the answer is LocalLease's.

func NodeReported

func NodeReported(pr PlacedResult) string

NodeReported is the id the executing node stamped on its own result, when that differs from the node the placement used (pr.Node); "" otherwise. See ResultWire.NodeReported.

func PinReasons

func PinReasons() []string

PinReasons is the closed set of pin_reason values, in the order the tool schemas list them.

func PlaceForecast

func PlaceForecast(remotes []NodeView) (int, bool)

PlaceForecast picks the fleet node that runs ONE forecast when the caller has decided the work leaves the box (route remote, or route auto on a box with no forecast model or a blocked card). It is PlaceText with the forecast lane's gate: the node must ADVERTISE the lane (ServesForecast; an older node is never a target) and its card must not be spoken for. Ranking is betterRemote; the return is the INDEX into remotes.

func PlaceSTT

func PlaceSTT(remotes []NodeView, hq bool, size int64) (int, bool)

PlaceSTT picks the fleet node that transcribes ONE uploaded audio file (the stt upload door, ADR 0072) when the caller has decided the work leaves the box (route remote, or route auto while the local whisper admission would block). It is PlaceVision with the door's own gate: the node must ADVERTISE the door (ServesSTTUpload: an older node lists only the legacy path-taking "stt", which cannot be sent bytes, so it is never a target), have an hq model when hq is asked, take a file this size (size bytes against its published cap), and have a card that is not spoken for (the same LeasedText / LeaseBusy refusals). Ranking is betterRemote, as for vision, and the return is the INDEX into remotes, for the same reason.

func PlaceText

func PlaceText(remotes []NodeView, task string) (int, bool)

PlaceText picks the fleet node that runs ONE text task (classify / extract, 0.154.0) when the caller has decided the work leaves the box (route remote, or route auto on a busy local card). It is PlaceVision with the text lane's own gate: the node must ADVERTISE the lane and list THIS task in text_tasks (ServesTextTask: no list means no lane, never "all", so an older node is never a target), and its card must not be spoken for. Ranking is betterRemote, as for vision; the return is the INDEX into remotes, for the same reason.

func PlaceVision

func PlaceVision(remotes []NodeView, task string) (int, bool)

PlaceVision picks the fleet node that runs ONE vision task (vqa / ocr / assess_image, 0.116.0) when the caller has decided the work leaves the box (route remote, or route auto on a busy local card — that decision is the caller's, exactly as localBusy is Place's caller's). It returns ok=false when no remote is eligible; the caller then defers (route remote) or runs local (route auto) — never a silent local run under route remote.

Eligibility is the vision lane's own gate, not the agent lane's: the node must ADVERTISE the lane (ServesVision — an older node never does, so it is never a target), it must serve THIS task (ServesVisionTask — a node that publishes no vision_tasks serves all three, so an older node stays eligible for every task; one that lists a subset is skipped for the rest), and its card must not be spoken for (the same LeasedText / LeaseBusy refusals remoteEligible applies: a reserved card is a non-target whatever the lane). AgentEnabled, residency, ctx arithmetic and the output_schema rule are agent-contract facts and do not apply to an image.

Ranking reuses betterRemote — not-saturated, then a provably free slot, then (W-11) a queue-wait tie-break, then queue depth, then GPU utilization, ties in roster order — so a vision placement and an agent placement agree on which of two nodes is the less loaded one. The seed for W-11's P2C draw is minted once per call (PlaceVision carries no wire job id of its own to thread through — visionremote's caller is outside this PR's scope): the property the draw needs is only that independent CALLS disagree, which a fresh seed per call already gives it.

It returns the INDEX into remotes rather than the view, so a caller that holds a parallel slice of base URLs (a NodeView carries no address) can dispatch to the node it chose without matching on node_id — two misconfigured nodes can share one id, and an id is not an address.

func PrepareContract

func PrepareContract(spec SubtaskSpec, readRoot string) (core.AgentContract, error)

PrepareContract turns a SubtaskSpec into a dispatchable core.AgentContract: it MINTS schema_version and depth (the surface IS the origin — a caller claim of either is overwritten, never trusted), applies the same MaxSteps/TimeoutSec ceilings DecodeAgentContract applies on the wire (so a locally-run contract obeys the same rules as a dispatched one), inlines context_paths under readRoot confinement, then runs the full Validate — fail before the network, exactly like the wire decoder's posture. It validates at the plain transport cap (core.AgentContextMaxBytes); a surface on a composite box passes its own cap through PrepareContractWithCap.

func PrepareContractWithCap

func PrepareContractWithCap(spec SubtaskSpec, readRoot string, capBytes int) (core.AgentContract, error)

PrepareContractWithCap is PrepareContract validating the inline context at capBytes — config.AgentContextCapBytes() for the box the surface runs on (ADR 0052): 256 KiB on a plain box, the largest layer window × 3 on a composite one. Without it a contract sized for the long seats is refused at the door before placement can ever choose them, and both long seats are dead code. capBytes ≤ 0 reads as the plain cap (ValidateWithCap's rule): an unset cap never admits an unbounded context.

func RecoverOrphans

func RecoverOrphans(ctx context.Context, cfg config.Config) (int, error)

RecoverOrphans polls every still-open intent once and files what it finds. Returns how many results were recovered to disk. Exported for tests and for any future operator surface; the automatic trigger is maybeRecoverOrphans.

func Reserved

func Reserved(info gpulease.Info) bool

Reserved reports whether info is a held TEXT-class lease: a benchmark, eval or measured run has reserved the cards (`gpu reserve --class text`), so the local seat is not a placement target at all for route auto/spread — not merely a less-preferred one. Before 0.113.14 a held lease only steered placement toward a remote and the contract still ran locally when no remote qualified, which is exactly how three foreign contracts loaded a reserved two-card seat mid-measurement (2026-09-05 08:04–08:09).

A media holder is deliberately NOT "reserved" here. Renders are arbitrated at the model-affinity gate (ADR 0026), which waits for the render and then admits the load; turning that into a placement defer would change every single-box render for no measured reason. Media keeps steering (LocalBusy) and nothing more.

An INHERITED lease exempts the caller, exactly as the affinity gate's rule (modelaffinity.gpuwait): `gpu reserve --class text -- local-offload delegate …` runs the delegate as the holder's child with GPU_LEASE_EPOCH set, and the holder's own measured work must not be refused by its own reservation. The epoch is compared, never presence-checked, so a stale variable from a lease since handed on exempts nothing; the holder's PID is deliberately not an exemption (the MCP server holds leases and serves foreign calls in one process).

Asked of EACH live lease (Info.Each): with card-scoped leases several are live at once, Info describes only the lowest, and the exemption is per lease.

func ReservedFor

func ReservedFor(info gpulease.Info, pins []string) bool

ReservedFor is Reserved asked on behalf of a seat on the cards pins name.

func RootGoneDefer

func RootGoneDefer(r core.AgentWireResult) bool

RootGoneDefer reports whether a result is the lost-root defer (register C-79): an `infrastructure` defer whose reason carries core.RootGoneReason, i.e. the run's own file tools could not open the workspace root the executing node materialized for it, and the loop ended the run instead of letting the seat answer from nothing.

It is the FOURTH infrastructure defer worth a retry, after the two admission-time ones (IncoherentSeatDefer, SeatWarmFailedDefer) and the seat-down defer (SeatDownDefer), and for the same kind of reason: the fault is a property of THAT run's directory, the contract is sound, and the same contract placed on another node materializes a root of its own. It is safe to re-place because a node-filed defer is an OBSERVED terminal: the node reported it, so nothing is still running the contract.

It matches on the CONSTANT the producer writes (pipeline.rootGoneReason builds the reason from core.RootGoneReason), never on prose, and on the prefix only: the same words in another class, or in the middle of another reason, are not it. A node without C-79 never emits it and keeps filing the same fault as the seat's failed answer, which is retried as a verification failure as before.

func Run

func Run(ctx context.Context, cfg config.Config, local LocalRunner, subtasks []core.AgentContract, route string, remotes []string) ([]PlacedResult, Summary, error)

Run is RunWith without options — the signature every existing caller uses.

func RunBatched

func RunBatched(ctx context.Context, cfg config.Config, local LocalRunner, subtasks []core.AgentContract, route string, remotes []string, opts *RunOptions) ([]PlacedResult, Summary, error)

RunBatched runs contracts in order as ONE joint deal of up to MaxBatchSubtasks (16), and a longer list as consecutive deals of that size (ADR 0076). offload_research builds ONE contract per usable page and allows 12 URLs per call, so a 9–12-page call hit Run's 8-subtask refusal and every page was lost (2026-09-01, three sessions); the fix cut it into chunks of eight and ran them SEQUENTIALLY, which left chunk two waiting on the slowest page of chunk one and a 12-page call using at most four of the fleet's slots. The whole list is now dealt at once, across every node, and sized by that deal (dealParallelism): the bound the sequential chunks kept, that a burst cannot stampede a GPU, is the node's published ceiling and the local seat's run-cap line, both of which the deal counts. Results come back in input order; Summary counters are summed; the first error is returned WITH the results collected before it, so a caller can render the partial work.

func RunWith

func RunWith(ctx context.Context, cfg config.Config, local LocalRunner, subtasks []core.AgentContract, route string, remotes []string, opts *RunOptions) ([]PlacedResult, Summary, error)

RunWith is Run with caller-owned options (see RunOptions). It refuses more than MaxSubtasks (8) subtasks, which is the bound of the MCP door (agent_delegate) and of the CLI verb; RunBatched is the entry that lifts it.

func SchemaMissRescuable

func SchemaMissRescuable(w core.AgentWireResult) bool

SchemaMissRescuable reports whether a wire result is a finished answer whose structuring failed, and so worth re-packing on the delegator: a defer that carries the loop's complete answer and no structured object. A node that publishes SchemaMiss says so; one that predates the flag (0.140.x) is read from what it always sent: the loop ended `done`, and the defer's reason is a re-pack failure. A cut answer (output_truncated) is never rescuable — a partial cannot be re-packed into the whole object — and neither is a defer whose reason says the CALLER's context ended.

func SeatDownDefer

func SeatDownDefer(r core.AgentWireResult) bool

SeatDownDefer reports whether a result is the seat-down defer (ADR 0066, register C-72): an `infrastructure` defer whose reason carries core.SeatDownReason, i.e. the executing node's seat went down under the run — the engine hung with work outstanding, or died and llama-swap no longer serves it — and the node's own bounded wait and one re-issue did not bring it back.

It is the THIRD infrastructure defer that is worth a retry, after the two admission-time ones (IncoherentSeatDefer, SeatWarmFailedDefer), and for the same reason: the fault is a property of THIS seat and the contract itself is sound, so the same contract on another node is the cure. It is safe to re-place because a node-filed defer is an OBSERVED terminal — the node reported it, so nothing is still running the contract (the "never re-place after a 202" rule is about jobs whose outcome nobody observed). It matches on the CONSTANT the producer writes, never on prose. A node without ADR 0066 never emits it, and keeps emitting `stalled:` for the same outage until it is upgraded — for such a node this changes nothing.

func SeatWarmFailedDefer

func SeatWarmFailedDefer(r core.AgentWireResult) bool

SeatWarmFailedDefer reports whether a result is the admission-time warm-up defer: an `infrastructure` defer whose reason carries core.SeatWarmFailedReason, i.e. the executing node's warm request was refused with a server error and there was positive evidence the seat's process did not start (a busy answer, a seat that reads starting or another model mid-swap never produce it). Like the coherence defer it is a property of THIS seat, was caught before the wall started, and is cured by the same contract on another node.

func WithRescueOrigin

func WithRescueOrigin(ctx context.Context, o RescueOrigin) context.Context

WithRescueOrigin returns ctx carrying o for a RescueFunc to read. The RescueFunc signature is unchanged, so every door that wires a rescue keeps working, and one that ignores the origin is exactly the rescue it always was.

Types

type ImageRecipeFileView

type ImageRecipeFileView struct {
	Role        string `json:"role"`
	Name        string `json:"name"`
	Bytes       int64  `json:"bytes"`
	Fingerprint string `json:"fingerprint"`
}

ImageRecipeFileView is one weight file of a recipe: its role, its name, its size on the node (-1: not found there) and its content fingerprint (a sha256 in hex, "pending" while the node is still hashing it, "unreadable", or "" for a file that is not there or a node that predates the field: only a hash is an identity).

type ImageRecipeView

type ImageRecipeView struct {
	Name          string                `json:"name"`
	Default       bool                  `json:"default"`
	Digest        string                `json:"digest"`
	Engine        string                `json:"engine"`
	Graph         string                `json:"graph"`
	Files         []ImageRecipeFileView `json:"files"`
	Preset        string                `json:"preset"`
	Steps         int                   `json:"steps"`
	CFG           float64               `json:"cfg"`
	Sampler       string                `json:"sampler"`
	Scheduler     string                `json:"scheduler"`
	Schedule      string                `json:"schedule"`
	Shift         float64               `json:"shift"`
	LoRAStrength  float64               `json:"lora_strength"`
	License       string                `json:"license"`
	CommercialUse *bool                 `json:"commercial_use"`
	Explicit      []string              `json:"explicit"`
}

ImageRecipeView mirrors fleetnode.ImageRecipeHealth (and the mediacap.Recipe embedded in it): one ComfyUI image binding a payload's `family` can select, and what it is. Mirrored here, not imported, as MediaRouteView mirrors its row, so the delegator's decoder stays free of the media packages.

type IntakeRejection

type IntakeRejection struct {
	Index int
	Err   error
}

IntakeRejection is one subtask the intake refused: Index is its position in the call's input, Err the reason PrepareContractWithCap gave.

type Kind

type Kind int

Kind is the coarse shape of a contract.

const (
	// KindMechanical is extraction, listing, counting, filtering, digesting —
	// work whose answer is IN the material and needs no chain of inference. It
	// is also the DEFAULT for a goal no rule matches (see matchShape).
	KindMechanical Kind = iota
	// KindReasoning is explanation, causation, cross-file interaction, tracing,
	// comparison — work that needs the contract held in mind at once.
	KindReasoning
)

func (Kind) String

func (k Kind) String() string

type LeaseView

type LeaseView struct {
	Epoch uint64
	Class string
	// Devices are the cards the lease sits on, as lower-cased GPU UUIDs. Empty is the whole
	// node, and every reader must take it as every card.
	Devices []string
	// Scope says where Devices came from: declared, inferred or whole-node.
	Scope string
	// Until is the declared term end; the zero Time when the lease declares none.
	Until        time.Time
	RemainingSec int
	Busy         bool
	Overdue      bool
	Exclusive    bool
	Draining     bool
	Orphaned     bool
	Stalled      bool
	// Verdict is the node's one word for what the lease is doing (held, held-stalled,
	// held-orphaned, held-overdue).
	Verdict string
}

LeaseView is one live lease of a node, as its health leases[] publishes it.

type LocalOptions

type LocalOptions struct {
	// Seat is the llama-swap id/alias to run the loop and the re-pack on; ""
	// keeps the box's planner seat.
	Seat string
	// Placed is published verbatim as the result's `placed` block; nil
	// publishes none (the byte-identical constraint for plain boxes).
	Placed *core.Placed
	// ParentJobID is the delegator's job id for this run (register C-62). The
	// runner's own ledger row becomes an inner row of that job — the
	// delegator's agent_delegate row is the job's one record — so a
	// route=local job is counted once, not twice. "" (every caller that is not
	// the delegator) keeps the runner's row a job of its own.
	ParentJobID string
}

LocalOptions is what a delegator that already DECIDED where a contract runs hands the local runner (ADR 0052): the seat to run instead of the planner default and the placement block to publish on the result. It exists because placement is decided once, delegator-side, over the same table a node uses — the runner must not re-derive (and possibly contradict) that decision, so it receives it. The zero value means "decide nothing here": the planner seat runs and no placed block is published, which is every pre-0.116 call. pipeline.AgentContractOptions is this type by alias, so the method value pipeline.RunAgentContract satisfies LocalRunner without a shim.

type LocalRunner

type LocalRunner func(ctx context.Context, contract core.AgentContract, opts LocalOptions) (core.AgentWireResult, error)

LocalRunner executes one contract in-process on the local node — the same read-only agent.Build path a fleet node runs (pipeline.RunAgentContract satisfies it). A seam rather than a *pipeline.Pipeline so this routing package does not drag the whole media pipeline into its dependency graph, and so tests fake local execution with a closure. The options carry a decided seat and placement (LocalOptions); the runner never places on its own.

type MediaRecipeView

type MediaRecipeView struct {
	Lane          string                `json:"lane"`
	Name          string                `json:"name"`
	Default       bool                  `json:"default"`
	Engine        string                `json:"engine"`
	Digest        string                `json:"digest"`
	Files         []ImageRecipeFileView `json:"files"`
	License       string                `json:"license"`
	CommercialUse *bool                 `json:"commercial_use"`
}

MediaRecipeView mirrors fleetnode.MediaRecipeHealth (mediacap.LaneRow): one family a node's video, animation or audio binding names, and what it loads. Lane is the fleet task type (video-gen, animate, audio-gen). Name is what a caller reaches the family by (a video row: the `model` value). Files reuse the image row's file shape; a file's Bytes is -1 when the node does not hold it. Digest is empty in this release: a row is never an identity. Mirrored here, not imported, like the image row.

type MediaRouteView

type MediaRouteView struct {
	Route  string `json:"route"`
	Engine string `json:"engine"`
	State  string `json:"state"`
}

MediaRouteView mirrors fleetnode.MediaRouteHealth: one media route and its verdict on that node.

type NodeView

type NodeView struct {
	NodeID string
	// HarnessVersion is the node's advertised release (/fleet/health
	// harness_version); empty on a node too old to publish it. Read by
	// doctor's fleet-skew rows (security standard L0), never by placement.
	HarnessVersion string
	AgentEnabled   bool
	AgentSeat      string
	AgentResident  bool
	AgentCtxTokens int
	QueueDepth     int
	// JobsRunning / JobsQueued split QueueDepth. MaxConcurrentJobs is the node's
	// execution limit and MaxQueueDepth its ADMISSION ceiling on QueueDepth —
	// the one and only thing that produces a `503 queue full`.
	//
	// For BOTH limits, 0 means "no usable number": the node publishes 0 for
	// unlimited, and a node too old to publish the field at all also decodes to
	// 0, and this decoder cannot tell those apart. So 0 is read as UNKNOWN
	// everywhere — never as a limit, never as unlimited. Same house rule
	// AgentCtxTokens already follows: unknown is not a capacity.
	//
	// gate.go DOES consult these (capacity-aware placement, 0.101.0): a node
	// whose published ceiling is already met loses to any node that is not
	// provably full, and a node with a provably free execution slot outranks
	// one whose workers are all busy. QueueDepth keeps its own meaning and its
	// own role as the ordering key — this is added on top, not in place of it.
	JobsRunning       int
	JobsQueued        int
	MaxConcurrentJobs int
	MaxQueueDepth     int
	// JobsRunningCapped is the part of JobsRunning that counts against MaxConcurrentJobs (health
	// jobs_running_capped), valid when JobsRunningCappedKnown: JobsRunning counts every job on the node, a
	// render included, so only this says whether the workers a queued agent job waits for are busy.
	JobsRunningCapped      int
	JobsRunningCappedKnown bool
	// ServedModels is the node's advertised roster (health served_models).
	// nil/empty = UNKNOWN (a pre-0.113.0 node): never a refusal. When
	// published, the agent seat must be in it — a stronger check than the
	// cached residency flag, and the capability gate PAIR calls "the exact
	// requested model is present".
	ServedModels []string
	// Accelerators is the node's advertised additive-device list (health
	// `accelerators`, ADR 0024). Absent = none. Read by accelremote to pick the
	// node that carries a device this box lacks (Coral Phase B).
	Accelerators []string
	// SeatRate is the node's published seat rate (health `seat_rate`,
	// 0.117.2): the retry floor a RETRY on that node is sized by (D-46).
	// nil = the node published none (older node, or no sample yet) — the
	// delegator then falls back to the first attempt's seat numbers.
	SeatRate *SeatRateView
	// SeatBudget is the node's published completion budget (health
	// `seat_budget`); nil on an older node.
	SeatBudget *SeatBudgetView
	// GpuUtilPct is the busiest device's utilization; GpuUtilKnown is false
	// when the node did not publish it. Read by betterRemote as the LAST key —
	// a tie-breaker, never a primary signal (operator decision 2026-09-03).
	GpuUtilPct   int
	GpuUtilKnown bool
	// WorkUtilPct is the busiest card the harness can actually run a seat on —
	// the node skips a display card it can prove (gpuprobe.DisplayCardUUIDs).
	// GpuUtilPct is the busiest card on the whole box, so it counts the
	// operator's desktop or game; WorkUtilPct does not, and it is what the
	// tie-break should compare. WorkUtilKnown is false on a node that predates
	// the field, and the tie-break then falls back to GpuUtilPct.
	WorkUtilPct   int
	WorkUtilKnown bool
	// LeasedText is true when the node publishes a held TEXT-class GPU lease
	// (health "lease", 0.113.16): its card is reserved for a measurement and the
	// gate treats it as ineligible. Absent (older node) or a media lease decodes
	// to false — a render is arbitrated on the node, never a placement refusal.
	LeasedText bool
	// LeaseHeld is true when the node publishes a held GPU lease of ANY class (health
	// "lease".held). A media client (mediaremote) ranks a node with no held lease ahead of one
	// with a short media lease; placement of agent work keeps reading LeasedText and LeaseBusy.
	LeaseHeld bool
	// LeaseClass, LeaseReason and LeaseRemainingSec describe the lease LeaseHeld speaks of, as the node's singular
	// lease block states it (the worst of the live leases when several are held): its class, why it was taken and
	// the seconds left of the term it declared. A media client quotes them when it tells a caller what a node is
	// busy with. Empty and 0 when no lease is held or on a node too old to publish them.
	LeaseClass        string
	LeaseReason       string
	LeaseRemainingSec int
	// ImageRecipes is what each ComfyUI image family on the node IS (health `image_recipes`, ADR 0082): the weight
	// files with their sizes and their content fingerprints (F59: a sampled sha256, or `pending` while the node is
	// still reading the file and `unreadable` when it cannot), the resolved sampling and a digest, which is empty on
	// a row that has a file without a fingerprint yet. nil on a node that predates it or that has no binding to
	// identify, which is "cannot be matched", never "matches anything". RefineHonoured is health `refine_honoured`:
	// the node's image-gen task carries an explicit refine=false.
	ImageRecipes   []ImageRecipeView
	RefineHonoured bool
	// MediaRecipes are the family rows of the node's video, animation and audio bindings (health `media_recipes`, ADR 0082
	// Amendment 3): which family each binding names and how big each weight file is on the node (-1: not there). A row carries no
	// digest in this release, so it is never an identity. nil on a node that predates it or binds none of the three lanes through
	// ComfyUI or sd.cpp, which a reader takes as UNKNOWN, never as "has no weights".
	MediaRecipes []MediaRecipeView
	// MediaRoutes is the node's own verdict on each file-backed media route (health
	// `media_routes`, ADR 0077): CONFIGURED, NOT CONFIGURED or BOUND-BUT-MISSING. It is only
	// meaningful when MediaRoutesKnown: a node that predates the field publishes none, which is
	// UNKNOWN, never "no route is configured".
	MediaRoutes      []MediaRouteView
	MediaRoutesKnown bool
	// LeaseBusy is the node's own "my card is spoken for long enough that you
	// should place elsewhere" verdict (0.113.27), true for a LONG lease of any
	// class. It exists because LeasedText alone left the harness's longest job
	// class — anything holding the MEDIA lease, up to a training run — looking
	// idle, so placement routed work toward the busy box (2026-09-07 audit).
	// False on an older node, which is exactly the previous behaviour.
	LeaseBusy bool
	// LeaseOverdue is true when the node publishes a HELD lease whose declared
	// window has already ended (health lease.overdue, GPU routing P1): the
	// holder is still using the cards, so the declared end says nothing about
	// when they free. It is decoded SEPARATELY from LeaseBusy on purpose. The
	// node also publishes busy=true for such a lease, but a busy non-text lease
	// is a hard exclusion in the gate, and an abandoned lease must rank the node
	// last without making it unroutable for longer than it was before. False on
	// a node one release behind.
	LeaseOverdue bool
	// Leases is every live lease the node published (health leases[], GPU routing P7), each
	// with the cards it sits on. nil means the node published none, which is an older node or
	// no lease at all: the singular fields above are then the whole reading, exactly as before.
	// They are the worst across the leases when this is set, so a reader that ignores Leases is
	// never told less than is true. Read it through leasesHolding, never directly: whether a
	// lease matters depends on the contract and on the node's seats.
	Leases []LeaseView
	// Devices is the node's per-card truth (health gpu_devices[], the nvidia-smi
	// per-device rows): uuid, VRAM total/free, utilisation, display_active. nil
	// when the node publishes none (an older node, or a source that cannot
	// enumerate devices), which is UNKNOWN and never "no free card". Read it
	// through FreeCards / cardTier, never directly.
	Devices []gpuprobe.Device

	// Saturation* decode health's `saturation` block (0.113.18). SaturationKnown
	// is false on an older node, and an unknown saturation is neither credited
	// nor blamed — the same rule every other capacity field follows. High means
	// the node itself says a new band-0 dispatch would be refused right now;
	// IdleSlot means a sheddable one would be admitted. Score is 0..1.
	SaturationKnown bool
	SaturationScore float64
	SaturationHigh  bool
	IdleSlot        bool
	// Tasks is the node's advertised `supported_task_types` (0.116.0). nil on
	// a node that publishes none. PlaceVision keys on it: a node serves the
	// vision lane exactly when "vision" is listed, so an older node — which
	// never lists it — is never a vision target.
	Tasks []string
	// VisionModel is the node's advertised vision seat (health
	// `vision_model`, 0.116.0) — informational, published beside the result so
	// a caller can see WHICH model judged its image without opening the node.
	VisionModel string
	// VisionTasks is the subset of vqa / ocr / assess_image the node's vision seat
	// serves (health `vision_tasks`). nil = the node publishes none, which means ALL
	// three: an older node, and a node whose seat serves everything, both read as
	// today. Read it through ServesVisionTask, never directly.
	VisionTasks []string
	// TextTasks is the subset of classify / extract the node's text lane serves
	// (health `text_tasks`, 0.154.0). nil = the node publishes none, which here means
	// NONE: the lane is dark unless declared, and an older node never lists "text"
	// either. Read it through ServesTextTask, never directly.
	TextTasks []string
	// ForecastModel decodes health's `forecast_model`: the alias of the node's bound forecast seat,
	// published only by a node that advertises "forecast". Empty on an older node and on one
	// without the lane; read the lane through ServesForecast, never this.
	ForecastModel string
	// STTHQ / STTUploadMaxMB decode health's `stt_hq` and `stt_upload_max_mb` (ADR 0072): whether the
	// node has an hq whisper model and the largest audio upload its door takes, MiB decoded. Both
	// are published only by a node that advertises "stt-upload", so an older node decodes to nil
	// and 0. STTHQ is a POINTER: false (a node with the door and no hq model) must stay distinct
	// from absent. Read them through ServesSTTUpload and PlaceSTT, never directly.
	STTHQ          *bool
	STTUploadMaxMB int
	// Layers is a composite node's advertised device layers (health `layers`,
	// ADR 0052): the spec of every layer and seat, live occupancy, and the
	// node's OWN admissibility verdict per layer. The delegator rebuilds them
	// with placetable.FromRows and runs the SAME placement table over them
	// (remoteDecision) — council R5: one placement rule, no second fit
	// heuristic across layers. nil on a plain node, which keeps today's
	// single-lane gate (AgentCtxTokens) exactly.
	Layers []placetable.LayerRow
	Local  bool
	// PublicOnly is true when the operator declared this node "public" in delegate_remote_classes (register SF-40):
	// its admin is not this box's operator, so the placement gate takes it public-data work only (dataclass.go).
	// It is not read from health: a node cannot declare its own trustworthiness. probeRemotes stamps it from the
	// config, beside the base URL that keys it; every other view (the local seat, a fresh single-node read) is
	// false, and none of those is a placement candidate.
	PublicOnly bool
	// JobsAdmitting is the SUBSET of JobsRunning still in admission (cordon,
	// swap pre-flight, warm, coherence probe) — health `jobs_admitting`
	// (0.127). Those jobs hold a capped slot while the card is idle; placement
	// (W-31) reads it to tell "busy" from "loaded-idle". 0 = none, or a node
	// too old to publish it — the pre-0.127 reading either way.
	JobsAdmitting int
	// VisionCallsRunning is health `vision_calls_running`: single-shot vision calls other processes
	// on the node have on a seat (a CLI loop, an MCP server's offload_vqa), outside its job store.
	// Status adds it to the node's in_flight; no placement rule reads it. 0 = none, or a node too old
	// to publish it.
	VisionCallsRunning int
	// SeatLoaded / SeatStarting mirror health `seat_loaded`/`seat_starting`
	// (0.127): what the node's last /running read said about the agent seat.
	// POINTERS: nil is UNKNOWN (the read never happened, or failed), and must
	// never be read as false (idle) — the same tri-state rule the VRAM reclaim
	// verdict already follows. SeatStarting true means a load is in progress
	// (not ready even though SeatLoaded may read true too).
	SeatLoaded, SeatStarting *bool
	// LeaseExclusive / LeaseDraining are the two lease facts a placement needs
	// that `LeaseBusy`'s declared-time verdict never carried: whether the
	// reservation FENCES the cards (no load may land on them) and whether it
	// is still draining the seat. Health `lease_exclusive`/`lease_draining`
	// (0.127), top-level, published only while a lease is held and only when
	// true — a node with no lease, and every node one release behind, decodes
	// both false.
	LeaseExclusive, LeaseDraining bool
	// RecentAgentWallSec is the median wall of this node's last finished agent
	// jobs — health `recent_agent_wall_sec` (0.127), the completion signal a
	// node with no seat_rate sample has no other way to publish. 0 = the node
	// has finished no agent job, or predates the field.
	RecentAgentWallSec float64
	// QueueWaitEstimateSec is the node's OWN estimate of how long a new job
	// would sit in its backlog — health `queue_wait_estimate_sec` (PR-6,
	// 0.128+). nil on every node at 0.127: W-11's queueWaitFor then falls
	// back to deriving the same shape from jobs_running/jobs_queued/
	// max_concurrent_jobs/recent_agent_wall_sec. A POINTER because 0 is a
	// genuine "no wait right now" answer and must read differently from
	// "this node does not publish the estimate at all".
	QueueWaitEstimateSec *float64
	// NewJobWaitSec is the node's OWN estimate of how long a job submitted NOW waits for a worker -
	// health `new_job_wait_sec` (ADR 0073), one slot deeper than QueueWaitEstimateSec, which is the
	// wait of the deepest job ALREADY queued. nil on a node that predates it, and on any node while
	// a worker is free (omitempty). publishedStartWait prefers it as-is; without it the older
	// estimate gets the slot added.
	NewJobWaitSec *float64
	// PowerProfile is whether the node's boot-time GPU power profile took (health `power_profile`, register A-103).
	// nil on a node too old to publish it, which is unknown, never "no profile". Shown by offload_status; placement
	// never reads it.
	PowerProfile *PowerProfileView
	// GpuFaults is the node's driver fault summary (health `gpu_faults`, 0.200.0): each card's incidents and
	// NVSentinel's repeat rule where it is met. A live repeat on every seat's cards demotes the node (ADR 0096,
	// faultdemotion.go). nil = a node one release behind, no reading yet or no NVIDIA card: never demoted.
	GpuFaults *gpuactivity.FaultSummary
	// contains filtered or unexported fields
}

NodeView is one node's placement-relevant state, built from /fleet/health (FetchNodeView) for remotes and from local knowledge for the local node.

func FetchNodeView

func FetchNodeView(ctx context.Context, base, token string) (NodeView, error)

FetchNodeView reads one node's /fleet/health into a NodeView (Local=false — a fetched view is by definition a remote node). token, when non-empty, is sent as a bearer credential. Health answers without it, but a node that has a token withholds the private fields of the answer (the lease's free-text reason, the store steward's status, the weight-file rows of its recipes) from a caller that does not present it, so a caller that holds the token sends it and reads the whole view.

func Place

func Place(seed string, st Subtask, local NodeView, remotes []NodeView, localBusy bool) NodeView

Place decides which node runs st. The rule, exactly as reshaped:

  • localBusy false ⇒ LOCAL, unconditionally. An idle local node always wins — delegation exists to keep work flowing while the local GPU is occupied, never to chase throughput on a weaker seat (quality-first, operator verbatim: "not a race about speed").
  • localBusy true ⇒ the best remote that passes the hard gate, ranked by capacity, then by QueueDepth, then by GPU utilization (ties: first listed, so the caller's roster order is the stable preference order — see betterRemote). No remote passes ⇒ LOCAL regardless — queued-local beats ineligible-remote every time.

Place is pure: it never probes anything. Callers build the inputs from FetchNodeView + LocalBusy. seed is the W-11 P2C draw's input (the wire job id when the caller has minted one, else any string a caller wants two otherwise-identical calls to agree on) — see betterRemote.

func (NodeView) FreeCards

func (v NodeView) FreeCards() (free, total int, known bool)

FreeCards is the layer-agnostic count offload_status publishes: how many of the node's cards are idle, not a display and have room for a seat, out of how many it published. known is false when the node published no per-card utilisation, which a caller must read as "no figure", never as zero.

func (NodeView) RouteState

func (v NodeView) RouteState(route string) (state string, known bool)

RouteState reports the node's verdict on a media route. known is false when the node published no media_routes at all (an older node) and ALSO when it published a list that omits the route; state is then "".

func (NodeView) ServesForecast

func (v NodeView) ServesForecast() bool

ServesForecast reports whether v advertises the forecast lane. The lane has one task, so the advertisement is the whole answer: an older node never lists it and is never picked.

func (NodeView) ServesSTTUpload

func (v NodeView) ServesSTTUpload() bool

ServesSTTUpload reports whether v advertises the stt upload door.

func (NodeView) ServesSTTUploadOf

func (v NodeView) ServesSTTUploadOf(hq bool, size int64) bool

ServesSTTUploadOf reports whether v can transcribe a file of size bytes: it advertises the door, takes a file that large, and has an hq model when hq is asked (a node that does not publish stt_hq is not assumed to have one).

func (NodeView) ServesText

func (v NodeView) ServesText() bool

ServesText reports whether v advertises the text lane.

func (NodeView) ServesTextTask

func (v NodeView) ServesTextTask(task string) bool

ServesTextTask reports whether v serves the text lane AND the given task (classify or extract). Unlike the vision lane an absent list is NOT "all": the lane ships dark, so a node is a target only when it lists both the lane and the task. An older node (which publishes neither) is therefore never picked, and neither is a node that lists the lane with an empty task set.

func (NodeView) ServesVision

func (v NodeView) ServesVision() bool

ServesVision reports whether v advertises the vision lane.

func (NodeView) ServesVisionTask

func (v NodeView) ServesVisionTask(task string) bool

ServesVisionTask reports whether v serves the vision lane AND the given task (vqa, ocr or assess_image). A node that publishes no vision_tasks serves all three, so an older node is exactly as eligible as before; one that publishes a list serves only what it names — a seat whose runtime cannot do a task (the RKLLM runtime cannot run assess_image's grammar) must not be handed it.

type PinStats

type PinStats struct {
	// Since is when the tally started, the start of the window the counts cover.
	Since time.Time
	// Reasoned counts the subtasks of calls pinned under each reason; every reason of the closed set is present.
	Reasoned map[string]int
	// Hints counts the subtasks of calls whose local or remote route had no pin_reason and was placed as a hint, and
	// HintsOverridden how many of those placement did not honour (a local hint placed on a remote node, a remote hint
	// placed on the local seat). A hint nothing ran stays in Hints and in neither.
	Hints           int
	HintsOverridden int
	// Unreasoned counts the subtasks of calls that pinned placement through a caller with no pin_reason channel and
	// reached the engine (the review lane's remote fallthrough and the remote route of offload_ask and agent_run; an
	// explicit local route on those two runs on this box's seat without reaching it, and is counted nowhere): they stay
	// authoritative. An agent_run that names a model is not among them: it carries PinOperator and counts in Reasoned.
	Unreasoned int
}

PinStats is a copy of a PinTally.

type PinTally

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

PinTally is the pin accounting offload_status publishes: how many subtasks callers pinned under each reason, how many came as hints and how many of those placement overrode. It belongs to one MCP server, not to the package: the server makes one at start (NewPinTally) and hands it to every door it runs the engine through (RunOptions.PinTally), so the window it describes is exactly "since this server started" and nothing scans the ledger to build it. A call that carries none is not counted. Counts are in subtasks (published results).

func NewPinTally

func NewPinTally() *PinTally

NewPinTally starts an empty accounting whose window opens now.

func (*PinTally) Snapshot

func (t *PinTally) Snapshot() PinStats

Snapshot copies the tally. A nil tally is an empty one.

type PlaceWait

type PlaceWait struct {
	// Node is the node the subtask stood in line for (its node_id; the delegator's own box for
	// the local seat).
	Node string `json:"node"`
	// On is what it stood behind: lease (a lease on the cards the contract needs), queue (the
	// node's own admission ceiling or no room), backlog (a queue longer than the caller will
	// wait), cooldown (the node's own refusal), seat (another vLLM seat holds the local cards
	// and loading the agent seat would unload it).
	On string `json:"on"`
	// Detail is the sentence behind On.
	Detail string `json:"detail"`
	// EtaSec is when the place is expected to clear, in seconds from the end of the wait; 0 when
	// nothing says (an overdue lease, a node that publishes no estimate).
	EtaSec int `json:"eta_sec,omitempty"`
}

PlaceWait is one place in line a subtask stood in when its capacity wait ended with nothing having taken the work (GPU routing P7, invariant I4: a busy card is a place in line). It is what the caller re-asks by: which node, behind what, and when that is expected to clear.

type PlacedResult

type PlacedResult struct {
	Node               string
	Seat               string
	Result             core.AgentWireResult
	AcceptanceFailures []string
	// AcceptanceAuthority is the authority the contract closed at (core.ClosedAt, set by gradeAcceptance): the weakest
	// authority among its checks, stated only when every check passed and nothing else failed the result. AuthNone says
	// nothing (a contract with an unqualified check, a failure, an unknown, an excused fingerprint, or no answer).
	AcceptanceAuthority core.Authority
	JobID               string

	PlacementReason string
	// PinReason is the closed reason the call was pinned under (RunOptions.PinReason, ADR 0078), stamped on the
	// result as the caller receives it and on its ledger row; "" for a call with no reasoned pin.
	PinReason string

	// Err is non-empty when the subtask FAILED for transport/config reasons
	// (dispatch refused, auth rejected, undecodable result). Counted in
	// Summary.Failed, never in Deferred — eight quiet defers and one broken
	// wire are different outcomes and must read differently.
	Err string

	// RetriedOn names the node a second attempt ran on after the first attempt
	// came back failed_verification or an honest abstention. The published
	// result is the BETTER attempt (a success beats any failure; otherwise the
	// first attempt stands), and RetryNote says what the other attempt did, so a
	// reader can tell "the 27B fixed what the 4B missed" from "both seats missed".
	// Empty when no retry ran (no different node was available, or the first
	// attempt did not qualify).
	RetriedOn string
	RetryNote string

	// PollNote (register D-116) names the bound the delegator polled a
	// timeout_auto contract at and where the number came from — the node's
	// advertised seat rate, the node's own published wall, or the cap when it
	// advertised neither. Empty for a contract that named its own timeout_sec,
	// which is polled at timeout_sec + grace exactly as before.
	PollNote string

	// Replacements counts how many times this subtask was RE-PLACED on a
	// different node after a node REFUSED it at dispatch. 0 on the
	// overwhelming majority of results, so a healthy run publishes exactly
	// what it published before this existed.
	Replacements int
	// ReplacementNote names every node that refused and what it said, in the
	// order they were tried. Present whenever Replacements > 0 — on the result
	// that finally ran as much as on the one that ran out of nodes — because a
	// fleet quietly shedding load onto one box otherwise looks identical to a
	// healthy one.
	ReplacementNote string
	// CapacityWaitSec (0.113.18) is how long this subtask waited for a node to
	// have room before one took it — the capacity wait (the call's deadline less a
	// reserve, else agent_placement_wait_sec; ADR 0073) — and is NOT part of timeout_sec. waited marks it for Summary.Waited; shed
	// marks a sheddable subtask that found no idle node (Summary.Shed).
	CapacityWaitSec float64
	// PlaceKeeping and RetryAfterSec (GPU routing P7) are what a capacity wait that ended with
	// nothing taking the work knew about the places it stood in: every node it stood behind with
	// what it waited on and when that is expected to clear, and the soonest of those as a hint
	// for when a re-ask can succeed. Empty on every result that did not end that way.
	PlaceKeeping  []PlaceWait
	RetryAfterSec int

	// Unplaced marks a result NO node ran (a capacity defer, a shed, or a
	// route=remote with nothing eligible): it carries Replacements for the
	// refusals it collected, but must never be tallied as a replacement that
	// RECOVERED — nothing took the work.
	//
	// EXPORTED because a SURFACE has to tell "the node answered and deferred"
	// from "the node was never exercised": both carry Deferred, but only the
	// first one's Node and Seat describe the box under test. The second stamps
	// the DECIDING (local) box, and fleet-smoke rendering that as the node under
	// test made a dead remote read as a failure of the operator's own machine
	// (issue #250).
	Unplaced bool

	// Placed (ADR 0052, 0.116.0) is the placement decision this result was
	// produced under — the block published as `placed` beside the untouched
	// `placement` reason string. Local: the delegator's own decision, replaced
	// by the pipeline's stamp once the run answers (identical by construction).
	// Remote: the delegator's decision over the node's advertised rows until
	// the node's wire result carries its own (the node re-decides with its live
	// guards, council R5). nil on a plain box and for a plain node, so every
	// pre-0.116 result publishes byte-identically.
	Placed *core.Placed
	// contains filtered or unexported fields
}

PlacedResult is one subtask's outcome: where it ran, what came back, and what the delegator-side verification found. Beyond the placement/result core, JobID and PlacementReason are carried for the surfaces and the telemetry (mis-routing hygiene: every result names its node, seat, and why it landed there), and Err marks a transport/config FAILURE — distinct from a defer, which is the node honestly reporting it could not complete.

type PlannedPlacement

type PlannedPlacement struct {
	// Route is the route the deal would apply (a pin hint's route is already resolved to auto).
	Route string `json:"route"`
	// Where is one of: "local", "node" (a fleet node, named by Node), "capacity_wait" (every eligible node is
	// full or too far from starting the job, so a real call would wait for room), "no_eligible_node", or
	// "not_computed".
	Where string `json:"where"`
	Node  string `json:"node,omitempty"`
	// Reason is the deal's own sentence, or why nothing was computed.
	Reason string `json:"reason"`
}

PlannedPlacement is where a call's joint deal WOULD put one subtask, read without dispatching it (agent_delegate lint_only, register D-109).

func PlanPlacement

func PlanPlacement(ctx context.Context, cfg config.Config, contracts []core.AgentContract, route string, remotes []string, opts *RunOptions) []PlannedPlacement

PlanPlacement is the placement the route=auto / route=remote deal would give each of contracts, computed from the same readings RunWith takes before it deals, and nothing else: the local lease file (read), the local seat's in-flight count (one GET), the local run registry (read), and each fleet node's health document (one GET each). It takes no lease, mints no job, writes no ledger or intent row, opens no queue and starts no seat; the job ids the deal mints are throwaway ranking seeds and are discarded.

The answer is the DEAL's pick. A real call can still land elsewhere: a lease taken in between, a node that refuses, a retry. The reason says so where it matters. A route this does not model (local is trivial, spread and queue are not computed) answers Where "local" or "not_computed" with the reason, never a guess.

type PowerProfileView

type PowerProfileView struct {
	State     string `json:"state"`
	Reason    string `json:"reason"`
	LimitW    []int  `json:"limit_w"`
	ClockLock bool   `json:"clock_lock"`
	AppliedAt string `json:"applied_at"`
}

PowerProfileView mirrors fleetnode.PowerProfileHealth: State is "ok", "skipped" or "unknown", Reason the short token that says why a node is not ok, LimitW the cards' power limits as the node's state record read them, ClockLock whether a clock-lock step returned success and AppliedAt the record's own time (RFC 3339, UTC).

type PreparedBatch

type PreparedBatch struct {
	// Total is the number of subtasks the call carried: len(Contracts) + len(Rejections).
	Total int
	// Contracts are the subtasks that passed intake, in input order.
	Contracts []core.AgentContract
	// Indices[k] is the input position of Contracts[k].
	Indices []int
	// Rejections are the subtasks that did not, in input order.
	Rejections []IntakeRejection
}

PreparedBatch is the outcome of preparing a whole call, subtask by subtask.

func PrepareBatchWithCap

func PrepareBatchWithCap(specs []SubtaskSpec, readRoot string, capBytes int) PreparedBatch

PrepareBatchWithCap prepares every spec as PrepareContractWithCap does (the same minting, clamps, context_paths confinement under readRoot and validation at capBytes) and returns the valid contracts with their original positions beside the per-position rejections. Preparing one spec never depends on another, so a rejection changes nothing about the rest: PrepareContractWithCap(spec, ...) succeeds or fails alike alone or in a batch.

func (PreparedBatch) AllRejected

func (b PreparedBatch) AllRejected() bool

AllRejected reports a call with nothing valid in it: there is nothing to run, and the surface answers with the flat defer (FlatReason) it always gave.

func (PreparedBatch) AlsoRefused

func (b PreparedBatch) AlsoRefused(reason, label string, ids []int) string

AlsoRefused words a whole-call defer that came from somewhere other than intake (the engine refused the call, so nothing ran and there is no result to splice a rejection into) so that it still names the subtasks intake refused: "<reason>; also refused at intake: subtask 1: ...". A caller who fixes the engine's complaint and resubmits meets nothing it was not told. A call with nothing refused gets reason back untouched.

func (PreparedBatch) FlatReason

func (b PreparedBatch) FlatReason(label string, ids []int) string

FlatReason is the reason of the whole-call defer: every rejection, in input order, each under its own label and number. A call with one bad subtask reads exactly as it did when that was the only thing a call could say ("subtask 0: ...").

func (PreparedBatch) MapProgress

func (b PreparedBatch) MapProgress(fn func(ProgressEvent)) func(ProgressEvent)

MapProgress turns the callback the engine reports through into one that speaks in the caller's numbers. The engine is handed only Contracts, so its events number subtasks among the valid ones and total only those: for input [ok, bad, ok] the third subtask would be announced as "2 of 2". The mapped event carries the subtask's input position (where its result sits in the answer), the call's full Total, and a Done count that includes the subtasks intake refused, which are finished before anything runs. A nil callback stays nil (the engine reports nothing then), and a batch with no rejections returns fn itself: its numbers were already right.

func (PreparedBatch) Splice

func (b PreparedBatch) Splice(results []PlacedResult, sum Summary, label string, ids []int) ([]PlacedResult, Summary)

Splice puts the rejected subtasks back among the results of the valid ones, so the call answers one result per input subtask, in input order. results and sum are what the engine returned for Contracts; the merged summary counts each rejection as Deferred and nothing else, because the fleet is healthy and the caller has a contract to fix (Summary.Infrastructure). label and ids word the reasons as in FlatReason.

results normally holds one entry per valid contract. When it holds fewer (RunBatched returned an error with the results it had collected), the merge ends at the first valid subtask with no result: what lies beyond it was never attempted, and a rejection there is counted as Skipped with the rest instead of being published ahead of results that do not exist.

type ProgressEvent

type ProgressEvent struct {
	// Kind is "started" (a subtask began) or "finished" (one ended, any way).
	Kind string
	// Index is the subtask's position in the WHOLE call (0-based), across every
	// chunk of a batched call.
	Index int
	// Done is how many subtasks of the whole call have ended so far, this one
	// included when Kind is "finished".
	Done int
	// Total is how many subtasks the whole call owes an answer for.
	Total int
	// Node names where a finished subtask ran ("" when it ran nowhere or the
	// node is unknown). Outcome is set only on "finished": succeeded, failed,
	// failed verification, or deferred (with the defer class).
	Node    string
	Outcome string
}

ProgressEvent is one state change of a running call.

type Quarantine

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

Quarantine is the process-scoped memory of fleet nodes whose answers failed the DOCUMENT FINGERPRINT check (research.DocFingerprint) — the shape of the <node-c> 4B's phantom "latest Go version" digests (2026-08-31 … 09-01): a result that passes as a result while sharing nothing with the page it was handed. Two strikes within TTL block the node for TTL, provided they outnumber the node's passes of the same window (Pass: a lexical tripwire misfires on an honest answer now and then, and a node that passed most of its work is not off-document); the block expires on its own, so a flaky node is re-tried later without operator action.

Owned by the CALLER (the MCP server keeps one for its lifetime; a CLI run gets a fresh one) and passed through RunOptions, so it survives RunBatched's chunking — a per-Run map died every 8 contracts (roast, 2026-09-02). It is never persisted: the node bug it guards against needs a fix on the node, and a file that outlives the process would hide the fix's effect.

Coverage: the default, spread and remote routes (fetchViews filters blocked nodes; runRemote strikes). The `queue` route hands placement to the pull holders (ADR 0030) before a runner exists, so it is NOT covered — a known bound, stated rather than hidden. The local seat is never quarantined.

Only fingerprint failures strike. A user's over-strict `contains:` or a thin page's `min_items` is the CONTRACT's fault and must never quarantine the seat that answered honestly; the same goes for a fingerprint the contract can never close (a grounded check on a contract with no context documents grades unknown for every node, and the intake lint warns about it).

A stated limit, on purpose: a node that answers about the wrong document less often than about the right one (4 misses beside 6 passes in the window) is not quarantined. The tripwire fails the RESULT, and a failed fingerprint keeps its cross-seat retry (skipsRetryAsResearchAcceptanceOnly), so such a node's miss is never delivered as verified: each miss costs one retry on another node (a miss whose retry cannot be placed is published as failed verification, not as an answer). Idling a node on a lexical check costs the fleet a whole seat for the window, which is the larger loss, and the one rule that measured it (a node that passed 48 of 51 and was out for 30 minutes after two misses) is what the majority rule answers. An honest absence is neither a pass nor a strike (noteFingerprint), so it neither shields nor condemns.

func NewQuarantine

func NewQuarantine(ttl time.Duration) *Quarantine

NewQuarantine builds an empty Quarantine. ttl <= 0 uses DefaultQuarantineTTL.

func (*Quarantine) Blocked

func (q *Quarantine) Blocked(base string) bool

Blocked reports whether base is currently quarantined. A nil Quarantine blocks nothing.

func (*Quarantine) Pass

func (q *Quarantine) Pass(base string)

Pass records one result of base that carried the fingerprint check and PASSED it. A node is quarantined for answering about the wrong document, and the check is lexical: it misfires on an honest answer now and then, so "two failures in the window" would quarantine a node that passed most of its work. A node that is truly off-document fails MORE often than it passes, which is what Strike now requires. Passes age out with the same window as strikes. A nil Quarantine records nothing.

func (*Quarantine) Strike

func (q *Quarantine) Strike(base string) bool

Strike records one fingerprint failure for base. It returns true exactly when this strike FLIPS the node into quarantine (at least two strikes inside TTL, and more strikes than passes in the same window: see Pass), so the caller can count flips without double-counting. A nil Quarantine records nothing.

func (*Quarantine) Until

func (q *Quarantine) Until(base string) time.Time

Until reports when base's quarantine ends (zero time when not blocked).

type QuoteCheck

type QuoteCheck struct {
	// Checked counts the non-empty quotes looked up.
	Checked int `json:"checked"`
	// Verbatim counts the quotes that are the page's own bytes.
	Verbatim int `json:"verbatim"`
	// Corrected counts the quotes found on the page only after case, spacing,
	// quote-mark and dash differences were set aside; each was replaced in the
	// published digest by the page's own span.
	Corrected int `json:"corrected,omitempty"`
	// Unverified lists the quotes found nowhere on the page, exactly as the seat
	// wrote them. They stay in the digest's `quotes`.
	Unverified []string `json:"unverified,omitempty"`
	// Note says in one line what the Unverified list means; empty when there is none.
	Note string `json:"note,omitempty"`
}

QuoteCheck reports what the delegator found when it looked each item of a research digest's `quotes` up in the page the digest was written from. A quote is the one field of a digest that promises the page's own words, and a seat that paraphrases it hands a fact-checker something no search of the page can find (register F4). The check never fails a digest: an acceptance failure discards a whole run (register C15), so a quote that is not on the page is FLAGGED here and left where the seat put it.

type RescueFunc

type RescueFunc func(ctx context.Context, contract core.AgentContract, output string, budget time.Duration) (Rescued, error)

RescueFunc structures a finished answer for a contract. It is a seam, like LocalRunner, because the completion runs on the delegator's own pipeline and this package cannot import it. budget is the most it may wait (never below rescueFloor). It returns the object, the seat that produced it and how; an error means it could not, and the defer stays.

type RescueOrigin

type RescueOrigin struct {
	// Base is the node's dial base, as the run used it.
	Base string
	// Seat is the seat that wrote the answer on that node (the wire result's seat).
	Seat string
	// Node is the node's id as the placement used it (results[].node), for a note.
	Node string
}

RescueOrigin is where a finished answer was written: the node whose agent loop produced it, and the seat that wrote it. The delegator's rescue is handed it (WithRescueOrigin) because that node holds its seat hot: it has just decoded the answer, so a one-completion re-pack there waits for no load, and it does not depend on THIS box's seat being resident or its cards being free. It is not handed when the node's own re-pack failed for its seat's health (originSeatFailed).

func RescueOriginFrom

func RescueOriginFrom(ctx context.Context) (RescueOrigin, bool)

RescueOriginFrom reads the origin a rescue was handed: ok is false when the result did not come from a node (a local run) or the node named no seat.

type Rescued

type Rescued struct {
	// Structured is the answer as an object of the contract's schema. The
	// delegator validates it again before it delivers anything.
	Structured json.RawMessage
	// Seat is the delegator-side seat that produced it ("" when no completion ran).
	Seat string
	// TokensOut is the completion's own generation, added to the result's total.
	TokensOut int
	// How says what produced the object, for the note.
	How string
}

Rescued is what a RescueFunc hands back.

type ResponseWire

type ResponseWire struct {
	Summary SummaryWire  `json:"summary"`
	Results []ResultWire `json:"results"`
}

ResponseWire is the full response: summary first, then per-subtask results in submission order.

func WireResponse

func WireResponse(results []PlacedResult, sum Summary, lints [][]string) ResponseWire

WireResponse shapes Run's raw outcome for publication. lints is the intake lint per subtask, indexed in SUBMISSION order (the same order results keep); nil, or a shorter slice, simply leaves the remaining results unlinted — absence of a warning must never be manufactured into an error.

type ResultWire

type ResultWire struct {
	Node string `json:"node"`
	// NodeReported is the id the executing node stamped on its OWN result, present only when it differs (case-insensitively)
	// from Node: Node is the id the placement used (the node_id /fleet/health publishes, the name the placement text carries),
	// so the two differ in two cases: a node on a build before 0.185.0 (it stamps its hostname where it was launched with
	// another --node-id) and a local run attributed to another box's engine (register C-58: the runner stamps its own box, the
	// placement names the engine's). A node on this build stamps the id it advertises, so it never differs there. Absent when
	// the two are the same and when no node took the subtask. Stamped in one place, WireResponse, from NodeReported().
	NodeReported string `json:"node_reported,omitempty"`
	// Seat is the agent seat that ran the subtask.
	Seat string `json:"seat"`
	// Placement is the placement REASON, a string — read as text (council R4) — so the composite decision is
	// published beside it as Placed, never folded into it. Where the subtask RAN is RanOn, not a word in this text:
	// the opencode plugin reads RanOn first and this text only when a result has none.
	Placement string `json:"placement"`
	// RanOn (D-32) says where the subtask RAN, as a closed value: RanOnLocal, the delegator's own seat, or RanOnNode, a
	// fleet node (a route queue answer a claiming node filed reads node). Absent when no seat ran the work (a defer, a shed,
	// a refusal chain, a subtask that never started, a job a node took back or whose record says it never ran, even when the
	// call deadline cut the row afterwards) and on a result from a delegator that predates it. A job the deadline cut while a
	// node still held it reads node: it was placed and dispatched there and may start. It is stamped in one place,
	// WireResponse, from placedWhere: the decision that also writes the hint clause and the pin tallies, so it cannot
	// disagree with them. Placement stays the reason, in words; a reader that wants the location reads this, never the word
	// "local" in that text.
	RanOn string `json:"ran_on,omitempty"`
	// PinReason (ADR 0078) is the closed reason the caller pinned the call under (privacy, locality, measurement,
	// operator). Present only on a call pinned with one; a route local or remote that gave none is a hint, and the
	// placement above opens by saying whether it was honoured or overridden. omitempty — every other result
	// publishes byte-identically to before.
	PinReason string `json:"pin_reason,omitempty"`
	// Placed (ADR 0052, 0.116.0) is the composite placement block: tier,
	// layer, role, seat, device pin, reason, and on a defer the guard that
	// refused. omitempty — a plain box publishes byte-identically to before.
	Placed             *core.Placed    `json:"placed,omitempty"`
	JobID              string          `json:"job_id"`
	Output             string          `json:"output,omitempty"`
	Structured         json.RawMessage `json:"structured,omitempty"`
	Deferred           bool            `json:"deferred"`
	Reason             string          `json:"reason,omitempty"`
	DeferClass         string          `json:"defer_class,omitempty"`
	Failed             bool            `json:"failed,omitempty"`
	AcceptanceFailures []string        `json:"acceptance_failures,omitempty"`
	// AcceptanceAuthority is the authority the contract closed at: "answer", "field" or "grounded", the weakest
	// authority among its checks, present only when every check passed, nothing else failed the result and every check
	// was authority-qualified (contracts/README.md, "Authority-graded checks"). omitempty: a result with an unqualified
	// check, a failure, or no graded answer publishes byte-identically to before.
	AcceptanceAuthority string `json:"acceptance_authority,omitempty"`
	WallMs              int64  `json:"wall_ms"`
	// ContentionWaitSec / AdmissionWaitSec / AdmissionNote carry the agent
	// result's own wait accounting (ADR 0032) up to the delegating caller —
	// without them the CLI/MCP reader could not see that a wait fired at all
	// (found by the parallel-sessions gate, 2026-09-02).
	ContentionWaitSec float64 `json:"contention_wait_sec,omitempty"`
	AdmissionWaitSec  float64 `json:"admission_wait_sec,omitempty"`
	AdmissionNote     string  `json:"admission_note,omitempty"`
	// QueuedMs is the wall the run spent in the busy hold (ADR 0061): waiting
	// on a seat whose engine was working for other requests. Carried to the
	// caller beside the other wait figures, so a slow answer that was queued
	// reads as contention, not as a slow seat.
	QueuedMs int64 `json:"queued_ms,omitempty"`
	// SeatRecoveries / SeatDownWaitSec (ADR 0066): how many times the run's seat
	// went down under it and the run waited for the seat and re-issued the failed
	// step instead of ending, and the wall it spent waiting on a downed seat.
	// Carried to the caller beside the other wait figures, so a slow answer that
	// survived a seat restart reads as one, not as a slow seat.
	SeatRecoveries  int     `json:"seat_recoveries,omitempty"`
	SeatDownWaitSec float64 `json:"seat_down_wait_sec,omitempty"`
	// CoherenceNote carries the node's post-warm coherence probe (register
	// D-118) up to the delegating caller: without it a run that deferred before
	// its wall started, because the seat was emitting NaN tokens, would reach
	// the caller as a bare infrastructure defer with nothing saying the seat
	// itself was tested and failed.
	CoherenceNote string `json:"coherence_note,omitempty"`
	// RetriedOn / RetryNote: the published result is the better of two attempts
	// when a retry ran; the note says what the other attempt did.
	RetriedOn string `json:"retried_on,omitempty"`
	RetryNote string `json:"retry_note,omitempty"`
	// Replacements / ReplacementNote: how many times a node refused this
	// subtask at dispatch before one took it, and which nodes those were with
	// what each of them said.
	Replacements    int    `json:"replacements,omitempty"`
	ReplacementNote string `json:"replacement_note,omitempty"`
	// CapacityWaitSec (0.113.18): how long this subtask waited for a node to
	// have room (the call's deadline less a reserve, else agent_placement_wait_sec) — not charged to timeout_sec.
	CapacityWaitSec float64 `json:"capacity_wait_sec,omitempty"`
	// PlaceKeeping / RetryAfterSec (GPU routing P7): when the capacity wait ended with nothing
	// taking the work, the places in line it stood in (node, what it waited behind, when that is
	// expected to clear) and the soonest of those in seconds. Absent on every other result.
	PlaceKeeping  []PlaceWait `json:"place_keeping,omitempty"`
	RetryAfterSec int         `json:"retry_after_sec,omitempty"`
	// PollNote (register D-116) names the bound the DELEGATOR polled this
	// subtask at and where that number came from: "sized from <node>'s
	// seat_rate X tok/s: N s", "the node's own wall N s", or "cap: no seat
	// rate advertised". Present only for a contract the caller left unsized
	// (timeout_auto) — one that named its own timeout_sec is polled at
	// timeout_sec + grace and publishes nothing here, byte-identically to
	// before. Delegator-side: it is NOT a field on core.AgentWireResult.
	PollNote string `json:"poll_note,omitempty"`
	// Calls (register D-99) is the node's per-completion record for this
	// subtask — finish reason, token counts, thinking_off, sampling — bounded
	// to the LAST wireCallsMax completions (the final answer and the re-pack
	// are what a reader wants; a 12-step run records more than that). Before
	// this field a delegator could read the record only from the node's own
	// GET /fleet/jobs/{id} with the fleet token, although the tool description
	// had promised results[].calls. omitempty: a node that recorded nothing
	// publishes a row byte-identical to before.
	Calls []core.AgentCallRecord `json:"calls,omitempty"`
	// AcceptanceLint carries the intake lint's warnings for THIS subtask's
	// acceptance (delegate.LintAcceptance): parrot-passable / ungrounded /
	// shape-only. Warn-only — the run above happened regardless. It rides the
	// response so the CALLER (usually a model mid-session) sees it beside the
	// result it weakens, and can fix the acceptance before the next call.
	AcceptanceLint []string `json:"acceptance_lint,omitempty"`
	// A1 config pins, passed through from the node's wire result (see
	// core.AgentWireResult) so a caller can verify WHAT served its subtask
	// without opening the delegation log. Absent = the node predates pinning:
	// unknown, never a value.
	HarnessVersion     string `json:"harness_version,omitempty"`
	HarnessBuildSHA256 string `json:"harness_build_sha256,omitempty"`
	SeatConfigSHA256   string `json:"seat_config_sha256,omitempty"`
	SeatConfigBasis    string `json:"seat_config_basis,omitempty"`
	// Steps / StopReason / StopNote / OutputTruncated (0.115.20): the node's
	// loop accounting, passed through from core.AgentWireResult. Without them
	// a `done` that the forced final step extracted at the step cap (D-89,
	// stop_note "forced final answer: …") and a `length`-cut partial were
	// indistinguishable from a voluntary, complete answer unless the caller
	// opened the delegation log — the D-89 acceptance run read as "all four
	// legs answered" with no trace of WHICH ones the cap forced. omitempty:
	// a pre-0.115.20 node's result publishes as before.
	Steps           int    `json:"steps,omitempty"`
	StopReason      string `json:"stop_reason,omitempty"`
	StopNote        string `json:"stop_note,omitempty"`
	OutputTruncated bool   `json:"output_truncated,omitempty"`
	// Wall sizing (0.115.21, register D-03), passed through from the node: the
	// run's measured decode rate, the wall the node estimated the contract
	// needed on that seat, the retry floor it implies, and the arithmetic.
	SeatTokS        float64 `json:"seat_tok_s,omitempty"`
	WallEstimateSec int     `json:"wall_estimate_sec,omitempty"`
	MinTurnSec      int     `json:"min_turn_sec,omitempty"`
	WallNote        string  `json:"wall_note,omitempty"`
	// WallSec (register D-03): the wall the node ran under when IT sized it (a
	// timeout_auto contract); omitted when the contract named its own timeout_sec.
	WallSec int `json:"wall_sec,omitempty"`
	// Re-pack accounting (0.115.23, register D-91), passed through.
	RepackMs       int64  `json:"repack_ms,omitempty"`
	RepackAttempts int    `json:"repack_attempts,omitempty"`
	RepackNote     string `json:"repack_note,omitempty"`
	// RepackAttemptsDetail (register C-80) is the node's record of each re-pack
	// attempt (lane, max_tokens, tokens generated, finish reason, a clip of what the
	// seat wrote, why it failed or was skipped), passed through bounded to the first
	// wireRepackAttemptsMax: the earliest attempt shows what went wrong, and a node
	// sends at most three and a skip. Before it, only the node's own job result and
	// the delegation log held it, so the caller who asked what a failed re-pack did
	// could not read it. omitempty: a node that predates the field publishes a row
	// byte-identical to before.
	RepackAttemptsDetail []core.AgentRepackAttempt `json:"repack_attempts_detail,omitempty"`
	// Final-budget fit and the list-cap re-issue (0.122.1, register D-95),
	// passed through from the node. Without them a caller sizing its next
	// contract cannot tell an answer that fitted from one the wall narrowed,
	// nor a partial that was asked again from one that never was.
	FinalBudgetFit int    `json:"final_budget_fit,omitempty"`
	BudgetNote     string `json:"budget_note,omitempty"`
	FinalReissue   string `json:"final_reissue,omitempty"`
	// The write door (0.122.0, register D-06), passed through from the node.
	// Diff is a unified patch the CALLER applies — the harness never does —
	// DiffFiles names the paths it touches, and WriteNote says what the door
	// did when there is no diff to read. All omitempty: a read-only
	// delegation publishes byte-identically to before the door existed.
	Diff      string   `json:"diff,omitempty"`
	DiffFiles []string `json:"diff_files,omitempty"`
	WriteNote string   `json:"write_note,omitempty"`
	// QuoteCheck (register F4) is the research lane's finding about this digest's
	// `quotes` against the page it was written from. Only offload_research and the
	// research verb set it, after the engine returns; every other door publishes
	// no such block, byte-identically to before.
	QuoteCheck *QuoteCheck `json:"quote_check,omitempty"`
}

ResultWire is one subtask's published outcome. Failed marks a transport/config failure (distinct from a defer — the node never reported); wall_ms is the DELEGATOR-observed round trip, not the node's own wall (which stays inside the node's result and the delegation log).

type RunOptions

type RunOptions struct {
	// Quarantine, when set, excludes nodes it blocks from placement and is
	// struck on every document-fingerprint verification failure. Owned by the
	// caller so it survives RunBatched's chunks (and, in the MCP server, the
	// process lifetime).
	Quarantine *Quarantine
	// Priority is the scheduling band every subtask of this run is dispatched
	// with (core.BandSheddable / BandNormal / BandUrgent; clamped). A sheddable
	// run takes only idle fleet capacity: a node without an idle slot refuses it
	// (503, re-placeable), and with no idle node anywhere the subtask is SHED
	// (deferred, class capacity) instead of waiting or queuing behind
	// production work. Measurement and gate traffic runs at -1.
	Priority int
	// Tenant identifies the delegator to the fleet (one MCP server = one Claude
	// session; one CLI process = one tenant) so a node can round-robin its
	// backlog across tenants. Empty = anonymous, arrival order on the node.
	Tenant string
	// LocalDecider is the placement decision a LOCAL run is made under on a
	// composite box (ADR 0052). nil = production: placetable.Decide over the
	// config's layers with ONE memoised placetable.NewSnapshot per run (2 s
	// TTL), so a 32-subtask spread deciding per subtask per tick execs
	// nvidia-smi once, not 32 times. Tests inject readers here; a box with no
	// layers never calls it (the zero Decision is the pre-layer behaviour).
	LocalDecider func(ctx context.Context, contract core.AgentContract, st Subtask) placetable.Decision
	// Rescue re-packs a finished answer whose structured re-pack failed on the
	// executing node (register C-66, PR-4): the delegator holds the answer, so it
	// structures it itself instead of counting a finished loop as lost work.
	// nil = no rescue, the behaviour before the rescue existed: the defer is delivered as it is.
	// The surfaces that own a pipeline wire pipeline.RescueRepack here.
	Rescue RescueFunc
	// Deadline, when non-zero, is the instant the WHOLE call must be over: the
	// MCP doors set it below the client's own abort (config.CallDeadline) so a
	// call returns what has finished instead of being dropped with it (ADR 0065,
	// register C-67). At Deadline every subtask still running is cancelled and
	// published as a budget defer "call deadline reached; N unfinished" beside the
	// finished results, and nothing further is started. The zero value is no
	// deadline — every caller that is not an MCP door, and every pre-0065 call.
	Deadline time.Time
	// OnProgress, when set, is told each time a subtask starts and each time one
	// ends (progress.go). It is called from the run's own goroutines, concurrently,
	// so it must be safe for that and must not block: the MCP doors hand each event
	// to a channel. Nothing in the engine reads it back.
	OnProgress func(ProgressEvent)
	// RosterOnly says the call's remotes list was named by a MODEL (the MCP agent_delegate door), so
	// it may only NARROW the configured fleet: an entry outside cfg.DelegateRemotes, or any entry on a
	// box that configures none, is refused before anything is dialled (CheckRosterRemotes). The
	// operator's own surfaces (the CLI verbs, fleet-smoke) leave it false and keep naming any tailnet
	// node, which is how a node that has not joined the roster yet is tested.
	RosterOnly bool
	// PinReason is the closed reason (privacy, locality, measurement, operator: PinReasons) a caller gave for
	// pinning the call with route local or remote (ADR 0078). A reasoned pin is authoritative, exactly as the route
	// always was, and the reason is recorded on every ledger row and result. CheckPinReason refuses a value outside
	// the set, one the route does not take, and one given with a route that is not a pin, before any placement.
	PinReason string
	// PinNeedsReason is set by the doors that offer pin_reason (agent_delegate, offload_research and their CLI
	// verbs): a route local or remote WITHOUT a PinReason is then a hint that placement may override (see pin.go).
	// The zero value keeps today's authoritative pin for every caller that has no reason channel (fleet-smoke, the
	// review lane's remote fallthrough, offload_ask and agent_run).
	PinNeedsReason bool
	// RemoteRetryOnly keeps the second chance of a route=remote call (a failed verification, an abstention, a seat-down
	// re-issue) on a fleet node: another node takes it or it is not run, and it never lands on this box's seat. It is
	// the narrow half of a reasoned remote pin and no more: it records no pin_reason, so the call stays counted as
	// unreasoned, which is what it is. It is for a door with no reason channel whose own caller already moved the work
	// off this box (offload_ask's cross-seat retry), where the bare remote route's retry would hand it straight back.
	// It does nothing for a route other than remote, for a remote hint (a hint is placed as auto), or beside a
	// PinReason, which already says it.
	RemoteRetryOnly bool
	// PinTally, when set, is the accounting the call's pins are added to (the MCP server's, which offload_status
	// publishes). nil = not counted: the CLI verbs and fleet-smoke are one-call processes with nobody to report to.
	PinTally *PinTally
	// contains filtered or unexported fields
}

Run executes subtasks (bounded concurrency), placing each per route:

"auto"   — gate.go's Place: an idle local node always wins; a held GPU
           lease considers gate-passing remotes; no eligible remote =
           queued-local (quality-first).
"local"  — forced local, no network at all.
"remote" — forced remote; with no gate-passing remote the subtask DEFERS
           loudly rather than silently overriding an explicit route.

The returned error is reserved for CONFIG mistakes (bad route, subtask bounds, a non-tailnet remote) where nothing executed; per-subtask transport failures land in PlacedResult.Err / Summary.Failed instead, so one broken node cannot void seven finished results. RunOptions carries caller-owned state a Run consults but does not own.

type SeatBudgetView

type SeatBudgetView struct {
	StepTokens  int    `json:"step_tokens"`
	FinalTokens int    `json:"final_tokens"`
	Thinking    string `json:"thinking"`
}

SeatBudgetView mirrors fleetnode.SeatBudgetHealth.

type SeatBusy

type SeatBusy struct {
	// Busy is true when the seat has a request in flight, has a load or an unload in progress (llama-swap lists both as a
	// state change the seat cannot be asked through), or is not loaded and loading it would unload another loaded vLLM
	// seat. A seat that cannot be read is not busy: the reading is a reason to place a call elsewhere, never a gate, so
	// "could not read" falls toward running where the call always ran.
	Busy bool
	// Why is the fact behind Busy, for a placement note: "2 in flight", "a load or unload is in progress", or the seat a
	// load would evict. Empty when the seat is not busy.
	Why string
}

SeatBusy is the reading of one local seat.

func LocalSeatBusy

func LocalSeatBusy(ctx context.Context, cfg config.Config, seat, what string) SeatBusy

LocalSeatBusy reads whether the local seat named seat is busy right now. what names the seat's role for the log ("vision seat"). An empty seat or a box with no local endpoint reads idle: there is nothing to queue behind.

type SeatRateView

type SeatRateView struct {
	TokS        float64 `json:"tok_s"`
	ColdLoadSec float64 `json:"cold_load_sec"`
	Samples     int     `json:"samples"`
	MinTurnSec  int     `json:"min_turn_sec"`
	// PrefillTokS / PrefillSlowTokS: the seat's prefill rate (average, and the slowest recent solo
	// sample its stall bound is sized from). 0 = the node publishes none (register F10).
	PrefillTokS     float64 `json:"prefill_tok_s,omitempty"`
	PrefillSlowTokS float64 `json:"prefill_slow_tok_s,omitempty"`
}

SeatRateView mirrors fleetnode.SeatRateHealth.

type Subtask

type Subtask struct {
	Contract  core.AgentContract
	EstTokens int
}

Subtask pairs one delegation contract with its token estimate. EstTokens is carried beside the contract (not recomputed inside Place) so a caller that gains a REAL tokenizer count later can supply it without the gate changing.

type SubtaskSpec

type SubtaskSpec struct {
	core.AgentContract
	ContextPaths []string `json:"context_paths,omitempty"`
}

SubtaskSpec is one surface-level subtask: the wire contract's own fields plus the delegator-side context_paths extension. The embedded contract decodes/encodes under its normal JSON tags, so a CLI contract file and the MCP subtask object share one vocabulary.

type Summary

type Summary struct {
	// Waited / Shed (0.113.18): subtasks that waited for fleet capacity before a
	// node took them, and sheddable subtasks shed for lack of an idle node.
	Waited int
	Shed   int

	Succeeded          int
	Deferred           int
	FailedVerification int
	Failed             int
	// Infrastructure counts the results whose story is a broken stack rather
	// than the work: defers whose defer_class says so (infrastructure|config),
	// PLUS a local placement taken while every configured remote was failing
	// its health probe. It is an ANNOTATION, not a fifth bucket — the four
	// counts above still add up to len(results) without it. It exists because a
	// node with a dead llama-swap otherwise reports exactly what a small model
	// honestly abstaining reports, and both exit 0. A non-zero Infrastructure
	// makes the CLI exit non-zero.
	//
	// Contract-side defers (core.DeferClassContract — no output_schema, past
	// the origin hop, too big for any advertised ceiling) are deliberately NOT
	// counted: the fleet is healthy and the CALLER has a contract to fix, so
	// telling the operator a box is broken sends them to the wrong machine.
	Infrastructure int
	// LostToStack counts the subtasks that DELIVERED NO USABLE RESULT because the
	// stack failed them — a defer whose class is infrastructure|config. It is the
	// half of Infrastructure that represents lost WORK, split out because
	// Infrastructure conflates two states a caller must act on differently:
	//
	//	remotesUnreachable → a result that SUCCEEDED anyway (local took it)
	//	BrokenStackDefer   → a subtask whose contracted output never arrived
	//
	// "No usable result" is not always "no bytes", and the distinction is load-
	// bearing because the PREDICATE is what ships: pipeline/agenttask.go sets
	// wire.Output before the re-pack and keeps it populated on every failure
	// branch below, so the CALLER still receives the loop's answer in the
	// result's `output` field. (It is preserved for the caller, NOT for
	// acceptance. THE RULE, binding on every caller of EvalAcceptance in any
	// package: never evaluate a DEFERRED result. A defer's preserved prose was
	// never offered as an answer, so checking it manufactures failures about
	// content nobody claimed — an honest defer would land in the ledger and the
	// corpus as a verification failure. This package keeps the rule by guarding
	// both call sites on !wire.Deferred, pinned by
	// TestRunLocalDeferSkipsAcceptance; mcpserver's ask lane keeps it by
	// returning on wire.Deferred before it ever reaches the call. Stated as a
	// rule rather than as a tally of call sites on purpose: the tally said "both"
	// while there were three, and a doc comment reads back as evidence the code
	// obeys it.) So a subtask whose agent loop
	// FINISHED and whose re-pack seat was unreachable publishes prose beside
	// defer_class:"infrastructure" and IS counted here. That is
	// deliberate, not an oversight: a contract carrying an output_schema asked for
	// a mechanically checkable deliverable, and prose with no `structured` is not
	// one — the contracted output genuinely did not arrive, so the caller must be
	// told rather than left to merge an unchecked answer. Read this field as "the
	// contracted output was lost", never as "the result is empty".
	//
	// Without the split, "was anything lost?" had no answer in the summary, and
	// the MCP surface approximated it with `Succeeded == 0` — which silenced a
	// subtask genuinely eaten by a broken box the moment ANY sibling succeeded.
	// `Deferred > 0 && Infrastructure > 0` is NOT the same predicate and cannot
	// replace this: a contract-classed defer sitting beside a fleet-down local
	// success satisfies both while nothing was lost to the stack at all.
	//
	// Like Infrastructure it is an ANNOTATION, not a fifth bucket — it is a
	// subset of BOTH Deferred and Infrastructure, and the four counts above
	// still add up to len(results) without it.
	LostToStack int
	// CorpusRows*/LedgerRows* count the telemetry rows this run ATTEMPTED and
	// LOST. Telemetry never fails the work, but "this run's corpus rows are
	// LOST" reads identically whether 1 of 8 or 8 of 8 failed — and the MCP
	// caller, this lane's primary consumer, could not see it at all until these
	// rode the published summary.
	//
	// Attempted ships beside Lost because the doc promised "N of M" and only N
	// was published, leaving the caller unable to reconstruct M. And the TOTAL
	// loss — ledger.Open itself failing — used to increment nothing at all
	// (record()'s `if r.led != nil` guard), so the worst case published
	// byte-identically to a run that wrote every row.
	CorpusRowsAttempted int
	CorpusRowsLost      int
	LedgerRowsAttempted int
	LedgerRowsLost      int
	// Retried counts subtasks that got a second attempt on a different node
	// after a failed_verification / abstention; RetryRecovered is the subset the
	// second attempt turned into a success. Annotations, not buckets: the four
	// outcome counts above still add up to len(results).
	Retried        int
	RetryRecovered int
	// Replaced counts subtasks RE-PLACED at least once after a node refused
	// them at dispatch. ReplacementRecovered is the subset that then reached a
	// node which TOOK the work — the subtask stopped being a refusal.
	//
	// Read ReplacementRecovered precisely: it says the work was PLACED, not
	// that the answer was good. A re-placed subtask whose seat then deferred,
	// or whose result failed acceptance, still counts here, because the defect
	// this fixes is work that nobody ran at all. The four outcome counts above
	// say what the answer was. Annotations, not buckets.
	Replaced             int
	ReplacementRecovered int
	// Quarantined counts nodes that FLIPPED into quarantine during this run
	// (two document-fingerprint failures inside the TTL). Batches counts the
	// deals RunBatched ran: 1 for a batched call of up to MaxBatchSubtasks (it was
	// 2 for 9 to 12 pages), more only for a longer list (ADR 0076); 0 for a plain Run.
	Quarantined int
	Batches     int
	// Skipped counts subtasks RunBatched never attempted because an earlier
	// chunk returned a top-level error — they are in no result and in no other
	// counter, so without this they would vanish from the summary.
	Skipped int
}

Summary is the per-run outcome tally, reported AT THE TOP of every surface's result (roast delta 14): eight quiet defers must read as a loud outcome, not eight green jobs.

type SummaryWire

type SummaryWire struct {
	Succeeded          int `json:"succeeded"`
	Deferred           int `json:"deferred"`
	FailedVerification int `json:"failed_verification"`
	Failed             int `json:"failed"`
	Infrastructure     int `json:"infrastructure"`
	// LostToStack is the half of Infrastructure that is LOST WORK: subtasks whose
	// CONTRACTED OUTPUT never arrived because the stack failed them, as opposed to
	// a successful local placement annotated with "the fleet was down". omitempty —
	// a run that lost nothing publishes byte-identically to before this field
	// existed.
	//
	// `output` on such a result may be NON-EMPTY, and a reader must not treat this
	// count as "the result is blank": an agent loop that finished and then could
	// not reach the re-pack seat publishes its prose beside
	// defer_class:"infrastructure" with `structured` absent. It still counts as
	// lost, because a contract carrying an output_schema asked for a checkable
	// deliverable and unchecked prose is not one.
	//
	// It is published rather than kept internal because a partial result is no
	// longer error-flagged (C-75): `infrastructure: 1` beside `succeeded: 1` does
	// not say on its own whether a subtask was eaten, and this count is the
	// caller's loud signal for it. The MCP error flag now marks only a call that
	// delivered nothing.
	LostToStack int `json:"lost_to_stack,omitempty"`
	// CorpusRows*/LedgerRows* publish telemetry loss to the CALLER. omitempty:
	// a healthy run's response stays byte-identical to before these fields
	// existed. They are not outcome buckets — the four counts above still add
	// up to len(results) — but a delegation that wrote nothing to the standing
	// corpus published identically to one that wrote everything, and the MCP
	// caller had no way to learn it.
	//
	// The *Attempted counts ride ALONGSIDE their losses — Summary carries them
	// only when there IS a loss, so the byte-identity promise above still holds
	// for a healthy run: "N rows lost" is unreadable without the M it was lost
	// out of, and 1 of 8 is a transient while 8 of 8 is a full disk.
	CorpusRowsLost      int `json:"corpus_rows_lost,omitempty"`
	CorpusRowsAttempted int `json:"corpus_rows_attempted,omitempty"`
	LedgerRowsLost      int `json:"ledger_rows_lost,omitempty"`
	LedgerRowsAttempted int `json:"ledger_rows_attempted,omitempty"`
	// Retried / RetryRecovered: second attempts on a different node after a
	// failed_verification or abstention, and how many of them recovered.
	// omitempty — a run with no retry publishes byte-identically to before.
	Retried        int `json:"retried,omitempty"`
	RetryRecovered int `json:"retry_recovered,omitempty"`
	// Replaced / ReplacementRecovered: subtasks a node REFUSED at dispatch and
	// the delegator re-placed on another node, and how many of those then
	// reached a node that took the work. omitempty — a run where nothing was
	// refused publishes byte-identically to before this existed.
	//
	// They are published rather than kept internal because a fleet quietly
	// shedding load onto one box is otherwise invisible: every subtask still
	// completes, the four buckets read green, and nothing anywhere says the
	// roster is saturated. `replaced: 6` on a healthy-looking run is the line
	// that sends an operator to fleet_max_queue_depth before the next run has
	// nowhere left to go.
	Replaced             int `json:"replaced,omitempty"`
	ReplacementRecovered int `json:"replacement_recovered,omitempty"`
	Quarantined          int `json:"quarantined,omitempty"`
	Batches              int `json:"batches,omitempty"`
	Skipped              int `json:"skipped,omitempty"`
	// Waited / Shed (0.113.18): subtasks that waited for fleet capacity before a
	// node took them (the capacity wait: the call's deadline less a reserve, else
	// agent_placement_wait_sec, ADR 0073), and
	// sheddable subtasks (priority -1) that found no idle node and were shed
	// (defer_class capacity). omitempty — a run that neither waited nor shed
	// publishes byte-identically to before. `waited: 5` on a green run is the
	// line that says the fleet was full and the wait is what saved the work.
	Waited int `json:"waited,omitempty"`
	Shed   int `json:"shed,omitempty"`
}

SummaryWire is the top-of-response tally. Infrastructure is a SUBSET of Deferred (the defers whose class blames the stack or the config, not the work), published beside it so "one node is broken" cannot hide inside a green-looking defer count.

Jump to

Keyboard shortcuts

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