graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat: add governed local learning pipeline
Rach Pradhan6bda1c9b0a09
diff --git a/README.md b/README.mdindex 9397bbab..21e11201 100644--- a/README.md+++ b/README.md@@ -259,9 +259,9 @@ the directory, so concurrent processes never share a truncate/append cursor:- **Tool-use is mined too.** Each agent logs its tool calls (name + error flag,in order): the process signal behind "which tool combinations work",joinable to scores via `prompt_sha`.-- **Closed loop in releases.** Release binaries ship anonymous evolution- telemetry (opt-out) so agent-variant fitness is learned across the fleet, not- just one laptop. `/trajectory` renders the current session's agent tree; see+- **Consent-scoped fleet loop.** Learning stays local by default; users can+ contribute prompt-free aggregate fitness or individually reviewed reusable+ templates. `/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@@ -858,22 +858,26 @@ It's *pseudonymous, not anonymous*: records carry a **random** per-install idname, 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,+workflow/ultracode counts), plus per-`workflow` and per-error records. When+learning privacy is `aggregate` or higher it also admits per-run/score records+keyed by a one-way **system-prompt fingerprint** 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 followsthe metadata/content rules above; only explicit content mode permits opaqueadapter 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:-`GRAFF_FLEET=off` or `/fleet off`. They're hashes and labels, with one exception.-`fleet:propose` sends an agent's **system-prompt / persona text** (≤8192 chars: the-evolved "genome"; graff's own text for built-in agents, *your* text for a custom-agent or inline override). Error details are capped at 200 chars. The SDKs tag their-child harness with `HARNESS_CLIENT=sdk-ts|sdk-py` and a separate id-(`~/.simple-harness-sdk-id`). A flush failure never disturbs the session.+**Fleet / evolution signals are local by default.** `/privacy` selects a+session-scoped learning ceiling: `local` sends nothing automatically (the+bundled `learn_candidate` tool can request one aggregate-only send); `aggregate` permits+signed grades and prompt-free fleet metadata; `templates` additionally offers+each private reusable persona/template for an exact preview approval; and+`examples` reserves a future one-shot reviewed-example channel (raw example+upload is not implemented). `GRAFF_LEARNING_PRIVACY` or+`--learning-privacy` can select the same mode, while `GRAFF_FLEET=off` or+`/fleet off` remains a master kill switch. Template approvals never persist,+are not bypassed by `--yolo`, and are re-scanned at the final egress point.+Raw task prompts, bindings, code, paths, reports, tool results, and traces have+no fleet upload path. See [Learning privacy and consent](docs/learning-privacy.md).</details>diff --git a/docs/behavioral-trajectories.md b/docs/behavioral-trajectories.mdindex 3b1bf2a6..9d924bdc 100644--- a/docs/behavioral-trajectories.md+++ b/docs/behavioral-trajectories.md@@ -79,9 +79,10 @@ controlled classes (`shell`, `read`, `write`, `search`, `web`, `agent`, `verify`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+rewrite the existing OTLP score/run/fleet contract. In aggregate-or-higher+learning mode, OTLP score/run records can contain prompt fingerprints; a fleet proposal can contain reusable prompt text+only after the separate `/privacy templates` exact-artifact consent described+in [learning-privacy.md](learning-privacy.md). Disabling ordinary telemetrydisables both OTLP and behavioral upload.Metadata admission is field-based; values of allowed fields are not scanned ordiff --git a/docs/hyperagents.md b/docs/hyperagents.mdindex 156285fd..de090589 100644--- a/docs/hyperagents.md+++ b/docs/hyperagents.md@@ -238,8 +238,8 @@ additionally binds `niche` and `provider_class` so a score can't be replayedinto another MAP-Elites cell. Verifiers still accept the legacy `v1` envelope(the same tuple without the last two fields) during the transition window.-**Key custody.** `GRAFF_SCORE_KEY_FILE` names a key file *outside* cwd. The-env var holds only the path; the file is unreadable by the evolving+**Key custody.** `GRAFF_SCORE_KEY_FILE` names a key file *outside* cwd and+defaults to `~/.simple-harness/score.key`. The file is unreadable by the evolvingvariant — subagent file tools are confined to cwd, and subagent bash iscwd-locked with no redirection. `confinedPath` guards cwd-*escape*, but thearchive and `main.zig` live *inside* cwd, so the key must live outside it.@@ -268,9 +268,12 @@ actual work. Step 1 replaces it as the primary gradient:**Held-out replay eval.** `examples/replay_judge.py` runs a candidategenome against `examples/dgm_eval_set.jsonl` — tasks with DETERMINISTIC,-out-of-process assertions (a shell command's exit code or a golden-substring in the final report), each in a fresh scratch directory so file-assertions are hermetic. The judge is dependency-free (speaks the+out-of-process assertions (a shell command's exit code or an exact final+answer), each in a fresh scratch directory so file assertions are hermetic.+Exact-answer checks deliberately reject substring false positives such as+`1391` for an expected answer of `391`. The separate+`examples/dgm_canary_eval_set.jsonl` supplies unseen boundary variants for a+final generalization check. The judge is dependency-free (speaks the`harness --json` protocol directly) so its pinned copy runs anywhere.**Custody (same model as the score key).** `--pin` installs the eval set@@ -287,25 +290,25 @@ closed), and that hash is written into each score record's signed```replay judge failed/missing → 0.0 (fail closed)pass_rate < 1.0 → 0.8 × pass_rate (capped at 0.8)-all held-out tasks pass → 0.9 + 0.1 × llm (LLM reorders only)+all held-out tasks pass → 0.9 + 0.1 × efficiency```-`h.ask` survives only as `llm_tiebreak`, a secondary gradient that can-reorder already-passing variants but can never admit a failing one — a-variant that fails any deterministic check cannot reach the promotable-band (≥ 0.9) no matter how well it charms the LLM.+Once correctness saturates, `efficiency = tasks / (tasks + tool_calls)`+reorders passing variants. A variant that fails any deterministic check cannot+reach the promotable band (≥ 0.9), no matter how persuasive its report sounds.Verified (`examples/test_step1.py`): the band invariant holds for every-pass_rate × tie-break combination; judge-missing and pin-mismatch paths-fail closed; and live, a sabotage variant whose report *claims* success-(h.ask rates it high) is pinned ≤ 0.8 by the failing replay suite while+failing pass rate; exact checks reject substring false positives;+judge-missing and pin-mismatch paths fail closed; and live, a sabotage variant+whose report *claims* success is pinned ≤ 0.8 by the failing replay suite whilethe honest seed lands ≥ 0.9 with `eval_set_hash` populated and signed.## 8. What's deliberately not built yet-- **Eval-set breadth**: five held-out tasks prove the mechanism; a real- evolution run wants a corpus broad enough that overfitting the suite is- harder than being generally good. Growing it is data work, not code.+- **Eval-set breadth**: the 15-case replay suite plus 10-case canary prove the+ mechanism; a real evolution run still wants a larger private corpus broad+ enough that overfitting is harder than being generally good. Growing it is+ data work, not code.- **Parent selection**: the archive has everything the formula needs(scores per sha, children per node); the sampling lives in the driver —per the paper, even DGM-H's self-modified selection didn't beat the@@ -326,7 +329,7 @@ DGM.The load-bearing constraint is **"let the provider be me":** every expensivestep (mutating a prompt, running the eval) runs on *each user's own provider*,-opt-out, during their session. Central infra (`harness-telemetry`) does only+locally unless the user raises the learning ceiling. Central infra (`harness-telemetry`) does onlycheap, deterministic work — HMAC-verify, artifact re-check, SQL-aggregate,serve elites. **No central inference → it runs at fleet scale for free.**@@ -337,21 +340,24 @@ serve elites. **No central inference → it runs at fleet scale for free.**- **Eval: private suite, public hash.** Only `eval_set_hash` is public; thesuite is secret and rotated, so the honest majority can't study to theanswer. Already bound into every score signature (Step 0).-- **Contribution: opt-out, authored personas included.** Scores *and* persona- genomes contribute by default; `GRAFF_FLEET=off` / `/fleet off` disables.+- **Contribution: local by default, independently scoped.** `/privacy+ aggregate` admits prompt-free scores/metadata. `/privacy templates` raises+ the ceiling, but each private persona still requires exact interactive+ approval; `GRAFF_FLEET=off` remains a master kill switch.- **Grid: niche × provider-class.** The elite you *receive* is the one that wonon *your* model tier — "let the provider be me" made literal.-The one hard invariant, true regardless of the opt-out toggle: **task / user-content never leaves the machine.** Only the genome (persona prompt text), the-score float, `eval_set_hash`, `provider_class`, and the deterministic eval-artifact are ever transmitted.+The hard invariant is that **raw task/user content never enters fleet egress.**+Aggregate mode sends only scores and controlled metadata. A reusable persona+genome can be transmitted only after the user previews and approves that exact+version; task prompts, bindings, repository data, reports, and tool results+remain local.### The federated loop (A→E)| phase | who runs it | what happens ||---|---|---|-| **A — Harvest** | every install (fleet on) | signed pinned-eval scores + variant fingerprints accumulate in D1 |+| **A — Harvest** | aggregate-enabled installs | signed pinned-eval scores + variant fingerprints accumulate in D1 || **B — Propose** | the user's own provider | mine local failures → mutate the niche's current elite → run the **private replay suite** → sign(score, `eval_set_hash`, `artifact_sha`, `provider_class`) → submit || **C — Rank** | central worker (SQL, no inference) | per cell `(niche × provider_class × eval_set_hash)`: HMAC-verify · re-check golden artifacts · K-install floor · LCB · anomaly-eject → `harness_elites` || **D — Promote** | central worker (automatic) | challenger beats the incumbent built-in by margin M over W days with ≥K distinct installs → flip `live` |@@ -360,9 +366,9 @@ artifact are ever transmitted.### Driving Propose (B) yourselfTwo entry points feed a niche's cell. Both tag the score with the niche so the-worker can group it into `(niche × provider_class × eval_set_hash)`, and both-ride the genome (the persona's `prompt_text`) over on `fleet:propose` so a-promoted cell actually has a persona to serve:+worker can group it into `(niche × provider_class × eval_set_hash)`. Aggregate+mode can establish fitness without content. A promotable genome row is created+only when the exact persona text has separately passed template consent:- **Harness eval loop.** Name the role the eval optimizes:@@ -450,7 +456,7 @@ both clients, since the SDKs are generated):| body | kind | emitted by | attrs | meaning ||---|---|---|---|---|| `score` | — | harness (on `h.score()`) | `prompt_sha`, `value`, `parent_sha`, `provider_class`, `artifact_sha`, `eval_set_hash`, `niche`, `sig` | a signed fitness write-back (the gradient) |-| `fleet` | `propose` | harness · SDK driver | `niche`, `prompt_sha`, `parent_sha`, `provider_class`, `prompt_text` | a variant was generated/mutated (carries the genome) |+| `fleet` | `propose` | harness · SDK driver | `niche`, `prompt_sha`, `parent_sha`, `provider_class`; consented CLI proposals may add `prompt_text` | a variant was generated/mutated || `fleet` | `submit` | harness · SDK driver | `niche`, `prompt_sha`, `provider_class`, `eval_set_hash` | a scored variant was submitted to the fleet || `fleet` | `elite_pull` | SDK driver | `provider_class`, `eval_set_hash`, `n_elites` | current elites fetched from `/v1/elites` || `fleet` | `promote` | worker | `niche`, `provider_class`, `prompt_sha`, `lcb`, `n_installs` | the backend flipped a new champion live |@@ -461,11 +467,11 @@ scores submitted → cells promoted) per client, exactly as `prompt_variants` /`scores_recorded` did for the local loop.SDK surface (both clients): `score(promptOrSha, value, …, niche)` carries the-signed fields and emits `fleet:submit`; when handed the full persona text plus a-`niche` it also emits `fleet:propose` carrying the genome, so the cell it submits-into is promotable. `pullElites(providerClass)` / `pull_elites(...)` returns the-live champions and emits `fleet:elite_pull`. All gated by the same telemetry-opt-out as the rest of the SDK.+signed fields and can emit prompt-free `fleet:propose`/`fleet:submit` in+aggregate-or-higher mode. The generated SDKs have no interactive artifact+review UI, so their final emitter strips `prompt_text` even in template mode.+`pullElites(providerClass)` / `pull_elites(...)` is gated by the same learning+mode. A future SDK content API needs an explicit preview/consent primitive.### Scaffolded vs TODO@@ -474,8 +480,8 @@ opt-out as the rest of the SDK.fields, the SDK `fleet` signal emitters, and — as of this change — the**harness-side `fleet` emitters too**: `Telemetry.fleetEvent` (body `fleet`,matching the SDK `_fleet_signal`), `fleet:propose` at the variant spawn- (`runSub`) and on each eval-loop best (`runEval`, gated on `--niche`), both- carrying the genome `prompt_text`; the niche-tagged `fleet:submit` at the+ (`runSub`) and on each eval-loop best (`runEval`, gated on `--niche`), with+ genome text admitted only after exact CLI template consent; the niche-tagged `fleet:submit` at the`score` write-back, a `providerClass()`tier tag, and the graff-side startup pull (`pullElites` → `fleet:elite_pull`,with `loadAgentTypes`/builtins deferring to a live champion's prompt). Verified@@ -485,5 +491,5 @@ opt-out as the rest of the SDK.re-verification for golden tasks, and the auto-promote margin/window rule in D(so `promotes` / `live_cells` move). The harness side is now complete: the`fleet` emitters, a curated-table + models.dev-price `providerClass()`, the- startup elite-pull, and the `GRAFF_FLEET` env / `/fleet` opt-out (live A/B- verified — `GRAFF_FLEET=off` leaves `proposes` flat while `variants` still ticks).+ startup elite-pull, the learning-privacy gate, and the `GRAFF_FLEET` env /+ `/fleet` master kill switch.diff --git a/docs/learning-privacy.md b/docs/learning-privacy.mdnew file mode 100644index 00000000..3b261c30--- /dev/null+++ b/docs/learning-privacy.md@@ -0,0 +1,127 @@+# Learning privacy and consent++Graff separates calls to the user's selected model provider, ordinary+operational telemetry, and federated prompt-policy learning. The controls on+this page govern only the third path.++`Local` therefore means **no background learning upload to the Graff backend**.+The one exception is a separately confirmed `learn_candidate` action that sends+one aggregate-only receipt. Local does not claim that a prompt stays on-device+when the configured model provider is remote.++## Modes++The default is `local`. Change the session ceiling interactively:++```text+/privacy+/privacy aggregate+/privacy templates+/privacy examples+```++Or select it at launch:++```sh+graff --learning-privacy aggregate+GRAFF_LEARNING_PRIVACY=aggregate graff+```++Only exact lowercase environment values are recognized. Unknown, padded, or+case-varied values fail closed to `local`.++| Mode | Learning data admitted | Additional consent |+| --- | --- | --- |+| `local` | Nothing automatically | One-shot confirmation if `learn_candidate` requests aggregate submission |+| `aggregate` | Signed grades, counts, buckets, fingerprints, controlled cohort metadata | Selecting the mode |+| `templates` | Aggregate data plus reviewed reusable system/persona templates | Exact template-version approval |+| `examples` | Same implemented behavior as `templates` today | Raw example transport is reserved but not implemented |++`GRAFF_FLEET=off` and `/fleet off` remain master kill switches. Ordinary+telemetry still follows `--no-telemetry` / `GRAFF_NO_TELEMETRY` and the+behavioral upload controls documented separately.++## Template consent++`templates` is a ceiling, not blanket content consent. Before a private inline,+personal, project, or locally learned persona can enter a `fleet:propose`, the+interactive root shows:++- its short fingerprint and byte count;+- a bounded one-line preview;+- what is included and structurally excluded; and+- any locally detected credential marker.++The user can share that exact version for the current process, run the child+locally, or cancel it. Changing one byte changes the fingerprint and asks+again. Approvals are kept only in memory and are cleared on every mode change.+A repository-controlled settings file cannot grant them.++`--yolo`, saved command approvals, subagents, and noninteractive runs cannot+approve template publication. Without an interactive approval, the child still+runs but its prompt text is omitted. Builtin and already-downloaded fleet+personas are public artifacts and do not need to be republished as private user+content.++## Final egress boundary++All score and fleet call sites converge in `Telemetry.scoreEvent` and+`Telemetry.fleetEvent`. Those functions enforce the current mode again.+Template text is admitted only when its exact SHA-256 digest is on the+session-local approval list and a second secret scan passes.++This double check means a missed condition at an individual mutation,+evaluation, subagent, or workflow call site cannot silently attach content.++Raw task prompts, template bindings, user messages, code, paths, child reports,+tool arguments/results, and local traces have no field in the fleet contract.+The future `examples` path must use a separate endpoint, preview hash, consent+receipt, short retention, and deletion API before it can be enabled.++## Hashes are not anonymity++Graff does not describe deterministic prompt hashes as anonymous. Short or+low-entropy prompt text can be guessed and checked against an ordinary hash,+and stable identifiers permit correlation.++Private prompt fingerprints therefore remain local unless needed as controlled+aggregate lineage metadata. Public/builtin templates may use stable IDs because+their content is already known. Raw prompt text is never made safe merely by+hashing it.++## Local files++Local is still sensitive storage. Trajectory archives can contain complete+system/persona prompt genomes, subagent nodes contain a short task preview, and+`.graff/subagents/` inspection reports contain full task/report detail. Keep+`.graff/` out of version control, protect the workspace permissions, and delete+those files when they are no longer needed.++## Explicit grade submission++`graff learn submit` and `graff learn run --submit` require an aggregate-or-+higher ceiling in addition to their existing signing key and telemetry endpoint:++```sh+graff --learning-privacy aggregate learn submit RUN_ID+graff --learning-privacy aggregate learn run --submit+```++The root `learn_candidate` tool is a deliberate one-shot exception: it bundles+local evaluation, grading, and aggregate submission. In Local mode the root+shows the exact aggregate categories and requires a separate confirmation;+`--yolo`, saved approvals, subagents, and noninteractive calls cannot bypass it.+The permit is consumed once without changing the session mode. The tool cannot+publish prompt text or promote a candidate automatically.++## Regression contract++Tests assert that:++- local mode creates no score or fleet record;+- aggregate mode records grades and fleet metadata without prompt text;+- template mode still omits unapproved text;+- approval applies only to the exact template version;+- planted API keys, tokens, authorization headers, and private-key markers+ cannot be approved; and+- lowering or changing the mode revokes prior content approvals.diff --git a/docs/local-learning.md b/docs/local-learning.mdindex 3cd53cb0..c17263d8 100644--- a/docs/local-learning.md+++ b/docs/local-learning.md@@ -35,6 +35,8 @@ protocols.```textgraff learn init --parent PATH --config PATHgraff learn run [--candidates N] [--repetitions N] [--auto] [--lock-timeout-ms N]+graff --learning-privacy aggregate learn run [--candidates N] [--repetitions N] --submit+graff --learning-privacy aggregate learn submit RUN_ID [--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]@@ -61,6 +63,47 @@ graff learn rollbackOnly one learning operation runs at a time. `--lock-timeout-ms` controls howlong a command waits for the local engine lock, up to 600,000 ms.+`run --submit` performs mutation, paired primary/holdout grading, immutable+storage, and aggregate publication in one command. `submit RUN_ID` re-verifies+and retries an already stored run. Both use `GRAFF_SCORE_KEY_FILE`, falling back+to `~/.simple-harness/score.key`, plus the normal OTLP endpoint configuration.+A retry is idempotent at the collector.+Neither form promotes the selected candidate; use the separate manual or+two-key automatic promotion policy described above.++For multiple candidates, execution is a barriered tournament:++1. every mutation arm runs concurrently;+2. every unique arm runs the same primary suite concurrently with common pair+ seeds and one fixed evaluator cohort;+3. ranking minimizes critical regressions, then maximizes observed correctness,+ then minimizes measured tool calls, latency, cost, and prompt size;+4. only that primary winner is evaluated on the holdout; and+5. promotion remains a separate manual action unless the configured two-key+ automatic policy is explicitly enabled and all statistical gates pass.++Run records use `codegraff.learn.run.v2` and persist the primary winner even+when evidence is underpowered. Missing tool-call instrumentation is recorded as+unknown and cannot masquerade as zero calls. `GRAFF_NO_TELEMETRY=1` and+`GRAFF_FLEET=off` both block explicit aggregate submission.++The bundled model-backed example adapters fail safely around transient or+malformed model output. A mutation gets one corrective turn after deterministic+size/invariant validation; a second failure becomes an unchanged-parent+non-contender rather than aborting other arms. An evaluation turn that ends+without gradeable evidence gets one bounded retry in a newly initialized task+directory, so partial file changes cannot leak into the retry.++The root model also receives an approval-gated `learn_candidate` tool when it+runs in a configured workspace. The tool bundles `run --submit` into one+model-facing action. In Local mode it shows the aggregate payload categories+and requires a one-shot confirmation that `--yolo` cannot bypass. It accepts+only candidate/repetition limits, is unavailable to subagents, and exposes no+promotion option. This consent controls learning telemetry; it does not make a+networked mutator local. A configured model adapter may send the parent prompt+and mutation instruction to its declared provider, which the confirmation+discloses separately.+## ConfigurationThe configuration is copied into `.graff/learn`, content-addressed, and treated@@ -109,6 +152,10 @@ as immutable. Unknown JSON fields are rejected."alpha_ppm": 50000,"minimum_delta_ppm": 50000,"minimum_pairs": 20,+ "economy_gate_enabled": false,+ "promotion_mode": "correctness",+ "minimum_tool_reduction_ppm": 100000,+ "minimum_economy_pairs": 8,"default_candidates": 1,"default_repetitions": 1},@@ -191,6 +238,23 @@ aggregate parent and child pass counts for that case. Therefore:candidates.- Correctness gates run before cost is used as a tie-breaker.+`promotion_mode` preregisters either `correctness` or `economy`; primary and+holdout cannot clear different endpoints. Economy mode also requires+`economy_gate_enabled`, zero case-level correctness losses, no mean-score+regression, measured calls, the configured aggregate call reduction, and a+separately Bonferroni-corrected per-case tool-call sign test.+`minimum_economy_pairs` counts only discordant cases (wins plus losses), since+tool-call ties provide no information to that sign test.+Latency is reported and used only as a ranking tie-breaker; it is not promotion+evidence because wall-clock measurements are comparatively noisy.++After each run, the CLI prints a prompt-free aggregate summary for every+candidate: parent and child pass counts, effect size, paired wins/losses/ties,+p-value, tool-call reduction and its per-case sign test, latency, cost movement,+prompt size, primary/holdout gate results, and the final decision.+This lets a user or the root model distinguish a harmful candidate from a+promising but underpowered result without weakening the promotion gate.+## Adapter protocolsPrograms are invoked directly, never through a generated shell command:@@ -327,11 +391,22 @@ independent gate against ordinary overfitting, not a secret from a malicious orcolluding adapter. Do not run adapters you do not trust; use an external sandboxwhen 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:+Learning artifacts and prompt genomes remain local by default. Submission also+requires an aggregate-or-higher learning ceiling, selected with+`--learning-privacy aggregate`, `GRAFF_LEARNING_PRIVACY=aggregate`, or+`/privacy aggregate`. The root-only `learn_candidate` tool can instead request+one explicit bundled aggregate submission without changing the session mode. An explicit `--submit` or+`learn submit` then publishes only the existing signed score envelope:+short parent/child fingerprints, aggregate pass rate, run/suite/cohort metadata,+and content-addressed evidence IDs. It does not publish prompt text, tasks,+adapter input/output, repository data, or local traces. The collector exposes a+retry-safe receipt at `GET /v1/learning/<RUN_ID>`.++Once activated, 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;+- prompt fingerprints stay in local trajectories and enter learning telemetry+ only in aggregate-or-higher mode;- provider/model identifiers and other ordinary telemetry follow the existingtelemetry policy; and- local trace/session files retain their documented behavior.@@ -353,9 +428,20 @@ network access:```shzig buildpython3 tests/learn_e2e.py --graff zig-out/bin/graff+python3 tests/learn_tournament_e2e.py --graff zig-out/bin/graff+python3 tests/learn_graff_adapters.py```-## Collective learning: design, not implemented authority+For an explicitly consented model-backed trial,+`examples/prepare_graff_tournament.py` creates an isolated workspace, a newly+randomized five-case holdout, and pinned four-arm configuration. The shipped+arm map uses `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, and+`gpt-5.4-mini`; all prompts are evaluated by the same pinned cohort. The+mutator intentionally sends the parent prompt to those providers, while inner+agent telemetry is disabled and only the five signed aggregate tournament+grades are submitted. The generated config keeps automatic promotion off.++## Collective learning: aggregate receipts, not promotion authorityA privacy-preserving collective layer should exchange verified artifacts andattestations, not raw repositories, prompts, tool arguments, or local traces.@@ -386,4 +472,7 @@ A safe design has these components:D1 can serve as a small control plane for bundle manifests, signer keys,revocations, and aggregate pointers. Larger evidence/aggregation workloadsbelong behind a queue and analytical store rather than synchronous D1 writes.-No such collective promotion authority is implemented by `graff learn` today.+The signed aggregate score/receipt path is implemented. Prompt distribution,+central hidden-holdout inference, and collective promotion authority are not:+backend results remain advisory, and only the local verified promotion path can+change the active policy.diff --git a/examples/dgm_canary_eval_set.jsonl b/examples/dgm_canary_eval_set.jsonlnew file mode 100644index 00000000..d97296a2--- /dev/null+++ b/examples/dgm_canary_eval_set.jsonl@@ -0,0 +1,10 @@+{"id": "single-line-no-newline", "task": "Count the lines of text in singleton.txt and reply with only the number.", "setup_files": {"singleton.txt": "solitary"}, "check": {"exact": "1"}}+{"id": "four-lines-no-newline", "task": "Count the lines of text in directions.txt and reply with only the number.", "setup_files": {"directions.txt": "north\nsouth\neast\nwest"}, "check": {"exact": "4"}}+{"id": "empty-line-count", "task": "Count the lines of text in empty.txt and reply with only the number.", "setup_files": {"empty.txt": ""}, "check": {"exact": "0"}}+{"id": "json-array-length", "task": "Read payload.json and reply with only the number of entries in jobs.", "setup_files": {"payload.json": "{\"jobs\":[\"a\",\"b\",\"c\",\"d\",\"e\"]}\n"}, "check": {"exact": "5"}}+{"id": "signed-sum", "task": "Sum the signed integers in signed.txt and reply with only the total.", "setup_files": {"signed.txt": "-12\n5\n20\n-5\n"}, "check": {"exact": "8"}}+{"id": "numeric-sort", "task": "Sort the integers in unsorted.txt numerically into sorted.txt, one per line.", "setup_files": {"unsorted.txt": "10\n2\n1\n"}, "check": {"cmd": "test \"$(sed -n 1p sorted.txt)\" = 1 && test \"$(sed -n 2p sorted.txt)\" = 2 && test \"$(sed -n 3p sorted.txt)\" = 10 && test \"$(grep -c . sorted.txt)\" -eq 3"}}+{"id": "preserve-unterminated-edit", "task": "In phrase.txt replace beta with BETA while preserving every other byte, including the lack of a trailing newline.", "setup_files": {"phrase.txt": "alpha\nbeta"}, "check": {"cmd": "test \"$(cat phrase.txt)\" = 'alpha\nBETA' && test \"$(wc -c < phrase.txt)\" -eq 10"}}+{"id": "csv-column-sum", "task": "Read sales.csv and reply with only the sum of the amount column, excluding the header.", "setup_files": {"sales.csv": "item,amount\na,10\nb,20\nc,30\n"}, "check": {"exact": "60"}}+{"id": "dedupe-stable", "task": "Remove duplicate lines from colors.txt in place, keeping the first occurrence and original order.", "setup_files": {"colors.txt": "red\nblue\nred\ngreen\nblue\n"}, "check": {"cmd": "test \"$(sed -n 1p colors.txt)\" = red && test \"$(sed -n 2p colors.txt)\" = blue && test \"$(sed -n 3p colors.txt)\" = green && test \"$(grep -c . colors.txt)\" -eq 3"}}+{"id": "zero-byte-file", "task": "Create a file named blank.bin containing exactly zero bytes.", "check": {"cmd": "test -f blank.bin && test ! -s blank.bin"}}diff --git a/examples/dgm_eval_set.jsonl b/examples/dgm_eval_set.jsonlindex b93d3836..691451d8 100644--- a/examples/dgm_eval_set.jsonl+++ b/examples/dgm_eval_set.jsonl@@ -1,15 +1,15 @@{"id": "write-file", "task": "Create a file named out.txt whose entire content is exactly the single line: hello-dgm", "check": {"cmd": "test \"$(cat out.txt)\" = hello-dgm"}}-{"id": "arith", "task": "Compute 17*23 and reply with only the number.", "check": {"substring": "391"}}-{"id": "json-extract", "task": "Read cfg.json in the current directory and reply with only the value of service.port.", "setup_files": {"cfg.json": "{\"service\": {\"name\": \"gateway\", \"port\": 4117}, \"debug\": false}\n"}, "check": {"substring": "4117"}}+{"id": "arith", "task": "Compute 17*23 and reply with only the number.", "check": {"exact": "391"}}+{"id": "json-extract", "task": "Read cfg.json in the current directory and reply with only the value of service.port.", "setup_files": {"cfg.json": "{\"service\": {\"name\": \"gateway\", \"port\": 4117}, \"debug\": false}\n"}, "check": {"exact": "4117"}}{"id": "append-line", "task": "Append the line gamma to log.txt, keeping the existing lines unchanged.", "setup_files": {"log.txt": "alpha\nbeta\n"}, "check": {"cmd": "test \"$(head -1 log.txt)\" = alpha && test \"$(sed -n 2p log.txt)\" = beta && test \"$(sed -n 3p log.txt)\" = gamma"}}-{"id": "count-lines", "task": "Count the number of lines in words.txt and reply with only that number.", "setup_files": {"words.txt": "ember\nquartz\nfjord\nlumen\nbasalt\nrivet\ncairn\n"}, "check": {"substring": "7"}}-{"id": "count-lines-no-newline", "task": "Count the number of lines of text in notes.txt and reply with only that number.", "setup_files": {"notes.txt": "alpha\nbravo\ncharlie"}, "check": {"substring": "3"}}-{"id": "sum-file", "task": "Sum all the integers in nums.txt and reply with only the total.", "setup_files": {"nums.txt": "12\n30\n8\n50\n"}, "check": {"substring": "100"}}-{"id": "json-nested", "task": "Read app.json and reply with only the value of server.db.port.", "setup_files": {"app.json": "{\"server\": {\"host\": \"local\", \"db\": {\"name\": \"main\", \"port\": 5544}}}\n"}, "check": {"substring": "5544"}}+{"id": "count-lines", "task": "Count the number of lines in words.txt and reply with only that number.", "setup_files": {"words.txt": "ember\nquartz\nfjord\nlumen\nbasalt\nrivet\ncairn\n"}, "check": {"exact": "7"}}+{"id": "count-lines-no-newline", "task": "Count the number of lines of text in notes.txt and reply with only that number.", "setup_files": {"notes.txt": "alpha\nbravo\ncharlie"}, "check": {"exact": "3"}}+{"id": "sum-file", "task": "Sum all the integers in nums.txt and reply with only the total.", "setup_files": {"nums.txt": "12\n30\n8\n50\n"}, "check": {"exact": "100"}}+{"id": "json-nested", "task": "Read app.json and reply with only the value of server.db.port.", "setup_files": {"app.json": "{\"server\": {\"host\": \"local\", \"db\": {\"name\": \"main\", \"port\": 5544}}}\n"}, "check": {"exact": "5544"}}{"id": "merge-unique", "task": "Combine the lines of a.txt and b.txt into a new file merged.txt, sorted alphabetically with duplicate lines removed (one word per line).", "setup_files": {"a.txt": "banana\napple\ncherry\n", "b.txt": "cherry\ndate\napple\n"}, "check": {"cmd": "test \"$(grep -c . merged.txt)\" -eq 4 && test \"$(sed -n 1p merged.txt)\" = apple && test \"$(sed -n 2p merged.txt)\" = banana && test \"$(sed -n 3p merged.txt)\" = cherry && test \"$(sed -n 4p merged.txt)\" = date"}}{"id": "inplace-edit", "task": "In greeting.txt, change every occurrence of the word world to graff, leaving everything else unchanged.", "setup_files": {"greeting.txt": "hello world\ngoodbye world\nkeep this line\n"}, "check": {"cmd": "grep -q '^hello graff$' greeting.txt && grep -q '^goodbye graff$' greeting.txt && grep -q '^keep this line$' greeting.txt && ! grep -q world greeting.txt"}}{"id": "exact-bytes", "task": "Create a file named status.txt whose content is exactly the five characters READY with no trailing newline and nothing else.", "check": {"cmd": "test \"$(cat status.txt)\" = READY && test \"$(wc -c < status.txt)\" -eq 5"}}-{"id": "sha256", "task": "Compute the SHA-256 hash of the exact 5-letter ASCII string graff (no quotes, no newline) and reply with only the lowercase hex digest.", "check": {"substring": "7ee9757fe856d8589607b8c1008bafb969bc2c6d73b2d8fb8922db09800f31a5"}}+{"id": "sha256", "task": "Compute the SHA-256 hash of the exact 5-letter ASCII string graff (no quotes, no newline) and reply with only the lowercase hex digest.", "check": {"exact": "7ee9757fe856d8589607b8c1008bafb969bc2c6d73b2d8fb8922db09800f31a5"}}{"id": "ledger-sum", "task": "Each line of ledger.txt is 'name amount'. Sum the amounts and write only the total (digits only) to total.txt.", "setup_files": {"ledger.txt": "rent 45\nfood 55\ntravel 100\nmisc 20\n"}, "check": {"cmd": "test \"$(tr -cd '0-9' < total.txt)\" = 220"}}-{"id": "grep-count", "task": "Count how many lines in events.txt contain the word INFO and reply with only that number.", "setup_files": {"events.txt": "INFO start\nWARN low disk\nINFO tick\nERROR boom\nINFO done\n"}, "check": {"substring": "3"}}+{"id": "grep-count", "task": "Count how many lines in events.txt contain the word INFO and reply with only that number.", "setup_files": {"events.txt": "INFO start\nWARN low disk\nINFO tick\nERROR boom\nINFO done\n"}, "check": {"exact": "3"}}{"id": "delete-lines", "task": "Remove every line containing the word DROP from data.txt, leaving the remaining lines in their original order.", "setup_files": {"data.txt": "keep1\nDROP me\nkeep2\nDROP again\nkeep3\n"}, "check": {"cmd": "! grep -q DROP data.txt && test \"$(sed -n 1p data.txt)\" = keep1 && test \"$(sed -n 2p data.txt)\" = keep2 && test \"$(sed -n 3p data.txt)\" = keep3 && test \"$(grep -c . data.txt)\" -eq 3"}}diff --git a/examples/dgm_loop.py b/examples/dgm_loop.pyindex 4a54d72b..9a354fba 100644--- a/examples/dgm_loop.py+++ b/examples/dgm_loop.py@@ -216,7 +216,7 @@ def main():f"child={prompt_fingerprint(child)} score={s:.2f}"f"{' [PASSING]' if s >= 0.9 else ' [failing]'}")h.close()- print(f"archive: {ARCHIVE} — rerun to keep evolving; /trajectory to inspect")+ print(f"archive: {ARCHIVE_DIR} — rerun to keep evolving; /trajectory to inspect")if __name__ == "__main__":diff --git a/examples/learn_graff_arms.json b/examples/learn_graff_arms.jsonnew file mode 100644index 00000000..f226b20e--- /dev/null+++ b/examples/learn_graff_arms.json@@ -0,0 +1,58 @@+{+ "schema": "codegraff.learn.graff-arms.v1",+ "template_egress": true,+ "maximum_changed_bytes": 640,+ "maximum_total_bytes": 4096,+ "protected_substrings": [+ "Do not claim a relaunch is required.",+ "never in the current working repository's issue tracker.",+ "do NOT override GIT_AUTHOR_*/GIT_COMMITTER_*",+ "Co-Authored-By: Codegraff <[email protected]>",+ "`reset --hard`, `clean -f`"+ ],+ "targets": {+ "root_workflow": "Before an exact edit, read one current uncompressed target span, apply the smallest edit that preserves terminal-newline state, do not verify after success, and reread/retry only on stale source, ambiguity, or failure."+ },+ "arms": [+ {+ "index": 0,+ "id": "sol-semantic-boundaries",+ "provider": "codex",+ "model": "gpt-5.6-sol",+ "effort": "high",+ "target": "root_workflow",+ "placement": "replace",+ "focus": "Replace the target with one concise instruction: use compact reads only for broad discovery; when an edit is likely, read the exact uncompressed span once, reuse it for the edit, preserve terminal-newline state, and reread only after stale-source or edit failure."+ },+ {+ "index": 1,+ "id": "terra-edit-transaction",+ "provider": "codex",+ "model": "gpt-5.6-terra",+ "effort": "high",+ "target": "root_workflow",+ "placement": "replace",+ "focus": "Replace the target with one concise exact-edit transaction: one current uncompressed span read, one minimum edit preserving terminal-newline state, no verification after exact success, and reread/retry only for stale source, ambiguity, or failure."+ },+ {+ "index": 2,+ "id": "luna-dependency-dag",+ "provider": "codex",+ "model": "gpt-5.6-luna",+ "effort": "medium",+ "target": "root_workflow",+ "placement": "replace",+ "focus": "Replace the target with one concise dependency-aware edit instruction: batch known-independent exact reads, use each result once, preserve terminal-newline state, perform one derived mutation, and stop after exact success unless stale or ambiguous."+ },+ {+ "index": 3,+ "id": "terra-outcome-stop-medium",+ "provider": "codex",+ "model": "gpt-5.6-terra",+ "effort": "medium",+ "target": "root_workflow",+ "placement": "replace",+ "focus": "Replace the target with one concise outcome instruction: for an edit, read the exact current span once, preserve exact bytes and terminal-newline state, make the minimum mutation, and stop after exact success unless ambiguity, stale source, or failure is reported."+ }+ ]+}diff --git a/examples/learn_graff_evaluator.json b/examples/learn_graff_evaluator.jsonnew file mode 100644index 00000000..d22ecdeb--- /dev/null+++ b/examples/learn_graff_evaluator.json@@ -0,0 +1,10 @@+{+ "schema": "codegraff.learn.graff-evaluator.v1",+ "provider": "codex",+ "model": "gpt-5.4-mini",+ "effort": "low",+ "max_model_calls": 8,+ "max_tool_calls": 8,+ "max_attempts": 2,+ "task_timeout_seconds": 180+}diff --git a/examples/learn_graff_evaluator.py b/examples/learn_graff_evaluator.pynew file mode 100755index 00000000..8bc809ed--- /dev/null+++ b/examples/learn_graff_evaluator.py@@ -0,0 +1,466 @@+#!/usr/bin/env python3+"""Typed deterministic-task evaluator for model-backed Graff prompt tournaments."""++from __future__ import annotations++import hashlib+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile+import threading+import time+from typing import Any+++REQUEST_SCHEMA = "codegraff.learn.evaluation.request.v1"+RESPONSE_SCHEMA = "codegraff.learn.evaluation.response.v1"+BASELINE_REQUEST_SCHEMA = "codegraff.learn.primary-baseline.request.v1"+BASELINE_RESPONSE_SCHEMA = "codegraff.learn.primary-baseline.response.v1"+PRIMARY_REQUEST_SCHEMA = "codegraff.learn.primary-evaluation.request.v1"+PRIMARY_RESPONSE_SCHEMA = "codegraff.learn.primary-evaluation.response.v1"+PROGRESS_SCHEMA = "codegraff.learn.evaluator-progress.v1"+++class EvaluationAttemptError(Exception):+ """A bounded model turn failed before producing gradeable evidence."""++ def __init__(+ self,+ message: str,+ *,+ latency_ms: int = 0,+ tool_calls: int = 0,+ cost_micros: int = 0,+ ) -> None:+ super().__init__(message)+ self.latency_ms = max(0, latency_ms)+ self.tool_calls = max(0, tool_calls)+ self.cost_micros = max(0, cost_micros)+++def fail(message: str) -> "NoReturn":+ print(f"learn_graff_evaluator: {message}", file=sys.stderr)+ raise SystemExit(2)+++def load_json(path: Path) -> Any:+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:+ fail(f"cannot read {path}: {exc}")+++def request_pairs(request: dict[str, Any]) -> list[dict[str, Any]]:+ pairs = request.get("pairs")+ if not isinstance(pairs, list) or any(not isinstance(pair, dict) for pair in pairs):+ fail("request pairs must be an object array")+ return pairs+++def load_progress(+ path: Path,+ request_path: Path,+ pairs: list[dict[str, Any]],+) -> tuple[str, list[dict[str, Any]]]:+ request_sha256 = hashlib.sha256(request_path.read_bytes()).hexdigest()+ if not path.exists():+ return request_sha256, []+ value = load_json(path)+ if (not isinstance(value, dict) or value.get("schema") != PROGRESS_SCHEMA+ or value.get("request_sha256") != request_sha256):+ fail("evaluator progress does not match the request")+ results = value.get("results")+ if not isinstance(results, list) or len(results) > len(pairs):+ fail("invalid evaluator progress results")+ for result, pair in zip(results, pairs):+ if (not isinstance(result, dict) or result.get("case_id") != pair.get("case_id")+ or result.get("seed") != pair.get("seed")):+ fail("evaluator progress is not a valid pair prefix")+ return request_sha256, results+++def save_progress(path: Path, request_sha256: str, results: list[dict[str, Any]]) -> None:+ temporary = path.with_name(path.name + ".tmp")+ temporary.write_text(json.dumps({+ "schema": PROGRESS_SCHEMA,+ "request_sha256": request_sha256,+ "results": results,+ }, separators=(",", ":")) + "\n", encoding="utf-8")+ temporary.replace(path)+++def validate_settings(value: Any) -> dict[str, Any]:+ if not isinstance(value, dict) or value.get("schema") != "codegraff.learn.graff-evaluator.v1":+ fail("invalid evaluator settings schema")+ if value.get("provider") != "codex" or not isinstance(value.get("model"), str):+ fail("evaluator must pin a Codex model")+ if value.get("effort") not in {"low", "medium", "high", "xhigh", "max", "ultra"}:+ fail("invalid evaluator effort")+ for field in ("max_model_calls", "max_tool_calls", "max_attempts", "task_timeout_seconds"):+ if not isinstance(value.get(field), int) or value[field] <= 0:+ fail(f"invalid {field}")+ if value["max_attempts"] > 3:+ fail("max_attempts must be at most 3")+ return value+++def send(proc: subprocess.Popen[str], value: dict[str, Any], expected: str) -> dict[str, Any]:+ assert proc.stdin is not None and proc.stdout is not None+ proc.stdin.write(json.dumps(value, separators=(",", ":")) + "\n")+ proc.stdin.flush()+ for raw in proc.stdout:+ try:+ event = json.loads(raw)+ except json.JSONDecodeError:+ continue+ if not isinstance(event, dict):+ continue+ if event.get("type") == "error":+ fail(f"Graff error during {expected}: {event.get('message', 'unknown')}")+ if event.get("type") == expected:+ return event+ fail(f"Graff exited before {expected}")+++def safe_setup(root: Path, files: Any) -> None:+ if files is None:+ return+ if not isinstance(files, dict):+ fail("setup_files must be an object")+ resolved_root = root.resolve()+ for raw_name, content in files.items():+ if not isinstance(raw_name, str) or not isinstance(content, str):+ fail("setup file names and contents must be strings")+ target = (root / raw_name).resolve()+ if target == resolved_root or resolved_root not in target.parents:+ fail("setup path escapes task scratch")+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(content, encoding="utf-8")+++def executable_snapshot(source: Path) -> Path:+ target = Path(".learn-graff-bin").resolve()+ if not target.exists():+ shutil.copyfile(source, target)+ target.chmod(0o700)+ return target+++def check_case(case: dict[str, Any], text: str, cwd: Path) -> bool:+ check = case.get("check")+ if not isinstance(check, dict):+ fail("case check must be an object")+ if isinstance(check.get("exact"), str):+ return text.strip() == check["exact"]+ if isinstance(check.get("substring"), str):+ return check["substring"] in text+ if isinstance(check.get("cmd"), str):+ completed = subprocess.run(+ ["sh", "-c", check["cmd"]], cwd=cwd,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10, check=False,+ )+ return completed.returncode == 0+ fail("case has no supported check")+++def reported_cost_micros(event: dict[str, Any]) -> int:+ try:+ return max(0, round(float(event.get("cost_usd", 0.0) or 0.0) * 1_000_000))+ except (TypeError, ValueError, OverflowError):+ return 0+++def run_variant(+ graff: Path,+ settings: dict[str, Any],+ prompt: str,+ case: dict[str, Any],+ cwd: Path,+) -> dict[str, Any]:+ env = os.environ.copy()+ env["GRAFF_NO_TELEMETRY"] = "1"+ env["GRAFF_BEHAVIOR_TRACE"] = "0"+ env["HARNESS_CLIENT"] = "learn-evaluator"+ env.pop("OTEL_EXPORTER_OTLP_ENDPOINT", None)+ env.pop("GRAFF_OTEL_ENDPOINT", None)+ argv = [+ str(graff), "--json", "--model", "codex", "--no-resume", "--no-telemetry", "--yolo",+ "--max-model-calls", str(settings["max_model_calls"]),+ "--max-tool-calls", str(settings["max_tool_calls"]),+ "--system-prompt", prompt,+ ]+ started = time.monotonic()+ proc = subprocess.Popen(+ argv, cwd=cwd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.PIPE, text=True, bufsize=1,+ )+ timer = threading.Timer(settings["task_timeout_seconds"], proc.kill)+ timer.start()+ tool_calls = 0+ final: dict[str, Any] | None = None+ attempt_error: str | None = None+ cost_micros = 0+ try:+ model = send(proc, {+ "type": "set_model", "provider": settings["provider"], "model": settings["model"],+ }, "model")+ if model.get("provider") != settings["provider"] or model.get("model") != settings["model"]:+ fail("evaluator model pin was not honored")+ effort = send(proc, {"type": "set_effort", "level": settings["effort"]}, "effort")+ if effort.get("level") != settings["effort"] or effort.get("applies") is not True:+ fail("evaluator effort pin was not honored")+ assert proc.stdin is not None and proc.stdout is not None+ proc.stdin.write(json.dumps({"type": "user", "text": case["task"]}, separators=(",", ":")) + "\n")+ proc.stdin.flush()+ for raw in proc.stdout:+ try:+ event = json.loads(raw)+ except json.JSONDecodeError:+ continue+ if not isinstance(event, dict):+ continue+ if "cost_usd" in event:+ cost_micros = reported_cost_micros(event)+ if event.get("type") == "tool_call":+ tool_calls += 1+ elif event.get("type") == "error":+ attempt_error = f"evaluation turn failed: {event.get('message', 'unknown')}"+ break+ elif event.get("type") == "turn":+ if event.get("complete") is not True:+ attempt_error = "evaluation turn was incomplete"+ break+ final = event+ break+ finally:+ timer.cancel()+ if proc.stdin is not None:+ proc.stdin.close()+ try:+ proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait()+ latency_ms = max(0, round((time.monotonic() - started) * 1000))+ if attempt_error is not None:+ raise EvaluationAttemptError(+ attempt_error,+ latency_ms=latency_ms,+ tool_calls=tool_calls,+ cost_micros=cost_micros,+ )+ if final is None:+ raise EvaluationAttemptError(+ "evaluation produced no terminal turn",+ latency_ms=latency_ms,+ tool_calls=tool_calls,+ cost_micros=cost_micros,+ )+ passed = check_case(case, str(final.get("text", "")), cwd)+ return {+ "pass": passed,+ "score_ppm": 1_000_000 if passed else 0,+ "cost_micros": cost_micros,+ "latency_ms": latency_ms,+ "tool_calls": tool_calls,+ }+++def run_with_retries(+ graff: Path,+ settings: dict[str, Any],+ prompt: str,+ case: dict[str, Any],+ label: str,+) -> dict[str, Any]:+ prior = {"latency_ms": 0, "tool_calls": 0, "cost_micros": 0}+ last_error: EvaluationAttemptError | None = None+ for _attempt in range(settings["max_attempts"]):+ scratch = Path(tempfile.mkdtemp(prefix=f"learn-{label}-", dir="."))+ try:+ safe_setup(scratch, case.get("setup_files"))+ run = run_variant(graff, settings, prompt, case, scratch)+ for metric in prior:+ run[metric] += prior[metric]+ return run+ except EvaluationAttemptError as exc:+ last_error = exc+ prior["latency_ms"] += exc.latency_ms+ prior["tool_calls"] += exc.tool_calls+ prior["cost_micros"] += exc.cost_micros+ finally:+ shutil.rmtree(scratch, ignore_errors=True)+ fail(f"evaluation failed after bounded retries: {last_error}")+++def load_request_suite(request_path: Path, expected_schema: str) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:+ request = load_json(request_path)+ suite = load_json(Path(request.get("suite_path", ""))) if isinstance(request, dict) else None+ if not isinstance(request, dict) or request.get("schema") != expected_schema:+ fail("invalid evaluation request schema")+ if not isinstance(suite, dict) or suite.get("schema") != "codegraff.learn.suite.v1":+ fail("invalid suite schema")+ cases = suite.get("cases")+ if not isinstance(cases, list):+ fail("suite cases must be an array")+ case_map = {case.get("id"): case.get("payload") for case in cases if isinstance(case, dict)}+ return request, suite, case_map+++def case_for_pair(pair: Any, case_map: dict[str, Any]) -> dict[str, Any]:+ if not isinstance(pair, dict) or pair.get("case_id") not in case_map:+ fail("pair references an unknown case")+ case = case_map[pair["case_id"]]+ if not isinstance(case, dict) or not isinstance(case.get("task"), str):+ fail("case payload must contain a task")+ return case+++def evaluate(settings_path: Path, graff: Path, request_path: Path, response_path: Path) -> None:+ settings = validate_settings(load_json(settings_path))+ request, _, case_map = load_request_suite(request_path, REQUEST_SCHEMA)+ parent = Path(request["parent"]["path"]).read_text(encoding="utf-8")+ child = Path(request["child"]["path"]).read_text(encoding="utf-8")+ graff_executable = executable_snapshot(graff)+ pairs = request_pairs(request)+ progress_path = Path(".paired-progress.json")+ request_sha256, results = load_progress(progress_path, request_path, pairs)+ for pair in pairs[len(results):]:+ case = case_for_pair(pair, case_map)+ runs: dict[str, dict[str, Any]] = {}+ order = (("parent", parent), ("child", child))+ if int(str(pair.get("seed", "0"))[-1], 16) % 2:+ order = tuple(reversed(order))+ for label, prompt in order:+ runs[label] = run_with_retries(graff_executable, settings, prompt, case, label)+ parent_run = runs["parent"]+ child_run = runs["child"]+ results.append({+ "case_id": pair["case_id"], "seed": pair["seed"],+ "parent_pass": parent_run["pass"], "child_pass": child_run["pass"],+ "parent_score_ppm": parent_run["score_ppm"], "child_score_ppm": child_run["score_ppm"],+ "parent_cost_micros": parent_run["cost_micros"], "child_cost_micros": child_run["cost_micros"],+ "parent_latency_ms": parent_run["latency_ms"], "child_latency_ms": child_run["latency_ms"],+ "latency_measured": True,+ "tool_calls_measured": True,+ "parent_tool_calls": parent_run["tool_calls"], "child_tool_calls": child_run["tool_calls"],+ })+ save_progress(progress_path, request_sha256, results)+ response = {+ "schema": RESPONSE_SCHEMA,+ "trial_id": request.get("trial_id"),+ "candidate_index": request.get("candidate_index"),+ "cohort_id": request.get("cohort_id"),+ "suite_sha256": request.get("suite_sha256"),+ "parent_id": request.get("parent", {}).get("id"),+ "child_id": request.get("child", {}).get("id"),+ "pairs": results,+ }+ response_path.write_text(json.dumps(response, separators=(",", ":")) + "\n", encoding="utf-8")+++def evaluate_baseline(settings_path: Path, graff: Path, request_path: Path, response_path: Path) -> None:+ settings = validate_settings(load_json(settings_path))+ request, _, case_map = load_request_suite(request_path, BASELINE_REQUEST_SCHEMA)+ parent = Path(request["parent"]["path"]).read_text(encoding="utf-8")+ graff_executable = executable_snapshot(graff)+ pairs = request_pairs(request)+ progress_path = Path(".baseline-progress.json")+ request_sha256, results = load_progress(progress_path, request_path, pairs)+ for pair in pairs[len(results):]:+ case = case_for_pair(pair, case_map)+ run = run_with_retries(graff_executable, settings, parent, case, "baseline")+ results.append({+ "case_id": pair["case_id"], "seed": pair["seed"],+ "pass": run["pass"], "score_ppm": run["score_ppm"],+ "cost_micros": run["cost_micros"], "latency_ms": run["latency_ms"],+ "latency_measured": True, "tool_calls_measured": True,+ "tool_calls": run["tool_calls"],+ })+ save_progress(progress_path, request_sha256, results)+ response = {+ "schema": BASELINE_RESPONSE_SCHEMA,+ "trial_id": request.get("trial_id"),+ "cohort_id": request.get("cohort_id"),+ "suite_sha256": request.get("suite_sha256"),+ "parent_id": request.get("parent", {}).get("id"),+ "pairs": results,+ }+ response_path.write_text(json.dumps(response, separators=(",", ":")) + "\n", encoding="utf-8")+++def evaluate_primary(settings_path: Path, graff: Path, request_path: Path, response_path: Path) -> None:+ settings = validate_settings(load_json(settings_path))+ request, _, case_map = load_request_suite(request_path, PRIMARY_REQUEST_SCHEMA)+ baseline = load_json(Path(request.get("baseline", {}).get("path", "")))+ if not isinstance(baseline, dict) or baseline.get("schema") != BASELINE_RESPONSE_SCHEMA:+ fail("invalid primary baseline")+ pairs = request_pairs(request)+ baseline_pairs = baseline.get("pairs")+ if not isinstance(baseline_pairs, list) or len(baseline_pairs) != len(pairs):+ fail("primary baseline pair count mismatch")+ child = Path(request["child"]["path"]).read_text(encoding="utf-8")+ graff_executable = executable_snapshot(graff)+ progress_path = Path(".primary-progress.json")+ request_sha256, results = load_progress(progress_path, request_path, pairs)+ for pair, parent_run in zip(pairs[len(results):], baseline_pairs[len(results):]):+ case = case_for_pair(pair, case_map)+ if (not isinstance(parent_run, dict)+ or parent_run.get("case_id") != pair.get("case_id")+ or parent_run.get("seed") != pair.get("seed")):+ fail("primary baseline pair mismatch")+ child_run = run_with_retries(graff_executable, settings, child, case, "child")+ results.append({+ "case_id": pair["case_id"], "seed": pair["seed"],+ "parent_pass": parent_run.get("pass"), "child_pass": child_run["pass"],+ "parent_score_ppm": parent_run.get("score_ppm"), "child_score_ppm": child_run["score_ppm"],+ "parent_cost_micros": parent_run.get("cost_micros", 0), "child_cost_micros": child_run["cost_micros"],+ "parent_latency_ms": parent_run.get("latency_ms", 0), "child_latency_ms": child_run["latency_ms"],+ "latency_measured": bool(parent_run.get("latency_measured")),+ "tool_calls_measured": bool(parent_run.get("tool_calls_measured")),+ "parent_tool_calls": parent_run.get("tool_calls", 0), "child_tool_calls": child_run["tool_calls"],+ })+ save_progress(progress_path, request_sha256, results)+ response = {+ "schema": PRIMARY_RESPONSE_SCHEMA,+ "trial_id": request.get("trial_id"),+ "candidate_index": request.get("candidate_index"),+ "cohort_id": request.get("cohort_id"),+ "suite_sha256": request.get("suite_sha256"),+ "parent_id": request.get("parent_id"),+ "child_id": request.get("child", {}).get("id"),+ "pairs": results,+ }+ response_path.write_text(json.dumps(response, separators=(",", ":")) + "\n", encoding="utf-8")+++def main() -> None:+ if len(sys.argv) == 3 and sys.argv[1] == "--validate":+ validate_settings(load_json(Path(sys.argv[2])))+ print("Graff evaluator settings valid")+ return+ if len(sys.argv) != 6:+ fail("usage: learn_graff_evaluator.py SETTINGS GRAFF OPERATION REQUEST RESPONSE")+ settings_path, graff_path, operation, request_path, response_path = sys.argv[1:]+ operations = {+ "evaluate": evaluate,+ "baseline": evaluate_baseline,+ "evaluate_primary": evaluate_primary,+ }+ handler = operations.get(operation)+ if handler is None:+ fail("unsupported evaluator operation")+ handler(Path(settings_path), Path(graff_path), Path(request_path), Path(response_path))+++if __name__ == "__main__":+ try:+ main()+ except SystemExit:+ raise+ except Exception as exc:+ fail(f"unexpected {type(exc).__name__}: {exc}")diff --git a/examples/learn_graff_mutator.py b/examples/learn_graff_mutator.pynew file mode 100755index 00000000..85356c99--- /dev/null+++ b/examples/learn_graff_mutator.py@@ -0,0 +1,306 @@+#!/usr/bin/env python3+"""Typed four-arm Graff mutator for `graff learn`.++The adapter sends only the configured target excerpt and mutation instruction+to the selected Codex model. A local deterministic patcher inserts the returned+clause; the complete parent genome never leaves this process.+"""++from __future__ import annotations++import hashlib+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+from typing import Any+++REQUEST_SCHEMA = "codegraff.learn.mutation.request.v1"+RESPONSE_SCHEMA = "codegraff.learn.mutation.response.v1"+EFFORTS = {"low", "medium", "high", "xhigh", "max", "ultra"}+++def fail(message: str) -> "NoReturn":+ print(f"learn_graff_mutator: {message}", file=sys.stderr)+ raise SystemExit(2)+++def load_json(path: Path) -> Any:+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:+ fail(f"cannot read {path}: {exc}")+++def validate_arms(value: Any) -> tuple[list[dict[str, Any]], list[str], dict[str, str], int, int]:+ if not isinstance(value, dict) or value.get("schema") != "codegraff.learn.graff-arms.v1":+ fail("invalid arms schema")+ if value.get("template_egress") is not True:+ fail("arms must explicitly acknowledge template_egress")+ protected = value.get("protected_substrings")+ if not isinstance(protected, list) or not protected or any(not isinstance(item, str) or not item for item in protected):+ fail("protected_substrings must be a non-empty string array")+ maximum_changed = value.get("maximum_changed_bytes")+ maximum_total = value.get("maximum_total_bytes")+ if not isinstance(maximum_changed, int) or not 64 <= maximum_changed <= 4096:+ fail("maximum_changed_bytes must be between 64 and 4096")+ if not isinstance(maximum_total, int) or not 1024 <= maximum_total <= 1_048_576:+ fail("maximum_total_bytes must be between 1024 and 1048576")+ targets = value.get("targets")+ if not isinstance(targets, dict) or not targets:+ fail("targets must be a non-empty object")+ if any(not isinstance(key, str) or not key or not isinstance(text, str) or not text+ for key, text in targets.items()):+ fail("targets must map non-empty names to non-empty paragraphs")+ arms = value.get("arms")+ if not isinstance(arms, list) or len(arms) != 4:+ fail("exactly four arms are required")+ seen: set[str] = set()+ for index, arm in enumerate(arms):+ if not isinstance(arm, dict) or arm.get("index") != index:+ fail("arm indexes must be exactly 0..3")+ required = ("id", "provider", "model", "effort", "focus", "target", "placement")+ if any(not isinstance(arm.get(key), str) or not arm[key] for key in required):+ fail(f"arm {index} has missing fields")+ if arm["id"] in seen or arm["provider"] != "codex" or arm["effort"] not in EFFORTS:+ fail(f"arm {index} is duplicate or unsupported")+ if arm["placement"] not in {"append", "replace"}:+ fail(f"arm {index} has an unsupported placement")+ fixed_clause = arm.get("fixed_clause")+ if fixed_clause is not None and (not isinstance(fixed_clause, str) or not fixed_clause):+ fail(f"arm {index} has an invalid fixed_clause")+ if arm["target"] not in targets:+ fail(f"arm {index} names an unknown target")+ seen.add(arm["id"])+ if arms[0]["model"] != "gpt-5.6-sol":+ fail("arm 0 must be the gpt-5.6-sol quality anchor")+ if arms[3]["model"] != "gpt-5.6-terra" or arms[3]["effort"] != "medium":+ fail("arm 3 must be the medium-effort Terra challenger")+ return arms, protected, targets, maximum_changed, maximum_total+++def request(proc: subprocess.Popen[str], value: dict[str, Any], expected: str) -> dict[str, Any]:+ assert proc.stdin is not None and proc.stdout is not None+ proc.stdin.write(json.dumps(value, separators=(",", ":")) + "\n")+ proc.stdin.flush()+ for raw in proc.stdout:+ try:+ event = json.loads(raw)+ except json.JSONDecodeError:+ continue+ if not isinstance(event, dict):+ continue+ if event.get("type") == "error":+ fail(f"Graff error during {expected}: {event.get('message', 'unknown')}")+ if event.get("type") == expected:+ return event+ fail(f"Graff exited before {expected}")+++def changed_bytes(old: str, new: str) -> int:+ old_bytes, new_bytes = old.encode("utf-8"), new.encode("utf-8")+ prefix = 0+ while prefix < min(len(old_bytes), len(new_bytes)) and old_bytes[prefix] == new_bytes[prefix]:+ prefix += 1+ suffix = 0+ while (suffix < len(old_bytes) - prefix and suffix < len(new_bytes) - prefix+ and old_bytes[-1 - suffix] == new_bytes[-1 - suffix]):+ suffix += 1+ return len(old_bytes) + len(new_bytes) - 2 * prefix - 2 * suffix+++def apply_patch(+ raw: str,+ parent: str,+ target: str,+ protected: list[str],+ maximum_changed: int,+ maximum_total: int,+ placement: str = "append",+) -> tuple[str | None, list[str]]:+ violations: list[str] = []+ try:+ patch = json.loads(raw.strip())+ except json.JSONDecodeError:+ return None, ["the response was not one JSON object"]+ if not isinstance(patch, dict) or set(patch) != {"clause"}:+ return None, ["the JSON object must contain only clause"]+ clause = patch.get("clause")+ if not isinstance(clause, str):+ return None, ["clause must be a string"]+ if not clause or clause != clause.strip() or "\0" in clause:+ violations.append("clause was empty, padded, or contained a NUL byte")+ if "\n" in clause:+ violations.append("clause contained a newline")+ new = target + " " + clause if placement == "append" else clause+ if changed_bytes(target, new) > maximum_changed:+ violations.append(f"the patch changed more than {maximum_changed} bytes")+ if violations:+ return None, violations+ child = parent.replace(target, new, 1)+ if len(child.encode("utf-8")) > maximum_total:+ violations.append(f"the merged prompt exceeded {maximum_total} UTF-8 bytes")+ changed_protected = [item for item in protected if child.count(item) != parent.count(item)]+ if changed_protected:+ violations.append(f"the patch changed {len(changed_protected)} protected substrings")+ return (None if violations else child), violations+++def executable_snapshot(source: Path) -> Path:+ target = Path(".learn-graff-bin").resolve()+ shutil.copyfile(source, target)+ target.chmod(0o700)+ return target+++def mutate(arms_path: Path, graff: Path, request_path: Path, response_path: Path) -> None:+ request_value = load_json(request_path)+ if not isinstance(request_value, dict) or request_value.get("schema") != REQUEST_SCHEMA:+ fail("invalid mutation request schema")+ index = request_value.get("candidate_index")+ if not isinstance(index, int) or not 0 <= index < 4:+ fail("candidate_index must be 0..3")+ arms, protected, targets, maximum_changed, configured_total = validate_arms(load_json(arms_path))+ arm = arms[index]+ parent_path = request_value.get("parent", {}).get("path")+ child_path = request_value.get("child_path")+ maximum = request_value.get("maximum_bytes")+ instruction = request_value.get("instruction")+ if not isinstance(parent_path, str) or not isinstance(child_path, str):+ fail("invalid genome paths")+ if not isinstance(maximum, int) or maximum <= 0 or not isinstance(instruction, str):+ fail("invalid mutation limits")+ parent = Path(parent_path).read_text(encoding="utf-8")+ missing_parent = [item for item in protected if item not in parent]+ if missing_parent:+ fail("parent prompt is missing configured protected substrings")+ target = targets[arm["target"]]+ if parent.count(target) != 1:+ fail(f"configured target for {arm['id']} must occur exactly once in the parent")+ total_limit = min(maximum, configured_total)++ system = (+ "You draft one concise clause for a coding-agent system prompt. Return ONLY one "+ "strict JSON object with exactly one string field: clause. The local caller applies "+ "it at one fixed target. No analysis, preface, Markdown fence, secrets, or "+ "repository-specific data."+ )+ task = f"""Draft one behavioral clause.++Mutation instruction:+{instruction}++Arm focus:+{arm['focus']}++Success criteria:+- the clause is self-contained, unambiguous, and has no newline+- do not repeat or rewrite the existing paragraph+- the local patch placement is {arm['placement']}+- the local insertion may add at most {maximum_changed} UTF-8 bytes+- keep the locally merged complete prompt within {total_limit} UTF-8 bytes+- return exactly {{"clause":"..."}}++Target paragraph:+<target>+{target}+</target>+"""+ fixed_clause = arm.get("fixed_clause")+ if fixed_clause is not None:+ child, violations = apply_patch(+ json.dumps({"clause": fixed_clause}), parent, target, protected, maximum_changed, total_limit,+ arm["placement"],+ )+ else:+ env = os.environ.copy()+ env["GRAFF_NO_TELEMETRY"] = "1"+ env["GRAFF_BEHAVIOR_TRACE"] = "0"+ env["HARNESS_CLIENT"] = "learn-mutator"+ env.pop("OTEL_EXPORTER_OTLP_ENDPOINT", None)+ env.pop("GRAFF_OTEL_ENDPOINT", None)+ graff_executable = executable_snapshot(graff)+ argv = [+ str(graff_executable), "--json", "--model", "codex", "--no-resume", "--no-telemetry",+ "--max-model-calls", "2", "--max-tool-calls", "0", "--system-prompt", system,+ ]+ proc = subprocess.Popen(+ argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ text=True, bufsize=1, env=env,+ )+ try:+ model_event = request(proc, {+ "type": "set_model", "provider": arm["provider"], "model": arm["model"],+ }, "model")+ if model_event.get("provider") != arm["provider"] or model_event.get("model") != arm["model"]:+ fail(f"model pin was not honored for {arm['id']}")+ effort_event = request(proc, {"type": "set_effort", "level": arm["effort"]}, "effort")+ if effort_event.get("level") != arm["effort"] or effort_event.get("applies") is not True:+ fail(f"effort pin was not honored for {arm['id']}")+ turn = request(proc, {"type": "user", "text": task}, "turn")+ child, violations = apply_patch(+ str(turn.get("text", "")), parent, target, protected, maximum_changed, total_limit,+ arm["placement"],+ )+ if violations:+ correction = (+ "Your clause failed deterministic validation: "+ + "; ".join(violations)+ + ". Return ONLY a corrected JSON object with exactly one clause string. "+ + "Use one concise clause with no newline or commentary."+ )+ turn = request(proc, {"type": "user", "text": correction}, "turn")+ child, violations = apply_patch(+ str(turn.get("text", "")), parent, target, protected, maximum_changed, total_limit,+ arm["placement"],+ )+ finally:+ if proc.stdin is not None:+ proc.stdin.close()+ try:+ proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait()+ validation_fallback = child is None or bool(violations)+ if validation_fallback:+ # Invalid model text never becomes a genome. An unchanged parent is a+ # safe, deterministic non-contender that lets other arms finish.+ child = parent+ assert child is not None+ child_bytes = child.encode("utf-8")+ Path(child_path).write_bytes(child_bytes)+ response = {+ "schema": RESPONSE_SCHEMA,+ "trial_id": request_value.get("trial_id"),+ "candidate_index": index,+ "parent_id": request_value.get("parent", {}).get("id"),+ "child_path": child_path,+ "child_sha256": hashlib.sha256(child_bytes).hexdigest(),+ "description": (+ f"{arm['id']} ({arm['model']}/{arm['effort']})"+ + ("; frozen confirmation" if fixed_clause is not None else "")+ + ("; validation fallback: parent" if validation_fallback else "")+ ),+ }+ response_path.write_text(json.dumps(response, separators=(",", ":")) + "\n", encoding="utf-8")+++def main() -> None:+ if len(sys.argv) == 3 and sys.argv[1] == "--validate":+ validate_arms(load_json(Path(sys.argv[2])))+ print("four Graff mutation arms valid")+ return+ if len(sys.argv) != 6:+ fail("usage: learn_graff_mutator.py ARMS GRAFF mutate REQUEST RESPONSE")+ arms_path, graff_path, operation, request_path, response_path = sys.argv[1:]+ if operation != "mutate":+ fail("only mutate is supported")+ mutate(Path(arms_path), Path(graff_path), Path(request_path), Path(response_path))+++if __name__ == "__main__":+ main()diff --git a/examples/learn_graff_suites.py b/examples/learn_graff_suites.pynew file mode 100644index 00000000..c13b2f24--- /dev/null+++ b/examples/learn_graff_suites.py@@ -0,0 +1,418 @@+#!/usr/bin/env python3+"""Case builders for the four-arm Graff prompt tournament."""++from __future__ import annotations++import json+import secrets+from typing import Any+++def _case(+ case_id: str,+ task: str,+ check: dict[str, str],+ setup: dict[str, str] | None = None,+ *,+ critical: bool = False,+) -> dict[str, Any]:+ payload: dict[str, Any] = {"id": case_id, "task": task, "check": check}+ if setup is not None:+ payload["setup_files"] = setup+ result: dict[str, Any] = {"id": case_id, "payload": payload}+ if critical:+ result["critical"] = True+ return result+++def _exact(case_id: str, task: str, expected: str, setup: dict[str, str] | None = None) -> dict[str, Any]:+ return _case(case_id, task, {"exact": expected}, setup)+++def _mutation(case_id: str, task: str, command: str, setup: dict[str, str] | None = None) -> dict[str, Any]:+ return _case(case_id, task, {"cmd": command}, setup, critical=True)+++def primary_cases() -> list[dict[str, Any]]:+ """Sixty randomized public cases, including twenty edit-economy probes."""+ sort_values = [secrets.randbelow(80) + 1 for _ in range(3)]+ while len(set(sort_values)) != 3:+ sort_values = [secrets.randbelow(80) + 1 for _ in range(3)]+ nested_maximum = secrets.randbelow(70) + 20+ selected_price = secrets.randbelow(70) + 20+ desired_threshold = secrets.randbelow(70) + 20+ factor_a, factor_b = secrets.randbelow(30) + 11, secrets.randbelow(30) + 11+ ledger_values = [secrets.randbelow(50) + 10 for _ in range(4)]+ sum_values = [secrets.randbelow(40) + 5 for _ in range(4)]+ cases = [+ # Semantic boundaries and exactness.+ _exact(+ "semantic-count-unterminated",+ "Count the lines of text in notes.txt and reply with only the number.",+ "3",+ {"notes.txt": "alpha\nbravo\ncharlie"},+ ),+ _exact(+ "semantic-count-empty",+ "Count the lines of text in empty.txt and reply with only the number.",+ "0",+ {"empty.txt": ""},+ ),+ _exact(+ "semantic-count-blank-record",+ "Count all text lines in stanza.txt, including blank lines, and reply with only the number.",+ "3",+ {"stanza.txt": "alpha\n\ncharlie\n"},+ ),+ _mutation(+ "semantic-exact-no-newline",+ "Create status.txt containing exactly the five characters READY with no trailing newline.",+ "test \"$(cat status.txt)\" = READY && test \"$(wc -c < status.txt)\" -eq 5",+ ),+ _mutation(+ "semantic-preserve-unterminated",+ "In phrase.txt replace beta with BETA while preserving every other byte, including the lack of a trailing newline.",+ "test \"$(cat phrase.txt)\" = 'alpha\nBETA' && test \"$(wc -c < phrase.txt)\" -eq 10",+ {"phrase.txt": "alpha\nbeta"},+ ),+ _mutation(+ "semantic-numeric-sort",+ "Sort the integers in unsorted.txt numerically into sorted.txt, one per line.",+ "test \"$(cat sorted.txt)\" = '" + "\n".join(map(str, sorted(sort_values))) + "'",+ {"unsorted.txt": "\n".join(map(str, reversed(sort_values))) + "\n"},+ ),+ _exact(+ "semantic-csv-header",+ "Reply with only the sum of the amount column in sales.csv, excluding the header.",+ "60",+ {"sales.csv": "item,amount\na,10\nb,20\nc,30\n"},+ ),+ _exact(+ "semantic-count-crlf",+ "Count the text lines in windows.txt and reply with only the number.",+ "2",+ {"windows.txt": "red\r\nblue\r\n"},+ ),+ _mutation(+ "semantic-preserve-terminal-newline",+ "In word.txt uppercase only gamma while preserving its trailing newline.",+ "test \"$(cat word.txt)\" = 'alpha GAMMA' && test \"$(wc -c < word.txt)\" -eq 12",+ {"word.txt": "alpha gamma\n"},+ ),+ _exact(+ "semantic-nested-number",+ "Read limits.json and reply with only the integer at worker.maximum.",+ str(nested_maximum),+ {"limits.json": json.dumps({"worker": {"minimum": 3, "maximum": nested_maximum}}) + "\n"},+ ),++ # Exact edit transactions and state preservation.+ _mutation(+ "edit-replace-all",+ "In greeting.txt change every standalone world to graff, preserving all other text.",+ "test \"$(cat greeting.txt)\" = 'hello graff\ngoodbye graff\nkeep'",+ {"greeting.txt": "hello world\ngoodbye world\nkeep\n"},+ ),+ _mutation(+ "edit-replace-first-only",+ "In queue.txt change only the first occurrence of pending to ready, leaving the later occurrence unchanged.",+ "test \"$(sed -n 1p queue.txt)\" = ready && test \"$(sed -n 2p queue.txt)\" = pending && test \"$(sed -n 3p queue.txt)\" = keep",+ {"queue.txt": "pending\npending\nkeep\n"},+ ),+ _mutation(+ "edit-append-preserve",+ "Append the line gamma to log.txt, keeping all existing lines unchanged.",+ "test \"$(cat log.txt)\" = 'alpha\nbeta\ngamma'",+ {"log.txt": "alpha\nbeta\n"},+ ),+ _mutation(+ "edit-delete-stable",+ "Remove every line containing DROP from data.txt without reordering the remaining lines.",+ "test \"$(cat data.txt)\" = 'keep1\nkeep2\nkeep3'",+ {"data.txt": "keep1\nDROP me\nkeep2\nDROP again\nkeep3\n"},+ ),+ _mutation(+ "edit-dedupe-stable",+ "Remove duplicate lines from colors.txt in place, keeping first-occurrence order.",+ "test \"$(cat colors.txt)\" = 'red\nblue\ngreen'",+ {"colors.txt": "red\nblue\nred\ngreen\nblue\n"},+ ),+ _mutation(+ "edit-target-exact-key",+ "In app.env change only the exact line mode=dev to mode=prod; do not change mode_backup.",+ "test \"$(sed -n 1p app.env)\" = mode=prod && test \"$(sed -n 2p app.env)\" = mode_backup=dev",+ {"app.env": "mode=dev\nmode_backup=dev\n"},+ ),+ _mutation(+ "edit-already-satisfied",+ "Ensure flags.conf contains exactly enabled=true. If it already does, leave it unchanged.",+ "test \"$(cat flags.conf)\" = enabled=true && test \"$(wc -c < flags.conf)\" -eq 13",+ {"flags.conf": "enabled=true\n"},+ ),+ _mutation(+ "edit-remove-comments",+ "Remove lines beginning with # from settings.ini without changing other lines.",+ "test \"$(cat settings.ini)\" = 'mode=fast\nlevel=2'",+ {"settings.ini": "# generated\nmode=fast\n# keep out\nlevel=2\n"},+ ),+ _mutation(+ "edit-collapse-adjacent-duplicates",+ "Collapse adjacent duplicate lines in sequence.txt, preserving first-occurrence order.",+ "test \"$(cat sequence.txt)\" = 'a\nb\na\nc'",+ {"sequence.txt": "a\na\nb\nb\na\nc\nc\n"},+ ),+ _mutation(+ "edit-noop-exact",+ "Ensure policy.txt contains exactly allow=yes. It already does, so do not rewrite it.",+ "test \"$(cat policy.txt)\" = allow=yes && test \"$(wc -c < policy.txt)\" -eq 10",+ {"policy.txt": "allow=yes\n"},+ ),++ # Independent evidence and dependency ordering.+ _exact(+ "dependency-compare-json",+ "Read east.json and west.json and reply with only the region whose latency value is lower.",+ "east",+ {"east.json": '{"latency":17}\n', "west.json": '{"latency":29}\n'},+ ),+ _exact(+ "dependency-sum-two-files",+ "Reply with only the sum of all integers across left.txt and right.txt.",+ "42",+ {"left.txt": "4\n8\n", "right.txt": "10\n20\n"},+ ),+ _mutation(+ "dependency-merge-unique",+ "Combine a.txt and b.txt into merged.txt, sorted alphabetically with duplicate lines removed.",+ "test \"$(cat merged.txt)\" = 'apple\nbanana\ncherry\ndate'",+ {"a.txt": "banana\napple\ncherry\n", "b.txt": "cherry\ndate\napple\n"},+ ),+ _exact(+ "dependency-keyed-lookup",+ "Use current.txt to choose the matching key in values.txt, then reply with only its numeric value.",+ "73",+ {"current.txt": "blue\n", "values.txt": "red 41\nblue 73\ngreen 19\n"},+ ),+ _mutation(+ "dependency-sync-config",+ "Read desired.json and update only the port value in service.json to match it.",+ "grep -q '\"host\":\"local\"' service.json && grep -Eq '\"port\"[[:space:]]*:[[:space:]]*4117' service.json",+ {"desired.json": '{"port":4117}\n', "service.json": '{"host":"local","port":3000}\n'},+ ),+ _mutation(+ "dependency-set-intersection",+ "Write common.txt with the values present in both first.txt and second.txt, sorted, one per line.",+ "test \"$(cat common.txt)\" = 'blue\ngreen'",+ {"first.txt": "red\nblue\ngreen\n", "second.txt": "green\nblue\ngold\n"},+ ),+ _exact(+ "dependency-max-three-files",+ "Read one.txt, two.txt, and three.txt and reply with only the largest integer found.",+ "91",+ {"one.txt": "17\n", "two.txt": "91\n", "three.txt": "44\n"},+ ),+ _exact(+ "dependency-selected-price",+ "Use selected.txt to choose the matching item in prices.txt and reply with only its price.",+ str(selected_price),+ {"selected.txt": "pear\n", "prices.txt": f"apple 31\npear {selected_price}\nplum 52\n"},+ ),+ _mutation(+ "dependency-combine-columns",+ "Pair each line of names.txt with the same-position line of scores.txt in result.txt as name=score.",+ "test \"$(cat result.txt)\" = 'ada=8\nlin=13\nmax=21'",+ {"names.txt": "ada\nlin\nmax\n", "scores.txt": "8\n13\n21\n"},+ ),+ _mutation(+ "dependency-copy-threshold",+ "Read desired.conf and update only threshold in runtime.conf to match it.",+ f"grep -q '^name=worker$' runtime.conf && grep -q '^threshold={desired_threshold}$' runtime.conf",+ {"desired.conf": f"threshold={desired_threshold}\n", "runtime.conf": "name=worker\nthreshold=40\n"},+ ),++ # Outcome stopping and minimum sufficient evidence.+ _exact("economy-arithmetic", f"Compute {factor_a}*{factor_b} and reply with only the number.", str(factor_a * factor_b)),+ _exact(+ "economy-single-extract",+ "Read cfg.json and reply with only the value of service.port.",+ "4117",+ {"cfg.json": '{"service":{"port":4117},"debug":false}\n'},+ ),+ _mutation(+ "economy-simple-create",+ "Create out.txt whose entire content is exactly hello-dgm with no trailing newline.",+ "test \"$(cat out.txt)\" = hello-dgm && test \"$(wc -c < out.txt)\" -eq 9",+ ),+ _mutation(+ "economy-zero-byte",+ "Create blank.bin containing exactly zero bytes.",+ "test -f blank.bin && test ! -s blank.bin",+ ),+ _mutation(+ "economy-simple-edit",+ "In title.txt replace draft with final, leaving everything else unchanged.",+ "test \"$(cat title.txt)\" = 'status: final'",+ {"title.txt": "status: draft\n"},+ ),+ _mutation(+ "economy-ledger-write",+ "Sum the numeric second column of ledger.txt and write only the total to total.txt.",+ f"test \"$(cat total.txt)\" = {sum(ledger_values)}",+ {"ledger.txt": "\n".join(f"item{index} {value}" for index, value in enumerate(ledger_values)) + "\n"},+ ),+ _exact(+ "economy-already-done",+ "Read state.txt. If it says complete, reply with only done.",+ "done",+ {"state.txt": "complete\n"},+ ),+ _mutation(+ "economy-sum-write",+ "Sum the integers in values.txt and write only the total to sum.txt.",+ f"test \"$(cat sum.txt)\" = {sum(sum_values)}",+ {"values.txt": "\n".join(map(str, sum_values)) + "\n"},+ ),+ _mutation(+ "economy-uppercase-write",+ "Read label.txt and write its uppercase text to upper.txt with no trailing newline.",+ "test \"$(cat upper.txt)\" = ORBIT && test \"$(wc -c < upper.txt)\" -eq 5",+ {"label.txt": "orbit\n"},+ ),+ _mutation(+ "economy-filter-write",+ "Write clean.txt from raw.txt with lines beginning TEMP: removed, preserving all others.",+ "test \"$(cat clean.txt)\" = 'first\nsecond\nthird'",+ {"raw.txt": "first\nTEMP:x\nsecond\nTEMP:y\nthird\n"},+ ),+ ]+ for index in range(5):+ token = secrets.token_hex(3)+ name = f"ready{index}.conf"+ cases.append(_mutation(+ f"edit-noop-random-{index}",+ f"Ensure {name} contains exactly state={token}. It already does, so leave it unchanged.",+ f"test \"$(cat {name})\" = state={token} && test \"$(wc -c < {name})\" -eq {len(token) + 7}",+ {name: f"state={token}\n"},+ ))+ for index in range(5):+ cases.append(_mutation(+ f"edit-filter-random-{index}",+ f"Remove lines beginning DROP: from filter{index}.txt without reordering the other lines.",+ f"test \"$(cat filter{index}.txt)\" = 'a{index}\nb{index}\nc{index}'",+ {f"filter{index}.txt": f"a{index}\nDROP:x\nb{index}\nDROP:y\nc{index}\n"},+ ))+ for index in range(5):+ cases.append(_mutation(+ f"edit-dedupe-random-{index}",+ f"Deduplicate ids{index}.txt in place, preserving first-occurrence order.",+ f"test \"$(cat ids{index}.txt)\" = 'k{index}a\nk{index}b\nk{index}c'",+ {f"ids{index}.txt": f"k{index}a\nk{index}b\nk{index}a\nk{index}c\nk{index}b\n"},+ ))+ for index in range(5):+ desired_value = secrets.randbelow(8000) + 1000+ cases.append(_mutation(+ f"edit-copy-random-{index}",+ f"Read desired{index}.ini and update only limit in runtime{index}.ini to match it.",+ f"grep -q '^name=worker{index}$' runtime{index}.ini && grep -q '^limit={desired_value}$' runtime{index}.ini",+ {+ f"desired{index}.ini": f"limit={desired_value}\n",+ f"runtime{index}.ini": f"name=worker{index}\nlimit=10\n",+ },+ ))+ return cases+++def fresh_holdout() -> list[dict[str, Any]]:+ """Forty randomized, structurally shifted cases kept away from mutation."""+ token = secrets.token_hex(5)+ product_a, product_b = secrets.randbelow(30) + 11, secrets.randbelow(30) + 11+ port = secrets.randbelow(7000) + 2000+ numbers = [secrets.randbelow(40) + 10 for _ in range(4)]+ desired = secrets.randbelow(7000) + 2000+ cases = [+ _exact("fresh-sem-crlf-records", "Count the text lines in routes.txt and reply with only the number.", "3", {"routes.txt": "north\r\nsouth\r\neast"}),+ _exact("fresh-sem-blank-record", "Count all lines in verse.txt, including blank lines, and reply with only the number.", "3", {"verse.txt": "one\n\nthree"}),+ _mutation("fresh-sem-exact-token", f"Create token.dat containing exactly {token} with no trailing newline.", f"test \"$(cat token.dat)\" = {token} && test \"$(wc -c < token.dat)\" -eq {len(token)}"),+ _mutation("fresh-sem-preserve-newline", "In pair.txt replace right with RIGHT while preserving its trailing newline.", "test \"$(cat pair.txt)\" = 'left\nRIGHT' && test \"$(wc -c < pair.txt)\" -eq 11", {"pair.txt": "left\nright\n"}),+ _exact("fresh-sem-tsv-header", "Reply with only the sum of the amount column in report.tsv, excluding its header.", "45", {"report.tsv": "name\tamount\na\t12\nb\t14\nc\t19\n"}),+ _mutation("fresh-sem-preserve-terminal", "In tail.txt uppercase only end while preserving its trailing newline.", "test \"$(cat tail.txt)\" = 'start\nEND' && test \"$(wc -c < tail.txt)\" -eq 10", {"tail.txt": "start\nend\n"}),+ _exact("fresh-sem-nested-value", "Read quota.json and reply with only pool.available.", "29", {"quota.json": '{"pool":{"used":11,"available":29}}\n'}),++ _mutation("fresh-edit-last-only", "In stages.txt change only the last pending line to ready.", "test \"$(sed -n 1p stages.txt)\" = pending && test \"$(sed -n 2p stages.txt)\" = pending && test \"$(sed -n 3p stages.txt)\" = ready", {"stages.txt": "pending\npending\npending\n"}),+ _mutation("fresh-edit-append-unterminated", "Append the line dusk to day.txt while preserving its existing two lines.", "test \"$(cat day.txt)\" = 'dawn\nnoon\ndusk'", {"day.txt": "dawn\nnoon"}),+ _mutation("fresh-edit-delete-prefix", "Remove lines beginning with OMIT: from items.txt without reordering other lines.", "test \"$(cat items.txt)\" = 'first\nsecond\nthird'", {"items.txt": "first\nOMIT:x\nsecond\nOMIT:y\nthird\n"}),+ _mutation("fresh-edit-dedupe-ids", "Deduplicate ids.txt in place, retaining first-occurrence order.", "test \"$(cat ids.txt)\" = 'k2\nk1\nk3'", {"ids.txt": "k2\nk1\nk2\nk3\nk1\n"}),+ _mutation("fresh-edit-noop", "Ensure switch.ini contains exactly active=yes. If it already does, leave it unchanged.", "test \"$(cat switch.ini)\" = active=yes && test \"$(wc -c < switch.ini)\" -eq 11", {"switch.ini": "active=yes\n"}),+ _mutation("fresh-edit-remove-marked", "Remove lines beginning SKIP: from rows.txt without reordering the remaining lines.", "test \"$(cat rows.txt)\" = 'north\nsouth\neast'", {"rows.txt": "north\nSKIP:x\nsouth\nSKIP:y\neast\n"}),+ _mutation("fresh-edit-adjacent-dedupe", "Collapse adjacent duplicate lines in runs.txt while preserving order.", "test \"$(cat runs.txt)\" = 'x\ny\nx\nz'", {"runs.txt": "x\nx\ny\ny\nx\nz\nz\n"}),++ _exact("fresh-dep-compare-ini", "Read alpha.ini and beta.ini and reply with only the name having the larger score.", "beta", {"alpha.ini": "score=31\n", "beta.ini": "score=48\n"}),+ _exact("fresh-dep-chain-lookup", "Use selected.txt to choose a row in catalog.txt and reply with only that row's code.", "ZX7", {"selected.txt": "moon\n", "catalog.txt": "sun AB2\nmoon ZX7\nstar LM4\n"}),+ _mutation("fresh-dep-join-labels", "Use labels.txt to replace each numeric key in keys.txt and write the labels to result.txt in key order.", "test \"$(cat result.txt)\" = 'oak\npine\ncedar'", {"keys.txt": "2\n1\n3\n", "labels.txt": "1 pine\n2 oak\n3 cedar\n"}),+ _mutation("fresh-dep-union", "Write union.txt containing the unique values from north.txt and south.txt, sorted alphabetically.", "test \"$(cat union.txt)\" = 'amber\ncyan\nindigo\nviolet'", {"north.txt": "violet\namber\ncyan\n", "south.txt": "cyan\nindigo\namber\n"}),+ _mutation("fresh-dep-transfer-value", "Read desired.ini and update only timeout in runtime.ini to match it.", f"grep -q '^name=gateway$' runtime.ini && grep -q '^timeout={desired}$' runtime.ini", {"desired.ini": f"timeout={desired}\n", "runtime.ini": "name=gateway\ntimeout=30\n"}),+ _exact("fresh-dep-selected-code", "Use wanted.txt to choose the matching row in codes.txt and reply with only its code.", "Q9", {"wanted.txt": "cedar\n", "codes.txt": "oak A2\ncedar Q9\npine M4\n"}),+ _mutation("fresh-dep-zipped-pairs", "Pair same-position lines from keys.txt and vals.txt into paired.txt as key:value.", "test \"$(cat paired.txt)\" = 'a:3\nb:5\nc:8'", {"keys.txt": "a\nb\nc\n", "vals.txt": "3\n5\n8\n"}),++ _exact("fresh-econ-product", f"Compute {product_a}*{product_b} and reply with only the number.", str(product_a * product_b)),+ _exact("fresh-econ-json", "Read runtime.json and reply with only runtime.port.", str(port), {"runtime.json": json.dumps({"runtime": {"port": port}}) + "\n"}),+ _mutation("fresh-econ-create", "Create signal.txt containing exactly GO with no trailing newline.", "test \"$(cat signal.txt)\" = GO && test \"$(wc -c < signal.txt)\" -eq 2"),+ _mutation("fresh-econ-empty", "Create void.dat as an exactly zero-byte file.", "test -f void.dat && test ! -s void.dat"),+ _mutation("fresh-econ-sum-write", "Sum the integers in amounts.txt and write only the total to answer.txt.", f"test \"$(cat answer.txt)\" = {sum(numbers)}", {"amounts.txt": "\n".join(map(str, numbers)) + "\n"}),+ _mutation("fresh-econ-uppercase", "Read phase.txt and write its uppercase text to loud.txt with no trailing newline.", "test \"$(cat loud.txt)\" = AURORA && test \"$(wc -c < loud.txt)\" -eq 6", {"phase.txt": "aurora\n"}),+ _mutation("fresh-econ-filter", "Write kept.txt from source.txt with lines beginning DROP: removed, preserving all others.", "test \"$(cat kept.txt)\" = 'one\ntwo\nthree'", {"source.txt": "one\nDROP:a\ntwo\nDROP:b\nthree\n"}),+ ]+ for index in range(3):+ fresh_token = secrets.token_hex(4)+ name = f"fresh-ready{index}.cfg"+ cases.append(_mutation(+ f"fresh-edit-noop-random-{index}",+ f"Ensure {name} contains exactly ready={fresh_token}. It already does; leave it unchanged.",+ f"test \"$(cat {name})\" = ready={fresh_token} && test \"$(wc -c < {name})\" -eq {len(fresh_token) + 7}",+ {name: f"ready={fresh_token}\n"},+ ))+ for index in range(3):+ cases.append(_mutation(+ f"fresh-edit-filter-random-{index}",+ f"Remove lines beginning OMIT: from fresh-filter{index}.txt without reordering other lines.",+ f"test \"$(cat fresh-filter{index}.txt)\" = 'p{index}\nq{index}\nr{index}'",+ {f"fresh-filter{index}.txt": f"p{index}\nOMIT:x\nq{index}\nOMIT:y\nr{index}\n"},+ ))+ for index in range(3):+ cases.append(_mutation(+ f"fresh-edit-dedupe-random-{index}",+ f"Deduplicate fresh-ids{index}.txt in place while preserving first-occurrence order.",+ f"test \"$(cat fresh-ids{index}.txt)\" = 'v{index}a\nv{index}b\nv{index}c'",+ {f"fresh-ids{index}.txt": f"v{index}a\nv{index}b\nv{index}a\nv{index}c\nv{index}b\n"},+ ))+ for index in range(3):+ desired_limit = secrets.randbelow(8000) + 1000+ cases.append(_mutation(+ f"fresh-edit-copy-random-{index}",+ f"Read wanted{index}.conf and update only limit in live{index}.conf to match it.",+ f"grep -q '^name=service{index}$' live{index}.conf && grep -q '^limit={desired_limit}$' live{index}.conf",+ {+ f"wanted{index}.conf": f"limit={desired_limit}\n",+ f"live{index}.conf": f"name=service{index}\nlimit=20\n",+ },+ ))+ return cases+++def validate_case_catalog(cases: list[dict[str, Any]], expected: int) -> None:+ if len(cases) != expected or len({case.get("id") for case in cases}) != expected:+ raise ValueError(f"expected {expected} unique cases")+ for case in cases:+ payload = case.get("payload")+ if not isinstance(payload, dict) or not isinstance(payload.get("task"), str):+ raise ValueError("every case needs a task payload")+ check = payload.get("check")+ if not isinstance(check, dict) or len(check) != 1:+ raise ValueError("every case needs exactly one check")+++if __name__ == "__main__":+ primary, holdout = primary_cases(), fresh_holdout()+ validate_case_catalog(primary, 60)+ validate_case_catalog(holdout, 40)+ print(json.dumps({"primary": len(primary), "holdout": len(holdout)}))diff --git a/examples/prepare_graff_tournament.py b/examples/prepare_graff_tournament.pynew file mode 100755index 00000000..9325f9cf--- /dev/null+++ b/examples/prepare_graff_tournament.py@@ -0,0 +1,124 @@+#!/usr/bin/env python3+"""Prepare a fresh, pinned four-arm learning workspace outside the repo."""++from __future__ import annotations++import argparse+import hashlib+import json+from pathlib import Path+import secrets++from learn_graff_suites import fresh_holdout, primary_cases, validate_case_catalog+++def digest(path: Path) -> str:+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def write_json(path: Path, value: object) -> None:+ path.write_text(json.dumps(value, separators=(",", ":")) + "\n", encoding="utf-8")+ path.chmod(0o600)+++def extract_root_prompt(source: Path) -> str:+ lines = source.read_text(encoding="utf-8").splitlines()+ collecting = False+ result: list[str] = []+ for line in lines:+ if line.startswith("pub const main_system_prompt ="):+ collecting = True+ continue+ if collecting and line == ";":+ break+ if collecting:+ marker = line.find("\\\\")+ if marker >= 0:+ result.append(line[marker + 2 :])+ if not result:+ raise ValueError("could not extract main_system_prompt")+ return "\n".join(result).strip() + "\n"+++def pin(path: Path) -> dict[str, str]:+ return {"path": str(path.resolve()), "sha256": digest(path)}+++def program_pin(path: Path) -> dict[str, str]:+ return {"program": str(path.resolve()), "sha256": digest(path)}+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("output", type=Path)+ parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parents[1])+ parser.add_argument("--graff", type=Path, default=Path("zig-out/bin/graff"))+ args = parser.parse_args()+ repo = args.repo.resolve()+ output = args.output.resolve()+ output.mkdir(parents=True, mode=0o700, exist_ok=False)+ workspace = output / "workspace"+ workspace.mkdir(mode=0o700)++ graff = (repo / args.graff).resolve() if not args.graff.is_absolute() else args.graff.resolve()+ mutator = (repo / "examples" / "learn_graff_mutator.py").resolve()+ arms = (repo / "examples" / "learn_graff_arms.json").resolve()+ evaluator = (repo / "examples" / "learn_graff_evaluator.py").resolve()+ evaluator_settings = (repo / "examples" / "learn_graff_evaluator.json").resolve()+ for path in (graff, mutator, arms, evaluator, evaluator_settings):+ if not path.is_file():+ raise FileNotFoundError(path)++ parent = output / "parent.md"+ parent.write_text(extract_root_prompt(repo / "src" / "prompts.zig"), encoding="utf-8")+ parent.chmod(0o600)+ primary = output / "primary.json"+ holdout = output / "fresh-holdout.json"+ public_cases, hidden_cases = primary_cases(), fresh_holdout()+ validate_case_catalog(public_cases, 60)+ validate_case_catalog(hidden_cases, 40)+ write_json(primary, {"schema": "codegraff.learn.suite.v1", "suite_id": "graff-primary-v6", "cases": public_cases})+ write_json(holdout, {"schema": "codegraff.learn.suite.v1", "suite_id": "fresh-" + secrets.token_hex(8), "cases": hidden_cases})++ config = {+ "schema": "codegraff.learn.config.v1",+ "agent_name": "graff-root-tournament",+ "agent_description": "manual-only four-arm root prompt tournament",+ "mutation_instruction": "Patch exactly one configured paragraph with one concise, role-specific behavioral clause. Preserve every other byte and every safety or authority invariant.",+ "mutator": {+ **program_pin(mutator), "args": [str(arms), str(graff)],+ "inputs": [pin(arms), pin(graff)], "pass_env": ["CODEX_HOME"],+ },+ "evaluator": {+ **program_pin(evaluator), "args": [str(evaluator_settings), str(graff)],+ "inputs": [pin(evaluator_settings), pin(graff)], "pass_env": ["CODEX_HOME"],+ },+ "evaluation_suite": pin(primary),+ "holdout_suite": pin(holdout),+ "limits": {"mutator_timeout_ms": 600000, "evaluator_timeout_ms": 1800000},+ "gate": {+ "alpha_ppm": 50000,+ "minimum_delta_ppm": 50000,+ "minimum_pairs": 40,+ "economy_gate_enabled": True,+ "promotion_mode": "economy",+ "minimum_tool_reduction_ppm": 100000,+ "minimum_economy_pairs": 10,+ "require_all_candidates": True,+ "default_candidates": 4,+ "default_repetitions": 1,+ },+ "auto": {"enabled": False},+ "cohort": {"provider": "codex", "model": "gpt-5.4-mini", "task_family": "coding-flow", "adapter_version": "graff-eval-v6", "verifier_version": "exact-v5"},+ }+ config_path = output / "config.json"+ write_json(config_path, config)+ print(json.dumps({+ "workspace": str(workspace), "parent": str(parent), "config": str(config_path),+ "primary_sha256": digest(primary), "holdout_sha256": digest(holdout),+ "primary_cases": len(public_cases), "holdout_cases": len(hidden_cases),+ }, indent=2))+++if __name__ == "__main__":+ main()diff --git a/examples/replay_judge.py b/examples/replay_judge.pyindex 3f3af95c..f0a129d4 100644--- a/examples/replay_judge.py+++ b/examples/replay_judge.py@@ -2,9 +2,10 @@"""replay_judge.py — Step 1: the grounded, out-of-process evolution judge.Runs a candidate system prompt (a DGM genome) against a held-out eval set of-tasks with DETERMINISTIC assertions — a shell command's exit code or a golden-substring in the final report — and emits a pass rate. No LLM grades anything-here; this is the primary fitness gradient the evolving agent cannot charm.+tasks with DETERMINISTIC assertions — a shell command's exit code, exact final+answer, or (for intentionally partial reports) a golden substring — and emits a+pass rate. No LLM grades anything here; this is the primary fitness gradient the+evolving agent cannot charm.Custody model (mirrors the Step 0 score key):- The eval set lives OUTSIDE the editable tree, named by GRAFF_EVAL_SET_FILE.@@ -128,7 +129,7 @@ def run_variant(system_prompt, task_text, cwd):def check_task(task, report, cwd):- """Deterministic, out-of-process assertion: exit code or golden substring."""+ """Deterministic assertion: exit code, exact answer, or golden substring."""chk = task.get("check", {})if "cmd" in chk:r = subprocess.run(["sh", "-c", chk["cmd"]], cwd=cwd,@@ -137,6 +138,9 @@ def check_task(task, report, cwd):if "substring" in chk:ok = chk["substring"] in reportreturn ok, "substring " + ("found" if ok else "missing")+ if "exact" in chk:+ ok = report.strip() == chk["exact"]+ return ok, "exact output " + ("matched" if ok else "mismatched")return False, "no check defined"diff --git a/examples/test_step1.py b/examples/test_step1.pyindex b755dbfc..31d9da5d 100755--- a/examples/test_step1.py+++ b/examples/test_step1.py@@ -22,6 +22,8 @@ import osimport subprocessimport sys+import replay_judge+HERE = os.path.dirname(os.path.abspath(__file__))@@ -40,6 +42,8 @@ def check(name, ok, detail=""):def offline(loop):ok = True+ passed, _ = replay_judge.check_task({"check": {"exact": "391"}}, "1391", HERE)+ ok &= check("exact-answer checks reject substring false positives", not passed)# 1. The promotable band is unreachable while any held-out task fails.worst_gap = min(0.9 + 0.1 * llm - 0.8 * pfor p in (i / 100 for i in range(100)) # pass_rate < 1diff --git a/sdk/generate.py b/sdk/generate.pyindex f47ed667..6ec4863d 100644--- a/sdk/generate.py+++ b/sdk/generate.py@@ -216,19 +216,21 @@ function reportError(kind: string, detail: string): void {{}} catch {{ /* fetch unavailable: drop */ }}}}-/** Best-effort OTLP "fleet" log for the federated evolution loop (docs §9):- * propose / submit / elite_pull signals, tagged by client so CLI/TS/Python- * contributions stay distinguishable in /v1/stats. Same opt-out + endpoint as- * reportError. Fire-and-forget. */+/** Prompt-free SDK fleet signal. Local is the fail-closed default; SDKs have+ * no interactive artifact-review UI, so prompt_text is never admitted. */export function fleetSignal(kind: string, attrs: Record<string, string | number> = {{}}): void {{if (process.env.GRAFF_NO_TELEMETRY) return;+ const privacy = process.env.GRAFF_LEARNING_PRIVACY ?? "local";+ if (!(["aggregate", "templates", "examples"] as string[]).includes(privacy)) return;+ const admitted = {{ ...attrs }};+ delete admitted.prompt_text;let base = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.GRAFF_OTEL_ENDPOINT || TELEMETRY_DEFAULT;while (base.endsWith("/")) base = base.slice(0, -1);const url = base.endsWith("/v1/logs") ? base : base + "/v1/logs";const attributes: Array<Record<string, unknown>> = [{{ key: "kind", value: {{ stringValue: kind }} }},];- for (const [k, v] of Object.entries(attrs)) {{+ for (const [k, v] of Object.entries(admitted)) {{attributes.push({{ key: k, value: typeof v === "number" ? {{ doubleValue: v }} : {{ stringValue: String(v) }} }});}}const payload = JSON.stringify({{ resourceLogs: [{{@@ -377,8 +379,8 @@ export class Harness {{* prompt: that genome-lineage edge is what DGM parent selection counts* children with. Pass `niche` (reviewer/researcher/implementer/skeptic, or* a custom agent) to file the score into that MAP-Elites cell so the fleet- * can promote a champion for the role; with the full persona text the genome- * also rides over on a `fleet:propose`. Scale: the canonical wire scale is+ * can promote a champion for the role; full text produces only a prompt-free+ * fingerprint proposal until the SDK has review UI. Scale: the wire scale is* [0, 1]. Pass scale "unit" to assert `value` is already in [0, 1]* (anything else is rejected), or "percent" to always send value/100* (accepts [0, 100] — a percent-scale 0.5 means 0.005, not 0.5). Without@@ -390,10 +392,7 @@ export class Harness {{const sha = /^[0-9a-f]{{16}}$/.test(promptOrSha) ? promptOrSha : promptFingerprint(promptOrSha);const parent_sha = parent === undefined ? undefined: /^[0-9a-f]{{16}}$/.test(parent) ? parent : promptFingerprint(parent);- // Genome-send (docs §9.B): a cell only promotes when a score's prompt_sha- // joins a stored genome, so when we hold the full persona text + a niche,- // register it first on a `fleet:propose` (deduped by prompt_sha on the- // collector). This is the SDK analog of the harness eval loop's propose.+ // The SDK emitter strips prompt_text until it has an interactive review UI.if (niche && !/^[0-9a-f]{{16}}$/.test(promptOrSha)) fleetSignal("propose", {{ niche, prompt_sha: sha, parent_sha: parent_sha ?? "", prompt_text: promptOrSha }});this.proc.stdin.write(JSON.stringify({{ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche, scale }}) + "\\n");// Same edge-version tolerance as setSystemPrompt: skip unknown events@@ -406,11 +405,10 @@ export class Harness {{}}}}- /** Pull the fleet's live champion personas for a model tier (docs §9 Step 2,- * GET /v1/elites). Emits a `fleet:elite_pull` signal and returns the elites- * (empty when none are promoted yet). Hits the telemetry collector, not the- * harness subprocess. */+ /** Pull the fleet's live champion personas (GET /v1/elites). Local mode+ * returns before contacting the telemetry collector. */async pullElites(providerClass: string, evalSetHash?: string): Promise<Array<Record<string, unknown>>> {{+ if (!(["aggregate", "templates", "examples"] as string[]).includes(process.env.GRAFF_LEARNING_PRIVACY ?? "local")) return [];let base = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.GRAFF_OTEL_ENDPOINT || TELEMETRY_DEFAULT;while (base.endsWith("/")) base = base.slice(0, -1);if (base.endsWith("/v1/logs")) base = base.slice(0, -"/v1/logs".length);@@ -849,18 +847,19 @@ def _report_error(kind: str, detail: str) -> None:def _fleet_signal(kind: str, attrs: Optional[dict] = None) -> None:- """Best-effort OTLP "fleet" log for the federated evolution loop (docs §9):- propose / submit / elite_pull signals, tagged by client so CLI/TS/Python- contributions stay distinguishable in /v1/stats. Same opt-out + endpoint as- _report_error. Fire-and-forget on a daemon thread; never raises."""+ """Prompt-free SDK fleet signal; local is the fail-closed default."""if os.environ.get("GRAFF_NO_TELEMETRY"):return+ privacy = os.environ.get("GRAFF_LEARNING_PRIVACY", "local")+ if privacy not in ("aggregate", "templates", "examples"):+ return+ attrs = {{k: v for k, v in (attrs or {{}}).items() if k != "prompt_text"}}base = (os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")or os.environ.get("GRAFF_OTEL_ENDPOINT")or _TELEMETRY_DEFAULT).rstrip("/")url = base if base.endswith("/v1/logs") else base + "/v1/logs"al = [{{"key": "kind", "value": {{"stringValue": kind}}}}]- for k, v in (attrs or {{}}).items():+ for k, v in attrs.items():val = {{"doubleValue": v}} if isinstance(v, (int, float)) else {{"stringValue": str(v)}}al.append({{"key": k, "value": val}})payload = json.dumps({{"resourceLogs": [{{@@ -1095,8 +1094,8 @@ class Harness:HMAC so a forged fitness row is detectable (see `verify_score`).`niche` (reviewer/researcher/implementer/skeptic, or a custom agent)files the score into that MAP-Elites cell so the fleet can promote a- champion for the role; with the full persona text the genome also rides- over on a `fleet:propose`.+ champion for the role; full text produces only a prompt-free fingerprint+ proposal until the SDK has an interactive review UI.Scale: the canonical wire scale is [0, 1]. Pass scale="unit" toassert `value` is already in [0, 1] (anything else is rejected), or@@ -1123,9 +1122,7 @@ class Harness:req["niche"] = nicheif scale:req["scale"] = scale- # Genome-send (docs §9.B): a cell only promotes when a score's prompt_sha- # joins a stored genome, so when we hold the full persona text + a niche,- # register it first (deduped by prompt_sha on the collector).+ # The SDK emitter strips prompt_text until it has an interactive review UI.if niche and not re.fullmatch(r"[0-9a-f]{{16}}", prompt_or_sha):_fleet_signal("propose", {{"niche": niche, "prompt_sha": sha,"parent_sha": req.get("parent_sha", ""),@@ -1149,10 +1146,9 @@ class Harness:raise RuntimeError("harness closed before acking score")def pull_elites(self, provider_class: str, eval_set_hash: str = "") -> list:- """Pull the fleet's live champion personas for a model tier (docs §9- Step 2, GET /v1/elites). Emits a `fleet:elite_pull` signal and returns- the elites list (empty when none are promoted yet). Hits the telemetry- collector, not the harness subprocess."""+ """Pull fleet champions; local mode returns without network access."""+ if os.environ.get("GRAFF_LEARNING_PRIVACY", "local") not in ("aggregate", "templates", "examples"):+ return []base = (os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")or os.environ.get("GRAFF_OTEL_ENDPOINT")or _TELEMETRY_DEFAULT).rstrip("/")@@ -1313,7 +1309,7 @@ class RemoteHarness:niche: str = "", scale: str = "") -> None:"""Record an evaluation score in the server-side trajectory archive —same semantics (and provenance fields) as `Harness.score`, including- the `niche` MAP-Elites tag, genome-send, and the optional `scale`+ prompt-free MAP-Elites lineage and the optional `scale`("unit" | "percent") override of the harness's value-normalizationheuristic."""sha = prompt_or_sha if re.fullmatch(r"[0-9a-f]{{16}}", prompt_or_sha) \\@@ -1332,8 +1328,7 @@ class RemoteHarness:req["niche"] = nicheif scale:req["scale"] = scale- # Genome-send (docs §9.B): register the persona when we hold the full- # text + a niche so a promoted cell has a genome to serve.+ # The SDK emitter strips prompt_text until it has an interactive review UI.if niche and not re.fullmatch(r"[0-9a-f]{{16}}", prompt_or_sha):_fleet_signal("propose", {{"niche": niche, "prompt_sha": sha,"parent_sha": req.get("parent_sha", ""),diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.pyindex 4bc68a78..34e84aaa 100644--- a/sdk/py/harness_sdk.py+++ b/sdk/py/harness_sdk.py@@ -14,7 +14,7 @@ import urllib.requestfrom typing import Iterator, OptionalMODELS = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"]-TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow"]+TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "learn_candidate"]PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "minimax", "xiaomi", "kimi", "moonshot", "xai", "zai", "fugu", "fireworks", "mlx", "lmstudio", "codex"]@@ -97,18 +97,19 @@ def _report_error(kind: str, detail: str) -> None:def _fleet_signal(kind: str, attrs: Optional[dict] = None) -> None:- """Best-effort OTLP "fleet" log for the federated evolution loop (docs §9):- propose / submit / elite_pull signals, tagged by client so CLI/TS/Python- contributions stay distinguishable in /v1/stats. Same opt-out + endpoint as- _report_error. Fire-and-forget on a daemon thread; never raises."""+ """Prompt-free SDK fleet signal; local is the fail-closed default."""if os.environ.get("GRAFF_NO_TELEMETRY"):return+ privacy = os.environ.get("GRAFF_LEARNING_PRIVACY", "local")+ if privacy not in ("aggregate", "templates", "examples"):+ return+ attrs = {k: v for k, v in (attrs or {}).items() if k != "prompt_text"}base = (os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")or os.environ.get("GRAFF_OTEL_ENDPOINT")or _TELEMETRY_DEFAULT).rstrip("/")url = base if base.endswith("/v1/logs") else base + "/v1/logs"al = [{"key": "kind", "value": {"stringValue": kind}}]- for k, v in (attrs or {}).items():+ for k, v in attrs.items():val = {"doubleValue": v} if isinstance(v, (int, float)) else {"stringValue": str(v)}al.append({"key": k, "value": val})payload = json.dumps({"resourceLogs": [{@@ -343,8 +344,8 @@ class Harness:HMAC so a forged fitness row is detectable (see `verify_score`).`niche` (reviewer/researcher/implementer/skeptic, or a custom agent)files the score into that MAP-Elites cell so the fleet can promote a- champion for the role; with the full persona text the genome also rides- over on a `fleet:propose`.+ champion for the role; full text produces only a prompt-free fingerprint+ proposal until the SDK has an interactive review UI.Scale: the canonical wire scale is [0, 1]. Pass scale="unit" toassert `value` is already in [0, 1] (anything else is rejected), or@@ -371,9 +372,7 @@ class Harness:req["niche"] = nicheif scale:req["scale"] = scale- # Genome-send (docs §9.B): a cell only promotes when a score's prompt_sha- # joins a stored genome, so when we hold the full persona text + a niche,- # register it first (deduped by prompt_sha on the collector).+ # The SDK emitter strips prompt_text until it has an interactive review UI.if niche and not re.fullmatch(r"[0-9a-f]{16}", prompt_or_sha):_fleet_signal("propose", {"niche": niche, "prompt_sha": sha,"parent_sha": req.get("parent_sha", ""),@@ -397,10 +396,9 @@ class Harness:raise RuntimeError("harness closed before acking score")def pull_elites(self, provider_class: str, eval_set_hash: str = "") -> list:- """Pull the fleet's live champion personas for a model tier (docs §9- Step 2, GET /v1/elites). Emits a `fleet:elite_pull` signal and returns- the elites list (empty when none are promoted yet). Hits the telemetry- collector, not the harness subprocess."""+ """Pull fleet champions; local mode returns without network access."""+ if os.environ.get("GRAFF_LEARNING_PRIVACY", "local") not in ("aggregate", "templates", "examples"):+ return []base = (os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")or os.environ.get("GRAFF_OTEL_ENDPOINT")or _TELEMETRY_DEFAULT).rstrip("/")@@ -561,7 +559,7 @@ class RemoteHarness:niche: str = "", scale: str = "") -> None:"""Record an evaluation score in the server-side trajectory archive —same semantics (and provenance fields) as `Harness.score`, including- the `niche` MAP-Elites tag, genome-send, and the optional `scale`+ prompt-free MAP-Elites lineage and the optional `scale`("unit" | "percent") override of the harness's value-normalizationheuristic."""sha = prompt_or_sha if re.fullmatch(r"[0-9a-f]{16}", prompt_or_sha) \@@ -580,8 +578,7 @@ class RemoteHarness:req["niche"] = nicheif scale:req["scale"] = scale- # Genome-send (docs §9.B): register the persona when we hold the full- # text + a niche so a promoted cell has a genome to serve.+ # The SDK emitter strips prompt_text until it has an interactive review UI.if niche and not re.fullmatch(r"[0-9a-f]{16}", prompt_or_sha):_fleet_signal("propose", {"niche": niche, "prompt_sha": sha,"parent_sha": req.get("parent_sha", ""),diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex 65a51d5c..b102b6e3 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -11,7 +11,7 @@ import { createInterface } from "node:readline";export const HARNESS_VERSION = "0.6";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "learn_candidate";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by `harness --json` (one JSON object per stdout line), each@@ -165,19 +165,21 @@ function reportError(kind: string, detail: string): void {} catch { /* fetch unavailable: drop */ }}-/** Best-effort OTLP "fleet" log for the federated evolution loop (docs §9):- * propose / submit / elite_pull signals, tagged by client so CLI/TS/Python- * contributions stay distinguishable in /v1/stats. Same opt-out + endpoint as- * reportError. Fire-and-forget. */+/** Prompt-free SDK fleet signal. Local is the fail-closed default; SDKs have+ * no interactive artifact-review UI, so prompt_text is never admitted. */export function fleetSignal(kind: string, attrs: Record<string, string | number> = {}): void {if (process.env.GRAFF_NO_TELEMETRY) return;+ const privacy = process.env.GRAFF_LEARNING_PRIVACY ?? "local";+ if (!(["aggregate", "templates", "examples"] as string[]).includes(privacy)) return;+ const admitted = { ...attrs };+ delete admitted.prompt_text;let base = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.GRAFF_OTEL_ENDPOINT || TELEMETRY_DEFAULT;while (base.endsWith("/")) base = base.slice(0, -1);const url = base.endsWith("/v1/logs") ? base : base + "/v1/logs";const attributes: Array<Record<string, unknown>> = [{ key: "kind", value: { stringValue: kind } },];- for (const [k, v] of Object.entries(attrs)) {+ for (const [k, v] of Object.entries(admitted)) {attributes.push({ key: k, value: typeof v === "number" ? { doubleValue: v } : { stringValue: String(v) } });}const payload = JSON.stringify({ resourceLogs: [{@@ -326,8 +328,8 @@ export class Harness {* prompt: that genome-lineage edge is what DGM parent selection counts* children with. Pass `niche` (reviewer/researcher/implementer/skeptic, or* a custom agent) to file the score into that MAP-Elites cell so the fleet- * can promote a champion for the role; with the full persona text the genome- * also rides over on a `fleet:propose`. Scale: the canonical wire scale is+ * can promote a champion for the role; full text produces only a prompt-free+ * fingerprint proposal until the SDK has review UI. Scale: the wire scale is* [0, 1]. Pass scale "unit" to assert `value` is already in [0, 1]* (anything else is rejected), or "percent" to always send value/100* (accepts [0, 100] — a percent-scale 0.5 means 0.005, not 0.5). Without@@ -339,10 +341,7 @@ export class Harness {const sha = /^[0-9a-f]{16}$/.test(promptOrSha) ? promptOrSha : promptFingerprint(promptOrSha);const parent_sha = parent === undefined ? undefined: /^[0-9a-f]{16}$/.test(parent) ? parent : promptFingerprint(parent);- // Genome-send (docs §9.B): a cell only promotes when a score's prompt_sha- // joins a stored genome, so when we hold the full persona text + a niche,- // register it first on a `fleet:propose` (deduped by prompt_sha on the- // collector). This is the SDK analog of the harness eval loop's propose.+ // The SDK emitter strips prompt_text until it has an interactive review UI.if (niche && !/^[0-9a-f]{16}$/.test(promptOrSha)) fleetSignal("propose", { niche, prompt_sha: sha, parent_sha: parent_sha ?? "", prompt_text: promptOrSha });this.proc.stdin.write(JSON.stringify({ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche, scale }) + "\n");// Same edge-version tolerance as setSystemPrompt: skip unknown events@@ -355,11 +354,10 @@ export class Harness {}}- /** Pull the fleet's live champion personas for a model tier (docs §9 Step 2,- * GET /v1/elites). Emits a `fleet:elite_pull` signal and returns the elites- * (empty when none are promoted yet). Hits the telemetry collector, not the- * harness subprocess. */+ /** Pull the fleet's live champion personas (GET /v1/elites). Local mode+ * returns before contacting the telemetry collector. */async pullElites(providerClass: string, evalSetHash?: string): Promise<Array<Record<string, unknown>>> {+ if (!(["aggregate", "templates", "examples"] as string[]).includes(process.env.GRAFF_LEARNING_PRIVACY ?? "local")) return [];let base = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.GRAFF_OTEL_ENDPOINT || TELEMETRY_DEFAULT;while (base.endsWith("/")) base = base.slice(0, -1);if (base.endsWith("/v1/logs")) base = base.slice(0, -"/v1/logs".length);@@ -420,4 +418,4 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "learn_candidate"];diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex ad972922..bfa84f59 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -10,7 +10,7 @@export const HARNESS_VERSION = "0.6";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "learn_candidate";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by the bridge (same `--json` contract as the stdio SDK).@@ -250,4 +250,4 @@ export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerat}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "learn_candidate"];diff --git a/src/agent.zig b/src/agent.zigindex c4e3966b..6de5d8d8 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -1,21 +1,7 @@-//! The Agent struct itself: one agent's fields (message history, streaming/-//! markdown-render state, thinking-block state, eval-loop state, ...) plus-//! its smallest methods (prompt/say/sayApiError/emit/systemPrompt/-//! effortApplies/toolsJson/runTurn/renderTodos). Every other Agent method is-//! a free `pub fn method(self: *Agent, ...)` in an agent_*.zig sibling file,-//! member-aliased back inside this struct (`pub const method =-//! @import("agent_x.zig").method;`) so both `self.method(...)` and static-//! `Agent.method(...)` test calls resolve unchanged regardless of which-//! physical file a method's body lives in. Split out of main.zig (600-line-//! goal). Back-imports main (as main_mod, since a request()/etc. param is-//! conventionally named `root` elsewhere and to avoid the `agent`/`Agent`-//! self-name clash) for Provider/ReasoningEffort/the json_mode/plan_mode/-//! show_cost/g_cwd_display/g_gui_mu live globals. Sibling-imports mcp-//! (Registry), approvals (Approvals), trace (Tracer/ToolSink), tools-//! (Snapshots), vision (PendingImage), prompts (the system-prompt text),-//! schema (the per-wire-format tool JSON + providerTakesEffort), pricing-//! (priceFor/g_cost), and ansi (the color palette) directly instead of-//! going back through main's private aliases for them.+//! The Agent struct, its state, and its smallest methods. Larger methods are+//! split into `agent_*.zig` siblings and member-aliased back into the struct.+//! Live process/session globals are reached through main_mod; focused helpers+//! are imported directly from their owning modules.const std = @import("std");const Io = std.Io;@@ -38,6 +24,7 @@ const pricing = @import("pricing.zig");const models_cache = @import("models_cache.zig");const keys_cli = @import("keys_cli.zig");const run_budget_mod = @import("run_budget.zig");+const learning_privacy = @import("learning_privacy.zig");const ansi = @import("ansi.zig");const style = &ansi.style;@@ -245,6 +232,12 @@ pub const Agent = struct {if (main_mod.plan_mode) try writePromptBadge(w, style.yellow, "Plan");if (self.strict) try writePromptBadge(w, style.red, "Strict");if (self.ultracode_mode) try writePromptBadge(w, style.accent, "Ultracode");+ const privacy_mode = learning_privacy.current();+ try writePromptBadge(w, switch (privacy_mode) {+ .local, .aggregate => style.green,+ .templates => style.yellow,+ .examples => style.red,+ }, privacy_mode.badge());try w.print("{s} · cwd {s}{s}{s}", .{ style.dim, style.reset, main_mod.g_cwd_display, style.dim });const context_tokens = self.effectiveContextTokens();if (self.last_context_tokens > 0) {diff --git a/src/agent_compact.zig b/src/agent_compact.zigindex 1bba75c4..ba7b9f34 100644--- a/src/agent_compact.zig+++ b/src/agent_compact.zig@@ -2,10 +2,10 @@//! recovery when a summary request cannot run.const std = @import("std");-const Io = std.Io;const Value = std.json.Value;const Allocator = std.mem.Allocator;const utf8Prefix = @import("util.zig").utf8Prefix;+const context_tokens = @import("context_tokens.zig");const main_mod = @import("main.zig");const agent_mod = @import("agent.zig");@@ -26,14 +26,6 @@ pub const runJudge = agent_eval.runJudge;pub const recent_context_tokens: u64 = 8_000;-fn serializedTokens(value: Value) u64 {- var buf: [256]u8 = undefined;- var d: Io.Writer.Discarding = .init(&buf);- var s: std.json.Stringify = .{ .writer = &d.writer };- s.write(value) catch {};- return @intCast(d.fullCount() / 4);-}-/// Pick the earliest clean user-turn boundary whose suffix fits in the recent/// context budget. Returning items.len means "summarize everything". We never/// split at a tool output, so retained call/result history stays valid.@@ -44,7 +36,7 @@ pub fn recentContextStart(items: []const Value, token_budget: u64) usize {var i = items.len;while (i > 0) {i -= 1;- total +|= serializedTokens(items[i]);+ total +|= context_tokens.estimatedTokens(items[i]);if (total > token_budget) break;if (cleanUserTurn(items[i])) start = i;}diff --git a/src/agent_compact_test.zig b/src/agent_compact_test.zigindex 6155e37b..9e4f0490 100644--- a/src/agent_compact_test.zig+++ b/src/agent_compact_test.zig@@ -255,6 +255,34 @@ test "recentContextStart keeps a clean recent suffix and never orphans tool outptry std.testing.expectEqual(msgs.items[2..].len, recentContextStart(msgs.items[2..], 8_000));}+test "recentContextStart preserves a fresh image without counting its Base64 as text" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const payload = try arena.alloc(u8, 1_600_000);+ @memset(payload, 'A');+ const uri = try std.fmt.allocPrint(arena, "data:image/png;base64,{s}", .{payload});++ var image_url: std.json.ObjectMap = .empty;+ try image_url.put(arena, "url", .{ .string = uri });+ var image: std.json.ObjectMap = .empty;+ try image.put(arena, "type", .{ .string = "image_url" });+ try image.put(arena, "image_url", .{ .object = image_url });+ var content = std.json.Array.init(arena);+ try content.append(.{ .object = image });+ var user: std.json.ObjectMap = .empty;+ try user.put(arena, "role", .{ .string = "user" });+ try user.put(arena, "content", .{ .array = content });+ var messages = std.json.Array.init(arena);+ try messages.append(.{ .object = user });++ // The whole short conversation still needs summarizing when compact() is+ // explicitly requested, but the image itself fits the recent-turn budget+ // and can be retained when older history exists.+ try messages.insert(0, try textMessage(arena, "user", &util.repeatBytes("x", 40_000)));+ try std.testing.expectEqual(@as(usize, 1), recentContextStart(messages.items, 8_000));+}+test "capOversizedToolOutputs (#193): bounds an oversized output in every wire format, leaves small ones + non-tool msgs" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();diff --git a/src/agent_context.zig b/src/agent_context.zigindex 2db2bacc..c0bf8cd8 100644--- a/src/agent_context.zig+++ b/src/agent_context.zig@@ -2,10 +2,10 @@const std = @import("std");const util = @import("util.zig");-const Io = std.Io;const Value = std.json.Value;const Agent = @import("agent.zig").Agent;+const context_tokens = @import("context_tokens.zig");const messages_mod = @import("messages.zig");const pricing = @import("pricing.zig");const g_cost = &pricing.g_cost;@@ -100,7 +100,7 @@ test "context estimate reuses an already-serialized history byte count" {agent.last_context_tokens = 12_000;agent.context_local_tokens = 8_000;- const input_bytes = jsonSerializedLen(Value{ .array = messages });+ const input_bytes = context_tokens.serializedLen(Value{ .array = messages });const estimate = contextEstimateFromInputBytes(&agent, input_bytes);try std.testing.expectEqual(fullRequestEstimateTokens(&agent), estimate.local);try std.testing.expectEqual(estimate.local + 4_000, estimate.effective);@@ -109,12 +109,12 @@ test "context estimate reuses an already-serialized history byte count" {pub fn recordUsage(self: *Agent, root: std.json.ObjectMap, req_body_len: usize) void {self.last_cache_read = 0;self.last_usage_includes_output = false;- // #202: keep the context meter live when the provider omits usage — otherwise- // the between-turns compaction gate freezes at a stale value and a long session- // can wedge. Mirror the codex/.responses fallback (req_body_len/4, floored at the- // full-input estimate) that recordUsageResponses already applies (#174).- const usage = root.get("usage") orelse return floorContextTokens(self, req_body_len / 4);- if (usage != .object) return floorContextTokens(self, req_body_len / 4);+ // #202/#260: keep the context meter live when the provider omits usage.+ // Estimate the serialized body while replacing inline image transport bytes+ // with bounded vision tokens, then floor it at the full-input estimate.+ const fallback = requestBodyEstimateTokens(self, req_body_len);+ const usage = root.get("usage") orelse return floorContextTokens(self, fallback);+ if (usage != .object) return floorContextTokens(self, fallback);const u = usage.object;switch (self.provider.kind) {.anthropic => {@@ -127,7 +127,7 @@ pub fn recordUsage(self: *Agent, root: std.json.ObjectMap, req_body_len: usize)if (total > 0)replaceContextTokens(self, @intCast(total))else- floorContextTokens(self, req_body_len / 4);+ floorContextTokens(self, fallback);self.last_usage_includes_output = total > 0 and if (u.get("output_tokens")) |v| v == .integer and v.integer >= 0 else false;const cache = usageInt(u, "cache_read_input_tokens");if (cache > 0) self.last_cache_read = @intCast(cache);@@ -141,7 +141,7 @@ pub fn recordUsage(self: *Agent, root: std.json.ObjectMap, req_body_len: usize)if (reported_total > 0)replaceContextTokens(self, @intCast(reported_total))else- floorContextTokens(self, req_body_len / 4);+ floorContextTokens(self, fallback);self.last_usage_includes_output = reported_total > 0 and(total > 0 or if (u.get("completion_tokens")) |v| v == .integer and v.integer >= 0 else false);// deepseek reports prompt_cache_hit_tokens; the OpenAI shape@@ -190,17 +190,6 @@ pub fn recordCost(self: *Agent, uncached_in: i64, cache_in: i64, out: i64) voidg_cost.add(self.io, self.provider.id, self.provider.model, uncached_in, cache_in, out);}-/// Count a value's serialized JSON bytes without allocating the output.-fn jsonSerializedLen(value: anytype) usize {- var buf: [512]u8 = undefined;- var d: Io.Writer.Discarding = .init(&buf);- var s: std.json.Stringify = .{ .writer = &d.writer };- // Discarding is infallible today. Preserve the bytes counted so far if a- // future writer becomes stricter instead of returning a spurious zero.- s.write(value) catch return d.fullCount();- return d.fullCount();-}-/// #174: ~4-bytes/token estimate of the FULL history serialized as Responses/// `input` items — the cost of the next full-history resend (runTurn closes/// the WS per turn, so every turn's first request replays everything). The@@ -209,7 +198,7 @@ fn jsonSerializedLen(value: anytype) usize {/// every retained encrypted reasoning item again. Counting discard writer —/// no allocation.pub fn fullInputEstimateTokens(self: *Agent) u64 {- return @intCast(jsonSerializedLen(Value{ .array = self.messages }) / 4);+ return context_tokens.estimatedTokens(Value{ .array = self.messages });}/// Estimate the complete fixed+history input sent by a normal model request.@@ -218,16 +207,19 @@ pub fn fullInputEstimateTokens(self: *Agent) u64 {/// the old 8k conservative baseline when those serialize smaller, but never let it/// hide an unbounded set_system_prompt/set_agent payload.fn requestEstimateFromInputBytes(self: *Agent, input_bytes: usize) u64 {- const system_bytes = jsonSerializedLen(self.systemPrompt());- const total_bytes = input_bytes +| system_bytes +| self.toolsJson().len;- const measured: u64 = @intCast(total_bytes / 4);- const input_tokens: u64 = @intCast(input_bytes / 4);+ const input_tokens = context_tokens.estimatedTokensFromLen(Value{ .array = self.messages }, input_bytes);+ const fixed_bytes = context_tokens.serializedLen(self.systemPrompt()) +| self.toolsJson().len;+ const measured = input_tokens +| @as(u64, @intCast(fixed_bytes / 4));const baseline = @min(@as(u64, 8000), self.provider.context / 8);return @max(measured, input_tokens +| baseline);}pub fn fullRequestEstimateTokens(self: *Agent) u64 {- return requestEstimateFromInputBytes(self, jsonSerializedLen(Value{ .array = self.messages }));+ return requestEstimateFromInputBytes(self, context_tokens.serializedLen(Value{ .array = self.messages }));+}++fn requestBodyEstimateTokens(self: *Agent, body_bytes: usize) u64 {+ return context_tokens.estimatedTokensFromLen(Value{ .array = self.messages }, body_bytes);}pub const ContextEstimate = struct {@@ -239,7 +231,7 @@ pub const ContextEstimate = struct {/// occupancy in one history serialization. Callers that need both previously/// walked the entire JSON history twice.pub fn contextEstimate(self: *Agent) ContextEstimate {- return self.contextEstimateFromInputBytes(jsonSerializedLen(Value{ .array = self.messages }));+ return self.contextEstimateFromInputBytes(context_tokens.serializedLen(Value{ .array = self.messages }));}/// Variant for callers already serializing the history (session persistence).@@ -393,13 +385,51 @@ test "inputOverCompactThreshold (#193): local estimate gates a pre-send compact"try std.testing.expect(!inputOverCompactThreshold(&agent));}+test "inputOverCompactThreshold (#260): a fresh Base64 image is vision context, not text" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ const payload = try a.alloc(u8, 1_600_000);+ @memset(payload, 'A');+ const uri = try std.fmt.allocPrint(a, "data:image/png;base64,{s}", .{payload});+ var image_url: std.json.ObjectMap = .empty;+ try image_url.put(a, "url", .{ .string = uri });+ var image: std.json.ObjectMap = .empty;+ try image.put(a, "type", .{ .string = "image_url" });+ try image.put(a, "image_url", .{ .object = image_url });+ var content = std.json.Array.init(a);+ try content.append(.{ .object = image });+ var user: std.json.ObjectMap = .empty;+ try user.put(a, "role", .{ .string = "user" });+ try user.put(a, "content", .{ .array = content });+ var messages = std.json.Array.init(a);+ try messages.append(.{ .object = user });++ var agent: Agent = undefined;+ agent.messages = messages;+ agent.last_context_tokens = 0;+ agent.context_local_tokens = 0;+ agent.sub = false;+ agent.strict = false;+ agent.sys_normal = "";+ agent.sys_strict = "";+ agent.tools_openai = "";+ agent.provider = .{ .id = "codegraff", .kind = .openai, .auth = .bearer, .url = "", .api_key = "", .model = "kimi-k2.6", .context = 262_000 };++ const raw_tokens: u64 = @intCast(context_tokens.serializedLen(Value{ .array = messages }) / 4);+ try std.testing.expect(raw_tokens > agent.provider.compactAt());+ try std.testing.expect(fullInputEstimateTokens(&agent) < 5_000);+ try std.testing.expect(!inputOverCompactThreshold(&agent));+}+pub fn recordUsageResponses(self: *Agent, response: std.json.ObjectMap, req_body_len: usize) void {self.last_cache_read = 0;self.last_usage_includes_output = false;- // Fallback estimate (~4 bytes/token) from the serialized request body,- // which holds the full conversation — keeps the ctx meter and the- // compact@ trigger live when codex omits usage counts entirely.- const est: u64 = req_body_len / 4;+ // Fallback estimate from the serialized request body, with inline Base64+ // images charged as bounded vision tokens rather than text. This keeps the+ // context meter live when Codex omits usage without compacting fresh images.+ const est = requestBodyEstimateTokens(self, req_body_len);// A held Codex WS sends only previous_response_id + the unsent delta, so// body/4 can be tiny even when the preceding response reported a near-full// context. Missing or malformed usage is not evidence that the context gotdiff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zignew file mode 100644index 00000000..9f988df8--- /dev/null+++ b/src/agent_tool_gate.zig@@ -0,0 +1,284 @@+//! Root tool permission gate. Kept separate from agent_tools.zig so the+//! dispatch/meta-tool module stays below the repository's source-size limit.++const std = @import("std");+const main_mod = @import("main.zig");+const agent_mod = @import("agent.zig");+const Agent = agent_mod.Agent;+const tools_mod = @import("tools.zig");+const ToolCall = tools_mod.ToolCall;+const ExecResult = tools_mod.ExecResult;+const mcp = @import("mcp.zig");+const Approvals = @import("approvals.zig").Approvals;+const skills = @import("skills.zig");+const companionTrusted = skills.companionTrusted;+const companionReadOnly = skills.companionReadOnly;+const fleet = @import("fleet.zig");+const telemetry = @import("telemetry.zig");+const learning_privacy = @import("learning_privacy.zig");++const TemplateCandidates = struct {+ items: [16][]const u8 = undefined,+ len: usize = 0,++ fn add(self: *TemplateCandidates, io: std.Io, obj: std.json.ObjectMap) void {+ const prompt = fleet.privateOverride(obj) orelse return;+ if (learning_privacy.isTemplateApproved(io, prompt)) return;+ for (self.items[0..self.len]) |existing| if (std.mem.eql(u8, existing, prompt)) return;+ if (self.len == self.items.len) return;+ self.items[self.len] = prompt;+ self.len += 1;+ }+};++fn collectPrivateTemplates(io: std.Io, call: ToolCall) TemplateCandidates {+ var found: TemplateCandidates = .{};+ if (call.input != .object) return found;+ if (std.mem.eql(u8, call.name, "subagent")) {+ found.add(io, call.input.object);+ return found;+ }+ if (!std.mem.eql(u8, call.name, "workflow")) return found;+ if (call.input.object.get("phases")) |phases| if (phases == .array) {+ for (phases.array.items) |phase| {+ if (phase != .object) continue;+ if (phase.object.get("tasks")) |tasks| if (tasks == .array) {+ for (tasks.array.items) |task| if (task == .object) found.add(io, task.object);+ };+ }+ };+ if (call.input.object.get("pipeline")) |pipeline| if (pipeline == .object) {+ if (pipeline.object.get("stages")) |stages| if (stages == .array) {+ for (stages.array.items) |stage| if (stage == .object) found.add(io, stage.object);+ };+ };+ return found;+}++fn previewLine(buf: []u8, prompt: []const u8) []const u8 {+ const source = prompt[0..@min(prompt.len, buf.len)];+ for (source, 0..) |c, i| buf[i] = if (c < 0x20 or c == 0x7f) ' ' else c;+ return buf[0..source.len];+}++/// Template mode is only a ceiling. A private persona still needs exact+/// interactive approval; no stdin, --yolo, or saved command approval can turn+/// that into content consent. Declining sharing continues the child locally.+fn gatePrivateTemplateSharing(self: *Agent, call: ToolCall) !?ExecResult {+ if (!learning_privacy.allowsTemplateReview() or !main_mod.g_fleet) return null;+ const telem = telemetry.g_telem orelse return null;+ if (!telem.on()) return null;+ const candidates = collectPrivateTemplates(self.io, call);+ if (candidates.len == 0) return null;+ const in = self.in orelse return null;+ const w = self.out orelse return null;++ try w.print(" ⚠ {d} private reusable subagent template{s} could be published\n", .{ candidates.len, if (candidates.len == 1) "" else "s" });+ var blocked_kind: []const u8 = "";+ for (candidates.items[0..candidates.len]) |prompt| {+ const fp = learning_privacy.displayFingerprint(prompt);+ const scan = learning_privacy.scanSecrets(prompt);+ if (!scan.safe() and blocked_kind.len == 0) blocked_kind = scan.first_kind;+ var pbuf: [120]u8 = undefined;+ try w.print(" {s} · {d} bytes · {s}{s}\n", .{ &fp, prompt.len, previewLine(&pbuf, prompt), if (prompt.len > pbuf.len) "…" else "" });+ }+ if (blocked_kind.len > 0) {+ try w.print(" blocked by local secret scan ({s}); child will run locally and no template text will be sent.\n", .{blocked_kind});+ try w.flush();+ return null;+ }+ try w.writeAll(" Sends: exact reusable system/persona text. Excludes: task prompt, bindings, code, paths, reports, and tool results.\n");+ try w.writeAll(" [y] share exact template version(s) this session · [l] run locally · [n] cancel child › ");+ try w.flush();+ const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";+ const answer = std.mem.trim(u8, raw, " \t\r");+ if (answer.len > 0 and (answer[0] == 'y' or answer[0] == 'Y')) {+ for (candidates.items[0..candidates.len]) |prompt| {+ if (!learning_privacy.approveTemplate(self.io, prompt)) return .{+ .text = try self.arena.dupe(u8, "template approval failed closed; retry locally or inspect the prompt for secret-like content"),+ .is_error = true,+ };+ }+ return null;+ }+ if (answer.len == 0 or answer[0] == 'l' or answer[0] == 'L') return null;+ return .{+ .text = try self.arena.dupe(u8, "user cancelled the child at the template-publication boundary"),+ .is_error = true,+ };+}++/// The permission gate, root side: an unapproved external action prompts the+/// user. Subagents never prompt; their gate is the executor's allowlist.+pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {+ if (self.sub) {+ if (std.mem.eql(u8, call.name, "learn_candidate")) return .{+ .text = try self.arena.dupe(u8, "learning is root-only — subagents cannot run mutators, evaluators, or publish grades"),+ .is_error = true,+ };+ if (std.mem.eql(u8, call.name, "bash") and call.input == .object) {+ if (call.input.object.get("command")) |cv| if (cv == .string and Approvals.isDestructiveGit(cv.string)) return .{+ .text = try self.arena.dupe(u8, "destructive git is blocked for subagents (no one to confirm) — leave reset --hard / clean -f / force-push / branch -D to the root session"),+ .is_error = true,+ };+ }+ return null;+ }+ if (try gatePrivateTemplateSharing(self, call)) |blocked| return blocked;+ const approvals = self.approvals orelse return null;++ if (main_mod.plan_mode) {+ if (std.mem.eql(u8, call.name, "learn_candidate") or+ std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or+ (mcp.Registry.isMcp(call.name) and !companionReadOnly(call.name, call.input))) return .{+ .text = try self.arena.dupe(u8, "plan mode is on — read-only. Fold this change into the plan you present; the user applies it after approving (/plan toggles the mode off)."),+ .is_error = true,+ };+ if (std.mem.eql(u8, call.name, "bash")) {+ const cmd_val = call.input.object.get("command") orelse return null;+ if (cmd_val != .string) return null;+ const cmd = std.mem.trim(u8, cmd_val.string, " \t");+ if (Approvals.readOnlyAllowed(cmd)) return null;+ if (Approvals.readOnlyExternal(cmd)) {+ if (approvals.planReadAllowed(self.io, cmd)) return null;+ if (self.in) |in| if (self.out) |w| {+ try w.print(" ⚠ plan mode — read outside the project: {s}\n [a]llow read-only access to these paths this session · [n]o › ", .{cmd});+ try w.flush();+ const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";+ const answer = std.mem.trim(u8, raw, " \t\r");+ if (answer.len > 0 and (answer[0] == 'a' or answer[0] == 'A' or answer[0] == 'y' or answer[0] == 'Y')) {+ try approvals.approvePlanRead(self.io, self.gpa, cmd);+ return null;+ }+ };+ return .{+ .text = try self.arena.dupe(u8, "plan mode — read-only access outside the project was declined; describe what you need read in the plan instead"),+ .is_error = true,+ };+ }+ return .{+ .text = try self.arena.dupe(u8, "plan mode is on — only read-only commands run (ls/cat/grep/git status…). Put this command in the plan instead."),+ .is_error = true,+ };+ }+ }++ var key: []const u8 = undefined;+ var line_buf: [256]u8 = undefined;+ var prompt_line: []const u8 = undefined;+ if (std.mem.eql(u8, call.name, "bash")) {+ const cmd_val = call.input.object.get("command") orelse return null;+ if (cmd_val != .string) return null;+ const cmd = std.mem.trim(u8, cmd_val.string, " \t");+ const destructive_git = Approvals.isDestructiveGit(cmd);+ const gate_ok = !destructive_git or Approvals.destructiveGitAllowed(approvals.yolo, self.sub);+ if (gate_ok and approvals.allowed(self.io, cmd)) return null;+ key = firstWord(cmd);+ prompt_line = if (destructive_git)+ std.fmt.bufPrint(&line_buf, "DESTRUCTIVE git — run: {s}", .{cmd}) catch cmd+ else+ std.fmt.bufPrint(&line_buf, "run: {s}", .{cmd}) catch cmd;+ } else if (std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file")) {+ if (approvals.allowedExact(self.io, call.name)) return null;+ key = call.name;+ const path = if (call.input == .object)+ (if (call.input.object.get("path")) |p| (if (p == .string) p.string else "?") else "?")+ else+ "?";+ prompt_line = std.fmt.bufPrint(&line_buf, "{s} {s}", .{ call.name, path }) catch call.name;+ } else if (std.mem.eql(u8, call.name, "learn_candidate")) {+ if (!learning_privacy.allowsAggregate()) {+ const in = self.in orelse return .{+ .text = try self.arena.dupe(u8, "learning privacy is Local and no interactive user can approve this one-shot aggregate submission"),+ .is_error = true,+ };+ const w = self.out orelse return .{+ .text = try self.arena.dupe(u8, "learning privacy is Local and no interactive user can approve this one-shot aggregate submission"),+ .is_error = true,+ };+ try w.writeAll(+ " ⚠ learn_candidate will run the pinned adapters, then send signed aggregate grades once\n" +++ " Adapter egress: a configured model adapter may send prompt/genome text to its model provider.\n" +++ " Sends: pass rates, prompt/parent fingerprints, run/suite/cohort and evidence IDs.\n" +++ " Excludes: prompt/genome text, tasks, code, paths, evaluator input/output, and traces.\n" +++ " [y] run + send once · [n] cancel › ",+ );+ try w.flush();+ const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";+ const answer = std.mem.trim(u8, raw, " \t\r");+ if (answer.len > 0 and (answer[0] == 'y' or answer[0] == 'Y')) {+ learning_privacy.authorizeAggregateOnce(self.io);+ return null;+ }+ return .{+ .text = try self.arena.dupe(u8, "user declined the bundled learning submission"),+ .is_error = true,+ };+ }+ if (approvals.allowedExact(self.io, call.name)) return null;+ key = call.name;+ prompt_line = "run pinned learning mutator/evaluator and submit signed aggregate grades";+ } else if (mcp.Registry.isMcp(call.name)) {+ if (companionTrusted(call.name)) return null;+ if (approvals.allowedExact(self.io, call.name)) return null;+ key = call.name;+ prompt_line = std.fmt.bufPrint(&line_buf, "call MCP tool {s}", .{call.name}) catch call.name;+ } else return null;++ const in = self.in orelse return .{+ .text = try self.arena.dupe(u8, "not pre-approved, and no interactive user to ask in one-shot mode — pre-approve it in .harness/settings.json, or run with --yolo"),+ .is_error = true,+ };+ const w = self.out orelse return .{+ .text = try self.arena.dupe(u8, "not pre-approved, and no interactive user to ask — pre-approve it in .harness/settings.json, or run with --yolo"),+ .is_error = true,+ };+ try w.print(" ⚠ {s}\n [y]es once · [a]lways allow \"{s}\" (saved to {s}) · [n]o › ", .{ prompt_line, key, Approvals.settings_path });+ try w.flush();+ const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";+ const answer = std.mem.trim(u8, raw, " \t\r");+ if (answer.len > 0) switch (answer[0]) {+ 'y', 'Y' => return null,+ 'a', 'A' => {+ try approvals.approve(self.io, self.gpa, key);+ if (std.mem.eql(u8, call.name, "bash") and Approvals.isInterpreter(key)) {+ try w.print(" note: \"{s}\" can execute arbitrary code (e.g. {s} -c '…'); approving it is effectively unrestricted.\n", .{ key, key });+ try w.flush();+ }+ return null;+ },+ else => {},+ };+ return .{+ .text = try self.arena.dupe(u8, "user declined this tool call — try another approach or ask them how to proceed"),+ .is_error = true,+ };+}++pub fn firstWord(cmd: []const u8) []const u8 {+ const end = std.mem.indexOfAny(u8, cmd, " \t") orelse cmd.len;+ return cmd[0..end];+}++test "firstWord splits the command on the first whitespace" {+ try std.testing.expectEqualStrings("git", firstWord("git status -s"));+ try std.testing.expectEqualStrings("ls", firstWord("ls"));+ try std.testing.expectEqualStrings("cat", firstWord("cat\tfile"));+ try std.testing.expectEqualStrings("", firstWord(""));+ try std.testing.expectEqualStrings("", firstWord(" leading"));+}++test "private template collector covers subagents and workflow stages" {+ const io = std.testing.io;+ learning_privacy.setMode(io, .templates);+ defer learning_privacy.setMode(io, .local);+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const sub_value = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"system_prompt\":\"private one\",\"prompt\":\"task\"}", .{});+ const sub = collectPrivateTemplates(io, .{ .id = "1", .name = "subagent", .input = sub_value });+ try std.testing.expectEqual(@as(usize, 1), sub.len);+ const wf_value = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"phases\":[{\"tasks\":[{\"system_prompt\":\"phase private\",\"prompt\":\"x\"}]}],\"pipeline\":{\"stages\":[{\"system_prompt\":\"stage private\",\"prompt\":\"y\"}]}}", .{});+ const wf = collectPrivateTemplates(io, .{ .id = "2", .name = "workflow", .input = wf_value });+ try std.testing.expectEqual(@as(usize, 2), wf.len);+}diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex 663cd4b5..7d5295d9 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -26,17 +26,10 @@ const style = &ansi.style;const terminal = @import("term.zig");const tty = terminal.tty;-const mcp = @import("mcp.zig");--const approvals_mod = @import("approvals.zig");-const Approvals = approvals_mod.Approvals;--const skills = @import("skills.zig");-const companionTrusted = skills.companionTrusted;-const companionReadOnly = skills.companionReadOnly;-const schema = @import("schema.zig");const isMetaName = schema.isMetaName;+pub const gateTool = @import("agent_tool_gate.zig").gateTool;+pub const firstWord = @import("agent_tool_gate.zig").firstWord;const tools_mod = @import("tools.zig");const ToolCtx = tools_mod.ToolCtx;@@ -217,145 +210,6 @@ pub fn emitToolRejected(self: *Agent, call: ToolCall, reason: []const u8, messagself.emit(.{ .type = "tool_rejected", .name = call.name, .reason = reason, .input = call.input, .message = message });}-/// The permission gate, root side: an unapproved bash command prompts-/// the user — yes once, always (approve the command's first word for-/// the rest of the session), or no. Returns the denial result, or null-/// when cleared to execute. Subagents never prompt; their gate is the-/// allowlist check in execToolInner.-pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {- if (self.sub) {- // Destructive git is blocked for subagents outright — they have no- // human to confirm with. The root agent falls through to a y/n- // prompt below. Completes the Codex-style `.git` guard across both.- if (std.mem.eql(u8, call.name, "bash") and call.input == .object) {- if (call.input.object.get("command")) |cv| if (cv == .string and Approvals.isDestructiveGit(cv.string)) return .{- .text = try self.arena.dupe(u8, "destructive git is blocked for subagents (no one to confirm) — leave reset --hard / clean -f / force-push / branch -D to the root session"),- .is_error = true,- };- }- return null; // subagents: otherwise gated structurally, not by prompt- }- const approvals = self.approvals orelse return null;-- // Plan mode: read-only, regardless of approvals — deny mutating tools- // up front (no point prompting for something the mode forbids).- if (main_mod.plan_mode) {- if (std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or- (mcp.Registry.isMcp(call.name) and !companionReadOnly(call.name, call.input))) return .{- .text = try self.arena.dupe(u8, "plan mode is on — read-only. Fold this change into the plan you present; the user applies it after approving (/plan toggles the mode off)."),- .is_error = true,- };- if (std.mem.eql(u8, call.name, "bash")) {- const cmd_val = call.input.object.get("command") orelse return null;- if (cmd_val != .string) return null;- const cmd = std.mem.trim(u8, cmd_val.string, " \t");- // Safe, cwd-confined read-only commands auto-run (unchanged).- if (Approvals.readOnlyAllowed(cmd)) return null;- // A read-only verb reading OUTSIDE cwd is the sibling-repo case (#64):- // allow once the user approves those paths this session, else prompt.- // Mutating verbs / metacharacter smuggling fall through to the deny.- if (Approvals.readOnlyExternal(cmd)) {- if (approvals.planReadAllowed(self.io, cmd)) return null;- if (self.in) |in| if (self.out) |w| {- try w.print(" ⚠ plan mode — read outside the project: {s}\n [a]llow read-only access to these paths this session · [n]o › ", .{cmd});- try w.flush();- const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";- const answer = std.mem.trim(u8, raw, " \t\r");- if (answer.len > 0 and (answer[0] == 'a' or answer[0] == 'A' or answer[0] == 'y' or answer[0] == 'Y')) {- try approvals.approvePlanRead(self.io, self.gpa, cmd);- return null;- }- };- return .{- .text = try self.arena.dupe(u8, "plan mode — read-only access outside the project was declined; describe what you need read in the plan instead"),- .is_error = true,- };- }- return .{- .text = try self.arena.dupe(u8, "plan mode is on — only read-only commands run (ls/cat/grep/git status…). Put this command in the plan instead."),- .is_error = true,- };- }- }-- // Decide whether this call needs approval, and what the approval key- // and prompt line are. bash keys on the command's first word; writes- // and MCP tools key on the tool name.- var key: []const u8 = undefined;- var line_buf: [256]u8 = undefined;- var prompt_line: []const u8 = undefined;-- if (std.mem.eql(u8, call.name, "bash")) {- const cmd_val = call.input.object.get("command") orelse return null;- if (cmd_val != .string) return null;- const cmd = std.mem.trim(u8, cmd_val.string, " \t");- // Destructive git (reset --hard, clean -f, branch -D, force-push…)- // stays gated in normal mode + for subagents, but DOES run under --yolo- // so the agent can't wipe the user's work or a worktree's checkpoints.- // It falls through to a human y/n (or a deny in non-interactive runs).- const destructive_git = Approvals.isDestructiveGit(cmd);- const gate_ok = !destructive_git or Approvals.destructiveGitAllowed(approvals.yolo, self.sub);- if (gate_ok and approvals.allowed(self.io, cmd)) return null;- key = firstWord(cmd);- prompt_line = if (destructive_git)- std.fmt.bufPrint(&line_buf, "DESTRUCTIVE git — run: {s}", .{cmd}) catch cmd- else- std.fmt.bufPrint(&line_buf, "run: {s}", .{cmd}) catch cmd;- } else if (std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file")) {- if (approvals.allowedExact(self.io, call.name)) return null;- key = call.name;- const path = if (call.input == .object)- (if (call.input.object.get("path")) |p| (if (p == .string) p.string else "?") else "?")- else- "?";- prompt_line = std.fmt.bufPrint(&line_buf, "{s} {s}", .{ call.name, path }) catch call.name;- } else if (mcp.Registry.isMcp(call.name)) {- if (companionTrusted(call.name)) return null; // the whole suite: like native tools- if (approvals.allowedExact(self.io, call.name)) return null;- key = call.name;- prompt_line = std.fmt.bufPrint(&line_buf, "call MCP tool {s}", .{call.name}) catch call.name;- } else {- return null; // read_file, subagent, workflow, meta: not gated- }-- // No human to ask (one-shot -p, or stdin gone): deny instead of- // hanging. Pre-approve in .harness/settings.json or pass --yolo.- const in = self.in orelse return .{- .text = try self.arena.dupe(u8, "not pre-approved, and no interactive user to ask in one-shot mode — pre-approve it in .harness/settings.json, or run with --yolo"),- .is_error = true,- };- const w = self.out orelse return .{- .text = try self.arena.dupe(u8, "not pre-approved, and no interactive user to ask — pre-approve it in .harness/settings.json, or run with --yolo"),- .is_error = true,- };-- try w.print(" ⚠ {s}\n [y]es once · [a]lways allow \"{s}\" (saved to {s}) · [n]o › ", .{ prompt_line, key, Approvals.settings_path });- try w.flush();- const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";- const answer = std.mem.trim(u8, raw, " \t\r");- if (answer.len > 0) switch (answer[0]) {- 'y', 'Y' => return null,- 'a', 'A' => {- try approvals.approve(self.io, self.gpa, key);- if (std.mem.eql(u8, call.name, "bash") and Approvals.isInterpreter(key)) {- try w.print(" note: \"{s}\" can execute arbitrary code (e.g. {s} -c '…'); approving it is effectively unrestricted.\n", .{ key, key });- try w.flush();- }- return null;- },- else => {},- };- return .{- .text = try self.arena.dupe(u8, "user declined this tool call — try another approach or ask them how to proceed"),- .is_error = true,- };-}--pub fn firstWord(cmd: []const u8) []const u8 {- const end = std.mem.indexOfAny(u8, cmd, " \t") orelse cmd.len;- return cmd[0..end];-}-/// #225: clock_sleep meta tool — root-only, feature-flagged (main.zig/// g_clock_sleep / --clock-sleep / GRAFF_CLOCK_SLEEP=1). Mirrors codex's/// clock.sleep: capped at 12h, cancelled by user input like any other@@ -565,14 +419,6 @@ pub fn sayToolResult(self: *Agent, name: []const u8, r: ExecResult) void {w.flush() catch return;}-test "firstWord: splits the command on the first whitespace" {- try std.testing.expectEqualStrings("git", firstWord("git status -s"));- try std.testing.expectEqualStrings("ls", firstWord("ls"));- try std.testing.expectEqualStrings("cat", firstWord("cat\tfile")); // tab delimiter- try std.testing.expectEqualStrings("", firstWord(""));- try std.testing.expectEqualStrings("", firstWord(" leading"));-}-test "parseClockSleepMs: valid ms passes through, missing/negative/non-integer reject, over-cap clamps (#225)" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();diff --git a/src/args.zig b/src/args.zigindex 63a612ba..04104235 100644--- a/src/args.zig+++ b/src/args.zig@@ -23,6 +23,7 @@ const std = @import("std");const Allocator = std.mem.Allocator;const main_mod = @import("main.zig");+const learning_privacy = @import("learning_privacy.zig");/// Every CLI-flag local main() used to declare, plus the resolved/// positionals/subcommand-detection/one-shot-prompt outputs computed right@@ -30,6 +31,7 @@ const main_mod = @import("main.zig");pub const Flags = struct {yolo_flag: bool = false,no_telemetry_flag: bool = false,+ learning_privacy_flag: ?learning_privacy.Mode = null,schema_flag: bool = false,login_flag: bool = false,refresh_flag: bool = false,@@ -99,6 +101,9 @@ pub fn parse(init: std.process.Init) !Flags {flags.eval_niche_flag = it.next() orelse std.process.fatal("--niche needs a name (e.g. --niche reviewer)", .{});} else if (std.mem.eql(u8, arg, "--no-telemetry")) {flags.no_telemetry_flag = true;+ } else if (std.mem.eql(u8, arg, "--learning-privacy")) {+ const value = it.next() orelse std.process.fatal("--learning-privacy needs local|aggregate|templates|examples", .{});+ flags.learning_privacy_flag = learning_privacy.parse(value) orelse std.process.fatal("invalid learning privacy mode '{s}' — use local|aggregate|templates|examples", .{value});} else if (std.mem.eql(u8, arg, "--timing")) {main_mod.show_timing = true;} else if (std.mem.eql(u8, arg, "--cost")) {diff --git a/src/behavior_trace.zig b/src/behavior_trace.zigindex d1c4cced..f6116b19 100644--- a/src/behavior_trace.zig+++ b/src/behavior_trace.zig@@ -15,6 +15,7 @@ const trace = @import("trace.zig");test {_ = @import("behavior_trace_tests.zig");+ _ = @import("behavior_trace_rich_tests.zig");}// ── Behavioral trace (one experimental event file per run) ────────────────diff --git a/src/behavior_trace_rich_tests.zig b/src/behavior_trace_rich_tests.zignew file mode 100644index 00000000..e5e32323--- /dev/null+++ b/src/behavior_trace_rich_tests.zig@@ -0,0 +1,265 @@+//! Opt-in rich behavioral capture tests, split from the lifecycle suite.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const btrace = @import("behavior_trace.zig");+const BehaviorTrace = btrace.BehaviorTrace;+const max_text_delta_bytes = btrace.max_text_delta_bytes;+const max_tool_args_bytes = btrace.max_tool_args_bytes;+const behavior_upload = @import("behavior_upload.zig");+const Tracer = @import("trace.zig").Tracer;++test "BehaviorTrace: rich kinds are gated by GRAFF_BEHAVIOR_TRACE=full (#255)" {+ 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 = "rich-gate-run",+ };+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));+ try std.testing.expectEqual(@as(u64, 2), behavior.seq); // run_started + turn_started++ // rich defaults to false: every typed rich emitter is a no-op, even with+ // a live local sink and a valid turn/call_id.+ const call_id = behavior.reserveCallId();+ behavior.toolStarted(1, call_id, "edit_file", "{}");+ behavior.toolFinished(1, call_id, "edit_file", 5, false, 10);+ behavior.actionTaken(1, call_id, "edit_file", false);+ behavior.textDelta(1, "hello");+ try std.testing.expectEqual(@as(u64, 2), behavior.seq);++ // rich == true: the same calls now emit tool_started, tool_finished,+ // action_taken (edit_file is a write-class tool), and text_delta.+ behavior.rich = true;+ const call_id2 = behavior.reserveCallId();+ behavior.toolStarted(1, call_id2, "edit_file", "{\"path\":\"a.zig\"}");+ behavior.toolFinished(1, call_id2, "edit_file", 5, false, 10);+ behavior.actionTaken(1, call_id2, "edit_file", false);+ behavior.textDelta(1, "hello");+ try std.testing.expectEqual(@as(u64, 6), behavior.seq);++ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');+ _ = lines.next(); // run_started+ _ = lines.next(); // turn_started++ var started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer started.deinit();+ try std.testing.expectEqualStrings("tool_started", started.value.object.get("kind").?.string);+ try std.testing.expectEqual(@as(i64, @intCast(call_id2)), started.value.object.get("call_id").?.integer);+ try std.testing.expectEqualStrings("a.zig", started.value.object.get("args").?.object.get("path").?.string);+ try std.testing.expect(!started.value.object.get("args_truncated").?.bool);++ var finished = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer finished.deinit();+ try std.testing.expectEqualStrings("tool_finished", finished.value.object.get("kind").?.string);+ try std.testing.expectEqual(@as(i64, @intCast(call_id2)), finished.value.object.get("call_id").?.integer);+ try std.testing.expect(!finished.value.object.get("is_error").?.bool);++ var action = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer action.deinit();+ try std.testing.expectEqualStrings("action_taken", action.value.object.get("kind").?.string);+ try std.testing.expectEqual(@as(i64, @intCast(call_id2)), action.value.object.get("call_id").?.integer);++ var text = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer text.deinit();+ try std.testing.expectEqualStrings("text_delta", text.value.object.get("kind").?.string);+ try std.testing.expectEqualStrings("hello", text.value.object.get("text").?.string);+ try std.testing.expect(lines.next() == null);+}++test "BehaviorTrace: action_taken skips non-mutating tool classes even when rich (#255)" {+ 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 = "action-class-run",+ .rich = true,+ };+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));+ const before = behavior.seq;+ // read_file is a read-class tool: an observation, not an action.+ behavior.actionTaken(1, behavior.reserveCallId(), "read_file", false);+ try std.testing.expectEqual(before, behavior.seq);+ // bash is shell-class: a state mutation.+ behavior.actionTaken(1, behavior.reserveCallId(), "bash", true);+ try std.testing.expectEqual(before + 1, behavior.seq);+}++test "BehaviorTrace: rich caps truncate args and text without corrupting JSON (#255)" {+ 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 = "cap-run",+ .rich = true,+ };+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));++ // Oversized args are never re-parsed as JSON, even when the raw bytes+ // happen to look JSON-ish up to the cut point — always a plain string.+ const oversized_args = try gpa.alloc(u8, max_tool_args_bytes + 1);+ defer gpa.free(oversized_args);+ @memset(oversized_args, 'a');+ oversized_args[0] = '{';+ behavior.toolStarted(1, 1, "bash", oversized_args);++ const oversized_text = try gpa.alloc(u8, max_text_delta_bytes + 1);+ defer gpa.free(oversized_text);+ @memset(oversized_text, 'b');+ behavior.textDelta(1, oversized_text);++ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');+ _ = lines.next(); // run_started+ _ = lines.next(); // turn_started++ var started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer started.deinit();+ try std.testing.expect(started.value.object.get("args_truncated").?.bool);+ try std.testing.expect(started.value.object.get("args").? == .string);+ try std.testing.expectEqual(@as(usize, max_tool_args_bytes), started.value.object.get("args").?.string.len);++ var text = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer text.deinit();+ try std.testing.expect(text.value.object.get("text_truncated").?.bool);+ try std.testing.expectEqual(@as(usize, max_text_delta_bytes), text.value.object.get("text").?.string.len);+ try std.testing.expect(lines.next() == null);+}++test "BehaviorTrace: rich kinds never reach the uploader (#255)" {+ 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('u'),+ .client_name = "harness",+ .service_version = "test",+ .run_id = "0123456789abcdef",+ .mode = .content, // the most permissive collector mode+ };+ defer upload.deinit();+ var behavior: BehaviorTrace = .{+ .io = io,+ .gpa = gpa,+ .out = &local.writer,+ .upload = &upload,+ .run_id = "0123456789abcdef",+ .rich = true,+ };+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));+ // run_started + turn_started are upload-eligible.+ try std.testing.expectEqual(@as(usize, 2), upload.events.items.len);++ const call_id = behavior.reserveCallId();+ behavior.toolStarted(1, call_id, "bash", "{\"command\":\"ls\"}");+ behavior.toolFinished(1, call_id, "bash", 5, false, 10);+ behavior.actionTaken(1, call_id, "bash", false);+ behavior.textDelta(1, "hello");++ // The local file grew by four lines, but the uploader saw nothing new,+ // and none of it counted as a drop — a documented exclusion, not a loss.+ try std.testing.expectEqual(@as(usize, 2), upload.events.items.len);+ try std.testing.expectEqual(@as(u64, 0), upload.dropped_events);+ try std.testing.expectEqual(@as(u64, 6), behavior.seq);+}++test "BehaviorTrace.reserveCallId: monotonic per run, independent of lifecycle state (#255)" {+ const io = std.testing.io;+ var behavior: BehaviorTrace = .{+ .io = io,+ .gpa = std.testing.allocator,+ .out = null,+ .run_id = "call-id-run",+ };+ try std.testing.expectEqual(@as(u64, 1), behavior.reserveCallId());+ try std.testing.expectEqual(@as(u64, 2), behavior.reserveCallId());+ try std.testing.expectEqual(@as(u64, 3), behavior.reserveCallId());+ // Reservation never no-ops, unlike the typed emitters (rich/turn gated).+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 4), behavior.reserveCallId());+}++test "Tracer.toolStarted/toolFinished: call_id pairs interleaved calls (#255)" {+ 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 = "tracer-run",+ .rich = true,+ };+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));+ var tracer: Tracer = .{+ .io = io,+ .gpa = gpa,+ .out = null,+ .start = Io.Timestamp.now(io, .awake),+ .behavior = &behavior,+ };++ var args = try std.json.parseFromSlice(Value, gpa, "{\"command\":\"ls\"}", .{});+ defer args.deinit();+ const call_a = tracer.toolStarted("bash", args.value);+ const call_b = tracer.toolStarted("bash", args.value);+ try std.testing.expect(call_a != 0 and call_b != 0 and call_a != call_b);+ // Finish out of order: the second call started finishes first.+ tracer.toolFinished("bash", call_b, 3, false, 5);+ tracer.toolFinished("bash", call_a, 7, true, 9);++ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');+ _ = lines.next(); // run_started+ _ = lines.next(); // turn_started++ var started_a = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer started_a.deinit();+ try std.testing.expectEqual(@as(i64, @intCast(call_a)), started_a.value.object.get("call_id").?.integer);++ var started_b = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer started_b.deinit();+ try std.testing.expectEqual(@as(i64, @intCast(call_b)), started_b.value.object.get("call_id").?.integer);++ var finished_b = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer finished_b.deinit();+ try std.testing.expectEqualStrings("tool_finished", finished_b.value.object.get("kind").?.string);+ try std.testing.expectEqual(@as(i64, @intCast(call_b)), finished_b.value.object.get("call_id").?.integer);++ var action_b = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer action_b.deinit();+ try std.testing.expectEqualStrings("action_taken", action_b.value.object.get("kind").?.string);+ try std.testing.expectEqual(@as(i64, @intCast(call_b)), action_b.value.object.get("call_id").?.integer);++ var finished_a = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer finished_a.deinit();+ try std.testing.expectEqual(@as(i64, @intCast(call_a)), finished_a.value.object.get("call_id").?.integer);+ try std.testing.expect(finished_a.value.object.get("is_error").?.bool);++ var action_a = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer action_a.deinit();+ try std.testing.expectEqualStrings("action_taken", action_a.value.object.get("kind").?.string);+ try std.testing.expect(lines.next() == null);+}diff --git a/src/behavior_trace_tests.zig b/src/behavior_trace_tests.zigindex 26487bc8..3d66483b 100644--- a/src/behavior_trace_tests.zig+++ b/src/behavior_trace_tests.zig@@ -564,257 +564,3 @@ test "endRootTurn: clears attribution while preserving the dense parent chain" {try std.testing.expectEqual(@as(i64, 1), second_started.value.object.get("parent_turn").?.integer);try std.testing.expect(lines.next() == null);}--test "BehaviorTrace: rich kinds are gated by GRAFF_BEHAVIOR_TRACE=full (#255)" {- 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 = "rich-gate-run",- };- behavior.start("test", 1);- try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));- try std.testing.expectEqual(@as(u64, 2), behavior.seq); // run_started + turn_started-- // rich defaults to false: every typed rich emitter is a no-op, even with- // a live local sink and a valid turn/call_id.- const call_id = behavior.reserveCallId();- behavior.toolStarted(1, call_id, "edit_file", "{}");- behavior.toolFinished(1, call_id, "edit_file", 5, false, 10);- behavior.actionTaken(1, call_id, "edit_file", false);- behavior.textDelta(1, "hello");- try std.testing.expectEqual(@as(u64, 2), behavior.seq);-- // rich == true: the same calls now emit tool_started, tool_finished,- // action_taken (edit_file is a write-class tool), and text_delta.- behavior.rich = true;- const call_id2 = behavior.reserveCallId();- behavior.toolStarted(1, call_id2, "edit_file", "{\"path\":\"a.zig\"}");- behavior.toolFinished(1, call_id2, "edit_file", 5, false, 10);- behavior.actionTaken(1, call_id2, "edit_file", false);- behavior.textDelta(1, "hello");- try std.testing.expectEqual(@as(u64, 6), behavior.seq);-- var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');- _ = lines.next(); // run_started- _ = lines.next(); // turn_started-- var started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer started.deinit();- try std.testing.expectEqualStrings("tool_started", started.value.object.get("kind").?.string);- try std.testing.expectEqual(@as(i64, @intCast(call_id2)), started.value.object.get("call_id").?.integer);- try std.testing.expectEqualStrings("a.zig", started.value.object.get("args").?.object.get("path").?.string);- try std.testing.expect(!started.value.object.get("args_truncated").?.bool);-- var finished = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer finished.deinit();- try std.testing.expectEqualStrings("tool_finished", finished.value.object.get("kind").?.string);- try std.testing.expectEqual(@as(i64, @intCast(call_id2)), finished.value.object.get("call_id").?.integer);- try std.testing.expect(!finished.value.object.get("is_error").?.bool);-- var action = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer action.deinit();- try std.testing.expectEqualStrings("action_taken", action.value.object.get("kind").?.string);- try std.testing.expectEqual(@as(i64, @intCast(call_id2)), action.value.object.get("call_id").?.integer);-- var text = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer text.deinit();- try std.testing.expectEqualStrings("text_delta", text.value.object.get("kind").?.string);- try std.testing.expectEqualStrings("hello", text.value.object.get("text").?.string);- try std.testing.expect(lines.next() == null);-}--test "BehaviorTrace: action_taken skips non-mutating tool classes even when rich (#255)" {- 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 = "action-class-run",- .rich = true,- };- behavior.start("test", 1);- try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));- const before = behavior.seq;- // read_file is a read-class tool: an observation, not an action.- behavior.actionTaken(1, behavior.reserveCallId(), "read_file", false);- try std.testing.expectEqual(before, behavior.seq);- // bash is shell-class: a state mutation.- behavior.actionTaken(1, behavior.reserveCallId(), "bash", true);- try std.testing.expectEqual(before + 1, behavior.seq);-}--test "BehaviorTrace: rich caps truncate args and text without corrupting JSON (#255)" {- 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 = "cap-run",- .rich = true,- };- behavior.start("test", 1);- try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));-- // Oversized args are never re-parsed as JSON, even when the raw bytes- // happen to look JSON-ish up to the cut point — always a plain string.- const oversized_args = try gpa.alloc(u8, max_tool_args_bytes + 1);- defer gpa.free(oversized_args);- @memset(oversized_args, 'a');- oversized_args[0] = '{';- behavior.toolStarted(1, 1, "bash", oversized_args);-- const oversized_text = try gpa.alloc(u8, max_text_delta_bytes + 1);- defer gpa.free(oversized_text);- @memset(oversized_text, 'b');- behavior.textDelta(1, oversized_text);-- var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');- _ = lines.next(); // run_started- _ = lines.next(); // turn_started-- var started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer started.deinit();- try std.testing.expect(started.value.object.get("args_truncated").?.bool);- try std.testing.expect(started.value.object.get("args").? == .string);- try std.testing.expectEqual(@as(usize, max_tool_args_bytes), started.value.object.get("args").?.string.len);-- var text = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer text.deinit();- try std.testing.expect(text.value.object.get("text_truncated").?.bool);- try std.testing.expectEqual(@as(usize, max_text_delta_bytes), text.value.object.get("text").?.string.len);- try std.testing.expect(lines.next() == null);-}--test "BehaviorTrace: rich kinds never reach the uploader (#255)" {- 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('u'),- .client_name = "harness",- .service_version = "test",- .run_id = "0123456789abcdef",- .mode = .content, // the most permissive collector mode- };- defer upload.deinit();- var behavior: BehaviorTrace = .{- .io = io,- .gpa = gpa,- .out = &local.writer,- .upload = &upload,- .run_id = "0123456789abcdef",- .rich = true,- };- behavior.start("test", 1);- try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));- // run_started + turn_started are upload-eligible.- try std.testing.expectEqual(@as(usize, 2), upload.events.items.len);-- const call_id = behavior.reserveCallId();- behavior.toolStarted(1, call_id, "bash", "{\"command\":\"ls\"}");- behavior.toolFinished(1, call_id, "bash", 5, false, 10);- behavior.actionTaken(1, call_id, "bash", false);- behavior.textDelta(1, "hello");-- // The local file grew by four lines, but the uploader saw nothing new,- // and none of it counted as a drop — a documented exclusion, not a loss.- try std.testing.expectEqual(@as(usize, 2), upload.events.items.len);- try std.testing.expectEqual(@as(u64, 0), upload.dropped_events);- try std.testing.expectEqual(@as(u64, 6), behavior.seq);-}--test "BehaviorTrace.reserveCallId: monotonic per run, independent of lifecycle state (#255)" {- const io = std.testing.io;- var behavior: BehaviorTrace = .{- .io = io,- .gpa = std.testing.allocator,- .out = null,- .run_id = "call-id-run",- };- try std.testing.expectEqual(@as(u64, 1), behavior.reserveCallId());- try std.testing.expectEqual(@as(u64, 2), behavior.reserveCallId());- try std.testing.expectEqual(@as(u64, 3), behavior.reserveCallId());- // Reservation never no-ops, unlike the typed emitters (rich/turn gated).- behavior.start("test", 1);- try std.testing.expectEqual(@as(u64, 4), behavior.reserveCallId());-}--test "Tracer.toolStarted/toolFinished: call_id pairs interleaved calls (#255)" {- 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 = "tracer-run",- .rich = true,- };- behavior.start("test", 1);- try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));- var tracer: Tracer = .{- .io = io,- .gpa = gpa,- .out = null,- .start = Io.Timestamp.now(io, .awake),- .behavior = &behavior,- };-- var args = try std.json.parseFromSlice(Value, gpa, "{\"command\":\"ls\"}", .{});- defer args.deinit();- const call_a = tracer.toolStarted("bash", args.value);- const call_b = tracer.toolStarted("bash", args.value);- try std.testing.expect(call_a != 0 and call_b != 0 and call_a != call_b);- // Finish out of order: the second call started finishes first.- tracer.toolFinished("bash", call_b, 3, false, 5);- tracer.toolFinished("bash", call_a, 7, true, 9);-- var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');- _ = lines.next(); // run_started- _ = lines.next(); // turn_started-- var started_a = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer started_a.deinit();- try std.testing.expectEqual(@as(i64, @intCast(call_a)), started_a.value.object.get("call_id").?.integer);-- var started_b = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer started_b.deinit();- try std.testing.expectEqual(@as(i64, @intCast(call_b)), started_b.value.object.get("call_id").?.integer);-- var finished_b = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer finished_b.deinit();- try std.testing.expectEqualStrings("tool_finished", finished_b.value.object.get("kind").?.string);- try std.testing.expectEqual(@as(i64, @intCast(call_b)), finished_b.value.object.get("call_id").?.integer);-- var action_b = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer action_b.deinit();- try std.testing.expectEqualStrings("action_taken", action_b.value.object.get("kind").?.string);- try std.testing.expectEqual(@as(i64, @intCast(call_b)), action_b.value.object.get("call_id").?.integer);-- var finished_a = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer finished_a.deinit();- try std.testing.expectEqual(@as(i64, @intCast(call_a)), finished_a.value.object.get("call_id").?.integer);- try std.testing.expect(finished_a.value.object.get("is_error").?.bool);-- var action_a = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});- defer action_a.deinit();- try std.testing.expectEqualStrings("action_taken", action_a.value.object.get("kind").?.string);- try std.testing.expect(lines.next() == null);-}diff --git a/src/cli.zig b/src/cli.zigindex 97ad59fd..d78edd1a 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -100,6 +100,7 @@ pub const usage_text =\\ --max-model-calls N total provider calls allowed across this run (default 256; includes children/title/judges)\\ --dedupe-tool-calls reject duplicate root tool name+input calls per turn\\ --no-telemetry disable anonymous usage telemetry for this run+ \\ --learning-privacy <mode> learning egress ceiling: local|aggregate|templates|examples (default local)\\ -h, --help this help\\ -V, --version print version\\@@ -113,6 +114,8 @@ pub const usage_text =\\OTEL_EXPORTER_OTLP_ENDPOINT (or GRAFF_OTEL_ENDPOINT) is set; opt out\\with --no-telemetry or GRAFF_NO_TELEMETRY=1. GRAFF_TELEMETRY_KEY sends\\an optional x-harness-key token to the configured collector.+ \\learning privacy: prompt-policy learning stays local by default; /privacy+ \\changes the session ceiling. Template text still needs exact approval.\\;diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 322b9d83..e2fdf5ff 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -42,6 +42,7 @@ pub const commands = [_]Item{.{ .name = "/strict", .desc = "toggle \"every message is a tool\" mode" },.{ .name = "/yolo", .desc = "toggle bash auto-approval (skip permission prompts)" },.{ .name = "/trace", .desc = "toggle this run's JSONL event trace (and show its path)" },+ .{ .name = "/privacy", .usage = "/privacy [local|aggregate|templates|examples]", .desc = "control prompt-learning data egress for this session" },.{ .name = "/trajectory", .desc = "show this session's agent tree — turns + spawned subagents" },.{ .name = "/agents", .desc = "list agent types — builtin personas + .harness/agents/*.md" },.{ .name = "/skills", .usage = "/skills [remove <name>]", .desc = "list available skills; /skills remove <name> disables one" },diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex 8b6029ee..ae8cf24e 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -53,6 +53,8 @@ const PickItem = pickers.PickItem;const listPicker = pickers.listPicker;const trace = @import("trace.zig");+const commands_privacy = @import("commands_privacy.zig");+const learning_privacy = @import("learning_privacy.zig");fn providerModelCount(provider_id: []const u8) usize {var count: usize = 0;@@ -127,6 +129,7 @@ fn showModelsHealth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer/// `line` doesn't match any command in this file — the caller falls through/// to handleRest() for the unknown-command/help terminal stage.pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {+ if (try commands_privacy.tryHandle(root, line, out)) return true;if (std.mem.eql(u8, line, "/todo")) {try out.print("{s}\n", .{root.renderTodos()});try out.flush();@@ -365,10 +368,10 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,if (std.mem.eql(u8, line, "/fleet") or std.mem.startsWith(u8, line, "/fleet ")) {const arg = std.mem.trim(u8, line["/fleet".len..], " \t");if (arg.len == 0) {- try out.print("fleet contribution: {s} — federated DGM (propose/submit/elite_pull). /fleet off to disable, /fleet on to enable (or GRAFF_FLEET=off).\n", .{if (main_mod.g_fleet) "ON" else "off"});+ try out.print("fleet master switch: {s} · learning privacy: {s}. /fleet off kills contribution; /privacy controls what may leave.\n", .{ if (main_mod.g_fleet) "ON" else "off", learning_privacy.current().label() });} else if (std.mem.eql(u8, arg, "on")) {main_mod.g_fleet = true;- try out.writeAll("fleet ON — this session's persona variants + scores contribute to the federated grid.\n");+ try out.writeAll("fleet master switch ON — contribution still follows /privacy (Local sends nothing).\n");} else if (std.mem.eql(u8, arg, "off")) {main_mod.g_fleet = false;try out.writeAll("fleet off — no propose/submit/elite_pull this session (usage telemetry unaffected; /fleet on to re-enable).\n");diff --git a/src/commands_privacy.zig b/src/commands_privacy.zignew file mode 100644index 00000000..1dc76dff--- /dev/null+++ b/src/commands_privacy.zig@@ -0,0 +1,47 @@+//! `/privacy`: session-scoped prompt-learning egress controls.++const std = @import("std");+const Io = std.Io;+const Agent = @import("agent.zig").Agent;+const privacy = @import("learning_privacy.zig");++fn printStatus(out: *Io.Writer) !void {+ const mode = privacy.current();+ try out.print("learning privacy: {s}\n", .{mode.label()});+ try out.writeAll(+ \\ local no background learning egress; learn_candidate may ask to send one aggregate receipt+ \\ aggregate signed grades, counts, buckets, and public strategy IDs; no prompt text+ \\ templates aggregate + individually reviewed reusable persona/template text+ \\ examples templates + a future one-shot reviewed-example channel+ \\+ \\This controls learning/fleet egress, not requests to your selected model provider+ \\or ordinary operational telemetry. Template approval is exact and session-local;+ \\--yolo cannot bypass it. Raw task prompts, bindings, reports, and traces have no+ \\learning upload path in this build.+ \\+ );+}++pub fn tryHandle(root: *Agent, line: []const u8, out: *Io.Writer) !bool {+ if (!std.mem.eql(u8, line, "/privacy") and !std.mem.startsWith(u8, line, "/privacy ")) return false;+ const arg = std.mem.trim(u8, line["/privacy".len..], " \t");+ if (arg.len == 0 or std.mem.eql(u8, arg, "status")) {+ try printStatus(out);+ try out.flush();+ return true;+ }+ const mode = privacy.parse(arg) orelse {+ try out.writeAll("usage: /privacy [status|local|aggregate|templates|examples]\n");+ try out.flush();+ return true;+ };+ privacy.setMode(root.io, mode);+ switch (mode) {+ .local => try out.writeAll("learning privacy → Local; background fleet contribution is off and prior approvals are revoked. learn_candidate must ask separately to send once.\n"),+ .aggregate => try out.writeAll("learning privacy → Aggregate; signed grades and prompt-free fleet metadata may be sent.\n"),+ .templates => try out.writeAll("learning privacy → Templates; each private reusable prompt still needs an exact preview approval.\n"),+ .examples => try out.writeAll("learning privacy → Examples ceiling; templates still need approval, and raw-example upload is not implemented yet.\n"),+ }+ try out.flush();+ return true;+}diff --git a/src/context_tokens.zig b/src/context_tokens.zignew file mode 100644index 00000000..72ab520e--- /dev/null+++ b/src/context_tokens.zig@@ -0,0 +1,126 @@+//! Conservative JSON context estimates that treat inline image bytes as media,+//! not ordinary text. Providers tokenize images from decoded dimensions/content;+//! the Base64 transport size is not part of the language-model context.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;++/// One image can still consume meaningful vision context. This bound is high+/// enough for detailed screenshots while keeping one fresh attachment inside+/// compaction's 8k recent-turn preservation budget.+pub const image_tokens: u64 = 4_096;++const MediaStats = struct {+ payload_bytes: usize = 0,+ images: u64 = 0,++ fn add(self: *MediaStats, other: MediaStats) void {+ self.payload_bytes +|= other.payload_bytes;+ self.images +|= other.images;+ }+};++fn stringValue(value: ?Value) ?[]const u8 {+ const found = value orelse return null;+ return if (found == .string) found.string else null;+}++fn dataImagePayloadLen(uri: []const u8) ?usize {+ if (!std.mem.startsWith(u8, uri, "data:image/")) return null;+ const marker = ";base64,";+ const marker_start = std.mem.indexOf(u8, uri, marker) orelse return null;+ return uri.len - (marker_start + marker.len);+}++fn imageBlockPayloadLen(obj: std.json.ObjectMap) ?usize {+ const kind = stringValue(obj.get("type")) orelse return null;+ if (std.mem.eql(u8, kind, "image_url")) {+ const image_url = obj.get("image_url") orelse return null;+ const uri = switch (image_url) {+ .string => |s| s,+ .object => |nested| stringValue(nested.get("url")) orelse return null,+ else => return null,+ };+ return dataImagePayloadLen(uri);+ }+ if (std.mem.eql(u8, kind, "input_image")) {+ return dataImagePayloadLen(stringValue(obj.get("image_url")) orelse return null);+ }+ if (std.mem.eql(u8, kind, "image")) {+ const source = obj.get("source") orelse return null;+ if (source != .object) return null;+ if (!std.mem.eql(u8, stringValue(source.object.get("type")) orelse return null, "base64")) return null;+ return (stringValue(source.object.get("data")) orelse return null).len;+ }+ return null;+}++fn mediaStats(value: Value) MediaStats {+ var stats: MediaStats = .{};+ switch (value) {+ .array => |items| for (items.items) |item| stats.add(mediaStats(item)),+ .object => |obj| {+ if (imageBlockPayloadLen(obj)) |payload_bytes| {+ stats.payload_bytes +|= payload_bytes;+ stats.images +|= 1;+ }+ var it = obj.iterator();+ while (it.next()) |entry| stats.add(mediaStats(entry.value_ptr.*));+ },+ else => {},+ }+ return stats;+}++/// Count a JSON value's serialized bytes without allocating its output.+pub fn serializedLen(value: anytype) usize {+ var buf: [512]u8 = undefined;+ var discarding: Io.Writer.Discarding = .init(&buf);+ var stringify: std.json.Stringify = .{ .writer = &discarding.writer };+ stringify.write(value) catch return discarding.fullCount();+ return discarding.fullCount();+}++/// Estimate a JSON container when its serialized byte count is already known.+/// Inline image payloads are removed from the text estimate and replaced by a+/// bounded per-image vision estimate; every other byte retains the prior /4+/// policy so tool output and reasoning overflow protection stays conservative.+pub fn estimatedTokensFromLen(value: Value, total_bytes: usize) u64 {+ const media = mediaStats(value);+ const text_bytes = total_bytes -| media.payload_bytes;+ return @as(u64, @intCast(text_bytes / 4)) +| media.images *| image_tokens;+}++pub fn estimatedTokens(value: Value) u64 {+ return estimatedTokensFromLen(value, serializedLen(value));+}++test "inline image payload size does not masquerade as text context" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ const payload = try arena.alloc(u8, 1_600_000);+ @memset(payload, 'A');+ const uri = try std.fmt.allocPrint(arena, "data:image/png;base64,{s}", .{payload});+ var image_url: std.json.ObjectMap = .empty;+ try image_url.put(arena, "url", .{ .string = uri });+ var block: std.json.ObjectMap = .empty;+ try block.put(arena, "type", .{ .string = "image_url" });+ try block.put(arena, "image_url", .{ .object = image_url });++ const value: Value = .{ .object = block };+ try std.testing.expect(serializedLen(value) / 4 > 390_000);+ try std.testing.expect(estimatedTokens(value) >= image_tokens);+ try std.testing.expect(estimatedTokens(value) < 5_000);+}++test "ordinary large strings remain fully counted" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const text = try arena.alloc(u8, 40_000);+ @memset(text, 'A');+ try std.testing.expect(estimatedTokens(.{ .string = text }) >= 10_000);+}diff --git a/src/exec.zig b/src/exec.zigindex 65712fcf..056dd095 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -1,10 +1,10 @@//! Tool dispatch: `execTool` (the timed/traced/hooked outer wrapper) and//! `execToolInner` (the big per-tool-name switch — bash, bash_output,//! bash_kill, webfetch, read_file, codedb, edit_file, write_file, subagent,-//! workflow). Split out of main.zig (600-line goal); LAST in the tool-exec+//! workflow, learn_candidate). Split out of main.zig (600-line goal); LAST in the tool-exec//! region since it's the glue that imports tools.zig/subagent.zig///! workflow.zig as siblings, plus approvals.zig/mcp.zig/jobs.zig/skills.zig/-//! input_util.zig/telemetry.zig. Back-imports main (as `main_mod`) for+//! telemetry.zig. Back-imports main (as `main_mod`) for//! `ToolCall`/`plan_mode` (pub-flipped) and `utf8Prefix`.const std = @import("std");@@ -52,10 +52,10 @@ const jobOutput = jobs.jobOutput;const jobKill = jobs.jobKill;const shellArgv = jobs.shellArgv;const skills = @import("skills.zig");-const input_util = @import("input_util.zig");-const binaryFileExt = input_util.binaryFileExt;+const read_file = @import("read_file.zig");const hooks = @import("hooks.zig");const telemetry = @import("telemetry.zig");+const learning_privacy = @import("learning_privacy.zig");/// Wall-clock ceiling for one *subagent* bash command. Subagents run on pool/// threads with no TTY, so there is no Esc to kill a runaway command — without@@ -64,6 +64,19 @@ const telemetry = @import("telemetry.zig");/// no-deadline behavior (a human is watching and may want a long build).const subagent_bash_deadline_ms: u64 = 120 * 1000;+fn learningArgv(argv: *[10][]const u8, exe_path: []const u8, contribute: bool) usize {+ var argc: usize = 0;+ for ([_][]const u8{ exe_path, "--learning-privacy", if (contribute) "aggregate" else "local", "learn", "run" }) |arg| {+ argv[argc] = arg;+ argc += 1;+ }+ if (contribute) {+ argv[argc] = "--submit";+ argc += 1;+ }+ return argc;+}+/// Runs on a pool thread; never throws — failures become is_error results./// Every execution is timed (out.ms) and traced.pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {@@ -107,7 +120,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {// Plan mode backstop: the root gate already denies these with a nicer// message; this catches subagents (which skip the gate entirely).if (main_mod.plan_mode) {- if (std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or mcp.Registry.isMcp(call.name)) return .{+ if (std.mem.eql(u8, call.name, "learn_candidate") or std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or mcp.Registry.isMcp(call.name)) return .{.text = try gpa.dupe(u8, "plan mode is on — read-only; describe the change instead of making it"),.is_error = true,};@@ -134,6 +147,45 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {}const input = call.input;+ if (std.mem.eql(u8, call.name, "learn_candidate")) {+ if (ctx.from_sub) return .{+ .text = try gpa.dupe(u8, "learning is root-only — subagents cannot run mutators, evaluators, or publish grades"),+ .is_error = true,+ };+ const candidates = intField(input, "candidates");+ const repetitions = intField(input, "repetitions");+ if (candidates) |n| if (n < 1 or n > 16) return .{ .text = try gpa.dupe(u8, "candidates must be between 1 and 16"), .is_error = true };+ if (repetitions) |n| if (n < 1 or n > 100) return .{ .text = try gpa.dupe(u8, "repetitions must be between 1 and 100"), .is_error = true };+ const exe_path = try std.process.executablePathAlloc(io, gpa);+ defer gpa.free(exe_path);+ var candidates_buf: [20]u8 = undefined;+ var repetitions_buf: [20]u8 = undefined;+ var argv_buf: [10][]const u8 = undefined;+ const contribute = main_mod.g_fleet and (learning_privacy.allowsAggregate() or learning_privacy.consumeAggregateOnce(io));+ var argc = learningArgv(&argv_buf, exe_path, contribute);+ if (candidates) |n| {+ argv_buf[argc] = "--candidates";+ argv_buf[argc + 1] = try std.fmt.bufPrint(&candidates_buf, "{d}", .{n});+ argc += 2;+ }+ if (repetitions) |n| {+ argv_buf[argc] = "--repetitions";+ argv_buf[argc + 1] = try std.fmt.bufPrint(&repetitions_buf, "{d}", .{n});+ argc += 2;+ }+ const run = try runCapped(gpa, io, argv_buf[0..argc], 256 * 1024, 64 * 1024, 0);+ defer gpa.free(run.stdout);+ defer gpa.free(run.stderr);+ const ok = run.term == .exited and run.term.exited == 0 and !run.timed_out;+ var aw: Io.Writer.Allocating = .init(gpa);+ errdefer aw.deinit();+ if (run.stdout.len > 0) try aw.writer.writeAll(run.stdout);+ if (run.stdout_truncated) try aw.writer.writeAll("\n[learning output truncated]");+ if (run.stderr.len > 0) try aw.writer.print("\n[stderr]\n{s}", .{run.stderr});+ if (run.stderr_truncated) try aw.writer.writeAll("\n[learning stderr truncated]");+ if (run.stdout.len == 0 and run.stderr.len == 0) try aw.writer.writeAll(if (ok) "learning run completed" else "learning run failed without output");+ return .{ .text = try aw.toOwnedSlice(), .is_error = !ok };+ }if (std.mem.eql(u8, call.name, "bash")) {const cmd = strField(input, "command") orelse return missingArg(gpa, "command");// Subagents have no stdin to prompt on; their gate is the allowlist.@@ -232,27 +284,29 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {if (try codedbCompactRead(gpa, io, path, start_line, end_line)) |out| return out;}}- const data = Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(256 * 1024)) catch |err| {+ const outcome = read_file.read(io, gpa, .cwd(), path, start_line, end_line) catch |err| {if (fsErrorText(gpa, .read, path, err)) |t| return .{ .text = t, .is_error = true };return err;};- // Binary guard: PDFs/images/archives would only poison the context- // with mojibake — point the model at bash converters instead.- if (binaryFileExt(path) or std.mem.indexOfScalar(u8, data[0..@min(data.len, 4096)], 0) != null) {- defer gpa.free(data);- return .{ .text = try std.fmt.allocPrint(gpa, "{s} is a binary file ({d} bytes) — read_file only handles text. Use bash instead (e.g. `file`, `strings`, `pdftotext`, `sips`, `unzip -l`).", .{ path, data.len }), .is_error = true };- }- // #66: byte-exact 1-based inclusive line window — still a literal substring- // of the file, so it stays safe to paste into an edit_file old_string.- if (start_line != null or end_line != null) {- defer gpa.free(data);- const win = sliceLines(data, start_line, end_line) orelse return .{+ return switch (outcome) {+ .text => |text| .{ .text = text },+ .truncated => |value| blk: {+ defer gpa.free(value.head);+ break :blk .{ .text = try std.fmt.allocPrint(gpa, "{s}\n\n[read_file preview: {d}-byte file exceeds the {d} KiB whole-file limit; use start_line/end_line for byte-exact windows]", .{ util.utf8Prefix(value.head, value.head.len), value.total_bytes, read_file.max_bytes / 1024 }) };+ },+ .binary => |size| .{+ .text = try std.fmt.allocPrint(gpa, "{s} is a binary file ({d} bytes) — read_file only handles text. Use bash instead (e.g. `file`, `strings`, `pdftotext`, `sips`, `unzip -l`).", .{ path, size }),+ .is_error = true,+ },+ .range_too_large => .{+ .text = try std.fmt.allocPrint(gpa, "read_file: requested range from {s} exceeds {d} KiB — request a narrower start_line/end_line window", .{ path, read_file.max_bytes / 1024 }),+ .is_error = true,+ },+ .start_past_end => .{.text = try std.fmt.allocPrint(gpa, "start_line {?d} is past the end of {s}", .{ start_line, path }),.is_error = true,- };- return .{ .text = try gpa.dupe(u8, win) };- }- return .{ .text = data };+ },+ };}if (std.mem.eql(u8, call.name, "codedb")) {const cmd = strField(input, "command") orelse return missingArg(gpa, "command");@@ -370,33 +424,6 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {return .{ .text = try std.fmt.allocPrint(gpa, "unknown tool: {s}", .{call.name}), .is_error = true };}-/// Byte-exact 1-based inclusive line window into `data`: the sub-slice spanning-/// the start of line `start` through the end of line `end` (incl. that line's-/// trailing newline when present). null if `start` is past EOF. A literal-/// substring of the file, so it stays safe to paste into edit_file (#66).-fn sliceLines(data: []const u8, start_opt: ?i64, end_opt: ?i64) ?[]const u8 {- if (data.len == 0) return null;- const start_1: usize = if (start_opt) |s| (if (s < 1) 1 else @intCast(s)) else 1;- const end_1: usize = if (end_opt) |e| (if (e < 1) 1 else @intCast(e)) else std.math.maxInt(usize);- if (end_1 < start_1) return null;- var line: usize = 1;- var begin: ?usize = if (start_1 == 1) 0 else null;- var stop: usize = data.len;- var i: usize = 0;- while (i < data.len) : (i += 1) {- if (data[i] == '\n') {- line += 1;- if (line == start_1) begin = i + 1;- if (line == end_1 +| 1) { // saturating: maxInt (no end_line) never matches `line`- stop = i + 1;- break;- }- }- }- const b = begin orelse return null; // start_1 is beyond EOF- return data[b..stop];-}-/// Opt-in exploratory read via `codedb read <path> [-L a-b] --compact`. Lossy view/// for reasoning only; returns null on any codedb failure so the caller falls back/// to the native byte-exact read (#66).@@ -423,17 +450,6 @@ fn codedbCompactRead(gpa: Allocator, io: Io, path: []const u8, start: ?i64, end:return ToolOutput{ .text = try std.fmt.allocPrint(gpa, "{s}\n[compact view — comments/blank lines stripped, line numbers shown; re-read WITHOUT compact before building an edit_file old_string]", .{run.stdout}) };}-test "sliceLines: byte-exact 1-based inclusive window (#66)" {- const data = "a\nb\nc\nd\n";- try std.testing.expectEqualStrings("b\nc\n", sliceLines(data, 2, 3).?);- try std.testing.expectEqualStrings("a\n", sliceLines(data, 1, 1).?);- try std.testing.expectEqualStrings("a\nb\nc\nd\n", sliceLines(data, null, null).?);- try std.testing.expectEqualStrings("c\nd\n", sliceLines(data, 3, 99).?); // end clamps to EOF- try std.testing.expect(sliceLines(data, 99, 100) == null); // start past EOF- try std.testing.expectEqualStrings("y", sliceLines("x\ny", 2, 2).?); // no trailing newline- try std.testing.expect(std.mem.indexOf(u8, data, sliceLines(data, 2, 3).?) != null); // literal substring-}-/// The three native file tools, used to shape a filesystem-error message with/// the tool's own name and the right recovery hint (#183).const FileOp = enum {@@ -508,3 +524,11 @@ test "fsErrorText names the tool, path, and failure (#183)" {// Errors outside the usual path/permission set fall through to the generic handler.try std.testing.expect(fsErrorText(gpa, .read, "p", error.OutOfMemory) == null);}++test "internal learning respects the parent privacy ceiling" {+ var argv: [10][]const u8 = undefined;+ var len = learningArgv(&argv, "graff", false);+ try std.testing.expectEqualSlices([]const u8, &.{ "graff", "--learning-privacy", "local", "learn", "run" }, argv[0..len]);+ len = learningArgv(&argv, "graff", true);+ try std.testing.expectEqualSlices([]const u8, &.{ "graff", "--learning-privacy", "aggregate", "learn", "run", "--submit" }, argv[0..len]);+}diff --git a/src/fleet.zig b/src/fleet.zigindex fce31609..807e2daa 100644--- a/src/fleet.zig+++ b/src/fleet.zig@@ -20,6 +20,7 @@ const learn_store = @import("learn_store.zig");const root = @import("main.zig");const trace = @import("trace.zig");const telemetry_mod = @import("telemetry.zig");+const learning_privacy = @import("learning_privacy.zig");const Telemetry = telemetry_mod.Telemetry;const http = @import("http.zig");@@ -297,7 +298,7 @@ fn applyRemoteElite(arena: Allocator, types: []AgentType, name: []const u8, prom/// returns `types` unchanged. `endpoint` is the OTLP base (…/v1/logs); the elites/// live beside it at /v1/elites.pub fn pullElites(io: Io, arena: Allocator, client: *std.http.Client, telem: ?*Telemetry, endpoint: []const u8, provider_class: []const u8, eval_set_hash: []const u8, types: []const AgentType) []const AgentType {- if (endpoint.len == 0 or !root.g_fleet) return types;+ if (endpoint.len == 0 or !root.g_fleet or !learning_privacy.allowsAggregate()) return types;http.waitForClientReady(io);var base = std.mem.trimEnd(u8, endpoint, "/");if (std.mem.endsWith(u8, base, "/v1/logs")) base = base[0 .. base.len - "/v1/logs".len];@@ -395,6 +396,28 @@ pub fn resolveOverride(obj: std.json.ObjectMap) ?[]const u8 {return null;}+/// The private prompt content, if this spawn would use an inline, personal,+/// project, or locally learned persona. Builtin/remote fleet personas are+/// already public artifacts and do not need a new publication decision.+pub fn privateOverride(obj: std.json.ObjectMap) ?[]const u8 {+ if (obj.get("system_prompt")) |v| {+ if (v == .string and v.string.len > 0) return v.string;+ }+ if (obj.get("agent")) |v| if (v == .string) {+ for (g_agent_types) |agent_type| {+ if (std.mem.eql(u8, agent_type.name, v.string) and !agent_type.builtin) return agent_type.prompt;+ }+ };+ return null;+}++pub fn promptIsPublic(prompt: []const u8) bool {+ for (g_agent_types) |agent_type| {+ if (agent_type.builtin and std.mem.eql(u8, agent_type.prompt, prompt)) return true;+ }+ return false;+}+/// The MAP-Elites niche name for a subagent/workflow input: the named agent/// type (agent: "<name>"), or "" for an inline system_prompt variant.pub fn resolveNiche(obj: std.json.ObjectMap) []const u8 {@@ -420,6 +443,27 @@ test "resolveNiche: agent name is the fleet cell, inline variant is uncelled" {try std.testing.expectEqualStrings("", resolveNiche(obj(a, "{\"description\":\"x\",\"prompt\":\"y\"}")));}+test "privateOverride distinguishes authored content from builtin personas" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const saved = g_agent_types;+ defer g_agent_types = saved;+ const types = [_]AgentType{+ .{ .name = "public", .desc = "public", .prompt = "public prompt", .builtin = true },+ .{ .name = "private", .desc = "private", .prompt = "private prompt" },+ };+ g_agent_types = &types;+ const public_obj = (try std.json.parseFromSliceLeaky(Value, arena, "{\"agent\":\"public\"}", .{})).object;+ const private_obj = (try std.json.parseFromSliceLeaky(Value, arena, "{\"agent\":\"private\"}", .{})).object;+ const inline_obj = (try std.json.parseFromSliceLeaky(Value, arena, "{\"system_prompt\":\"inline\"}", .{})).object;+ try std.testing.expect(privateOverride(public_obj) == null);+ try std.testing.expectEqualStrings("private prompt", privateOverride(private_obj).?);+ try std.testing.expectEqualStrings("inline", privateOverride(inline_obj).?);+ try std.testing.expect(promptIsPublic("public prompt"));+ try std.testing.expect(!promptIsPublic("private prompt"));+}+test "remote elites cannot replace a verified learned policy" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();diff --git a/src/learn_cli.zig b/src/learn_cli.zigindex a4c3403a..01f0b126 100644--- a/src/learn_cli.zig+++ b/src/learn_cli.zig@@ -9,6 +9,11 @@ const build_options = @import("build_options");const store_mod = @import("learn_store.zig");const eval = @import("learn_eval.zig");+const holdout = @import("learn_holdout.zig");+const primary = @import("learn_primary.zig");+const learn_run = @import("learn_run.zig");+const submit = @import("learn_submit.zig");+const tournament = @import("learn_tournament.zig");const util = @import("util.zig");pub const usage =@@ -16,7 +21,8 @@ pub const usage =\\\\usage:\\ graff learn init --parent PATH --config PATH- \\ graff learn run [--candidates N] [--repetitions N] [--auto] [--lock-timeout-ms N]+ \\ graff learn run [--candidates N] [--repetitions N] [--submit] [--auto] [--lock-timeout-ms N]+ \\ graff learn submit RUN_ID [--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]@@ -30,9 +36,10 @@ pub const usage =;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 RunArgs = struct { candidates: ?usize = null, repetitions: ?usize = null, submit: bool = false, 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 SubmitArgs = 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 };@@ -41,6 +48,7 @@ pub const Parsed = union(enum) {init: InitArgs,run: RunArgs,status: StatusArgs,+ submit: SubmitArgs,promote: PromoteArgs,rollback: RollbackArgs,verify: StatusArgs,@@ -91,6 +99,7 @@ pub fn parse(args: []const []const u8) !Parsed {var seen_candidates = false;var seen_repetitions = false;var seen_auto = false;+ var seen_submit = false;var seen_lock = false;var index: usize = 1;while (index < args.len) : (index += 1) {@@ -113,6 +122,10 @@ pub fn parse(args: []const []const u8) !Parsed {if (seen_auto) return error.DuplicateOption;seen_auto = true;result.auto = true;+ } else if (std.mem.eql(u8, arg, "--submit")) {+ if (seen_submit) return error.DuplicateOption;+ seen_submit = true;+ result.submit = true;} else if (!try parseLockOption(args, &index, &seen_lock, &result.lock_timeout_ms)) return error.UnknownOption;}return .{ .run = result };@@ -132,6 +145,14 @@ pub fn parse(args: []const []const u8) !Parsed {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, "submit")) {+ if (args.len < 2 or !store_mod.validId(args[1])) return error.InvalidId;+ var result: SubmitArgs = .{ .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 .{ .submit = result };+ }if (std.mem.eql(u8, command_name, "rollback")) {var result: RollbackArgs = .{};var seen_to = false;@@ -162,48 +183,6 @@ fn verifyPins(io: Io, arena: Allocator, config: store_mod.Config) !void {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;@@ -220,8 +199,10 @@ fn verifyMutationEvidence(arena: Allocator, store: *store_mod.Store, config: sto!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;+ !std.unicode.utf8ValidateSlice(response.description) or std.mem.indexOfScalar(u8, response.description, 0) != null or+ !std.mem.eql(u8, response.description, candidate.mutation.description)) return error.MutationMismatch;const child = try store.readGenome(arena, candidate.genome_id, config.limits.genome_bytes);+ if (candidate.mutation.genome_bytes != child.len) return error.MutationOutputMismatch;const child_sha256 = store_mod.rawSha256(child);if (!std.mem.eql(u8, response.child_sha256, &child_sha256)) return error.MutationOutputMismatch;}@@ -237,7 +218,7 @@ fn verifyRun(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);+ const expected_trial_id = learn_run.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, .{});@@ -246,43 +227,90 @@ fn verifyRun(_ = 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| {+ const current_schema = std.mem.eql(u8, run.schema, eval.run_schema);+ var baseline_response: ?eval.PrimaryBaselineResponse = null;+ if (current_schema) if (run.primary_baseline) |baseline| {+ baseline_response = try primary.verifyBaseline(+ arena,+ io,+ store,+ config.value,+ &config.id,+ build_options.version,+ run.trial_id,+ run.parent_genome_id,+ config.value.evaluation_suite,+ run.repetitions,+ baseline,+ );+ };++ const computed = try arena.dupe(eval.CandidateRecord, run.candidates);+ var primary_count: usize = 0;+ for (run.candidates, computed, 0..) |candidate, *recomputed_candidate, index| {_ = try store.readGenome(arena, candidate.genome_id, config.value.limits.genome_bytes);try verifyMutationEvidence(arena, store, config.value, run, index, candidate);- // Mirror runCommand's precedence exactly: identical_parent wins and- // skips the prior-duplicate scan. Letting duplicate_candidate- // overwrite it made a run with two parent-identical candidates- // permanently unverifiable (writer said identical_parent, verifier- // demanded duplicate_candidate).- var duplicate_reason: ?[]const u8 = null;+ var excluded = false;if (std.mem.eql(u8, candidate.genome_id, run.parent_genome_id)) {- duplicate_reason = "identical_parent";+ excluded = true;} else for (run.candidates[0..index]) |prior| if (std.mem.eql(u8, candidate.genome_id, prior.genome_id)) {- duplicate_reason = "duplicate_candidate";+ excluded = true;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;+ if (excluded) {+ if (candidate.primary != null or candidate.holdout != null or candidate.eligible) 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";+ primary_count += 1;+ recomputed_candidate.primary = if (current_schema) try primary.verifyCandidate(+ 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,+ run.primary_baseline orelse return error.MissingPrimaryBaseline,+ baseline_response orelse return error.MissingPrimaryBaseline,+ primary_record,+ ) else 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);+ recomputed_candidate.holdout = null;+ recomputed_candidate.eligible = false;+ }+ if (current_schema and ((primary_count == 0) != (run.primary_baseline == null))) return error.PrimaryBaselineTopologyMismatch;++ const primary_winner_index = tournament.primaryWinnerIndex(run.parent_genome_id, computed);+ for (run.candidates, computed, 0..) |candidate, *recomputed_candidate, index| {+ const is_winner = primary_winner_index != null and index == primary_winner_index.?;+ if (candidate.holdout != null and !is_winner) return error.CandidateMismatch;+ if (is_winner) {+ const should_have_holdout = !current_schema or recomputed_candidate.primary.?.eligible;+ if (should_have_holdout) {+ if (config.value.holdout_suite) |suite| {+ const holdout_record = candidate.holdout orelse return error.CandidateMismatch;+ if (current_schema) try holdout.verify(io, store.root, arena, suite.sha256, run.trial_id);+ recomputed_candidate.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, 1, holdout_record);+ } else if (candidate.holdout != null) return error.CandidateMismatch;} 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 finalized = try tournament.finalize(run.parent_genome_id, computed, config.value.holdout_suite != null);+ for (run.candidates, computed) |candidate, expected| {+ if (candidate.eligible != expected.eligible or !std.mem.eql(u8, candidate.reason, expected.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 };+ const primary_winner = if (finalized.primary_winner_index) |index| computed[index].genome_id else null;+ if ((primary_winner == null) != (run.primary_winner_genome_id == null)) return error.SelectionMismatch;+ if (primary_winner) |id| if (!std.mem.eql(u8, id, run.primary_winner_genome_id.?)) return error.SelectionMismatch;+ if ((finalized.selected_genome_id == null) != (run.selected_genome_id == null)) return error.SelectionMismatch;+ if (finalized.selected_genome_id) |id| if (!std.mem.eql(u8, id, run.selected_genome_id.?)) return error.SelectionMismatch;+ return .{ .run = run, .selected = finalized.selected_genome_id };}fn activeMatchesRun(active: store_mod.ActiveRef, run: eval.RunRecord) bool {@@ -321,93 +349,30 @@ fn runCommand(gpa: Allocator, arena: Allocator, io: Io, environ: *const std.procconst 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;+ if (args.submit) try submit.preflight(io, arena, environ);try out.writeAll("warning: mutator and evaluator execute as your OS user; scratch isolation is not a sandbox\n");- const nonce = try 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| {+ const result = try learn_run.execute(gpa, arena, io, environ, &store, config, active, .{+ .candidates = args.candidates,+ .repetitions = args.repetitions,+ .submit = args.submit,+ .auto = args.auto,+ }, out);+ if (result.selected_genome_id) |genome_id| {try out.print("selected {s}\n", .{genome_id});if (args.auto) {- const verified = try verifyRun(arena, io, &store, config, &run_id);+ const verified = try verifyRun(arena, io, &store, config, &result.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));+ if (!activeMatchesRun(current.ref, verified.run)) return error.ActiveParentChanged;+ try store.activate(gpa, current.ref, &config.id, genome_id, &result.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");+ } else try out.print("manual promotion: graff learn promote {s}\n", .{result.run_id});+ } else if (result.primary_winner_genome_id != null) {+ try out.writeAll("primary winner recorded, but it did not clear every promotion gate; active genome unchanged\n");+ } else try out.writeAll("no unique candidate produced primary evidence; active genome unchanged\n");}fn statusCommand(arena: Allocator, io: Io, timeout_ms: u64, out: *Io.Writer, verify_all: bool) !void {@@ -455,6 +420,17 @@ fn promoteCommand(gpa: Allocator, arena: Allocator, io: Io, args: PromoteArgs, otry out.print("promoted {s} from run {s}\n", .{ selected, args.run_id });}+fn submitCommand(gpa: Allocator, arena: Allocator, io: Io, environ: *const std.process.Environ.Map, args: SubmitArgs, 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 verified = try verifyRun(arena, io, &store, config, args.run_id);+ const sent = try submit.submitVerifiedRun(io, gpa, arena, environ, config.value, args.run_id, verified.run);+ try out.print("submitted {d} signed aggregate grade(s) for run {s}; prompt text stayed local\n", .{ sent.grades, args.run_id });+}+fn ancestorTarget(arena: Allocator, store: *store_mod.Store, active: store_mod.LoadedActive, requested: ?[]const u8) ![]const u8 {// After a rollback, previous_genome_id names the genome just rolled AWAY// from, so a default-target rollback would move forward and reinstate it.@@ -502,6 +478,7 @@ pub fn command(io: Io, gpa: Allocator, arena: Allocator, init: std.process.Init,.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),+ .submit => |args| try submitCommand(gpa, arena, io, init.environ_map, args, out),.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),@@ -514,35 +491,13 @@ pub fn command(io: Io, gpa: Allocator, arena: Allocator, init: std.process.Init,}test "learn parser preserves strict command-local options" {- const parsed = try parse(&.{ "run", "--candidates", "4", "--repetitions", "2", "--auto", "--lock-timeout-ms", "50" });+ const parsed = try parse(&.{ "run", "--candidates", "4", "--repetitions", "2", "--submit", "--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.expect(parsed.run.submit);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_comparison.zig b/src/learn_comparison.zignew file mode 100644index 00000000..8bd677e2--- /dev/null+++ b/src/learn_comparison.zig@@ -0,0 +1,169 @@+//! Aggregate paired correctness, economy, and latency evidence.++const std = @import("std");+const store = @import("learn_store.zig");+const protocol = @import("learn_eval_types.zig");+const stats = @import("learn_stats.zig");++fn reductionPpm(parent: u64, child: u64) i64 {+ if (parent == 0) return if (child == 0) 0 else -1_000_000;+ const delta = @as(i128, parent) - @as(i128, child);+ return @intCast(@divTrunc(delta * 1_000_000, @as(i128, parent)));+}++pub fn computeComparison(+ config: store.Config,+ suite_sha256: []const u8,+ request_id: []const u8,+ response_id: []const u8,+ requested: []const protocol.PairRequest,+ response: protocol.EvaluationResponse,+ planned_candidates: usize,+) !protocol.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 tool_wins: usize = 0;+ var tool_losses: usize = 0;+ var child_critical_failures: usize = 0;+ var critical_regressions: usize = 0;+ var score_delta: i128 = 0;+ var parent_cost: u64 = 0;+ var child_cost: u64 = 0;+ var parent_tool_calls: u64 = 0;+ var child_tool_calls: u64 = 0;+ var parent_latency: u64 = 0;+ var child_latency: u64 = 0;+ var tool_calls_measured = true;+ var latency_measured = true;+ 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 > stats.js_exact_max or result.child_cost_micros > stats.js_exact_max or result.parent_latency_ms > stats.js_exact_max or result.child_latency_ms > stats.js_exact_max or result.parent_tool_calls > stats.js_exact_max or result.child_tool_calls > stats.js_exact_max) return error.InvalidMetric;+ if (result.parent_pass) parent_passes += 1;+ if (result.child_pass) child_passes += 1;+ if (!result.child_pass and pair.critical) child_critical_failures += 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 stats.checkedMetricAdd(parent_cost, result.parent_cost_micros);+ child_cost = try stats.checkedMetricAdd(child_cost, result.child_cost_micros);+ parent_tool_calls = try stats.checkedMetricAdd(parent_tool_calls, result.parent_tool_calls);+ child_tool_calls = try stats.checkedMetricAdd(child_tool_calls, result.child_tool_calls);+ parent_latency = try stats.checkedMetricAdd(parent_latency, result.parent_latency_ms);+ child_latency = try stats.checkedMetricAdd(child_latency, result.child_latency_ms);+ tool_calls_measured = tool_calls_measured and result.tool_calls_measured;+ latency_measured = latency_measured and result.latency_measured;+ }++ // Repetitions of one case are one statistical unit. Aggregate correctness+ // and calls per case before comparing directions.+ 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;+ var parent_case_calls: u64 = 0;+ var child_case_calls: u64 = 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;+ parent_case_calls = try stats.checkedMetricAdd(parent_case_calls, result.parent_tool_calls);+ child_case_calls = try stats.checkedMetricAdd(child_case_calls, result.child_tool_calls);+ }+ if (child_case_passes > parent_case_passes) wins += 1;+ if (parent_case_passes > child_case_passes) losses += 1;+ if (tool_calls_measured and child_case_calls < parent_case_calls) tool_wins += 1;+ if (tool_calls_measured and parent_case_calls < child_case_calls) tool_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 correctness_p = stats.pairedTail(wins, losses);+ const tool_p = stats.pairedTail(tool_wins, tool_losses);+ const alpha: f64 = @as(f64, @floatFromInt(config.gate.alpha_ppm)) / 1_000_000.0;+ const correction: f64 = @floatFromInt(planned_candidates);+ const correctness_significant = correctness_p * correction <= alpha;+ const tool_significant = tool_p * correction <= alpha;+ const tool_delta = reductionPpm(parent_tool_calls, child_tool_calls);+ const tool_discordant = tool_wins + tool_losses;+ const economy_eligible = config.gate.economy_gate_enabled and+ child_critical_failures == 0 and statistical_units >= config.gate.minimum_pairs and+ child_passes >= parent_passes and losses == 0 and mean_score_delta >= 0 and+ tool_calls_measured and+ tool_discordant >= config.gate.minimum_economy_pairs and+ tool_delta >= config.gate.minimum_tool_reduction_ppm and tool_significant;++ var eligible = true;+ var reason: []const u8 = "eligible";+ if (child_critical_failures > 0) {+ eligible = false;+ reason = if (critical_regressions > 0) "critical_regression" else "critical_failure";+ } else if (statistical_units < config.gate.minimum_pairs) {+ eligible = false;+ reason = "minimum_pairs";+ } else if (config.gate.promotion_mode == .correctness and delta_ppm >= config.gate.minimum_delta_ppm and correctness_significant) {+ // Pre-registered correctness-improvement path.+ } else if (config.gate.promotion_mode == .economy and economy_eligible) {+ reason = "economy_eligible";+ } else {+ eligible = false;+ reason = if (config.gate.promotion_mode == .economy and (child_passes < parent_passes or losses > 0 or mean_score_delta < 0))+ "correctness_regression"+ else if (config.gate.promotion_mode == .economy and !tool_calls_measured)+ "tool_calls_unmeasured"+ else if (config.gate.promotion_mode == .economy and tool_discordant < config.gate.minimum_economy_pairs)+ "minimum_economy_pairs"+ else if (config.gate.promotion_mode == .economy and tool_delta < config.gate.minimum_tool_reduction_ppm)+ "minimum_tool_reduction"+ else if (config.gate.promotion_mode == .economy and !tool_significant)+ "economy_not_significant"+ else if (delta_ppm < config.gate.minimum_delta_ppm)+ "minimum_delta"+ else+ "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,+ .child_critical_failures = child_critical_failures,+ .critical_regressions = critical_regressions,+ .delta_ppm = delta_ppm,+ .mean_score_delta_ppm = mean_score_delta,+ .p_value_ppb = stats.toPpb(correctness_p),+ .parent_cost_micros = parent_cost,+ .child_cost_micros = child_cost,+ .tool_calls_measured = tool_calls_measured,+ .parent_tool_calls = parent_tool_calls,+ .child_tool_calls = child_tool_calls,+ .tool_wins = tool_wins,+ .tool_losses = tool_losses,+ .tool_ties = if (tool_calls_measured) statistical_units - tool_wins - tool_losses else 0,+ .tool_delta_ppm = tool_delta,+ .tool_p_value_ppb = stats.toPpb(tool_p),+ .latency_measured = latency_measured,+ .parent_latency_ms = parent_latency,+ .child_latency_ms = child_latency,+ .economy_eligible = economy_eligible,+ .eligible = eligible,+ .reason = reason,+ };+}diff --git a/src/learn_eval.zig b/src/learn_eval.zigindex cd82b78d..5770ebd9 100644--- a/src/learn_eval.zig+++ b/src/learn_eval.zig@@ -12,145 +12,42 @@ 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 protocol = @import("learn_eval_types.zig");++pub const mutation_request_schema = protocol.mutation_request_schema;+pub const mutation_response_schema = protocol.mutation_response_schema;+pub const evaluation_request_schema = protocol.evaluation_request_schema;+pub const evaluation_response_schema = protocol.evaluation_response_schema;+pub const primary_baseline_request_schema = protocol.primary_baseline_request_schema;+pub const primary_baseline_response_schema = protocol.primary_baseline_response_schema;+pub const primary_evaluation_request_schema = protocol.primary_evaluation_request_schema;+pub const primary_evaluation_response_schema = protocol.primary_evaluation_response_schema;+pub const legacy_run_schema = protocol.legacy_run_schema;+pub const run_schema = protocol.run_schema;+pub const GenomeRef = protocol.GenomeRef;+pub const MutationRequest = protocol.MutationRequest;+pub const MutationResponse = protocol.MutationResponse;+pub const PairRequest = protocol.PairRequest;+pub const EvaluationRequest = protocol.EvaluationRequest;+pub const PairResult = protocol.PairResult;+pub const EvaluationResponse = protocol.EvaluationResponse;+pub const BaselinePairResult = protocol.BaselinePairResult;+pub const PrimaryBaselineRequest = protocol.PrimaryBaselineRequest;+pub const PrimaryBaselineResponse = protocol.PrimaryBaselineResponse;+pub const PrimaryBaselineRecord = protocol.PrimaryBaselineRecord;+pub const PrimaryBaselineRef = protocol.PrimaryBaselineRef;+pub const PrimaryEvaluationRequest = protocol.PrimaryEvaluationRequest;+pub const PrimaryEvaluationResponse = protocol.PrimaryEvaluationResponse;+pub const MutationRecord = protocol.MutationRecord;+pub const ComparisonRecord = protocol.ComparisonRecord;+pub const CandidateRecord = protocol.CandidateRecord;+pub const RunRecord = protocol.RunRecord;+pub const MutationOutcome = protocol.MutationOutcome;const file_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_file else .fromMode(0o600);pub const executable_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_file else .fromMode(0o700);pub const dir_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_dir else .fromMode(0o700);-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;@@ -172,7 +69,7 @@ pub fn cohortId(config_id: []const u8, suite_sha256: []const u8, harness_versionreturn 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 {+pub fn pairSeed(trial_id: []const u8, suite_sha256: []const u8, 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});@@ -182,10 +79,9 @@ pub fn pairSeed(trial_id: []const u8, suite_sha256: []const u8, candidate_index: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 repetition_bytes: [8]u8 = undefined;+ std.mem.writeInt(u64, &repetition_bytes, @intCast(repetition), .big);+ hash.update(&repetition_bytes);var digest: [32]u8 = undefined;hash.final(&digest);return std.fmt.bytesToHex(digest, .lower);@@ -339,12 +235,46 @@ pub fn invoke(// The bare error alone cost real debugging time: surface which tool// failed and a bounded stderr excerpt before the scratch dir (and the// request/response evidence in it) is deleted by the caller.- const excerpt = run.stderr[0..@min(run.stderr.len, 512)];+ const excerpt = run.stderr[0..@min(run.stderr.len, 4096)];std.debug.print("learn: {s} failed ({any}); stderr (first {d} of {d} bytes):\n{s}\n", .{ program.program, run.term, excerpt.len, run.stderr.len, excerpt });return error.ProcessFailed;}}+/// Retry one failed evaluator process in the same private scratch directory.+/// Cooperative adapters can resume from their request-bound case checkpoint,+/// avoiding a second baseline or replay of already completed cases.+pub fn invokeEvaluator(+ 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 attempt: usize = 0;+ while (true) : (attempt += 1) {+ invoke(gpa, io, parent_env, scratch, program, operation, stdout_cap, stderr_cap, timeout_ms) catch |err| switch (err) {+ error.ProcessFailed, error.ProcessTimedOut => if (attempt == 0) {+ var program_name_buf: [64]u8 = undefined;+ const program_name = try std.fmt.bufPrint(&program_name_buf, "program{s}", .{snapshotExtension(program.program)});+ try scratch.deleteFile(io, program_name);+ 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) });+ try scratch.deleteFile(io, name);+ }+ continue;+ } else return err,+ else => return err,+ };+ return;+ }+}+fn validDescription(value: []const u8) bool {return value.len <= 512 and std.unicode.utf8ValidateSlice(value) and std.mem.indexOfScalar(u8, value, 0) == null;}@@ -412,11 +342,13 @@ pub fn mutate(.seed = try arena.dupe(u8, &seed),.request_evidence_id = try arena.dupe(u8, &request_id),.response_evidence_id = try arena.dupe(u8, &response_id),+ .description = try arena.dupe(u8, response.description),+ .genome_bytes = prompt.len,},};}-fn buildPairs(gpa: Allocator, trial_id: []const u8, suite: store_mod.Suite, manifest: store_mod.SuiteManifest, candidate_index: usize, repetitions: usize) ![]PairRequest {+pub fn buildPairs(gpa: Allocator, trial_id: []const u8, suite: store_mod.Suite, manifest: store_mod.SuiteManifest, _: 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);@@ -427,7 +359,10 @@ fn buildPairs(gpa: Allocator, trial_id: []const u8, suite: store_mod.Suite, mani}for (0..repetitions) |repetition| {for (manifest.cases) |case| {- const seed = pairSeed(trial_id, suite.sha256, candidate_index, case.id, repetition);+ // Common random numbers: every arm receives identical primary+ // seeds for the same case/repetition, so generator identity is the+ // only intended source of between-arm variation.+ const seed = pairSeed(trial_id, suite.sha256, case.id, repetition);const seed_copy = try gpa.dupe(u8, &seed);pairs[initialized] = .{.case_id = case.id,@@ -440,110 +375,17 @@ fn buildPairs(gpa: Allocator, trial_id: []const u8, suite: store_mod.Suite, manireturn pairs;}-fn freePairs(gpa: Allocator, pairs: []PairRequest) void {+pub fn freePairs(gpa: Allocator, pairs: []PairRequest) void {for (pairs) |pair| gpa.free(pair.seed);gpa.free(pairs);}-// Exact paired-binomial statistics + metric guards live in learn_stats.zig-// (600-line goal); re-exported so existing call sites are unchanged.+// Statistics and comparison aggregation live in focused sibling modules.const learn_stats = @import("learn_stats.zig");pub const js_exact_max = learn_stats.js_exact_max;pub const pairedTail = learn_stats.pairedTail;-const toPpb = learn_stats.toPpb;-const checkedMetricAdd = learn_stats.checkedMetricAdd;--pub 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,- };-}+const comparison_mod = @import("learn_comparison.zig");+pub const computeComparison = comparison_mod.computeComparison;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@@ -617,7 +459,7 @@ pub fn evaluate(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);+ try invokeEvaluator(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, .{});@@ -629,15 +471,22 @@ pub fn evaluate(return comparison;}-fn comparisonEqual(a: ComparisonRecord, b: ComparisonRecord) bool {+pub fn comparisonEqual(a: ComparisonRecord, b: ComparisonRecord) bool {return std.mem.eql(u8, a.suite_sha256, b.suite_sha256) andstd.mem.eql(u8, a.request_evidence_id, b.request_evidence_id) andstd.mem.eql(u8, a.response_evidence_id, b.response_evidence_id) anda.pairs == b.pairs and a.statistical_units == b.statistical_units anda.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.wins == b.wins and a.losses == b.losses and a.ties == b.ties and+ a.child_critical_failures == b.child_critical_failures and a.critical_regressions == b.critical_regressions anda.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 anda.parent_cost_micros == b.parent_cost_micros and a.child_cost_micros == b.child_cost_micros and+ a.tool_calls_measured == b.tool_calls_measured and+ a.parent_tool_calls == b.parent_tool_calls and a.child_tool_calls == b.child_tool_calls and+ a.tool_wins == b.tool_wins and a.tool_losses == b.tool_losses and a.tool_ties == b.tool_ties and+ a.tool_delta_ppm == b.tool_delta_ppm and a.tool_p_value_ppb == b.tool_p_value_ppb and+ a.latency_measured == b.latency_measured and a.parent_latency_ms == b.parent_latency_ms and a.child_latency_ms == b.child_latency_ms and+ a.economy_eligible == b.economy_eligible anda.eligible == b.eligible and std.mem.eql(u8, a.reason, b.reason);}@@ -676,10 +525,18 @@ pub fn verifyComparison(}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;+ const current = std.mem.eql(u8, run.schema, run_schema);+ const legacy = std.mem.eql(u8, run.schema, legacy_run_schema);+ if ((!current and !legacy) 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.primary_winner_genome_id) |id| if (!store_mod.validId(id)) return error.InvalidRun;if (run.selected_genome_id) |id| if (!store_mod.validId(id)) return error.InvalidRun;+ if (current) {+ if (run.primary_baseline) |baseline| {+ if (!store_mod.validId(baseline.suite_sha256) or !store_mod.validId(baseline.request_evidence_id) or !store_mod.validId(baseline.response_evidence_id)) return error.InvalidRun;+ }+ } else if (run.primary_baseline != null) 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;diff --git a/src/learn_eval_tests.zig b/src/learn_eval_tests.zigindex e4c8ae59..e1ffe385 100644--- a/src/learn_eval_tests.zig+++ b/src/learn_eval_tests.zig@@ -73,6 +73,110 @@ test "paired gate rejects critical regressions and requires corrected significanconst 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);++ results[0].parent_pass = false;+ const jointly_failed_critical = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1);+ try std.testing.expect(!jointly_failed_critical.eligible);+ try std.testing.expectEqual(@as(usize, 1), jointly_failed_critical.child_critical_failures);+ try std.testing.expectEqual(@as(usize, 0), jointly_failed_critical.critical_regressions);+ try std.testing.expectEqualStrings("critical_failure", jointly_failed_critical.reason);+}++test "economy gate requires corrected per-case evidence without correctness loss" {+ 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 = 50_000,+ .minimum_pairs = 8,+ .economy_gate_enabled = true,+ .promotion_mode = .economy,+ .minimum_tool_reduction_ppm = 100_000,+ .minimum_economy_pairs = 6,+ },+ .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" };+ var requested: [8]PairRequest = undefined;+ var results: [8]PairResult = undefined;+ for (0..8) |i| {+ requested[i] = .{ .case_id = case_ids[i], .seed = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", .critical = i == 0 };+ results[i] = .{+ .case_id = case_ids[i],+ .seed = requested[i].seed,+ .parent_pass = true,+ .child_pass = true,+ .parent_score_ppm = 1_000_000,+ .child_score_ppm = 1_000_000,+ .parent_latency_ms = 5,+ .child_latency_ms = 4,+ .latency_measured = true,+ .tool_calls_measured = true,+ .parent_tool_calls = 2,+ .child_tool_calls = 1,+ };+ }+ 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 strong = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 4);+ try std.testing.expect(strong.eligible);+ try std.testing.expect(strong.economy_eligible);+ try std.testing.expectEqualStrings("economy_eligible", strong.reason);+ try std.testing.expectEqual(@as(usize, 8), strong.tool_wins);+ try std.testing.expectEqual(@as(u64, 40), strong.parent_latency_ms);+ try std.testing.expectEqual(@as(u64, 32), strong.child_latency_ms);++ var correctness_only = results;+ for (&correctness_only) |*result| {+ result.parent_pass = false;+ result.child_pass = true;+ result.parent_score_ppm = 0;+ result.child_score_ppm = 1_000_000;+ result.child_tool_calls = result.parent_tool_calls;+ }+ const correctness_response: EvaluationResponse = .{ .schema = evaluation_response_schema, .trial_id = response.trial_id, .candidate_index = 0, .cohort_id = response.cohort_id, .suite_sha256 = response.suite_sha256, .parent_id = response.parent_id, .child_id = response.child_id, .pairs = &correctness_only };+ const wrong_endpoint = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, correctness_response, 4);+ try std.testing.expect(!wrong_endpoint.eligible);+ var correctness_config = config;+ correctness_config.gate.promotion_mode = .correctness;+ const registered_endpoint = try computeComparison(correctness_config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, correctness_response, 4);+ try std.testing.expect(registered_endpoint.eligible);++ // Six directional wins are not enough after correcting for four arms,+ // even though the aggregate call reduction remains above ten percent.+ results[6].child_tool_calls = 2;+ results[7].child_tool_calls = 2;+ const weak = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 4);+ try std.testing.expect(!weak.eligible);+ try std.testing.expectEqualStrings("economy_not_significant", weak.reason);++ results[5].child_tool_calls = 2;+ const too_few_directions = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 4);+ try std.testing.expect(!too_few_directions.eligible);+ try std.testing.expectEqualStrings("minimum_economy_pairs", too_few_directions.reason);++ results[0].tool_calls_measured = false;+ const unmeasured = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 4);+ try std.testing.expect(!unmeasured.eligible);+ try std.testing.expectEqualStrings("tool_calls_unmeasured", unmeasured.reason);++ results[0].tool_calls_measured = true;+ results[0].parent_pass = true;+ results[0].child_pass = false;+ results[1].parent_pass = false;+ results[1].child_pass = true;+ const traded_correctness = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 4);+ try std.testing.expect(!traded_correctness.eligible);+ try std.testing.expectEqualStrings("critical_regression", traded_correctness.reason);++ requested[0].critical = false;+ const noncritical_trade = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 4);+ try std.testing.expect(!noncritical_trade.eligible);+ try std.testing.expectEqualStrings("correctness_regression", noncritical_trade.reason);}test "tool invocation executes verified private program and input snapshots" {diff --git a/src/learn_eval_types.zig b/src/learn_eval_types.zignew file mode 100644index 00000000..a1f9d84d--- /dev/null+++ b/src/learn_eval_types.zig@@ -0,0 +1,236 @@+//! Wire and persisted record types for the local learning engine.++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 primary_baseline_request_schema = "codegraff.learn.primary-baseline.request.v1";+pub const primary_baseline_response_schema = "codegraff.learn.primary-baseline.response.v1";+pub const primary_evaluation_request_schema = "codegraff.learn.primary-evaluation.request.v1";+pub const primary_evaluation_response_schema = "codegraff.learn.primary-evaluation.response.v1";+pub const legacy_run_schema = "codegraff.learn.run.v2";+pub const run_schema = "codegraff.learn.run.v3";++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,+ latency_measured: bool = false,+ /// False means the adapter did not measure calls; zero must not be+ /// interpreted as a free execution.+ tool_calls_measured: bool = false,+ parent_tool_calls: u64 = 0,+ child_tool_calls: 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 BaselinePairResult = struct {+ case_id: []const u8,+ seed: []const u8,+ pass: bool,+ score_ppm: u32,+ cost_micros: u64 = 0,+ latency_ms: u64 = 0,+ latency_measured: bool = false,+ tool_calls_measured: bool = false,+ tool_calls: u64 = 0,+};++pub const PrimaryBaselineRequest = struct {+ schema: []const u8,+ trial_id: []const u8,+ cohort_id: []const u8,+ suite_sha256: []const u8,+ suite_path: []const u8,+ parent: GenomeRef,+ repetitions: usize,+ pairs: []const PairRequest,+};++pub const PrimaryBaselineResponse = struct {+ schema: []const u8,+ trial_id: []const u8,+ cohort_id: []const u8,+ suite_sha256: []const u8,+ parent_id: []const u8,+ pairs: []const BaselinePairResult,+};++pub const PrimaryBaselineRecord = struct {+ suite_sha256: []const u8,+ request_evidence_id: []const u8,+ response_evidence_id: []const u8,+};++pub const PrimaryBaselineRef = struct {+ request_evidence_id: []const u8,+ response_evidence_id: []const u8,+ path: []const u8,+};++pub const PrimaryEvaluationRequest = struct {+ schema: []const u8,+ trial_id: []const u8,+ candidate_index: usize,+ cohort_id: []const u8,+ suite_sha256: []const u8,+ suite_path: []const u8,+ parent_id: []const u8,+ baseline: PrimaryBaselineRef,+ child: GenomeRef,+ repetitions: usize,+ pairs: []const PairRequest,+};++pub const PrimaryEvaluationResponse = 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,+ /// Non-sensitive local arm label supplied by the pinned mutator.+ description: []const u8 = "",+ genome_bytes: usize = 0,+};++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,+ child_critical_failures: usize = 0,+ critical_regressions: usize,+ delta_ppm: i64,+ mean_score_delta_ppm: i64,+ p_value_ppb: u64,+ parent_cost_micros: u64,+ child_cost_micros: u64,+ tool_calls_measured: bool = false,+ parent_tool_calls: u64 = 0,+ child_tool_calls: u64 = 0,+ tool_wins: usize = 0,+ tool_losses: usize = 0,+ tool_ties: usize = 0,+ tool_delta_ppm: i64 = 0,+ tool_p_value_ppb: u64 = 1_000_000_000,+ latency_measured: bool = false,+ parent_latency_ms: u64 = 0,+ child_latency_ms: u64 = 0,+ economy_eligible: bool = false,+ 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,+ primary_baseline: ?PrimaryBaselineRecord = null,+ candidates: []const CandidateRecord,+ /// Best primary-suite contender. This remains populated when the evidence+ /// is useful but not adequately powered for promotion.+ primary_winner_genome_id: ?[]const u8 = null,+ /// Populated only when the primary winner clears every promotion gate.+ selected_genome_id: ?[]const u8,+};++pub const MutationOutcome = struct {+ genome_id: [64]u8,+ prompt: []u8,+ record: MutationRecord,+};diff --git a/src/learn_holdout.zig b/src/learn_holdout.zignew file mode 100644index 00000000..33f69c71--- /dev/null+++ b/src/learn_holdout.zig@@ -0,0 +1,78 @@+//! One-use reservations for hidden learning suites.+//!+//! The marker is created before evaluator invocation. A crash after exposure+//! therefore leaves the suite consumed, which is safer than silently reusing a+//! holdout until it passes.++const std = @import("std");+const builtin = @import("builtin");+const store = @import("learn_store.zig");++const Io = std.Io;+const Allocator = std.mem.Allocator;+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);++fn markerName(suite_sha256: []const u8, buffer: *[69]u8) ![]const u8 {+ if (!store.validId(suite_sha256)) return error.InvalidId;+ return std.fmt.bufPrint(buffer, "{s}.used", .{suite_sha256});+}++fn openReservations(io: Io, root: Io.Dir) !Io.Dir {+ root.createDir(io, "holdouts", dir_permissions) catch |err| switch (err) {+ error.PathAlreadyExists => {},+ else => return err,+ };+ const dir = try root.openDir(io, "holdouts", .{ .iterate = true, .follow_symlinks = false });+ errdefer dir.close(io);+ if (builtin.os.tag != .windows) {+ const stat = try dir.stat(io);+ if ((stat.permissions.toMode() & 0o077) != 0) return error.InsecurePermissions;+ }+ return dir;+}++pub fn reserve(io: Io, root: Io.Dir, suite_sha256: []const u8, trial_id: []const u8) !void {+ if (!store.validId(trial_id)) return error.InvalidId;+ var name_buffer: [69]u8 = undefined;+ const name = try markerName(suite_sha256, &name_buffer);+ const reservations = try openReservations(io, root);+ defer reservations.close(io);+ const file = reservations.createFile(io, name, .{+ .exclusive = true,+ .permissions = file_permissions,+ }) catch |err| switch (err) {+ error.PathAlreadyExists => return error.HoldoutConsumed,+ else => return err,+ };+ defer file.close(io);+ try file.writeStreamingAll(io, trial_id);+ try file.writeStreamingAll(io, "\n");+ try file.sync(io);+ try store.syncDirectory(io, reservations);+ try store.syncDirectory(io, root);+}++pub fn verify(io: Io, root: Io.Dir, allocator: Allocator, suite_sha256: []const u8, trial_id: []const u8) !void {+ if (!store.validId(trial_id)) return error.InvalidId;+ var name_buffer: [69]u8 = undefined;+ const name = try markerName(suite_sha256, &name_buffer);+ const reservations = try openReservations(io, root);+ defer reservations.close(io);+ const bytes = try store.readFileNoFollow(io, reservations, name, allocator, 65);+ defer allocator.free(bytes);+ if (bytes.len != 65 or bytes[64] != '\n' or !std.mem.eql(u8, bytes[0..64], trial_id))+ return error.HoldoutReservationMismatch;+}++test "hidden suite reservations are durable and one-use" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const suite = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";+ const trial = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";+ try reserve(io, tmp.dir, suite, trial);+ try verify(io, tmp.dir, std.testing.allocator, suite, trial);+ try std.testing.expectError(error.HoldoutConsumed, reserve(io, tmp.dir, suite, trial));+ try std.testing.expectError(error.HoldoutReservationMismatch, verify(io, tmp.dir, std.testing.allocator, suite, "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"));+}diff --git a/src/learn_primary.zig b/src/learn_primary.zignew file mode 100644index 00000000..4bd6e737--- /dev/null+++ b/src/learn_primary.zig@@ -0,0 +1,312 @@+//! Shared primary-baseline execution and verification.+//!+//! A parent is evaluated once, then every concurrent child response must copy+//! that immutable parent projection exactly. The ordinary paired evaluator is+//! retained for the single winner's holdout.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const eval = @import("learn_eval.zig");+const store_mod = @import("learn_store.zig");++const baseline_path = "baseline.json";++fn validateRequestedPairs(actual: []const eval.PairRequest, expected: []const eval.PairRequest) !void {+ if (actual.len != expected.len) return error.PairMismatch;+ for (actual, expected) |got, want| {+ if (!std.mem.eql(u8, got.case_id, want.case_id) or+ !std.mem.eql(u8, got.seed, want.seed) or got.critical != want.critical) return error.PairMismatch;+ }+}++fn validateBaselineEnvelope(+ request: eval.PrimaryBaselineRequest,+ response: eval.PrimaryBaselineResponse,+ trial_id: []const u8,+ cohort_id: []const u8,+ suite: store_mod.Suite,+ parent_id: []const u8,+ repetitions: usize,+) !void {+ if (!std.mem.eql(u8, request.schema, eval.primary_baseline_request_schema) or+ !std.mem.eql(u8, request.trial_id, trial_id) 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+ request.repetitions != repetitions) return error.InvalidBaselineRequest;+ if (!std.mem.eql(u8, response.schema, eval.primary_baseline_response_schema) or+ !std.mem.eql(u8, response.trial_id, trial_id) 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)) return error.InvalidBaselineResponse;+}++fn validateBaselinePairs(response: eval.PrimaryBaselineResponse, requested: []const eval.PairRequest) !void {+ if (response.pairs.len != requested.len) return error.MissingPair;+ 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.score_ppm > 1_000_000) return error.InvalidScore;+ if (result.cost_micros > eval.js_exact_max or result.latency_ms > eval.js_exact_max or result.tool_calls > eval.js_exact_max) return error.InvalidMetric;+ }+}++fn validatePrimaryEnvelope(+ request: eval.PrimaryEvaluationRequest,+ response: eval.PrimaryEvaluationResponse,+ baseline: eval.PrimaryBaselineRecord,+ 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, eval.primary_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.baseline.request_evidence_id, baseline.request_evidence_id) or+ !std.mem.eql(u8, request.baseline.response_evidence_id, baseline.response_evidence_id) or+ !std.mem.eql(u8, request.baseline.path, baseline_path) 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.InvalidPrimaryRequest;+ if (!std.mem.eql(u8, response.schema, eval.primary_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.InvalidPrimaryResponse;+}++fn validateParentProjection(baseline: eval.PrimaryBaselineResponse, response: eval.PrimaryEvaluationResponse) !void {+ if (response.pairs.len != baseline.pairs.len) return error.MissingPair;+ for (response.pairs, baseline.pairs) |pair, parent| {+ if (!std.mem.eql(u8, pair.case_id, parent.case_id) or+ !std.mem.eql(u8, pair.seed, parent.seed) or+ pair.parent_pass != parent.pass or+ pair.parent_score_ppm != parent.score_ppm or+ pair.parent_cost_micros != parent.cost_micros or+ pair.parent_latency_ms != parent.latency_ms or+ pair.latency_measured != parent.latency_measured or+ pair.parent_tool_calls != parent.tool_calls or+ pair.tool_calls_measured != parent.tool_calls_measured) return error.BaselineProjectionMismatch;+ }+}++pub fn evaluateBaseline(+ 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,+ parent_id: []const u8,+ parent_prompt: []const u8,+ suite: store_mod.Suite,+ repetitions: usize,+) !eval.PrimaryBaselineRecord {+ const loaded_suite = try store_mod.loadSuite(io, arena, suite);+ const pairs = try eval.buildPairs(gpa, trial_id, suite, loaded_suite.manifest, 0, repetitions);+ defer eval.freePairs(gpa, pairs);+ const cohort = eval.cohortId(config_id, suite.sha256, harness_version);++ var scratch = try eval.createScratch(io, store);+ defer store.tmp.deleteTree(io, &scratch.name) catch {};+ defer scratch.dir.close(io);+ try scratch.dir.createDir(io, "home", eval.dir_permissions);+ try scratch.dir.createDir(io, "tmp", eval.dir_permissions);+ try eval.writePrivate(io, scratch.dir, "parent.genome", parent_prompt);+ try eval.writePrivate(io, scratch.dir, "suite.json", loaded_suite.bytes);++ const request: eval.PrimaryBaselineRequest = .{+ .schema = eval.primary_baseline_request_schema,+ .trial_id = trial_id,+ .cohort_id = &cohort,+ .suite_sha256 = suite.sha256,+ .suite_path = "suite.json",+ .parent = .{ .id = parent_id, .path = "parent.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 eval.writePrivate(io, scratch.dir, "request.json", request_bytes);++ try eval.invokeEvaluator(gpa, io, parent_env, scratch.dir, config.evaluator, "baseline", config.limits.stdout_bytes, config.limits.stderr_bytes, config.limits.evaluator_timeout_ms);+ const response_bytes = try store_mod.readFileNoFollow(io, scratch.dir, "response.json", gpa, config.limits.response_bytes);+ defer gpa.free(response_bytes);+ const response = try std.json.parseFromSliceLeaky(eval.PrimaryBaselineResponse, arena, response_bytes, .{});+ try validateBaselineEnvelope(request, response, trial_id, &cohort, suite, parent_id, repetitions);+ try validateBaselinePairs(response, pairs);+ const response_id = try store.writeEvidence(gpa, response_bytes);+ return .{+ .suite_sha256 = try arena.dupe(u8, suite.sha256),+ .request_evidence_id = try arena.dupe(u8, &request_id),+ .response_evidence_id = try arena.dupe(u8, &response_id),+ };+}++pub fn evaluateCandidate(+ 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,+ child_id: []const u8,+ child_prompt: []const u8,+ suite: store_mod.Suite,+ repetitions: usize,+ planned_candidates: usize,+ baseline_record: eval.PrimaryBaselineRecord,+) !eval.ComparisonRecord {+ if (!std.mem.eql(u8, baseline_record.suite_sha256, suite.sha256)) return error.BaselineSuiteMismatch;+ const loaded_suite = try store_mod.loadSuite(io, arena, suite);+ const pairs = try eval.buildPairs(gpa, trial_id, suite, loaded_suite.manifest, candidate_index, repetitions);+ defer eval.freePairs(gpa, pairs);+ const cohort = eval.cohortId(config_id, suite.sha256, harness_version);+ const baseline_bytes = try store.readEvidence(arena, baseline_record.response_evidence_id, config.limits.response_bytes);+ const baseline = try std.json.parseFromSliceLeaky(eval.PrimaryBaselineResponse, arena, baseline_bytes, .{});+ try validateBaselinePairs(baseline, pairs);++ var scratch = try eval.createScratch(io, store);+ defer store.tmp.deleteTree(io, &scratch.name) catch {};+ defer scratch.dir.close(io);+ try scratch.dir.createDir(io, "home", eval.dir_permissions);+ try scratch.dir.createDir(io, "tmp", eval.dir_permissions);+ try eval.writePrivate(io, scratch.dir, "child.genome", child_prompt);+ try eval.writePrivate(io, scratch.dir, "suite.json", loaded_suite.bytes);+ try eval.writePrivate(io, scratch.dir, baseline_path, baseline_bytes);++ const request: eval.PrimaryEvaluationRequest = .{+ .schema = eval.primary_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,+ .baseline = .{+ .request_evidence_id = baseline_record.request_evidence_id,+ .response_evidence_id = baseline_record.response_evidence_id,+ .path = baseline_path,+ },+ .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 eval.writePrivate(io, scratch.dir, "request.json", request_bytes);++ try eval.invokeEvaluator(gpa, io, parent_env, scratch.dir, config.evaluator, "evaluate_primary", config.limits.stdout_bytes, config.limits.stderr_bytes, config.limits.evaluator_timeout_ms);+ const response_bytes = try store_mod.readFileNoFollow(io, scratch.dir, "response.json", gpa, config.limits.response_bytes);+ defer gpa.free(response_bytes);+ const response = try std.json.parseFromSliceLeaky(eval.PrimaryEvaluationResponse, arena, response_bytes, .{});+ try validatePrimaryEnvelope(request, response, baseline_record, trial_id, candidate_index, &cohort, suite, parent_id, child_id, repetitions);+ try validateParentProjection(baseline, response);+ const response_id = try store.writeEvidence(gpa, response_bytes);+ var comparison = try eval.computeComparison(config, suite.sha256, &request_id, &response_id, pairs, .{+ .schema = eval.evaluation_response_schema,+ .trial_id = response.trial_id,+ .candidate_index = response.candidate_index,+ .cohort_id = response.cohort_id,+ .suite_sha256 = response.suite_sha256,+ .parent_id = response.parent_id,+ .child_id = response.child_id,+ .pairs = response.pairs,+ }, planned_candidates);+ comparison.request_evidence_id = try arena.dupe(u8, &request_id);+ comparison.response_evidence_id = try arena.dupe(u8, &response_id);+ return comparison;+}++pub fn verifyBaseline(+ arena: Allocator,+ io: Io,+ store: *store_mod.Store,+ config: store_mod.Config,+ config_id: []const u8,+ harness_version: []const u8,+ trial_id: []const u8,+ parent_id: []const u8,+ suite: store_mod.Suite,+ repetitions: usize,+ record: eval.PrimaryBaselineRecord,+) !eval.PrimaryBaselineResponse {+ if (!std.mem.eql(u8, record.suite_sha256, suite.sha256)) return error.BaselineSuiteMismatch;+ const loaded_suite = try store_mod.loadSuite(io, arena, suite);+ const expected = try eval.buildPairs(arena, trial_id, suite, loaded_suite.manifest, 0, repetitions);+ const request_bytes = try store.readEvidence(arena, record.request_evidence_id, config.limits.request_bytes);+ const response_bytes = try store.readEvidence(arena, record.response_evidence_id, config.limits.response_bytes);+ const request = try std.json.parseFromSliceLeaky(eval.PrimaryBaselineRequest, arena, request_bytes, .{});+ const response = try std.json.parseFromSliceLeaky(eval.PrimaryBaselineResponse, arena, response_bytes, .{});+ const cohort = eval.cohortId(config_id, suite.sha256, harness_version);+ try validateBaselineEnvelope(request, response, trial_id, &cohort, suite, parent_id, repetitions);+ try validateRequestedPairs(request.pairs, expected);+ try validateBaselinePairs(response, request.pairs);+ return response;+}++pub fn verifyCandidate(+ 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,+ baseline_record: eval.PrimaryBaselineRecord,+ baseline: eval.PrimaryBaselineResponse,+ recorded: eval.ComparisonRecord,+) !eval.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 = try eval.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(eval.PrimaryEvaluationRequest, arena, request_bytes, .{});+ const response = try std.json.parseFromSliceLeaky(eval.PrimaryEvaluationResponse, arena, response_bytes, .{});+ const cohort = eval.cohortId(config_id, suite.sha256, harness_version);+ try validatePrimaryEnvelope(request, response, baseline_record, trial_id, candidate_index, &cohort, suite, parent_id, child_id, repetitions);+ try validateRequestedPairs(request.pairs, expected);+ try validateParentProjection(baseline, response);+ const recomputed = try eval.computeComparison(config, suite.sha256, recorded.request_evidence_id, recorded.response_evidence_id, request.pairs, .{+ .schema = eval.evaluation_response_schema,+ .trial_id = response.trial_id,+ .candidate_index = response.candidate_index,+ .cohort_id = response.cohort_id,+ .suite_sha256 = response.suite_sha256,+ .parent_id = response.parent_id,+ .child_id = response.child_id,+ .pairs = response.pairs,+ }, planned_candidates);+ if (!eval.comparisonEqual(recomputed, recorded)) return error.ComparisonMismatch;+ return recomputed;+}diff --git a/src/learn_report.zig b/src/learn_report.zignew file mode 100644index 00000000..c2443aa6--- /dev/null+++ b/src/learn_report.zig@@ -0,0 +1,116 @@+//! Human/model-facing summaries for local learning runs. These deliberately+//! expose aggregate evidence only: no genome text, suite payloads, or paths.++const std = @import("std");+const Io = std.Io;+const eval = @import("learn_eval.zig");++fn writeComparison(out: *Io.Writer, label: []const u8, comparison: eval.ComparisonRecord) !void {+ try out.print(+ " {s}: pass {d}/{d} -> {d}/{d}; delta {d} ppm; " +++ "wins/losses/ties {d}/{d}/{d}; p {d} ppb; ",+ .{+ label,+ comparison.parent_passes,+ comparison.pairs,+ comparison.child_passes,+ comparison.pairs,+ comparison.delta_ppm,+ comparison.wins,+ comparison.losses,+ comparison.ties,+ comparison.p_value_ppb,+ },+ );+ if (comparison.tool_calls_measured)+ try out.print("calls {d} -> {d} ({d} ppm; case W/L/T {d}/{d}/{d}; p {d} ppb); ", .{+ comparison.parent_tool_calls,+ comparison.child_tool_calls,+ comparison.tool_delta_ppm,+ comparison.tool_wins,+ comparison.tool_losses,+ comparison.tool_ties,+ comparison.tool_p_value_ppb,+ })+ else+ try out.writeAll("calls unmeasured; ");+ if (comparison.latency_measured)+ try out.print("latency {d} -> {d} ms; ", .{ comparison.parent_latency_ms, comparison.child_latency_ms })+ else+ try out.writeAll("latency unmeasured; ");+ try out.print("cost {d} -> {d} micros; gate {s}\n", .{+ comparison.parent_cost_micros,+ comparison.child_cost_micros,+ comparison.reason,+ });+}++pub fn writeCandidateSummary(out: *Io.Writer, candidates: []const eval.CandidateRecord) !void {+ for (candidates, 0..) |candidate, index| {+ try out.print("candidate {d} {s}", .{ index + 1, candidate.genome_id });+ if (candidate.mutation.description.len > 0) try out.print(" ({s})", .{candidate.mutation.description});+ if (candidate.mutation.genome_bytes > 0) try out.print(" [{d} bytes]", .{candidate.mutation.genome_bytes});+ try out.writeByte('\n');+ if (candidate.primary) |primary|+ try writeComparison(out, "primary", primary)+ else+ try out.writeAll(" primary: not run\n");+ if (candidate.holdout) |holdout|+ try writeComparison(out, "holdout", holdout)+ else+ try out.writeAll(" holdout: not run\n");+ try out.print(" decision: {s}\n", .{candidate.reason});+ }+}++test "candidate summary reports actionable aggregate evidence without content" {+ const comparison: eval.ComparisonRecord = .{+ .suite_sha256 = "suite",+ .request_evidence_id = "request",+ .response_evidence_id = "response",+ .pairs = 15,+ .statistical_units = 15,+ .parent_passes = 14,+ .child_passes = 15,+ .wins = 1,+ .losses = 0,+ .ties = 14,+ .critical_regressions = 0,+ .delta_ppm = 66_666,+ .mean_score_delta_ppm = 66_666,+ .p_value_ppb = 500_000_000,+ .parent_cost_micros = 23,+ .child_cost_micros = 29,+ .tool_calls_measured = true,+ .parent_tool_calls = 23,+ .child_tool_calls = 29,+ .tool_wins = 2,+ .tool_losses = 1,+ .tool_ties = 12,+ .tool_delta_ppm = -260_869,+ .tool_p_value_ppb = 500_000_000,+ .latency_measured = true,+ .parent_latency_ms = 100,+ .child_latency_ms = 80,+ .eligible = false,+ .reason = "not_significant",+ };+ const candidates = [_]eval.CandidateRecord{.{+ .genome_id = "child-fingerprint",+ .mutation = .{ .seed = "seed", .request_evidence_id = "mutation-request", .response_evidence_id = "mutation-response" },+ .primary = comparison,+ .holdout = null,+ .eligible = false,+ .reason = "not_significant",+ }};+ var allocating: Io.Writer.Allocating = .init(std.testing.allocator);+ defer allocating.deinit();+ try writeCandidateSummary(&allocating.writer, &candidates);+ const rendered = allocating.written();+ try std.testing.expect(std.mem.indexOf(u8, rendered, "pass 14/15 -> 15/15") != null);+ try std.testing.expect(std.mem.indexOf(u8, rendered, "wins/losses/ties 1/0/14") != null);+ try std.testing.expect(std.mem.indexOf(u8, rendered, "calls 23 -> 29") != null);+ try std.testing.expect(std.mem.indexOf(u8, rendered, "latency 100 -> 80 ms") != null);+ try std.testing.expect(std.mem.indexOf(u8, rendered, "decision: not_significant") != null);+ try std.testing.expect(std.mem.indexOf(u8, rendered, "suite") == null);+}diff --git a/src/learn_run.zig b/src/learn_run.zignew file mode 100644index 00000000..beccf0ba--- /dev/null+++ b/src/learn_run.zig@@ -0,0 +1,317 @@+//! Concurrent four-arm tournament execution for `graff learn run`.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const build_options = @import("build_options");++const eval = @import("learn_eval.zig");+const holdout = @import("learn_holdout.zig");+const primary = @import("learn_primary.zig");+const report = @import("learn_report.zig");+const store_mod = @import("learn_store.zig");+const submit = @import("learn_submit.zig");+const tournament = @import("learn_tournament.zig");+const util = @import("util.zig");++pub const Options = struct {+ candidates: ?usize,+ repetitions: ?usize,+ submit: bool,+ auto: bool,+};++pub const Result = struct {+ run_id: [64]u8,+ primary_winner_genome_id: ?[]const u8,+ selected_genome_id: ?[]const u8,+};++pub 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);+}++const MutationTaskResult = struct {+ arena: std.heap.ArenaAllocator,+ outcome: eval.MutationOutcome,+};++fn mutationTask(+ gpa: Allocator,+ io: Io,+ environ: *const std.process.Environ.Map,+ store: *store_mod.Store,+ config: store_mod.Config,+ trial_id: []const u8,+ index: usize,+ parent_id: []const u8,+ parent_prompt: []const u8,+) anyerror!MutationTaskResult {+ var task_arena = std.heap.ArenaAllocator.init(gpa);+ errdefer task_arena.deinit();+ const outcome = try eval.mutate(gpa, task_arena.allocator(), io, environ, store, config, trial_id, index, parent_id, parent_prompt);+ return .{ .arena = task_arena, .outcome = outcome };+}++const EvaluationTaskResult = struct {+ arena: std.heap.ArenaAllocator,+ comparison: eval.ComparisonRecord,+};++fn primaryTask(+ gpa: Allocator,+ io: Io,+ environ: *const std.process.Environ.Map,+ store: *store_mod.Store,+ config: store_mod.Config,+ config_id: []const u8,+ trial_id: []const u8,+ index: usize,+ parent_id: []const u8,+ child_id: []const u8,+ child_prompt: []const u8,+ suite: store_mod.Suite,+ repetitions: usize,+ planned_candidates: usize,+ baseline: eval.PrimaryBaselineRecord,+) anyerror!EvaluationTaskResult {+ var task_arena = std.heap.ArenaAllocator.init(gpa);+ errdefer task_arena.deinit();+ const comparison = try primary.evaluateCandidate(+ gpa,+ task_arena.allocator(),+ io,+ environ,+ store,+ config,+ config_id,+ build_options.version,+ trial_id,+ index,+ parent_id,+ child_id,+ child_prompt,+ suite,+ repetitions,+ planned_candidates,+ baseline,+ );+ return .{ .arena = task_arena, .comparison = comparison };+}++fn mutationIsDuplicate(parent_id: []const u8, candidates: []const eval.CandidateRecord, index: usize) ?[]const u8 {+ if (std.mem.eql(u8, candidates[index].genome_id, parent_id)) return "identical_parent";+ for (candidates[0..index]) |prior| {+ if (std.mem.eql(u8, prior.genome_id, candidates[index].genome_id)) return "duplicate_candidate";+ }+ return null;+}++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 requireCompleteCandidateSet(required: bool, planned: usize, actual: usize) !void {+ if (required and actual != planned) return error.IncompleteCandidateSet;+}++/// Runs mutations and primary comparisons behind separate barriers. The+/// holdout adapter is invoked only after every primary result has joined and+/// the sole winner has been selected.+pub fn execute(+ gpa: Allocator,+ arena: Allocator,+ io: Io,+ environ: *const std.process.Environ.Map,+ store: *store_mod.Store,+ config: store_mod.LoadedConfig,+ active: store_mod.LoadedActive,+ options: Options,+ out: *Io.Writer,+) !Result {+ const candidate_count = options.candidates orelse config.value.gate.default_candidates;+ const repetitions = options.repetitions orelse config.value.gate.default_repetitions;+ if (candidate_count == 0 or candidate_count > 16 or repetitions == 0 or repetitions > 100) return error.InvalidNumber;++ const nonce = try 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);++ const mutation_futures = try arena.alloc(Io.Future(anyerror!MutationTaskResult), candidate_count);+ const mutation_results = try arena.alloc(anyerror!MutationTaskResult, candidate_count);+ for (mutation_futures, 0..) |*future, index| {+ future.* = io.async(mutationTask, .{ gpa, io, environ, store, config.value, &trial_id, index, active.ref.genome_id, active.genome });+ }+ for (mutation_futures, mutation_results) |*future, *result| result.* = future.await(io);+ defer for (mutation_results) |*result| {+ if (result.*) |*task_result| {+ gpa.free(task_result.outcome.prompt);+ task_result.arena.deinit();+ } else |_| {}+ };++ for (mutation_results, candidates) |result, *candidate| {+ const completed = result catch |err| {+ if (config.value.gate.require_all_candidates) return error.IncompleteCandidateSet;+ return err;+ };+ candidate.* = .{+ .genome_id = try arena.dupe(u8, &completed.outcome.genome_id),+ .mutation = completed.outcome.record,+ .primary = null,+ .holdout = null,+ .eligible = false,+ .reason = "unevaluated",+ };+ }++ var primary_indices: std.ArrayList(usize) = .empty;+ defer primary_indices.deinit(gpa);+ for (candidates, 0..) |*candidate, index| {+ if (mutationIsDuplicate(active.ref.genome_id, candidates, index)) |reason| {+ candidate.reason = reason;+ } else try primary_indices.append(gpa, index);+ }+ try requireCompleteCandidateSet(config.value.gate.require_all_candidates, candidate_count, primary_indices.items.len);++ const primary_baseline: ?eval.PrimaryBaselineRecord = if (primary_indices.items.len > 0)+ try primary.evaluateBaseline(+ gpa,+ arena,+ io,+ environ,+ store,+ config.value,+ &config.id,+ build_options.version,+ &trial_id,+ active.ref.genome_id,+ active.genome,+ config.value.evaluation_suite,+ repetitions,+ )+ else+ null;++ const primary_futures = try arena.alloc(Io.Future(anyerror!EvaluationTaskResult), primary_indices.items.len);+ const primary_results = try arena.alloc(anyerror!EvaluationTaskResult, primary_indices.items.len);+ for (primary_indices.items, primary_futures) |index, *future| {+ const mutation = try mutation_results[index];+ future.* = io.async(primaryTask, .{+ gpa, io, environ, store, config.value, &config.id,+ &trial_id, index, active.ref.genome_id, candidates[index].genome_id, mutation.outcome.prompt, config.value.evaluation_suite,+ repetitions, candidate_count, primary_baseline.?,+ });+ }+ for (primary_futures, primary_results) |*future, *result| result.* = future.await(io);+ defer for (primary_results) |*result| {+ if (result.*) |*task_result| task_result.arena.deinit() else |_| {}+ };+ for (primary_indices.items, primary_results) |index, result| {+ candidates[index].primary = (try result).comparison;+ }++ const primary_winner_index = tournament.primaryWinnerIndex(active.ref.genome_id, candidates);+ if (primary_winner_index) |winner_index| {+ if (candidates[winner_index].primary.?.eligible) if (config.value.holdout_suite) |holdout_suite| {+ const mutation = try mutation_results[winner_index];+ try holdout.reserve(io, store.root, holdout_suite.sha256, &trial_id);+ candidates[winner_index].holdout = try eval.evaluate(+ gpa,+ arena,+ io,+ environ,+ store,+ config.value,+ &config.id,+ build_options.version,+ &trial_id,+ winner_index,+ active.ref.genome_id,+ active.genome,+ candidates[winner_index].genome_id,+ mutation.outcome.prompt,+ holdout_suite,+ repetitions,+ 1,+ );+ };+ }+ const finalized = try tournament.finalize(active.ref.genome_id, candidates, config.value.holdout_suite != null);+ const primary_winner = if (finalized.primary_winner_index) |index| candidates[index].genome_id else null;++ // Re-check every externally controlled executable and suite after use and+ // before committing the immutable run record.+ try verifyPins(io, arena, config.value);++ 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 = options.auto,+ .primary_baseline = primary_baseline,+ .candidates = candidates,+ .primary_winner_genome_id = primary_winner,+ .selected_genome_id = finalized.selected_genome_id,+ };+ 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});+ try report.writeCandidateSummary(out, candidates);+ if (primary_winner) |id| try out.print("primary winner {s}\n", .{id});+ if (options.submit) {+ const sent = try submit.submitVerifiedRun(io, gpa, arena, environ, config.value, &run_id, record);+ try out.print("submitted {d} signed aggregate grade(s); prompt text stayed local\n", .{sent.grades});+ }+ return .{+ .run_id = run_id,+ .primary_winner_genome_id = primary_winner,+ .selected_genome_id = finalized.selected_genome_id,+ };+}++test "trial IDs bind active generation and transaction" {+ const original = trialId("config", "parent", 7, "transaction-a", "nonce");+ try std.testing.expectEqualSlices(u8, &original, &trialId("config", "parent", 7, "transaction-a", "nonce"));+ try std.testing.expect(!std.mem.eql(u8, &original, &trialId("config", "parent", 8, "transaction-a", "nonce")));+ try std.testing.expect(!std.mem.eql(u8, &original, &trialId("config", "parent", 7, "transaction-b", "nonce")));+}++test "required tournaments reject a partial unique candidate set" {+ try requireCompleteCandidateSet(false, 4, 3);+ try std.testing.expectError(error.IncompleteCandidateSet, requireCompleteCandidateSet(true, 4, 3));+ try requireCompleteCandidateSet(true, 4, 4);+}diff --git a/src/learn_store.zig b/src/learn_store.zigindex 9b08a560..3d604769 100644--- a/src/learn_store.zig+++ b/src/learn_store.zig@@ -8,132 +8,33 @@ 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 model = @import("learn_store_types.zig");+pub const config_schema = model.config_schema;+pub const suite_schema = model.suite_schema;+pub const active_schema = model.active_schema;+pub const transaction_schema = model.transaction_schema;+pub const version_bytes = model.version_bytes;+pub const max_config_bytes = model.max_config_bytes;+pub const max_record_bytes = model.max_record_bytes;+pub const max_program_bytes = model.max_program_bytes;+pub const max_suite_bytes = model.max_suite_bytes;+pub const max_pairs = model.max_pairs;+pub const PinnedFile = model.PinnedFile;+pub const Program = model.Program;+pub const Suite = model.Suite;+pub const Limits = model.Limits;+pub const Gate = model.Gate;+pub const AutoPolicy = model.AutoPolicy;+pub const Cohort = model.Cohort;+pub const Config = model.Config;+pub const SuiteCase = model.SuiteCase;+pub const SuiteManifest = model.SuiteManifest;+pub const ActiveRef = model.ActiveRef;+pub const Transaction = model.Transaction;+pub const LoadedConfig = model.LoadedConfig;+pub const LoadedActive = model.LoadedActive;+pub const ActiveAgent = model.ActiveAgent;+pub var active_agent_loaded: bool = false;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);@@ -176,43 +77,12 @@ const validate_mod = @import("learn_store_validate.zig");pub const validId = validate_mod.validId;pub const validateConfig = validate_mod.validateConfig;const validateSuite = validate_mod.validateSuite;--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;- // Fail closed: trial nonces feed trial-ID derivation, so degrading to- // non-cryptographic randomness silently would weaken an integrity- // boundary rather than a convenience.- try io.randomSecure(&raw);- return std.fmt.bytesToHex(raw, .lower);-}+pub const validateTransaction = validate_mod.validateTransaction;+const hash_mod = @import("learn_store_hash.zig");+pub const rawSha256 = hash_mod.rawSha256;+pub const domainId = hash_mod.domainId;+pub const jsonBytes = hash_mod.jsonBytes;+pub const randomId = hash_mod.randomId;pub fn readFileNoFollow(io: Io, dir: Io.Dir, path: []const u8, gpa: Allocator, max: usize) ![]u8 {const file = try openFileNoFollow(io, dir, path, .{});@@ -699,27 +569,15 @@ pub const Store = struct {}};-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 {+ active_agent_loaded = false;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;+ active_agent_loaded = true;return .{.name = config.value.agent_name,.description = config.value.agent_description,diff --git a/src/learn_store_hash.zig b/src/learn_store_hash.zignew file mode 100644index 00000000..b4d28b6b--- /dev/null+++ b/src/learn_store_hash.zig@@ -0,0 +1,41 @@+//! Hashing, serialization, and nonce helpers for learning-store objects.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++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;+ // Trial nonces feed trial-ID derivation, so weak fallback randomness would+ // silently weaken an integrity boundary. Fail closed instead.+ try io.randomSecure(&raw);+ return std.fmt.bytesToHex(raw, .lower);+}diff --git a/src/learn_store_types.zig b/src/learn_store_types.zignew file mode 100644index 00000000..35a8ba19--- /dev/null+++ b/src/learn_store_types.zig@@ -0,0 +1,147 @@+//! Persistent schemas and value types for the local learning store.++const std = @import("std");++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 PromotionMode = enum {+ correctness,+ economy,+};++pub const Gate = struct {+ alpha_ppm: u32 = 50_000,+ minimum_delta_ppm: u32 = 50_000,+ minimum_pairs: usize = 20,+ /// Allow an equally correct candidate to clear the gate through a+ /// statistically significant reduction in measured tool calls.+ economy_gate_enabled: bool = false,+ /// Pre-registered superiority endpoint. Safety and minimum sample gates+ /// remain mandatory in either mode.+ promotion_mode: PromotionMode = .correctness,+ minimum_tool_reduction_ppm: u32 = 100_000,+ /// Minimum number of case-level tool-call wins plus losses. Ties carry no+ /// information for the exact directional economy test.+ minimum_economy_pairs: usize = 8,+ /// Fail the run before any evaluation unless every requested arm produced+ /// a unique genome distinct from the parent.+ require_all_candidates: bool = false,+ 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,+};diff --git a/src/learn_store_validate.zig b/src/learn_store_validate.zigindex ad31c717..8976aa4d 100644--- a/src/learn_store_validate.zig+++ b/src/learn_store_validate.zig@@ -4,7 +4,7 @@//! entry points so external call sites are unchanged.const std = @import("std");-const store = @import("learn_store.zig");+const store = @import("learn_store_types.zig");const Config = store.Config;const Program = store.Program;@@ -74,6 +74,9 @@ pub fn validateConfig(config: Config) !void {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.minimum_tool_reduction_ppm > 1_000_000) return error.InvalidGate;+ if (config.gate.minimum_economy_pairs == 0 or config.gate.minimum_economy_pairs > max_pairs) return error.InvalidGate;+ if (config.gate.promotion_mode == .economy and !config.gate.economy_gate_enabled) 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;@@ -112,3 +115,17 @@ pub fn validateSuite(manifest: SuiteManifest) !void {for (manifest.cases[0..i]) |prior| if (std.mem.eql(u8, prior.id, case.id)) return error.DuplicateCaseId;}}++pub fn validateTransaction(tx: store.Transaction) !void {+ if (!std.mem.eql(u8, tx.schema, store.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;+}diff --git a/src/learn_submit.zig b/src/learn_submit.zignew file mode 100644index 00000000..066d9976--- /dev/null+++ b/src/learn_submit.zig@@ -0,0 +1,190 @@+//! Privacy-preserving publication of verified local-learning grades.+//!+//! Candidate genomes and evaluation payloads stay in the local immutable+//! store. Only the existing signed OTLP score envelope leaves the machine:+//! short prompt/parent fingerprints, aggregate pass rate, suite/cohort+//! metadata, and content-addressed evidence ids.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const build_options = @import("build_options");++const eval = @import("learn_eval.zig");+const store = @import("learn_store.zig");+const scoring = @import("scoring.zig");+const telemetry = @import("telemetry.zig");+const telemetry_net = @import("telemetry_net.zig");+const keys_cli = @import("keys_cli.zig");+const learning_privacy = @import("learning_privacy.zig");++pub const SubmitResult = struct {+ grades: usize,+ endpoint: []const u8,+};++fn endpoint(environ: *const std.process.Environ.Map) ![]const u8 {+ if (environ.get("GRAFF_NO_TELEMETRY") != null) return error.TelemetryDisabled;+ if (environ.get("GRAFF_FLEET")) |value| {+ if (std.ascii.eqlIgnoreCase(value, "off") or std.mem.eql(u8, value, "0") or std.ascii.eqlIgnoreCase(value, "false"))+ return error.TelemetryDisabled;+ }+ const value = environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") orelse+ environ.get("GRAFF_OTEL_ENDPOINT") orelse+ build_options.telemetry_endpoint;+ if (value.len == 0) return error.TelemetryDisabled;+ return value;+}++/// Fail before an expensive learning run when an explicit submit could not+/// produce the backend's required authenticated score envelope.+pub fn preflight(io: Io, arena: Allocator, environ: *const std.process.Environ.Map) !void {+ if (!learning_privacy.allowsAggregate()) return error.LearningPrivacyLocal;+ _ = try endpoint(environ);+ scoring.g_score_key = scoring.loadScoreKey(io, arena, environ) orelse+ return error.ScoreSigningKeyRequired;+}++fn passRate(comparison: eval.ComparisonRecord) !f64 {+ if (comparison.pairs == 0 or comparison.child_passes > comparison.pairs)+ return error.InvalidComparison;+ return @as(f64, @floatFromInt(comparison.child_passes)) /+ @as(f64, @floatFromInt(comparison.pairs));+}++fn appendGrade(+ sink: *telemetry.Telemetry,+ config: store.Config,+ run_id: []const u8,+ run: eval.RunRecord,+ candidate: eval.CandidateRecord,+ comparison: eval.ComparisonRecord,+ judge_id: []const u8,+) !void {+ const prompt_sha = candidate.genome_id[0..16];+ const parent_sha = run.parent_genome_id[0..16];+ const value = try passRate(comparison);+ const provider_class = scoring.providerClass(config.cohort.model);+ // A configured agent name may be an internal project label. Use an opaque+ // config fingerprint for grouping instead of transmitting it verbatim.+ const niche = run.config_id[0..16];+ const signature = scoring.signScore(+ prompt_sha,+ parent_sha,+ value,+ run_id,+ judge_id,+ comparison.response_evidence_id,+ comparison.suite_sha256,+ niche,+ provider_class,+ );+ if (signature[0] == 0) return error.ScoreSigningKeyRequired;+ var provenance_buf: [320]u8 = undefined;+ const provenance = std.fmt.bufPrint(&provenance_buf, "{s}\t{s}\t{s}\t{s}\t{s}", .{+ judge_id,+ comparison.response_evidence_id,+ comparison.suite_sha256,+ provider_class,+ niche,+ }) catch return error.ProvenanceTooLong;+ sink.scoreEvent(prompt_sha, parent_sha, value, run_id, &signature, provenance);+}++pub fn submitVerifiedRun(+ io: Io,+ gpa: Allocator,+ arena: Allocator,+ environ: *const std.process.Environ.Map,+ config: store.Config,+ run_id: []const u8,+ run: eval.RunRecord,+) !SubmitResult {+ try preflight(io, arena, environ);+ var primary_count: usize = 0;+ var holdout_count: usize = 0;+ var primary_winner_eligible = false;+ for (run.candidates) |candidate| {+ if (candidate.primary != null) primary_count += 1;+ if (candidate.holdout != null) holdout_count += 1;+ if (run.primary_winner_genome_id) |winner_id| {+ if (std.mem.eql(u8, candidate.genome_id, winner_id) and candidate.primary != null)+ primary_winner_eligible = candidate.primary.?.eligible;+ }+ }+ if (primary_count == 0 or primary_count > run.planned_candidates) return error.InvalidTournamentTopology;+ if (config.holdout_suite != null) {+ const expected_holdouts: usize = if (primary_winner_eligible) 1 else 0;+ if (holdout_count != expected_holdouts) return error.InvalidTournamentTopology;+ } else if (holdout_count != 0) return error.InvalidTournamentTopology;+ const target = try endpoint(environ);+ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ const home = keys_cli.homeEnv(environ) orelse "";+ var sink: telemetry.Telemetry = .{+ .io = io,+ .gpa = gpa,+ .client = &client,+ .endpoint = target,+ .auth_key = telemetry.validatedAuthKey(environ.get("GRAFF_TELEMETRY_KEY")),+ .install_id = keys_cli.loadOrCreateId(io, gpa, home, ".simple-harness-install-id"),+ .client_name = "harness-learn",+ .sdk_install_id = "",+ .start = Io.Timestamp.now(io, .awake),+ .start_unix_ms = run.created_unix_ms,+ };+ defer sink.deinit();++ var grades: usize = 0;+ for (run.candidates) |candidate| {+ if (candidate.primary) |comparison| {+ try appendGrade(&sink, config, run_id, run, candidate, comparison, "learn-primary-v2");+ grades += 1;+ }+ if (candidate.holdout) |comparison| {+ try appendGrade(&sink, config, run_id, run, candidate, comparison, "learn-holdout-v2");+ grades += 1;+ }+ }+ if (grades == 0) return error.NoEvaluatedCandidates;++ var payload: Io.Writer.Allocating = .init(gpa);+ defer payload.deinit();+ try sink.writeOtlp(&payload.writer, sink.events.items, false);+ const url = (try telemetry_net.otlpLogsUrl(gpa, target)) orelse return error.InvalidTelemetryEndpoint;+ defer gpa.free(url);+ const accepted = telemetry_net.postOtlpWithDeadline(+ io,+ &client,+ url,+ payload.writer.buffered(),+ sink.auth_key orelse "",+ .fromSeconds(10),+ );+ if (!accepted) return error.SubmissionFailed;+ return .{ .grades = grades, .endpoint = target };+}++test "learning pass-rate grade uses repeated pair count" {+ const comparison: eval.ComparisonRecord = .{+ .suite_sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ .request_evidence_id = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ .response_evidence_id = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",+ .pairs = 4,+ .statistical_units = 2,+ .parent_passes = 1,+ .child_passes = 3,+ .wins = 2,+ .losses = 0,+ .ties = 2,+ .critical_regressions = 0,+ .delta_ppm = 500_000,+ .mean_score_delta_ppm = 0,+ .p_value_ppb = 1,+ .parent_cost_micros = 0,+ .child_cost_micros = 0,+ .eligible = true,+ .reason = "eligible",+ };+ try std.testing.expectApproxEqAbs(@as(f64, 0.75), try passRate(comparison), 1e-12);+}diff --git a/src/learn_tournament.zig b/src/learn_tournament.zignew file mode 100644index 00000000..b799f2f7--- /dev/null+++ b/src/learn_tournament.zig@@ -0,0 +1,279 @@+//! Pure tournament policy for primary ranking, one-winner holdout evaluation,+//! and final promotion eligibility.++const std = @import("std");+const eval = @import("learn_eval.zig");++pub const Eligibility = struct {+ eligible: bool,+ reason: []const u8,+};++pub const Finalized = struct {+ /// Best unique, non-parent candidate with primary evidence. This candidate+ /// advances to the holdout even when its primary gate is not yet eligible.+ primary_winner_index: ?usize,+ /// Set only when that one winner passes every configured promotion gate.+ selected_genome_id: ?[]const u8,+};++fn passRateOrder(a: eval.ComparisonRecord, b: eval.ComparisonRecord) std.math.Order {+ if (a.pairs == 0 or b.pairs == 0) {+ if (a.pairs == 0 and b.pairs == 0) return .eq;+ return if (a.pairs == 0) .lt else .gt;+ }+ const a_rate = @as(u128, a.child_passes) * @as(u128, b.pairs);+ const b_rate = @as(u128, b.child_passes) * @as(u128, a.pairs);+ return std.math.order(a_rate, b_rate);+}++/// Safety and the candidate's own observed correctness dominate the+/// tournament. Parent-relative deltas and one-shot latency are deliberately+/// excluded: a stochastic parent or noisy wall clock must not choose a winner.+/// Resource use is considered only after child correctness ties.+pub fn primaryOutranks(a: eval.CandidateRecord, b: eval.CandidateRecord) bool {+ const ac = a.primary.?;+ const bc = b.primary.?;+ if (ac.child_critical_failures != bc.child_critical_failures) return ac.child_critical_failures < bc.child_critical_failures;+ if (ac.critical_regressions != bc.critical_regressions) return ac.critical_regressions < bc.critical_regressions;+ switch (passRateOrder(ac, bc)) {+ .gt => return true,+ .lt => return false,+ .eq => {},+ }+ if (ac.child_passes != bc.child_passes) return ac.child_passes > bc.child_passes;+ // Missing instrumentation is unknown, not zero. Prefer measured economy;+ // only compare exact call counts when both adapters supplied them.+ if (ac.tool_calls_measured != bc.tool_calls_measured) return ac.tool_calls_measured;+ if (ac.tool_calls_measured and ac.child_tool_calls != bc.child_tool_calls) return ac.child_tool_calls < bc.child_tool_calls;+ if (ac.child_cost_micros != bc.child_cost_micros) return ac.child_cost_micros < bc.child_cost_micros;+ if (a.mutation.genome_bytes != 0 and b.mutation.genome_bytes != 0 and a.mutation.genome_bytes != b.mutation.genome_bytes)+ return a.mutation.genome_bytes < b.mutation.genome_bytes;+ return std.mem.order(u8, a.genome_id, b.genome_id) == .lt;+}++fn exclusionReason(parent_genome_id: []const u8, candidates: []const eval.CandidateRecord, index: usize) ?[]const u8 {+ const contender = candidates[index];+ if (std.mem.eql(u8, contender.genome_id, parent_genome_id)) return "identical_parent";+ for (candidates[0..index]) |prior| {+ if (std.mem.eql(u8, contender.genome_id, prior.genome_id)) return "duplicate_candidate";+ }+ return null;+}++/// Chooses the sole candidate that may see the hidden holdout. A primary+/// comparison is required, but primary eligibility is deliberately not: the+/// tournament ranks observed performance before applying promotion gates.+pub fn primaryWinnerIndex(parent_genome_id: []const u8, candidates: []const eval.CandidateRecord) ?usize {+ var winner: ?usize = null;+ for (candidates, 0..) |contender, index| {+ if (contender.primary == null or exclusionReason(parent_genome_id, candidates, index) != null) continue;+ if (winner == null or primaryOutranks(contender, candidates[winner.?])) winner = index;+ }+ return winner;+}++/// Computes promotion eligibility for the primary winner. A primary rejection+/// is final and does not require exposing the configured hidden holdout.+pub fn deriveWinnerEligibility(+ primary: eval.ComparisonRecord,+ holdout: ?eval.ComparisonRecord,+ holdout_required: bool,+) !Eligibility {+ if (!primary.eligible) return .{ .eligible = false, .reason = primary.reason };+ if (holdout_required and holdout == null) return error.MissingHoldout;+ if (!holdout_required and holdout != null) return error.UnexpectedHoldout;+ if (holdout) |holdout_comparison| {+ if (!holdout_comparison.eligible) return .{ .eligible = false, .reason = "holdout_rejected" };+ }+ return .{ .eligible = true, .reason = "eligible" };+}++/// Applies the final gate atomically after the winner's optional holdout has+/// been evaluated. Primary losers can never remain eligible, and holdout+/// evidence on any loser is rejected so the hidden suite stays winner-only.+pub fn finalize(+ parent_genome_id: []const u8,+ candidates: []eval.CandidateRecord,+ holdout_required: bool,+) !Finalized {+ const winner = primaryWinnerIndex(parent_genome_id, candidates);+ for (candidates, 0..) |contender, index| {+ if (contender.holdout != null and (winner == null or index != winner.?)) return error.NonWinnerHoldout;+ }++ const decision: ?Eligibility = if (winner) |index|+ try deriveWinnerEligibility(candidates[index].primary.?, candidates[index].holdout, holdout_required)+ else+ null;++ for (candidates, 0..) |*candidate, index| {+ candidate.eligible = false;+ if (exclusionReason(parent_genome_id, candidates, index)) |reason| {+ candidate.reason = reason;+ } else if (winner != null and index == winner.?) {+ candidate.eligible = decision.?.eligible;+ candidate.reason = decision.?.reason;+ } else if (candidate.primary != null) {+ candidate.reason = "not_primary_winner";+ }+ }++ return .{+ .primary_winner_index = winner,+ .selected_genome_id = if (winner) |index|+ if (candidates[index].eligible) candidates[index].genome_id else null+ else+ null,+ };+}++const mutation: eval.MutationRecord = .{+ .seed = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ .request_evidence_id = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ .response_evidence_id = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",+};++fn fakeComparison(delta: i64, score_delta: i64, p: u64, cost: u64, eligible: bool, reason: []const u8) eval.ComparisonRecord {+ return .{+ .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 = delta,+ .mean_score_delta_ppm = score_delta,+ .p_value_ppb = p,+ .parent_cost_micros = 100,+ .child_cost_micros = cost,+ .tool_calls_measured = true,+ .parent_tool_calls = 10,+ .child_tool_calls = 10,+ .latency_measured = true,+ .parent_latency_ms = 100,+ .child_latency_ms = 100,+ .eligible = eligible,+ .reason = reason,+ };+}++fn fakeCandidate(id: []const u8, primary: ?eval.ComparisonRecord) eval.CandidateRecord {+ return .{+ .genome_id = id,+ .mutation = mutation,+ .primary = primary,+ .holdout = null,+ .eligible = false,+ .reason = if (primary == null) "unevaluated" else primary.?.reason,+ };+}++test "primary winner is correctness-first then tool calls, cost, and genome ID" {+ var candidates = [_]eval.CandidateRecord{+ fakeCandidate("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", fakeComparison(20, 10, 5, 1, true, "eligible")),+ fakeCandidate("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", fakeComparison(30, 10, 5, 100, false, "not_significant")),+ };+ // Parent-relative deltas cannot break an equal-child tie. Candidate zero+ // is cheaper despite having the smaller apparent delta.+ try std.testing.expectEqual(@as(?usize, 0), primaryWinnerIndex("parent", &candidates));++ candidates[0].primary = fakeComparison(30, 10, 5, 50, true, "eligible");+ try std.testing.expectEqual(@as(?usize, 0), primaryWinnerIndex("parent", &candidates));++ candidates[0].primary.?.child_tool_calls = 9;+ candidates[1].primary.?.child_tool_calls = 8;+ try std.testing.expectEqual(@as(?usize, 1), primaryWinnerIndex("parent", &candidates));++ candidates[0].primary.?.child_tool_calls = 8;+ candidates[1].primary.?.child_cost_micros = 50;+ try std.testing.expectEqual(@as(?usize, 1), primaryWinnerIndex("parent", &candidates));++ // One-shot latency is reported, but is too noisy to choose a winner.+ candidates[0].primary.?.child_cost_micros = 50;+ candidates[0].mutation.genome_bytes = 100;+ candidates[1].mutation.genome_bytes = 200;+ candidates[0].primary.?.child_latency_ms = 1_000;+ candidates[1].primary.?.child_latency_ms = 1;+ try std.testing.expectEqual(@as(?usize, 0), primaryWinnerIndex("parent", &candidates));+}++test "critical child safety outranks higher pass rate" {+ var candidates = [_]eval.CandidateRecord{+ fakeCandidate("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", fakeComparison(100, 100, 1, 1, false, "critical_regression")),+ fakeCandidate("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", fakeComparison(0, 0, 1_000_000_000, 100, false, "minimum_delta")),+ };+ candidates[0].primary.?.child_critical_failures = 1;+ candidates[0].primary.?.child_passes = 20;+ candidates[1].primary.?.child_passes = 19;+ try std.testing.expectEqual(@as(?usize, 1), primaryWinnerIndex("parent", &candidates));+}++test "higher pass rate outranks cheaper operation" {+ var candidates = [_]eval.CandidateRecord{+ fakeCandidate("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", fakeComparison(0, 0, 1, 1, false, "minimum_delta")),+ fakeCandidate("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", fakeComparison(0, 0, 1, 100, false, "minimum_delta")),+ };+ candidates[0].primary.?.child_passes = 14;+ candidates[0].primary.?.child_tool_calls = 1;+ candidates[1].primary.?.child_passes = 15;+ candidates[1].primary.?.child_tool_calls = 100;+ try std.testing.expectEqual(@as(?usize, 1), primaryWinnerIndex("parent", &candidates));+}++test "null, parent-identical, and duplicate candidates do not contend" {+ const parent = "1111111111111111111111111111111111111111111111111111111111111111";+ const unique = "2222222222222222222222222222222222222222222222222222222222222222";+ var candidates = [_]eval.CandidateRecord{+ fakeCandidate("0000000000000000000000000000000000000000000000000000000000000000", null),+ fakeCandidate(parent, fakeComparison(999, 999, 0, 0, true, "eligible")),+ fakeCandidate(unique, fakeComparison(10, 10, 10, 10, false, "minimum_pairs")),+ fakeCandidate(unique, fakeComparison(999, 999, 0, 0, true, "eligible")),+ };+ try std.testing.expectEqual(@as(?usize, 2), primaryWinnerIndex(parent, &candidates));+}++test "only the primary winner can become finally eligible" {+ const parent = "1111111111111111111111111111111111111111111111111111111111111111";+ var candidates = [_]eval.CandidateRecord{+ fakeCandidate("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", fakeComparison(20, 10, 5, 10, true, "eligible")),+ fakeCandidate("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", fakeComparison(30, 10, 5, 20, true, "eligible")),+ };+ candidates[0].eligible = true;+ candidates[1].holdout = fakeComparison(5, 5, 10, 5, true, "eligible");++ const result = try finalize(parent, &candidates, true);+ try std.testing.expectEqual(@as(?usize, 1), result.primary_winner_index);+ try std.testing.expectEqualStrings(candidates[1].genome_id, result.selected_genome_id.?);+ try std.testing.expect(!candidates[0].eligible);+ try std.testing.expectEqualStrings("not_primary_winner", candidates[0].reason);+ try std.testing.expect(candidates[1].eligible);+}++test "holdout cannot rescue a primary rejection" {+ var candidates = [_]eval.CandidateRecord{+ fakeCandidate("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", fakeComparison(20, 10, 5, 10, false, "not_significant")),+ };+ const result = try finalize("parent", &candidates, true);+ try std.testing.expectEqual(@as(?usize, 0), result.primary_winner_index);+ try std.testing.expect(result.selected_genome_id == null);+ try std.testing.expectEqualStrings("not_significant", candidates[0].reason);+}++test "finalization fails closed around hidden holdout evidence" {+ var candidates = [_]eval.CandidateRecord{+ fakeCandidate("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", fakeComparison(30, 10, 5, 10, true, "eligible")),+ fakeCandidate("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", fakeComparison(20, 10, 5, 10, true, "eligible")),+ };+ try std.testing.expectError(error.MissingHoldout, finalize("parent", &candidates, true));+ try std.testing.expect(!candidates[0].eligible);++ candidates[0].holdout = fakeComparison(20, 10, 5, 10, true, "eligible");+ candidates[1].holdout = fakeComparison(20, 10, 5, 10, true, "eligible");+ try std.testing.expectError(error.NonWinnerHoldout, finalize("parent", &candidates, true));+}diff --git a/src/learning_privacy.zig b/src/learning_privacy.zignew file mode 100644index 00000000..d4dec7cb--- /dev/null+++ b/src/learning_privacy.zig@@ -0,0 +1,244 @@+//! Privacy policy for federated prompt-policy learning.+//!+//! This is deliberately separate from ordinary usage telemetry. The mode is a+//! ceiling, not blanket content consent: template text also needs an exact,+//! session-local approval before the OTLP fleet path may carry it. Raw task+//! instances, bindings, reports, and traces have no upload path here.++const std = @import("std");+const Io = std.Io;+const util = @import("util.zig");++pub const Mode = enum(u8) {+ local,+ aggregate,+ templates,+ examples,++ pub fn label(self: Mode) []const u8 {+ return switch (self) {+ .local => "Local",+ .aggregate => "Aggregate",+ .templates => "Templates",+ .examples => "Examples",+ };+ }++ pub fn badge(self: Mode) []const u8 {+ return switch (self) {+ .local => "Privacy:Local",+ .aggregate => "Privacy:Aggregate",+ .templates => "Privacy:Templates",+ .examples => "Privacy:Examples",+ };+ }+};++var mode_value: std.atomic.Value(u8) = .init(@intFromEnum(Mode.local));+var approvals_mu: Io.Mutex = .init;+const max_approved_templates = 64;+var approved_hashes: [max_approved_templates][32]u8 = undefined;+var approved_len: usize = 0;+var aggregate_once: bool = false;++/// Exact lowercase values only. Unknown, case-varied, or whitespace-padded+/// configuration fails closed to Local when passed through init().+pub fn parse(value: []const u8) ?Mode {+ if (std.mem.eql(u8, value, "local")) return .local;+ if (std.mem.eql(u8, value, "aggregate")) return .aggregate;+ if (std.mem.eql(u8, value, "templates")) return .templates;+ if (std.mem.eql(u8, value, "examples")) return .examples;+ return null;+}++pub fn init(cli_mode: ?Mode, env_value: ?[]const u8) void {+ const selected = cli_mode orelse if (env_value) |value| parse(value) orelse .local else .local;+ mode_value.store(@intFromEnum(selected), .release);+ // Startup is single-threaded. Artifact approvals never persist between+ // processes, and a repo-controlled file cannot silently grant them.+ approved_len = 0;+ aggregate_once = false;+}++pub fn current() Mode {+ return @enumFromInt(mode_value.load(.acquire));+}++pub fn setMode(io: Io, mode: Mode) void {+ approvals_mu.lockUncancelable(io);+ defer approvals_mu.unlock(io);+ mode_value.store(@intFromEnum(mode), .release);+ // A mode change invalidates content approvals. Raising the ceiling must+ // still ask for each artifact; lowering it revokes them immediately.+ approved_len = 0;+ aggregate_once = false;+}++pub fn allowsAggregate() bool {+ return @intFromEnum(current()) >= @intFromEnum(Mode.aggregate);+}++pub fn allowsTemplateReview() bool {+ return @intFromEnum(current()) >= @intFromEnum(Mode.templates);+}++pub fn allowsExamples() bool {+ return current() == .examples;+}++/// The model-facing learning tool may request one explicit evaluate → grade →+/// submit operation while the session otherwise remains Local. This permit is+/// memory-only, single-use, and deliberately separate from --yolo/approvals.+pub fn authorizeAggregateOnce(io: Io) void {+ approvals_mu.lockUncancelable(io);+ defer approvals_mu.unlock(io);+ aggregate_once = true;+}++pub fn consumeAggregateOnce(io: Io) bool {+ approvals_mu.lockUncancelable(io);+ defer approvals_mu.unlock(io);+ if (!aggregate_once) return false;+ aggregate_once = false;+ return true;+}++pub const SecretScan = struct {+ matches: usize = 0,+ first_kind: []const u8 = "",++ pub fn safe(self: SecretScan) bool {+ return self.matches == 0;+ }+};++const secret_markers = [_]struct { needle: []const u8, kind: []const u8 }{+ .{ .needle = "-----BEGIN PRIVATE KEY-----", .kind = "private key" },+ .{ .needle = "-----BEGIN OPENSSH PRIVATE KEY-----", .kind = "SSH private key" },+ .{ .needle = "authorization: bearer ", .kind = "authorization header" },+ .{ .needle = "aws_access_key_id", .kind = "AWS credential" },+ .{ .needle = "aws_secret_access_key", .kind = "AWS credential" },+ .{ .needle = "openai_api_key", .kind = "API key assignment" },+ .{ .needle = "anthropic_api_key", .kind = "API key assignment" },+ .{ .needle = "github_token", .kind = "GitHub token assignment" },+ .{ .needle = "ghp_", .kind = "GitHub token" },+ .{ .needle = "github_pat_", .kind = "GitHub token" },+ .{ .needle = "sk-proj-", .kind = "API key" },+ .{ .needle = "xoxb-", .kind = "Slack token" },+ .{ .needle = "xoxp-", .kind = "Slack token" },+};++/// A deliberately conservative local canary scan. It is a second boundary,+/// not a claim that arbitrary text can be perfectly sanitized: typed schemas,+/// exact approval, and server-side validation remain required too.+pub fn scanSecrets(text: []const u8) SecretScan {+ var result: SecretScan = .{};+ for (secret_markers) |marker| {+ if (util.indexOfIgnoreCase(text, marker.needle) == null) continue;+ result.matches += 1;+ if (result.first_kind.len == 0) result.first_kind = marker.kind;+ }+ return result;+}++fn contentHash(text: []const u8) [32]u8 {+ var digest: [32]u8 = undefined;+ std.crypto.hash.sha2.Sha256.hash(text, &digest, .{});+ return digest;+}++pub fn displayFingerprint(text: []const u8) [16]u8 {+ const digest = contentHash(text);+ return std.fmt.bytesToHex(digest[0..8].*, .lower);+}++/// Approve this exact template version for this process only. A changed byte+/// has a different hash and asks again. Secret-like content fails closed.+pub fn approveTemplate(io: Io, text: []const u8) bool {+ if (!allowsTemplateReview() or text.len == 0 or !scanSecrets(text).safe()) return false;+ const digest = contentHash(text);+ approvals_mu.lockUncancelable(io);+ defer approvals_mu.unlock(io);+ for (approved_hashes[0..approved_len]) |approved| {+ if (std.mem.eql(u8, &approved, &digest)) return true;+ }+ if (approved_len == max_approved_templates) return false;+ approved_hashes[approved_len] = digest;+ approved_len += 1;+ return true;+}++pub fn isTemplateApproved(io: Io, text: []const u8) bool {+ if (!allowsTemplateReview() or text.len == 0 or !scanSecrets(text).safe()) return false;+ const digest = contentHash(text);+ approvals_mu.lockUncancelable(io);+ defer approvals_mu.unlock(io);+ for (approved_hashes[0..approved_len]) |approved| {+ if (std.mem.eql(u8, &approved, &digest)) return true;+ }+ return false;+}++/// The only function fleet telemetry uses to admit prompt text. This makes an+/// omitted check at an individual propose call site safe by construction.+pub fn templateTextForUpload(io: Io, text: []const u8) []const u8 {+ return if (isTemplateApproved(io, text)) text else "";+}++test "learning privacy config fails closed and modes form a ceiling" {+ init(null, null);+ try std.testing.expectEqual(Mode.local, current());+ try std.testing.expect(!allowsAggregate());+ init(null, "AGGREGATE");+ try std.testing.expectEqual(Mode.local, current());+ init(.templates, "local");+ try std.testing.expectEqual(Mode.templates, current());+ try std.testing.expect(allowsAggregate());+ try std.testing.expect(allowsTemplateReview());+ try std.testing.expect(!allowsExamples());+}++test "secret canaries are blocked without flagging ordinary agent templates" {+ const canaries = [_][]const u8{+ "OPENAI_API_KEY=sk-proj-test-only-not-real",+ "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.test.signature",+ "-----BEGIN OPENSSH PRIVATE KEY-----\nnot-real",+ "export AWS_SECRET_ACCESS_KEY=not-real",+ "token=ghp_abcdefghijklmnopqrstuvwxyz",+ "slack xoxb-111111111-222222222-notreal",+ };+ for (canaries) |canary| try std.testing.expect(!scanSecrets(canary).safe());+ const benign = [_][]const u8{+ "Review the selected files and report defensible correctness bugs.",+ "Run the repository test command, then summarize failures with file and line.",+ "Do not print credentials, authorization headers, environment values, or private keys.",+ "Compare the implementation against the task and give a concise verdict.",+ };+ for (benign) |text| try std.testing.expect(scanSecrets(text).safe());+}++test "template approval is exact, session-local, and cannot approve a canary" {+ const io = std.testing.io;+ setMode(io, .templates);+ defer setMode(io, .local);+ const safe = "You are a careful reviewer.";+ try std.testing.expectEqualStrings("", templateTextForUpload(io, safe));+ try std.testing.expect(approveTemplate(io, safe));+ try std.testing.expectEqualStrings(safe, templateTextForUpload(io, safe));+ try std.testing.expectEqualStrings("", templateTextForUpload(io, "You are a careful reviewer!"));+ try std.testing.expect(!approveTemplate(io, "GITHUB_TOKEN=ghp_not_a_real_token"));+ try std.testing.expectEqualStrings("", templateTextForUpload(io, "GITHUB_TOKEN=ghp_not_a_real_token"));+ setMode(io, .aggregate);+ try std.testing.expectEqualStrings("", templateTextForUpload(io, safe));+}++test "bundled aggregate consent is single-use and revoked by mode changes" {+ const io = std.testing.io;+ setMode(io, .local);+ authorizeAggregateOnce(io);+ try std.testing.expect(consumeAggregateOnce(io));+ try std.testing.expect(!consumeAggregateOnce(io));+ authorizeAggregateOnce(io);+ setMode(io, .local);+ try std.testing.expect(!consumeAggregateOnce(io));+}diff --git a/src/main.zig b/src/main.zigindex 92998940..8462f95d 100644--- a/src/main.zig+++ b/src/main.zig@@ -155,20 +155,18 @@ const Tracer = trace.Tracer;const BehaviorTrace = trace.BehaviorTrace;const behavior_trace = @import("behavior_trace.zig");const behavior_upload = @import("behavior_upload.zig");+const learning_privacy = @import("learning_privacy.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.+// Agent types / MAP-Elites fleet.const fleet = @import("fleet.zig");const joinElites = fleet.joinElites;-// Prompt/provider-class fingerprinting + DGM score signing live in scoring.zig.const scoring = @import("scoring.zig");-// Subagent cards (#51): the parallel-subagent launch/done cards + box helpers + the inspect-report writer live in cards.zig.const cards = @import("cards.zig");-// Telemetry (OTEL): the Telemetry sink lives in telemetry.zig; the session-global pointer is reached telemetry.-qualified at call sites.const telemetry = @import("telemetry.zig");-/// Federated-fleet contribution toggle (docs/hyperagents.md §9); on by default, GRAFF_FLEET=off or /fleet off disables propose/submit/elite_pull.+/// Fleet master switch; learning privacy is the independent default-local egress gate./// General usage telemetry is separate (GRAFF_NO_TELEMETRY).pub var g_fleet: bool = true;const unixMs = util.unixMs;@@ -285,6 +283,7 @@ pub fn main(init: std.process.Init) !void {}// CLI flags: the Flags struct + parsing loop live in args.zig; downstream code reads flags.<name> in place of ~27 locals this block used to declare.const flags = try args.parse(init);+ learning_privacy.init(flags.learning_privacy_flag, init.environ_map.get("GRAFF_LEARNING_PRIVACY"));var invocation_budget: run_budget_mod.RunBudget = .{ .max_model_calls = max_model_calls };boot.mark(init.io, "args");// GRAFF_CODEX_URL: override the codex responses endpoint (localhost mocks / integration tests). Parsed BEFORE subcommand dispatch and@@ -375,7 +374,6 @@ pub fn main(init: std.process.Init) !void {var telem = session_start.initTelemetry(io, gpa, &client, init.environ_map, flags, default_telemetry_endpoint);telemetry.g_telem = &telem;- // Fleet contribution opt-out, independent of telemetry: GRAFF_FLEET=off|0|false|no.if (init.environ_map.get("GRAFF_FLEET")) |fv| {g_fleet = !(std.ascii.eqlIgnoreCase(fv, "off") or std.mem.eql(u8, fv, "0") or std.ascii.eqlIgnoreCase(fv, "false") or std.ascii.eqlIgnoreCase(fv, "no"));}diff --git a/src/prompts.zig b/src/prompts.zigindex 7f18975f..6e70e15d 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -12,11 +12,7 @@ pub const main_system_prompt =\\edit_file for changes to existing files and write_file only for new\\files or full rewrites. To navigate code — finding symbols, callers,\\definitions, or where logic lives — prefer the codedb tool (it's indexed- \\and structural) over bash grep/find/ls. When you only need part of a large- \\file, pass read_file start_line/end_line to read just that span; add compact- \\for a read that only feeds reasoning (not one you'll copy into an edit) to- \\strip comments/blanks — then re-read the exact span WITHOUT compact right- \\before an edit_file, which matches bytes exactly. Some bash commands need user approval — if one+ \\and structural) over bash grep/find/ls. Before an exact edit, read one current uncompressed target span, apply the smallest edit that preserves terminal-newline state, do not verify after success, and reread/retry only on stale source, ambiguity, or failure. Some bash commands need user approval — if one\\is declined, try another approach or ask. Native file tools deliberately\\stay inside the current working directory. If the user explicitly names\\a repository or path outside it, the root agent may inspect and modifydiff --git a/src/providers.zig b/src/providers.zigindex a9984e8f..4691332b 100644--- a/src/providers.zig+++ b/src/providers.zig@@ -387,54 +387,8 @@ 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 = @splat(null) };- 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 {+ _ = @import("providers_behavior_tests.zig");}test "failoverEligible: accepts unavailable credentials/models, rejects transient or prompt errors" {diff --git a/src/providers_behavior_tests.zig b/src/providers_behavior_tests.zignew file mode 100644index 00000000..3e0311ae--- /dev/null+++ b/src/providers_behavior_tests.zig@@ -0,0 +1,59 @@+//! Behavioral root-scope regression tests for provider fallback.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Agent = @import("agent.zig").Agent;+const Keys = @import("provider.zig").Keys;+const providers = @import("providers.zig");+const trace = @import("trace.zig");++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 = @splat(null) };+ try std.testing.expectError(+ error.FallbackConsentRequired,+ providers.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);+}diff --git a/src/read_file.zig b/src/read_file.zignew file mode 100644index 00000000..5868661a--- /dev/null+++ b/src/read_file.zig@@ -0,0 +1,175 @@+//! Bounded native text-file reads. Whole-file reads return a small actionable+//! preview when the file exceeds the tool cap; explicit line windows stream+//! through large files without first allocating their entire contents.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const binaryFileExt = @import("input_util.zig").binaryFileExt;++pub const max_bytes: usize = 256 * 1024;+pub const preview_bytes: usize = 1536;++pub const Truncated = struct {+ head: []u8,+ total_bytes: u64,+};++pub const Result = union(enum) {+ text: []u8,+ truncated: Truncated,+ binary: u64,+ range_too_large,+ start_past_end,+};++fn normalizedBounds(start_opt: ?i64, end_opt: ?i64) ?struct { start: usize, end: usize } {+ const start: usize = if (start_opt) |value| (if (value < 1) 1 else @intCast(value)) else 1;+ const end: usize = if (end_opt) |value| (if (value < 1) 1 else @intCast(value)) else std.math.maxInt(usize);+ if (end < start) return null;+ return .{ .start = start, .end = end };+}++fn readPrefix(io: Io, file: Io.File, size: u64, buffer: []u8) ![]const u8 {+ const want: usize = @intCast(@min(size, buffer.len));+ const got = try file.readPositionalAll(io, buffer[0..want], 0);+ if (got != want) return error.UnexpectedEndOfFile;+ return buffer[0..got];+}++fn readWindow(io: Io, gpa: Allocator, file: Io.File, size: u64, start_opt: ?i64, end_opt: ?i64) !Result {+ const bounds = normalizedBounds(start_opt, end_opt) orelse return .start_past_end;+ if (size == 0) return .start_past_end;++ var output: std.ArrayList(u8) = .empty;+ defer output.deinit(gpa);+ var buffer: [16 * 1024]u8 = undefined;+ var offset: u64 = 0;+ var line: usize = 1;+ var reached_start = bounds.start == 1;++ while (offset < size) {+ const want: usize = @intCast(@min(@as(u64, buffer.len), size - offset));+ const got = try file.readPositionalAll(io, buffer[0..want], offset);+ if (got != want) return error.UnexpectedEndOfFile;+ offset += got;+ for (buffer[0..got]) |byte| {+ if (line >= bounds.start and line <= bounds.end) {+ if (output.items.len == max_bytes) return .range_too_large;+ try output.append(gpa, byte);+ }+ if (byte != '\n') continue;+ if (line == bounds.end) return .{ .text = try output.toOwnedSlice(gpa) };+ line +|= 1;+ if (line == bounds.start) reached_start = true;+ }+ }+ if (!reached_start) return .start_past_end;+ return .{ .text = try output.toOwnedSlice(gpa) };+}++/// Reads from `dir` without ever retaining more than `max_bytes`. The caller+/// owns `text` and `truncated.head` results.+pub fn read(io: Io, gpa: Allocator, dir: Io.Dir, path: []const u8, start_line: ?i64, end_line: ?i64) !Result {+ const file = try dir.openFile(io, path, .{});+ defer file.close(io);+ const before = try file.stat(io);+ if (before.kind != .file) return error.IsDir;+ if (binaryFileExt(path)) return .{ .binary = before.size };++ var prefix_buffer: [4096]u8 = undefined;+ const prefix = try readPrefix(io, file, before.size, &prefix_buffer);+ if (std.mem.indexOfScalar(u8, prefix, 0) != null) return .{ .binary = before.size };++ if (start_line != null or end_line != null)+ return readWindow(io, gpa, file, before.size, start_line, end_line);++ if (before.size > max_bytes) return .{ .truncated = .{+ .head = try gpa.dupe(u8, prefix[0..@min(prefix.len, preview_bytes)]),+ .total_bytes = before.size,+ } };++ const bytes = try gpa.alloc(u8, @intCast(before.size));+ errdefer gpa.free(bytes);+ const got = try file.readPositionalAll(io, bytes, 0);+ if (got != bytes.len) return error.UnexpectedEndOfFile;+ return .{ .text = bytes };+}++test "large whole reads preview while line windows stream byte-exactly" {+ const gpa = std.testing.allocator;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const large = try gpa.alloc(u8, max_bytes + 64);+ defer gpa.free(large);+ @memset(large, 'x');+ large[large.len - 13] = '\n';+ @memcpy(large[large.len - 12 ..], "target\nlast\n");+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "large.txt", .data = large });++ const whole = try read(std.testing.io, gpa, tmp.dir, "large.txt", null, null);+ switch (whole) {+ .truncated => |value| {+ defer gpa.free(value.head);+ try std.testing.expectEqual(@as(u64, large.len), value.total_bytes);+ try std.testing.expectEqual(@as(usize, preview_bytes), value.head.len);+ },+ else => return error.TestExpectedTruncated,+ }++ const window = try read(std.testing.io, gpa, tmp.dir, "large.txt", 2, 3);+ switch (window) {+ .text => |text| {+ defer gpa.free(text);+ try std.testing.expectEqualStrings("target\nlast\n", text);+ },+ else => return error.TestExpectedText,+ }+}++test "streamed windows preserve the original line-slice semantics" {+ const gpa = std.testing.allocator;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "small.txt", .data = "a\nb\nc\nd\n" });++ const cases = [_]struct { start: ?i64, end: ?i64, expected: ?[]const u8 }{+ .{ .start = null, .end = null, .expected = "a\nb\nc\nd\n" },+ .{ .start = 1, .end = 1, .expected = "a\n" },+ .{ .start = 2, .end = 3, .expected = "b\nc\n" },+ .{ .start = 3, .end = 99, .expected = "c\nd\n" },+ .{ .start = 99, .end = 100, .expected = null },+ };+ for (cases) |case| {+ const outcome = try read(std.testing.io, gpa, tmp.dir, "small.txt", case.start, case.end);+ if (case.expected) |expected| switch (outcome) {+ .text => |text| {+ defer gpa.free(text);+ try std.testing.expectEqualStrings(expected, text);+ },+ else => return error.TestExpectedText,+ } else try std.testing.expect(outcome == .start_past_end);+ }++ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "unterminated.txt", .data = "x\ny" });+ const final_line = try read(std.testing.io, gpa, tmp.dir, "unterminated.txt", 2, 2);+ switch (final_line) {+ .text => |text| {+ defer gpa.free(text);+ try std.testing.expectEqualStrings("y", text);+ },+ else => return error.TestExpectedText,+ }+}++test "oversized requested line fails bounded instead of StreamTooLong" {+ const gpa = std.testing.allocator;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const large = try gpa.alloc(u8, max_bytes + 1);+ defer gpa.free(large);+ @memset(large, 'x');+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "one-line.txt", .data = large });+ try std.testing.expect((try read(std.testing.io, gpa, tmp.dir, "one-line.txt", 1, 1)) == .range_too_large);+}diff --git a/src/schema.zig b/src/schema.zigindex e8c5197b..68562eaa 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -13,6 +13,7 @@ const Allocator = std.mem.Allocator;const mcp = @import("mcp.zig");const pricing = @import("pricing.zig");const model_table = pricing.model_table;+const learn_store = @import("learn_store.zig");const root = @import("main.zig");const provider_mod = @import("provider.zig");@@ -82,7 +83,8 @@ const schema_flags_json =\\ {"flag": "--max-tool-calls", "arg": "N", "description": "hard per-turn root tool-call budget; rejected calls emit tool_rejected/tool_result"},\\ {"flag": "--max-model-calls", "arg": "N", "description": "invocation-wide provider-call ceiling shared by root, subagents, retries, title, compaction, and judges; default 256"},\\ {"flag": "--dedupe-tool-calls", "arg": null, "description": "reject duplicate root tool name+normalized-input calls per turn"},- \\ {"flag": "--no-telemetry", "arg": null, "description": "disable anonymous OTEL usage telemetry for this run"}+ \\ {"flag": "--no-telemetry", "arg": null, "description": "disable anonymous OTEL usage telemetry for this run"},+ \\ {"flag": "--learning-privacy", "arg": "local|aggregate|templates|examples", "description": "set the prompt-learning egress ceiling; default local, and template text still requires exact interactive approval"}\\];const ToolSpec = struct {@@ -119,7 +121,7 @@ const base_specs = [_]ToolSpec{},.{.name = "read_file",- .desc = "Read a UTF-8 text file. Call this before editing any file. For a big file you only need part of, pass start_line/end_line (1-based, inclusive) to read just that span.",+ .desc = "Read a UTF-8 text file. Call this before editing any file. Whole-file reads over 256 KiB return a short preview; pass start_line/end_line (1-based, inclusive) for a byte-exact window from any size file.",.schema =\\{"type": "object", "properties": {"path": {"type": "string", "description": "File path, relative to the working directory"}, "start_line": {"type": "integer", "description": "Optional 1-based first line to return (byte-exact slice; omit for whole file)"}, "end_line": {"type": "integer", "description": "Optional 1-based last line to return, inclusive"}, "compact": {"type": "boolean", "description": "Exploratory only: return a comment/blank-stripped view via codedb (line numbers shown). NEVER use before an edit — re-read without compact to copy exact text."}}, "required": ["path"]},@@ -215,7 +217,15 @@ const workflow_spec = ToolSpec{,};-pub const root_specs = base_specs ++ meta_specs ++ [_]ToolSpec{ subagent_spec, workflow_spec };+const learn_candidate_spec = ToolSpec{+ .name = "learn_candidate",+ .desc = "Bundle the workspace's pinned prompt-policy mutation, paired evaluation, immutable evidence, and signed aggregate grade submission into one action. Grade telemetry excludes prompt/genome text, but configured adapters may send it to their declared model provider. In Local privacy mode this requires a separate one-shot confirmation that --yolo cannot bypass; Aggregate or higher uses normal tool approval. This never promotes or changes the active policy and is root-only.",+ .schema =+ \\{"type": "object", "properties": {"candidates": {"type": "integer", "minimum": 1, "maximum": 16, "description": "Optional candidate count; defaults to the learning config"}, "repetitions": {"type": "integer", "minimum": 1, "maximum": 100, "description": "Optional repetitions per evaluation case; defaults to the learning config"}}}+ ,+};++pub const root_specs = base_specs ++ meta_specs ++ [_]ToolSpec{ subagent_spec, workflow_spec, learn_candidate_spec };// The common catalog (clock_sleep off) is static too. Previously every root// startup allocated and filled a filtered ToolSpec array before rendering even@@ -232,6 +242,30 @@ const root_specs_without_clock = blk: {break :blk out;};+const root_specs_without_learning = blk: {+ var out: [root_specs.len - 1]ToolSpec = undefined;+ var len: usize = 0;+ for (root_specs) |tool| {+ if (std.mem.eql(u8, tool.name, "learn_candidate")) continue;+ out[len] = tool;+ len += 1;+ }+ if (len != out.len) @compileError("root tool catalog must contain exactly one learn_candidate entry");+ break :blk out;+};++const root_specs_without_optional = blk: {+ var out: [root_specs.len - 2]ToolSpec = undefined;+ var len: usize = 0;+ for (root_specs) |tool| {+ if (std.mem.eql(u8, tool.name, "clock_sleep") or std.mem.eql(u8, tool.name, "learn_candidate")) continue;+ out[len] = tool;+ len += 1;+ }+ if (len != out.len) @compileError("root tool catalog optional entries changed");+ break :blk out;+};+pub fn isMetaName(name: []const u8) bool {return std.mem.eql(u8, name, "todo_write") orstd.mem.eql(u8, name, "todo_read") or@@ -301,16 +335,12 @@ pub fn renderRootTools(return aw.toOwnedSlice();}-/// Root tool catalog for the current session: drops clock_sleep unless the-/// root-only feature flag is on (--clock-sleep / GRAFF_CLOCK_SLEEP=1, see-/// main.zig g_clock_sleep) so the model never even sees a tool it can't-/// call while the flag is off (#225). Subagents are unaffected — they-/// build their tool lists from base_specs only (tools_*_sub above), which-/// never included meta_specs/clock_sleep in the first place.+/// Root tool catalog for the current session: optional tools are absent unless+/// enabled and usable, avoiding schema tokens for calls that cannot succeed.pub fn effectiveRootSpecs(arena: Allocator) ![]const ToolSpec {_ = arena;- if (root.g_clock_sleep) return &root_specs;- return &root_specs_without_clock;+ if (root.g_clock_sleep) return if (learn_store.active_agent_loaded) &root_specs else &root_specs_without_learning;+ return if (learn_store.active_agent_loaded) &root_specs_without_clock else &root_specs_without_optional;}const Schema = union(enum) { raw: []const u8, value: Value };@@ -520,7 +550,12 @@ test "effectiveRootSpecs: drops clock_sleep from the root tool catalog unless thdefer arena_state.deinit();const a = arena_state.allocator();const saved = root.g_clock_sleep;- defer root.g_clock_sleep = saved;+ const saved_learning = learn_store.active_agent_loaded;+ defer {+ root.g_clock_sleep = saved;+ learn_store.active_agent_loaded = saved_learning;+ }+ learn_store.active_agent_loaded = true;root.g_clock_sleep = false;const off_specs = try effectiveRootSpecs(a);@@ -536,6 +571,21 @@ test "effectiveRootSpecs: drops clock_sleep from the root tool catalog unless thif (std.mem.eql(u8, t.name, "clock_sleep")) found = true;}try std.testing.expect(found);++ root.g_clock_sleep = false;+ learn_store.active_agent_loaded = false;+ const minimal_specs = try effectiveRootSpecs(a);+ try std.testing.expectEqual(root_specs.len - 2, minimal_specs.len);+ for (minimal_specs) |tool| try std.testing.expect(!std.mem.eql(u8, tool.name, "learn_candidate"));+}+test "learn_candidate is root-only and cannot become a subagent tool" {+ var found = false;+ for (root_specs) |tool| if (std.mem.eql(u8, tool.name, "learn_candidate")) {+ found = true;+ };+ try std.testing.expect(found);+ try std.testing.expect(std.mem.indexOf(u8, learn_candidate_spec.desc, "adapters may send it") != null);+ try std.testing.expect(std.mem.indexOf(u8, tools_openai_sub, "learn_candidate") == null);}test "providerTakesEffort: effort-honoring providers, but never for grok models" {try std.testing.expect(providerTakesEffort(.responses, "codex", "gpt-5.5"));diff --git a/src/scoring.zig b/src/scoring.zigindex ddc1f4ae..cdcc943f 100644--- a/src/scoring.zig+++ b/src/scoring.zig@@ -156,10 +156,14 @@ pub fn sanitizeMetaField(buf: []u8, field: []const u8) []const u8 {return buf[0..n];}-/// Read the signing key from GRAFF_SCORE_KEY_FILE (a path outside cwd) into-/// `arena`. Whitespace-trimmed; null when unset, unreadable, or empty.+/// Read the signing key from GRAFF_SCORE_KEY_FILE, or the conventional+/// ~/.simple-harness/score.key when no path is configured. The key stays+/// outside cwd so learning adapters and confined subagents cannot read it.pub fn loadScoreKey(io: Io, arena: Allocator, environ: anytype) ?[]const u8 {- const path = environ.get("GRAFF_SCORE_KEY_FILE") orelse return null;+ const path = environ.get("GRAFF_SCORE_KEY_FILE") orelse blk: {+ const home = environ.get("HOME") orelse environ.get("USERPROFILE") orelse return null;+ break :blk std.fmt.allocPrint(arena, "{s}/.simple-harness/score.key", .{home}) catch return null;+ };const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 * 1024)) catch return null;const trimmed = std.mem.trim(u8, data, " \t\r\n");return if (trimmed.len == 0) null else trimmed;diff --git a/src/subagent.zig b/src/subagent.zigindex 9532fa7c..0c06e9fc 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -31,6 +31,7 @@ const promptFingerprint = scoring.promptFingerprint;const providerClass = scoring.providerClass;const signScore = scoring.signScore;const fleet = @import("fleet.zig");+const learning_privacy = @import("learning_privacy.zig");const agentTypePrompt = fleet.agentTypePrompt;const cards = @import("cards.zig");const trace = @import("trace.zig");@@ -188,6 +189,7 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const};const sub_start = Io.Timestamp.now(ctx.io, .awake);if (sys_override) |so| if (telemetry.g_telem) |t| {+ if (fleet.promptIsPublic(so)) _ = learning_privacy.approveTemplate(ctx.io, so);t.countVariant();// fleet:propose (docs §9.B) — a niche's elite was mutated into a variant.const child_fp = promptFingerprint(so);diff --git a/src/telemetry.zig b/src/telemetry.zigindex df2f03e4..3b137e9d 100644--- a/src/telemetry.zig+++ b/src/telemetry.zig@@ -25,6 +25,7 @@ const http = @import("http.zig");// For the session run id (score/run join key) and the propose-site// fingerprint check. No cycle: scoring imports only std + pricing.const scoring = @import("scoring.zig");+const learning_privacy = @import("learning_privacy.zig");const root = @import("main.zig");const harness_version = root.harness_version;@@ -179,7 +180,7 @@ pub const Telemetry = struct {/// Count a subagent spawned with a system-prompt override (an agent-type/// persona or an inline variant) — the swarm's prompt diversity signal.pub fn countVariant(self: *Telemetry) void {- if (!self.on()) return;+ if (!self.on() or !learning_privacy.allowsAggregate()) return;self.mutex.lockUncancelable(self.io);defer self.mutex.unlock(self.io);self.prompt_variants += 1;@@ -189,7 +190,7 @@ pub const Telemetry = struct {/// backend can validate that the evolution loop is actually running:/// one log record per score, prompt_sha + value as attributes.pub fn scoreEvent(self: *Telemetry, sha: []const u8, parent: []const u8, value: f64, run_id: []const u8, sig: []const u8, prov: []const u8) void {- if (!self.on()) return;+ if (!self.on() or !learning_privacy.allowsAggregate()) return;{self.mutex.lockUncancelable(self.io);defer self.mutex.unlock(self.io);@@ -221,19 +222,20 @@ pub const Telemetry = struct {/// _fleet_signal so the worker counts every client identically. signal is a/// static literal; the rest are duped/truncated like scoreEvent.pub fn fleetEvent(self: *Telemetry, signal: []const u8, niche: []const u8, prompt_sha: []const u8, parent_sha: []const u8, provider_class: []const u8, eval_set_hash: []const u8, n_elites: i64, prompt_text: []const u8) void {- if (!self.on() or !root.g_fleet) return;+ if (!self.on() or !root.g_fleet or !learning_privacy.allowsAggregate()) return;+ const admitted_text = learning_privacy.templateTextForUpload(self.io, prompt_text);// Review F6: never ship a truncated genome — skip the propose instead// (the fingerprint the scores reference stays computed over the full// text; only the genome-send is dropped).- if (std.mem.eql(u8, signal, "propose") and prompt_text.len > max_propose_text) return;+ if (std.mem.eql(u8, signal, "propose") and admitted_text.len > max_propose_text) return;// Propose-site integrity (issue #168 Gap 3, debug builds only): the// genome text must hash to the fingerprint it claims — a promoted// cell would otherwise serve text that never earned its scores. This// asserts on exactly what will be sent: oversized proposes returned// above, so the utf8Prefix cap below can no longer truncate a genome.// The backend independently recomputes and rejects mismatches.- if (builtin.mode == .Debug and std.mem.eql(u8, signal, "propose") and prompt_text.len > 0 and prompt_sha.len > 0) {- const fp = scoring.promptFingerprint(prompt_text);+ if (builtin.mode == .Debug and std.mem.eql(u8, signal, "propose") and admitted_text.len > 0 and prompt_sha.len > 0) {+ const fp = scoring.promptFingerprint(admitted_text);std.debug.assert(std.mem.eql(u8, &fp, prompt_sha));}{@@ -247,7 +249,7 @@ pub const Telemetry = struct {self.gpa.dupe(u8, std.fmt.bufPrint(&pbuf, "{s}\t{s}", .{ provider_class, eval_set_hash }) catch "") catch ""else"";- const dtext = if (prompt_text.len > 0) self.gpa.dupe(u8, utf8Prefix(prompt_text, max_propose_text)) catch "" else "";+ const dtext = if (admitted_text.len > 0) self.gpa.dupe(u8, utf8Prefix(admitted_text, max_propose_text)) catch "" else "";self.push(.{ .t_ms = self.elapsedMsLocked(), .body = "fleet", .kind = signal, .detail = ddet, .extra = dnic, .run_id = dpar, .prov = provdup, .tasks = n_elites, .text = dtext });}self.maybeFlushEvents();@@ -257,7 +259,7 @@ pub const Telemetry = struct {/// sequence — the process-mining signal behind "which tool combinations/// work". Lands as a generic body="run" record (attrs JSON) server-side.pub fn runEvent(self: *Telemetry, sha: []const u8, variant: bool, ok: bool, ms: i64, tools: []const u8) void {- if (!self.on()) return;+ if (!self.on() or !learning_privacy.allowsAggregate()) return;{self.mutex.lockUncancelable(self.io);defer self.mutex.unlock(self.io);diff --git a/src/telemetry_net.zig b/src/telemetry_net.zigindex db9c780a..992cad97 100644--- a/src/telemetry_net.zig+++ b/src/telemetry_net.zig@@ -32,6 +32,36 @@ pub fn otlpLogsUrl(gpa: Allocator, endpoint: []const u8) !?[]u8 {return try std.fmt.allocPrint(gpa, "{s}/v1/logs{s}", .{ base, query });}+/// Observable, bounded variant of Telemetry.sendBatchWithDeadline for+/// explicit commands that must tell the caller whether the collector accepted+/// the payload. Ordinary session telemetry remains best-effort and silent.+pub fn postOtlpWithDeadline(+ io: Io,+ client: *std.http.Client,+ url: []const u8,+ payload: []const u8,+ auth_key: []const u8,+ deadline: Io.Duration,+) bool {+ const Done = union(enum) { posted: bool, deadline: void };+ var done_buf: [2]Done = undefined;+ var sel: Io.Select(Done) = .init(io, &done_buf);+ sel.concurrent(.deadline, Telemetry.flushDeadline, .{ io, deadline }) catch return false;+ sel.concurrent(.posted, Telemetry.postOtlp, .{ client, url, payload, auth_key }) catch {+ sel.cancelDiscard();+ return false;+ };+ const first = sel.await() catch {+ sel.cancelDiscard();+ return false;+ };+ sel.cancelDiscard();+ return switch (first) {+ .posted => |accepted| accepted,+ .deadline => false,+ };+}+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);diff --git a/src/telemetry_tests.zig b/src/telemetry_tests.zigindex 71a1397f..8b440a5b 100644--- a/src/telemetry_tests.zig+++ b/src/telemetry_tests.zig@@ -7,6 +7,9 @@ const Io = std.Io;const telemetry = @import("telemetry.zig");const Telemetry = telemetry.Telemetry;const Event = Telemetry.Event;+const learning_privacy = @import("learning_privacy.zig");+const main_mod = @import("main.zig");+const scoring = @import("scoring.zig");test "telemetry dupDetail never yields invalid UTF-8" {var t: Telemetry = .{@@ -96,3 +99,52 @@ test "telemetry writeOtlp stamps run records with run_id (issue #168 Gap 6)" {try std.testing.expect(std.mem.indexOf(u8, out, "\"cafef00dcafef00d\"") != null);try std.testing.expect(std.mem.indexOf(u8, out, "\"read,edit\"") != null); // tools}++test "learning privacy gates fleet metadata, scores, and exact template text" {+ const io = std.testing.io;+ main_mod.g_fleet = true;+ var t: Telemetry = .{+ .io = io,+ .gpa = std.testing.allocator,+ .endpoint = "https://collector.invalid/v1/logs",+ .install_id = @splat('0'),+ .client_name = "harness",+ .sdk_install_id = "",+ .start = Io.Timestamp.now(io, .awake),+ .start_unix_ms = 0,+ };+ defer t.deinit();+ defer learning_privacy.setMode(io, .local);+ const prompt = "You are an exact private reviewer template.";+ const prompt_fp = scoring.promptFingerprint(prompt);++ learning_privacy.setMode(io, .local);+ t.fleetEvent("propose", "reviewer", &prompt_fp, "", "frontier", "", 0, prompt);+ t.scoreEvent("abcd", "", 1.0, "run", "sig", "");+ t.runEvent(&prompt_fp, true, true, 1, "read_file");+ t.countVariant();+ try std.testing.expectEqual(@as(usize, 0), t.events.items.len);+ try std.testing.expectEqual(@as(u64, 0), t.prompt_variants);++ learning_privacy.setMode(io, .aggregate);+ t.fleetEvent("propose", "reviewer", &prompt_fp, "", "frontier", "", 0, prompt);+ t.scoreEvent("abcd", "", 1.0, "run", "sig", "");+ t.runEvent(&prompt_fp, true, true, 1, "read_file");+ t.countVariant();+ try std.testing.expectEqual(@as(usize, 3), t.events.items.len);+ try std.testing.expectEqual(@as(u64, 1), t.prompt_variants);+ try std.testing.expectEqualStrings("", t.events.items[0].text);++ learning_privacy.setMode(io, .templates);+ t.fleetEvent("propose", "reviewer", &prompt_fp, "", "frontier", "", 0, prompt);+ try std.testing.expectEqualStrings("", t.events.items[3].text);+ try std.testing.expect(learning_privacy.approveTemplate(io, prompt));+ t.fleetEvent("propose", "reviewer", &prompt_fp, "", "frontier", "", 0, prompt);+ try std.testing.expectEqualStrings(prompt, t.events.items[4].text);++ const canary = "OPENAI_API_KEY=sk-proj-test-only";+ const canary_fp = scoring.promptFingerprint(canary);+ try std.testing.expect(!learning_privacy.approveTemplate(io, canary));+ t.fleetEvent("propose", "reviewer", &canary_fp, "", "frontier", "", 0, canary);+ try std.testing.expectEqualStrings("", t.events.items[5].text);+}diff --git a/tests/learn_e2e.py b/tests/learn_e2e.pyindex acb8ad46..f159fe17 100644--- a/tests/learn_e2e.py+++ b/tests/learn_e2e.py@@ -1,11 +1,11 @@#!/usr/bin/env python3-"""Local-only end-to-end regression test for `graff learn`.+"""Loopback-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.+The fixture uses deterministic local mutator/evaluator programs. Ordinary+telemetry is disabled; one explicit submit is captured by a loopback server."""from __future__ import annotations@@ -13,6 +13,8 @@ from __future__ import annotationsimport argparseimport copyimport hashlib+import hmac+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerimport jsonimport osfrom pathlib import Path@@ -22,6 +24,7 @@ import structimport subprocessimport sysimport tempfile+import threadingfrom typing import Any@@ -75,33 +78,52 @@ pathlib.Path(response_path).write_text(json.dumps(response, separators=(",", ":"EVALUATOR_BODY = r'''import hashlib, json, os, pathlib, sysassert 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,-}+if operation == "baseline":+ pairs = [{+ "case_id": pair["case_id"], "seed": pair["seed"],+ "pass": False, "score_ppm": 0, "cost_micros": 100,+ } for pair in request["pairs"]]+ response = {+ "schema": "codegraff.learn.primary-baseline.response.v1",+ "trial_id": request["trial_id"], "cohort_id": request["cohort_id"],+ "suite_sha256": request["suite_sha256"],+ "parent_id": request["parent"]["id"], "pairs": pairs,+ }+elif operation == "evaluate_primary":+ baseline = json.loads(pathlib.Path(request["baseline"]["path"]).read_text())+ pairs = [{+ "case_id": parent["case_id"], "seed": parent["seed"],+ "parent_pass": parent["pass"], "child_pass": True,+ "parent_score_ppm": parent["score_ppm"], "child_score_ppm": 1000000,+ "parent_cost_micros": parent["cost_micros"], "child_cost_micros": 90,+ } for parent in baseline["pairs"]]+ response = {+ "schema": "codegraff.learn.primary-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,+ }+elif operation == "evaluate":+ pairs = [{+ "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,+ } for pair in request["pairs"]]+ 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,+ }+else:+ raise AssertionError(f"unexpected operation {operation}")pathlib.Path(response_path).write_text(json.dumps(response, separators=(",", ":")) + "\n")'''@@ -168,8 +190,9 @@ def write_interpreter_shim(tools: Path, name: str, python: Path, body: str) -> tdef invoke(graff: Path, workspace: Path, env: dict[str, str], *args: str, succeeds: bool = True) -> subprocess.CompletedProcess[str]:+ privacy_args = ["--learning-privacy", "aggregate"] if (args and (args[0] == "submit" or "--submit" in args)) else []result = subprocess.run(- [str(graff), "learn", *args],+ [str(graff), *privacy_args, "learn", *args],cwd=workspace,env=env,text=True,@@ -192,6 +215,84 @@ def run_id_from(output: str) -> str:return match.group(1)+class GradeCapture(BaseHTTPRequestHandler):+ payloads: list[dict[str, Any]] = []++ def do_POST(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API+ assert self.path == "/v1/logs"+ length = int(self.headers["content-length"])+ self.payloads.append(json.loads(self.rfile.read(length)))+ self.send_response(202)+ self.send_header("content-type", "application/json")+ self.end_headers()+ self.wfile.write(b'{"ok":true,"queued":true}')++ def log_message(self, _format: str, *_args: Any) -> None:+ pass+++def verify_grade_submit(graff: Path, workspace: Path, env: dict[str, str], root: Path, run_id: str) -> None:+ """The explicit publish path sends signed aggregates and no genome text."""+ key = b"fixture-score-key"+ key_path = root / ".simple-harness" / "score.key"+ key_path.parent.mkdir(mode=0o700)+ write_private(key_path, key + b"\n")+ GradeCapture.payloads = []+ server = ThreadingHTTPServer(("127.0.0.1", 0), GradeCapture)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ submit_env = env.copy()+ submit_env.pop("GRAFF_NO_TELEMETRY", None)+ submit_env["HOME"] = str(root)+ submit_env["GRAFF_OTEL_ENDPOINT"] = f"http://127.0.0.1:{server.server_port}"+ submit_env.pop("GRAFF_SCORE_KEY_FILE", None)+ try:+ local = subprocess.run(+ [str(graff), "learn", "submit", run_id],+ cwd=workspace,+ env=submit_env,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ timeout=60,+ check=False,+ )+ assert local.returncode != 0 and "LearningPrivacyLocal" in local.stderr+ assert not GradeCapture.payloads, "local privacy must fail before network egress"+ fleet_off_env = {**submit_env, "GRAFF_FLEET": "off"}+ disabled = invoke(graff, workspace, fleet_off_env, "submit", run_id, succeeds=False)+ assert "TelemetryDisabled" in disabled.stderr+ assert not GradeCapture.payloads, "fleet master-off must block learning egress"+ output = invoke(graff, workspace, submit_env, "submit", run_id).stdout+ assert "submitted 2 signed aggregate grade(s)" in output+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)++ assert len(GradeCapture.payloads) == 1+ payload = GradeCapture.payloads[0]+ encoded = json.dumps(payload, separators=(",", ":"))+ assert "prompt_text" not in encoded and "Learned fixture policy" not in encoded+ resource = payload["resourceLogs"][0]+ resource_attrs = {item["key"]: next(iter(item["value"].values())) for item in resource["resource"]["attributes"]}+ assert resource_attrs["client.name"] == "harness-learn"+ records = resource["scopeLogs"][0]["logRecords"]+ assert len(records) == 2+ for record in records:+ assert record["body"]["stringValue"] == "score"+ attrs = {item["key"]: next(iter(item["value"].values())) for item in record["attributes"]}+ assert attrs["run_id"] == run_id and attrs["value"] == 1+ message = "\n".join(+ [+ "v2", attrs["prompt_sha"], attrs["parent_sha"], f'{attrs["value"]:.6f}',+ attrs["run_id"], attrs["judge_id"], attrs["artifact_sha"],+ attrs["eval_set_hash"], attrs["niche"], attrs["provider_class"],+ ]+ ).encode()+ assert attrs["sig"] == hmac.new(key, message, hashlib.sha256).hexdigest()++def status(graff: Path, workspace: Path, env: dict[str, str]) -> dict[str, Any]:return json.loads(invoke(graff, workspace, env, "status").stdout)@@ -297,6 +398,7 @@ def exercise(graff: Path, root: Path) -> None:learn_root = workspace / ".graff" / "learn"run_path = learn_root / "runs" / f"{manual_run}.json"original_record = json.loads(run_path.read_text())+ verify_grade_submit(graff, workspace, env, root, manual_run)# A forged mutation response that does not bind the selected child bytes# must not become promotable, even if all other run evidence is copied.@@ -348,12 +450,37 @@ def exercise(graff: Path, root: Path) -> None: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+ # This workspace already exposed its configured hidden suite. A later run+ # must fail before reusing it, even for an automatic promotion request.+ consumed = invoke(graff, workspace, env, "run", "--auto", succeeds=False)+ assert "HoldoutConsumed" in consumed.stderr+ assert status(graff, workspace, env)["generation"] == 2++ # Automatic promotion remains covered with a fresh, independently pinned+ # hidden suite in a separate learning store.+ automatic_workspace = root / "workspace-auto"+ automatic_workspace.mkdir(mode=0o700)+ automatic_holdout = tools / "holdout-suite-auto.json"+ automatic_manifest = copy.deepcopy(holdout_manifest)+ automatic_manifest["suite_id"] = "fixture-holdout-auto"+ write_private(automatic_holdout, json_bytes(automatic_manifest))+ automatic_config = copy.deepcopy(config)+ automatic_config["holdout_suite"] = {+ "path": str(automatic_holdout.resolve()),+ "sha256": raw_sha256(automatic_holdout),+ }+ automatic_config_path = root / "config-auto.json"+ write_private(automatic_config_path, json_bytes(automatic_config))+ invoke(+ graff, automatic_workspace, env, "init",+ "--parent", str(parent.resolve()), "--config", str(automatic_config_path.resolve()),+ )+ automatic_output = invoke(graff, automatic_workspace, env, "run", "--auto").stdoutassert run_id_from(automatic_output)- automatic = status(graff, workspace, env)- assert automatic["generation"] == 3+ automatic = status(graff, automatic_workspace, env)+ assert automatic["generation"] == 1assert automatic["active_genome_id"] != initial_genome- verified = invoke(graff, workspace, env, "verify")+ verified = invoke(graff, automatic_workspace, env, "verify")assert json.loads(verified.stdout)["integrity"] == "ok"exercise_identical_parent(graff, root, evaluator_program, holdout_suite, evaluation_suite, parent, env)diff --git a/tests/learn_graff_adapters.py b/tests/learn_graff_adapters.pynew file mode 100755index 00000000..4ff5e811--- /dev/null+++ b/tests/learn_graff_adapters.py@@ -0,0 +1,308 @@+#!/usr/bin/env python3+"""Offline protocol tests for the pinned model-backed learning adapters."""++from __future__ import annotations++import hashlib+import json+from pathlib import Path+import runpy+import subprocess+import sys+import tempfile+++ROOT = Path(__file__).resolve().parents[1]+MUTATOR = ROOT / "examples" / "learn_graff_mutator.py"+EVALUATOR = ROOT / "examples" / "learn_graff_evaluator.py"+ARMS = ROOT / "examples" / "learn_graff_arms.json"+SETTINGS = ROOT / "examples" / "learn_graff_evaluator.json"+PREPARE = ROOT / "examples" / "prepare_graff_tournament.py"++FAKE_GRAFF = r'''#!/usr/bin/env python3+import json, pathlib, sys+args = sys.argv[1:]+system = args[args.index("--system-prompt") + 1]+turns = 0+for raw in sys.stdin:+ value = json.loads(raw)+ kind = value.get("type")+ if kind == "set_model":+ event = {"type":"model","ok":True,"provider":value["provider"],"model":value["model"]}+ elif kind == "set_effort":+ event = {"type":"effort","ok":True,"level":value["level"],"applies":True}+ elif kind == "user":+ if "concise clause" in system:+ turns += 1+ text = "invalid first attempt" if turns == 1 else json.dumps({+ "clause":"Added focused rule.",+ }, separators=(",", ":"))+ event = {"type":"turn","text":text,"complete":True,"cost_usd":0.001}+ else:+ marker = pathlib.Path(sys.argv[0]).parent / ".eval-retry-once"+ if not marker.exists():+ marker.write_text("retry")+ raise SystemExit(0)+ print(json.dumps({"type":"tool_call","name":"read_file","input":{}}), flush=True)+ event = {"type":"turn","text":"42","complete":True,"cost_usd":0.002}+ else:+ event = {"type":"error","message":"unexpected request"}+ print(json.dumps(event), flush=True)+'''+++def write_json(path: Path, value: object) -> None:+ path.write_text(json.dumps(value, separators=(",", ":")) + "\n", encoding="utf-8")+++def assert_patch_boundaries() -> None:+ apply_patch = runpy.run_path(str(MUTATOR))["apply_patch"]+ parent = "Target SAFE paragraph.\n\nInvariant.\n"+ target = "Target SAFE paragraph."+ protected = ["SAFE", "Invariant."]++ valid = json.dumps({"clause": "Added rule."})+ child, violations = apply_patch(valid, parent, target, protected, 128, 4096)+ assert child == "Target SAFE paragraph. Added rule.\n\nInvariant.\n"+ assert not violations++ replacement_parent = "Target paragraph.\n\nProtected invariant.\n"+ replacement, violations = apply_patch(+ json.dumps({"clause": "Read the exact span once."}),+ replacement_parent,+ "Target paragraph.",+ ["Protected invariant."],+ 128,+ 4096,+ "replace",+ )+ assert replacement == "Read the exact span once.\n\nProtected invariant.\n"+ assert not violations++ cases = (+ (json.dumps({"clause": "Added rule.", "extra": True}), 128, 4096,+ "only clause"),+ (json.dumps({"clause": "SAFE"}), 128, 4096,+ "protected substrings"),+ (json.dumps({"clause": "x" * 200}), 64, 4096,+ "changed more than"),+ (valid, 128, len(parent.encode("utf-8")), "merged prompt exceeded"),+ )+ for raw, changed_limit, total_limit, expected in cases:+ child, violations = apply_patch(+ raw, parent, target, protected, changed_limit, total_limit,+ )+ assert child is None+ assert any(expected in violation for violation in violations)+++def run() -> None:+ assert_patch_boundaries()+ with tempfile.TemporaryDirectory(prefix="learn-adapters-") as raw:+ root = Path(raw)+ fake = root / "graff"+ fake.write_text(FAKE_GRAFF, encoding="utf-8")+ fake.chmod(0o700)++ subprocess.run([sys.executable, str(MUTATOR), "--validate", str(ARMS)], check=True)+ subprocess.run([sys.executable, str(EVALUATOR), "--validate", str(SETTINGS)], check=True)++ # Keep this protocol fixture small while exercising the same invariant+ # preservation contract as the production arm configuration.+ test_arms = root / "arms.json"+ arms = json.loads(ARMS.read_text(encoding="utf-8"))+ arms["protected_substrings"] = ["Target paragraph.", "Protected invariant."]+ arms["targets"] = {"root_workflow": "Target paragraph."}+ for arm in arms["arms"]:+ arm["placement"] = "append"+ arms["maximum_changed_bytes"] = 128+ write_json(test_arms, arms)++ parent = root / "parent.genome"+ child = root / "child.genome"+ parent.write_text("Target paragraph.\n\nProtected invariant.\n", encoding="utf-8")+ mutation_request = root / "mutation-request.json"+ mutation_response = root / "mutation-response.json"+ parent_id = "a" * 64+ write_json(mutation_request, {+ "schema": "codegraff.learn.mutation.request.v1",+ "trial_id": "b" * 64,+ "candidate_index": 0,+ "seed": "c" * 64,+ "parent": {"id": parent_id, "path": str(parent)},+ "child_path": str(child),+ "maximum_bytes": 4096,+ "instruction": "improve tool economy",+ })+ subprocess.run([+ sys.executable, str(MUTATOR), str(test_arms), str(fake), "mutate",+ str(mutation_request), str(mutation_response),+ ], cwd=root, check=True)+ mutation = json.loads(mutation_response.read_text())+ assert child.read_text() == "Target paragraph. Added focused rule.\n\nProtected invariant.\n"+ assert mutation["description"] == "sol-semantic-boundaries (gpt-5.6-sol/high)"+ assert mutation["child_sha256"] == hashlib.sha256(child.read_bytes()).hexdigest()++ fixed_arms_path = root / "fixed-arms.json"+ fixed_arms = json.loads(test_arms.read_text(encoding="utf-8"))+ fixed_arms["protected_substrings"] = ["Protected invariant."]+ fixed_arms["arms"][1]["placement"] = "replace"+ fixed_arms["arms"][1]["fixed_clause"] = "Read the exact span once."+ write_json(fixed_arms_path, fixed_arms)+ fixed_child = root / "fixed-child.genome"+ fixed_request = root / "fixed-request.json"+ fixed_response = root / "fixed-response.json"+ fixed_request_value = json.loads(mutation_request.read_text(encoding="utf-8"))+ fixed_request_value["candidate_index"] = 1+ fixed_request_value["child_path"] = str(fixed_child)+ write_json(fixed_request, fixed_request_value)+ subprocess.run([+ sys.executable, str(MUTATOR), str(fixed_arms_path), str(root / "missing-graff"),+ "mutate", str(fixed_request), str(fixed_response),+ ], cwd=root, check=True)+ assert fixed_child.read_text() == "Read the exact span once.\n\nProtected invariant.\n"+ assert "frozen confirmation" in json.loads(fixed_response.read_text())["description"]++ invalid_fake = root / "graff-invalid"+ invalid_fake.write_text(FAKE_GRAFF.replace(+ 'text = "invalid first attempt" if turns == 1 else json.dumps({\n'+ ' "clause":"Added focused rule.",\n'+ ' }, separators=(",", ":"))',+ 'text = json.dumps({"clause":"Target paragraph."})',+ ), encoding="utf-8")+ invalid_fake.chmod(0o700)+ fallback_response = root / "fallback-response.json"+ child.unlink()+ subprocess.run([+ sys.executable, str(MUTATOR), str(test_arms), str(invalid_fake), "mutate",+ str(mutation_request), str(fallback_response),+ ], cwd=root, check=True)+ fallback = json.loads(fallback_response.read_text())+ assert child.read_bytes() == parent.read_bytes()+ assert fallback["description"].endswith("validation fallback: parent")++ prepared = root / "prepared"+ output = subprocess.run([+ sys.executable, str(PREPARE), str(prepared), "--repo", str(ROOT),+ "--graff", str(fake),+ ], check=True, text=True, capture_output=True)+ preparation = json.loads(output.stdout)+ primary = json.loads((prepared / "primary.json").read_text(encoding="utf-8"))+ holdout = json.loads((prepared / "fresh-holdout.json").read_text(encoding="utf-8"))+ config = json.loads((prepared / "config.json").read_text(encoding="utf-8"))+ assert preparation["primary_cases"] == len(primary["cases"]) == 60+ assert preparation["holdout_cases"] == len(holdout["cases"]) == 40+ assert len({case["id"] for case in primary["cases"]}) == 60+ assert len({case["id"] for case in holdout["cases"]}) == 40+ primary_ids = [case["id"] for case in primary["cases"]]+ holdout_ids = [case["id"] for case in holdout["cases"]]+ assert [sum(item.startswith(prefix) for item in primary_ids) for prefix in (+ "semantic-", "edit-", "dependency-", "economy-",+ )] == [10, 30, 10, 10]+ assert [sum(item.startswith(prefix) for item in holdout_ids) for prefix in (+ "fresh-sem-", "fresh-edit-", "fresh-dep-", "fresh-econ-",+ )] == [7, 19, 7, 7]+ configured_target = json.loads(ARMS.read_text(encoding="utf-8"))["targets"]["root_workflow"]+ prepared_parent = (prepared / "parent.md").read_text(encoding="utf-8")+ assert prepared_parent.count(configured_target) == 1+ assert config["gate"]["default_candidates"] == 4+ assert config["gate"]["promotion_mode"] == "economy"+ assert config["gate"]["require_all_candidates"] is True+ assert config["auto"] == {"enabled": False}++ suite = root / "suite.json"+ write_json(suite, {+ "schema": "codegraff.learn.suite.v1",+ "suite_id": "offline",+ "cases": [{+ "id": "answer",+ "payload": {"task": "Reply 42", "check": {"exact": "42"}},+ }],+ })+ evaluation_request = root / "evaluation-request.json"+ evaluation_response = root / "evaluation-response.json"+ write_json(evaluation_request, {+ "schema": "codegraff.learn.evaluation.request.v1",+ "trial_id": "b" * 64,+ "candidate_index": 0,+ "cohort_id": "d" * 64,+ "suite_sha256": hashlib.sha256(suite.read_bytes()).hexdigest(),+ "suite_path": str(suite),+ "parent": {"id": parent_id, "path": str(parent)},+ "child": {"id": "e" * 64, "path": str(child)},+ "repetitions": 1,+ "pairs": [{"case_id": "answer", "seed": "f" * 64, "critical": False}],+ })+ subprocess.run([+ sys.executable, str(EVALUATOR), str(SETTINGS), str(fake), "evaluate",+ str(evaluation_request), str(evaluation_response),+ ], cwd=root, check=True)+ result = json.loads(evaluation_response.read_text())["pairs"][0]+ assert result["parent_pass"] and result["child_pass"]+ assert result["tool_calls_measured"] is True+ assert result["latency_measured"] is True+ assert result["parent_tool_calls"] == result["child_tool_calls"] == 1+ assert result["parent_cost_micros"] == result["child_cost_micros"] == 2000++ baseline_request = root / "baseline-request.json"+ baseline_response = root / "baseline-response.json"+ write_json(baseline_request, {+ "schema": "codegraff.learn.primary-baseline.request.v1",+ "trial_id": "b" * 64,+ "cohort_id": "d" * 64,+ "suite_sha256": hashlib.sha256(suite.read_bytes()).hexdigest(),+ "suite_path": str(suite),+ "parent": {"id": parent_id, "path": str(parent)},+ "repetitions": 1,+ "pairs": [{"case_id": "answer", "seed": "f" * 64, "critical": False}],+ })+ subprocess.run([+ sys.executable, str(EVALUATOR), str(SETTINGS), str(fake), "baseline",+ str(baseline_request), str(baseline_response),+ ], cwd=root, check=True)+ baseline = json.loads(baseline_response.read_text())+ assert baseline["schema"] == "codegraff.learn.primary-baseline.response.v1"+ assert baseline["parent_id"] == parent_id+ assert baseline["pairs"] == [{+ "case_id": "answer", "seed": "f" * 64,+ "pass": True, "score_ppm": 1_000_000,+ "cost_micros": 2000, "latency_ms": baseline["pairs"][0]["latency_ms"],+ "latency_measured": True, "tool_calls_measured": True, "tool_calls": 1,+ }]++ primary_request = root / "primary-request.json"+ primary_response = root / "primary-response.json"+ write_json(primary_request, {+ "schema": "codegraff.learn.primary-evaluation.request.v1",+ "trial_id": "b" * 64,+ "candidate_index": 0,+ "cohort_id": "d" * 64,+ "suite_sha256": hashlib.sha256(suite.read_bytes()).hexdigest(),+ "suite_path": str(suite),+ "parent_id": parent_id,+ "baseline": {+ "request_evidence_id": "1" * 64,+ "response_evidence_id": "2" * 64,+ "path": str(baseline_response),+ },+ "child": {"id": "e" * 64, "path": str(child)},+ "repetitions": 1,+ "pairs": [{"case_id": "answer", "seed": "f" * 64, "critical": False}],+ })+ subprocess.run([+ sys.executable, str(EVALUATOR), str(SETTINGS), str(fake), "evaluate_primary",+ str(primary_request), str(primary_response),+ ], cwd=root, check=True)+ primary_result = json.loads(primary_response.read_text())["pairs"][0]+ baseline_result = baseline["pairs"][0]+ assert primary_result["parent_pass"] == baseline_result["pass"]+ assert primary_result["parent_score_ppm"] == baseline_result["score_ppm"]+ assert primary_result["parent_cost_micros"] == baseline_result["cost_micros"]+ assert primary_result["parent_latency_ms"] == baseline_result["latency_ms"]+ assert primary_result["parent_tool_calls"] == baseline_result["tool_calls"]+ assert primary_result["child_pass"] is True+++if __name__ == "__main__":+ run()+ print("Graff learning adapter tests passed")diff --git a/tests/learn_graff_evaluator_retries.py b/tests/learn_graff_evaluator_retries.pynew file mode 100644index 00000000..47899dc6--- /dev/null+++ b/tests/learn_graff_evaluator_retries.py@@ -0,0 +1,190 @@+#!/usr/bin/env python3+"""Focused retry-accounting tests for the model-backed Graff evaluator."""++from __future__ import annotations++import importlib.util+import io+import json+import os+from pathlib import Path+import tempfile+import unittest+from unittest import mock+++REPO = Path(__file__).resolve().parents[1]+SPEC = importlib.util.spec_from_file_location(+ "learn_graff_evaluator", REPO / "examples" / "learn_graff_evaluator.py"+)+assert SPEC is not None and SPEC.loader is not None+EVALUATOR = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(EVALUATOR)+++class RetryAccountingTests(unittest.TestCase):+ def test_progress_is_atomic_request_bound_pair_prefix(self) -> None:+ with tempfile.TemporaryDirectory(prefix="learn-progress-test-") as raw_temp:+ temp = Path(raw_temp)+ request_path = temp / "request.json"+ progress_path = temp / "progress.json"+ pairs = [+ {"case_id": "one", "seed": "a"},+ {"case_id": "two", "seed": "b"},+ ]+ request_path.write_text(json.dumps({"pairs": pairs}), encoding="utf-8")+ request_sha256, empty = EVALUATOR.load_progress(+ progress_path, request_path, pairs,+ )+ self.assertEqual(empty, [])+ completed = [{"case_id": "one", "seed": "a", "child_pass": True}]+ EVALUATOR.save_progress(progress_path, request_sha256, completed)+ loaded_sha256, loaded = EVALUATOR.load_progress(+ progress_path, request_path, pairs,+ )+ self.assertEqual(loaded_sha256, request_sha256)+ self.assertEqual(loaded, completed)+ self.assertFalse((temp / "progress.json.tmp").exists())++ request_path.write_text(json.dumps({"pairs": list(reversed(pairs))}), encoding="utf-8")+ with mock.patch.object(EVALUATOR.sys, "stderr", io.StringIO()), \+ self.assertRaises(SystemExit):+ EVALUATOR.load_progress(progress_path, request_path, list(reversed(pairs)))++ def test_terminal_error_carries_observed_resources(self) -> None:+ events = [+ {"type": "model", "provider": "codex", "model": "test-model"},+ {"type": "effort", "level": "low", "applies": True},+ *({"type": "tool_call"} for _ in range(4)),+ {"type": "error", "message": "retry me", "cost_usd": 0.000020},+ ]++ class FakeProcess:+ stdin = io.StringIO()+ stdout = iter(json.dumps(event) + "\n" for event in events)+ stderr = io.StringIO()++ def wait(self, timeout=None):+ return 0++ def kill(self):+ return None++ class FakeTimer:+ def __init__(self, *args, **kwargs):+ pass++ def start(self):+ pass++ def cancel(self):+ pass++ settings = {+ "provider": "codex", "model": "test-model", "effort": "low",+ "max_model_calls": 8, "max_tool_calls": 8, "task_timeout_seconds": 10,+ }+ with mock.patch.object(EVALUATOR.subprocess, "Popen", return_value=FakeProcess()), \+ mock.patch.object(EVALUATOR.threading, "Timer", FakeTimer), \+ mock.patch.object(EVALUATOR.time, "monotonic", side_effect=(1.0, 1.03)):+ with self.assertRaises(EVALUATOR.EvaluationAttemptError) as raised:+ EVALUATOR.run_variant(+ Path("/unused-graff"), settings, "prompt", {"task": "task"}, Path.cwd()+ )+ self.assertEqual(raised.exception.tool_calls, 4)+ self.assertEqual(raised.exception.latency_ms, 30)+ self.assertEqual(raised.exception.cost_micros, 20)++ def test_failed_attempt_resources_are_added_to_success(self) -> None:+ with tempfile.TemporaryDirectory(prefix="learn-retry-test-") as raw_temp:+ temp = Path(raw_temp)+ settings_path = temp / "settings.json"+ suite_path = temp / "suite.json"+ request_path = temp / "request.json"+ response_path = temp / "response.json"+ parent_path = temp / "parent.md"+ child_path = temp / "child.md"+ settings_path.write_text(json.dumps({+ "schema": "codegraff.learn.graff-evaluator.v1",+ "provider": "codex",+ "model": "test-model",+ "effort": "low",+ "max_model_calls": 8,+ "max_tool_calls": 8,+ "max_attempts": 2,+ "task_timeout_seconds": 10,+ }), encoding="utf-8")+ suite_path.write_text(json.dumps({+ "schema": "codegraff.learn.suite.v1",+ "cases": [{+ "id": "retry-case",+ "payload": {+ "task": "return ok",+ "setup_files": {"fixture.txt": "clean"},+ "check": {"exact": "ok"},+ },+ }],+ }), encoding="utf-8")+ parent_path.write_text("parent", encoding="utf-8")+ child_path.write_text("child", encoding="utf-8")+ request_path.write_text(json.dumps({+ "schema": EVALUATOR.REQUEST_SCHEMA,+ "trial_id": "trial",+ "candidate_index": 0,+ "cohort_id": "cohort",+ "suite_path": str(suite_path),+ "suite_sha256": "suite",+ "parent": {"id": "parent", "path": str(parent_path)},+ "child": {"id": "child", "path": str(child_path)},+ "pairs": [{"case_id": "retry-case", "seed": "0"}],+ }), encoding="utf-8")++ child_attempts = 0+ child_scratch: list[Path] = []++ def fake_run_variant(graff, settings, prompt, case, cwd):+ nonlocal child_attempts+ self.assertEqual((cwd / "fixture.txt").read_text(encoding="utf-8"), "clean")+ if prompt == "parent":+ return {+ "pass": True, "score_ppm": 1_000_000,+ "cost_micros": 11, "latency_ms": 10, "tool_calls": 5,+ }+ child_attempts += 1+ child_scratch.append(cwd)+ self.assertFalse((cwd / "failed-attempt.txt").exists())+ if child_attempts == 1:+ (cwd / "failed-attempt.txt").write_text("dirty", encoding="utf-8")+ raise EVALUATOR.EvaluationAttemptError(+ "failed after tools", latency_ms=30, tool_calls=4, cost_micros=20+ )+ return {+ "pass": True, "score_ppm": 1_000_000,+ "cost_micros": 10, "latency_ms": 15, "tool_calls": 2,+ }++ original_cwd = Path.cwd()+ os.chdir(temp)+ try:+ with mock.patch.object(EVALUATOR, "executable_snapshot", side_effect=lambda path: path), \+ mock.patch.object(EVALUATOR, "run_variant", side_effect=fake_run_variant):+ EVALUATOR.evaluate(+ settings_path, temp / "unused-graff", request_path, response_path+ )+ finally:+ os.chdir(original_cwd)++ pair = json.loads(response_path.read_text(encoding="utf-8"))["pairs"][0]+ self.assertEqual(child_attempts, 2)+ self.assertEqual(len(set(child_scratch)), 2)+ self.assertEqual(pair["child_tool_calls"], 6)+ self.assertEqual(pair["child_latency_ms"], 45)+ self.assertEqual(pair["child_cost_micros"], 30)+ self.assertGreater(pair["child_tool_calls"], pair["parent_tool_calls"])+ self.assertGreater(pair["child_latency_ms"], pair["parent_latency_ms"])+ self.assertGreater(pair["child_cost_micros"], pair["parent_cost_micros"])+ self.assertNotIn("attempt_count", pair)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/learn_tournament_e2e.py b/tests/learn_tournament_e2e.pynew file mode 100755index 00000000..344f1af8--- /dev/null+++ b/tests/learn_tournament_e2e.py@@ -0,0 +1,338 @@+#!/usr/bin/env python3+"""Four-arm concurrency, winner-only holdout, and five-grade regression."""++from __future__ import annotations++import argparse+from collections import Counter+import copy+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import shutil+import sys+import tempfile+import threading+import time++from learn_e2e import (+ GradeCapture,+ invoke,+ json_bytes,+ raw_sha256,+ run_id_from,+ status,+ write_forged_object,+ write_interpreter_shim,+ write_posix_shebang,+ write_private,+)+++MUTATOR = r'''import hashlib, json, os, pathlib, sys, time+operation, request_path, response_path = sys.argv[1:4]+assert operation == "mutate"+request = json.loads(pathlib.Path(request_path).read_text())+index = request["candidate_index"]+barrier = pathlib.Path(os.environ["TOURNAMENT_BARRIER"])+(barrier / f"mutation-{index}").write_text("started")+deadline = time.monotonic() + 10+while len(list(barrier.glob("mutation-*"))) != 4:+ assert time.monotonic() < deadline, "mutations did not run concurrently"+ time.sleep(0.01)+parent = pathlib.Path(request["parent"]["path"]).read_text()+child = parent.rstrip() + f"\n\nTournament variant {index}.\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": index,+ "parent_id": request["parent"]["id"],+ "child_path": request["child_path"],+ "child_sha256": hashlib.sha256(child_bytes).hexdigest(),+ "description": f"fixture arm {index}",+}+pathlib.Path(response_path).write_text(json.dumps(response, separators=(",", ":")) + "\n")+'''+++EVALUATOR = r'''import hashlib, json, os, pathlib, sys, time+operation, request_path, response_path = sys.argv[1:4]+request = json.loads(pathlib.Path(request_path).read_text())+suite_bytes = pathlib.Path(request["suite_path"]).read_bytes()+assert hashlib.sha256(suite_bytes).hexdigest() == request["suite_sha256"]+suite = json.loads(suite_bytes)+barrier = pathlib.Path(os.environ["TOURNAMENT_BARRIER"])++if operation == "baseline":+ assert suite["suite_id"] == "tournament-primary"+ (barrier / "baseline-once").open("x").write("parent")+ pairs = [{+ "case_id": pair["case_id"], "seed": pair["seed"],+ "pass": False, "score_ppm": 0, "cost_micros": 100,+ "tool_calls_measured": True, "tool_calls": 10,+ } for pair in request["pairs"]]+ response = {+ "schema": "codegraff.learn.primary-baseline.response.v1",+ "trial_id": request["trial_id"], "cohort_id": request["cohort_id"],+ "suite_sha256": request["suite_sha256"],+ "parent_id": request["parent"]["id"], "pairs": pairs,+ }+ (barrier / "baseline-done").write_text("done")+elif operation == "evaluate_primary":+ assert suite["suite_id"] == "tournament-primary"+ assert (barrier / "baseline-done").is_file()+ index = request["candidate_index"]+ baseline = json.loads(pathlib.Path(request["baseline"]["path"]).read_text())+ (barrier / f"primary-start-{index}").write_text("started")+ deadline = time.monotonic() + 10+ while len(list(barrier.glob("primary-start-*"))) != 4:+ assert time.monotonic() < deadline, "primary evaluations did not run concurrently"+ time.sleep(0.01)+ retry_marker = barrier / f"primary-retried-{index}"+ if index == 0 and not retry_marker.exists():+ retry_marker.write_text("retry")+ raise SystemExit(17)+ calls = [9, 7, 3, 5][index]+ assert [(p["case_id"], p["seed"]) for p in baseline["pairs"]] == [+ (p["case_id"], p["seed"]) for p in request["pairs"]+ ]+ pairs = [{+ "case_id": parent["case_id"], "seed": parent["seed"],+ "parent_pass": parent["pass"], "child_pass": True,+ "parent_score_ppm": parent["score_ppm"], "child_score_ppm": 1000000,+ "parent_cost_micros": parent["cost_micros"], "child_cost_micros": calls,+ "tool_calls_measured": parent["tool_calls_measured"],+ "parent_tool_calls": parent["tool_calls"], "child_tool_calls": calls,+ } for parent in baseline["pairs"]]+ response = {+ "schema": "codegraff.learn.primary-evaluation.response.v1",+ "trial_id": request["trial_id"], "candidate_index": index,+ "cohort_id": request["cohort_id"], "suite_sha256": request["suite_sha256"],+ "parent_id": request["parent_id"], "child_id": request["child"]["id"],+ "pairs": pairs,+ }+ (barrier / f"primary-done-{index}").write_text("done")+elif operation == "evaluate":+ assert suite["suite_id"] == "tournament-fresh-holdout"+ index = request["candidate_index"]+ assert len(list(barrier.glob("primary-done-*"))) == 4, "holdout started before the primary barrier"+ (barrier / "holdout-once").open("x").write(str(index))+ calls = [9, 7, 3, 5][index]+ pairs = [{+ "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": calls,+ "tool_calls_measured": True, "parent_tool_calls": 10, "child_tool_calls": calls,+ } for pair in request["pairs"]]+ response = {+ "schema": "codegraff.learn.evaluation.response.v1",+ "trial_id": request["trial_id"], "candidate_index": index,+ "cohort_id": request["cohort_id"], "suite_sha256": request["suite_sha256"],+ "parent_id": request["parent"]["id"], "child_id": request["child"]["id"],+ "pairs": pairs,+ }+else:+ raise AssertionError(f"unexpected operation {operation}")+pathlib.Path(response_path).write_text(json.dumps(response, separators=(",", ":")) + "\n")+'''+++def attrs(record: dict) -> dict:+ return {item["key"]: next(iter(item["value"].values())) for item in record["attributes"]}+++def exercise(graff: Path, root: Path) -> None:+ workspace = root / "workspace"+ tools = root / "tools"+ barrier = root / "barrier"+ for path in (workspace, tools, barrier):+ path.mkdir(mode=0o700)++ python = Path(sys.executable).resolve()+ if sys.platform == "win32":+ mutator, _ = write_interpreter_shim(tools, "tournament-mutator", python, MUTATOR)+ else:+ mutator_path = tools / "tournament-mutator.py"+ write_posix_shebang(mutator_path, python, MUTATOR)+ mutator = {"program": str(mutator_path.resolve()), "sha256": raw_sha256(mutator_path)}+ evaluator, _ = write_interpreter_shim(tools, "tournament-evaluator", python, EVALUATOR)+ mutator["pass_env"] = ["TOURNAMENT_BARRIER"]+ evaluator["pass_env"] = ["TOURNAMENT_BARRIER"]++ primary = tools / "primary.json"+ holdout = tools / "holdout.json"+ write_private(primary, json_bytes({+ "schema": "codegraff.learn.suite.v1",+ "suite_id": "tournament-primary",+ "cases": [{"id": f"primary-{index}"} for index in range(8)],+ }))+ write_private(holdout, json_bytes({+ "schema": "codegraff.learn.suite.v1",+ "suite_id": "tournament-fresh-holdout",+ "cases": [{"id": f"holdout-{index}"} for index in range(8)],+ }))+ parent = root / "parent.md"+ write_private(parent, b"Initial tournament policy.\n")+ config_path = root / "config.json"+ config = {+ "schema": "codegraff.learn.config.v1",+ "agent_name": "secret-internal-agent-name",+ "mutation_instruction": "produce one indexed tournament variant",+ "mutator": mutator,+ "evaluator": evaluator,+ "evaluation_suite": {"path": str(primary.resolve()), "sha256": raw_sha256(primary)},+ "holdout_suite": {"path": str(holdout.resolve()), "sha256": raw_sha256(holdout)},+ "gate": {+ "alpha_ppm": 50000,+ "minimum_delta_ppm": 100000,+ "minimum_pairs": 8,+ "require_all_candidates": True,+ "default_candidates": 4,+ "default_repetitions": 1,+ },+ "auto": {"enabled": False},+ "cohort": {+ "provider": "fixture", "model": "fixture", "task_family": "tournament",+ "adapter_version": "v2", "verifier_version": "v2",+ },+ }+ write_private(config_path, json_bytes(config))++ key_path = root / ".simple-harness" / "score.key"+ key_path.parent.mkdir(mode=0o700)+ write_private(key_path, b"fixture-score-key\n")+ env = os.environ.copy()+ env.update({+ "HOME": str(root),+ "GRAFF_BEHAVIOR_TRACE": "0",+ "TOURNAMENT_BARRIER": str(barrier),+ })+ env.pop("GRAFF_NO_TELEMETRY", None)++ GradeCapture.payloads = []+ server = ThreadingHTTPServer(("127.0.0.1", 0), GradeCapture)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ env["GRAFF_OTEL_ENDPOINT"] = f"http://127.0.0.1:{server.server_port}"+ try:+ invoke(graff, workspace, env, "init", "--parent", str(parent.resolve()), "--config", str(config_path.resolve()))+ output = invoke(graff, workspace, env, "run", "--candidates", "4", "--submit").stdout+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)++ run_id = run_id_from(output)+ record_path = workspace / ".graff" / "learn" / "runs" / f"{run_id}.json"+ record = json.loads(record_path.read_text())+ assert record["schema"] == "codegraff.learn.run.v3"+ assert record["primary_baseline"] is not None+ assert len(record["candidates"]) == 4+ assert (barrier / "primary-retried-0").is_file()+ assert sum(candidate["primary"] is not None for candidate in record["candidates"]) == 4+ assert sum(candidate["holdout"] is not None for candidate in record["candidates"]) == 1+ winner = next(candidate for candidate in record["candidates"] if candidate["holdout"] is not None)+ assert winner["primary"]["child_tool_calls"] == 24+ parent_projections = {+ (+ candidate["primary"]["parent_passes"],+ candidate["primary"]["parent_tool_calls"],+ candidate["primary"]["parent_cost_micros"],+ )+ for candidate in record["candidates"]+ }+ assert parent_projections == {(0, 80, 800)}+ assert winner["genome_id"] == record["primary_winner_genome_id"] == record["selected_genome_id"]+ assert "manual promotion:" in output+ assert status(graff, workspace, env)["generation"] == 0+ assert len(list(barrier.glob("mutation-*"))) == 4+ assert (barrier / "baseline-once").read_text() == "parent"+ assert len(list(barrier.glob("primary-done-*"))) == 4+ assert (barrier / "holdout-once").read_text() == "2"++ assert len(GradeCapture.payloads) == 1+ encoded = json.dumps(GradeCapture.payloads[0], separators=(",", ":"))+ assert "secret-internal-agent-name" not in encoded+ assert "Tournament variant" not in encoded and "prompt_text" not in encoded+ records = GradeCapture.payloads[0]["resourceLogs"][0]["scopeLogs"][0]["logRecords"]+ assert len(records) == 5+ stages = Counter(attrs(item)["judge_id"] for item in records)+ assert stages == {"learn-primary-v2": 4, "learn-holdout-v2": 1}+ hashes = Counter(attrs(item)["eval_set_hash"] for item in records)+ assert hashes == {raw_sha256(primary): 4, raw_sha256(holdout): 1}++ # Parent fields in every primary response are a cryptographic projection+ # of the one shared baseline. Re-addressing a forged response and run must+ # still fail verification before it can promote anything.+ learn_root = workspace / ".graff" / "learn"+ forged = copy.deepcopy(record)+ response_id = forged["candidates"][0]["primary"]["response_evidence_id"]+ response = json.loads((learn_root / "evidence" / f"{response_id}.json").read_text())+ response["pairs"][0]["parent_tool_calls"] += 1+ forged_response_id = write_forged_object(+ learn_root / "evidence", "codegraff-learn/evidence/v1", response,+ )+ forged["candidates"][0]["primary"]["response_evidence_id"] = forged_response_id+ forged_run_id = write_forged_object(learn_root / "runs", "codegraff-learn/run/v1", forged)+ rejected = invoke(graff, workspace, env, "promote", forged_run_id, succeeds=False)+ assert "BaselineProjectionMismatch" in rejected.stderr+ assert status(graff, workspace, env)["generation"] == 0++ # The untampered v3 evidence remains fully verifiable and promotable.+ invoke(graff, workspace, env, "promote", run_id)+ assert status(graff, workspace, env)["generation"] == 1+ assert json.loads(invoke(graff, workspace, env, "verify").stdout)["integrity"] == "ok"++ # A ranked but underpowered primary is persisted without exposing the+ # hidden suite at all.+ ineligible_workspace = root / "workspace-ineligible"+ ineligible_barrier = root / "barrier-ineligible"+ ineligible_workspace.mkdir(mode=0o700)+ ineligible_barrier.mkdir(mode=0o700)+ ineligible_config = copy.deepcopy(config)+ ineligible_config["gate"]["minimum_pairs"] = 9+ ineligible_config_path = root / "config-ineligible.json"+ write_private(ineligible_config_path, json_bytes(ineligible_config))+ ineligible_env = {**env, "TOURNAMENT_BARRIER": str(ineligible_barrier)}+ invoke(+ graff, ineligible_workspace, ineligible_env, "init",+ "--parent", str(parent.resolve()), "--config", str(ineligible_config_path.resolve()),+ )+ ineligible_output = invoke(graff, ineligible_workspace, ineligible_env, "run", "--candidates", "4").stdout+ ineligible_record = json.loads(+ ineligible_workspace.joinpath(+ ".graff", "learn", "runs", f"{run_id_from(ineligible_output)}.json",+ ).read_text()+ )+ assert ineligible_record["primary_winner_genome_id"] is not None+ assert ineligible_record["selected_genome_id"] is None+ assert all(candidate["holdout"] is None for candidate in ineligible_record["candidates"])+ assert not (ineligible_barrier / "holdout-once").exists()+++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")+ args = parser.parse_args()+ graff = args.graff.resolve()+ root = Path(tempfile.mkdtemp(prefix="codegraff-learn-tournament."))+ try:+ exercise(graff, root)+ except Exception:+ print(f"tournament E2E failed; fixture preserved at {root}", file=sys.stderr)+ raise+ if args.keep:+ print(f"tournament E2E passed; fixture preserved at {root}")+ else:+ shutil.rmtree(root)+ print("tournament E2E passed")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/privacy_efficacy.py b/tests/privacy_efficacy.pynew file mode 100644index 00000000..312f515e--- /dev/null+++ b/tests/privacy_efficacy.py@@ -0,0 +1,127 @@+#!/usr/bin/env python3+"""Deterministic SDK egress checks for the learning-privacy contract."""++from __future__ import annotations++import importlib.util+import json+import os+from pathlib import Path+import threading+from typing import Any+++ROOT = Path(__file__).resolve().parents[1]+SDK_PATH = ROOT / "sdk" / "py" / "harness_sdk.py"+++def load_sdk() -> Any:+ spec = importlib.util.spec_from_file_location("privacy_test_harness_sdk", SDK_PATH)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++class Response:+ def read(self) -> bytes:+ return b"{}"++ def __enter__(self) -> "Response":+ return self++ def __exit__(self, *_args: Any) -> None:+ pass+++def emit(module: Any, mode: str | None, telemetry_off: bool = False) -> list[dict[str, Any]]:+ captured: list[dict[str, Any]] = []+ ready = threading.Event()++ def fake_urlopen(request: Any, timeout: int = 0) -> Response:+ del timeout+ captured.append(json.loads(request.data))+ ready.set()+ return Response()++ original_urlopen = module.urllib.request.urlopen+ original_id = module._sdk_install_id+ original_env = os.environ.copy()+ try:+ module.urllib.request.urlopen = fake_urlopen+ module._sdk_install_id = lambda: "0" * 32+ for key in ("GRAFF_LEARNING_PRIVACY", "GRAFF_NO_TELEMETRY"):+ os.environ.pop(key, None)+ if mode is not None:+ os.environ["GRAFF_LEARNING_PRIVACY"] = mode+ if telemetry_off:+ os.environ["GRAFF_NO_TELEMETRY"] = "1"+ module._fleet_signal(+ "propose",+ {+ "niche": "reviewer",+ "prompt_sha": "0123456789abcdef",+ "prompt_text": "OPENAI_API_KEY=sk-proj-test-only",+ },+ )+ ready.wait(1)+ return captured+ finally:+ module.urllib.request.urlopen = original_urlopen+ module._sdk_install_id = original_id+ os.environ.clear()+ os.environ.update(original_env)+++def encoded(payload: dict[str, Any]) -> str:+ return json.dumps(payload, separators=(",", ":"))+++def local_pull_requests(module: Any, mode: str | None) -> list[Any]:+ requests: list[Any] = []+ original_urlopen = module.urllib.request.urlopen+ original_env = os.environ.copy()+ try:+ module.urllib.request.urlopen = lambda request, timeout=0: requests.append(request)+ os.environ.pop("GRAFF_LEARNING_PRIVACY", None)+ if mode is not None:+ os.environ["GRAFF_LEARNING_PRIVACY"] = mode+ harness = module.Harness.__new__(module.Harness)+ assert harness.pull_elites("test-provider") == []+ return requests+ finally:+ module.urllib.request.urlopen = original_urlopen+ os.environ.clear()+ os.environ.update(original_env)+++def main() -> int:+ sdk = load_sdk()+ assert emit(sdk, None) == []+ assert emit(sdk, "LOCAL") == []+ assert emit(sdk, "unknown") == []+ assert emit(sdk, "aggregate", telemetry_off=True) == []++ aggregate = emit(sdk, "aggregate")+ assert len(aggregate) == 1+ aggregate_text = encoded(aggregate[0])+ assert "prompt_text" not in aggregate_text+ assert "sk-proj-test-only" not in aggregate_text+ assert "0123456789abcdef" in aggregate_text++ templates = emit(sdk, "templates")+ assert len(templates) == 1+ assert "prompt_text" not in encoded(templates[0])+ assert local_pull_requests(sdk, None) == []+ assert local_pull_requests(sdk, "LOCAL") == []++ ts = (ROOT / "sdk" / "ts" / "harness.ts").read_text()+ assert 'const privacy = process.env.GRAFF_LEARNING_PRIVACY ?? "local"' in ts+ assert "delete admitted.prompt_text" in ts+ assert 'includes(process.env.GRAFF_LEARNING_PRIVACY ?? "local")) return []' in ts+ print("privacy efficacy: 8/8 SDK egress cases passed; prompt canary never transmitted")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())