This is the supported embedding surface for downstream products (e.g.
tracker-runner) that run Tracker as a library instead of shelling out to the
tracker CLI. Everything here is a stable seam — build on it rather than
hand-composing pipeline.NewEngine, which is exactly how stale runners
re-accrued missing budget/cost/gateway/backend wiring.
All of it lives in the top-level tracker package (tracker.go,
tracker_*.go). Import only that package — LLM clients, registries, and
environments are auto-wired from Config.
| Entry point | Use |
|---|---|
tracker.Run(ctx, source, cfg) (*Result, error) |
One-call convenience: parse → wire → execute → Close(). source is pipeline content (a .dip string, or a strict digraph DOT string — DOT is deprecated), not a path. |
tracker.NewEngineWithContext(ctx, source, cfg) (*Engine, error) |
Construct without running (call engine.Run(ctx) yourself); defer engine.Close(). |
tracker.NewEngineFromGraph(ctx, graph, cfg) (*Engine, error) |
Construct from an already-parsed *pipeline.Graph, skipping the parse step. This exists (tracker.go) — use it when you hold a graph in memory. |
tracker.ParseSource(source, format, opts...) (*pipeline.Graph, error) |
Parse without constructing, with the same sidecar resolution Run/NewEngine apply: pass WithSource(SourceRef{Builtin: "build_product"}) (or info.Ref() from OpenWorkflow/ResolveSource) and prompt_file/command_file resolve from the embed FS and the graph is marked as the built-in, so NewEngineFromGraph materializes its ${graph.workflow_dir} tree. Use this — not pipeline.LoadDippinWorkflow on the raw text, which fails at the first prompt_file — when you must mutate the graph first (per-node model tiering, a forced provider, attr injection) and then call NewEngineFromGraph. |
tracker.Config |
The single wiring struct. Zero value is usable; every field is optional. |
Key Config fields for embedders: WorkingDir, ArtifactDir, CheckpointDir,
ResumeRunID, Provider/Model, Backend, LLMClient (inject a custom
agent.Completer), EventHandler/AgentEvents (live streams), TokenTracker,
Budget, GatewayURL/GatewayKind, Interviewer (the human-gate transport
seam), Subgraphs, Git, GitArtifacts, SteeringChan, Capture (on-disk
run capture — run.json + spec + activity.jsonl, see §4a), Inputs (the
workflow's declared input values — see §1a).
Config.Backend takes native, claude-code or acp; "auto" is rejected
because backend: auto is a node value (an explicit Config.Backend also
overrides auto nodes). An engine constructs without a native client when no
agent node needs one (all auto / claude-code / acp), so explain runs
with no LLMClient and no provider key on a machine with Claude Code. A
workflow that keeps state in its run dir — quickfix does — needs
Config.ArtifactDir set: with no artifact dir, tools get no
TRACKER_RUN_DIR and quickfix refuses at Preflight.
The library never loads .env files. Provider keys, base URLs and
TRACKER_* knobs are read from the process environment the embedder
provides; the CLI's source-aware .env loader (cmd/tracker/envfiles.go,
env-policy.md) is CLI-only. An embedder that wants
file-based configuration owns that policy, and should treat anything a
checkout can write as untrusted for everything but provider keys.
A workflow can declare a typed input signature via a dippin inputs block
(dippin #190, requires dippin ≥ v0.51). The engine treats it as a first-class
contract — the seam a host (tracker-runner, a web/Slack front-end) uses to
collect and validate caller data before committing a run:
| Entry point | Use |
|---|---|
tracker.DescribeInputs(source, format) ([]pipeline.InputSpec, error) |
Introspect the declared schema without running — render a form or ask conversationally. Returns nil for a pipeline with no inputs block. |
tracker.ValidateInputs(specs, []tracker.Input) []pipeline.InputError |
Validate supplied values standalone (before Run). Structured, per-input errors (missing_required, type_mismatch, pattern, range, length, enum, unsupported_kind, unknown_input) so a host re-prompts precisely. |
tracker.StringInput(name, value) / FileInput(name, path) / FileInputBytes(name, bytes) / SecretInput(name, value) |
Build the []tracker.Input for Config.Inputs. FileInputBytes is for values that arrive over the wire (no local path). SecretInput stages the value to a 0600 file so ${inputs.<name>} is only the path (see the secret bullet below). |
Config.Inputs []tracker.Input |
Supplied values, validated + bound at run start. |
Semantics:
- Fail closed at t=0. A missing required input or a constraint violation
returns
*tracker.InputValidationErrorfromNewEngineFromGraph/Runbefore any node executes — no silent empty-string expansion mid-run. (An empty/whitespace value for a required input counts as missing.) ${inputs.<name>}namespace. Bound values are read via a dedicated, closedinputs.*namespace, untrusted by construction — never interpolated into atool_command(seecontext-flow.md).- File inputs are staged. A
fileinput (path or inline bytes) is copied at run start to<workDir>/.tracker/inputs/<name>— a fixed, deterministic path derived from the declared name — and${inputs.<name>}is that relative path. A workflow's shell reads the staged path directly (safe); the untrusted value never enters the command.build_productuses this: supplyspecand it is adopted asSPEC.md. Staged files travel in the run dir (checkpoint / bundle). secretinputs are staged like files: the VALUE is written to a 0600 file at<workDir>/.tracker/inputs/<name>and${inputs.<name>}resolves to the PATH, never the value — so the secret stays out of prompts, the provider wire, the trace, and the checkpoint (SecretInput(name, value)). Read it from the staged path in a tool..tracker/is git-excluded from artifact repos so it never reaches a commit/bundle. Residual: the 0600 file on same-UID local disk, and the value on the provider wire once the agent uses it.- Backward compatible. A pipeline with no
inputsblock is unaffected;DescribeInputsreturns nil and binding is a no-op.
Config.GitArtifacts bool— makes the artifact run dir a git repo and commits after every terminal node outcome. Requiresgitin PATH and is a no-op unlessConfig.ArtifactDiris set. This is the seam for branch-per-run and PR-as-deliverable. (Before this field existed,WithGitArtifactswas an engine-only option unreachable from the libraryConfig— embedders could not enable git artifacts at all.)Result.ArtifactRunDir— the canonical run-dir locator (<artifactDir>/<runID>). Pass it toExportBundle.tracker.ExportBundle(runDir, outPath) error— wrapsgit bundle create --allfor portable, single-file run history. The canonical hand-off pattern for a remote worker →git clone <bundle>on the user's machine. Populates nothing onResultunless you call it; setResult.BundlePathyourself if you track it.
- Per-run usage:
Result.Trace.AggregateUsage() *pipeline.UsageSummaryaggregates all session stats + child-run rollups.UsageSummarycarriesTotalInputTokens/TotalOutputTokens/TotalTokens/TotalCostUSD, cache/reasoning totals,SessionCount, andProviderTotals map[string]pipeline.ProviderUsage(per-provider breakdown). Per-node stats hang offTrace.Entries[].Stats(pipeline.SessionStats). - Dollar cost:
Result.Cost *CostReport(TotalUSD,ByProvider map[string]llm.ProviderCost,LimitsHit);Result.TokensByProviderfor rawllm.Usageper provider. - Budget enforcement: set
Config.Budget pipeline.BudgetLimits(MaxTotalTokens,MaxCostCents,MaxWallTime,StallTimeout,SleepAware).tracker.ResolveBudgetLimits(cfg.Budget, graph)folds in workflow-leveldefaults:(Config wins). A breach yields terminal statusbudget_exceededandEventBudgetExceeded. - The exact field shapes of
SessionStats/UsageSummary/ProviderUsageare pinned by the golden-trace fixtures (§5) — a rename or retype breaks them.
- Status is an open enum.
Result.Statusis one ofsuccess,fail,budget_exceeded,validation_overridden,paused_billing,paused_gatetoday; future minors may add more. Never switch exhaustively on the raw string — classify withpipeline.TerminalStatus(r.Status).IsSuccess()(fail-closed) and treat an unknown value as "not a success I understand", not as a failure to report. paused_billingis recoverable, not failed. Provider credit/quota exhaustion (#487) stops the run in a resumable terminal: the checkpoint is written and in-flight work preserved, so re-running withConfig.ResumeRunID = <run id>(sameWorkingDirand sameConfig.ArtifactDirthe run used) continues from the paused node once credits are topped up.ResumeRunIDresolves the run in that artifact dir (#696), and the resumed run writes its node artifacts and checkpoint snapshot there; with a differentArtifactDirthe run is split across two dirs (a full ID still resumes from the secure checkpoint, with a warning). Exception: a run started with an explicitConfig.CheckpointDirresumes with that sameCheckpointDir. A setCheckpointDiris loaded as-is and bypassesResumeRunIDresolution entirely, and such a run writes no secure or artifact-dir checkpoint copy forResumeRunIDto find. Otherwise leaveCheckpointDirunset.Runreturns both thepaused_billingresult and the billing error, so a control plane must classify onResult.Status—err != nilalone is not "dead". UnderRunManagerthis surfaces asRunPausedwithManagedRun.ResumeRunID()(§ Concurrency intransport-boundary.md).paused_gatewaits for an answer. WithConfig.GateMode: "pause"(needsConfig.ArtifactDir) a human gate stops the run in the resumablepaused_gateterminal instead of blocking;Result.PausedGatenames the gate andRunreturns the result with a*pipeline.PauseError. To answer, calltracker.Answer(ctx, source, cfg, tracker.AnswerInput{RunID, Label | Text | Default | InterviewAnswers | Cancel})with the run's own source andConfig: it reads the gate from the secure checkpoint (tracker.PendingGates), validates the answer (tracker.ValidateAnswer— case-insensitive labels, an error listing the valid ones), takes the run lock, and resumes the run with the answer held in memory. When a parallel node's branches wait at several gates, answer them all at once withAnswerInput.Gates(keyed by gate node ID or<scope>/<node>): the resume re-runs the parallel node, so an unanswered sibling gate would pause it again.tracker.WaitingRuns(artifactDir)lists runs waiting at a gate. Every resume of an existing checkpoint takes the same OS file lock, so a second resume of a run in progress fails withpipeline.ErrRunLocked. A gate-paused resume keeps its context as-is (no resume compaction) and its budget runs across answers. Seehandlers/human.md.- Events:
Config.EventHandler pipeline.PipelineEventHandlerreceives thepipeline.PipelineEventstream (types inpipeline/events.go);Config.AgentEvents agent.EventHandlerreceives per-sessionagent.Events.tracker.NewNDJSONWriter(io.Writer)yields the same stream shape astracker --json. StreamEventis at payload parity withactivity.jsonl. The NDJSON envelope carries the structured payloads — cost snapshot (total_cost_usd,provider_totals,wall_elapsed_ms,estimated), edge decisions (edge_from/edge_to/edge_priority/condition_match/context_snapshot), truncation / marker / route diagnostics, override detail, the full gate payload (gate_mode,gate_prompt,gate_choices,gate_questions,gate_response,gate_actor), per-turn agent usage (token_input/token_output/cache_read_tokens/cache_write_tokens/estimated_cost), and thepipeline_startednode inventory (snapshot_nodes,snapshot_*). Field names are identical to theactivity.jsonlline schema wherever the datum is shared, so one decoder serves both; only thesnapshot_*group is wire-only. (The per-turn cache/cost figures were briefly carried under a second name settoken_cache_read/token_cache_write/turn_cost_usd; #520 converged them onto the singlecache_read_tokens/cache_write_tokens/estimated_costset.) Every field isomitempty— read the ones documented for the event'stypeand tolerate unknown keys.ActivityEntryis at payload parity too — replay reads like the live stream.tracker.ParseActivityLine/LoadActivityLog/ScanActivityLogdecode every field the runtime writes toactivity.jsonl, so reconstructing a finished run through the supported reader loses nothing: same cost snapshot, edge decisions, tool diagnostics, override detail and gate lifecycle (gate_idcorrelatesgate_openedwithgate_resolved), plus the line'sSource(pipeline/agent/llm/cli) andBundleIdentity. Each field's Go name is the same as the matchingStreamEventfield, so code that follows a live run and code that replays a finished one read the same names.ActivityEntryis deliberately not a JSON wire type (the log has two historical timestamp formats, andtime.Timeunmarshals only RFC3339Nano) — decode withParseActivityLine, neverjson.Unmarshal, and map to your own wire type when re-encoding.ConditionMatch/RestartCountare pointers sofalse/0is distinguishable from "the line does not carry it"; every other optional field reads as its zero value. Unknown keys are ignored, so a log written by a newer runtime still parses.
The three seams above (EventHandler, AgentEvents, LLMTrace) are the live
streams — nothing about them writes to disk. On-disk run capture (the
activity.jsonl audit log, the spec artifacts, and the run.json manifest) is a
separate concern the CLI produces by wiring a pipeline.JSONLEventHandler into
all three seams and finalizing the spec/manifest after the run. Hand-wiring all
of that is error-prone: forget LLMTrace and run.json has no per-call counts;
wire WriteLLMEvent instead of LLMTraceObserver() and every session call is
logged twice (the session re-emits its trace as agent llm_* events).
Config.Capture *CaptureConfig does it for you — the same path the CLI now
uses, so the two cannot drift:
res, err := tracker.Run(ctx, source, tracker.Config{
WorkingDir: workDir,
Capture: &tracker.CaptureConfig{}, // empty value is enough
})
// res.ArtifactRunDir/{run.json, workflow.dip, workflow.ir.json, activity.jsonl}- Produces, under
Result.ArtifactRunDir(<ArtifactDir>/<runID>, defaulting to<WorkingDir>/.tracker/runs/<runID>whenArtifactDiris unset): the identity-bearingactivity.jsonl(secure path + a sentinel-stripped snapshot), the spec artifacts (workflow.dipverbatim + the expandedworkflow.ir.json+ redacted params, keyed offpipeline.SpecSourceFile/SpecIRFile), and therun.jsonmanifest (pipeline.RunManifestFile). - On the
Run/NewEngineWithContextpath an emptyCaptureConfig{}is enough: the library fillsSourceand the expanded IRWorkflowfrom the source it parsed. FromNewEngineFromGraph(no source string), setSource/Workflow/SourcePathyourself if you want the spec artifacts. CaptureRawLLMmirrors the CLI's--verbose: it stores raw provider streaming chunks (off by default — they are ~92% of log volume and are debugging payload).- The
LLMTraceSessionOwned de-dup is handled internally, so each LLM call is logged exactly once even though capture wires all three seams to one handler. - The raw seams keep working alongside capture: any
EventHandler/AgentEvents/LLMTraceyou also set is fanned out in addition to the capture handler (this is exactly how the CLI keeps its console/TUI output). - The engine owns the capture handler's lifecycle:
run.jsonis finalized insideEngine.Run, and theactivity.jsonlsnapshot is flushed onEngine.Close. Do not also pass your ownJSONLEventHandlerwhen usingCapture— pick one or the other. Read the result back withtracker.LoadActivityLog/pipeline.AssembleRunManifest(see §4).
Downstream ports cross many engine versions; tests written against old shapes
pass while behavior silently drifts. The tracker-conformance binary ships
golden-trace fixtures to catch that mechanically:
tracker-conformance golden <fixture.dip>
emits a normalized, deterministic JSON document — event sequence,
per-node SessionStats, aggregate UsageSummary, and terminal status/class —
generated via a stub completer (no API keys, no wall-clock/run-id/duration
noise). Committed goldens live at cmd/tracker-conformance/testdata/golden/*.golden.json
and are versioned in lockstep with the tracker tag (GoReleaser ships the
binary). A downstream port pins a tracker version and diffs the binary's
stdout (or the committed file) against its own expectation; any event-schema,
handler-contract, or usage-shape change surfaces as a diff.
Regenerate after an intentional engine change:
go test ./cmd/tracker-conformance -run TestGoldenTraces -update-golden
Coverage (what is and isn't pinned). The fixtures pin the start/exit,
tool, wait.human (yes_no, auto-approved), conditional-edge routing, codergen,
and parallel/parallel.fan_in handler contracts; the
SessionStats/UsageSummary/ProviderUsage shapes (single- and multi-session);
the EventStageRetrying retry path; and the success, fail, and
budget_exceeded terminal statuses/classes (agent_linear, control_flow,
tool_failure, parallel_fanin, budget_exceeded, retry_exhausted).
Because parallel branches emit events from concurrent goroutines with no stable
cross-node order, the schema (v2) groups events per node (node_events) plus
a node-less pipeline_events stream, and sorts trace entries / completed nodes by
node id. Only within-node event order is pinned — that's the only order the
engine reproduces under parallelism. A downstream harness must normalize the same
way or parallel fixtures will flake.
These contracts are now pinned too: the validation_overridden terminal +
EventValidationOverridden (validation_overridden), the subgraph handler with
child-usage rollup (subgraph), the stack.manager_loop supervisor with scoped
child events (manager_loop), mode=interview driven by the deterministic
auto-approve interviewer (interview), and the recoverable paused_billing
terminal + EventBillingPaused (#487) via a stub completer that returns a billing
error (paused_billing).
- Transport boundary (how front-ends plug in):
transport-boundary.md - System orientation:
../../ARCHITECTURE.md