Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat: add behavioral trajectories and local learning (#246)

justrach5aed7f132fa5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index edf88713..9f6bfc53 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -40,7 +40,7 @@ jobs:
run: zig build
- name: zig fmt --check
- run: zig fmt --check src/main.zig src/mcp.zig build.zig
+ run: zig fmt --check src build.zig
- name: Zig source size guard
run: bash scripts/check-zig-lines.sh
@@ -48,6 +48,9 @@ jobs:
- name: zig build test
run: zig build test --summary all
+ - name: Local learning lifecycle and security regression
+ run: python3 tests/learn_e2e.py --graff zig-out/bin/graff
+
- name: JSON live-control protocol test
run: python3 scripts/test-json-controls.py zig-out/bin/graff
diff --git a/README.md b/README.md
index 403f30ee..460df639 100644
--- a/README.md
+++ b/README.md
@@ -236,9 +236,9 @@ so the harness itself is the substrate for agent self-improvement. Each run
writes a unique `.graff/trajectories/<run-id>.jsonl`; archive readers aggregate
the directory, so concurrent processes never share a truncate/append cursor:
-- **A lineage tree, not a flat log.** Root turns form a spine (each turn's
- parent is the previous one); every subagent and workflow task hangs off the
- turn that spawned it. Each node carries a **fingerprint of the system prompt
+- **A lineage tree, not a flat log.** Interactive root turns form a spine (each
+ turn's parent is the previous one); every subagent and workflow task hangs off
+ the turn that spawned it. Each node carries a **fingerprint of the system prompt
it ran with** (`prompt_sha` = first 8 bytes of SHA-256), so prompt mutations (
`set_system_prompt` on the spine, per-child `system_prompt` overrides on the
fan-out) show up as hash changes along edges. A lineage can be replayed or
@@ -264,6 +264,14 @@ the directory, so concurrent processes never share a truncate/append cursor:
just one laptop. `/trajectory` renders the current session's agent tree; see
[docs/hyperagents.md](docs/hyperagents.md) for the full design.
+For controlled local hill-climbing, `graff learn` adds a separate
+parent → mutate → paired-evaluate → select loop with immutable evidence, manual
+promotion by default, explicitly gated automatic promotion, atomic activation,
+and rollback. It never treats trajectories or best-effort telemetry as promotion
+authority. See [Local prompt-policy learning](docs/local-learning.md), including
+the no-sandbox trust boundary and the collective-learning design that is **not**
+yet an implemented remote authority.
+
---
## Providers & models
@@ -353,6 +361,7 @@ usage:
graff key list show which providers have keys
graff mcp add <name> -- <cmd> add an MCP server to .mcp.json
graff mcp list configured MCP servers
+ graff learn <command> local prompt-policy learning and rollback
graff --schema print the machine-readable interface (SDK codegen)
flags:
@@ -373,6 +382,10 @@ dispatch, so `graff login --help` prints usage instead of starting an OAuth
flow. With no key configured at all, startup fails with the three quickest fixes
spelled out rather than a bare env-var list.
+`graff learn help` lists the local learning commands. Configuration, adapter
+protocols, statistical gates, activation semantics, and security limitations are
+specified in [docs/local-learning.md](docs/local-learning.md).
+
**One-shot mode** makes the harness scriptable without the SDK: `graff -p "how
many TODOs in src/?"` runs a full agentic turn (tools included), prints only the
final answer on stdout (progress lines go to stderr), and exits non-zero on
@@ -766,7 +779,8 @@ request/response bytes, context tokens) and every tool execution (duration,
result size, errors, root-vs-subagent) is appended as one JSON line to the
run's unique `.graff/traces/<run-id>.jsonl`. Every line carries the run id, PID,
and runtime session id; concurrent processes therefore remain independently
-inspectable. The system prompt tells the agent how to locate the file, so
+inspectable. API/tool rows also carry the active behavioral `turn` when one
+exists. The system prompt tells the agent how to locate the file, so
"profile yourself" or "why was that slow?" makes it answer from data. `/trace`
toggles tracing and prints the exact path.
@@ -786,24 +800,63 @@ suffix forward verbatim. A shared atomic run budget allows at most four model
calls concurrently and one subagent level; set the total provider-call ceiling
with `--max-model-calls N` or the lower-precedence `GRAFF_MAX_MODEL_CALLS`.
+**Behavioral trajectories are a separate experimental stream.** Each initialized
+agent session can write an exclusively-created
+`.graff/trajectories/<run_id>.jsonl` with an ordered, attributable lifecycle
+envelope. The local JSONL is never uploaded wholesale. Local capture defaults on
+and is independently disabled with `GRAFF_BEHAVIOR_TRACE=off`.
+
+When ordinary telemetry is enabled, Codegraff also defaults to one bounded,
+end-of-run **field-allowlisted metadata** POST. A terminal `/v1/logs` path is
+replaced with `/v1/behavior`; otherwise `/v1/behavior` is appended to the
+configured base path. Query parameters are preserved and URL fragments omitted.
+Disable it with `GRAFF_BEHAVIOR_UPLOAD=off` or either ordinary telemetry opt-out.
+Only exact lowercase `metadata` or `content` values enable an explicit upload
+mode; `content` opts into caller-supplied adapter content and unknown/case/
+whitespace variants fail closed. `GRAFF_TELEMETRY_KEY` supplies an optional
+bounded `x-harness-key` token to both OTLP and behavioral requests. Metadata mode
+includes lifecycle/correlation fields, a controlled client class (`harness`,
+`sdk-ts`, or `sdk-py`), an initial run-start provider/model/effort snapshot,
+drop/completeness status, and content-free per-turn API/tool-category aggregates.
+The local prompt fingerprint is omitted from default metadata because a
+low-entropy prompt can be recovered by enumeration. It has no dedicated fields for prompts, generated text or hidden
+reasoning, source code or diffs, filesystem paths or repository names, tool
+arguments/results, commands, arbitrary environment values, or exact private MCP
+names. Provider and model identifiers are included exactly as configured; Phase
+1 does not inspect, classify, or redact those identifier values.
+
+Ordinary Phase 1 runs contain lifecycle events only: typed
+commitment/misprediction APIs exist, but no built-in task adapter calls them yet.
+Content mode adds fields supplied through those APIs, with no redactor or secret
+scanner; the local prompt fingerprint remains excluded. This is not yet a
+generic predict → act → verify → repair loop
+or a behavioral score source. Individual collector rows are not publicly exposed;
+public behavioral statistics are aggregate-only, and opted-in content rows expire
+after 30 days. See [the schema, privacy policy, and current
+limitations](docs/behavioral-trajectories.md).
+
**Telemetry, pseudonymous, opt-out, on by default.** *Every* build (release,
source, and dev) bakes in a default OTLP endpoint (pass `-Dtelemetry-endpoint=""`
-to disable it at build time), so by default a session ships best-effort OTLP/HTTP
-JSON POSTs to `<endpoint>/v1/logs` (at exit, plus mid-session batches). **Opt out
-any time** with `--no-telemetry` or `GRAFF_NO_TELEMETRY=1`; setting
-`OTEL_EXPORTER_OTLP_ENDPOINT` (or `GRAFF_OTEL_ENDPOINT`) redirects it to your own
-collector instead.
+to disable it at build time). A default session ships best-effort operational
+OTLP/HTTP JSON POSTs to `<endpoint>/v1/logs` (at exit, plus mid-session batches)
+and the metadata-only behavioral POST described above. **Opt out of both** with
+`--no-telemetry` or `GRAFF_NO_TELEMETRY=1`; setting
+`OTEL_EXPORTER_OTLP_ENDPOINT` (or `GRAFF_OTEL_ENDPOINT`) redirects both paths to
+your own collector instead. `GRAFF_BEHAVIOR_UPLOAD=off` disables only the
+behavioral POST.
It's *pseudonymous, not anonymous*: records carry a **random** per-install id
(`~/.simple-harness-install-id`, generated with `io.random`, not derived from your
-name, host, or user) plus your request IP, version, OS, and arch. The payload is
-**counts, hashes, and tool names**: a `session` summary (duration, turns, API/tool
-call+error counts, models used, workflow/ultracode counts), per-`workflow` and
-per-error records, and per-turn/score records keyed by a one-way **system-prompt
-fingerprint** + `prompt_sha` hashes with a tool-**name** sequence (e.g.
-`read_file, bash, edit_file`). It does **not** send your prompts, your code, file
-contents, file paths, or tool arguments. Your input is never an argument to any
-telemetry call.
+name, host, or user) plus your request IP, version, OS, and arch. The
+**operational OTLP payload** is counts, hashes, and tool names: a `session`
+summary (duration, turns, API/tool call+error counts, models used,
+workflow/ultracode counts), per-`workflow` and per-error records, and
+per-turn/score records keyed by a one-way **system-prompt fingerprint** +
+`prompt_sha` hashes with a tool-**name** sequence (for example,
+`read_file, bash, edit_file`). It does not send prompts, code, file contents,
+file paths, or tool arguments. The separately bounded behavioral payload follows
+the metadata/content rules above; only explicit content mode permits opaque
+adapter fields that may contain task content.
**Fleet / evolution signals** (`fleet:propose|submit|elite_pull`, the
agent-evolution fitness loop) ride the same channel and have a *separate* opt-out:
diff --git a/architecture.md b/architecture.md
index d2f98317..c10bd6f0 100644
--- a/architecture.md
+++ b/architecture.md
@@ -428,11 +428,90 @@ threaded through every agent and
label); `execTool` wraps every external tool with timing. Events are structs
serialized by `std.json.Stringify` — one line each, flushed immediately, so
the file is always valid JSONL mid-session. Every line carries the run id,
-PID, and runtime session id. The system prompt points the agent at the file,
-which is what makes self-debugging work: the agent reads its own trace with
-`read_file` and analyzes it. `/trace` locates and toggles it, best-effort
+PID, and runtime session id. Consumers must still tolerate a malformed final
+tail after a crash or I/O failure. The system prompt points the agent at the
+file, which is what makes self-debugging work: the agent reads its own trace
+with `read_file` and analyzes it. `/trace` locates and toggles it, best-effort
(a failed open just disables tracing).
+`BehaviorTrace` is a second, mutex-protected producer with two independent
+sinks: a per-run `.graff/trajectories/<run_id>.jsonl` local stream and an optional
+bounded `behavior_upload.Upload` projection. Both use flat
+`codegraff.behavior.v1` events and retain one logical source sequence. A healthy
+local file is a contiguous prefix; bounded upload admission can preserve sparse
+source sequence numbers and reports gaps with `dropped_events`. Main owns both
+sinks, joins session workers before terminal closure, emits `run_finished`, and
+then makes at most one best-effort three-second POST beside the configured OTLP
+endpoint at `/v1/behavior`. An upload claims `complete=true` only when terminal
+event admission succeeds; a dropped terminal remains `complete=false` and is
+included in `dropped_events`. Timeout cancellation synchronously joins the HTTP
+task before its payload is released. The local file itself is never uploaded.
+
+`providers.runTurnWithFallback` is the common root-turn boundary. API/tool rows
+in the operational trace carry that active turn until the provider operation
+returns; subsequent administrative or resume-preprocessing work is turn `0`.
+The upload accumulates content-free per-turn API/tool-category metrics. Local
+run-start provider/model/effort/prompt-fingerprint fields are explicitly an
+initial snapshot, not per-turn wire facts. The deterministic prompt fingerprint
+is omitted from every network projection because low-entropy prompt variants can
+be enumerated. With ordinary telemetry enabled,
+the upload defaults to a fixed-field allowlisted metadata projection, including
+only a controlled client class rather than arbitrary `HARNESS_CLIENT` content;
+only an explicit content opt-in can serialize opaque fields supplied through the
+typed commitment/misprediction APIs. Provider/tool plumbing does not infer dedicated
+prompt-text, generated-output, hidden-reasoning, source, path, argument, result,
+or task-state fields. Initial provider and model identifiers are serialized
+exactly as configured and are not inspected or value-redacted. No built-in
+production adapter invokes the typed APIs yet, and automatic
+verification, behavioral scoring, repair, and fleet consumption remain deferred.
+The pre-existing append-only `Trajectory` DGM ledger and its record shapes remain
+unchanged. See
+[`docs/behavioral-trajectories.md`](docs/behavioral-trajectories.md).
+
+## Local learning engine
+
+`startup.zig` dispatches `graff learn` before ordinary provider/key/session
+initialization. `learn_cli.zig` owns strict command parsing and orchestration;
+`learn_eval.zig` owns typed mutation/evaluation protocols, deterministic seeds,
+paired aggregation, and evidence re-verification; `learn_store.zig` owns the
+private content-addressed store and activation transaction chain. The engine is
+separate from the append-only DGM trajectory and behavioral streams: neither is
+accepted as promotion evidence.
+
+A run binds the immutable config, harness version, parent genome, parent
+generation, parent transaction, random nonce, and a recomputed trial ID.
+Candidate and pair seeds derive from that envelope. Adapter requests/responses,
+genomes, and the final run record are domain-separated immutable objects. On
+promotion the engine reloads every object, reconstructs seeds and aggregates,
+checks mutation output bytes against the mutator's declared SHA-256, and requires
+the run's complete parent ref to equal the active ref.
+
+Repetitions remain useful measurements but are clustered by unique suite case
+for the one-sided sign test and `minimum_pairs`; repeating one case cannot create
+independent statistical units. Critical regressions reject immediately,
+Bonferroni correction uses the planned candidate count, holdout gates follow the
+primary gate, and cost participates only after correctness.
+
+Configured tools, declared inputs, and suites are read and hash-checked through
+single open handles. Each invocation executes a private verified program
+snapshot; the program must remain directly executable after relocation. Exact
+declared-input arguments are rewritten to private snapshots, and the evaluator
+sees a private `suite.json`. This closes pathname-reopen TOCTOU for the bytes
+Codegraff claims to pin. It is not process isolation: interpreters, libraries,
+undeclared dependencies, subprocesses, network data, and all other files visible
+to the user's OS account remain in the trusted computing base.
+
+On POSIX, activation publishes and synchronizes an immutable transaction, then
+atomically replaces `refs/active.json` and synchronizes its directory. Windows
+uses synced file contents and atomic replacement but skips unsupported directory
+flushes, so its power-loss guarantee is weaker; learning files there inherit
+ambient workspace/temp ACLs. Loads verify the complete ancestry; rollback
+appends a new transaction rather than deleting history. `fleet.zig`
+marks the verified learned agent as local activation authority so later remote
+elite merges cannot replace that name. Full schemas, operational guidance,
+privacy implications, and the unimplemented collective-learning design are in
+[`docs/local-learning.md`](docs/local-learning.md).
+
## Compaction
Client-side and provider-agnostic. Every response's `usage` is recorded
diff --git a/docs/behavioral-trajectories.md b/docs/behavioral-trajectories.md
new file mode 100644
index 00000000..04c39da2
--- /dev/null
+++ b/docs/behavioral-trajectories.md
@@ -0,0 +1,302 @@
+# Behavioral trajectories (experimental Phase 1)
+
+Codegraff has an experimental behavioral event stream inspired by the
+schema-harness traces discussed in [issue #246](https://github.com/justrach/codegraff/issues/246).
+It establishes an ordered per-run envelope and explicit APIs for caller-asserted
+commitments and mispredictions. Here, a **run** means an initialized agent
+session; utility invocations such as help, version, and `graff title` return
+before behavioral tracing starts. Phase 1 does **not** yet implement the complete
+generic predict → act → verify → repair loop, replayable task state, behavioral
+scoring, or fleet/DGM selection from those scores.
+
+## Three different local streams
+
+| Stream | Lifetime | Purpose |
+| --- | --- | --- |
+| `harness.trace.jsonl` | Truncated at startup | Operational API/tool latency and error counters, with active behavioral-turn attribution, used to debug the harness. |
+| `.graff/trajectories/<run_id>.jsonl` | Up to one exclusively-created file per initialized agent session | Experimental lifecycle and caller-asserted belief events. |
+| `harness.trajectory.jsonl` | Append-only across runs | Existing DGM/MAP-Elites lineage and fitness ledger. Its record shapes are unchanged. |
+
+Behavioral events are deliberately not mixed into the legacy DGM ledger. This
+keeps old consumers working and prevents concurrent processes from interleaving
+unattributed event rows. No built-in production task adapter calls the
+commitment or misprediction APIs yet, so ordinary Phase 1 files contain lifecycle
+events only. Adapter rows in the example below are illustrative.
+
+## Behavioral network upload
+
+The network destination is not a fourth local file and the local JSONL is never
+read back or uploaded wholesale. While producing each logical event,
+`BehaviorTrace` independently offers a privacy projection to a bounded in-memory
+uploader. Local capture and upload have separate controls:
+
+| Setting | Effect |
+| --- | --- |
+| `GRAFF_BEHAVIOR_TRACE=off` | Disables the local behavioral file only. `0`, `false`, and `no` are also accepted. |
+| `GRAFF_BEHAVIOR_UPLOAD=off` | Disables the behavioral POST only. `0`, `false`, and `no` are also accepted. |
+| `GRAFF_BEHAVIOR_UPLOAD=metadata` | Explicitly selects the field-allowlisted metadata projection. This is the default when ordinary telemetry is enabled. Only the exact lowercase literal enables an explicit selection. |
+| `GRAFF_BEHAVIOR_UPLOAD=content` | Explicitly opts into opaque content supplied by a task adapter. Only the exact lowercase literal `content` enables this mode. |
+| `GRAFF_TELEMETRY_KEY=<token>` | Sends the same bounded visible token as `x-harness-key` on ordinary OTLP and behavioral requests. Use it when the collector configures `TELEMETRY_KEY`. |
+
+Unknown upload values and case/whitespace variants fail closed to `off`. The existing telemetry consent gate
+is the parent gate: `--no-telemetry`, `GRAFF_NO_TELEMETRY=1`, or an empty
+telemetry endpoint forces behavioral upload off even if `content` is requested.
+Conversely, disabling local capture does not disable upload, and disabling upload
+does not disable the local file.
+
+At terminal closure the client derives `/v1/behavior` beside the configured
+`/v1/logs` OTLP endpoint and attempts one POST with a three-second deadline. A
+validated `GRAFF_TELEMETRY_KEY` is sent as `x-harness-key`; empty, oversized,
+whitespace, and control-bearing values are not sent. HTTP non-2xx responses are
+treated as failed attempts. Upload remains best-effort and silent, and it does
+not retry. Timeout cancellation synchronously joins the POST task before
+its payload and client state are released. A crash, kill, early
+`std.process.fatal`, network error, deadline, or serialization/admission failure
+can therefore leave no uploaded run or a batch with reported drops. The payload
+is capped at 256 KiB, 4,096 events, and 128 metric turns. Upload happens only
+after session-owned workers are joined. `complete=true` is sent only when the
+upload retained `run_finished`; if terminal admission or allocation fails, the
+batch instead reports `complete=false` and increments `dropped_events`.
+`run_finished(status="closed")` still means a clean session return, not
+successful task completion.
+
+The batch schema is `codegraff.behavior.batch.v1`; projected events retain
+`codegraff.behavior.v1`. In metadata mode the batch contains pseudonymous
+install/run attribution, a controlled client class (`harness`, `sdk-ts`, or
+`sdk-py`), lifecycle and turn relationships, an initial provider/model/effort
+snapshot, terminal and drop status, keyed opaque commitment references, and
+content-free per-turn API/tool aggregates. The local deterministic prompt
+fingerprint is deliberately omitted from all behavioral uploads because
+low-entropy prompt variants can be recovered by enumeration. Tool aggregates use
+controlled classes (`shell`, `read`, `write`, `search`, `web`, `agent`, `verify`,
+`mcp`, and `other`). Unknown private MCP server/tool names collapse to `mcp`
+rather than being serialized exactly.
+
+`GRAFF_BEHAVIOR_UPLOAD` governs only this new behavioral POST; it does not
+rewrite the existing OTLP score/run/fleet contract. Existing OTLP records can
+contain prompt fingerprints, and fleet proposal records can contain prompt text
+as documented in [hyperagents.md](hyperagents.md). Disabling ordinary telemetry
+disables both OTLP and behavioral upload.
+
+Metadata admission is field-based; values of allowed fields are not scanned or
+redacted. In particular, initial provider and model identifiers are transmitted
+exactly as configured and can themselves contain private labels or path/repository
+fragments. The schema has no dedicated fields for user/system prompts, generated
+model text or hidden reasoning, source, diffs, filesystem paths or repository
+names, tool arguments or results, shell commands, arbitrary environment values,
+credentials, headers, identity, prompt fingerprints, or free-text adapter
+content. Content mode changes typed adapter events: it may include
+`commitment_id`, `action`, `expect`, `reason`, `predicted`, `actual`, and `detail`
+exactly as supplied. There
+is no redactor, sanitizer, or secret scanner. No built-in production adapter
+currently supplies those fields.
+
+The collector stores individual runs privately and has no raw behavioral GET
+endpoint; its public stats expose aggregate totals only. Content-opt-in fields
+are isolated from event metadata and expire after 30 days. Metadata rows do not
+currently have an automatic expiry. The separately transmitted signed score
+signal can carry the same `run_id` for trusted correlation, but uploaded
+behavioral events are not themselves scores and do not enter fleet selection.
+
+## File and ordering contract
+
+Every complete line is one flat JSON object with these required envelope fields:
+
+| Field | Type | Meaning |
+| --- | --- | --- |
+| `kind` | string | One of the nine event-kind names below. |
+| `seq` | positive integer | Logical source-event order. A healthy local file is a contiguous prefix starting at `1`; a bounded upload projection can have gaps reported by its drop counters. |
+| `ts` | number | Wall-clock Unix time in fractional seconds. It can repeat or move backwards if the system clock changes. |
+| `run_id` | string | The run's random hexadecimal identifier, also used in the filename. |
+| `schema` | string | `codegraff.behavior.v1`. |
+
+Kind-specific fields are top-level fields rather than a nested `payload`.
+Consumers should ignore unknown top-level fields so compatible additions remain
+possible.
+
+A logical `seq` is reserved once before either sink is attempted. Each local
+record is built completely in memory, written, and flushed as one line. If local
+serialization or output fails, local capture is disabled for the rest of the
+process while upload remains independent; an upload admission failure likewise
+does not disable the local file. This makes a healthy local stream a contiguous
+prefix, while an upload may contain source-sequence gaps accounted for by
+`dropped_events`. A local event is capped at 64 KiB to bound temporary
+serialization memory; exceeding that cap disables the local sink for the rest of
+the run but does not disable metadata upload. Directory creation,
+private-permission setup, and exclusive-open collisions are best-effort; a
+failure silently leaves only local behavioral capture disabled. An I/O failure
+can still leave one malformed final
+line; consumers should process only complete JSON lines and treat a missing
+terminal `run_finished` as incomplete. The files currently have no manifest,
+checksum, or signature, so they cannot prove that a local file was not truncated
+or edited after the run.
+
+## Current event support
+
+The enum reserves the nine schema-harness event names, but Phase 1 intentionally
+implements only the lifecycle and caller-asserted adapter subset.
+
+### Automatically emitted
+
+#### `run_started`
+
+Fields:
+
+- `version` — Codegraff version string.
+- `unix_ms` — integer startup timestamp retained for correlation with existing
+ local records.
+- `provider` and `model` — restored/current root selection when lifecycle starts.
+- `prompt_sha` — a one-way fingerprint of the effective system prompt at that
+ point, not prompt text.
+- `effort` — configured reasoning-effort label at that point.
+
+These are an initial run-start snapshot, not immutable per-turn wire facts.
+Later `/model`, `/strict`, ultracode, provider fallback, or effort negotiation can
+change what a later request uses without rewriting `run_started`. Phase 1 does
+not emit per-turn configuration snapshots. The fields are optional for
+compatible producers but are emitted by the current root session path.
+`run_started` is the first logical event and is emitted at most once. For an
+interactive resume, persisted state is loaded before this event; any optional
+model-backed cold-cache compaction runs afterward, outside a root turn.
+
+#### `turn_started`
+
+Required fields:
+
+- `turn` — dense behavioral root-turn ID, starting at `1`.
+- `parent_turn` — previous root turn, or `0` for the first turn.
+- `trajectory_node` — current legacy DGM node when one was already reserved,
+ otherwise `0`.
+
+This event is emitted once at the shared provider boundary, before model or tool
+work. It covers interactive, JSON, one-shot, and zigzag REPL root turns. Provider
+fallback retries occur inside that boundary and do not create extra behavioral
+turns. Active attribution is cleared when the complete provider operation
+returns; later administrative or resume-preprocessing API/tool work carries
+operational turn `0` and does not create an uploaded turn-metric row. Subagent
+calls are not separate behavioral root turns in Phase 1.
+
+`trajectory_node` is correlation metadata scoped to the current process. Legacy
+node IDs restart in later processes and legacy rows do not all carry `run_id`, so
+historical consumers must not treat this number alone as a globally unique join
+key. One-shot and zigzag modes preserve their old DGM behavior and currently use
+`0` here.
+
+#### `run_finished`
+
+Required field:
+
+- `status` — currently `closed` or `error`.
+
+`closed` means that the initialized agent session returned without propagating
+a Zig error. It is **not** a task-success verdict and does not prove that every
+turn succeeded; interactive turn errors can be handled before a later clean
+close. `error` means that main unwound with an error or that the expected
+one-shot provider-failure path terminated through `std.process.fatal`. A crash,
+kill, trace-write failure, or another non-unwinding exit can leave no
+`run_finished` event.
+
+### Caller-asserted task-adapter APIs
+
+These records are never inferred from model prose or from a generic tool exit
+code. An adapter is responsible for deciding what the action, expectation, and
+verification mean; the backend neither authenticates that caller nor attests
+that verification occurred.
+
+#### `turn_committed`
+
+`BehaviorTrace.recordExpectedAction` records:
+
+- `turn` — the current nonzero behavioral turn.
+- `commitment_id` — nonempty, producer-defined correlation ID; it should be
+ unique within the run.
+- `action` — opaque JSON describing the intended action.
+- `expect` — opaque JSON describing the predicted result or state.
+- `reason` — producer-provided explanation of the commitment.
+
+#### `model_mispredicted`
+
+`BehaviorTrace.recordMisprediction` records the caller's assertion that an
+observation contradicted a prediction:
+
+- `turn` — the current nonzero behavioral turn.
+- `commitment_id` — nonempty correlation ID for the commitment being checked.
+- `predicted` — opaque JSON for the relevant prediction.
+- `actual` — opaque JSON for the caller-reported observation.
+- `detail` — producer-provided description of the contradiction.
+
+The typed call serializes opaque values synchronously rather than borrowing
+caller memory. The local file retains their serialized form; explicit content
+upload can retain a second copy under the 30-day policy above. Codegraff does not
+check semantic equivalence, prove that a verifier is correct, maintain a
+commitment registry, cancel a plan, or initiate a repair turn.
+
+### Reserved, not emitted in Phase 1
+
+- `text_delta`
+- `tool_started`
+- `tool_finished`
+- `action_taken`
+
+These names are reserved so later task adapters can use the same envelope. They
+are not automatically emitted yet because generic provider/tool plumbing cannot
+honestly determine task state, distinguish an action from an observation, or
+verify a prediction. Tool arguments, results, model text, and state snapshots
+also carry substantial credential/source/privacy risk. Do not interpret their
+absence as an empty tool/action history. The Phase 1 collector rejects these
+reserved kinds until a typed producer and versioned validation contract exist.
+
+## Local retention and privacy
+
+Behavioral files are ordinary local plaintext. Automatic Phase 1 events do
+**not** include prompts, generated text, hidden reasoning, source code, tool
+arguments/results, credentials, or environment contents. Opaque adapter values
+can contain sensitive task data, however. Adapter authors and callers are
+responsible for minimizing them; neither the local writer nor explicit content
+upload scans or sanitizes them.
+
+- `.graff/` is ignored by Git.
+- Directory components are opened relative to verified no-follow handles, so a
+ workspace symlink cannot redirect the trace outside the working directory.
+ On POSIX, the trajectories directory is set to mode `0700`; new files request
+ a maximum mode of `0600`, which a restrictive process umask may reduce
+ further. On Windows, access follows the directory's inherited ACLs.
+- The local JSONL bytes are never automatically uploaded. A separately built
+ metadata projection is uploaded by default only inside the existing telemetry
+ consent boundary, as described above.
+- Local capture is enabled by default and independent of the operational
+ `/trace` toggle and behavioral upload setting.
+- Local files have no automatic retention limit. Delete files from
+ `.graff/trajectories/` when they are no longer needed. Git ignore rules do not
+ prevent backups, artifact collectors, support bundles, workspace-capable
+ agent tools, or manual uploads from reading or copying them.
+- Behavioral events are not consumed for fleet/DGM selection in Phase 1.
+ Public collector visibility is aggregate-only, but the collector retains
+ private metadata rows and retains explicit content for up to 30 days.
+
+## Example
+
+```json
+{"kind":"run_started","seq":1,"ts":1770000000.125,"run_id":"0123456789abcdef","schema":"codegraff.behavior.v1","version":"0.0.200","unix_ms":1770000000125,"provider":"anthropic","model":"claude-sonnet","prompt_sha":"0011223344556677","effort":"high"}
+{"kind":"turn_started","seq":2,"ts":1770000001.25,"run_id":"0123456789abcdef","schema":"codegraff.behavior.v1","turn":1,"parent_turn":0,"trajectory_node":1}
+{"kind":"turn_committed","seq":3,"ts":1770000002.5,"run_id":"0123456789abcdef","schema":"codegraff.behavior.v1","turn":1,"commitment_id":"build-1","action":{"kind":"edit"},"expect":{"build":"passes"},"reason":"verify the patch"}
+{"kind":"model_mispredicted","seq":4,"ts":1770000003.75,"run_id":"0123456789abcdef","schema":"codegraff.behavior.v1","turn":1,"commitment_id":"build-1","predicted":{"build":"passes"},"actual":{"build":"fails"},"detail":"compiler verification contradicted the expectation"}
+{"kind":"run_finished","seq":5,"ts":1770000004.0,"run_id":"0123456789abcdef","schema":"codegraff.behavior.v1","status":"closed"}
+```
+
+## Deferred work for the full issue
+
+A complete predict–verify implementation still needs:
+
+1. Task adapters that define state snapshots, legal actions, action/observation
+ boundaries, and outcome semantics.
+2. Stable agent/invocation identities and real dispatch/completion hooks for
+ concurrent tool events.
+3. Explicit expectation binding, verification, surprise interruption, and
+ repair behavior.
+4. Versioned, recomputable behavioral scorers plus recipe/eval identity and
+ trace-integrity metadata.
+5. Admission of only trusted recomputed scores into eval, fleet, MAP-Elites,
+ and DGM selection.
+6. Replay of the published schema-harness ft09 trajectory and reproduction of
+ its reference score.
diff --git a/docs/local-learning.md b/docs/local-learning.md
new file mode 100644
index 00000000..3cd53cb0
--- /dev/null
+++ b/docs/local-learning.md
@@ -0,0 +1,389 @@
+# Local prompt-policy learning
+
+`graff learn` is an experimental, local-first engine for evolving one named
+agent prompt. It implements a complete local cycle:
+
+```text
+active parent → deterministic mutation seeds → paired evaluation
+ → Zig-side verification/aggregation → select → promote or reject
+```
+
+It does **not** infer semantic success from ordinary interactive traces, and it
+does not turn behavioral telemetry into promotion authority. Mutators and
+evaluators are explicit local adapters with pinned inputs and typed JSON
+protocols.
+
+## Safety defaults
+
+- A normal `learn run` writes immutable evidence and recommends a command; it
+ never changes the active policy.
+- Automatic promotion requires both `auto.enabled: true` in the immutable
+ configuration **and** an explicit `learn run --auto`. A holdout suite is also
+ mandatory.
+- Activation uses a content-addressed transaction followed by an atomically
+ replaced active ref. File data and containing directories are synchronized
+ before publication. Every load validates the complete transaction chain.
+- A run is promotable only while its parent genome, generation, and transaction
+ ID exactly match the active ref. Rolling back to identical parent bytes does
+ not make old evidence fresh again.
+- Full 64-character lowercase IDs are required; abbreviated IDs are rejected.
+- Local learned policy activation outranks built-in, personal, project, and
+ subsequently fetched remote-fleet prompts of the same name.
+
+## Commands
+
+```text
+graff learn init --parent PATH --config PATH
+graff learn run [--candidates N] [--repetitions N] [--auto] [--lock-timeout-ms N]
+graff learn status [--lock-timeout-ms N]
+graff learn promote RUN_ID [--lock-timeout-ms N]
+graff learn rollback [--to GENOME_ID] [--lock-timeout-ms N]
+graff learn verify [--lock-timeout-ms N]
+graff learn hash ABSOLUTE_PATH
+graff learn help
+```
+
+All configured paths must be canonical absolute paths and must use the exact
+spelling returned by the platform's `realPath` operation (including Windows
+prefix/case conventions). Use `learn hash` to produce the raw SHA-256 pin for a
+tool, declared input, or suite.
+
+A typical manual workflow is:
+
+```sh
+graff learn init --parent /absolute/parent.md --config /absolute/learn.json
+graff learn run
+graff learn promote <complete-run-id>
+graff learn status
+graff learn rollback
+```
+
+Only one learning operation runs at a time. `--lock-timeout-ms` controls how
+long a command waits for the local engine lock, up to 600,000 ms.
+
+## Configuration
+
+The configuration is copied into `.graff/learn`, content-addressed, and treated
+as immutable. Unknown JSON fields are rejected.
+
+```json
+{
+ "schema": "codegraff.learn.config.v1",
+ "agent_name": "reviewer",
+ "agent_description": "locally learned review policy",
+ "mutation_instruction": "change one behavior while preserving strengths",
+ "mutator": {
+ "program": "/absolute/mutator-adapter",
+ "sha256": "<64 lowercase hex>",
+ "args": ["/absolute/mutation-rules.json"],
+ "inputs": [
+ {"path": "/absolute/mutation-rules.json", "sha256": "<64 lowercase hex>"}
+ ],
+ "pass_env": ["MODEL_API_KEY"]
+ },
+ "evaluator": {
+ "program": "/absolute/evaluator",
+ "sha256": "<64 lowercase hex>",
+ "args": [],
+ "inputs": [],
+ "pass_env": []
+ },
+ "evaluation_suite": {
+ "path": "/absolute/primary-suite.json",
+ "sha256": "<64 lowercase hex>"
+ },
+ "holdout_suite": {
+ "path": "/absolute/holdout-suite.json",
+ "sha256": "<64 lowercase hex>"
+ },
+ "limits": {
+ "genome_bytes": 1048576,
+ "request_bytes": 1048576,
+ "response_bytes": 4194304,
+ "stdout_bytes": 65536,
+ "stderr_bytes": 65536,
+ "mutator_timeout_ms": 300000,
+ "evaluator_timeout_ms": 1800000
+ },
+ "gate": {
+ "alpha_ppm": 50000,
+ "minimum_delta_ppm": 50000,
+ "minimum_pairs": 20,
+ "default_candidates": 1,
+ "default_repetitions": 1
+ },
+ "auto": {"enabled": false},
+ "cohort": {
+ "provider": "anthropic",
+ "model": "claude-example",
+ "task_family": "code-review",
+ "adapter_version": "v1",
+ "verifier_version": "v1"
+ }
+}
+```
+
+`holdout_suite` is optional for manual operation and required for `--auto`.
+Cohort fields are exact labels used to prevent unlike evaluations from being
+compared as though they were interchangeable.
+
+### Pinned program snapshots
+
+The engine does not hash a tool and then reopen that original pathname for
+execution. For each invocation it:
+
+1. Opens the configured program and declared inputs without following the final
+ symlink.
+2. Reads and hashes each through that same handle.
+3. Rejects a digest mismatch, non-regular file, oversized file, non-canonical
+ path, and (on POSIX) group/world-writable source.
+4. Writes the verified bytes into the private per-invocation scratch directory.
+5. Executes only the private program snapshot.
+
+If an argument exactly equals a declared input's original path, the engine
+rewrites that argument to the corresponding private snapshot. Declared inputs
+are also exposed as `GRAFF_LEARN_INPUT_0`, `GRAFF_LEARN_INPUT_1`, and so on,
+with the count in `GRAFF_LEARN_INPUT_COUNT`.
+
+The configured program must be directly executable **after relocation** while
+retaining only its filename extension. Supported forms are a standalone
+relocatable native adapter (a native `.exe` on Windows) or, on POSIX, an
+executable script with a shebang. Do not configure an installed interpreter such
+as `python3` as `program`: copying only that binary can separate it from adjacent
+runtime files and make it unusable. Instead, make the adapter script itself
+executable with a shebang, or provide a standalone launcher.
+
+A pinned executable does not imply that its shebang interpreter, dynamic
+libraries, imports, subprocesses, network responses, adjacent resources, or
+undeclared files are pinned. Those runtime dependencies remain trusted external
+components; adapters that discover resources relative to their installation
+path are not supported by the Phase 1 snapshot model.
+
+## Suite schema and statistical unit
+
+A suite is pinned JSON:
+
+```json
+{
+ "schema": "codegraff.learn.suite.v1",
+ "suite_id": "review-v1",
+ "cases": [
+ {"id": "case-001", "critical": true, "payload": {"fixture": "..."}},
+ {"id": "case-002", "payload": null}
+ ]
+}
+```
+
+Case IDs must be unique. The evaluator receives a verified private copy as
+`suite.json`; the evaluation request never directs it back to the configured
+suite pathname.
+
+`default_repetitions` controls repeated measurements of each case. Repetitions
+are **not** independent statistical samples. For the exact one-sided paired
+sign test, all repetitions of one case are collapsed into one unit by comparing
+aggregate parent and child pass counts for that case. Therefore:
+
+- `minimum_pairs` means the minimum number of distinct suite cases.
+- Repeating one case cannot satisfy the minimum or manufacture significance.
+- Any parent-pass/child-fail result on a critical case is a hard rejection.
+- Pass-rate and mean-score deltas still use all repeated measurements.
+- The significance threshold is Bonferroni-corrected by the number of planned
+ candidates.
+- Correctness gates run before cost is used as a tie-breaker.
+
+## Adapter protocols
+
+Programs are invoked directly, never through a generated shell command:
+
+```text
+<private-program-snapshot> <configured-args...> mutate request.json response.json
+<private-program-snapshot> <configured-args...> evaluate request.json response.json
+```
+
+The child working directory is the private scratch directory. `HOME` and temp
+variables point inside it; the environment is replaced with a small baseline
+plus explicitly listed `pass_env` values. Standard output/error, response size,
+and direct-child execution time are bounded. These limits are not OS resource
+isolation: they do not cap CPU, memory, process count, or reliably terminate
+descendants started by an adapter.
+
+### Mutation
+
+The request has schema `codegraff.learn.mutation.request.v1`:
+
+```json
+{
+ "schema": "codegraff.learn.mutation.request.v1",
+ "trial_id": "<id>",
+ "candidate_index": 0,
+ "seed": "<deterministic id>",
+ "parent": {"id": "<genome id>", "path": "parent.genome"},
+ "child_path": "child.genome",
+ "maximum_bytes": 1048576,
+ "instruction": "..."
+}
+```
+
+The mutator writes `child.genome` and responds with
+`codegraff.learn.mutation.response.v1`:
+
+```json
+{
+ "schema": "codegraff.learn.mutation.response.v1",
+ "trial_id": "<same id>",
+ "candidate_index": 0,
+ "parent_id": "<same parent id>",
+ "child_path": "child.genome",
+ "child_sha256": "<raw SHA-256 of the exact child bytes>",
+ "description": "optional bounded description"
+}
+```
+
+The engine rejects the response unless `child_sha256` matches the exact bytes it
+stores as the candidate genome. Promotion rechecks that binding from immutable
+evidence.
+
+### Paired evaluation
+
+The request uses `codegraff.learn.evaluation.request.v1` and includes the trial,
+candidate, exact cohort ID, suite hash, `suite_path: "suite.json"`, parent and
+child IDs/relative files, repetition count, and ordered pairs:
+
+```json
+{"case_id": "case-001", "seed": "<deterministic id>", "critical": true}
+```
+
+The response uses `codegraff.learn.evaluation.response.v1`, repeats the envelope
+IDs, and returns exactly one ordered result per requested pair:
+
+```json
+{
+ "case_id": "case-001",
+ "seed": "<same seed>",
+ "parent_pass": true,
+ "child_pass": true,
+ "parent_score_ppm": 900000,
+ "child_score_ppm": 950000,
+ "parent_cost_micros": 100,
+ "child_cost_micros": 90,
+ "parent_latency_ms": 10,
+ "child_latency_ms": 9
+}
+```
+
+Costs and latencies are optional and default to zero. The Zig engine validates
+the envelope, ordering, bounds, deterministic seeds, trial derivation, and every
+stored aggregate again before promotion. The trial identifier binds the pinned
+configuration, parent genome, exact parent generation and transaction, and a
+fresh nonce; rolling back to identical parent bytes cannot rebind earlier
+evidence to the new transaction.
+
+## Local store, activation, and rollback
+
+The private store is rooted at `.graff/learn`:
+
+```text
+VERSION
+config.json
+configs/ immutable configurations
+genomes/ immutable prompt bytes
+evidence/ immutable adapter requests/responses
+runs/ immutable verified run records
+transactions/ immutable activation history
+refs/active.json mutable atomic active ref
+locks/engine.lock
+tmp/ per-invocation private scratch
+```
+
+Directories are mode `0700` and files mode `0600` on POSIX. Addressed objects
+use domain-separated SHA-256 IDs, so the same bytes in two object classes do not
+share an ID. Immutable writes use exclusive atomic publication. On POSIX,
+promotion writes and synchronizes the transaction first, then atomically
+replaces `refs/active.json` and synchronizes its directory; synchronization
+errors fail the command.
+
+Windows synchronizes file contents and uses atomic replacement, but the Zig I/O
+API does not portably flush directory handles. Graff therefore skips the
+post-rename directory flush on Windows rather than failing every operation with
+`ACCESS_DENIED`; its power-loss guarantee is weaker. Windows files and scratch
+directories also inherit the workspace/temp-directory ACLs instead of Graff
+installing a restrictive DACL. Use a workspace and temporary directory whose
+ACLs are private to the account. Across every platform, stable-media behavior
+ultimately depends on the OS, filesystem, and device.
+
+`rollback` creates a new transaction; it never rewinds or deletes history. By
+default it selects the immediately previous active genome. `--to` accepts only a
+full genome ID present in validated ancestry. Promotion and `learn verify`
+revalidate the configured source pins; changing or deleting an adapter or suite
+therefore fails closed even when the addressed run/evidence objects still exist.
+
+## Trust and privacy boundaries
+
+Scratch isolation and environment scrubbing are **not an OS sandbox**. Mutator
+and evaluator processes run with the invoking user's authority. They can read or
+modify anything that user can, inspect the holdout and learning store, access
+explicitly passed credentials, or use the network. A configured holdout is an
+independent gate against ordinary overfitting, not a secret from a malicious or
+colluding adapter. Do not run adapters you do not trust; use an external sandbox
+when stronger isolation is required.
+
+Learning artifacts have no upload path and remain local. Once activated, however,
+the learned prompt is used like any other agent prompt:
+
+- it is sent to the selected model provider when that agent runs;
+- prompt fingerprints can appear in ordinary trajectory/telemetry metadata;
+- provider/model identifiers and other ordinary telemetry follow the existing
+ telemetry policy; and
+- local trace/session files retain their documented behavior.
+
+Neither local behavioral JSONL nor best-effort telemetry is accepted as trusted
+promotion evidence.
+
+## Verification and regression test
+
+`graff learn verify` validates active configuration, pins, object hashes, active
+ref, current genome, and complete transaction ancestry. It does not execute the
+adapters or prove their semantic quality.
+
+The checked-in deterministic end-to-end fixture exercises manual promotion,
+rollback, stale-run rejection, trial derivation, mutation-output binding,
+private tool/suite snapshots, and explicitly gated automatic promotion without
+network access:
+
+```sh
+zig build
+python3 tests/learn_e2e.py --graff zig-out/bin/graff
+```
+
+## Collective learning: design, not implemented authority
+
+A privacy-preserving collective layer should exchange verified artifacts and
+attestations, not raw repositories, prompts, tool arguments, or local traces.
+A safe design has these components:
+
+1. **Content-addressed policy bundles.** A bundle identifies parent and child,
+ configuration/suite hashes, capability requirements, and cohort metadata.
+2. **Signed evaluator attestations.** Trusted evaluators sign exact bundle,
+ verifier, suite, result, cost, and harness-version claims. Local engines
+ verify signatures and still rerun required checks.
+3. **Cohort aggregation.** Compare only matching task family, verifier,
+ provider/model capability class, adapter version, and harness version.
+ Preserve MAP-Elites niches rather than electing one global prompt.
+4. **Central hidden holdout.** For high-value shared promotion, an independent
+ service evaluates a submitted content hash without exposing holdout material
+ to mutators. Local configured holdouts alone are not secret.
+5. **Abuse resistance.** Rate limits, per-install/per-signer contribution caps,
+ robust aggregation, replay protection, evaluator reputation, and explicit
+ anti-Sybil policy precede any fleet-wide recommendation.
+6. **Safe rollout.** Signed manifests, local allowlists, canary cohorts,
+ monotonic generation constraints, revocation lists, and one-command rollback
+ are mandatory. Remote data remains advisory unless the user separately opts
+ into a defined activation policy.
+7. **Privacy-preserving visibility.** Public views expose thresholded aggregate
+ cohort statistics, never raw run IDs, content, prompts, repositories, or
+ individual behavioral rows.
+
+D1 can serve as a small control plane for bundle manifests, signer keys,
+revocations, and aggregate pointers. Larger evidence/aggregation workloads
+belong behind a queue and analytical store rather than synchronous D1 writes.
+No such collective promotion authority is implemented by `graff learn` today.
diff --git a/src/agent_request.zig b/src/agent_request.zig
index cf453bbc..ded9f488 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -247,7 +247,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
{
self.last_api_error = std.fmt.allocPrint(self.arena, "rate limited (429): quota/billing cap — {s}", .{main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len]}) catch "rate limited (429): quota exceeded";
if (telemetry.g_telem) |t| t.errorEvent("quota", self.last_api_error orelse "quota exceeded");
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, 0, body.len, 0, 0, 0, true);
+ if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, 0, body.len, 0, 0, 0, true);
return error.ApiError;
}
if (attempt < max_attempts) {
@@ -295,7 +295,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
self.last_api_error = std.fmt.allocPrint(self.arena, "network error: {s} (gave up after {d} attempts)", .{ @errorName(err), max_attempts }) catch null;
self.last_request_write_failed = std.mem.eql(u8, @errorName(err), "WriteFailed");
if (telemetry.g_telem) |t| t.errorEvent("net", @errorName(err));
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, 0, body.len, 0, 0, 0, true);
+ if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, 0, body.len, 0, 0, 0, true);
return error.ApiError;
}
}
@@ -308,14 +308,14 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
if (self.provider.kind == .responses) {
const r = self.parseResponses(resp_body) catch {
try self.say("unparseable codex response: {s}\n", .{resp_body[0..@min(resp_body.len, 600)]});
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
+ if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
return error.ApiError;
};
switch (r) {
.ok => |obj| {
if (!self.compaction_request) self.compact_transport_failures = 0;
self.recordUsageResponses(obj, body.len);
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
+ if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });
return obj;
},
@@ -345,7 +345,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
self.closeCodexWs();
continue :rebuild;
}
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
+ if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
try self.sayApiError("codex api error: {s}", .{msg});
return error.ApiError;
},
@@ -365,13 +365,13 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
const ecode = if (eo) |e| (if (e.get("code")) |cv| (if (cv == .string) cv.string else null) else null) else null;
if (recoverContextOverflow(self, emsg, ecode, &context_retried)) continue; // #193/#203: streamed error event overflow (by code or phrasing) → trim + retry
if (try retryTransientServerError(self, etype, ecode, emsg, &server_retries)) continue; // #opencode-parity: transient server overload → retry
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
+ if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
try self.sayApiError("api error ({s}): {s}", .{ etype, emsg });
return error.ApiError;
};
self.recordUsage(root, body.len);
if (!self.compaction_request) self.compact_transport_failures = 0;
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
+ if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });
return root;
}
@@ -392,7 +392,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
const ecode = if (eo) |e| (if (e.get("code")) |cv| (if (cv == .string) cv.string else null) else null) else null;
if (recoverContextOverflow(self, emsg, ecode, &context_retried)) continue; // #193/#203: {"type":"error"} overflow (by code or phrasing) → trim + retry
if (try retryTransientServerError(self, etype, ecode, emsg, &server_retries)) continue; // #opencode-parity: transient server overload → retry
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
+ if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
try self.sayApiError("api error ({s}): {s}", .{ etype, emsg });
return error.ApiError;
};
@@ -434,14 +434,14 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
// local provider whose message text we don't match on still recovers.
if (recoverContextOverflow(self, msg, errorCode(root), &context_retried)) continue;
if (try retryTransientServerError(self, "", errorCode(root), msg, &server_retries)) continue; // #opencode-parity: transient server overload → retry, not hard-fail
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
+ if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
try self.sayApiError("api error: {s}", .{msg});
return error.ApiError;
}
self.recordUsage(root, body.len);
if (!self.compaction_request) self.compact_transport_failures = 0;
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
+ if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });
return root;
}
diff --git a/src/args.zig b/src/args.zig
index 51dd7915..63a612ba 100644
--- a/src/args.zig
+++ b/src/args.zig
@@ -79,7 +79,9 @@ pub fn parse(init: std.process.Init) !Flags {
defer it.deinit();
_ = it.next(); // argv[0]
while (it.next()) |arg| {
- if (flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "mcp")) {
+ if (flags.positionals.items.len > 0 and
+ (std.mem.eql(u8, flags.positionals.items[0], "mcp") or std.mem.eql(u8, flags.positionals.items[0], "learn")))
+ {
try flags.positionals.append(arena, try arena.dupe(u8, arg));
} else if (std.mem.startsWith(u8, arg, "-")) {
if (std.mem.eql(u8, arg, "--yolo")) {
@@ -174,7 +176,7 @@ pub fn parse(init: std.process.Init) !Flags {
// One-shot print mode: `harness -p "prompt"` or a bare positional prompt
// (`harness "say hi"`). Subcommands (login/key) are not prompts.
flags.is_subcommand = flags.positionals.items.len > 0 and
- (std.mem.eql(u8, flags.positionals.items[0], "login") or std.mem.eql(u8, flags.positionals.items[0], "key") or std.mem.eql(u8, flags.positionals.items[0], "mcp") or
+ (std.mem.eql(u8, flags.positionals.items[0], "login") or std.mem.eql(u8, flags.positionals.items[0], "key") or std.mem.eql(u8, flags.positionals.items[0], "mcp") or std.mem.eql(u8, flags.positionals.items[0], "learn") or
std.mem.eql(u8, flags.positionals.items[0], "serve") or std.mem.eql(u8, flags.positionals.items[0], "update") or std.mem.eql(u8, flags.positionals.items[0], "title") or std.mem.eql(u8, flags.positionals.items[0], "repl") or
std.mem.eql(u8, flags.positionals.items[0], "worktree") or std.mem.eql(u8, flags.positionals.items[0], "sandboxes") or std.mem.eql(u8, flags.positionals.items[0], "cube") or std.mem.eql(u8, flags.positionals.items[0], "models"));
if (!flags.is_subcommand and flags.positionals.items.len > 0) {
diff --git a/src/behavior_upload.zig b/src/behavior_upload.zig
new file mode 100644
index 00000000..9a980482
--- /dev/null
+++ b/src/behavior_upload.zig
@@ -0,0 +1,790 @@
+//! Privacy-projected behavioral uploads. Local behavioral JSONL remains the
+//! source of truth; this module builds a separate, bounded batch containing
+//! only an allowlisted metadata projection by default. Content-bearing adapter
+//! fields require the explicit `content` mode and are never inferred from model
+//! text, tool arguments/results, source, or hidden reasoning.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+pub const batch_schema = "codegraff.behavior.batch.v1";
+pub const event_schema = "codegraff.behavior.v1";
+
+pub const max_events = 4096;
+const max_event_bytes = 16 * 1024;
+// Leave enough room below the 256 KiB wire limit for worst-case u64 turn
+// counters, the batch envelope, and JSON punctuation.
+const max_event_storage = 112 * 1024;
+const max_turns = 128;
+const max_payload_bytes = 256 * 1024;
+
+pub const Mode = enum {
+ off,
+ metadata,
+ content,
+
+ pub fn privacyName(self: Mode) []const u8 {
+ return switch (self) {
+ .off => "off",
+ .metadata => "metadata",
+ .content => "content_opt_in",
+ };
+ }
+};
+
+pub const SendResult = enum {
+ not_attempted,
+ accepted,
+ failed,
+ deadline,
+};
+
+/// Behavioral upload follows the existing telemetry consent boundary. With
+/// telemetry enabled, an unset value selects the content-free metadata mode.
+/// Invalid explicit values fail closed instead of accidentally enabling upload.
+pub fn resolveMode(value: ?[]const u8, telemetry_enabled: bool) Mode {
+ if (!telemetry_enabled) return .off;
+ const raw = value orelse return .metadata;
+ if (std.ascii.eqlIgnoreCase(raw, "off") or
+ std.mem.eql(u8, raw, "0") or
+ std.ascii.eqlIgnoreCase(raw, "false") or
+ std.ascii.eqlIgnoreCase(raw, "no")) return .off;
+ // Upload-enabling values are exact lowercase literals. In particular,
+ // case or whitespace variants must not turn a typo into network activity.
+ if (std.mem.eql(u8, raw, "metadata")) return .metadata;
+ // Content mode performs no automatic redaction. Require the exact lowercase
+ // opt-in literal rather than accepting aliases or case variants.
+ if (std.mem.eql(u8, raw, "content")) return .content;
+ return .off;
+}
+
+/// HARNESS_CLIENT remains an unconstrained ordinary-telemetry attribute, but
+/// behavioral metadata must not serialize arbitrary environment content.
+/// Preserve only the stable SDK attribution labels that Codegraff defines.
+fn controlledClientName(raw: []const u8) []const u8 {
+ const allowed = [_][]const u8{ "harness", "sdk-ts", "sdk-py" };
+ for (allowed) |name| if (std.mem.eql(u8, raw, name)) return name;
+ return "harness";
+}
+
+pub const TurnMetrics = struct {
+ turn: u64,
+ api_calls: u64 = 0,
+ api_errors: u64 = 0,
+ api_subagent_calls: u64 = 0,
+ api_latency_ms: u64 = 0,
+ request_bytes: u64 = 0,
+ response_bytes: u64 = 0,
+ context_tokens: u64 = 0,
+ cache_read_tokens: u64 = 0,
+ tool_calls: u64 = 0,
+ tool_errors: u64 = 0,
+ tool_subagent_calls: u64 = 0,
+ tool_latency_ms: u64 = 0,
+ result_bytes: u64 = 0,
+ tool_shell: u64 = 0,
+ tool_read: u64 = 0,
+ tool_write: u64 = 0,
+ tool_search: u64 = 0,
+ tool_web: u64 = 0,
+ tool_agent: u64 = 0,
+ tool_verify: u64 = 0,
+ tool_mcp: u64 = 0,
+ tool_other: u64 = 0,
+};
+
+const ToolClass = enum {
+ shell,
+ read,
+ write,
+ search,
+ web,
+ agent,
+ verify,
+ mcp,
+ other,
+};
+
+fn toolClass(name: []const u8) ToolClass {
+ if (std.mem.eql(u8, name, "bash") or std.mem.eql(u8, name, "bash_output") or std.mem.eql(u8, name, "bash_kill")) return .shell;
+ if (std.mem.eql(u8, name, "read_file")) return .read;
+ if (std.mem.eql(u8, name, "edit_file") or std.mem.eql(u8, name, "write_file")) return .write;
+ if (std.mem.eql(u8, name, "codedb")) return .search;
+ if (std.mem.eql(u8, name, "webfetch")) return .web;
+ if (std.mem.eql(u8, name, "workflow") or std.mem.eql(u8, name, "subagent") or std.mem.eql(u8, name, "ask_user") or std.mem.eql(u8, name, "todo_write") or std.mem.eql(u8, name, "todo_read")) return .agent;
+ if (std.mem.eql(u8, name, "eval")) return .verify;
+ if (std.mem.startsWith(u8, name, "mcp__codedbpro__")) {
+ if (std.mem.indexOf(u8, name, "edit") != null or
+ std.mem.indexOf(u8, name, "patch") != null or
+ std.mem.indexOf(u8, name, "create") != null or
+ std.mem.indexOf(u8, name, "replace") != null) return .write;
+ if (std.mem.indexOf(u8, name, "lint") != null or std.mem.indexOf(u8, name, "diff") != null) return .verify;
+ return .search;
+ }
+ if (std.mem.startsWith(u8, name, "mcp__")) return .mcp;
+ return .other;
+}
+
+const max_safe_json_integer: u64 = 9_007_199_254_740_991;
+
+fn saturatingAdd(dst: *u64, value: u64) void {
+ // The collector validates counters as exactly representable JSON numbers.
+ dst.* = @min(dst.* +| value, max_safe_json_integer);
+}
+
+fn nonNegative(value: i64) u64 {
+ return @intCast(@max(value, 0));
+}
+
+fn isMetadataField(comptime name: []const u8) bool {
+ return std.mem.eql(u8, name, "version") or
+ std.mem.eql(u8, name, "unix_ms") or
+ std.mem.eql(u8, name, "provider") or
+ std.mem.eql(u8, name, "model") or
+ std.mem.eql(u8, name, "effort") or
+ std.mem.eql(u8, name, "turn") or
+ std.mem.eql(u8, name, "parent_turn") or
+ std.mem.eql(u8, name, "trajectory_node") or
+ std.mem.eql(u8, name, "commitment_ref") or
+ std.mem.eql(u8, name, "status");
+}
+
+fn assertMetadataFields(comptime T: type) void {
+ inline for (std.meta.fields(T)) |field| {
+ if (!isMetadataField(field.name))
+ @compileError("field is not allowed in behavioral metadata: " ++ field.name);
+ }
+}
+
+pub const Upload = struct {
+ io: Io,
+ gpa: Allocator,
+ client: ?*std.http.Client,
+ endpoint: []const u8,
+ auth_key: ?[]const u8 = null,
+ last_send_result: SendResult = .not_attempted,
+ install_id: [32]u8,
+ client_name: []const u8,
+ service_version: []const u8,
+ run_id: []const u8,
+ mode: Mode,
+ events: std.ArrayList([]u8) = .empty,
+ turns: std.ArrayList(TurnMetrics) = .empty,
+ event_bytes: usize = 0,
+ dropped_events: u64 = 0,
+ dropped_metrics: u64 = 0,
+ sent: bool = false,
+
+ pub fn active(self: *const Upload) bool {
+ return self.mode != .off and self.endpoint.len > 0;
+ }
+
+ pub fn deinit(self: *Upload) void {
+ for (self.events.items) |event| self.gpa.free(event);
+ self.events.deinit(self.gpa);
+ self.turns.deinit(self.gpa);
+ }
+
+ /// Queue one event projection. `metadata_fields` must contain only the
+ /// content-free allowlist for this kind. `content_fields` is serialized
+ /// only after an explicit content opt-in.
+ pub fn appendEvent(
+ self: *Upload,
+ kind: []const u8,
+ seq: u64,
+ ts: f64,
+ metadata_fields: anytype,
+ content_fields: anytype,
+ ) bool {
+ comptime assertMetadataFields(@TypeOf(metadata_fields));
+ if (!self.active() or self.sent) return false;
+ if (self.events.items.len >= max_events) {
+ self.dropped_events +|= 1;
+ return false;
+ }
+ const event = switch (self.mode) {
+ .off => return false,
+ .metadata => self.allocEvent(kind, seq, ts, metadata_fields),
+ .content => self.allocEvent(kind, seq, ts, content_fields),
+ } orelse {
+ self.dropped_events +|= 1;
+ return false;
+ };
+ if (event.len > max_event_bytes or self.event_bytes > max_event_storage -| event.len) {
+ self.gpa.free(event);
+ self.dropped_events +|= 1;
+ return false;
+ }
+ self.events.append(self.gpa, event) catch {
+ self.gpa.free(event);
+ self.dropped_events +|= 1;
+ return false;
+ };
+ self.event_bytes += event.len;
+ return true;
+ }
+
+ fn allocEvent(self: *Upload, kind: []const u8, seq: u64, ts: f64, fields: anytype) ?[]u8 {
+ // Serialize into a fixed scratch buffer so an opted-in adapter cannot
+ // trigger an unbounded allocation before the per-event limit is checked.
+ var buf: [max_event_bytes + 1]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ var s: std.json.Stringify = .{ .writer = &w };
+ s.beginObject() catch return null;
+ s.objectField("kind") catch return null;
+ s.write(kind) catch return null;
+ s.objectField("seq") catch return null;
+ s.write(seq) catch return null;
+ s.objectField("ts") catch return null;
+ s.write(ts) catch return null;
+ s.objectField("run_id") catch return null;
+ s.write(self.run_id) catch return null;
+ s.objectField("schema") catch return null;
+ s.write(event_schema) catch return null;
+ inline for (std.meta.fields(@TypeOf(fields))) |field| {
+ comptime {
+ if (std.mem.eql(u8, field.name, "kind") or
+ std.mem.eql(u8, field.name, "seq") or
+ std.mem.eql(u8, field.name, "ts") or
+ std.mem.eql(u8, field.name, "run_id") or
+ std.mem.eql(u8, field.name, "schema"))
+ {
+ @compileError("behavior upload field collides with the event envelope: " ++ field.name);
+ }
+ }
+ s.objectField(field.name) catch return null;
+ s.write(@field(fields, field.name)) catch return null;
+ }
+ s.endObject() catch return null;
+ if (w.buffered().len > max_event_bytes) return null;
+ return self.gpa.dupe(u8, w.buffered()) catch null;
+ }
+
+ fn metricsForTurn(self: *Upload, turn: u64) ?*TurnMetrics {
+ if (!self.active() or self.sent or turn == 0) return null;
+ for (self.turns.items) |*metrics| if (metrics.turn == turn) return metrics;
+ if (self.turns.items.len >= max_turns) {
+ self.dropped_metrics +|= 1;
+ return null;
+ }
+ self.turns.append(self.gpa, .{ .turn = turn }) catch {
+ self.dropped_metrics +|= 1;
+ return null;
+ };
+ return &self.turns.items[self.turns.items.len - 1];
+ }
+
+ pub fn recordApi(
+ self: *Upload,
+ turn: u64,
+ from_subagent: bool,
+ ms: i64,
+ req_bytes: usize,
+ resp_bytes: usize,
+ context_tokens: u64,
+ cache_read_tokens: u64,
+ is_error: bool,
+ ) void {
+ const metrics = self.metricsForTurn(turn) orelse return;
+ saturatingAdd(&metrics.api_calls, 1);
+ saturatingAdd(&metrics.api_errors, @intFromBool(is_error));
+ saturatingAdd(&metrics.api_subagent_calls, @intFromBool(from_subagent));
+ saturatingAdd(&metrics.api_latency_ms, nonNegative(ms));
+ saturatingAdd(&metrics.request_bytes, @intCast(req_bytes));
+ saturatingAdd(&metrics.response_bytes, @intCast(resp_bytes));
+ saturatingAdd(&metrics.context_tokens, context_tokens);
+ saturatingAdd(&metrics.cache_read_tokens, cache_read_tokens);
+ }
+
+ pub fn recordTool(
+ self: *Upload,
+ turn: u64,
+ name: []const u8,
+ from_subagent: bool,
+ ms: i64,
+ result_bytes: usize,
+ is_error: bool,
+ ) void {
+ const metrics = self.metricsForTurn(turn) orelse return;
+ saturatingAdd(&metrics.tool_calls, 1);
+ saturatingAdd(&metrics.tool_errors, @intFromBool(is_error));
+ saturatingAdd(&metrics.tool_subagent_calls, @intFromBool(from_subagent));
+ saturatingAdd(&metrics.tool_latency_ms, nonNegative(ms));
+ saturatingAdd(&metrics.result_bytes, @intCast(result_bytes));
+ switch (toolClass(name)) {
+ .shell => saturatingAdd(&metrics.tool_shell, 1),
+ .read => saturatingAdd(&metrics.tool_read, 1),
+ .write => saturatingAdd(&metrics.tool_write, 1),
+ .search => saturatingAdd(&metrics.tool_search, 1),
+ .web => saturatingAdd(&metrics.tool_web, 1),
+ .agent => saturatingAdd(&metrics.tool_agent, 1),
+ .verify => saturatingAdd(&metrics.tool_verify, 1),
+ .mcp => saturatingAdd(&metrics.tool_mcp, 1),
+ .other => saturatingAdd(&metrics.tool_other, 1),
+ }
+ }
+
+ /// Build the bounded batch body. Kept separate from send() so tests can
+ /// validate the exact privacy projection without touching the network.
+ pub fn buildPayload(self: *Upload, complete: bool, terminal_status: []const u8) ![]u8 {
+ // A fixed heap buffer makes the advertised wire cap an allocation cap
+ // too. The event/turn admission limits leave deterministic headroom.
+ var backing = try self.gpa.alloc(u8, max_payload_bytes + 1);
+ errdefer self.gpa.free(backing);
+ var writer: Io.Writer = .fixed(backing);
+ const w = &writer;
+ try w.writeAll("{\"schema\":");
+ try writeJsonValue(w, batch_schema);
+ try w.writeAll(",\"event_schema\":");
+ try writeJsonValue(w, event_schema);
+ try w.writeAll(",\"privacy\":");
+ try writeJsonValue(w, self.mode.privacyName());
+ try w.writeAll(",\"run_id\":");
+ try writeJsonValue(w, self.run_id);
+ try w.writeAll(",\"install_id\":");
+ try writeJsonValue(w, &self.install_id);
+ try w.writeAll(",\"client_name\":");
+ try writeJsonValue(w, controlledClientName(self.client_name));
+ try w.writeAll(",\"service_version\":");
+ try writeJsonValue(w, self.service_version);
+ try w.writeAll(",\"complete\":");
+ try writeJsonValue(w, complete);
+ try w.writeAll(",\"terminal_status\":");
+ try writeJsonValue(w, terminal_status);
+ try w.writeAll(",\"dropped_events\":");
+ try writeJsonValue(w, self.dropped_events);
+ try w.writeAll(",\"dropped_metrics\":");
+ try writeJsonValue(w, self.dropped_metrics);
+ try w.writeAll(",\"events\":[");
+ for (self.events.items, 0..) |event, i| {
+ if (i > 0) try w.writeByte(',');
+ try w.writeAll(event);
+ }
+ try w.writeAll("],\"turn_metrics\":");
+ try writeJsonValue(w, self.turns.items);
+ try w.writeByte('}');
+ const used = w.buffered().len;
+ if (used > max_payload_bytes) return error.PayloadTooLarge;
+ backing = try self.gpa.realloc(backing, used);
+ return backing;
+ }
+
+ /// One best-effort POST at terminal closure. The run/event primary keys on
+ /// the collector make a repeated batch idempotent if retry support is added.
+ pub fn send(self: *Upload, complete: bool, terminal_status: []const u8) void {
+ self.sendWithDeadline(complete, terminal_status, .fromSeconds(3));
+ }
+
+ fn sendWithDeadline(self: *Upload, complete: bool, terminal_status: []const u8, deadline: Io.Duration) void {
+ if (!self.active() or self.sent or self.events.items.len == 0) return;
+ self.sent = true;
+ self.last_send_result = .failed;
+ const client = self.client orelse return;
+ const payload = self.buildPayload(complete, terminal_status) catch return;
+ defer self.gpa.free(payload);
+ const url = (behaviorUrl(self.gpa, self.endpoint) catch return) orelse return;
+ defer self.gpa.free(url);
+
+ const Done = union(enum) { posted: bool, deadline: void };
+ var done_buf: [2]Done = undefined;
+ var sel: Io.Select(Done) = .init(self.io, &done_buf);
+ // Arm the bound first. If concurrency is unavailable for the POST,
+ // canceling this timer is bounded; the reverse order could leave a
+ // successfully-started stalled POST with no deadline task.
+ sel.concurrent(.deadline, uploadDeadline, .{ self.io, deadline }) catch return;
+ sel.concurrent(.posted, postBatch, .{ client, url, payload, self.auth_key orelse "" }) catch {
+ sel.cancelDiscard();
+ return;
+ };
+ const first = sel.await() catch {
+ sel.cancelDiscard();
+ return;
+ };
+ // Io.Select.cancelDiscard() requests cancellation and synchronously
+ // waits for every remaining task to finish. payload, url, and client
+ // therefore remain live until the HTTP task has acknowledged it.
+ sel.cancelDiscard();
+ self.last_send_result = switch (first) {
+ .posted => |accepted| if (accepted) .accepted else .failed,
+ .deadline => .deadline,
+ };
+ }
+};
+
+fn writeJsonValue(w: *Io.Writer, value: anytype) !void {
+ var s: std.json.Stringify = .{ .writer = w };
+ try s.write(value);
+}
+
+fn behaviorUrl(gpa: Allocator, endpoint: []const u8) !?[]u8 {
+ // Derive from the URL path, not from its query. This preserves custom
+ // collector query parameters without appending a path inside their value.
+ const fragment_at = std.mem.indexOfScalar(u8, endpoint, '#') orelse endpoint.len;
+ const without_fragment = endpoint[0..fragment_at];
+ const query_at = std.mem.indexOfScalar(u8, without_fragment, '?') orelse without_fragment.len;
+ const query = without_fragment[query_at..];
+ var base = std.mem.trimEnd(u8, without_fragment[0..query_at], "/");
+ if (std.mem.endsWith(u8, base, "/v1/logs")) base = base[0 .. base.len - "/v1/logs".len];
+ base = std.mem.trimEnd(u8, base, "/");
+ if (base.len == 0) return null;
+ return try std.fmt.allocPrint(gpa, "{s}/v1/behavior{s}", .{ base, query });
+}
+
+fn postBatch(client: *std.http.Client, url: []const u8, payload: []const u8, auth_key: []const u8) bool {
+ const auth_header = [_]std.http.Header{.{ .name = "x-harness-key", .value = auth_key }};
+ const extra_headers: []const std.http.Header = if (auth_key.len > 0) &auth_header else &.{};
+ const response = client.fetch(.{
+ .location = .{ .url = url },
+ .method = .POST,
+ .payload = payload,
+ .headers = .{ .content_type = .{ .override = "application/json" } },
+ .extra_headers = extra_headers,
+ }) catch return false;
+ const status = @intFromEnum(response.status);
+ return status >= 200 and status < 300;
+}
+
+fn uploadDeadline(io: Io, deadline: Io.Duration) void {
+ io.sleep(deadline, .awake) catch {};
+}
+
+fn stallBehaviorCollector(io: Io, server: *Io.net.Server, accepted: *std.atomic.Value(bool)) void {
+ const stream = server.accept(io) catch return;
+ defer stream.close(io);
+ accepted.store(true, .release);
+ // Hold the connection open without sending an HTTP response. Test cleanup
+ // cancels this sleep after Upload has canceled and joined its fetch task.
+ io.sleep(.fromSeconds(5), .awake) catch {};
+}
+
+fn answerBehaviorCollector(
+ io: Io,
+ server: *Io.net.Server,
+ expected_key: []const u8,
+ accept_request: bool,
+ saw_key: *std.atomic.Value(bool),
+) void {
+ const stream = server.accept(io) catch return;
+ defer stream.close(io);
+ var read_buf: [16 * 1024]u8 = undefined;
+ var reader = Io.net.Stream.Reader.init(stream, io, &read_buf);
+ while (reader.interface.takeDelimiter('\n') catch null) |line| {
+ if (std.mem.eql(u8, line, "\r") or line.len == 0) break;
+ const prefix = "x-harness-key:";
+ if (!std.ascii.startsWithIgnoreCase(line, prefix)) continue;
+ const value = std.mem.trim(u8, line[prefix.len..], " \t\r\n");
+ saw_key.store(std.mem.eql(u8, value, expected_key), .release);
+ }
+ const response = if (accept_request)
+ "HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
+ else
+ "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
+ var write_buf: [256]u8 = undefined;
+ var writer = Io.net.Stream.Writer.init(stream, io, &write_buf);
+ writer.interface.writeAll(response) catch return;
+ writer.interface.flush() catch {};
+}
+
+test "behavior upload mode follows telemetry consent and fails closed" {
+ try std.testing.expectEqual(Mode.off, resolveMode(null, false));
+ try std.testing.expectEqual(Mode.off, resolveMode("content", false));
+ try std.testing.expectEqual(Mode.metadata, resolveMode(null, true));
+ try std.testing.expectEqual(Mode.metadata, resolveMode("metadata", true));
+ try std.testing.expectEqual(Mode.off, resolveMode("METADATA", true));
+ try std.testing.expectEqual(Mode.off, resolveMode("metadata ", true));
+ try std.testing.expectEqual(Mode.off, resolveMode("off", true));
+ try std.testing.expectEqual(Mode.off, resolveMode("0", true));
+ try std.testing.expectEqual(Mode.content, resolveMode("content", true));
+ try std.testing.expectEqual(Mode.off, resolveMode("CONTENT", true));
+ try std.testing.expectEqual(Mode.off, resolveMode("Content", true));
+ try std.testing.expectEqual(Mode.off, resolveMode("content ", true));
+ try std.testing.expectEqual(Mode.off, resolveMode("sanitized", true));
+ try std.testing.expectEqual(Mode.off, resolveMode("full", true));
+ try std.testing.expectEqual(Mode.off, resolveMode("typo", true));
+}
+
+test "behavior client attribution never serializes arbitrary HARNESS_CLIENT content" {
+ const gpa = std.testing.allocator;
+ var upload: Upload = .{
+ .io = std.testing.io,
+ .gpa = gpa,
+ .client = null,
+ .endpoint = "https://collector.example/v1/logs",
+ .install_id = @splat('a'),
+ .client_name = "HARNESS_CLIENT_PRIVATE_SENTINEL",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = .metadata,
+ };
+ defer upload.deinit();
+
+ const metadata_payload = try upload.buildPayload(true, "closed");
+ defer gpa.free(metadata_payload);
+ try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "HARNESS_CLIENT_PRIVATE_SENTINEL") == null);
+
+ var parsed = try std.json.parseFromSlice(std.json.Value, gpa, metadata_payload, .{});
+ defer parsed.deinit();
+ try std.testing.expectEqualStrings("harness", parsed.value.object.get("client_name").?.string);
+
+ upload.mode = .content;
+ const content_payload = try upload.buildPayload(true, "closed");
+ defer gpa.free(content_payload);
+ try std.testing.expect(std.mem.indexOf(u8, content_payload, "HARNESS_CLIENT_PRIVATE_SENTINEL") == null);
+
+ try std.testing.expectEqualStrings("sdk-ts", controlledClientName("sdk-ts"));
+ try std.testing.expectEqualStrings("sdk-py", controlledClientName("sdk-py"));
+}
+
+test "upload deadline synchronously cancels and joins a stalled POST" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var address = try Io.net.IpAddress.parseLiteral("127.0.0.1:0");
+ var server = try Io.net.IpAddress.listen(&address, io, .{});
+ defer server.deinit(io);
+
+ var accepted: std.atomic.Value(bool) = .init(false);
+ var server_group: Io.Group = .init;
+ defer server_group.cancel(io);
+ try server_group.concurrent(io, stallBehaviorCollector, .{ io, &server, &accepted });
+
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var endpoint_buf: [64]u8 = undefined;
+ const endpoint = try std.fmt.bufPrint(&endpoint_buf, "http://127.0.0.1:{d}", .{server.socket.address.getPort()});
+ var upload: Upload = .{
+ .io = io,
+ .gpa = gpa,
+ .client = &client,
+ .endpoint = endpoint,
+ .install_id = @splat('a'),
+ .client_name = "harness",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = .metadata,
+ };
+ defer upload.deinit();
+ try std.testing.expect(upload.appendEvent("run_started", 1, 1.0, .{}, .{}));
+
+ const started = Io.Timestamp.now(io, .awake).nanoseconds;
+ upload.sendWithDeadline(true, "closed", .fromMilliseconds(250));
+ const elapsed = Io.Timestamp.now(io, .awake).nanoseconds - started;
+
+ try std.testing.expect(accepted.load(.acquire));
+ try std.testing.expectEqual(SendResult.deadline, upload.last_send_result);
+ try std.testing.expect(elapsed >= 100 * std.time.ns_per_ms);
+ try std.testing.expect(elapsed < 3 * std.time.ns_per_s);
+}
+
+test "behavior POST sends the collector key and rejects non-success status" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+
+ inline for (.{ true, false }) |accept_request| {
+ var address = try Io.net.IpAddress.parseLiteral("127.0.0.1:0");
+ var server = try Io.net.IpAddress.listen(&address, io, .{});
+ defer server.deinit(io);
+ var saw_key: std.atomic.Value(bool) = .init(false);
+ var server_group: Io.Group = .init;
+ defer server_group.cancel(io);
+ try server_group.concurrent(io, answerBehaviorCollector, .{ io, &server, "collector-secret", accept_request, &saw_key });
+
+ var endpoint_buf: [64]u8 = undefined;
+ const endpoint = try std.fmt.bufPrint(&endpoint_buf, "http://127.0.0.1:{d}/v1/behavior", .{server.socket.address.getPort()});
+ try std.testing.expectEqual(accept_request, postBatch(&client, endpoint, "{}", "collector-secret"));
+ try std.testing.expect(saw_key.load(.acquire));
+ }
+}
+
+test "metadata projection omits content while explicit content mode includes it" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ const common = .{
+ .io = io,
+ .gpa = gpa,
+ .client = @as(?*std.http.Client, null),
+ .endpoint = "https://collector.example/v1/logs",
+ .install_id = @as([32]u8, @splat('a')),
+ .client_name = "test",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ };
+
+ var metadata: Upload = .{
+ .io = common.io,
+ .gpa = common.gpa,
+ .client = common.client,
+ .endpoint = common.endpoint,
+ .install_id = common.install_id,
+ .client_name = common.client_name,
+ .service_version = common.service_version,
+ .run_id = common.run_id,
+ .mode = .metadata,
+ };
+ defer metadata.deinit();
+ try std.testing.expect(metadata.appendEvent(
+ "turn_committed",
+ 1,
+ 1.5,
+ .{ .turn = @as(u64, 1), .commitment_ref = "safe-ref" },
+ .{ .turn = @as(u64, 1), .commitment_id = "private-id", .action = .{ .secret = "TOP_SECRET" }, .expect = .{ .ok = true }, .reason = "private reason" },
+ ));
+ const metadata_payload = try metadata.buildPayload(true, "closed");
+ defer gpa.free(metadata_payload);
+ try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "safe-ref") != null);
+ try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "TOP_SECRET") == null);
+ try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "private reason") == null);
+
+ var content: Upload = .{
+ .io = common.io,
+ .gpa = common.gpa,
+ .client = common.client,
+ .endpoint = common.endpoint,
+ .install_id = common.install_id,
+ .client_name = common.client_name,
+ .service_version = common.service_version,
+ .run_id = common.run_id,
+ .mode = .content,
+ };
+ defer content.deinit();
+ try std.testing.expect(content.appendEvent(
+ "turn_committed",
+ 1,
+ 1.5,
+ .{ .turn = @as(u64, 1), .commitment_ref = "safe-ref" },
+ .{ .turn = @as(u64, 1), .commitment_id = "private-id", .action = .{ .secret = "TOP_SECRET" }, .expect = .{ .ok = true }, .reason = "adapter-sanitized reason" },
+ ));
+ const content_payload = try content.buildPayload(true, "closed");
+ defer gpa.free(content_payload);
+ try std.testing.expect(std.mem.indexOf(u8, content_payload, "TOP_SECRET") != null);
+ try std.testing.expect(std.mem.indexOf(u8, content_payload, "content_opt_in") != null);
+}
+
+test "turn metrics aggregate safe categories without exact MCP names" {
+ const gpa = std.testing.allocator;
+ var upload: Upload = .{
+ .io = std.testing.io,
+ .gpa = gpa,
+ .client = null,
+ .endpoint = "https://collector.example",
+ .install_id = @splat('b'),
+ .client_name = "test",
+ .service_version = "test",
+ .run_id = "fedcba9876543210",
+ .mode = .metadata,
+ };
+ defer upload.deinit();
+ upload.recordApi(1, false, 20, 100, 200, 300, 250, false);
+ upload.recordTool(1, "bash", false, 5, 40, false);
+ upload.recordTool(1, "mcp__private_server__lookup_customer", true, 7, 80, true);
+ try std.testing.expectEqual(@as(usize, 1), upload.turns.items.len);
+ const metrics = upload.turns.items[0];
+ try std.testing.expectEqual(@as(u64, 1), metrics.api_calls);
+ try std.testing.expectEqual(@as(u64, 2), metrics.tool_calls);
+ try std.testing.expectEqual(@as(u64, 1), metrics.tool_shell);
+ try std.testing.expectEqual(@as(u64, 1), metrics.tool_mcp);
+ try std.testing.expectEqual(@as(u64, 1), metrics.tool_errors);
+
+ _ = upload.appendEvent("run_started", 1, 1.0, .{ .version = "test", .unix_ms = @as(i64, 1) }, .{ .version = "test", .unix_ms = @as(i64, 1) });
+ const payload = try upload.buildPayload(true, "closed");
+ defer gpa.free(payload);
+ try std.testing.expect(std.mem.indexOf(u8, payload, "lookup_customer") == null);
+ try std.testing.expect(std.mem.indexOf(u8, payload, "\"tool_mcp\":1") != null);
+}
+
+test "batch admission limits always fit the wire cap" {
+ const gpa = std.testing.allocator;
+ var upload: Upload = .{
+ .io = std.testing.io,
+ .gpa = gpa,
+ .client = null,
+ .endpoint = "https://collector.example",
+ .install_id = @splat('d'),
+ .client_name = "test",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = .metadata,
+ };
+ defer upload.deinit();
+
+ var turn: u64 = 1;
+ while (turn <= max_turns) : (turn += 1) {
+ upload.recordApi(turn, false, std.math.maxInt(i64), std.math.maxInt(usize), std.math.maxInt(usize), std.math.maxInt(u64), std.math.maxInt(u64), true);
+ upload.recordTool(turn, "bash", true, std.math.maxInt(i64), std.math.maxInt(usize), true);
+ inline for (std.meta.fields(TurnMetrics)) |field| {
+ if (!std.mem.eql(u8, field.name, "turn")) @field(upload.turns.items[@intCast(turn - 1)], field.name) = max_safe_json_integer;
+ }
+ }
+ upload.recordApi(max_turns + 1, false, 1, 1, 1, 1, 1, false);
+ try std.testing.expectEqual(@as(u64, 1), upload.dropped_metrics);
+
+ var seq: u64 = 1;
+ while (seq <= max_events) : (seq += 1) {
+ if (!upload.appendEvent(
+ "run_started",
+ seq,
+ 1.0,
+ .{ .version = "test", .unix_ms = @as(i64, 1), .provider = "provider-padding-provider-padding-provider-padding" },
+ .{ .version = "test", .unix_ms = @as(i64, 1) },
+ )) break;
+ }
+ try std.testing.expect(upload.dropped_events > 0);
+ const payload = try upload.buildPayload(true, "closed");
+ defer gpa.free(payload);
+ try std.testing.expect(payload.len <= max_payload_bytes);
+ var parsed = try std.json.parseFromSlice(std.json.Value, gpa, payload, .{});
+ defer parsed.deinit();
+ try std.testing.expect(parsed.value == .object);
+}
+
+test "oversized content event is rejected before queueing" {
+ const gpa = std.testing.allocator;
+ var upload: Upload = .{
+ .io = std.testing.io,
+ .gpa = gpa,
+ .client = null,
+ .endpoint = "https://collector.example",
+ .install_id = @splat('e'),
+ .client_name = "test",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = .content,
+ };
+ defer upload.deinit();
+ var oversized: [max_event_bytes * 2]u8 = @splat('x');
+ try std.testing.expect(!upload.appendEvent(
+ "turn_committed",
+ 1,
+ 1.0,
+ .{ .turn = @as(u64, 1), .commitment_ref = "safe" },
+ .{ .turn = @as(u64, 1), .reason = oversized[0..] },
+ ));
+ try std.testing.expectEqual(@as(usize, 0), upload.events.items.len);
+ try std.testing.expectEqual(@as(u64, 1), upload.dropped_events);
+}
+
+test "behavior endpoint derives beside OTLP logs without a fixed URL buffer" {
+ const gpa = std.testing.allocator;
+ const Case = struct {
+ fn expect(gpa_inner: Allocator, endpoint: []const u8, expected: []const u8) !void {
+ const actual = (try behaviorUrl(gpa_inner, endpoint)).?;
+ defer gpa_inner.free(actual);
+ try std.testing.expectEqualStrings(expected, actual);
+ }
+ };
+ try Case.expect(gpa, "https://example.test/v1/logs", "https://example.test/v1/behavior");
+ try Case.expect(gpa, "https://example.test/base/", "https://example.test/base/v1/behavior");
+ try Case.expect(gpa, "https://example.test/v1/logs?token=x#ignored", "https://example.test/v1/behavior?token=x");
+ try Case.expect(gpa, "https://example.test/base/?token=x", "https://example.test/base/v1/behavior?token=x");
+
+ const long_token: [768]u8 = @splat('x');
+ var endpoint_buf: [1024]u8 = undefined;
+ const endpoint = try std.fmt.bufPrint(&endpoint_buf, "https://example.test/v1/logs?token={s}", .{long_token});
+ const actual = (try behaviorUrl(gpa, endpoint)).?;
+ defer gpa.free(actual);
+ try std.testing.expect(actual.len > 512);
+ try std.testing.expect(std.mem.startsWith(u8, actual, "https://example.test/v1/behavior?token="));
+ try std.testing.expect(std.mem.endsWith(u8, actual, &long_token));
+}
diff --git a/src/cli.zig b/src/cli.zig
index 1eb61247..97ad59fd 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -63,6 +63,7 @@ pub const usage_text =
\\ graff models [refresh] list the live catalog; refresh Codex + models.dev metadata
\\ graff mcp add <name> -- <cmd> add an MCP server to .mcp.json
\\ graff mcp list configured MCP servers
+ \\ graff learn [help] local mutate/evaluate/promote/rollback engine
\\ graff worktree list list the per-tab worktrees created by -w
\\ graff worktree merge <name> squash-land worktree-<name> onto the current branch + clean up
\\ graff worktree remove <name> discard worktree-<name> (drops its scratch work) + delete the branch
@@ -110,7 +111,8 @@ pub const usage_text =
\\.harness/settings.json.
\\telemetry: anonymous OTLP usage stats are sent only when
\\OTEL_EXPORTER_OTLP_ENDPOINT (or GRAFF_OTEL_ENDPOINT) is set; opt out
- \\with --no-telemetry or GRAFF_NO_TELEMETRY=1.
+ \\with --no-telemetry or GRAFF_NO_TELEMETRY=1. GRAFF_TELEMETRY_KEY sends
+ \\an optional x-harness-key token to the configured collector.
\\
;
diff --git a/src/fleet.zig b/src/fleet.zig
index d1dbeac6..fce31609 100644
--- a/src/fleet.zig
+++ b/src/fleet.zig
@@ -15,6 +15,7 @@ const style = &ansi.style;
const util = @import("util.zig");
const strFieldObj = util.strFieldObj;
+const learn_store = @import("learn_store.zig");
const root = @import("main.zig");
const trace = @import("trace.zig");
@@ -36,6 +37,7 @@ pub const AgentType = struct {
prompt: []const u8,
score: ?f64 = null, // written by the evolution driver, shown in /agents
builtin: bool = false,
+ learned: bool = false,
};
/// Preloaded niches: deliberately orthogonal *behavioral* dimensions (what
@@ -91,6 +93,26 @@ pub fn loadAgentTypes(io: Io, arena: Allocator, home: ?[]const u8) []const Agent
if (personal.len > 0) loadAgentDir(io, arena, &list, personal);
}
loadAgentDir(io, arena, &list, agents_dir);
+ // A verified learning ref is the highest-precedence project policy. The
+ // loader fails closed: incomplete/corrupt learning state contributes no
+ // agent and can be diagnosed with `graff learn verify`.
+ if (learn_store.loadActiveAgent(io, arena)) |learned| {
+ const at: AgentType = .{
+ .name = learned.name,
+ .desc = learned.description,
+ .prompt = learned.prompt,
+ .learned = true,
+ };
+ var replaced = false;
+ for (list.items) |*existing| {
+ if (std.mem.eql(u8, existing.name, at.name)) {
+ existing.* = at;
+ replaced = true;
+ break;
+ }
+ }
+ if (!replaced) list.append(arena, at) catch {};
+ }
return list.items;
}
@@ -256,6 +278,18 @@ pub fn agentTypePrompt(name: []const u8) ?[]const u8 {
return null;
}
+fn applyRemoteElite(arena: Allocator, types: []AgentType, name: []const u8, prompt: []const u8) bool {
+ for (types) |*agent_type| {
+ if (!std.mem.eql(u8, agent_type.name, name)) continue;
+ // A verified local learning ref is an activation authority; best-effort
+ // remote fleet data is not. Preserve unrelated remote elite updates.
+ if (agent_type.learned) return false;
+ agent_type.prompt = arena.dupe(u8, prompt) catch return false;
+ return true;
+ }
+ return false;
+}
+
/// Distribute (docs/hyperagents.md §9.E): fetch this tier's live fleet champions
/// from <base>/v1/elites, emit a fleet:elite_pull signal, and override matching
/// niches with the champion prompt so the baked builtins defer to the fleet
@@ -314,10 +348,7 @@ pub fn pullElites(io: Io, arena: Allocator, client: *std.http.Client, telem: ?*T
const nm = if (el.object.get("niche")) |x| (if (x == .string) x.string else "") else "";
const pt = if (el.object.get("prompt_text")) |x| (if (x == .string) x.string else "") else "";
if (nm.len == 0 or pt.len == 0) continue;
- for (out.items) |*t| if (std.mem.eql(u8, t.name, nm)) {
- t.prompt = arena.dupe(u8, pt) catch t.prompt;
- break;
- };
+ _ = applyRemoteElite(arena, out.items, nm, pt);
}
if (telem) |tl| tl.fleetEvent("elite_pull", "", "", "", provider_class, eval_set_hash, n, "");
return out.items;
@@ -388,3 +419,18 @@ test "resolveNiche: agent name is the fleet cell, inline variant is uncelled" {
// A plain task is uncelled too.
try std.testing.expectEqualStrings("", resolveNiche(obj(a, "{\"description\":\"x\",\"prompt\":\"y\"}")));
}
+
+test "remote elites cannot replace a verified learned policy" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var types = [_]AgentType{
+ .{ .name = "learned", .desc = "local", .prompt = "verified-local", .learned = true },
+ .{ .name = "reviewer", .desc = "remote-eligible", .prompt = "old" },
+ };
+
+ try std.testing.expect(!applyRemoteElite(arena, &types, "learned", "untrusted-remote"));
+ try std.testing.expectEqualStrings("verified-local", types[0].prompt);
+ try std.testing.expect(applyRemoteElite(arena, &types, "reviewer", "new-remote"));
+ try std.testing.expectEqualStrings("new-remote", types[1].prompt);
+}
diff --git a/src/jobs.zig b/src/jobs.zig
index 9e0a1045..64d542f8 100644
--- a/src/jobs.zig
+++ b/src/jobs.zig
@@ -22,7 +22,7 @@ const ToolOutput = tools_mod.ToolOutput;
const codegraff_coauthor = "Co-Authored-By: Codegraff <[email protected]>";
const Agent = agent_mod.Agent;
-const CappedRun = struct {
+pub const CappedRun = struct {
term: std.process.Child.Term,
stdout: []u8,
stderr: []u8,
@@ -31,6 +31,14 @@ const CappedRun = struct {
timed_out: bool,
};
+/// Optional process isolation knobs for trusted orchestrators. Supplying an
+/// explicit environment replaces (rather than augments) the parent process
+/// environment; argv is always executed directly, never through a shell.
+pub const CappedRunOptions = struct {
+ cwd: std.process.Child.Cwd = .inherit,
+ environ_map: ?*const std.process.Environ.Map = null,
+};
+
/// Like `std.process.run`, but hitting an output cap *truncates* instead of
/// failing the call: the first `cap` bytes are kept, the rest is discarded
/// as it streams (retained memory never exceeds the caps), and the child
@@ -43,8 +51,14 @@ const CappedRun = struct {
/// that long and reports `timed_out`. Subagents pass a real deadline since
/// they have no Esc (#93).
pub fn runCapped(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64) !CappedRun {
+ return runCappedWithOptions(gpa, io, argv, stdout_cap, stderr_cap, deadline_ms, .{});
+}
+
+pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64, options: CappedRunOptions) !CappedRun {
var child = try std.process.spawn(io, .{
.argv = argv,
+ .cwd = options.cwd,
+ .environ_map = options.environ_map,
.stdin = .ignore,
.stdout = .pipe,
.stderr = .pipe,
diff --git a/src/learn_cli.zig b/src/learn_cli.zig
new file mode 100644
index 00000000..76b7fc89
--- /dev/null
+++ b/src/learn_cli.zig
@@ -0,0 +1,531 @@
+//! `graff learn`: a local-first parent → mutate → paired-evaluate → select
+//! engine with immutable evidence, manual promotion by default, an explicit
+//! two-key automatic gate, and atomic active-reference rollback.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const build_options = @import("build_options");
+
+const store_mod = @import("learn_store.zig");
+const eval = @import("learn_eval.zig");
+const util = @import("util.zig");
+
+pub const usage =
+ \\graff learn — safe local prompt-policy learning
+ \\
+ \\usage:
+ \\ graff learn init --parent PATH --config PATH
+ \\ graff learn run [--candidates N] [--repetitions N] [--auto] [--lock-timeout-ms N]
+ \\ graff learn status [--lock-timeout-ms N]
+ \\ graff learn promote RUN_ID [--lock-timeout-ms N]
+ \\ graff learn rollback [--to GENOME_ID] [--lock-timeout-ms N]
+ \\ graff learn verify [--lock-timeout-ms N]
+ \\ graff learn hash ABSOLUTE_PATH
+ \\
+ \\IDs are complete 64-character lowercase SHA-256 identifiers. Learning
+ \\tools execute directly as your OS user; scratch directories and a scrubbed
+ \\environment are not an OS sandbox. Promotion never trusts trajectory rows.
+ \\
+;
+
+const InitArgs = struct { parent: []const u8, config: []const u8 };
+const RunArgs = struct { candidates: ?usize = null, repetitions: ?usize = null, auto: bool = false, lock_timeout_ms: u64 = 0 };
+const StatusArgs = struct { lock_timeout_ms: u64 = 0 };
+const PromoteArgs = struct { run_id: []const u8, lock_timeout_ms: u64 = 0 };
+const RollbackArgs = struct { to: ?[]const u8 = null, lock_timeout_ms: u64 = 0 };
+const HashArgs = struct { path: []const u8 };
+
+pub const Parsed = union(enum) {
+ help,
+ init: InitArgs,
+ run: RunArgs,
+ status: StatusArgs,
+ promote: PromoteArgs,
+ rollback: RollbackArgs,
+ verify: StatusArgs,
+ hash: HashArgs,
+};
+
+fn parseUnsigned(comptime T: type, value: []const u8) !T {
+ if (value.len == 0 or value[0] == '+' or value[0] == '-') return error.InvalidNumber;
+ return std.fmt.parseInt(T, value, 10) catch return error.InvalidNumber;
+}
+
+fn parseLockOption(args: []const []const u8, index: *usize, seen: *bool, value: *u64) !bool {
+ if (!std.mem.eql(u8, args[index.*], "--lock-timeout-ms")) return false;
+ if (seen.*) return error.DuplicateOption;
+ seen.* = true;
+ index.* += 1;
+ if (index.* >= args.len) return error.MissingOptionValue;
+ value.* = try parseUnsigned(u64, args[index.*]);
+ if (value.* > 600_000) return error.InvalidNumber;
+ return true;
+}
+
+pub fn parse(args: []const []const u8) !Parsed {
+ if (args.len == 0 or std.mem.eql(u8, args[0], "help") or std.mem.eql(u8, args[0], "--help")) return .help;
+ const command_name = args[0];
+ if (std.mem.eql(u8, command_name, "init")) {
+ var parent: ?[]const u8 = null;
+ var config: ?[]const u8 = null;
+ var index: usize = 1;
+ while (index < args.len) : (index += 1) {
+ const arg = args[index];
+ if (std.mem.eql(u8, arg, "--parent")) {
+ if (parent != null) return error.DuplicateOption;
+ index += 1;
+ if (index >= args.len) return error.MissingOptionValue;
+ parent = args[index];
+ } else if (std.mem.eql(u8, arg, "--config")) {
+ if (config != null) return error.DuplicateOption;
+ index += 1;
+ if (index >= args.len) return error.MissingOptionValue;
+ config = args[index];
+ } else return error.UnknownOption;
+ }
+ return .{ .init = .{ .parent = parent orelse return error.MissingOption, .config = config orelse return error.MissingOption } };
+ }
+ if (std.mem.eql(u8, command_name, "run")) {
+ var result: RunArgs = .{};
+ var seen_candidates = false;
+ var seen_repetitions = false;
+ var seen_auto = false;
+ var seen_lock = false;
+ var index: usize = 1;
+ while (index < args.len) : (index += 1) {
+ const arg = args[index];
+ if (std.mem.eql(u8, arg, "--candidates")) {
+ if (seen_candidates) return error.DuplicateOption;
+ seen_candidates = true;
+ index += 1;
+ if (index >= args.len) return error.MissingOptionValue;
+ result.candidates = try parseUnsigned(usize, args[index]);
+ if (result.candidates.? == 0 or result.candidates.? > 16) return error.InvalidNumber;
+ } else if (std.mem.eql(u8, arg, "--repetitions")) {
+ if (seen_repetitions) return error.DuplicateOption;
+ seen_repetitions = true;
+ index += 1;
+ if (index >= args.len) return error.MissingOptionValue;
+ result.repetitions = try parseUnsigned(usize, args[index]);
+ if (result.repetitions.? == 0 or result.repetitions.? > 100) return error.InvalidNumber;
+ } else if (std.mem.eql(u8, arg, "--auto")) {
+ if (seen_auto) return error.DuplicateOption;
+ seen_auto = true;
+ result.auto = true;
+ } else if (!try parseLockOption(args, &index, &seen_lock, &result.lock_timeout_ms)) return error.UnknownOption;
+ }
+ return .{ .run = result };
+ }
+ if (std.mem.eql(u8, command_name, "status") or std.mem.eql(u8, command_name, "verify")) {
+ var result: StatusArgs = .{};
+ var seen_lock = false;
+ var index: usize = 1;
+ while (index < args.len) : (index += 1) if (!try parseLockOption(args, &index, &seen_lock, &result.lock_timeout_ms)) return error.UnknownOption;
+ return if (std.mem.eql(u8, command_name, "status")) .{ .status = result } else .{ .verify = result };
+ }
+ if (std.mem.eql(u8, command_name, "promote")) {
+ if (args.len < 2 or !store_mod.validId(args[1])) return error.InvalidId;
+ var result: PromoteArgs = .{ .run_id = args[1] };
+ var seen_lock = false;
+ var index: usize = 2;
+ while (index < args.len) : (index += 1) if (!try parseLockOption(args, &index, &seen_lock, &result.lock_timeout_ms)) return error.UnknownOption;
+ return .{ .promote = result };
+ }
+ if (std.mem.eql(u8, command_name, "rollback")) {
+ var result: RollbackArgs = .{};
+ var seen_to = false;
+ var seen_lock = false;
+ var index: usize = 1;
+ while (index < args.len) : (index += 1) {
+ if (std.mem.eql(u8, args[index], "--to")) {
+ if (seen_to) return error.DuplicateOption;
+ seen_to = true;
+ index += 1;
+ if (index >= args.len or !store_mod.validId(args[index])) return error.InvalidId;
+ result.to = args[index];
+ } else if (!try parseLockOption(args, &index, &seen_lock, &result.lock_timeout_ms)) return error.UnknownOption;
+ }
+ return .{ .rollback = result };
+ }
+ if (std.mem.eql(u8, command_name, "hash")) {
+ if (args.len != 2 or !std.fs.path.isAbsolute(args[1])) return error.InvalidPath;
+ return .{ .hash = .{ .path = args[1] } };
+ }
+ return error.UnknownCommand;
+}
+
+fn verifyPins(io: Io, arena: Allocator, config: store_mod.Config) !void {
+ try store_mod.verifyProgram(io, config.mutator);
+ try store_mod.verifyProgram(io, config.evaluator);
+ _ = try store_mod.loadSuite(io, arena, config.evaluation_suite);
+ if (config.holdout_suite) |suite| _ = try store_mod.loadSuite(io, arena, suite);
+}
+
+fn trialId(
+ config_id: []const u8,
+ parent_id: []const u8,
+ parent_generation: u64,
+ parent_transaction_id: []const u8,
+ nonce: []const u8,
+) [64]u8 {
+ var hash = std.crypto.hash.sha2.Sha256.init(.{});
+ hash.update("codegraff-learn/trial/v1");
+ hash.update(&.{0});
+ var generation_bytes: [8]u8 = undefined;
+ std.mem.writeInt(u64, generation_bytes[0..], parent_generation, .big);
+ for ([_][]const u8{ config_id, parent_id, &generation_bytes, parent_transaction_id, nonce }) |field| {
+ var len: [8]u8 = undefined;
+ std.mem.writeInt(u64, len[0..], @intCast(field.len), .big);
+ hash.update(&len);
+ hash.update(field);
+ }
+ var digest: [32]u8 = undefined;
+ hash.final(&digest);
+ return std.fmt.bytesToHex(digest, .lower);
+}
+
+fn betterCandidate(a: eval.CandidateRecord, b: eval.CandidateRecord) bool {
+ const ac = a.primary.?;
+ const bc = b.primary.?;
+ if (ac.delta_ppm != bc.delta_ppm) return ac.delta_ppm > bc.delta_ppm;
+ if (ac.p_value_ppb != bc.p_value_ppb) return ac.p_value_ppb < bc.p_value_ppb;
+ if (ac.mean_score_delta_ppm != bc.mean_score_delta_ppm) return ac.mean_score_delta_ppm > bc.mean_score_delta_ppm;
+ if (ac.child_cost_micros != bc.child_cost_micros) return ac.child_cost_micros < bc.child_cost_micros;
+ return std.mem.order(u8, a.genome_id, b.genome_id) == .lt;
+}
+
+fn selectCandidate(candidates: []const eval.CandidateRecord) ?[]const u8 {
+ var selected: ?usize = null;
+ for (candidates, 0..) |candidate, index| {
+ if (!candidate.eligible) continue;
+ if (selected == null or betterCandidate(candidate, candidates[selected.?])) selected = index;
+ }
+ return if (selected) |index| candidates[index].genome_id else null;
+}
+
+fn verifyMutationEvidence(arena: Allocator, store: *store_mod.Store, config: store_mod.Config, run: eval.RunRecord, index: usize, candidate: eval.CandidateRecord) !void {
+ const expected_seed = eval.candidateSeed(run.trial_id, index);
+ if (!std.mem.eql(u8, candidate.mutation.seed, &expected_seed)) return error.MutationMismatch;
+ const request_bytes = try store.readEvidence(arena, candidate.mutation.request_evidence_id, config.limits.request_bytes);
+ const response_bytes = try store.readEvidence(arena, candidate.mutation.response_evidence_id, config.limits.response_bytes);
+ const request = try std.json.parseFromSliceLeaky(eval.MutationRequest, arena, request_bytes, .{});
+ const response = try std.json.parseFromSliceLeaky(eval.MutationResponse, arena, response_bytes, .{});
+ if (!std.mem.eql(u8, request.schema, eval.mutation_request_schema) or
+ !std.mem.eql(u8, request.trial_id, run.trial_id) or request.candidate_index != index or
+ !std.mem.eql(u8, request.seed, &expected_seed) or !std.mem.eql(u8, request.parent.id, run.parent_genome_id) or
+ !std.mem.eql(u8, request.parent.path, "parent.genome") or !std.mem.eql(u8, request.child_path, "child.genome") or
+ request.maximum_bytes != config.limits.genome_bytes or !std.mem.eql(u8, request.instruction, config.mutation_instruction)) return error.MutationMismatch;
+ if (!std.mem.eql(u8, response.schema, eval.mutation_response_schema) or
+ !std.mem.eql(u8, response.trial_id, run.trial_id) or response.candidate_index != index or
+ !std.mem.eql(u8, response.parent_id, run.parent_genome_id) or !std.mem.eql(u8, response.child_path, "child.genome") or
+ !store_mod.validId(response.child_sha256) or response.description.len > 512 or
+ !std.unicode.utf8ValidateSlice(response.description) or std.mem.indexOfScalar(u8, response.description, 0) != null) return error.MutationMismatch;
+ const child = try store.readGenome(arena, candidate.genome_id, config.limits.genome_bytes);
+ const child_sha256 = store_mod.rawSha256(child);
+ if (!std.mem.eql(u8, response.child_sha256, &child_sha256)) return error.MutationOutputMismatch;
+}
+
+fn verifyRun(
+ arena: Allocator,
+ io: Io,
+ store: *store_mod.Store,
+ config: store_mod.LoadedConfig,
+ run_id: []const u8,
+) !struct { run: eval.RunRecord, selected: ?[]const u8 } {
+ const bytes = try store.readRun(arena, run_id);
+ const run = try std.json.parseFromSliceLeaky(eval.RunRecord, arena, bytes, .{});
+ try eval.validateRun(run);
+ if (!std.mem.eql(u8, run.config_id, &config.id) or !std.mem.eql(u8, run.harness_version, build_options.version)) return error.CohortMismatch;
+ const expected_trial_id = trialId(run.config_id, run.parent_genome_id, run.parent_generation, run.parent_transaction_id, run.nonce);
+ if (!std.mem.eql(u8, run.trial_id, &expected_trial_id)) return error.TrialMismatch;
+ const parent_tx_bytes = try store.readTransaction(arena, run.parent_transaction_id);
+ const parent_tx = try std.json.parseFromSliceLeaky(store_mod.Transaction, arena, parent_tx_bytes, .{});
+ try store_mod.validateTransaction(parent_tx);
+ if (parent_tx.generation != run.parent_generation or !std.mem.eql(u8, parent_tx.next_genome_id, run.parent_genome_id)) return error.ParentTransactionMismatch;
+ _ = try store.readGenome(arena, run.parent_genome_id, config.value.limits.genome_bytes);
+ try verifyPins(io, arena, config.value);
+
+ for (run.candidates, 0..) |candidate, index| {
+ _ = try store.readGenome(arena, candidate.genome_id, config.value.limits.genome_bytes);
+ try verifyMutationEvidence(arena, store, config.value, run, index, candidate);
+ var duplicate_reason: ?[]const u8 = null;
+ if (std.mem.eql(u8, candidate.genome_id, run.parent_genome_id)) duplicate_reason = "identical_parent";
+ for (run.candidates[0..index]) |prior| if (std.mem.eql(u8, candidate.genome_id, prior.genome_id)) {
+ duplicate_reason = "duplicate_candidate";
+ break;
+ };
+ if (duplicate_reason) |reason| {
+ if (candidate.primary != null or candidate.holdout != null or candidate.eligible or !std.mem.eql(u8, candidate.reason, reason)) return error.CandidateMismatch;
+ continue;
+ }
+ const primary_record = candidate.primary orelse return error.CandidateMismatch;
+ const primary = try eval.verifyComparison(arena, io, store, config.value, &config.id, build_options.version, run.trial_id, index, run.parent_genome_id, candidate.genome_id, config.value.evaluation_suite, run.repetitions, run.planned_candidates, primary_record);
+ var eligible = primary.eligible;
+ var reason = primary.reason;
+ if (primary.eligible) {
+ if (config.value.holdout_suite) |suite| {
+ const holdout_record = candidate.holdout orelse return error.CandidateMismatch;
+ const holdout = try eval.verifyComparison(arena, io, store, config.value, &config.id, build_options.version, run.trial_id, index, run.parent_genome_id, candidate.genome_id, suite, run.repetitions, run.planned_candidates, holdout_record);
+ eligible = holdout.eligible;
+ reason = if (holdout.eligible) "eligible" else "holdout_rejected";
+ } else if (candidate.holdout != null) return error.CandidateMismatch;
+ } else if (candidate.holdout != null) return error.CandidateMismatch;
+ if (candidate.eligible != eligible or !std.mem.eql(u8, candidate.reason, reason)) return error.CandidateMismatch;
+ }
+ const selected = selectCandidate(run.candidates);
+ if ((selected == null) != (run.selected_genome_id == null)) return error.SelectionMismatch;
+ if (selected) |id| if (!std.mem.eql(u8, id, run.selected_genome_id.?)) return error.SelectionMismatch;
+ return .{ .run = run, .selected = selected };
+}
+
+fn activeMatchesRun(active: store_mod.ActiveRef, run: eval.RunRecord) bool {
+ return active.generation == run.parent_generation and
+ std.mem.eql(u8, active.genome_id, run.parent_genome_id) and
+ std.mem.eql(u8, active.transaction_id, run.parent_transaction_id);
+}
+
+fn initCommand(gpa: Allocator, arena: Allocator, io: Io, args: InitArgs, out: *Io.Writer) !void {
+ const config_bytes = try store_mod.readFileNoFollow(io, Io.Dir.cwd(), args.config, arena, store_mod.max_config_bytes);
+ const config = try std.json.parseFromSliceLeaky(store_mod.Config, arena, config_bytes, .{});
+ try store_mod.validateConfig(config);
+ try verifyPins(io, arena, config);
+ const parent = try store_mod.readFileNoFollow(io, Io.Dir.cwd(), args.parent, arena, config.limits.genome_bytes);
+
+ var store = try store_mod.Store.initAt(io, Io.Dir.cwd());
+ defer store.deinit();
+ var lock = try store.acquireLock(0);
+ defer lock.deinit();
+ const genome_id = try store.bootstrap(gpa, arena, config_bytes, parent, util.unixMs(io));
+ try out.print("initialized learned agent '{s}'\nactive genome {s}\n", .{ config.agent_name, genome_id });
+}
+
+fn runCommand(gpa: Allocator, arena: Allocator, io: Io, environ: *const std.process.Environ.Map, args: RunArgs, out: *Io.Writer) !void {
+ var store = try store_mod.Store.openAt(io, Io.Dir.cwd());
+ defer store.deinit();
+ var lock = try store.acquireLock(args.lock_timeout_ms);
+ defer lock.deinit();
+ const config = try store.loadConfig(arena);
+ const active = try store.loadActive(arena, config);
+ try verifyPins(io, arena, config.value);
+
+ const candidate_count = args.candidates orelse config.value.gate.default_candidates;
+ const repetitions = args.repetitions orelse config.value.gate.default_repetitions;
+ if (candidate_count == 0 or candidate_count > 16 or repetitions == 0 or repetitions > 100) return error.InvalidNumber;
+ if (args.auto and !config.value.auto.enabled) return error.AutoNotEnabled;
+ if (args.auto and config.value.holdout_suite == null) return error.AutoRequiresHoldout;
+
+ try out.writeAll("warning: mutator and evaluator execute as your OS user; scratch isolation is not a sandbox\n");
+ const nonce = store_mod.randomId(io);
+ const trial_id = trialId(&config.id, active.ref.genome_id, active.ref.generation, active.ref.transaction_id, &nonce);
+ const candidates = try arena.alloc(eval.CandidateRecord, candidate_count);
+
+ for (candidates, 0..) |*candidate, index| {
+ var mutation = try eval.mutate(gpa, arena, io, environ, &store, config.value, &trial_id, index, active.ref.genome_id, active.genome);
+ defer gpa.free(mutation.prompt);
+ const genome_id = try arena.dupe(u8, &mutation.genome_id);
+ candidate.* = .{
+ .genome_id = genome_id,
+ .mutation = mutation.record,
+ .primary = null,
+ .holdout = null,
+ .eligible = false,
+ .reason = "unevaluated",
+ };
+ if (std.mem.eql(u8, genome_id, active.ref.genome_id)) {
+ candidate.reason = "identical_parent";
+ continue;
+ }
+ var duplicate = false;
+ for (candidates[0..index]) |prior| if (std.mem.eql(u8, genome_id, prior.genome_id)) {
+ duplicate = true;
+ break;
+ };
+ if (duplicate) {
+ candidate.reason = "duplicate_candidate";
+ continue;
+ }
+
+ candidate.primary = try eval.evaluate(gpa, arena, io, environ, &store, config.value, &config.id, build_options.version, &trial_id, index, active.ref.genome_id, active.genome, genome_id, mutation.prompt, config.value.evaluation_suite, repetitions, candidate_count);
+ if (!candidate.primary.?.eligible) {
+ candidate.reason = candidate.primary.?.reason;
+ continue;
+ }
+ if (config.value.holdout_suite) |suite| {
+ candidate.holdout = try eval.evaluate(gpa, arena, io, environ, &store, config.value, &config.id, build_options.version, &trial_id, index, active.ref.genome_id, active.genome, genome_id, mutation.prompt, suite, repetitions, candidate_count);
+ if (!candidate.holdout.?.eligible) {
+ candidate.reason = "holdout_rejected";
+ continue;
+ }
+ }
+ candidate.eligible = true;
+ candidate.reason = "eligible";
+ }
+
+ try verifyPins(io, arena, config.value);
+ const selected = selectCandidate(candidates);
+ const record: eval.RunRecord = .{
+ .schema = eval.run_schema,
+ .trial_id = &trial_id,
+ .nonce = &nonce,
+ .created_unix_ms = util.unixMs(io),
+ .harness_version = build_options.version,
+ .config_id = &config.id,
+ .parent_genome_id = active.ref.genome_id,
+ .parent_generation = active.ref.generation,
+ .parent_transaction_id = active.ref.transaction_id,
+ .planned_candidates = candidate_count,
+ .repetitions = repetitions,
+ .auto_requested = args.auto,
+ .candidates = candidates,
+ .selected_genome_id = selected,
+ };
+ const record_bytes = try store_mod.jsonBytes(gpa, record);
+ defer gpa.free(record_bytes);
+ if (record_bytes.len > store_mod.max_record_bytes) return error.RunTooLarge;
+ const run_id = try store.writeRun(gpa, record_bytes);
+ try out.print("run {s}\n", .{run_id});
+ if (selected) |genome_id| {
+ try out.print("selected {s}\n", .{genome_id});
+ if (args.auto) {
+ const verified = try verifyRun(arena, io, &store, config, &run_id);
+ if (verified.selected == null or !std.mem.eql(u8, verified.selected.?, genome_id)) return error.SelectionMismatch;
+ const current = try store.loadActive(arena, config);
+ if (!activeMatchesRun(current.ref, record)) return error.ActiveParentChanged;
+ try store.activate(gpa, current.ref, &config.id, genome_id, &run_id, "promote", config.value.limits.genome_bytes, util.unixMs(io));
+ try out.writeAll("automatic promotion committed atomically\n");
+ } else try out.print("manual promotion: graff learn promote {s}\n", .{run_id});
+ } else try out.writeAll("no candidate passed all promotion gates; active genome unchanged\n");
+}
+
+fn statusCommand(arena: Allocator, io: Io, timeout_ms: u64, out: *Io.Writer, verify_all: bool) !void {
+ var store = try store_mod.Store.openAt(io, Io.Dir.cwd());
+ defer store.deinit();
+ var lock = try store.acquireLock(timeout_ms);
+ defer lock.deinit();
+ const config = try store.loadConfig(arena);
+ const active = try store.loadActive(arena, config);
+ if (verify_all) try verifyPins(io, arena, config.value);
+ const Status = struct {
+ schema: []const u8 = "codegraff.learn.status.v1",
+ integrity: []const u8 = "ok",
+ agent_name: []const u8,
+ generation: u64,
+ active_genome_id: []const u8,
+ transaction_id: []const u8,
+ config_id: []const u8,
+ pins_verified: bool,
+ };
+ const value: Status = .{
+ .agent_name = config.value.agent_name,
+ .generation = active.ref.generation,
+ .active_genome_id = active.ref.genome_id,
+ .transaction_id = active.ref.transaction_id,
+ .config_id = &config.id,
+ .pins_verified = verify_all,
+ };
+ var stringify: std.json.Stringify = .{ .writer = out };
+ try stringify.write(value);
+ try out.writeByte('\n');
+}
+
+fn promoteCommand(gpa: Allocator, arena: Allocator, io: Io, args: PromoteArgs, out: *Io.Writer) !void {
+ var store = try store_mod.Store.openAt(io, Io.Dir.cwd());
+ defer store.deinit();
+ var lock = try store.acquireLock(args.lock_timeout_ms);
+ defer lock.deinit();
+ const config = try store.loadConfig(arena);
+ const active = try store.loadActive(arena, config);
+ const verified = try verifyRun(arena, io, &store, config, args.run_id);
+ const selected = verified.selected orelse return error.NoPromotableCandidate;
+ if (!activeMatchesRun(active.ref, verified.run)) return error.ActiveParentChanged;
+ try store.activate(gpa, active.ref, &config.id, selected, args.run_id, "promote", config.value.limits.genome_bytes, util.unixMs(io));
+ try out.print("promoted {s} from run {s}\n", .{ selected, args.run_id });
+}
+
+fn ancestorTarget(arena: Allocator, store: *store_mod.Store, active: store_mod.LoadedActive, requested: ?[]const u8) ![]const u8 {
+ const default_target = active.transaction.previous_genome_id orelse return error.NoRollbackAvailable;
+ const target = requested orelse default_target;
+ if (std.mem.eql(u8, target, active.ref.genome_id)) return error.AlreadyActive;
+ var tx = active.transaction;
+ while (tx.generation > 0) {
+ if (tx.previous_genome_id) |genome_id| if (std.mem.eql(u8, genome_id, target)) return target;
+ const previous_id = tx.previous_transaction_id orelse return error.BrokenTransactionChain;
+ const previous_bytes = try store.readTransaction(arena, previous_id);
+ const previous = try std.json.parseFromSliceLeaky(store_mod.Transaction, arena, previous_bytes, .{});
+ try store_mod.validateTransaction(previous);
+ const expected_generation = std.math.add(u64, previous.generation, 1) catch return error.BrokenTransactionChain;
+ if (expected_generation != tx.generation or !std.mem.eql(u8, previous.next_genome_id, tx.previous_genome_id.?)) return error.BrokenTransactionChain;
+ tx = previous;
+ }
+ return error.NotInAncestry;
+}
+
+fn rollbackCommand(gpa: Allocator, arena: Allocator, io: Io, args: RollbackArgs, out: *Io.Writer) !void {
+ var store = try store_mod.Store.openAt(io, Io.Dir.cwd());
+ defer store.deinit();
+ var lock = try store.acquireLock(args.lock_timeout_ms);
+ defer lock.deinit();
+ const config = try store.loadConfig(arena);
+ const active = try store.loadActive(arena, config);
+ const target = try ancestorTarget(arena, &store, active, args.to);
+ _ = try store.readGenome(arena, target, config.value.limits.genome_bytes);
+ try store.activate(gpa, active.ref, &config.id, target, null, "rollback", config.value.limits.genome_bytes, util.unixMs(io));
+ try out.print("rolled back to {s}\n", .{target});
+}
+
+pub fn command(io: Io, gpa: Allocator, arena: Allocator, init: std.process.Init, argv: []const []const u8) !void {
+ const parsed = try parse(argv);
+ var out_buffer: [4096]u8 = undefined;
+ var stdout = Io.File.stdout().writer(io, &out_buffer);
+ const out = &stdout.interface;
+ defer out.flush() catch {};
+ switch (parsed) {
+ .help => try out.writeAll(usage),
+ .init => |args| try initCommand(gpa, arena, io, args, out),
+ .run => |args| try runCommand(gpa, arena, io, init.environ_map, args, out),
+ .status => |args| try statusCommand(arena, io, args.lock_timeout_ms, out, false),
+ .verify => |args| try statusCommand(arena, io, args.lock_timeout_ms, out, true),
+ .promote => |args| try promoteCommand(gpa, arena, io, args, out),
+ .rollback => |args| try rollbackCommand(gpa, arena, io, args, out),
+ .hash => |args| {
+ const digest = try store_mod.hashFileNoFollow(io, args.path);
+ try out.print("{s}\n", .{digest});
+ },
+ }
+ try out.flush();
+}
+
+test "learn parser preserves strict command-local options" {
+ const parsed = try parse(&.{ "run", "--candidates", "4", "--repetitions", "2", "--auto", "--lock-timeout-ms", "50" });
+ try std.testing.expectEqual(@as(usize, 4), parsed.run.candidates.?);
+ try std.testing.expectEqual(@as(usize, 2), parsed.run.repetitions.?);
+ try std.testing.expect(parsed.run.auto);
+ try std.testing.expectEqual(@as(u64, 50), parsed.run.lock_timeout_ms);
+ try std.testing.expectError(error.DuplicateOption, parse(&.{ "run", "--auto", "--auto" }));
+ try std.testing.expectError(error.UnknownOption, parse(&.{ "run", "--mystery" }));
+ try std.testing.expectError(error.InvalidId, parse(&.{ "promote", "abcd" }));
+}
+
+test "trial IDs bind the exact active generation and transaction" {
+ const original = trialId("config", "parent", 7, "transaction-a", "nonce");
+ const identical = trialId("config", "parent", 7, "transaction-a", "nonce");
+ const later_generation = trialId("config", "parent", 8, "transaction-a", "nonce");
+ const later_transaction = trialId("config", "parent", 7, "transaction-b", "nonce");
+ try std.testing.expectEqualSlices(u8, &original, &identical);
+ try std.testing.expect(!std.mem.eql(u8, &original, &later_generation));
+ try std.testing.expect(!std.mem.eql(u8, &original, &later_transaction));
+}
+
+test "learning selection is deterministic and correctness-first" {
+ const mutation: eval.MutationRecord = .{ .seed = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", .request_evidence_id = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", .response_evidence_id = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" };
+ const base: eval.ComparisonRecord = .{ .suite_sha256 = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", .request_evidence_id = mutation.request_evidence_id, .response_evidence_id = mutation.response_evidence_id, .pairs = 20, .statistical_units = 20, .parent_passes = 10, .child_passes = 15, .wins = 5, .losses = 0, .ties = 15, .critical_regressions = 0, .delta_ppm = 250_000, .mean_score_delta_ppm = 100_000, .p_value_ppb = 10_000_000, .parent_cost_micros = 100, .child_cost_micros = 100, .eligible = true, .reason = "eligible" };
+ var candidates = [_]eval.CandidateRecord{
+ .{ .genome_id = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", .mutation = mutation, .primary = base, .holdout = null, .eligible = true, .reason = "eligible" },
+ .{ .genome_id = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", .mutation = mutation, .primary = base, .holdout = null, .eligible = false, .reason = "holdout_rejected" },
+ };
+ try std.testing.expectEqualStrings(candidates[0].genome_id, selectCandidate(&candidates).?);
+ candidates[1].eligible = true;
+ candidates[1].primary.?.delta_ppm = 300_000;
+ try std.testing.expectEqualStrings(candidates[1].genome_id, selectCandidate(&candidates).?);
+}
diff --git a/src/learn_eval.zig b/src/learn_eval.zig
new file mode 100644
index 00000000..dcadf1e7
--- /dev/null
+++ b/src/learn_eval.zig
@@ -0,0 +1,810 @@
+//! Mutation/evaluation protocols and the trusted paired promotion gate.
+//!
+//! External tools are pinned and invoked with direct argv, bounded output,
+//! bounded response files, a private scratch cwd, and an explicit environment.
+//! They still execute with the invoking user's OS privileges: this is hygiene,
+//! not a security sandbox.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const jobs = @import("jobs.zig");
+const store_mod = @import("learn_store.zig");
+
+pub const mutation_request_schema = "codegraff.learn.mutation.request.v1";
+pub const mutation_response_schema = "codegraff.learn.mutation.response.v1";
+pub const evaluation_request_schema = "codegraff.learn.evaluation.request.v1";
+pub const evaluation_response_schema = "codegraff.learn.evaluation.response.v1";
+pub const run_schema = "codegraff.learn.run.v1";
+
+const file_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_file else .fromMode(0o600);
+const executable_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_file else .fromMode(0o700);
+const dir_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_dir else .fromMode(0o700);
+const js_exact_max: u64 = 9_007_199_254_740_991;
+
+pub const GenomeRef = struct {
+ id: []const u8,
+ path: []const u8,
+};
+
+pub const MutationRequest = struct {
+ schema: []const u8,
+ trial_id: []const u8,
+ candidate_index: usize,
+ seed: []const u8,
+ parent: GenomeRef,
+ child_path: []const u8,
+ maximum_bytes: usize,
+ instruction: []const u8,
+};
+
+pub const MutationResponse = struct {
+ schema: []const u8,
+ trial_id: []const u8,
+ candidate_index: usize,
+ parent_id: []const u8,
+ child_path: []const u8,
+ child_sha256: []const u8,
+ description: []const u8 = "",
+};
+
+pub const PairRequest = struct {
+ case_id: []const u8,
+ seed: []const u8,
+ critical: bool,
+};
+
+pub const EvaluationRequest = struct {
+ schema: []const u8,
+ trial_id: []const u8,
+ candidate_index: usize,
+ cohort_id: []const u8,
+ suite_sha256: []const u8,
+ suite_path: []const u8,
+ parent: GenomeRef,
+ child: GenomeRef,
+ repetitions: usize,
+ pairs: []const PairRequest,
+};
+
+pub const PairResult = struct {
+ case_id: []const u8,
+ seed: []const u8,
+ parent_pass: bool,
+ child_pass: bool,
+ parent_score_ppm: u32,
+ child_score_ppm: u32,
+ parent_cost_micros: u64 = 0,
+ child_cost_micros: u64 = 0,
+ parent_latency_ms: u64 = 0,
+ child_latency_ms: u64 = 0,
+};
+
+pub const EvaluationResponse = struct {
+ schema: []const u8,
+ trial_id: []const u8,
+ candidate_index: usize,
+ cohort_id: []const u8,
+ suite_sha256: []const u8,
+ parent_id: []const u8,
+ child_id: []const u8,
+ pairs: []const PairResult,
+};
+
+pub const MutationRecord = struct {
+ seed: []const u8,
+ request_evidence_id: []const u8,
+ response_evidence_id: []const u8,
+};
+
+pub const ComparisonRecord = struct {
+ suite_sha256: []const u8,
+ request_evidence_id: []const u8,
+ response_evidence_id: []const u8,
+ pairs: usize,
+ statistical_units: usize,
+ parent_passes: usize,
+ child_passes: usize,
+ wins: usize,
+ losses: usize,
+ ties: usize,
+ critical_regressions: usize,
+ delta_ppm: i64,
+ mean_score_delta_ppm: i64,
+ p_value_ppb: u64,
+ parent_cost_micros: u64,
+ child_cost_micros: u64,
+ eligible: bool,
+ reason: []const u8,
+};
+
+pub const CandidateRecord = struct {
+ genome_id: []const u8,
+ mutation: MutationRecord,
+ primary: ?ComparisonRecord,
+ holdout: ?ComparisonRecord,
+ eligible: bool,
+ reason: []const u8,
+};
+
+pub const RunRecord = struct {
+ schema: []const u8,
+ trial_id: []const u8,
+ nonce: []const u8,
+ created_unix_ms: i64,
+ harness_version: []const u8,
+ config_id: []const u8,
+ parent_genome_id: []const u8,
+ parent_generation: u64,
+ parent_transaction_id: []const u8,
+ planned_candidates: usize,
+ repetitions: usize,
+ auto_requested: bool,
+ candidates: []const CandidateRecord,
+ selected_genome_id: ?[]const u8,
+};
+
+pub const MutationOutcome = struct {
+ genome_id: [64]u8,
+ prompt: []u8,
+ record: MutationRecord,
+};
+
+pub fn candidateSeed(trial_id: []const u8, candidate_index: usize) [64]u8 {
+ var buffer: [96]u8 = undefined;
+ const framed = std.fmt.bufPrint(&buffer, "{s}:{d}", .{ trial_id, candidate_index }) catch unreachable;
+ return store_mod.domainId("codegraff-learn/candidate-seed/v1", framed);
+}
+
+pub fn cohortId(config_id: []const u8, suite_sha256: []const u8, harness_version: []const u8) [64]u8 {
+ var hash = std.crypto.hash.sha2.Sha256.init(.{});
+ hash.update("codegraff-learn/cohort/v1");
+ hash.update(&.{0});
+ for ([_][]const u8{ config_id, suite_sha256, harness_version }) |field| {
+ var len: [8]u8 = undefined;
+ std.mem.writeInt(u64, len[0..], @intCast(field.len), .big);
+ hash.update(&len);
+ hash.update(field);
+ }
+ var digest: [32]u8 = undefined;
+ hash.final(&digest);
+ return std.fmt.bytesToHex(digest, .lower);
+}
+
+pub fn pairSeed(trial_id: []const u8, suite_sha256: []const u8, candidate_index: usize, case_id: []const u8, repetition: usize) [64]u8 {
+ var hash = std.crypto.hash.sha2.Sha256.init(.{});
+ hash.update("codegraff-learn/pair-seed/v1");
+ hash.update(&.{0});
+ for ([_][]const u8{ trial_id, suite_sha256, case_id }) |field| {
+ var len: [8]u8 = undefined;
+ std.mem.writeInt(u64, len[0..], @intCast(field.len), .big);
+ hash.update(&len);
+ hash.update(field);
+ }
+ var ints: [16]u8 = undefined;
+ std.mem.writeInt(u64, ints[0..8], @intCast(candidate_index), .big);
+ std.mem.writeInt(u64, ints[8..16], @intCast(repetition), .big);
+ hash.update(&ints);
+ var digest: [32]u8 = undefined;
+ hash.final(&digest);
+ return std.fmt.bytesToHex(digest, .lower);
+}
+
+fn createScratch(io: Io, store: *store_mod.Store) !struct { name: [32]u8, dir: Io.Dir } {
+ var attempts: usize = 0;
+ while (attempts < 16) : (attempts += 1) {
+ var raw: [16]u8 = undefined;
+ io.randomSecure(&raw) catch io.random(&raw);
+ const name = std.fmt.bytesToHex(raw, .lower);
+ store.tmp.createDir(io, &name, dir_permissions) catch |err| switch (err) {
+ error.PathAlreadyExists => continue,
+ else => return err,
+ };
+ const dir = try store.tmp.openDir(io, &name, .{ .iterate = true, .follow_symlinks = false });
+ if (builtin.os.tag != .windows) try dir.setPermissions(io, dir_permissions);
+ return .{ .name = name, .dir = dir };
+ }
+ return error.ScratchNameCollision;
+}
+
+fn writePrivateWithPermissions(io: Io, dir: Io.Dir, name: []const u8, bytes: []const u8, permissions: Io.File.Permissions) !void {
+ const file = try dir.createFile(io, name, .{ .exclusive = true, .permissions = permissions });
+ defer file.close(io);
+ try file.writeStreamingAll(io, bytes);
+ try file.sync(io);
+}
+
+fn writePrivate(io: Io, dir: Io.Dir, name: []const u8, bytes: []const u8) !void {
+ return writePrivateWithPermissions(io, dir, name, bytes, file_permissions);
+}
+
+fn buildEnvironment(gpa: Allocator, parent: *const std.process.Environ.Map, program: store_mod.Program, input_paths: []const []const u8, scratch: Io.Dir, io: Io) !std.process.Environ.Map {
+ var env = std.process.Environ.Map.init(gpa);
+ errdefer env.deinit();
+ try env.put("PATH", if (builtin.os.tag == .windows) "C:\\Windows\\System32" else "/usr/bin:/bin");
+ try env.put("LANG", "C");
+ try env.put("LC_ALL", "C");
+ try env.put("GRAFF_LEARN_PROTOCOL", "1");
+
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const real_len = try scratch.realPath(io, &real_buf);
+ const root = real_buf[0..real_len];
+ const home = try std.fmt.allocPrint(gpa, "{s}{c}home", .{ root, std.fs.path.sep });
+ defer gpa.free(home);
+ const temp = try std.fmt.allocPrint(gpa, "{s}{c}tmp", .{ root, std.fs.path.sep });
+ defer gpa.free(temp);
+ try env.put("HOME", home);
+ try env.put("USERPROFILE", home);
+ try env.put("TMPDIR", temp);
+ try env.put("TMP", temp);
+ try env.put("TEMP", temp);
+
+ var count_buf: [32]u8 = undefined;
+ try env.put("GRAFF_LEARN_INPUT_COUNT", try std.fmt.bufPrint(&count_buf, "{d}", .{input_paths.len}));
+ for (input_paths, 0..) |path, index| {
+ var key_buf: [64]u8 = undefined;
+ const key = try std.fmt.bufPrint(&key_buf, "GRAFF_LEARN_INPUT_{d}", .{index});
+ try env.put(key, path);
+ }
+
+ if (builtin.os.tag == .windows) {
+ if (parent.get("SystemRoot")) |value| try env.put("SystemRoot", value);
+ if (parent.get("ComSpec")) |value| try env.put("ComSpec", value);
+ }
+ for (program.pass_env) |name| if (parent.get(name)) |value| try env.put(name, value);
+ return env;
+}
+
+fn snapshotExtension(path: []const u8) []const u8 {
+ const extension = std.fs.path.extension(path);
+ if (extension.len > 16) return "";
+ for (extension) |c| if (!(std.ascii.isAlphanumeric(c) or c == '.' or c == '_' or c == '-')) return "";
+ return extension;
+}
+
+fn invoke(
+ gpa: Allocator,
+ io: Io,
+ parent_env: *const std.process.Environ.Map,
+ scratch: Io.Dir,
+ program: store_mod.Program,
+ operation: []const u8,
+ stdout_cap: usize,
+ stderr_cap: usize,
+ timeout_ms: u64,
+) !void {
+ var root_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const root_len = try scratch.realPath(io, &root_buf);
+ const root = root_buf[0..root_len];
+
+ var program_name_buf: [64]u8 = undefined;
+ const program_name = try std.fmt.bufPrint(&program_name_buf, "program{s}", .{snapshotExtension(program.program)});
+ const program_bytes = try store_mod.readPinnedFileAlloc(io, gpa, .{ .path = program.program, .sha256 = program.sha256 }, store_mod.max_program_bytes);
+ defer gpa.free(program_bytes);
+ try writePrivateWithPermissions(io, scratch, program_name, program_bytes, executable_permissions);
+ const program_path = try std.fmt.allocPrint(gpa, "{s}{c}{s}", .{ root, std.fs.path.sep, program_name });
+ defer gpa.free(program_path);
+
+ const input_paths = try gpa.alloc([]const u8, program.inputs.len);
+ var initialized_inputs: usize = 0;
+ defer {
+ for (input_paths[0..initialized_inputs]) |path| gpa.free(path);
+ gpa.free(input_paths);
+ }
+ for (program.inputs, 0..) |input, index| {
+ var name_buf: [96]u8 = undefined;
+ const name = try std.fmt.bufPrint(&name_buf, "input-{d}{s}", .{ index, snapshotExtension(input.path) });
+ const bytes = try store_mod.readPinnedFileAlloc(io, gpa, input, store_mod.max_program_bytes);
+ defer gpa.free(bytes);
+ try writePrivate(io, scratch, name, bytes);
+ input_paths[index] = try std.fmt.allocPrint(gpa, "{s}{c}{s}", .{ root, std.fs.path.sep, name });
+ initialized_inputs += 1;
+ }
+
+ var argv: std.ArrayList([]const u8) = .empty;
+ defer argv.deinit(gpa);
+ try argv.append(gpa, program_path);
+ for (program.args) |arg| {
+ var effective = arg;
+ for (program.inputs, input_paths) |input, snapshot_path| {
+ if (std.mem.eql(u8, arg, input.path)) {
+ effective = snapshot_path;
+ break;
+ }
+ }
+ try argv.append(gpa, effective);
+ }
+ try argv.appendSlice(gpa, &.{ operation, "request.json", "response.json" });
+
+ var env = try buildEnvironment(gpa, parent_env, program, input_paths, scratch, io);
+ defer env.deinit();
+ const run = try jobs.runCappedWithOptions(gpa, io, argv.items, stdout_cap, stderr_cap, timeout_ms, .{
+ .cwd = .{ .dir = scratch },
+ .environ_map = &env,
+ });
+ defer {
+ gpa.free(run.stdout);
+ gpa.free(run.stderr);
+ }
+ if (run.timed_out) return error.ProcessTimedOut;
+ if (run.term != .exited or run.term.exited != 0) return error.ProcessFailed;
+}
+
+fn validDescription(value: []const u8) bool {
+ return value.len <= 512 and std.unicode.utf8ValidateSlice(value) and std.mem.indexOfScalar(u8, value, 0) == null;
+}
+
+pub fn mutate(
+ gpa: Allocator,
+ arena: Allocator,
+ io: Io,
+ parent_env: *const std.process.Environ.Map,
+ store: *store_mod.Store,
+ config: store_mod.Config,
+ trial_id: []const u8,
+ candidate_index: usize,
+ parent_id: []const u8,
+ parent_prompt: []const u8,
+) !MutationOutcome {
+ if (!store_mod.validId(trial_id) or !store_mod.validId(parent_id)) return error.InvalidId;
+ var scratch_created = try createScratch(io, store);
+ defer store.tmp.deleteTree(io, &scratch_created.name) catch {};
+ defer scratch_created.dir.close(io);
+ try scratch_created.dir.createDir(io, "home", dir_permissions);
+ try scratch_created.dir.createDir(io, "tmp", dir_permissions);
+ try writePrivate(io, scratch_created.dir, "parent.genome", parent_prompt);
+
+ const seed = candidateSeed(trial_id, candidate_index);
+ const request: MutationRequest = .{
+ .schema = mutation_request_schema,
+ .trial_id = trial_id,
+ .candidate_index = candidate_index,
+ .seed = &seed,
+ .parent = .{ .id = parent_id, .path = "parent.genome" },
+ .child_path = "child.genome",
+ .maximum_bytes = config.limits.genome_bytes,
+ .instruction = config.mutation_instruction,
+ };
+ const request_bytes = try store_mod.jsonBytes(gpa, request);
+ defer gpa.free(request_bytes);
+ if (request_bytes.len > config.limits.request_bytes) return error.RequestTooLarge;
+ const request_id = try store.writeEvidence(gpa, request_bytes);
+ try writePrivate(io, scratch_created.dir, "request.json", request_bytes);
+
+ try invoke(gpa, io, parent_env, scratch_created.dir, config.mutator, "mutate", config.limits.stdout_bytes, config.limits.stderr_bytes, config.limits.mutator_timeout_ms);
+ const response_bytes = try store_mod.readFileNoFollow(io, scratch_created.dir, "response.json", gpa, config.limits.response_bytes);
+ defer gpa.free(response_bytes);
+ const response = try std.json.parseFromSliceLeaky(MutationResponse, arena, response_bytes, .{});
+ if (!std.mem.eql(u8, response.schema, mutation_response_schema) or
+ !std.mem.eql(u8, response.trial_id, trial_id) or
+ response.candidate_index != candidate_index or
+ !std.mem.eql(u8, response.parent_id, parent_id) or
+ !std.mem.eql(u8, response.child_path, "child.genome") or
+ !store_mod.validId(response.child_sha256) or
+ !validDescription(response.description)) return error.InvalidMutationResponse;
+
+ const prompt = try store_mod.readFileNoFollow(io, scratch_created.dir, "child.genome", gpa, config.limits.genome_bytes);
+ errdefer gpa.free(prompt);
+ if (std.mem.trim(u8, prompt, " \t\r\n").len == 0 or !std.unicode.utf8ValidateSlice(prompt)) return error.InvalidGenome;
+ const child_sha256 = store_mod.rawSha256(prompt);
+ if (!std.mem.eql(u8, response.child_sha256, &child_sha256)) return error.MutationOutputMismatch;
+ const response_id = try store.writeEvidence(gpa, response_bytes);
+ const genome_id = try store.writeGenome(gpa, prompt);
+ return .{
+ .genome_id = genome_id,
+ .prompt = prompt,
+ .record = .{
+ .seed = try arena.dupe(u8, &seed),
+ .request_evidence_id = try arena.dupe(u8, &request_id),
+ .response_evidence_id = try arena.dupe(u8, &response_id),
+ },
+ };
+}
+
+fn buildPairs(gpa: Allocator, trial_id: []const u8, suite: store_mod.Suite, manifest: store_mod.SuiteManifest, candidate_index: usize, repetitions: usize) ![]PairRequest {
+ const count = std.math.mul(usize, manifest.cases.len, repetitions) catch return error.TooManyPairs;
+ if (count == 0 or count > store_mod.max_pairs) return error.TooManyPairs;
+ const pairs = try gpa.alloc(PairRequest, count);
+ var initialized: usize = 0;
+ errdefer {
+ for (pairs[0..initialized]) |pair| gpa.free(pair.seed);
+ gpa.free(pairs);
+ }
+ for (0..repetitions) |repetition| {
+ for (manifest.cases) |case| {
+ const seed = pairSeed(trial_id, suite.sha256, candidate_index, case.id, repetition);
+ const seed_copy = try gpa.dupe(u8, &seed);
+ pairs[initialized] = .{
+ .case_id = case.id,
+ .seed = seed_copy,
+ .critical = case.critical,
+ };
+ initialized += 1;
+ }
+ }
+ return pairs;
+}
+
+fn freePairs(gpa: Allocator, pairs: []PairRequest) void {
+ for (pairs) |pair| gpa.free(pair.seed);
+ gpa.free(pairs);
+}
+
+/// Exact one-sided paired-binomial tail, evaluated stably from the first tail
+/// term. A value at or below `alpha / planned_candidates` is significant.
+pub fn pairedTail(wins: usize, losses: usize) f64 {
+ const n = wins + losses;
+ if (n == 0 or wins * 2 <= n) return 1.0;
+ const nf: f64 = @floatFromInt(n);
+ const wf: f64 = @floatFromInt(wins);
+ const lf: f64 = @floatFromInt(n - wins);
+ const log_term = std.math.lgamma(f64, nf + 1.0) - std.math.lgamma(f64, wf + 1.0) - std.math.lgamma(f64, lf + 1.0) - nf * @log(2.0);
+ var term = @exp(log_term);
+ var total = term;
+ var k = wins;
+ while (k < n) : (k += 1) {
+ term *= @as(f64, @floatFromInt(n - k)) / @as(f64, @floatFromInt(k + 1));
+ total += term;
+ }
+ return @min(1.0, total);
+}
+
+fn toPpb(p: f64) u64 {
+ if (p >= 1.0) return 1_000_000_000;
+ if (p <= 0.0) return 0;
+ return @intFromFloat(@ceil(p * 1_000_000_000.0));
+}
+
+fn checkedMetricAdd(a: u64, b: u64) !u64 {
+ const sum = std.math.add(u64, a, b) catch return error.InvalidMetric;
+ if (sum > js_exact_max) return error.InvalidMetric;
+ return sum;
+}
+
+fn computeComparison(config: store_mod.Config, suite_sha256: []const u8, request_id: []const u8, response_id: []const u8, requested: []const PairRequest, response: EvaluationResponse, planned_candidates: usize) !ComparisonRecord {
+ if (response.pairs.len != requested.len) return error.MissingPair;
+ var parent_passes: usize = 0;
+ var child_passes: usize = 0;
+ var statistical_units: usize = 0;
+ var wins: usize = 0;
+ var losses: usize = 0;
+ var critical_regressions: usize = 0;
+ var score_delta: i128 = 0;
+ var parent_cost: u64 = 0;
+ var child_cost: u64 = 0;
+ for (response.pairs, requested) |result, pair| {
+ if (!std.mem.eql(u8, result.case_id, pair.case_id) or !std.mem.eql(u8, result.seed, pair.seed)) return error.PairMismatch;
+ if (result.parent_score_ppm > 1_000_000 or result.child_score_ppm > 1_000_000) return error.InvalidScore;
+ if (result.parent_cost_micros > js_exact_max or result.child_cost_micros > js_exact_max or result.parent_latency_ms > js_exact_max or result.child_latency_ms > js_exact_max) return error.InvalidMetric;
+ if (result.parent_pass) parent_passes += 1;
+ if (result.child_pass) child_passes += 1;
+ if (result.parent_pass and !result.child_pass and pair.critical) critical_regressions += 1;
+ score_delta += @as(i128, result.child_score_ppm) - @as(i128, result.parent_score_ppm);
+ parent_cost = try checkedMetricAdd(parent_cost, result.parent_cost_micros);
+ child_cost = try checkedMetricAdd(child_cost, result.child_cost_micros);
+ }
+
+ // Repetitions are repeated measurements of one case, not independent
+ // statistical samples. Collapse each unique case to one sign-test unit by
+ // comparing its aggregate parent/child pass counts across repetitions.
+ for (requested, 0..) |pair, index| {
+ var seen = false;
+ for (requested[0..index]) |prior| {
+ if (std.mem.eql(u8, prior.case_id, pair.case_id)) {
+ seen = true;
+ break;
+ }
+ }
+ if (seen) continue;
+ statistical_units += 1;
+ var parent_case_passes: usize = 0;
+ var child_case_passes: usize = 0;
+ for (response.pairs, requested) |result, grouped_pair| {
+ if (!std.mem.eql(u8, grouped_pair.case_id, pair.case_id)) continue;
+ if (result.parent_pass) parent_case_passes += 1;
+ if (result.child_pass) child_case_passes += 1;
+ }
+ if (child_case_passes > parent_case_passes) wins += 1;
+ if (parent_case_passes > child_case_passes) losses += 1;
+ }
+
+ const pair_count = requested.len;
+ const pass_delta: i128 = @as(i128, @intCast(child_passes)) - @as(i128, @intCast(parent_passes));
+ const delta_ppm: i64 = @intCast(@divTrunc(pass_delta * 1_000_000, @as(i128, @intCast(pair_count))));
+ const mean_score_delta: i64 = @intCast(@divTrunc(score_delta, @as(i128, @intCast(pair_count))));
+ const p = pairedTail(wins, losses);
+ const alpha: f64 = @as(f64, @floatFromInt(config.gate.alpha_ppm)) / 1_000_000.0;
+ const significant = p * @as(f64, @floatFromInt(planned_candidates)) <= alpha;
+
+ var eligible = true;
+ var reason: []const u8 = "eligible";
+ if (critical_regressions > 0) {
+ eligible = false;
+ reason = "critical_regression";
+ } else if (statistical_units < config.gate.minimum_pairs) {
+ eligible = false;
+ reason = "minimum_pairs";
+ } else if (delta_ppm < config.gate.minimum_delta_ppm) {
+ eligible = false;
+ reason = "minimum_delta";
+ } else if (!significant) {
+ eligible = false;
+ reason = "not_significant";
+ }
+ return .{
+ .suite_sha256 = suite_sha256,
+ .request_evidence_id = request_id,
+ .response_evidence_id = response_id,
+ .pairs = pair_count,
+ .statistical_units = statistical_units,
+ .parent_passes = parent_passes,
+ .child_passes = child_passes,
+ .wins = wins,
+ .losses = losses,
+ .ties = statistical_units - wins - losses,
+ .critical_regressions = critical_regressions,
+ .delta_ppm = delta_ppm,
+ .mean_score_delta_ppm = mean_score_delta,
+ .p_value_ppb = toPpb(p),
+ .parent_cost_micros = parent_cost,
+ .child_cost_micros = child_cost,
+ .eligible = eligible,
+ .reason = reason,
+ };
+}
+
+fn validateEvaluationEnvelope(request: EvaluationRequest, response: EvaluationResponse, trial_id: []const u8, candidate_index: usize, cohort_id: []const u8, suite: store_mod.Suite, parent_id: []const u8, child_id: []const u8, repetitions: usize) !void {
+ if (!std.mem.eql(u8, request.schema, evaluation_request_schema) or
+ !std.mem.eql(u8, request.trial_id, trial_id) or
+ request.candidate_index != candidate_index or
+ !std.mem.eql(u8, request.cohort_id, cohort_id) or
+ !std.mem.eql(u8, request.suite_sha256, suite.sha256) or
+ !std.mem.eql(u8, request.suite_path, "suite.json") or
+ !std.mem.eql(u8, request.parent.id, parent_id) or
+ !std.mem.eql(u8, request.parent.path, "parent.genome") or
+ !std.mem.eql(u8, request.child.id, child_id) or
+ !std.mem.eql(u8, request.child.path, "child.genome") or
+ request.repetitions != repetitions) return error.InvalidEvaluationRequest;
+ if (!std.mem.eql(u8, response.schema, evaluation_response_schema) or
+ !std.mem.eql(u8, response.trial_id, trial_id) or
+ response.candidate_index != candidate_index or
+ !std.mem.eql(u8, response.cohort_id, cohort_id) or
+ !std.mem.eql(u8, response.suite_sha256, suite.sha256) or
+ !std.mem.eql(u8, response.parent_id, parent_id) or
+ !std.mem.eql(u8, response.child_id, child_id)) return error.InvalidEvaluationResponse;
+}
+
+pub fn evaluate(
+ gpa: Allocator,
+ arena: Allocator,
+ io: Io,
+ parent_env: *const std.process.Environ.Map,
+ store: *store_mod.Store,
+ config: store_mod.Config,
+ config_id: []const u8,
+ harness_version: []const u8,
+ trial_id: []const u8,
+ candidate_index: usize,
+ parent_id: []const u8,
+ parent_prompt: []const u8,
+ child_id: []const u8,
+ child_prompt: []const u8,
+ suite: store_mod.Suite,
+ repetitions: usize,
+ planned_candidates: usize,
+) !ComparisonRecord {
+ const loaded_suite = try store_mod.loadSuite(io, arena, suite);
+ const pairs = try buildPairs(gpa, trial_id, suite, loaded_suite.manifest, candidate_index, repetitions);
+ defer freePairs(gpa, pairs);
+ const cohort = cohortId(config_id, suite.sha256, harness_version);
+
+ var scratch_created = try createScratch(io, store);
+ defer store.tmp.deleteTree(io, &scratch_created.name) catch {};
+ defer scratch_created.dir.close(io);
+ try scratch_created.dir.createDir(io, "home", dir_permissions);
+ try scratch_created.dir.createDir(io, "tmp", dir_permissions);
+ try writePrivate(io, scratch_created.dir, "parent.genome", parent_prompt);
+ try writePrivate(io, scratch_created.dir, "child.genome", child_prompt);
+ try writePrivate(io, scratch_created.dir, "suite.json", loaded_suite.bytes);
+
+ const request: EvaluationRequest = .{
+ .schema = evaluation_request_schema,
+ .trial_id = trial_id,
+ .candidate_index = candidate_index,
+ .cohort_id = &cohort,
+ .suite_sha256 = suite.sha256,
+ .suite_path = "suite.json",
+ .parent = .{ .id = parent_id, .path = "parent.genome" },
+ .child = .{ .id = child_id, .path = "child.genome" },
+ .repetitions = repetitions,
+ .pairs = pairs,
+ };
+ const request_bytes = try store_mod.jsonBytes(gpa, request);
+ defer gpa.free(request_bytes);
+ if (request_bytes.len > config.limits.request_bytes) return error.RequestTooLarge;
+ const request_id = try store.writeEvidence(gpa, request_bytes);
+ try writePrivate(io, scratch_created.dir, "request.json", request_bytes);
+
+ try invoke(gpa, io, parent_env, scratch_created.dir, config.evaluator, "evaluate", config.limits.stdout_bytes, config.limits.stderr_bytes, config.limits.evaluator_timeout_ms);
+ const response_bytes = try store_mod.readFileNoFollow(io, scratch_created.dir, "response.json", gpa, config.limits.response_bytes);
+ defer gpa.free(response_bytes);
+ const response = try std.json.parseFromSliceLeaky(EvaluationResponse, arena, response_bytes, .{});
+ try validateEvaluationEnvelope(request, response, trial_id, candidate_index, &cohort, suite, parent_id, child_id, repetitions);
+ const response_id = try store.writeEvidence(gpa, response_bytes);
+ var comparison = try computeComparison(config, suite.sha256, &request_id, &response_id, pairs, response, planned_candidates);
+ comparison.request_evidence_id = try arena.dupe(u8, &request_id);
+ comparison.response_evidence_id = try arena.dupe(u8, &response_id);
+ return comparison;
+}
+
+fn comparisonEqual(a: ComparisonRecord, b: ComparisonRecord) bool {
+ return std.mem.eql(u8, a.suite_sha256, b.suite_sha256) and
+ std.mem.eql(u8, a.request_evidence_id, b.request_evidence_id) and
+ std.mem.eql(u8, a.response_evidence_id, b.response_evidence_id) and
+ a.pairs == b.pairs and a.statistical_units == b.statistical_units and
+ a.parent_passes == b.parent_passes and a.child_passes == b.child_passes and
+ a.wins == b.wins and a.losses == b.losses and a.ties == b.ties and a.critical_regressions == b.critical_regressions and
+ a.delta_ppm == b.delta_ppm and a.mean_score_delta_ppm == b.mean_score_delta_ppm and a.p_value_ppb == b.p_value_ppb and
+ a.parent_cost_micros == b.parent_cost_micros and a.child_cost_micros == b.child_cost_micros and
+ a.eligible == b.eligible and std.mem.eql(u8, a.reason, b.reason);
+}
+
+pub fn verifyComparison(
+ arena: Allocator,
+ io: Io,
+ store: *store_mod.Store,
+ config: store_mod.Config,
+ config_id: []const u8,
+ harness_version: []const u8,
+ trial_id: []const u8,
+ candidate_index: usize,
+ parent_id: []const u8,
+ child_id: []const u8,
+ suite: store_mod.Suite,
+ repetitions: usize,
+ planned_candidates: usize,
+ recorded: ComparisonRecord,
+) !ComparisonRecord {
+ if (!std.mem.eql(u8, recorded.suite_sha256, suite.sha256)) return error.ComparisonMismatch;
+ const loaded_suite = try store_mod.loadSuite(io, arena, suite);
+ const expected_pairs = try buildPairs(arena, trial_id, suite, loaded_suite.manifest, candidate_index, repetitions);
+ const request_bytes = try store.readEvidence(arena, recorded.request_evidence_id, config.limits.request_bytes);
+ const response_bytes = try store.readEvidence(arena, recorded.response_evidence_id, config.limits.response_bytes);
+ const request = try std.json.parseFromSliceLeaky(EvaluationRequest, arena, request_bytes, .{});
+ const response = try std.json.parseFromSliceLeaky(EvaluationResponse, arena, response_bytes, .{});
+ const cohort = cohortId(config_id, suite.sha256, harness_version);
+ try validateEvaluationEnvelope(request, response, trial_id, candidate_index, &cohort, suite, parent_id, child_id, repetitions);
+ if (request.pairs.len != expected_pairs.len) return error.PairMismatch;
+ for (request.pairs, expected_pairs) |actual, expected| {
+ if (!std.mem.eql(u8, actual.case_id, expected.case_id) or !std.mem.eql(u8, actual.seed, expected.seed) or actual.critical != expected.critical) return error.PairMismatch;
+ }
+ const recomputed = try computeComparison(config, suite.sha256, recorded.request_evidence_id, recorded.response_evidence_id, request.pairs, response, planned_candidates);
+ if (!comparisonEqual(recomputed, recorded)) return error.ComparisonMismatch;
+ return recomputed;
+}
+
+pub fn validateRun(run: RunRecord) !void {
+ if (!std.mem.eql(u8, run.schema, run_schema) or !store_mod.validId(run.trial_id) or !store_mod.validId(run.nonce) or !store_mod.validId(run.config_id) or !store_mod.validId(run.parent_genome_id) or !store_mod.validId(run.parent_transaction_id)) return error.InvalidRun;
+ if (run.planned_candidates == 0 or run.planned_candidates > 16 or run.candidates.len != run.planned_candidates) return error.InvalidRun;
+ if (run.repetitions == 0 or run.repetitions > 100 or run.harness_version.len == 0 or run.harness_version.len > 128) return error.InvalidRun;
+ if (run.selected_genome_id) |id| if (!store_mod.validId(id)) return error.InvalidRun;
+ for (run.candidates) |candidate| {
+ if (!store_mod.validId(candidate.genome_id) or !store_mod.validId(candidate.mutation.seed) or !store_mod.validId(candidate.mutation.request_evidence_id) or !store_mod.validId(candidate.mutation.response_evidence_id)) return error.InvalidRun;
+ if (candidate.eligible and candidate.primary == null) return error.InvalidRun;
+ }
+}
+
+test "paired tail has known exact values" {
+ try std.testing.expectApproxEqAbs(@as(f64, 0.5), pairedTail(1, 0), 1e-12);
+ try std.testing.expectApproxEqAbs(@as(f64, 0.0546875), pairedTail(8, 2), 1e-12);
+ try std.testing.expectEqual(@as(f64, 1.0), pairedTail(2, 2));
+}
+
+test "paired gate rejects critical regressions and requires corrected significance" {
+ const config: store_mod.Config = .{
+ .schema = store_mod.config_schema,
+ .agent_name = "test",
+ .mutation_instruction = "change",
+ .mutator = .{ .program = "/bin/a", .sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" },
+ .evaluator = .{ .program = "/bin/b", .sha256 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" },
+ .evaluation_suite = .{ .path = "/suite", .sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" },
+ .gate = .{ .alpha_ppm = 50_000, .minimum_delta_ppm = 0, .minimum_pairs = 1 },
+ .cohort = .{ .provider = "p", .model = "m", .task_family = "t", .adapter_version = "a", .verifier_version = "v" },
+ };
+ const case_ids = [_][]const u8{ "case-0", "case-1", "case-2", "case-3", "case-4", "case-5", "case-6", "case-7", "case-8", "case-9" };
+ var requested: [10]PairRequest = undefined;
+ var results: [10]PairResult = undefined;
+ for (0..10) |i| {
+ requested[i] = .{ .case_id = case_ids[i], .seed = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", .critical = i == 0 };
+ results[i] = .{ .case_id = requested[i].case_id, .seed = requested[i].seed, .parent_pass = false, .child_pass = true, .parent_score_ppm = 0, .child_score_ppm = 1_000_000 };
+ }
+ const response: EvaluationResponse = .{ .schema = evaluation_response_schema, .trial_id = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", .candidate_index = 0, .cohort_id = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", .suite_sha256 = config.evaluation_suite.sha256, .parent_id = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", .child_id = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", .pairs = &results };
+ const comparison = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1);
+ try std.testing.expect(comparison.eligible);
+ try std.testing.expectEqual(@as(usize, 10), comparison.statistical_units);
+
+ results[0].parent_cost_micros = js_exact_max;
+ results[1].parent_cost_micros = 1;
+ try std.testing.expectError(error.InvalidMetric, computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1));
+ results[0].parent_cost_micros = 0;
+ results[1].parent_cost_micros = 0;
+
+ for (0..10) |i| {
+ requested[i].case_id = "repeated-case";
+ results[i].case_id = "repeated-case";
+ }
+ const repeated = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1);
+ try std.testing.expect(!repeated.eligible);
+ try std.testing.expectEqual(@as(usize, 1), repeated.statistical_units);
+ try std.testing.expectEqualStrings("not_significant", repeated.reason);
+
+ results[0].parent_pass = true;
+ results[0].child_pass = false;
+ const critical = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1);
+ try std.testing.expect(!critical.eligible);
+ try std.testing.expectEqualStrings("critical_regression", critical.reason);
+}
+
+test "tool invocation executes verified private program and input snapshots" {
+ if (builtin.os.tag == .windows) return;
+ const io = std.testing.io;
+ const allocator = std.testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+
+ try writePrivateWithPermissions(io, tmp.dir, "tool.sh",
+ \\#!/bin/sh
+ \\set -eu
+ \\[ "$0" != "$ORIGINAL_PROGRAM" ]
+ \\[ "$1" != "$ORIGINAL_INPUT" ]
+ \\[ "$1" = "$GRAFF_LEARN_INPUT_0" ]
+ \\[ "$GRAFF_LEARN_INPUT_COUNT" = "1" ]
+ \\[ "$(cat "$1")" = "pinned-data" ]
+ \\printf 'snapshot-ok' > "$4"
+ \\
+ , executable_permissions);
+ try writePrivate(io, tmp.dir, "input.txt", "pinned-data\n");
+
+ var root_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const root_len = try tmp.dir.realPath(io, &root_buf);
+ const root = root_buf[0..root_len];
+ const program_path = try std.fmt.allocPrint(allocator, "{s}{c}tool.sh", .{ root, std.fs.path.sep });
+ defer allocator.free(program_path);
+ const input_path = try std.fmt.allocPrint(allocator, "{s}{c}input.txt", .{ root, std.fs.path.sep });
+ defer allocator.free(input_path);
+ const program_bytes = try store_mod.readFileNoFollow(io, tmp.dir, "tool.sh", allocator, 4096);
+ defer allocator.free(program_bytes);
+ const input_bytes = try store_mod.readFileNoFollow(io, tmp.dir, "input.txt", allocator, 4096);
+ defer allocator.free(input_bytes);
+ const program_hash = store_mod.rawSha256(program_bytes);
+ const input_hash = store_mod.rawSha256(input_bytes);
+
+ var store = try store_mod.Store.initAt(io, tmp.dir);
+ defer store.deinit();
+ var scratch_created = try createScratch(io, &store);
+ defer store.tmp.deleteTree(io, &scratch_created.name) catch {};
+ defer scratch_created.dir.close(io);
+ try scratch_created.dir.createDir(io, "home", dir_permissions);
+ try scratch_created.dir.createDir(io, "tmp", dir_permissions);
+
+ var parent_env = std.process.Environ.Map.init(allocator);
+ defer parent_env.deinit();
+ try parent_env.put("ORIGINAL_PROGRAM", program_path);
+ try parent_env.put("ORIGINAL_INPUT", input_path);
+ const inputs = [_]store_mod.PinnedFile{.{ .path = input_path, .sha256 = &input_hash }};
+ const args = [_][]const u8{input_path};
+ const pass_env = [_][]const u8{ "ORIGINAL_PROGRAM", "ORIGINAL_INPUT" };
+ const program: store_mod.Program = .{
+ .program = program_path,
+ .sha256 = &program_hash,
+ .args = &args,
+ .inputs = &inputs,
+ .pass_env = &pass_env,
+ };
+ try invoke(allocator, io, &parent_env, scratch_created.dir, program, "test", 1024, 1024, 10_000);
+ const response = try store_mod.readFileNoFollow(io, scratch_created.dir, "response.json", allocator, 1024);
+ defer allocator.free(response);
+ try std.testing.expectEqualStrings("snapshot-ok", response);
+}
diff --git a/src/learn_store.zig b/src/learn_store.zig
new file mode 100644
index 00000000..77fa9434
--- /dev/null
+++ b/src/learn_store.zig
@@ -0,0 +1,852 @@
+//! Authoritative local storage for the prompt-policy learning engine.
+//!
+//! The legacy trajectory archive remains observability only. Learning state is
+//! held in immutable, full-SHA-256-addressed objects below `.graff/learn`, and
+//! the only mutable commit point is an atomically replaced active reference.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+pub const config_schema = "codegraff.learn.config.v1";
+pub const suite_schema = "codegraff.learn.suite.v1";
+pub const active_schema = "codegraff.learn.active.v1";
+pub const transaction_schema = "codegraff.learn.transaction.v1";
+pub const version_bytes = "1\n";
+
+pub const max_config_bytes: usize = 1 << 20;
+pub const max_record_bytes: usize = 8 << 20;
+pub const max_program_bytes: u64 = 128 << 20;
+pub const max_suite_bytes: usize = 8 << 20;
+pub const max_pairs: usize = 4096;
+
+pub const PinnedFile = struct {
+ path: []const u8,
+ sha256: []const u8,
+};
+
+pub const Program = struct {
+ program: []const u8,
+ sha256: []const u8,
+ args: []const []const u8 = &.{},
+ inputs: []const PinnedFile = &.{},
+ pass_env: []const []const u8 = &.{},
+};
+
+pub const Suite = struct {
+ path: []const u8,
+ sha256: []const u8,
+};
+
+pub const Limits = struct {
+ genome_bytes: usize = 1 << 20,
+ request_bytes: usize = 1 << 20,
+ response_bytes: usize = 4 << 20,
+ stdout_bytes: usize = 64 << 10,
+ stderr_bytes: usize = 64 << 10,
+ mutator_timeout_ms: u64 = 300_000,
+ evaluator_timeout_ms: u64 = 1_800_000,
+};
+
+pub const Gate = struct {
+ alpha_ppm: u32 = 50_000,
+ minimum_delta_ppm: u32 = 50_000,
+ minimum_pairs: usize = 20,
+ default_candidates: usize = 1,
+ default_repetitions: usize = 1,
+};
+
+pub const AutoPolicy = struct {
+ enabled: bool = false,
+};
+
+pub const Cohort = struct {
+ provider: []const u8,
+ model: []const u8,
+ task_family: []const u8,
+ adapter_version: []const u8,
+ verifier_version: []const u8,
+};
+
+pub const Config = struct {
+ schema: []const u8,
+ agent_name: []const u8,
+ agent_description: []const u8 = "locally learned prompt policy",
+ mutation_instruction: []const u8,
+ mutator: Program,
+ evaluator: Program,
+ evaluation_suite: Suite,
+ holdout_suite: ?Suite = null,
+ limits: Limits = .{},
+ gate: Gate = .{},
+ auto: AutoPolicy = .{},
+ cohort: Cohort,
+};
+
+pub const SuiteCase = struct {
+ id: []const u8,
+ critical: bool = false,
+ payload: std.json.Value = .null,
+};
+
+pub const SuiteManifest = struct {
+ schema: []const u8,
+ suite_id: []const u8,
+ cases: []const SuiteCase,
+};
+
+pub const ActiveRef = struct {
+ schema: []const u8,
+ config_id: []const u8,
+ generation: u64,
+ genome_id: []const u8,
+ transaction_id: []const u8,
+};
+
+pub const Transaction = struct {
+ schema: []const u8,
+ generation: u64,
+ operation: []const u8,
+ previous_genome_id: ?[]const u8,
+ next_genome_id: []const u8,
+ run_id: ?[]const u8,
+ previous_transaction_id: ?[]const u8,
+ created_unix_ms: i64,
+};
+
+pub const LoadedConfig = struct {
+ value: Config,
+ id: [64]u8,
+ bytes: []const u8,
+};
+
+pub const LoadedActive = struct {
+ ref: ActiveRef,
+ transaction: Transaction,
+ genome: []const u8,
+};
+
+pub const ActiveAgent = struct {
+ name: []const u8,
+ description: []const u8,
+ prompt: []const u8,
+ genome_id: []const u8,
+ generation: u64,
+};
+
+const dir_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_dir else .fromMode(0o700);
+const file_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_file else .fromMode(0o600);
+
+/// Persist a directory entry after an atomic link or rename. Io.Dir owns the
+/// handle; the temporary Io.File view must never be closed independently.
+/// Windows directory handles do not portably support FlushFileBuffers through
+/// this API (ACCESS_DENIED is common), so Windows relies on atomic replacement
+/// plus synced file contents and has a weaker crash-durability guarantee.
+fn syncDirectory(io: Io, dir: Io.Dir) !void {
+ if (builtin.os.tag == .windows) return;
+ if (builtin.os.tag != .wasi and dir.handle == std.posix.AT.FDCWD) {
+ var actual = try dir.openDir(io, ".", .{ .iterate = true, .follow_symlinks = false });
+ defer actual.close(io);
+ return syncDirectory(io, actual);
+ }
+ const file: Io.File = .{ .handle = dir.handle, .flags = .{ .nonblocking = false } };
+ try file.sync(io);
+}
+
+pub fn validId(id: []const u8) bool {
+ if (id.len != 64) return false;
+ for (id) |c| if (!(std.ascii.isDigit(c) or (c >= 'a' and c <= 'f'))) return false;
+ return true;
+}
+
+fn validName(value: []const u8, max: usize) bool {
+ if (value.len == 0 or value.len > max or !std.unicode.utf8ValidateSlice(value)) return false;
+ for (value) |c| {
+ if (!(std.ascii.isAlphanumeric(c) or c == '-' or c == '_' or c == '.')) return false;
+ }
+ return !std.mem.eql(u8, value, ".") and !std.mem.eql(u8, value, "..");
+}
+
+fn validText(value: []const u8, max: usize) bool {
+ return value.len > 0 and value.len <= max and std.unicode.utf8ValidateSlice(value) and std.mem.indexOfScalar(u8, value, 0) == null;
+}
+
+fn validEnvName(value: []const u8) bool {
+ if (value.len == 0 or value.len > 128) return false;
+ if (!(std.ascii.isAlphabetic(value[0]) or value[0] == '_')) return false;
+ for (value[1..]) |c| if (!(std.ascii.isAlphanumeric(c) or c == '_')) return false;
+ return !std.mem.eql(u8, value, "HOME") and
+ !std.mem.eql(u8, value, "USERPROFILE") and
+ !std.mem.eql(u8, value, "TMPDIR") and
+ !std.mem.eql(u8, value, "TMP") and
+ !std.mem.eql(u8, value, "TEMP") and
+ !std.mem.startsWith(u8, value, "GRAFF_LEARN_");
+}
+
+pub fn validateConfig(config: Config) !void {
+ if (!std.mem.eql(u8, config.schema, config_schema)) return error.UnsupportedSchema;
+ if (!validName(config.agent_name, 64)) return error.InvalidAgentName;
+ if (!validText(config.agent_description, 512)) return error.InvalidDescription;
+ if (!validText(config.mutation_instruction, 4096)) return error.InvalidMutationInstruction;
+ try validateProgram(config.mutator);
+ try validateProgram(config.evaluator);
+ try validateSuitePin(config.evaluation_suite);
+ if (config.holdout_suite) |suite| try validateSuitePin(suite);
+
+ if (config.limits.genome_bytes == 0 or config.limits.genome_bytes > 8 << 20) return error.InvalidLimit;
+ if (config.limits.request_bytes < 1024 or config.limits.request_bytes > max_record_bytes) return error.InvalidLimit;
+ if (config.limits.response_bytes < 1024 or config.limits.response_bytes > max_record_bytes) return error.InvalidLimit;
+ if (config.limits.stdout_bytes > 1 << 20 or config.limits.stderr_bytes > 1 << 20) return error.InvalidLimit;
+ if (config.limits.mutator_timeout_ms == 0 or config.limits.mutator_timeout_ms > 3_600_000) return error.InvalidLimit;
+ if (config.limits.evaluator_timeout_ms == 0 or config.limits.evaluator_timeout_ms > 3_600_000) return error.InvalidLimit;
+
+ if (config.gate.alpha_ppm == 0 or config.gate.alpha_ppm > 500_000) return error.InvalidGate;
+ if (config.gate.minimum_delta_ppm > 1_000_000) return error.InvalidGate;
+ if (config.gate.minimum_pairs == 0 or config.gate.minimum_pairs > max_pairs) return error.InvalidGate;
+ if (config.gate.default_candidates == 0 or config.gate.default_candidates > 16) return error.InvalidGate;
+ if (config.gate.default_repetitions == 0 or config.gate.default_repetitions > 100) return error.InvalidGate;
+ if (config.auto.enabled and config.holdout_suite == null) return error.AutoRequiresHoldout;
+
+ inline for (.{ config.cohort.provider, config.cohort.model, config.cohort.task_family, config.cohort.adapter_version, config.cohort.verifier_version }) |field| {
+ if (!validText(field, 256)) return error.InvalidCohort;
+ }
+}
+
+fn validateProgram(program: Program) !void {
+ if (!std.fs.path.isAbsolute(program.program) or !validText(program.program, std.fs.max_path_bytes)) return error.InvalidProgramPath;
+ if (!validId(program.sha256)) return error.InvalidDigest;
+ if (program.args.len > 64 or program.inputs.len > 64 or program.pass_env.len > 32) return error.InvalidProgramConfig;
+ for (program.args) |arg| if (arg.len > 4096 or std.mem.indexOfScalar(u8, arg, 0) != null) return error.InvalidProgramConfig;
+ for (program.inputs, 0..) |input, i| {
+ if (!std.fs.path.isAbsolute(input.path) or !validText(input.path, std.fs.max_path_bytes) or !validId(input.sha256)) return error.InvalidProgramConfig;
+ for (program.inputs[0..i]) |prior| if (std.mem.eql(u8, prior.path, input.path)) return error.DuplicateProgramInput;
+ }
+ for (program.pass_env, 0..) |name, i| {
+ if (!validEnvName(name)) return error.InvalidEnvironmentName;
+ for (program.pass_env[0..i]) |prior| if (std.mem.eql(u8, prior, name)) return error.DuplicateEnvironmentName;
+ }
+}
+
+fn validateSuitePin(suite: Suite) !void {
+ if (!std.fs.path.isAbsolute(suite.path) or !validText(suite.path, std.fs.max_path_bytes)) return error.InvalidSuitePath;
+ if (!validId(suite.sha256)) return error.InvalidDigest;
+}
+
+pub fn validateSuite(manifest: SuiteManifest) !void {
+ if (!std.mem.eql(u8, manifest.schema, suite_schema)) return error.UnsupportedSuiteSchema;
+ if (!validName(manifest.suite_id, 128)) return error.InvalidSuiteId;
+ if (manifest.cases.len == 0 or manifest.cases.len > max_pairs) return error.InvalidSuiteCases;
+ for (manifest.cases, 0..) |case, i| {
+ if (!validName(case.id, 128)) return error.InvalidCaseId;
+ for (manifest.cases[0..i]) |prior| if (std.mem.eql(u8, prior.id, case.id)) return error.DuplicateCaseId;
+ }
+}
+
+pub fn rawSha256(bytes: []const u8) [64]u8 {
+ var digest: [32]u8 = undefined;
+ std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{});
+ return std.fmt.bytesToHex(digest, .lower);
+}
+
+pub fn domainId(domain: []const u8, bytes: []const u8) [64]u8 {
+ var hash = std.crypto.hash.sha2.Sha256.init(.{});
+ hash.update(domain);
+ hash.update(&.{0});
+ var len: [8]u8 = undefined;
+ std.mem.writeInt(u64, len[0..], @intCast(bytes.len), .big);
+ hash.update(&len);
+ hash.update(bytes);
+ var digest: [32]u8 = undefined;
+ hash.final(&digest);
+ return std.fmt.bytesToHex(digest, .lower);
+}
+
+pub fn jsonBytes(gpa: Allocator, value: anytype) ![]u8 {
+ var allocating: Io.Writer.Allocating = .init(gpa);
+ defer allocating.deinit();
+ var stringify: std.json.Stringify = .{ .writer = &allocating.writer };
+ try stringify.write(value);
+ try allocating.writer.writeByte('\n');
+ return gpa.dupe(u8, allocating.writer.buffered());
+}
+
+pub fn randomId(io: Io) [64]u8 {
+ var raw: [32]u8 = undefined;
+ io.randomSecure(&raw) catch io.random(&raw);
+ return std.fmt.bytesToHex(raw, .lower);
+}
+
+pub fn readFileNoFollow(io: Io, dir: Io.Dir, path: []const u8, gpa: Allocator, max: usize) ![]u8 {
+ const file = if (std.fs.path.isAbsolute(path))
+ try Io.Dir.openFileAbsolute(io, path, .{ .follow_symlinks = false })
+ else
+ try dir.openFile(io, path, .{ .follow_symlinks = false, .resolve_beneath = true });
+ defer file.close(io);
+ const before = try file.stat(io);
+ if (before.kind != .file) return error.NotRegularFile;
+ if (before.size > max) return error.FileTooBig;
+ const size: usize = @intCast(before.size);
+ const bytes = try gpa.alloc(u8, size);
+ errdefer gpa.free(bytes);
+ const read = try file.readPositionalAll(io, bytes, 0);
+ if (read != size) return error.UnexpectedEndOfFile;
+ const after = try file.stat(io);
+ if (after.kind != .file or after.size != before.size) return error.FileChanged;
+ return bytes;
+}
+
+pub fn readPinnedFileAlloc(io: Io, gpa: Allocator, pin: PinnedFile, max: u64) ![]u8 {
+ if (!std.fs.path.isAbsolute(pin.path)) return error.PathNotAbsolute;
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const real_len = try Io.Dir.realPathFileAbsolute(io, pin.path, &real_buf);
+ if (!std.mem.eql(u8, pin.path, real_buf[0..real_len])) return error.NonCanonicalPath;
+
+ const file = try Io.Dir.openFileAbsolute(io, pin.path, .{ .follow_symlinks = false });
+ defer file.close(io);
+ const before = try file.stat(io);
+ if (before.kind != .file) return error.NotRegularFile;
+ if (before.size > max or before.size > std.math.maxInt(usize)) return error.FileTooBig;
+ if (builtin.os.tag != .windows and (before.permissions.toMode() & 0o022) != 0) return error.InsecurePermissions;
+
+ const bytes = try gpa.alloc(u8, @intCast(before.size));
+ errdefer gpa.free(bytes);
+ const read = try file.readPositionalAll(io, bytes, 0);
+ if (read != bytes.len) return error.UnexpectedEndOfFile;
+ const after = try file.stat(io);
+ if (after.kind != .file or after.size != before.size) return error.FileChanged;
+ const actual = rawSha256(bytes);
+ if (!std.mem.eql(u8, &actual, pin.sha256)) return error.PinMismatch;
+ return bytes;
+}
+
+pub fn hashFileNoFollow(io: Io, path: []const u8) ![64]u8 {
+ if (!std.fs.path.isAbsolute(path)) return error.PathNotAbsolute;
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const real_len = try Io.Dir.realPathFileAbsolute(io, path, &real_buf);
+ if (!std.mem.eql(u8, path, real_buf[0..real_len])) return error.NonCanonicalPath;
+
+ const file = try Io.Dir.openFileAbsolute(io, path, .{ .follow_symlinks = false });
+ defer file.close(io);
+ const before = try file.stat(io);
+ if (before.kind != .file) return error.NotRegularFile;
+ if (before.size > max_program_bytes) return error.FileTooBig;
+ if (builtin.os.tag != .windows and (before.permissions.toMode() & 0o022) != 0) return error.InsecurePermissions;
+
+ var hash = std.crypto.hash.sha2.Sha256.init(.{});
+ var buffer: [64 << 10]u8 = undefined;
+ var offset: u64 = 0;
+ while (offset < before.size) {
+ const want: usize = @intCast(@min(@as(u64, buffer.len), before.size - offset));
+ const got = try file.readPositionalAll(io, buffer[0..want], offset);
+ if (got != want) return error.UnexpectedEndOfFile;
+ hash.update(buffer[0..got]);
+ offset += got;
+ }
+ const after = try file.stat(io);
+ if (after.kind != .file or after.size != before.size) return error.FileChanged;
+ var digest: [32]u8 = undefined;
+ hash.final(&digest);
+ return std.fmt.bytesToHex(digest, .lower);
+}
+
+pub fn verifyPinnedFile(io: Io, pin: PinnedFile) !void {
+ const actual = try hashFileNoFollow(io, pin.path);
+ if (!std.mem.eql(u8, &actual, pin.sha256)) return error.PinMismatch;
+}
+
+pub fn verifyProgram(io: Io, program: Program) !void {
+ try verifyPinnedFile(io, .{ .path = program.program, .sha256 = program.sha256 });
+ for (program.inputs) |input| try verifyPinnedFile(io, input);
+}
+
+pub fn loadSuite(io: Io, arena: Allocator, suite: Suite) !struct { manifest: SuiteManifest, bytes: []const u8 } {
+ const bytes = try readPinnedFileAlloc(io, arena, .{ .path = suite.path, .sha256 = suite.sha256 }, max_suite_bytes);
+ const manifest = try std.json.parseFromSliceLeaky(SuiteManifest, arena, bytes, .{});
+ try validateSuite(manifest);
+ return .{ .manifest = manifest, .bytes = bytes };
+}
+
+fn openPrivateDir(io: Io, parent: Io.Dir, name: []const u8) !Io.Dir {
+ const dir = try parent.openDir(io, name, .{ .iterate = true, .follow_symlinks = false });
+ if (builtin.os.tag != .windows) {
+ const stat = try dir.stat(io);
+ if ((stat.permissions.toMode() & 0o077) != 0) return error.InsecurePermissions;
+ }
+ return dir;
+}
+
+fn createPrivateDir(io: Io, parent: Io.Dir, name: []const u8) !Io.Dir {
+ try parent.createDir(io, name, dir_permissions);
+ var dir = try parent.openDir(io, name, .{ .iterate = true, .follow_symlinks = false });
+ errdefer dir.close(io);
+ if (builtin.os.tag != .windows) try dir.setPermissions(io, dir_permissions);
+ try syncDirectory(io, dir);
+ try syncDirectory(io, parent);
+ return dir;
+}
+
+pub const Store = struct {
+ io: Io,
+ root: Io.Dir,
+ configs: Io.Dir,
+ genomes: Io.Dir,
+ evidence: Io.Dir,
+ runs: Io.Dir,
+ transactions: Io.Dir,
+ refs: Io.Dir,
+ locks: Io.Dir,
+ tmp: Io.Dir,
+
+ pub fn initAt(io: Io, base: Io.Dir) !Store {
+ base.createDir(io, ".graff", dir_permissions) catch |err| switch (err) {
+ error.PathAlreadyExists => {},
+ else => return err,
+ };
+ const graff = try base.openDir(io, ".graff", .{ .iterate = true, .follow_symlinks = false });
+ defer graff.close(io);
+ try syncDirectory(io, base);
+ graff.createDir(io, "learn", dir_permissions) catch |err| switch (err) {
+ error.PathAlreadyExists => return error.AlreadyInitialized,
+ else => return err,
+ };
+ var root = try graff.openDir(io, "learn", .{ .iterate = true, .follow_symlinks = false });
+ errdefer root.close(io);
+ if (builtin.os.tag != .windows) try root.setPermissions(io, dir_permissions);
+ try syncDirectory(io, root);
+ try syncDirectory(io, graff);
+
+ var configs = try createPrivateDir(io, root, "configs");
+ errdefer configs.close(io);
+ var genomes = try createPrivateDir(io, root, "genomes");
+ errdefer genomes.close(io);
+ var evidence = try createPrivateDir(io, root, "evidence");
+ errdefer evidence.close(io);
+ var runs = try createPrivateDir(io, root, "runs");
+ errdefer runs.close(io);
+ var transactions = try createPrivateDir(io, root, "transactions");
+ errdefer transactions.close(io);
+ var refs = try createPrivateDir(io, root, "refs");
+ errdefer refs.close(io);
+ var locks = try createPrivateDir(io, root, "locks");
+ errdefer locks.close(io);
+ var tmp = try createPrivateDir(io, root, "tmp");
+ errdefer tmp.close(io);
+
+ var store: Store = .{ .io = io, .root = root, .configs = configs, .genomes = genomes, .evidence = evidence, .runs = runs, .transactions = transactions, .refs = refs, .locks = locks, .tmp = tmp };
+ try store.writeImmutable(store.root, "VERSION", version_bytes, std.heap.page_allocator);
+ const lock = try store.locks.createFile(io, "engine.lock", .{ .exclusive = true, .permissions = file_permissions });
+ defer lock.close(io);
+ try lock.sync(io);
+ try syncDirectory(io, store.locks);
+ return store;
+ }
+
+ pub fn openAt(io: Io, base: Io.Dir) !Store {
+ const graff = try base.openDir(io, ".graff", .{ .iterate = true, .follow_symlinks = false });
+ defer graff.close(io);
+ var root = try openPrivateDir(io, graff, "learn");
+ errdefer root.close(io);
+ var configs = try openPrivateDir(io, root, "configs");
+ errdefer configs.close(io);
+ var genomes = try openPrivateDir(io, root, "genomes");
+ errdefer genomes.close(io);
+ var evidence = try openPrivateDir(io, root, "evidence");
+ errdefer evidence.close(io);
+ var runs = try openPrivateDir(io, root, "runs");
+ errdefer runs.close(io);
+ var transactions = try openPrivateDir(io, root, "transactions");
+ errdefer transactions.close(io);
+ var refs = try openPrivateDir(io, root, "refs");
+ errdefer refs.close(io);
+ var locks = try openPrivateDir(io, root, "locks");
+ errdefer locks.close(io);
+ var tmp = try openPrivateDir(io, root, "tmp");
+ errdefer tmp.close(io);
+ const version = try readFileNoFollow(io, root, "VERSION", std.heap.page_allocator, 16);
+ defer std.heap.page_allocator.free(version);
+ if (!std.mem.eql(u8, version, version_bytes)) return error.UnsupportedStoreVersion;
+ return .{ .io = io, .root = root, .configs = configs, .genomes = genomes, .evidence = evidence, .runs = runs, .transactions = transactions, .refs = refs, .locks = locks, .tmp = tmp };
+ }
+
+ pub fn deinit(self: *Store) void {
+ self.tmp.close(self.io);
+ self.locks.close(self.io);
+ self.refs.close(self.io);
+ self.transactions.close(self.io);
+ self.runs.close(self.io);
+ self.evidence.close(self.io);
+ self.genomes.close(self.io);
+ self.configs.close(self.io);
+ self.root.close(self.io);
+ self.* = undefined;
+ }
+
+ pub const LockGuard = struct {
+ io: Io,
+ file: Io.File,
+
+ pub fn deinit(self: *LockGuard) void {
+ self.file.unlock(self.io);
+ self.file.close(self.io);
+ self.* = undefined;
+ }
+ };
+
+ pub fn acquireLock(self: *Store, timeout_ms: u64) !LockGuard {
+ const file = try self.locks.openFile(self.io, "engine.lock", .{ .mode = .read_write, .follow_symlinks = false, .resolve_beneath = true });
+ errdefer file.close(self.io);
+ const stat = try file.stat(self.io);
+ if (stat.kind != .file) return error.InvalidLockFile;
+ const start: Io.Timestamp = .now(self.io, .awake);
+ while (!try file.tryLock(self.io, .exclusive)) {
+ if (start.untilNow(self.io, .awake).toMilliseconds() >= timeout_ms) return error.EngineBusy;
+ self.io.sleep(.fromMilliseconds(25), .awake) catch return error.EngineBusy;
+ }
+ return .{ .io = self.io, .file = file };
+ }
+
+ fn writeImmutable(self: *Store, dir: Io.Dir, name: []const u8, bytes: []const u8, gpa: Allocator) !void {
+ var atomic = try dir.createFileAtomic(self.io, name, .{ .permissions = file_permissions, .replace = false });
+ defer atomic.deinit(self.io);
+ try atomic.file.writeStreamingAll(self.io, bytes);
+ try atomic.file.sync(self.io);
+ atomic.link(self.io) catch |err| switch (err) {
+ error.PathAlreadyExists => {
+ const existing = try readFileNoFollow(self.io, dir, name, gpa, bytes.len + 1);
+ defer gpa.free(existing);
+ if (!std.mem.eql(u8, existing, bytes)) return error.ImmutableObjectConflict;
+ },
+ else => return err,
+ };
+ try syncDirectory(self.io, dir);
+ }
+
+ fn writeAtomicReplace(self: *Store, dir: Io.Dir, name: []const u8, bytes: []const u8) !void {
+ var atomic = try dir.createFileAtomic(self.io, name, .{ .permissions = file_permissions, .replace = true });
+ defer atomic.deinit(self.io);
+ try atomic.file.writeStreamingAll(self.io, bytes);
+ try atomic.file.sync(self.io);
+ try atomic.replace(self.io);
+ try syncDirectory(self.io, dir);
+ }
+
+ fn objectName(id: []const u8, extension: []const u8, buffer: []u8) ![]const u8 {
+ if (!validId(id)) return error.InvalidId;
+ return std.fmt.bufPrint(buffer, "{s}{s}", .{ id, extension });
+ }
+
+ fn writeAddressed(self: *Store, gpa: Allocator, dir: Io.Dir, domain: []const u8, extension: []const u8, bytes: []const u8) ![64]u8 {
+ const id = domainId(domain, bytes);
+ var name_buf: [80]u8 = undefined;
+ const name = try objectName(&id, extension, &name_buf);
+ try self.writeImmutable(dir, name, bytes, gpa);
+ return id;
+ }
+
+ fn readAddressed(self: *Store, arena: Allocator, dir: Io.Dir, domain: []const u8, extension: []const u8, id: []const u8, max: usize) ![]const u8 {
+ var name_buf: [80]u8 = undefined;
+ const name = try objectName(id, extension, &name_buf);
+ const bytes = try readFileNoFollow(self.io, dir, name, arena, max);
+ if (!std.mem.eql(u8, &domainId(domain, bytes), id)) return error.ObjectHashMismatch;
+ return bytes;
+ }
+
+ pub fn writeGenome(self: *Store, gpa: Allocator, bytes: []const u8) ![64]u8 {
+ if (bytes.len == 0 or !std.unicode.utf8ValidateSlice(bytes)) return error.InvalidGenome;
+ return self.writeAddressed(gpa, self.genomes, "codegraff-learn/genome/v1", ".md", bytes);
+ }
+
+ pub fn readGenome(self: *Store, arena: Allocator, id: []const u8, max: usize) ![]const u8 {
+ return self.readAddressed(arena, self.genomes, "codegraff-learn/genome/v1", ".md", id, max);
+ }
+
+ pub fn writeEvidence(self: *Store, gpa: Allocator, bytes: []const u8) ![64]u8 {
+ return self.writeAddressed(gpa, self.evidence, "codegraff-learn/evidence/v1", ".json", bytes);
+ }
+
+ pub fn readEvidence(self: *Store, arena: Allocator, id: []const u8, max: usize) ![]const u8 {
+ return self.readAddressed(arena, self.evidence, "codegraff-learn/evidence/v1", ".json", id, max);
+ }
+
+ pub fn writeRun(self: *Store, gpa: Allocator, bytes: []const u8) ![64]u8 {
+ return self.writeAddressed(gpa, self.runs, "codegraff-learn/run/v1", ".json", bytes);
+ }
+
+ pub fn readRun(self: *Store, arena: Allocator, id: []const u8) ![]const u8 {
+ return self.readAddressed(arena, self.runs, "codegraff-learn/run/v1", ".json", id, max_record_bytes);
+ }
+
+ pub fn writeTransaction(self: *Store, gpa: Allocator, bytes: []const u8) ![64]u8 {
+ return self.writeAddressed(gpa, self.transactions, "codegraff-learn/transaction/v1", ".json", bytes);
+ }
+
+ pub fn readTransaction(self: *Store, arena: Allocator, id: []const u8) ![]const u8 {
+ return self.readAddressed(arena, self.transactions, "codegraff-learn/transaction/v1", ".json", id, max_record_bytes);
+ }
+
+ pub fn loadConfig(self: *Store, arena: Allocator) !LoadedConfig {
+ const bytes = try readFileNoFollow(self.io, self.root, "config.json", arena, max_config_bytes);
+ const id = domainId("codegraff-learn/config/v1", bytes);
+ const value = try std.json.parseFromSliceLeaky(Config, arena, bytes, .{});
+ try validateConfig(value);
+ var name_buf: [80]u8 = undefined;
+ const object_name = try objectName(&id, ".json", &name_buf);
+ const immutable = try readFileNoFollow(self.io, self.configs, object_name, arena, max_config_bytes);
+ if (!std.mem.eql(u8, immutable, bytes)) return error.ConfigChanged;
+ return .{ .value = value, .id = id, .bytes = bytes };
+ }
+
+ pub fn bootstrap(self: *Store, gpa: Allocator, arena: Allocator, config_bytes: []const u8, parent: []const u8, created_unix_ms: i64) ![64]u8 {
+ const config = try std.json.parseFromSliceLeaky(Config, arena, config_bytes, .{});
+ try validateConfig(config);
+ if (parent.len > config.limits.genome_bytes or std.mem.trim(u8, parent, " \t\r\n").len == 0) return error.InvalidGenome;
+ const config_id = domainId("codegraff-learn/config/v1", config_bytes);
+ var config_name_buf: [80]u8 = undefined;
+ const config_name = try objectName(&config_id, ".json", &config_name_buf);
+ try self.writeImmutable(self.configs, config_name, config_bytes, gpa);
+ try self.writeImmutable(self.root, "config.json", config_bytes, gpa);
+ const genome_id = try self.writeGenome(gpa, parent);
+
+ const tx: Transaction = .{
+ .schema = transaction_schema,
+ .generation = 0,
+ .operation = "init",
+ .previous_genome_id = null,
+ .next_genome_id = &genome_id,
+ .run_id = null,
+ .previous_transaction_id = null,
+ .created_unix_ms = created_unix_ms,
+ };
+ const tx_bytes = try jsonBytes(gpa, tx);
+ defer gpa.free(tx_bytes);
+ const tx_id = try self.writeTransaction(gpa, tx_bytes);
+ const active: ActiveRef = .{
+ .schema = active_schema,
+ .config_id = &config_id,
+ .generation = 0,
+ .genome_id = &genome_id,
+ .transaction_id = &tx_id,
+ };
+ const active_bytes = try jsonBytes(gpa, active);
+ defer gpa.free(active_bytes);
+ try self.writeImmutable(self.refs, "active.json", active_bytes, gpa);
+ return genome_id;
+ }
+
+ pub fn validateTransactionChain(self: *Store, arena: Allocator, transaction_id: []const u8, transaction: Transaction) !void {
+ if (!validId(transaction_id)) return error.InvalidId;
+ var current = transaction;
+ while (true) {
+ try validateTransaction(current);
+ if (current.generation == 0) break;
+ const previous_id = current.previous_transaction_id orelse return error.BrokenTransactionChain;
+ const previous_bytes = try self.readTransaction(arena, previous_id);
+ const previous = try std.json.parseFromSliceLeaky(Transaction, arena, previous_bytes, .{});
+ try validateTransaction(previous);
+ const expected_generation = std.math.add(u64, previous.generation, 1) catch return error.BrokenTransactionChain;
+ if (expected_generation != current.generation or
+ !std.mem.eql(u8, previous.next_genome_id, current.previous_genome_id.?)) return error.BrokenTransactionChain;
+ current = previous;
+ }
+ }
+
+ fn ensureExpectedActive(self: *Store, gpa: Allocator, expected: ActiveRef, config_id: []const u8) !void {
+ const bytes = try readFileNoFollow(self.io, self.refs, "active.json", gpa, max_record_bytes);
+ defer gpa.free(bytes);
+ var parsed = try std.json.parseFromSlice(ActiveRef, gpa, bytes, .{});
+ defer parsed.deinit();
+ const current = parsed.value;
+ if (!std.mem.eql(u8, current.schema, active_schema) or
+ !std.mem.eql(u8, current.config_id, config_id) or
+ current.generation != expected.generation or
+ !std.mem.eql(u8, current.genome_id, expected.genome_id) or
+ !std.mem.eql(u8, current.transaction_id, expected.transaction_id)) return error.ActiveRefChanged;
+ }
+
+ pub fn loadActive(self: *Store, arena: Allocator, config: LoadedConfig) !LoadedActive {
+ const active_bytes = try readFileNoFollow(self.io, self.refs, "active.json", arena, max_record_bytes);
+ const active = try std.json.parseFromSliceLeaky(ActiveRef, arena, active_bytes, .{});
+ if (!std.mem.eql(u8, active.schema, active_schema) or !validId(active.config_id) or !validId(active.genome_id) or !validId(active.transaction_id)) return error.InvalidActiveRef;
+ if (!std.mem.eql(u8, active.config_id, &config.id)) return error.ConfigChanged;
+ const tx_bytes = try self.readTransaction(arena, active.transaction_id);
+ const tx = try std.json.parseFromSliceLeaky(Transaction, arena, tx_bytes, .{});
+ try validateTransaction(tx);
+ if (tx.generation != active.generation or !std.mem.eql(u8, tx.next_genome_id, active.genome_id)) return error.InvalidActiveRef;
+ try self.validateTransactionChain(arena, active.transaction_id, tx);
+ const genome = try self.readGenome(arena, active.genome_id, config.value.limits.genome_bytes);
+ return .{ .ref = active, .transaction = tx, .genome = genome };
+ }
+
+ pub fn activate(self: *Store, gpa: Allocator, expected: ActiveRef, config_id: []const u8, next_genome_id: []const u8, run_id: ?[]const u8, operation: []const u8, max_genome_bytes: usize, created_unix_ms: i64) !void {
+ if (!std.mem.eql(u8, operation, "promote") and !std.mem.eql(u8, operation, "rollback")) return error.InvalidOperation;
+ if (!validId(config_id) or !validId(next_genome_id)) return error.InvalidId;
+ if (run_id) |id| if (!validId(id)) return error.InvalidId;
+ if (max_genome_bytes == 0 or max_genome_bytes > max_record_bytes) return error.InvalidLimit;
+ try self.ensureExpectedActive(gpa, expected, config_id);
+ const verified_genome = try self.readGenome(gpa, next_genome_id, max_genome_bytes);
+ defer gpa.free(verified_genome);
+ const generation = std.math.add(u64, expected.generation, 1) catch return error.GenerationOverflow;
+ const tx: Transaction = .{
+ .schema = transaction_schema,
+ .generation = generation,
+ .operation = operation,
+ .previous_genome_id = expected.genome_id,
+ .next_genome_id = next_genome_id,
+ .run_id = run_id,
+ .previous_transaction_id = expected.transaction_id,
+ .created_unix_ms = created_unix_ms,
+ };
+ const tx_bytes = try jsonBytes(gpa, tx);
+ defer gpa.free(tx_bytes);
+ const tx_id = try self.writeTransaction(gpa, tx_bytes);
+ const active: ActiveRef = .{
+ .schema = active_schema,
+ .config_id = config_id,
+ .generation = generation,
+ .genome_id = next_genome_id,
+ .transaction_id = &tx_id,
+ };
+ const active_bytes = try jsonBytes(gpa, active);
+ defer gpa.free(active_bytes);
+ try self.writeAtomicReplace(self.refs, "active.json", active_bytes);
+ }
+};
+
+pub fn validateTransaction(tx: Transaction) !void {
+ if (!std.mem.eql(u8, tx.schema, transaction_schema)) return error.UnsupportedSchema;
+ if (!std.mem.eql(u8, tx.operation, "init") and !std.mem.eql(u8, tx.operation, "promote") and !std.mem.eql(u8, tx.operation, "rollback")) return error.InvalidOperation;
+ if (!validId(tx.next_genome_id)) return error.InvalidId;
+ if (tx.previous_genome_id) |id| if (!validId(id)) return error.InvalidId;
+ if (tx.run_id) |id| if (!validId(id)) return error.InvalidId;
+ if (tx.previous_transaction_id) |id| if (!validId(id)) return error.InvalidId;
+ if (std.mem.eql(u8, tx.operation, "init")) {
+ if (tx.generation != 0 or tx.previous_genome_id != null or tx.previous_transaction_id != null or tx.run_id != null) return error.InvalidTransaction;
+ } else if (tx.generation == 0 or tx.previous_genome_id == null or tx.previous_transaction_id == null) return error.InvalidTransaction;
+ if (std.mem.eql(u8, tx.operation, "promote") and tx.run_id == null) return error.InvalidTransaction;
+ if (std.mem.eql(u8, tx.operation, "rollback") and tx.run_id != null) return error.InvalidTransaction;
+}
+
+/// Best-effort, fail-closed bridge into the ordinary agent registry. Corrupt or
+/// incomplete learning state never becomes an executable prompt policy.
+pub fn loadActiveAgent(io: Io, arena: Allocator) ?ActiveAgent {
+ var store = Store.openAt(io, Io.Dir.cwd()) catch return null;
+ defer store.deinit();
+ const config = store.loadConfig(arena) catch return null;
+ const active = store.loadActive(arena, config) catch return null;
+ return .{
+ .name = config.value.agent_name,
+ .description = config.value.agent_description,
+ .prompt = active.genome,
+ .genome_id = active.ref.genome_id,
+ .generation = active.ref.generation,
+ };
+}
+
+test "learning IDs are full, domain-separated, and byte exact" {
+ const a = domainId("codegraff-learn/genome/v1", "hello\n");
+ const b = domainId("codegraff-learn/genome/v1", "hello");
+ const c = domainId("codegraff-learn/evidence/v1", "hello\n");
+ try std.testing.expect(validId(&a));
+ try std.testing.expect(!std.mem.eql(u8, &a, &b));
+ try std.testing.expect(!std.mem.eql(u8, &a, &c));
+ try std.testing.expect(!validId("ABC"));
+}
+
+test "learning config parser rejects unknown fields and unsafe auto" {
+ const good =
+ \\{"schema":"codegraff.learn.config.v1","agent_name":"candidate","mutation_instruction":"change one behavior","mutator":{"program":"/bin/a","sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"evaluator":{"program":"/bin/b","sha256":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"},"evaluation_suite":{"path":"/suite","sha256":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"},"cohort":{"provider":"test","model":"test","task_family":"test","adapter_version":"v1","verifier_version":"v1"}}
+ ;
+ var parsed = try std.json.parseFromSlice(Config, std.testing.allocator, good, .{});
+ defer parsed.deinit();
+ try validateConfig(parsed.value);
+ const unknown = good[0 .. good.len - 1] ++ ",\"surprise\":true}";
+ try std.testing.expectError(error.UnknownField, std.json.parseFromSlice(Config, std.testing.allocator, unknown, .{}));
+}
+
+test "immutable learning objects and atomic active ref round trip" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var store = try Store.initAt(io, tmp.dir);
+ defer store.deinit();
+
+ const first = try store.writeGenome(std.testing.allocator, "prompt one");
+ const again = try store.writeGenome(std.testing.allocator, "prompt one");
+ try std.testing.expectEqualStrings(&first, &again);
+ const read = try store.readGenome(std.testing.allocator, &first, 1024);
+ defer std.testing.allocator.free(read);
+ try std.testing.expectEqualStrings("prompt one", read);
+}
+
+test "learning activation rejects stale refs and broken transaction ancestry" {
+ const io = std.testing.io;
+ const allocator = std.testing.allocator;
+ var arena_state = std.heap.ArenaAllocator.init(allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var store = try Store.initAt(io, tmp.dir);
+ defer store.deinit();
+
+ const config: Config = .{
+ .schema = config_schema,
+ .agent_name = "test-agent",
+ .mutation_instruction = "change",
+ .mutator = .{ .program = "/bin/a", .sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" },
+ .evaluator = .{ .program = "/bin/b", .sha256 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" },
+ .evaluation_suite = .{ .path = "/suite", .sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" },
+ .cohort = .{ .provider = "p", .model = "m", .task_family = "t", .adapter_version = "a", .verifier_version = "v" },
+ };
+ const config_bytes = try jsonBytes(allocator, config);
+ defer allocator.free(config_bytes);
+ _ = try store.bootstrap(allocator, arena, config_bytes, "parent", 1);
+ const loaded_config = try store.loadConfig(arena);
+ const active_zero = try store.loadActive(arena, loaded_config);
+ const second = try store.writeGenome(allocator, "second");
+ try std.testing.expectError(error.FileTooBig, store.activate(allocator, active_zero.ref, &loaded_config.id, &second, null, "rollback", 1, 2));
+ try store.activate(allocator, active_zero.ref, &loaded_config.id, &second, null, "rollback", config.limits.genome_bytes, 2);
+ const active_one = try store.loadActive(arena, loaded_config);
+ const third = try store.writeGenome(allocator, "third");
+ try std.testing.expectError(error.ActiveRefChanged, store.activate(allocator, active_zero.ref, &loaded_config.id, &third, null, "rollback", config.limits.genome_bytes, 3));
+
+ const broken_tx: Transaction = .{
+ .schema = transaction_schema,
+ .generation = 2,
+ .operation = "rollback",
+ .previous_genome_id = active_one.ref.genome_id,
+ .next_genome_id = &third,
+ .run_id = null,
+ .previous_transaction_id = active_zero.ref.transaction_id,
+ .created_unix_ms = 4,
+ };
+ const broken_tx_bytes = try jsonBytes(allocator, broken_tx);
+ defer allocator.free(broken_tx_bytes);
+ const broken_tx_id = try store.writeTransaction(allocator, broken_tx_bytes);
+ const broken_active: ActiveRef = .{
+ .schema = active_schema,
+ .config_id = &loaded_config.id,
+ .generation = 2,
+ .genome_id = &third,
+ .transaction_id = &broken_tx_id,
+ };
+ const broken_active_bytes = try jsonBytes(allocator, broken_active);
+ defer allocator.free(broken_active_bytes);
+ try store.writeAtomicReplace(store.refs, "active.json", broken_active_bytes);
+ try std.testing.expectError(error.BrokenTransactionChain, store.loadActive(arena, loaded_config));
+}
+
+test "learning store rejects symlinked root" {
+ if (builtin.os.tag == .windows) return;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.createDir(io, "outside", .default_dir);
+ try tmp.dir.symLink(io, "outside", ".graff", .{ .is_directory = true });
+ if (Store.initAt(io, tmp.dir)) |opened| {
+ var store = opened;
+ store.deinit();
+ return error.TestExpectedError;
+ } else |_| {}
+}
diff --git a/src/main.zig b/src/main.zig
index ceec6047..96049d02 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -69,6 +69,9 @@ const pricing = @import("pricing.zig"); // model pricing/catalog + session cost
const models_cache = @import("models_cache.zig"); // graff models [refresh]: models.dev metadata cache + runtime overlay
const command_catalog = @import("command_catalog.zig");
const util = @import("util.zig"); // shared JSON ObjectMap getters (strFieldObj/intFieldObj)
+const learn_store = @import("learn_store.zig");
+const learn_eval = @import("learn_eval.zig");
+const learn_cli = @import("learn_cli.zig");
test {
// build.zig's unit_tests root is main.zig only — reference every split-out module so their test blocks keep running.
_ = pricing;
@@ -76,6 +79,9 @@ test {
_ = ansi;
_ = serve;
_ = util;
+ _ = learn_store;
+ _ = learn_eval;
+ _ = learn_cli;
_ = oauth;
_ = anim;
_ = approvals_mod;
@@ -142,10 +148,16 @@ const Keys = provider_mod.Keys;
// Approvals (command/tool approval gate) + confinedPath/noSymlinkEscape live in approvals.zig; main() constructs one directly for the session.
const approvals_mod = @import("approvals.zig");
const Approvals = approvals_mod.Approvals;
-// Run-scoped session tracing + DGM trajectory files live in trace.zig.
+// Operational tracing, per-run behavioral traces, and run-scoped DGM
+// trajectory files live in trace.zig.
const trace = @import("trace.zig");
const Tracer = trace.Tracer;
+const BehaviorTrace = trace.BehaviorTrace;
+const behavior_upload = @import("behavior_upload.zig");
const Trajectory = trace.Trajectory;
+const behavior_dir = trace.behavior_dir;
+const trajectory_path = trace.trajectory_path;
+const trace_path = trace.trace_path;
// Agent types / fleet (MAP-Elites niches): the AgentType registry, backgrounded elite pull, /agents promote, and niche/override resolvers live in fleet.zig.
const fleet = @import("fleet.zig");
const joinElites = fleet.joinElites;
@@ -426,8 +438,10 @@ pub fn main(init: std.process.Init) !void {
var snaps: Snapshots = .{ .gpa = gpa, .io = io };
defer snaps.deinit();
- // Background bash jobs die with the session: kill, await pumps, free.
- defer jobsReap(gpa, io);
+ // Keep an early fallback for failures before behavioral tracing is set up.
+ // A later guarded defer moves normal reaping ahead of terminal upload.
+ var jobs_reaped = false;
+ defer if (!jobs_reaped) jobsReap(gpa, io);
// Root Agent construction + post-construction config (session name, persisted thinking/goal/eval settings, session-start trace note) + the
// backgrounded fleet-champion pull live in session_start.zig. `root`'s pointer fields (snapshots/client/tracer/approvals/registry) all reference
// already-stable main()-owned storage passed in by address, so returning the constructed Agent by value here is safe.
@@ -439,9 +453,79 @@ pub fn main(init: std.process.Init) !void {
root.fallback_active = stale_saved_model != null;
root.fallback_blocked = root.fallback_active and preferred_provider != null and !std.mem.eql(u8, preferred_provider.?, root.provider.id) and !fallback_config.contains(root.fallback_allow, root.provider.id);
boot.mark(io, "root agent");
+
+ // Behavioral tracing starts only after the root Agent exists, so utility
+ // and self-test paths do not create zero-turn behavioral runs. The local
+ // JSONL and the privacy-projected upload are independent sinks.
+ const behavior_upload_mode = behavior_upload.resolveMode(
+ init.environ_map.get("GRAFF_BEHAVIOR_UPLOAD"),
+ telem.endpoint.len > 0,
+ );
+ var behavior_uploader: behavior_upload.Upload = .{
+ .io = io,
+ .gpa = gpa,
+ .client = &client,
+ .endpoint = telem.endpoint,
+ .auth_key = telem.auth_key,
+ .install_id = telem.install_id,
+ .client_name = telem.client_name,
+ .service_version = harness_version,
+ .run_id = &scoring.g_run_id,
+ .mode = behavior_upload_mode,
+ };
+ defer behavior_uploader.deinit();
+
+ const behavior_enabled = if (init.environ_map.get("GRAFF_BEHAVIOR_TRACE")) |value|
+ !(std.ascii.eqlIgnoreCase(value, "off") or std.mem.eql(u8, value, "0") or std.ascii.eqlIgnoreCase(value, "false") or std.ascii.eqlIgnoreCase(value, "no"))
+ else
+ true;
+ var behavior_buf: [8 * 1024]u8 = undefined;
+ var behavior_open = if (behavior_enabled)
+ session_start.openBehaviorFile(io, Io.Dir.cwd(), behavior_dir, &scoring.g_run_id, &behavior_buf)
+ else
+ session_start.FileWriterOpen{ .file = null, .writer = undefined };
+ defer if (behavior_open.file) |f| f.close(io);
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = if (behavior_open.file != null) &behavior_open.writer.interface else null,
+ .upload = if (behavior_uploader.active()) &behavior_uploader else null,
+ .run_id = &scoring.g_run_id,
+ };
+ // Assigned once; all root/subagent callbacks already share this stable
+ // tracer. The behavior storage remains alive until main's frame unwinds.
+ tracer.behavior = &behavior;
+ defer {
+ // A clean return is not a task success verdict. Session-owned workers
+ // are joined by newer defers before this terminal event and upload.
+ behavior.finish(.closed);
+ tracer.behavior = null;
+ }
+ // Registered after the normal defer so error unwinding records `error`
+ // first; finish() is idempotent and keeps that status terminal.
+ errdefer behavior.finish(.failed);
+
+ // LIFO teardown: joinElites, then background bash pumps, then emit/send
+ // run_finished, then close/deinit the two behavioral sinks. The earlier
+ // fallback remains for failures that occur before this defer is registered.
+ defer if (!jobs_reaped) {
+ jobsReap(gpa, io);
+ jobs_reaped = true;
+ };
defer joinElites(io); // reap if the session quits before any turn joins it
session_run.saveOrResumeSession(&root, &keys, arena, flags);
+ // Load restored configuration before run_started, but defer any model-backed
+ // cold-cache compaction until after lifecycle start.
+ try session_run.restoreResumedSession(arena, out, &root, &keys, flags, json_mode, g_cwd_display);
+ const behavior_prompt_sha = scoring.promptFingerprint(root.systemPrompt());
+ behavior.startWithMetadata(harness_version, telem.start_unix_ms, .{
+ .provider = root.provider.id,
+ .model = root.provider.model,
+ .prompt_sha = &behavior_prompt_sha,
+ .effort = @tagName(root.reasoning),
+ });
+ session_run.compactResumedSession(&root);
// `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL agent loop — each prompt runs a full root turn (tools + MCP) via
// replTurnCb, reusing the root agent's tool set + registry + system prompt. Self-contained — exits after.
@@ -468,7 +552,6 @@ pub fn main(init: std.process.Init) !void {
root.tools_used.deinit(gpa);
}
const interactive = use_color and !json_mode; // stdout is a TTY → enable line editing
- try session_run.restoreResumedSession(arena, out, &root, &keys, flags, json_mode, g_cwd_display);
// The interactive-REPL / --json-protocol loop lives in mainloop.zig. main() keeps owning every piece of storage the loop touches (root, keys,
// tracer/traj/telem via root, history, linebuf, stdin/stdout writers) — Ctx below only holds POINTERS into this stack frame, so nothing dangles
diff --git a/src/providers.zig b/src/providers.zig
index 7fcd79ac..8ed39316 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -24,6 +24,7 @@ const textMessage = messages_mod.textMessage;
const ansi = @import("ansi.zig");
const fallback_config = @import("fallback_config.zig");
const util = @import("util.zig");
+const trace = @import("trace.zig");
fn localProviderUrl(url: []const u8) bool {
return std.mem.startsWith(u8, url, "http://127.0.0.1") or std.mem.startsWith(u8, url, "http://localhost") or std.mem.startsWith(u8, url, "http://[::1]");
@@ -199,6 +200,8 @@ pub fn failoverEligible(detail: []const u8) bool {
/// fallback becomes active for this session but does not replace the saved
/// model preference.
pub fn runTurnWithFallback(root: *Agent, keys: *Keys, arena: Allocator, out: ?*Io.Writer) anyerror![]const u8 {
+ const behavior_turn = trace.beginRootTurn(root.tracer);
+ defer trace.endRootTurn(root.tracer, behavior_turn);
if (root.fallback_blocked) return error.FallbackConsentRequired;
var attempted: [provider_specs.len][]const u8 = undefined;
var attempted_len: usize = 1;
@@ -378,6 +381,56 @@ pub fn switchProvider(root: *Agent, arena: Allocator, p: Provider, out: *Io.Writ
// Tests moved from main.zig alongside the functions they cover (#123 split).
+test "runTurnWithFallback: blocked return closes behavioral root scope" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var events: Io.Writer.Allocating = .init(gpa);
+ defer events.deinit();
+ var behavior: trace.BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = &events.writer,
+ .run_id = "blocked-fallback-run",
+ };
+ behavior.start("test", 1);
+ var tracer: trace.Tracer = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .start = Io.Timestamp.now(io, .awake),
+ .behavior = &behavior,
+ };
+ const previous_trajectory = trace.g_traj;
+ trace.g_traj = null;
+ defer trace.g_traj = previous_trajectory;
+
+ var root: Agent = undefined;
+ root.tracer = &tracer;
+ root.fallback_blocked = true;
+ const keys: Keys = .{ .values = [_]?[]const u8{null} ** provider_specs.len };
+ try std.testing.expectError(
+ error.FallbackConsentRequired,
+ runTurnWithFallback(&root, @constCast(&keys), gpa, null),
+ );
+
+ try std.testing.expectEqual(@as(u64, 0), behavior.currentTurn());
+ try std.testing.expectEqual(
+ @as(u64, 0),
+ behavior.recordApiMetric(false, 1, 2, 3, 4, 5, false),
+ );
+
+ var turn_starts: usize = 0;
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, events.writer.buffered(), "\n"), '\n');
+ while (lines.next()) |line| {
+ if (line.len == 0) continue;
+ var parsed = try std.json.parseFromSlice(Value, gpa, line, .{});
+ defer parsed.deinit();
+ const kind = parsed.value.object.get("kind") orelse continue;
+ if (kind == .string and std.mem.eql(u8, kind.string, "turn_started")) turn_starts += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 1), turn_starts);
+}
+
test "failoverEligible: accepts unavailable credentials/models, rejects transient or prompt errors" {
try std.testing.expect(failoverEligible("codex api error: Unauthorized"));
try std.testing.expect(failoverEligible("access token has expired"));
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 971689ad..18cf4239 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -37,6 +37,7 @@ const messages_mod = @import("messages.zig");
const textMessage = messages_mod.textMessage;
const pricing = @import("pricing.zig");
const providers = @import("providers.zig");
+const trace = @import("trace.zig");
const serde = @import("serde.zig");
const fallback_config = @import("fallback_config.zig");
@@ -50,7 +51,7 @@ pub const ReplCtx = struct {
fallback_active: bool,
fallback_blocked: bool,
registry: ?*mcp.Registry,
- tracer: ?*@import("trace.zig").Tracer,
+ tracer: ?*trace.Tracer,
run_budget: ?*@import("run_budget.zig").RunBudget,
sys_normal: []const u8,
tools_anthropic: []const u8,
diff --git a/src/session_run.zig b/src/session_run.zig
index 20e6a770..564ba710 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -122,10 +122,18 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m
if (eval_note.len > 0) oneshot_user = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ oneshot_user, eval_note });
try root.messages.append(try messages_mod.textMessage(arena, "user", oneshot_user));
if (telemetry.g_telem) |t| t.countTurn();
- const final_text = providers.runTurnWithFallback(root, keys, arena, null) catch |err| switch (err) {
- error.FallbackConsentRequired => std.process.fatal("saved model unavailable; provider '{s}' is not allowlisted — run graff interactively, then /fallback allow {s}", .{ root.provider.id, root.provider.id }),
- error.ApiError => std.process.fatal("{s}", .{root.last_api_error orelse "api error"}),
- else => |e| std.process.fatal("turn failed: {t}", .{e}),
+ const final_text = providers.runTurnWithFallback(root, keys, arena, null) catch |err| {
+ // std.process.fatal does not unwind main's defers. Mirror their normal
+ // order here: join the fleet worker, reap background jobs and pumps,
+ // then emit/upload the terminal behavioral event.
+ fleet.joinElites(io);
+ jobs.jobsReap(gpa, io);
+ if (tracer.behavior) |behavior| behavior.finish(.failed);
+ switch (err) {
+ error.FallbackConsentRequired => std.process.fatal("saved model unavailable; provider '{s}' is not allowlisted — run graff interactively, then /fallback allow {s}", .{ root.provider.id, root.provider.id }),
+ error.ApiError => std.process.fatal("{s}", .{root.last_api_error orelse "api error"}),
+ else => |e| std.process.fatal("turn failed: {t}", .{e}),
+ }
};
try out.print("{s}\n", .{final_text});
try out.flush();
@@ -270,10 +278,10 @@ pub fn saveOrResumeSession(root: *agent_mod.Agent, keys: *provider_mod.Keys, are
/// Explicit resume only: bare `graff` starts fresh, while `--resume <name>`
/// restores that autosave target. Best-effort: a missing/keyless/corrupt
-/// file silently starts fresh. If the restored context is already as large
-/// as what would trigger live compaction, summarizes up front instead of
-/// re-billing the whole thing on the first turn. Moved out of main()
-/// verbatim (600-line goal); `root` is already stable main()-owned storage.
+/// file silently starts fresh. This load-only phase deliberately performs no
+/// model work: main emits run_started from the restored configuration before
+/// optional cold-cache compaction begins. `root` is already stable
+/// main()-owned storage.
pub fn restoreResumedSession(arena: Allocator, out: *Io.Writer, root: *agent_mod.Agent, keys: *provider_mod.Keys, flags: args.Flags, json_mode: bool, cwd_display: []const u8) !void {
if (!(flags.oneshot_prompt == null and flags.resume_flag != null and !flags.new_session_flag and !flags.no_resume_flag)) return;
if (session.loadSession(root, keys, arena, root.session_name)) |_| {
@@ -288,18 +296,24 @@ pub fn restoreResumedSession(arena: Allocator, out: *Io.Writer, root: *agent_mod
try out.print("↩ resumed {s}{s} — {d} message(s) on {s} · /new or /clear for a fresh start\n", .{ root.session_name, session.session_ext, root.messages.items.len, root.provider.model });
try out.flush();
}
- // Cold cache: loadSession rebased the saved server-only token delta
- // onto today's complete local request estimate. Summarize up front
- // when that conservative meter crosses compactAt. Resume itself is
- // never permission to destructively trim on a transient/empty
- // summary; a concrete provider overflow can still override this.
- if (root.inputOverCompactThreshold()) {
- root.compactOrRecover(false);
- }
}
} else |_| {}
}
+/// Summarize a large restored context only after behavioral lifecycle start.
+/// This preprocessing is outside a root-turn scope, so its operational API
+/// trace is explicitly attributed to turn 0 rather than to a stale user turn.
+/// Cold cache: loadSession rebased the saved server-only token delta onto
+/// today's complete local request estimate; summarize up front when that
+/// conservative meter crosses compactAt. Resume itself is never permission to
+/// destructively trim on a transient/empty summary; a concrete provider
+/// overflow can still override this.
+pub fn compactResumedSession(root: *agent_mod.Agent) void {
+ if (root.inputOverCompactThreshold()) {
+ root.compactOrRecover(false);
+ }
+}
+
/// Final save-on-exit (also captures command-driven edits since the last
/// turn — /clear, /rewind — so the next start resumes the true end state)
/// + the worktree checkpoint commit for any edits an interrupted/aborted
diff --git a/src/session_start.zig b/src/session_start.zig
index 276ac698..4efbbe30 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -7,9 +7,10 @@
//! registry connect (consent prompt + companion auto-activation), and the
//! `graff repl`/one-shot-prompt early-exit paths.
//!
-//! Same dangling-pointer discipline as startup.zig: `openTraceFile`/
-//! `openTrajFile` return a plain (non-self-referential) File.Writer by
-//! value — main() assigns it to its OWN stable local, and only THEN takes
+//! Same dangling-pointer discipline as startup.zig: `openTraceFile`,
+//! `openBehaviorFile`, and `openTrajFile` return a plain
+//! (non-self-referential) File.Writer by value — main() assigns it to its OWN
+//! stable local, and only THEN takes
//! `&writer.interface` for Tracer/Trajectory's `.out` pointer, so nothing
//! points at a soon-to-be-freed stack frame. `runReplCommand`/
//! `runOneshotPrompt` take `root: *main_mod.Agent` — by this point in
@@ -165,8 +166,9 @@ pub fn setupWorktreeAndBanner(
}
}
-/// A best-effort run-local JSONL file: the opened file handle (null on a
-/// failed open — tracing/trajectory just stays off) plus the File.Writer. The caller
+/// A best-effort log-file result shared by operational traces, behavioral
+/// traces, and the legacy trajectory archive: the opened file handle (null on
+/// a failed open) plus the File.Writer wrapping it. The caller
/// owns `buf`'s storage (a stack array in main()) and must keep it alive as
/// long as the returned writer is used; the writer itself is safe to copy by
/// value (see startup.zig's header) since nothing takes `&writer.interface`
@@ -192,6 +194,111 @@ pub fn openTraceFile(io: Io, path: []const u8, buf: []u8) FileWriterOpen {
return openRunFile(io, trace.traces_dir, path, buf);
}
+fn validBehaviorDirComponent(component: []const u8) bool {
+ if (component.len == 0 or std.mem.eql(u8, component, ".") or std.mem.eql(u8, component, "..")) return false;
+ for (component) |c| {
+ if (!(std.ascii.isAlphanumeric(c) or c == '.' or c == '_' or c == '-')) return false;
+ }
+ return true;
+}
+
+/// Opens one exclusive behavioral trace file. Every directory component is
+/// created and reopened relative to a verified no-follow parent handle, so a
+/// workspace symlink cannot redirect plaintext traces outside `base`. The
+/// filename itself comes from a validated hex run ID. POSIX directories use
+/// 0700 and files request a maximum mode of 0600 because task adapters may
+/// deliberately record sensitive state.
+pub fn openBehaviorFile(io: Io, base: Io.Dir, dir: []const u8, run_id: []const u8, buf: []u8) FileWriterOpen {
+ if (run_id.len == 0 or run_id.len > 64) return .{ .file = null, .writer = undefined };
+ for (run_id) |c| if (!std.ascii.isHex(c)) return .{ .file = null, .writer = undefined };
+
+ const dir_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_dir else .fromMode(0o700);
+ var current = base;
+ var current_owned = false;
+ defer if (current_owned) current.close(io);
+ var components = std.mem.splitScalar(u8, dir, '/');
+ var saw_component = false;
+ while (components.next()) |component| {
+ if (!validBehaviorDirComponent(component)) return .{ .file = null, .writer = undefined };
+ saw_component = true;
+ current.createDir(io, component, dir_permissions) catch |err| switch (err) {
+ error.PathAlreadyExists => {},
+ else => return .{ .file = null, .writer = undefined },
+ };
+ const next = current.openDir(io, component, .{ .iterate = true, .follow_symlinks = false }) catch return .{ .file = null, .writer = undefined };
+ if (current_owned) current.close(io);
+ current = next;
+ current_owned = true;
+ }
+ if (!saw_component) return .{ .file = null, .writer = undefined };
+ if (builtin.os.tag != .windows) current.setPermissions(io, dir_permissions) catch return .{ .file = null, .writer = undefined };
+
+ var name_buf: [72]u8 = undefined;
+ const file_name = std.fmt.bufPrint(&name_buf, "{s}.jsonl", .{run_id}) catch return .{ .file = null, .writer = undefined };
+ const file_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_file else .fromMode(0o600);
+ const file: ?Io.File = current.createFile(io, file_name, .{
+ .exclusive = true,
+ .permissions = file_permissions,
+ }) catch null;
+ const writer = if (file) |f| f.writer(io, buf) else undefined;
+ return .{ .file = file, .writer = writer };
+}
+
+test "openBehaviorFile: confines names, creates exclusively, and uses private POSIX modes" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+
+ var first_buf: [256]u8 = undefined;
+ const first = openBehaviorFile(io, tmp.dir, "trajectories", "0123456789abcdef", &first_buf);
+ try std.testing.expect(first.file != null);
+ defer if (first.file) |file| file.close(io);
+
+ var duplicate_buf: [256]u8 = undefined;
+ const duplicate = openBehaviorFile(io, tmp.dir, "trajectories", "0123456789abcdef", &duplicate_buf);
+ try std.testing.expect(duplicate.file == null);
+
+ var invalid_buf: [256]u8 = undefined;
+ const invalid = openBehaviorFile(io, tmp.dir, "trajectories", "../escape", &invalid_buf);
+ try std.testing.expect(invalid.file == null);
+
+ if (builtin.os.tag != .windows) {
+ const dir_stat = try tmp.dir.statFile(io, "trajectories", .{});
+ const file_stat = try tmp.dir.statFile(io, "trajectories/0123456789abcdef.jsonl", .{});
+ try std.testing.expectEqual(@as(u32, 0o700), @as(u32, @intCast(dir_stat.permissions.toMode() & 0o777)));
+ const file_mode: u32 = @intCast(file_stat.permissions.toMode() & 0o777);
+ try std.testing.expectEqual(@as(u32, 0), file_mode & 0o177);
+ }
+}
+
+test "openBehaviorFile: rejects symlinked path components" {
+ if (builtin.os.tag == .windows) return;
+ const io = std.testing.io;
+
+ {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.createDir(io, "outside", .default_dir);
+ try tmp.dir.symLink(io, "outside", ".graff", .{ .is_directory = true });
+ var buf: [256]u8 = undefined;
+ const opened = openBehaviorFile(io, tmp.dir, ".graff/trajectories", "0123456789abcdef", &buf);
+ try std.testing.expect(opened.file == null);
+ }
+
+ {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.createDir(io, ".graff", .default_dir);
+ try tmp.dir.createDir(io, "outside", .default_dir);
+ const graff = try tmp.dir.openDir(io, ".graff", .{});
+ defer graff.close(io);
+ try graff.symLink(io, "../outside", "trajectories", .{ .is_directory = true });
+ var buf: [256]u8 = undefined;
+ const opened = openBehaviorFile(io, tmp.dir, ".graff/trajectories", "fedcba9876543210", &buf);
+ try std.testing.expect(opened.file == null);
+ }
+}
+
/// Opens `.graff/trajectories/<run-id>.jsonl` exclusively. The aggregate
/// archive is the directory, not a shared append cursor.
pub fn openTrajFile(io: Io, path: []const u8, buf: []u8) FileWriterOpen {
@@ -231,6 +338,7 @@ pub fn initTelemetry(io: Io, gpa: Allocator, client: *std.http.Client, environ_m
.gpa = gpa,
.client = client,
.endpoint = telem_endpoint,
+ .auth_key = telemetry.validatedAuthKey(environ_map.get("GRAFF_TELEMETRY_KEY")),
.install_id = if (telem_endpoint.len > 0) keys_cli.loadOrCreateId(io, gpa, telem_home, ".simple-harness-install-id") else @splat('0'),
.client_name = environ_map.get("HARNESS_CLIENT") orelse "harness",
.sdk_install_id = environ_map.get("HARNESS_SDK_INSTALL_ID") orelse "",
diff --git a/src/startup.zig b/src/startup.zig
index 21518721..ac16b2d0 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -375,6 +375,7 @@ pub fn buildSystemPrompt(
const args = @import("args.zig");
const mcp_cli = @import("mcp_cli.zig");
+const learn_cli = @import("learn_cli.zig");
const cli = @import("cli.zig");
const jobs = @import("jobs.zig");
const cube = @import("cube.zig");
@@ -414,6 +415,15 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
return true;
}
+ // `graff learn ...`: local immutable policy learning. It runs before key
+ // resolution and normal session construction; configured child tools get
+ // only their explicitly allowlisted environment.
+ if (flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "learn")) {
+ learn_cli.command(io, gpa, arena, init, flags.positionals.items[1..]) catch |err|
+ std.process.fatal("learn: {s}", .{@errorName(err)});
+ return true;
+ }
+
// `harness login [codex] [--refresh]`: OAuth login. Default target is
// codegraff (device-code flow, writes ~/.simple-harness-codegraff.json);
// `codex` (or --refresh) runs the ChatGPT PKCE/refresh flow → ~/.codex/auth.json.
diff --git a/src/telemetry.zig b/src/telemetry.zig
index 37aefde2..49ad095a 100644
--- a/src/telemetry.zig
+++ b/src/telemetry.zig
@@ -41,12 +41,36 @@ const harness_version = root.harness_version;
/// anonymous id (~/.simple-harness-install-id) identifies the install; SDKs
/// pass their own id via HARNESS_SDK_INSTALL_ID + HARNESS_CLIENT so SDK
/// users are counted separately. Flush failures never disturb the session.
+pub fn validatedAuthKey(value: ?[]const u8) ?[]const u8 {
+ const key = value orelse return null;
+ if (key.len == 0 or key.len > 1024) return null;
+ // Header values must not admit control/whitespace injection. Collector keys
+ // are intentionally a single visible token rather than generic OTLP header
+ // syntax, which also keeps secrets out of parsing diagnostics.
+ for (key) |byte| if (byte < 0x21 or byte > 0x7e) return null;
+ return key;
+}
+
+fn otlpLogsUrl(gpa: Allocator, endpoint: []const u8) !?[]u8 {
+ // Append the signal path to the URL path rather than to a query value. URL
+ // fragments are client-side only and must not be sent to the collector.
+ const fragment_at = std.mem.indexOfScalar(u8, endpoint, '#') orelse endpoint.len;
+ const without_fragment = endpoint[0..fragment_at];
+ const query_at = std.mem.indexOfScalar(u8, without_fragment, '?') orelse without_fragment.len;
+ const query = without_fragment[query_at..];
+ const base = std.mem.trimEnd(u8, without_fragment[0..query_at], "/");
+ if (base.len == 0) return null;
+ if (std.mem.endsWith(u8, base, "/v1/logs")) return try std.fmt.allocPrint(gpa, "{s}{s}", .{ base, query });
+ return try std.fmt.allocPrint(gpa, "{s}/v1/logs{s}", .{ base, query });
+}
+
pub const Telemetry = struct {
mutex: Io.Mutex = .init,
io: Io,
gpa: Allocator,
endpoint: []const u8, // base OTLP endpoint; "" → disabled
client: ?*std.http.Client = null, // shared http client, set by main()
+ auth_key: ?[]const u8 = null, // optional x-harness-key; never serialized
install_id: [32]u8, // anonymous hex id for this install
client_name: []const u8, // "harness", or "sdk-ts"/"sdk-py" via HARNESS_CLIENT
sdk_install_id: []const u8, // the SDK's own install id, if driving us
@@ -345,50 +369,58 @@ pub const Telemetry = struct {
}
/// Build an OTLP/HTTP JSON payload for `events` (plus the session
- /// summary when `include_summary`) and POST it to <endpoint>/v1/logs
- /// (per the OTLP env spec the endpoint is a base URL; it's used verbatim
- /// only when it already ends in /v1/logs). The POST races a 3s deadline
- /// so a dead or wedged collector can never hang the session.
+ /// summary when `include_summary`) and POST it to <endpoint>/v1/logs.
+ /// Per the OTLP env spec the endpoint is a base URL; an existing /v1/logs
+ /// path is retained, query parameters are preserved, and fragments are
+ /// dropped. The POST races a 3s deadline so a dead or wedged collector can
+ /// never hang the session.
/// Best-effort: any failure is swallowed.
pub fn sendBatch(self: *Telemetry, events: []const Event, include_summary: bool) void {
+ self.sendBatchWithDeadline(events, include_summary, .fromSeconds(3));
+ }
+
+ fn sendBatchWithDeadline(self: *Telemetry, events: []const Event, include_summary: bool, deadline: Io.Duration) void {
if (!self.on()) return;
const client = self.client orelse return;
if (events.len == 0 and !include_summary) return;
var aw: Io.Writer.Allocating = .init(self.gpa);
defer aw.deinit();
self.writeOtlp(&aw.writer, events, include_summary) catch return;
- var ubuf: [512]u8 = undefined;
- const trimmed = std.mem.trimEnd(u8, self.endpoint, "/");
- const url = if (std.mem.endsWith(u8, trimmed, "/v1/logs"))
- trimmed
- else
- std.fmt.bufPrint(&ubuf, "{s}/v1/logs", .{trimmed}) catch return;
-
- const Done = union(enum) { posted: void, deadline: void };
+ const url = (otlpLogsUrl(self.gpa, self.endpoint) catch return) orelse return;
+ defer self.gpa.free(url);
+
+ const Done = union(enum) { posted: bool, deadline: void };
var done_buf: [2]Done = undefined;
var sel: Io.Select(Done) = .init(self.io, &done_buf);
- sel.concurrent(.posted, postOtlp, .{ client, url, aw.writer.buffered() }) catch return;
- sel.concurrent(.deadline, flushDeadline, .{self.io}) catch {
- _ = sel.await() catch {}; // no spare concurrency: wait unbounded
+ // Arm the deadline before starting network I/O. If no concurrency slot
+ // remains for the POST, canceling this timer is bounded; starting the
+ // POST first could otherwise leave teardown waiting without a bound.
+ sel.concurrent(.deadline, flushDeadline, .{ self.io, deadline }) catch return;
+ sel.concurrent(.posted, postOtlp, .{ client, url, aw.writer.buffered(), self.auth_key orelse "" }) catch {
sel.cancelDiscard();
return;
};
- _ = sel.await() catch {}; // first of POST / deadline wins
- sel.cancelDiscard(); // cancel the loser (fetch's socket ops are cancelation points)
+ _ = sel.await() catch {};
+ sel.cancelDiscard(); // cancel and synchronously join the loser
}
- pub fn postOtlp(client: *std.http.Client, url: []const u8, payload: []const u8) void {
+ pub fn postOtlp(client: *std.http.Client, url: []const u8, payload: []const u8, auth_key: []const u8) bool {
http.waitForClientReady(client.io);
- _ = client.fetch(.{
+ const auth_header = [_]std.http.Header{.{ .name = "x-harness-key", .value = auth_key }};
+ const extra_headers: []const std.http.Header = if (auth_key.len > 0) &auth_header else &.{};
+ const response = client.fetch(.{
.location = .{ .url = url },
.method = .POST,
.payload = payload,
.headers = .{ .content_type = .{ .override = "application/json" } },
- }) catch {};
+ .extra_headers = extra_headers,
+ }) catch return false;
+ const status = @intFromEnum(response.status);
+ return status >= 200 and status < 300;
}
- pub fn flushDeadline(io: Io) void {
- io.sleep(.fromSeconds(3), .awake) catch {};
+ pub fn flushDeadline(io: Io, deadline: Io.Duration) void {
+ io.sleep(deadline, .awake) catch {};
}
const AttrVal = union(enum) { str: []const u8, int: i64, num: f64 };
@@ -559,9 +591,124 @@ pub const Telemetry = struct {
}
};
+fn stallTelemetryCollector(io: Io, server: *Io.net.Server, accepted: *std.atomic.Value(bool)) void {
+ const stream = server.accept(io) catch return;
+ defer stream.close(io);
+ accepted.store(true, .release);
+ io.sleep(.fromSeconds(5), .awake) catch {};
+}
+
+fn answerTelemetryCollector(
+ io: Io,
+ server: *Io.net.Server,
+ expected_key: []const u8,
+ saw_key: *std.atomic.Value(bool),
+) void {
+ const stream = server.accept(io) catch return;
+ defer stream.close(io);
+ var read_buf: [16 * 1024]u8 = undefined;
+ var reader = Io.net.Stream.Reader.init(stream, io, &read_buf);
+ while (reader.interface.takeDelimiter('\n') catch null) |line| {
+ if (std.mem.eql(u8, line, "\r") or line.len == 0) break;
+ const prefix = "x-harness-key:";
+ if (!std.ascii.startsWithIgnoreCase(line, prefix)) continue;
+ const value = std.mem.trim(u8, line[prefix.len..], " \t\r\n");
+ saw_key.store(std.mem.eql(u8, value, expected_key), .release);
+ }
+ const response = "HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
+ var write_buf: [256]u8 = undefined;
+ var writer = Io.net.Stream.Writer.init(stream, io, &write_buf);
+ writer.interface.writeAll(response) catch return;
+ writer.interface.flush() catch {};
+}
+
/// Set once in main() when telemetry is configured; Tracer and the workflow
/// runner feed it through this. Null → every hook is a no-op.
pub var g_telem: ?*Telemetry = null;
+
+test "telemetry collector key accepts one bounded visible token" {
+ try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey(null));
+ try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey(""));
+ try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey("secret key"));
+ try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey("secret\r\ninjected"));
+ try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey("nön-ascii"));
+ try std.testing.expectEqualStrings("safe-token_123", validatedAuthKey("safe-token_123").?);
+}
+
+test "OTLP URL derivation preserves queries and drops fragments" {
+ const gpa = std.testing.allocator;
+ const appended = (try otlpLogsUrl(gpa, "https://collector.example/base/?token=x#ignored")).?;
+ defer gpa.free(appended);
+ try std.testing.expectEqualStrings("https://collector.example/base/v1/logs?token=x", appended);
+
+ const exact = (try otlpLogsUrl(gpa, "https://collector.example/v1/logs/?token=x#ignored")).?;
+ defer gpa.free(exact);
+ try std.testing.expectEqualStrings("https://collector.example/v1/logs?token=x", exact);
+
+ var long_host: [600]u8 = undefined;
+ @memset(&long_host, 'a');
+ const long_endpoint = try std.fmt.allocPrint(gpa, "https://{s}.example?token=x", .{long_host});
+ defer gpa.free(long_endpoint);
+ const long_url = (try otlpLogsUrl(gpa, long_endpoint)).?;
+ defer gpa.free(long_url);
+ try std.testing.expect(long_url.len > 512);
+ try std.testing.expect(std.mem.endsWith(u8, long_url, ".example/v1/logs?token=x"));
+}
+
+test "OTLP POST sends the collector key" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var address = try Io.net.IpAddress.parseLiteral("127.0.0.1:0");
+ var server = try Io.net.IpAddress.listen(&address, io, .{});
+ defer server.deinit(io);
+ var saw_key: std.atomic.Value(bool) = .init(false);
+ var server_group: Io.Group = .init;
+ defer server_group.cancel(io);
+ try server_group.concurrent(io, answerTelemetryCollector, .{ io, &server, "collector-secret", &saw_key });
+
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var endpoint_buf: [64]u8 = undefined;
+ const endpoint = try std.fmt.bufPrint(&endpoint_buf, "http://127.0.0.1:{d}/v1/logs", .{server.socket.address.getPort()});
+ try std.testing.expect(Telemetry.postOtlp(&client, endpoint, "{}", "collector-secret"));
+ try std.testing.expect(saw_key.load(.acquire));
+}
+
+test "OTLP flush arms its deadline before network I/O" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var address = try Io.net.IpAddress.parseLiteral("127.0.0.1:0");
+ var server = try Io.net.IpAddress.listen(&address, io, .{});
+ defer server.deinit(io);
+ var accepted: std.atomic.Value(bool) = .init(false);
+ var server_group: Io.Group = .init;
+ defer server_group.cancel(io);
+ try server_group.concurrent(io, stallTelemetryCollector, .{ io, &server, &accepted });
+
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var endpoint_buf: [64]u8 = undefined;
+ const endpoint = try std.fmt.bufPrint(&endpoint_buf, "http://127.0.0.1:{d}", .{server.socket.address.getPort()});
+ var telemetry: Telemetry = .{
+ .io = io,
+ .gpa = gpa,
+ .endpoint = endpoint,
+ .client = &client,
+ .install_id = @splat('0'),
+ .client_name = "harness",
+ .sdk_install_id = "",
+ .start = Io.Timestamp.now(io, .awake),
+ .start_unix_ms = 0,
+ };
+ defer telemetry.deinit();
+ const started = Io.Timestamp.now(io, .awake).nanoseconds;
+ telemetry.sendBatchWithDeadline(&.{}, true, .fromMilliseconds(250));
+ const elapsed = Io.Timestamp.now(io, .awake).nanoseconds - started;
+ try std.testing.expect(accepted.load(.acquire));
+ try std.testing.expect(elapsed >= 100 * std.time.ns_per_ms);
+ try std.testing.expect(elapsed < 3 * std.time.ns_per_s);
+}
+
test "telemetry dupDetail never yields invalid UTF-8" {
var t: Telemetry = .{
.io = undefined, // dupDetail only touches gpa
diff --git a/src/trace.zig b/src/trace.zig
index 3ce35be5..9520a60b 100644
--- a/src/trace.zig
+++ b/src/trace.zig
@@ -1,8 +1,11 @@
-//! Session tracing + DGM trajectory archive. Every invocation writes its own
-//! `.graff/traces/<run-id>.jsonl` and `.graff/trajectories/<run-id>.jsonl`, so
-//! independent graff processes never truncate or seek/write through the same
-//! file. Every record is stamped with the run id, process id, and runtime
-//! session id before the event's own fields.
+//! Operational tracing, per-run behavioral traces, and the DGM trajectory
+//! archive. Every invocation writes its own `.graff/traces/<run-id>.jsonl`
+//! (performance telemetry) and `.graff/trajectories/<run-id>.jsonl` (DGM
+//! archive nodes plus the experimental behavioral lifecycle/belief stream),
+//! so independent graff processes never truncate or seek/write through the
+//! same file. Every record is stamped with the run id, process id, and
+//! runtime session id before the event's own fields. Also owns the per-agent
+//! ToolSink summary.
const std = @import("std");
const Io = std.Io;
@@ -11,6 +14,7 @@ const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const telemetry = @import("telemetry.zig");
+const behavior_upload = @import("behavior_upload.zig");
pub const traces_dir = ".graff/traces";
pub const trajectories_dir = ".graff/trajectories";
@@ -107,12 +111,20 @@ pub const Tracer = struct {
identity: Identity = .{},
path: []const u8 = "",
enabled: bool = true,
+ // Assigned once before the first root turn. Keeping this on the stable
+ // shared tracer avoids a process-global pointer race on worker callbacks.
+ behavior: ?*BehaviorTrace = null,
- pub fn api(self: *Tracer, label: []const u8, model: []const u8, ms: i64, req_bytes: usize, resp_bytes: usize, context_tokens: u64, cache_read: u64, is_error: bool) void {
+ pub fn api(self: *Tracer, label: []const u8, from_subagent: bool, model: []const u8, ms: i64, req_bytes: usize, resp_bytes: usize, context_tokens: u64, cache_read: u64, is_error: bool) void {
if (telemetry.g_telem) |t| t.countApi(model, is_error);
+ const behavior_turn = if (self.behavior) |behavior|
+ behavior.recordApiMetric(from_subagent, ms, req_bytes, resp_bytes, context_tokens, cache_read, is_error)
+ else
+ 0;
self.write(.{
.t = self.elapsedMs(),
.ev = "api",
+ .turn = behavior_turn,
.agent = label,
.model = model,
.ms = ms,
@@ -126,9 +138,14 @@ pub const Tracer = struct {
pub fn tool(self: *Tracer, name: []const u8, ms: i64, is_error: bool, result_bytes: usize, from_sub: bool) void {
if (telemetry.g_telem) |t| t.countTool(is_error);
+ const behavior_turn = if (self.behavior) |behavior|
+ behavior.recordToolMetric(name, from_sub, ms, result_bytes, is_error)
+ else
+ 0;
self.write(.{
.t = self.elapsedMs(),
.ev = "tool",
+ .turn = behavior_turn,
.name = name,
.ms = ms,
.result_bytes = result_bytes,
@@ -165,6 +182,331 @@ pub const Tracer = struct {
}
};
+// ── Behavioral trace (one experimental event file per run) ────────────────
+
+pub const behavior_dir = ".graff/trajectories";
+pub const behavior_schema = "codegraff.behavior.v1";
+
+/// Task-agnostic behavioral records. Per-kind fields stay flat, matching the
+/// schema-harness event shape; state/action/expect values remain opaque JSON.
+pub const BehaviorKind = enum {
+ run_started,
+ turn_started,
+ text_delta,
+ tool_started,
+ tool_finished,
+ turn_committed,
+ action_taken,
+ model_mispredicted,
+ run_finished,
+};
+
+/// Typed lifecycle status; `.failed` is serialized as the JSON value `error`.
+pub const BehaviorRunStatus = enum {
+ closed,
+ failed,
+};
+
+const max_local_behavior_event_bytes = 64 * 1024;
+
+/// Serialize a behavioral event as one flat JSON object. `fields` must be a
+/// struct; its fields are appended after the common envelope. Building the
+/// full line before writing prevents serialization failures from corrupting the
+/// file. The fixed 64 KiB line buffer also prevents an opaque adapter value from
+/// causing unbounded temporary allocation. A write failure disables the stream
+/// so a partial tail is never joined to a later event.
+fn writeBehaviorLine(gpa: Allocator, w: *Io.Writer, kind: BehaviorKind, seq: u64, ts: f64, run_id: []const u8, fields: anytype) bool {
+ const backing = gpa.alloc(u8, max_local_behavior_event_bytes + 1) catch return false;
+ defer gpa.free(backing);
+ var line: Io.Writer = .fixed(backing);
+ var s: std.json.Stringify = .{ .writer = &line };
+ s.beginObject() catch return false;
+ s.objectField("kind") catch return false;
+ s.write(@tagName(kind)) catch return false;
+ s.objectField("seq") catch return false;
+ s.write(seq) catch return false;
+ s.objectField("ts") catch return false;
+ s.write(ts) catch return false;
+ s.objectField("run_id") catch return false;
+ s.write(run_id) catch return false;
+ s.objectField("schema") catch return false;
+ s.write(behavior_schema) catch return false;
+ inline for (std.meta.fields(@TypeOf(fields))) |field| {
+ comptime {
+ if (std.mem.eql(u8, field.name, "kind") or
+ std.mem.eql(u8, field.name, "seq") or
+ std.mem.eql(u8, field.name, "ts") or
+ std.mem.eql(u8, field.name, "run_id") or
+ std.mem.eql(u8, field.name, "schema"))
+ {
+ @compileError("behavioral event field collides with the common envelope: " ++ field.name);
+ }
+ }
+ s.objectField(field.name) catch return false;
+ s.write(@field(fields, field.name)) catch return false;
+ }
+ s.endObject() catch return false;
+ if (line.buffered().len > max_local_behavior_event_bytes) return false;
+ line.writeByte('\n') catch return false;
+ w.writeAll(line.buffered()) catch return false;
+ w.flush() catch return false;
+ return true;
+}
+
+/// Per-run behavioral event stream written to
+/// `.graff/trajectories/<run_id>.jsonl`. `seq` is contiguous file order for
+/// this run and starts at one. `ts` is Unix time in fractional seconds. Every
+/// event carries `run_id` and `schema`, so it remains attributable even if run
+/// files are later merged. Payload fields are plaintext and are not sanitized;
+/// callers must explicitly avoid secrets and proprietary content.
+fn commitmentRef(key: *const [32]u8, commitment_id: []const u8) [16]u8 {
+ // The random key never leaves this process, so low-entropy adapter IDs
+ // cannot be recovered from uploaded references with an offline dictionary.
+ var hash = std.crypto.hash.sha2.Sha256.init(.{});
+ hash.update(key);
+ hash.update(&.{0});
+ hash.update(commitment_id);
+ var digest: [32]u8 = undefined;
+ hash.final(&digest);
+ return std.fmt.bytesToHex(digest[0..8].*, .lower);
+}
+
+pub const BehaviorRunMetadata = struct {
+ provider: []const u8 = "",
+ model: []const u8 = "",
+ prompt_sha: []const u8 = "",
+ effort: []const u8 = "",
+};
+
+pub const BehaviorTrace = struct {
+ mutex: Io.Mutex = .init,
+ io: Io,
+ gpa: Allocator,
+ out: ?*Io.Writer,
+ upload: ?*behavior_upload.Upload = null,
+ run_id: []const u8,
+ seq: u64 = 0,
+ current_turn: u64 = 0,
+ turn_active: bool = false,
+ started: bool = false,
+ closed: bool = false,
+ commitment_key: [32]u8 = undefined,
+ commitment_key_initialized: bool = false,
+
+ fn timestamp(self: *BehaviorTrace) f64 {
+ const now = Io.Timestamp.now(self.io, .real);
+ return @as(f64, @floatFromInt(now.nanoseconds)) / 1_000_000_000.0;
+ }
+
+ /// Emit to the independent local and upload sinks. The return value says
+ /// whether the upload retained this event; callers otherwise do not couple
+ /// sink health. In particular, finish() uses it so `complete=true` cannot
+ /// describe a batch whose terminal event was dropped during admission.
+ fn eventLocked(self: *BehaviorTrace, kind: BehaviorKind, local_fields: anytype, metadata_fields: anytype, content_fields: anytype) bool {
+ if (self.closed or self.seq == std.math.maxInt(u64)) return false;
+ const uploader_active = if (self.upload) |uploader| uploader.active() else false;
+ if (self.out == null and !uploader_active) return false;
+
+ // This is the logical source sequence, reserved before either
+ // independent sink is attempted. A bounded upload may therefore have
+ // gaps, reported by dropped_events, while the local file remains a
+ // contiguous prefix until any terminal write failure.
+ const next = self.seq + 1;
+ self.seq = next;
+ const ts = self.timestamp();
+ if (self.out) |w| {
+ if (!writeBehaviorLine(self.gpa, w, kind, next, ts, self.run_id, local_fields)) {
+ // Do not append after a possible partial write. Upload remains
+ // independent so a local disk failure need not erase metadata.
+ self.out = null;
+ }
+ }
+ if (self.upload) |uploader| {
+ return uploader.appendEvent(@tagName(kind), next, ts, metadata_fields, content_fields);
+ }
+ return false;
+ }
+
+ /// Start this run exactly once. The generic serializer stays private so
+ /// callers cannot accidentally emit a kind without its required fields.
+ pub fn start(self: *BehaviorTrace, version: []const u8, unix_ms: i64) void {
+ self.startWithMetadata(version, unix_ms, .{});
+ }
+
+ pub fn startWithMetadata(self: *BehaviorTrace, version: []const u8, unix_ms: i64, metadata: BehaviorRunMetadata) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (self.started or self.closed) return;
+ self.io.randomSecure(&self.commitment_key) catch self.io.random(&self.commitment_key);
+ self.commitment_key_initialized = true;
+ self.started = true;
+ const local_fields = .{
+ .version = version,
+ .unix_ms = unix_ms,
+ .provider = metadata.provider,
+ .model = metadata.model,
+ .prompt_sha = metadata.prompt_sha,
+ .effort = metadata.effort,
+ };
+ // A deterministic prompt fingerprint is useful in the local trace but
+ // remains prompt-derived data: even a truncated digest can disclose a
+ // low-entropy prompt through enumeration. Never include it in either
+ // network projection.
+ const upload_fields = .{
+ .version = version,
+ .unix_ms = unix_ms,
+ .provider = metadata.provider,
+ .model = metadata.model,
+ .effort = metadata.effort,
+ };
+ _ = self.eventLocked(.run_started, local_fields, upload_fields, upload_fields);
+ }
+
+ /// Begin one root turn. Behavioral turn IDs are dense and independent of
+ /// legacy trajectory node IDs, which can skip as child agents are added.
+ pub fn beginTurn(self: *BehaviorTrace, trajectory_node: u64) u64 {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (!self.started or self.closed or self.current_turn == std.math.maxInt(u64)) return 0;
+ const parent_turn = self.current_turn;
+ const turn = parent_turn + 1;
+ self.current_turn = turn;
+ self.turn_active = true;
+ const fields = .{
+ .turn = turn,
+ .parent_turn = parent_turn,
+ .trajectory_node = trajectory_node,
+ };
+ _ = self.eventLocked(.turn_started, fields, fields, fields);
+ return turn;
+ }
+
+ /// Clear attribution only for the matching active turn. The last turn ID is
+ /// retained separately in current_turn so the next turn keeps a dense parent
+ /// chain, while late administrative API/tool work is attributed to turn 0.
+ pub fn endTurn(self: *BehaviorTrace, turn: u64) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (turn != 0 and self.turn_active and turn == self.current_turn) self.turn_active = false;
+ }
+
+ pub fn currentTurn(self: *BehaviorTrace) u64 {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ return if (self.turn_active) self.current_turn else 0;
+ }
+
+ /// Assert that a task adapter observed a committed action and expectation.
+ /// This records the caller's belief; it does not execute or verify the action.
+ pub fn recordExpectedAction(self: *BehaviorTrace, turn: u64, commitment_id: []const u8, action: anytype, expected: anytype, reason: []const u8) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (!self.started or self.closed or !self.turn_active or turn == 0 or turn != self.current_turn or commitment_id.len == 0) return;
+ const local_fields = .{
+ .turn = turn,
+ .commitment_id = commitment_id,
+ .action = action,
+ .expect = expected,
+ .reason = reason,
+ };
+ std.debug.assert(self.commitment_key_initialized);
+ const commitment_ref = commitmentRef(&self.commitment_key, commitment_id);
+ _ = self.eventLocked(.turn_committed, local_fields, .{
+ .turn = turn,
+ .commitment_ref = &commitment_ref,
+ }, local_fields);
+ }
+
+ /// Assert that a caller or task-specific verifier found a contradiction.
+ /// No generic semantic comparison is attempted by this backend.
+ pub fn recordMisprediction(self: *BehaviorTrace, turn: u64, commitment_id: []const u8, predicted: anytype, actual: anytype, detail: []const u8) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (!self.started or self.closed or !self.turn_active or turn == 0 or turn != self.current_turn or commitment_id.len == 0) return;
+ const local_fields = .{
+ .turn = turn,
+ .commitment_id = commitment_id,
+ .predicted = predicted,
+ .actual = actual,
+ .detail = detail,
+ };
+ std.debug.assert(self.commitment_key_initialized);
+ const commitment_ref = commitmentRef(&self.commitment_key, commitment_id);
+ _ = self.eventLocked(.model_mispredicted, local_fields, .{
+ .turn = turn,
+ .commitment_ref = &commitment_ref,
+ }, local_fields);
+ }
+
+ /// Attach content-free operational aggregates to the active root turn.
+ /// These are not behavioral tool events: no invocation identity, argument,
+ /// result, or action semantics are inferred from the operational hook.
+ pub fn recordApiMetric(
+ self: *BehaviorTrace,
+ from_subagent: bool,
+ ms: i64,
+ req_bytes: usize,
+ resp_bytes: usize,
+ context_tokens: u64,
+ cache_read_tokens: u64,
+ is_error: bool,
+ ) u64 {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (!self.started or self.closed or !self.turn_active) return 0;
+ const turn = self.current_turn;
+ if (self.upload) |uploader| uploader.recordApi(turn, from_subagent, ms, req_bytes, resp_bytes, context_tokens, cache_read_tokens, is_error);
+ return turn;
+ }
+
+ pub fn recordToolMetric(self: *BehaviorTrace, name: []const u8, from_subagent: bool, ms: i64, result_bytes: usize, is_error: bool) u64 {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (!self.started or self.closed or !self.turn_active) return 0;
+ const turn = self.current_turn;
+ if (self.upload) |uploader| uploader.recordTool(turn, name, from_subagent, ms, result_bytes, is_error);
+ return turn;
+ }
+
+ const FinishState = struct {
+ uploader: ?*behavior_upload.Upload,
+ complete: bool,
+ };
+
+ fn prepareFinish(self: *BehaviorTrace, status_name: []const u8) ?FinishState {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (self.closed) return null;
+
+ var terminal_retained = false;
+ if (self.started) {
+ const fields = .{ .status = status_name };
+ terminal_retained = self.eventLocked(.run_finished, fields, fields, fields);
+ }
+ self.turn_active = false;
+ self.closed = true;
+ return .{
+ .uploader = self.upload,
+ // This flag describes the uploaded lifecycle, not merely process
+ // control flow. A dropped terminal event must remain incomplete.
+ .complete = self.started and (self.upload == null or terminal_retained),
+ };
+ }
+
+ /// Mark a normal process/session close. This is deliberately not a task
+ /// success verdict. A missing run_finished record means the run is incomplete.
+ pub fn finish(self: *BehaviorTrace, status: BehaviorRunStatus) void {
+ const status_name: []const u8 = switch (status) {
+ .closed => "closed",
+ .failed => "error",
+ };
+ const state = self.prepareFinish(status_name) orelse return;
+ // Network I/O is terminal and bounded, but it must not hold the mutex
+ // used by concurrent API/tool callbacks.
+ if (state.uploader) |uploader| uploader.send(state.complete, status_name);
+ }
+};
+
// ── Trajectory (DGM-style archive tree) ────────────────────────────────────
/// Session trajectory in the shape of the Darwin Gödel Machine's archive
@@ -294,6 +636,22 @@ pub fn readTrajectoryArchive(io: Io, arena: Allocator, max_bytes: usize) []const
return aw.toOwnedSlice() catch "";
}
+/// Begin one behavioral root turn at the common provider boundary, before any
+/// model or tool work. Interactive mode may already have reserved a legacy DGM
+/// node; one-shot and zigzag REPL modes deliberately leave that ledger unchanged.
+pub fn beginRootTurn(tracer: ?*Tracer) u64 {
+ const trajectory_node = if (g_traj) |tj| tj.currentTurn() else 0;
+ const behavior = if (tracer) |tr| tr.behavior else null;
+ return if (behavior) |bt| bt.beginTurn(trajectory_node) else 0;
+}
+
+/// End only the matching root-turn scope. Keeping this at the same provider
+/// boundary prevents later administrative requests from inheriting its ID.
+pub fn endRootTurn(tracer: ?*Tracer, turn: u64) void {
+ const behavior = if (tracer) |tr| tr.behavior else null;
+ if (behavior) |bt| bt.endTurn(turn);
+}
+
/// Per-agent record of external tool calls (name + error flag, in call
/// order): the process signal behind "which tool combinations work" —
/// rendered into trajectory nodes and OTLP run events, joinable to scores
@@ -344,6 +702,12 @@ pub const ToolSink = struct {
self.entries.deinit(gpa);
}
};
+
+fn expectObjectKeys(object: std.json.ObjectMap, expected: []const []const u8) !void {
+ try std.testing.expectEqual(expected.len, object.count());
+ for (expected) |key| try std.testing.expect(object.get(key) != null);
+}
+
test "writeJsonLine: one complete newline-terminated JSON record per call" {
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
@@ -387,3 +751,483 @@ test "run-scoped paths separate traces and trajectories" {
try std.testing.expectEqualStrings(".graff/traces/abc123.jsonl", trace_path);
try std.testing.expectEqualStrings(".graff/trajectories/abc123.jsonl", trajectory_path);
}
+
+test "writeBehaviorLine: oversized adapter content is rejected before local allocation can grow" {
+ const gpa = std.testing.allocator;
+ var out: Io.Writer.Allocating = .init(gpa);
+ defer out.deinit();
+ const oversized = try gpa.alloc(u8, max_local_behavior_event_bytes + 1);
+ defer gpa.free(oversized);
+ @memset(oversized, 'x');
+ try std.testing.expect(!writeBehaviorLine(gpa, &out.writer, .turn_committed, 1, 1.0, "0123456789abcdef", .{
+ .turn = @as(u64, 1),
+ .reason = oversized,
+ }));
+ try std.testing.expectEqual(@as(usize, 0), out.writer.buffered().len);
+}
+
+test "BehaviorTrace: events are flat, attributable, and ordered" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = &aw.writer,
+ .run_id = "run-test-1",
+ };
+
+ behavior.start("test", 1_234);
+ behavior.start("ignored-duplicate", 9_999);
+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(7));
+ behavior.recordExpectedAction(
+ 1,
+ "commit-1",
+ .{ .tool = "edit_file", .note = "line one\nline two ☃" },
+ .{ .build = "passes", .attempts = @as(u64, 1) },
+ "verify the edit compiles",
+ );
+ behavior.recordMisprediction(
+ 1,
+ "commit-1",
+ .{ .build = "passes" },
+ .{ .build = "fails", .exit_code = @as(i64, 1) },
+ "reported by a task-specific verifier",
+ );
+ behavior.finish(.closed);
+ // Typed lifecycle methods cannot append after closure.
+ behavior.recordExpectedAction(1, "late", .{ .tool = "bash" }, .{ .ok = true }, "too late");
+
+ const out = aw.writer.buffered();
+ try std.testing.expectEqual(@as(usize, 5), std.mem.count(u8, out, "\n"));
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, out, "\n"), '\n');
+
+ var started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer started.deinit();
+ try std.testing.expectEqualStrings("run_started", started.value.object.get("kind").?.string);
+ try std.testing.expectEqual(@as(i64, 1), started.value.object.get("seq").?.integer);
+ try std.testing.expect(started.value.object.get("ts").? == .float);
+ try std.testing.expectEqualStrings("run-test-1", started.value.object.get("run_id").?.string);
+ try std.testing.expectEqualStrings(behavior_schema, started.value.object.get("schema").?.string);
+ try std.testing.expectEqualStrings("test", started.value.object.get("version").?.string);
+ try std.testing.expectEqual(@as(i64, 1_234), started.value.object.get("unix_ms").?.integer);
+ try std.testing.expect(started.value.object.get("payload") == null);
+
+ var turn = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer turn.deinit();
+ try std.testing.expectEqualStrings("turn_started", turn.value.object.get("kind").?.string);
+ try std.testing.expectEqual(@as(i64, 2), turn.value.object.get("seq").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), turn.value.object.get("turn").?.integer);
+ try std.testing.expectEqual(@as(i64, 0), turn.value.object.get("parent_turn").?.integer);
+ try std.testing.expectEqual(@as(i64, 7), turn.value.object.get("trajectory_node").?.integer);
+ try std.testing.expectEqualStrings("run-test-1", turn.value.object.get("run_id").?.string);
+
+ var committed = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer committed.deinit();
+ try std.testing.expectEqualStrings("turn_committed", committed.value.object.get("kind").?.string);
+ try std.testing.expectEqual(@as(i64, 3), committed.value.object.get("seq").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), committed.value.object.get("turn").?.integer);
+ try std.testing.expectEqualStrings("commit-1", committed.value.object.get("commitment_id").?.string);
+ try std.testing.expectEqualStrings("line one\nline two ☃", committed.value.object.get("action").?.object.get("note").?.string);
+ try std.testing.expectEqualStrings("passes", committed.value.object.get("expect").?.object.get("build").?.string);
+ try std.testing.expectEqualStrings("verify the edit compiles", committed.value.object.get("reason").?.string);
+
+ var mismatch = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer mismatch.deinit();
+ try std.testing.expectEqualStrings("model_mispredicted", mismatch.value.object.get("kind").?.string);
+ try std.testing.expectEqual(@as(i64, 4), mismatch.value.object.get("seq").?.integer);
+ try std.testing.expectEqualStrings("commit-1", mismatch.value.object.get("commitment_id").?.string);
+ try std.testing.expectEqualStrings("fails", mismatch.value.object.get("actual").?.object.get("build").?.string);
+ try std.testing.expectEqualStrings("reported by a task-specific verifier", mismatch.value.object.get("detail").?.string);
+
+ var finished = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer finished.deinit();
+ try std.testing.expectEqualStrings("run_finished", finished.value.object.get("kind").?.string);
+ try std.testing.expectEqual(@as(i64, 5), finished.value.object.get("seq").?.integer);
+ try std.testing.expectEqualStrings("closed", finished.value.object.get("status").?.string);
+ try std.testing.expectEqualStrings("run-test-1", finished.value.object.get("run_id").?.string);
+ try std.testing.expect(lines.next() == null);
+}
+
+test "BehaviorTrace: disabled writes do not consume sequence numbers" {
+ const io = std.testing.io;
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = std.testing.allocator,
+ .out = null,
+ .run_id = "disabled-run",
+ };
+
+ behavior.start("test", 0);
+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));
+ try std.testing.expectEqual(@as(u64, 0), behavior.seq);
+ try std.testing.expectEqual(@as(u64, 1), behavior.currentTurn());
+}
+
+test "BehaviorTrace: typed APIs reject out-of-lifecycle adapter events" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = &aw.writer,
+ .run_id = "lifecycle-run",
+ };
+
+ try std.testing.expectEqual(@as(u64, 0), behavior.beginTurn(9));
+ behavior.recordExpectedAction(1, "early", .{ .kind = "edit" }, .{ .ok = true }, "before start");
+ behavior.start("test", 1);
+ behavior.recordExpectedAction(1, "early", .{ .kind = "edit" }, .{ .ok = true }, "before turn");
+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(9));
+ behavior.recordExpectedAction(0, "zero-turn", .{ .kind = "edit" }, .{ .ok = true }, "invalid turn");
+ behavior.recordExpectedAction(2, "future-turn", .{ .kind = "edit" }, .{ .ok = true }, "invalid turn");
+ behavior.recordExpectedAction(1, "", .{ .kind = "edit" }, .{ .ok = true }, "empty commitment");
+ behavior.recordMisprediction(1, "", .{ .ok = true }, .{ .ok = false }, "empty commitment");
+
+ try std.testing.expectEqual(@as(u64, 2), behavior.seq);
+ try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, aw.writer.buffered(), "\n"));
+ behavior.finish(.failed);
+ behavior.finish(.closed); // the first terminal status wins
+ try std.testing.expectEqual(@as(u64, 3), behavior.seq);
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');
+ _ = lines.next();
+ _ = lines.next();
+ var finished = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer finished.deinit();
+ try std.testing.expectEqualStrings("error", finished.value.object.get("status").?.string);
+}
+
+test "BehaviorTrace: a full upload queue cannot claim a complete terminal lifecycle" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var upload: behavior_upload.Upload = .{
+ .io = io,
+ .gpa = gpa,
+ .client = null,
+ .endpoint = "https://collector.example/v1/logs",
+ .install_id = @splat('q'),
+ .client_name = "harness",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = .metadata,
+ };
+ defer upload.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .upload = &upload,
+ .run_id = "0123456789abcdef",
+ };
+
+ behavior.start("test", 1);
+ try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
+ const placeholder = upload.events.items[0][0..0];
+ try upload.events.resize(gpa, behavior_upload.max_events);
+ for (upload.events.items[1..]) |*event| event.* = placeholder;
+
+ const state = behavior.prepareFinish("closed").?;
+ try std.testing.expect(!state.complete);
+ try std.testing.expectEqual(@as(u64, 1), upload.dropped_events);
+ try std.testing.expectEqual(@as(usize, behavior_upload.max_events), upload.events.items.len);
+
+ // Remove synthetic queue entries before normal deinit and payload parsing.
+ upload.events.shrinkRetainingCapacity(1);
+ const payload = try upload.buildPayload(state.complete, "closed");
+ defer gpa.free(payload);
+ var parsed = try std.json.parseFromSlice(Value, gpa, payload, .{});
+ defer parsed.deinit();
+ try std.testing.expect(!parsed.value.object.get("complete").?.bool);
+ try std.testing.expectEqual(@as(usize, 1), parsed.value.object.get("events").?.array.items.len);
+}
+
+test "BehaviorTrace: terminal allocation failure leaves upload incomplete" {
+ const backing_gpa = std.testing.allocator;
+ const io = std.testing.io;
+ // run_started uses one allocation for its event and one for ArrayList
+ // storage. Fail the next allocation, which is run_finished serialization.
+ var failing = std.testing.FailingAllocator.init(backing_gpa, .{ .fail_index = 2 });
+ const failing_gpa = failing.allocator();
+ var upload: behavior_upload.Upload = .{
+ .io = io,
+ .gpa = failing_gpa,
+ .client = null,
+ .endpoint = "https://collector.example/v1/logs",
+ .install_id = @splat('a'),
+ .client_name = "harness",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = .metadata,
+ };
+ defer upload.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = backing_gpa,
+ .out = null,
+ .upload = &upload,
+ .run_id = "0123456789abcdef",
+ };
+
+ behavior.start("test", 1);
+ try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
+ const state = behavior.prepareFinish("error").?;
+ try std.testing.expect(failing.has_induced_failure);
+ try std.testing.expect(!state.complete);
+ try std.testing.expectEqual(@as(u64, 1), upload.dropped_events);
+ try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
+
+ failing.fail_index = std.math.maxInt(usize);
+ const payload = try upload.buildPayload(state.complete, "error");
+ defer failing_gpa.free(payload);
+ var parsed = try std.json.parseFromSlice(Value, backing_gpa, payload, .{});
+ defer parsed.deinit();
+ try std.testing.expect(!parsed.value.object.get("complete").?.bool);
+}
+
+test "BehaviorTrace: metadata-default upload is an exact content-free projection" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var local: Io.Writer.Allocating = .init(gpa);
+ defer local.deinit();
+ var upload: behavior_upload.Upload = .{
+ .io = io,
+ .gpa = gpa,
+ .client = null,
+ .endpoint = "https://collector.example/v1/logs",
+ .install_id = @splat('c'),
+ .client_name = "test",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = behavior_upload.resolveMode(null, true),
+ };
+ defer upload.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = &local.writer,
+ .upload = &upload,
+ .run_id = "0123456789abcdef",
+ };
+ behavior.startWithMetadata("test", 1_234, .{
+ .provider = "anthropic",
+ .model = "test-model",
+ .prompt_sha = "0011223344556677",
+ .effort = "high",
+ });
+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(7));
+ behavior.recordExpectedAction(
+ 1,
+ "COMMITMENT_SECRET",
+ .{ .source = "SOURCE_SECRET", .tool_args = "TOOL_ARGUMENT_SECRET" },
+ .{ .tool_result = "TOOL_RESULT_SECRET" },
+ "REASON_SECRET",
+ );
+ behavior.recordMisprediction(
+ 1,
+ "COMMITMENT_SECRET",
+ .{ .model_output = "MODEL_OUTPUT_SECRET" },
+ .{ .workspace_path = "PRIVATE_PATH_SECRET" },
+ "DETAIL_SECRET",
+ );
+ var tracer: Tracer = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .start = Io.Timestamp.now(io, .awake),
+ .behavior = &behavior,
+ };
+ tracer.api("repl", false, "test-model", 20, 100, 200, 300, 250, false);
+ tracer.tool("mcp__private_server__lookup_customer", 7, true, 80, true);
+ behavior.finish(.closed);
+ behavior.finish(.failed);
+ // Late callbacks may race terminal teardown. They must observe closure and
+ // leave the uploader untouched after send can begin.
+ try std.testing.expectEqual(@as(u64, 0), behavior.recordApiMetric(false, 99, 999, 999, 999, 999, true));
+ try std.testing.expectEqual(@as(u64, 0), behavior.recordToolMetric("bash", false, 99, 999, true));
+
+ const secrets = [_][]const u8{
+ "COMMITMENT_SECRET",
+ "SOURCE_SECRET",
+ "TOOL_ARGUMENT_SECRET",
+ "TOOL_RESULT_SECRET",
+ "REASON_SECRET",
+ "MODEL_OUTPUT_SECRET",
+ "PRIVATE_PATH_SECRET",
+ "DETAIL_SECRET",
+ "0011223344556677",
+ "private_server",
+ "lookup_customer",
+ };
+ const local_jsonl = local.writer.buffered();
+ for (secrets[0..9]) |secret| try std.testing.expect(std.mem.indexOf(u8, local_jsonl, secret) != null);
+
+ const payload = try upload.buildPayload(true, "closed");
+ defer gpa.free(payload);
+ for (&secrets) |secret| try std.testing.expect(std.mem.indexOf(u8, payload, secret) == null);
+ var parsed = try std.json.parseFromSlice(Value, gpa, payload, .{});
+ defer parsed.deinit();
+ const batch = parsed.value.object;
+ try expectObjectKeys(batch, &.{
+ "schema",
+ "event_schema",
+ "privacy",
+ "run_id",
+ "install_id",
+ "client_name",
+ "service_version",
+ "complete",
+ "terminal_status",
+ "dropped_events",
+ "dropped_metrics",
+ "events",
+ "turn_metrics",
+ });
+ try std.testing.expectEqualStrings("metadata", batch.get("privacy").?.string);
+ const events = batch.get("events").?.array.items;
+ try std.testing.expectEqual(@as(usize, 5), events.len);
+ try expectObjectKeys(events[0].object, &.{ "kind", "seq", "ts", "run_id", "schema", "version", "unix_ms", "provider", "model", "effort" });
+ try expectObjectKeys(events[1].object, &.{ "kind", "seq", "ts", "run_id", "schema", "turn", "parent_turn", "trajectory_node" });
+ try expectObjectKeys(events[2].object, &.{ "kind", "seq", "ts", "run_id", "schema", "turn", "commitment_ref" });
+ try expectObjectKeys(events[3].object, &.{ "kind", "seq", "ts", "run_id", "schema", "turn", "commitment_ref" });
+ try expectObjectKeys(events[4].object, &.{ "kind", "seq", "ts", "run_id", "schema", "status" });
+ try std.testing.expectEqualStrings(events[2].object.get("commitment_ref").?.string, events[3].object.get("commitment_ref").?.string);
+
+ const metrics = batch.get("turn_metrics").?.array.items;
+ try std.testing.expectEqual(@as(usize, 1), metrics.len);
+ try std.testing.expectEqual(@as(i64, 0), metrics[0].object.get("api_subagent_calls").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), metrics[0].object.get("tool_subagent_calls").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), metrics[0].object.get("tool_mcp").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), metrics[0].object.get("tool_errors").?.integer);
+}
+
+test "BehaviorTrace: prompt fingerprint stays local in content mode" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var local: Io.Writer.Allocating = .init(gpa);
+ defer local.deinit();
+ var upload: behavior_upload.Upload = .{
+ .io = io,
+ .gpa = gpa,
+ .client = null,
+ .endpoint = "https://collector.example/v1/logs",
+ .install_id = @splat('c'),
+ .client_name = "harness",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = .content,
+ };
+ defer upload.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = &local.writer,
+ .upload = &upload,
+ .run_id = "0123456789abcdef",
+ };
+ behavior.startWithMetadata("test", 1, .{ .prompt_sha = "0011223344556677" });
+ try std.testing.expect(std.mem.indexOf(u8, local.writer.buffered(), "0011223344556677") != null);
+ try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
+ try std.testing.expect(std.mem.indexOf(u8, upload.events.items[0], "0011223344556677") == null);
+ try std.testing.expect(std.mem.indexOf(u8, upload.events.items[0], "prompt_sha") == null);
+}
+
+test "beginRootTurn: correlates without allocating a legacy node" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = &aw.writer,
+ .run_id = "root-turn-run",
+ };
+ var trajectory: Trajectory = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .start = Io.Timestamp.now(io, .awake),
+ };
+ defer trajectory.deinit();
+
+ behavior.start("test", 1);
+ const trajectory_node = trajectory.nextId();
+ trajectory.setTurn(trajectory_node);
+ const legacy_next_id = trajectory.next_id;
+ var tracer: Tracer = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .start = Io.Timestamp.now(io, .awake),
+ .behavior = &behavior,
+ };
+ const previous_trajectory = g_traj;
+ g_traj = &trajectory;
+ defer g_traj = previous_trajectory;
+
+ try std.testing.expectEqual(@as(u64, 1), beginRootTurn(&tracer));
+ try std.testing.expectEqual(legacy_next_id, trajectory.next_id);
+ try std.testing.expectEqual(trajectory_node, trajectory.currentTurn());
+
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');
+ _ = lines.next(); // run_started
+ var turn = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer turn.deinit();
+ try std.testing.expectEqual(@as(i64, 1), turn.value.object.get("turn").?.integer);
+ try std.testing.expectEqual(@as(i64, @intCast(trajectory_node)), turn.value.object.get("trajectory_node").?.integer);
+}
+
+test "endRootTurn: clears attribution while preserving the dense parent chain" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = &aw.writer,
+ .run_id = "root-scope-run",
+ };
+ var tracer: Tracer = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .start = Io.Timestamp.now(io, .awake),
+ .behavior = &behavior,
+ };
+ const previous_trajectory = g_traj;
+ g_traj = null;
+ defer g_traj = previous_trajectory;
+
+ behavior.start("test", 1);
+ const first = beginRootTurn(&tracer);
+ try std.testing.expectEqual(@as(u64, 1), first);
+ try std.testing.expectEqual(first, behavior.recordApiMetric(false, 1, 1, 1, 1, 1, false));
+ try std.testing.expectEqual(first, behavior.recordToolMetric("bash", false, 1, 1, false));
+
+ endRootTurn(&tracer, first);
+ try std.testing.expectEqual(@as(u64, 0), behavior.currentTurn());
+ try std.testing.expectEqual(@as(u64, 0), behavior.recordApiMetric(false, 1, 1, 1, 1, 1, false));
+ try std.testing.expectEqual(@as(u64, 0), behavior.recordToolMetric("bash", false, 1, 1, false));
+ behavior.recordExpectedAction(first, "late", .{ .tool = "bash" }, .{ .ok = true }, "outside the root turn");
+
+ const second = beginRootTurn(&tracer);
+ try std.testing.expectEqual(@as(u64, 2), second);
+ endRootTurn(&tracer, first); // a stale scope cannot clear the new turn
+ try std.testing.expectEqual(second, behavior.currentTurn());
+ endRootTurn(&tracer, second);
+ try std.testing.expectEqual(@as(u64, 0), behavior.currentTurn());
+ try std.testing.expectEqual(@as(u64, 3), behavior.seq);
+
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');
+ _ = lines.next(); // run_started
+ _ = lines.next(); // first turn_started
+ var second_started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer second_started.deinit();
+ try std.testing.expectEqual(@as(i64, 2), second_started.value.object.get("turn").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), second_started.value.object.get("parent_turn").?.integer);
+ try std.testing.expect(lines.next() == null);
+}
diff --git a/tests/learn_e2e.py b/tests/learn_e2e.py
new file mode 100644
index 00000000..2b5b95eb
--- /dev/null
+++ b/tests/learn_e2e.py
@@ -0,0 +1,303 @@
+#!/usr/bin/env python3
+"""Local-only end-to-end regression test for `graff learn`.
+
+Build first, then run:
+ python3 tests/learn_e2e.py --graff zig-out/bin/graff
+
+The fixture uses deterministic local mutator/evaluator programs and disables
+telemetry. It never contacts a network service.
+"""
+
+from __future__ import annotations
+
+import argparse
+import copy
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+from typing import Any
+
+
+def raw_sha256(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def addressed_id(domain: str, data: bytes) -> str:
+ digest = hashlib.sha256()
+ digest.update(domain.encode("utf-8"))
+ digest.update(b"\0")
+ digest.update(struct.pack(">Q", len(data)))
+ digest.update(data)
+ return digest.hexdigest()
+
+
+def json_bytes(value: Any) -> bytes:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n"
+
+
+def write_private(path: Path, data: bytes, mode: int = 0o600) -> None:
+ path.write_bytes(data)
+ path.chmod(mode)
+
+
+def invoke(graff: Path, workspace: Path, env: dict[str, str], *args: str, succeeds: bool = True) -> subprocess.CompletedProcess[str]:
+ result = subprocess.run(
+ [str(graff), "learn", *args],
+ cwd=workspace,
+ env=env,
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ timeout=60,
+ check=False,
+ )
+ if succeeds and result.returncode != 0:
+ raise AssertionError(f"command failed: {' '.join(args)}\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}")
+ if not succeeds and result.returncode == 0:
+ raise AssertionError(f"command unexpectedly succeeded: {' '.join(args)}\n{result.stdout}")
+ return result
+
+
+def run_id_from(output: str) -> str:
+ match = re.search(r"^run ([0-9a-f]{64})$", output, re.MULTILINE)
+ if match is None:
+ raise AssertionError(f"missing run id in output:\n{output}")
+ return match.group(1)
+
+
+def status(graff: Path, workspace: Path, env: dict[str, str]) -> dict[str, Any]:
+ return json.loads(invoke(graff, workspace, env, "status").stdout)
+
+
+def write_forged_object(directory: Path, domain: str, value: Any) -> str:
+ data = json_bytes(value)
+ object_id = addressed_id(domain, data)
+ write_private(directory / f"{object_id}.json", data)
+ return object_id
+
+
+def exercise(graff: Path, root: Path) -> None:
+ workspace = root / "workspace"
+ workspace.mkdir(mode=0o700)
+ tools = root / "tools"
+ tools.mkdir(mode=0o700)
+
+ mutator = tools / "mutator.py"
+ evaluator = tools / "evaluator.py"
+ python = Path(sys.executable).resolve()
+ mutator_source = f"""#!{python}
+import hashlib, json, os, pathlib, sys
+assert pathlib.Path(sys.argv[0]).resolve() != pathlib.Path(os.environ[\"FIXTURE_MUTATOR_SOURCE\"]).resolve()
+operation, request_path, response_path = sys.argv[1:4]
+assert operation == \"mutate\"
+request = json.loads(pathlib.Path(request_path).read_text())
+parent = pathlib.Path(request[\"parent\"][\"path\"]).read_text()
+child = parent.rstrip() + \"\\n\\nLearned fixture policy.\\n\"
+child_bytes = child.encode()
+pathlib.Path(request[\"child_path\"]).write_bytes(child_bytes)
+response = {{
+ \"schema\": \"codegraff.learn.mutation.response.v1\",
+ \"trial_id\": request[\"trial_id\"],
+ \"candidate_index\": request[\"candidate_index\"],
+ \"parent_id\": request[\"parent\"][\"id\"],
+ \"child_path\": request[\"child_path\"],
+ \"child_sha256\": hashlib.sha256(child_bytes).hexdigest(),
+ \"description\": \"deterministic fixture mutation\",
+}}
+pathlib.Path(response_path).write_text(json.dumps(response, separators=(\",\", \":\")) + \"\\n\")
+"""
+ evaluator_source = f"""#!{python}
+import hashlib, json, os, pathlib, sys
+assert pathlib.Path(sys.argv[0]).resolve() != pathlib.Path(os.environ[\"FIXTURE_EVALUATOR_SOURCE\"]).resolve()
+operation, request_path, response_path = sys.argv[1:4]
+assert operation == \"evaluate\"
+request = json.loads(pathlib.Path(request_path).read_text())
+assert request[\"suite_path\"] == \"suite.json\"
+suite_bytes = pathlib.Path(request[\"suite_path\"]).read_bytes()
+assert hashlib.sha256(suite_bytes).hexdigest() == request[\"suite_sha256\"]
+pairs = []
+for pair in request[\"pairs\"]:
+ pairs.append({{
+ \"case_id\": pair[\"case_id\"],
+ \"seed\": pair[\"seed\"],
+ \"parent_pass\": False,
+ \"child_pass\": True,
+ \"parent_score_ppm\": 0,
+ \"child_score_ppm\": 1000000,
+ \"parent_cost_micros\": 100,
+ \"child_cost_micros\": 90,
+ }})
+response = {{
+ \"schema\": \"codegraff.learn.evaluation.response.v1\",
+ \"trial_id\": request[\"trial_id\"],
+ \"candidate_index\": request[\"candidate_index\"],
+ \"cohort_id\": request[\"cohort_id\"],
+ \"suite_sha256\": request[\"suite_sha256\"],
+ \"parent_id\": request[\"parent\"][\"id\"],
+ \"child_id\": request[\"child\"][\"id\"],
+ \"pairs\": pairs,
+}}
+pathlib.Path(response_path).write_text(json.dumps(response, separators=(\",\", \":\")) + \"\\n\")
+"""
+ write_private(mutator, mutator_source.encode(), 0o700)
+ write_private(evaluator, evaluator_source.encode(), 0o700)
+
+ evaluation_suite = tools / "evaluation-suite.json"
+ holdout_suite = tools / "holdout-suite.json"
+ evaluation_manifest = {
+ "schema": "codegraff.learn.suite.v1",
+ "suite_id": "fixture-primary",
+ "cases": [{"id": f"primary-{index}"} for index in range(6)],
+ }
+ holdout_manifest = {
+ "schema": "codegraff.learn.suite.v1",
+ "suite_id": "fixture-holdout",
+ "cases": [{"id": f"holdout-{index}"} for index in range(6)],
+ }
+ write_private(evaluation_suite, json_bytes(evaluation_manifest))
+ write_private(holdout_suite, json_bytes(holdout_manifest))
+
+ parent = root / "parent.md"
+ write_private(parent, b"Initial fixture policy.\n")
+ config_path = root / "config.json"
+ config = {
+ "schema": "codegraff.learn.config.v1",
+ "agent_name": "fixture-agent",
+ "agent_description": "local deterministic learning fixture",
+ "mutation_instruction": "append the fixture policy sentence",
+ "mutator": {
+ "program": str(mutator.resolve()),
+ "sha256": raw_sha256(mutator),
+ "pass_env": ["FIXTURE_MUTATOR_SOURCE"],
+ },
+ "evaluator": {
+ "program": str(evaluator.resolve()),
+ "sha256": raw_sha256(evaluator),
+ "pass_env": ["FIXTURE_EVALUATOR_SOURCE"],
+ },
+ "evaluation_suite": {"path": str(evaluation_suite.resolve()), "sha256": raw_sha256(evaluation_suite)},
+ "holdout_suite": {"path": str(holdout_suite.resolve()), "sha256": raw_sha256(holdout_suite)},
+ "gate": {
+ "alpha_ppm": 50000,
+ "minimum_delta_ppm": 100000,
+ "minimum_pairs": 6,
+ "default_candidates": 1,
+ "default_repetitions": 3,
+ },
+ "auto": {"enabled": True},
+ "cohort": {
+ "provider": "fixture",
+ "model": "fixture",
+ "task_family": "local-e2e",
+ "adapter_version": "v1",
+ "verifier_version": "v1",
+ },
+ }
+ write_private(config_path, json_bytes(config))
+
+ env = os.environ.copy()
+ env.update(
+ {
+ "GRAFF_NO_TELEMETRY": "1",
+ "GRAFF_BEHAVIOR_TRACE": "0",
+ "FIXTURE_MUTATOR_SOURCE": str(mutator.resolve()),
+ "FIXTURE_EVALUATOR_SOURCE": str(evaluator.resolve()),
+ }
+ )
+
+ invoke(graff, workspace, env, "init", "--parent", str(parent.resolve()), "--config", str(config_path.resolve()))
+ initial = status(graff, workspace, env)
+ assert initial["generation"] == 0
+ initial_genome = initial["active_genome_id"]
+
+ manual_output = invoke(graff, workspace, env, "run").stdout
+ manual_run = run_id_from(manual_output)
+ learn_root = workspace / ".graff" / "learn"
+ run_path = learn_root / "runs" / f"{manual_run}.json"
+ original_record = json.loads(run_path.read_text())
+
+ # A forged mutation response that does not bind the selected child bytes
+ # must not become promotable, even if all other run evidence is copied.
+ bad_response_record = copy.deepcopy(original_record)
+ mutation_response_id = bad_response_record["candidates"][0]["mutation"]["response_evidence_id"]
+ mutation_response = json.loads((learn_root / "evidence" / f"{mutation_response_id}.json").read_text())
+ mutation_response["child_sha256"] = "0" * 64
+ bad_evidence_id = write_forged_object(learn_root / "evidence", "codegraff-learn/evidence/v1", mutation_response)
+ bad_response_record["candidates"][0]["mutation"]["response_evidence_id"] = bad_evidence_id
+ bad_response_run = write_forged_object(learn_root / "runs", "codegraff-learn/run/v1", bad_response_record)
+ invoke(graff, workspace, env, "promote", bad_response_run, succeeds=False)
+ assert status(graff, workspace, env)["generation"] == 0
+
+ # Trial IDs are derived by the engine, not trusted from a run record.
+ bad_trial_record = copy.deepcopy(original_record)
+ bad_trial_record["trial_id"] = "0" * 64
+ bad_trial_run = write_forged_object(learn_root / "runs", "codegraff-learn/run/v1", bad_trial_record)
+ invoke(graff, workspace, env, "promote", bad_trial_run, succeeds=False)
+ assert status(graff, workspace, env)["generation"] == 0
+
+ invoke(graff, workspace, env, "promote", manual_run)
+ promoted = status(graff, workspace, env)
+ assert promoted["generation"] == 1
+ assert promoted["active_genome_id"] != initial_genome
+
+ invoke(graff, workspace, env, "rollback")
+ rolled_back = status(graff, workspace, env)
+ assert rolled_back["generation"] == 2
+ assert rolled_back["active_genome_id"] == initial_genome
+
+ # Returning to identical parent bytes does not make old evidence fresh: the
+ # parent generation and transaction ID must also match.
+ invoke(graff, workspace, env, "promote", manual_run, succeeds=False)
+ assert status(graff, workspace, env)["generation"] == 2
+
+ # Those fields are part of the trial derivation, not independently editable
+ # labels. Rebinding an old content-addressed run to the rollback transaction
+ # must invalidate its trial ID and all seeds derived from it.
+ rebound_record = copy.deepcopy(original_record)
+ rebound_record["parent_generation"] = rolled_back["generation"]
+ rebound_record["parent_transaction_id"] = rolled_back["transaction_id"]
+ rebound_run = write_forged_object(learn_root / "runs", "codegraff-learn/run/v1", rebound_record)
+ invoke(graff, workspace, env, "promote", rebound_run, succeeds=False)
+ assert status(graff, workspace, env)["generation"] == 2
+
+ automatic_output = invoke(graff, workspace, env, "run", "--auto").stdout
+ assert run_id_from(automatic_output)
+ automatic = status(graff, workspace, env)
+ assert automatic["generation"] == 3
+ assert automatic["active_genome_id"] != initial_genome
+ verified = invoke(graff, workspace, env, "verify")
+ assert json.loads(verified.stdout)["integrity"] == "ok"
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--graff", type=Path, default=Path("zig-out/bin/graff"))
+ parser.add_argument("--keep", action="store_true", help="preserve the temporary fixture directory")
+ args = parser.parse_args()
+ graff = args.graff.resolve()
+ if not graff.is_file():
+ parser.error(f"graff binary not found: {graff}")
+
+ root = Path(tempfile.mkdtemp(prefix="codegraff-learn-e2e."))
+ try:
+ exercise(graff, root)
+ except Exception:
+ print(f"learning E2E failed; fixture preserved at {root}", file=sys.stderr)
+ raise
+ if args.keep:
+ print(f"learning E2E passed; fixture preserved at {root}")
+ else:
+ shutil.rmtree(root)
+ print("learning E2E passed")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())