graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(learn): close the self-improvement loop and run it by default
Rach Pradhanb2fee85e0355
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1e6f14b4..0437a09b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -61,6 +61,9 @@ jobs:- name: Local learning lifecycle and security regressionrun: python3 tests/learn_e2e.py --graff zig-out/bin/graff+ - name: Zero-configuration learning bootstrap+ run: python3 tests/learn_bootstrap_e2e.py --graff zig-out/bin/graff+- name: Evolutionary tournament and behavioral metric regressionrun: |python3 tests/learn_tournament_e2e.py --graff zig-out/bin/graffdiff --git a/build.zig b/build.zigindex c0eeb66a..0f7c2020 100644--- a/build.zig+++ b/build.zig@@ -78,6 +78,22 @@ pub fn build(b: *std.Build) void {const test_step = b.step("test", "Run unit tests");test_step.dependOn(&run_tests.step);+ // Learning kit: the adapter/suite files `graff learn init` materializes+ // into a workspace so zero-configuration learning needs no repo checkout.+ // Embedded by name (src/learn_assets.zig `@embedFile`s these imports).+ for ([_]struct { import: []const u8, path: []const u8 }{+ .{ .import = "learn_kit_mutator", .path = "examples/learn_graff_mutator.py" },+ .{ .import = "learn_kit_evaluator", .path = "examples/learn_graff_evaluator.py" },+ .{ .import = "learn_kit_case", .path = "examples/learn_graff_case.py" },+ .{ .import = "learn_kit_behavior", .path = "examples/learn_behavior_metrics.py" },+ .{ .import = "learn_kit_suites", .path = "examples/learn_graff_suites.py" },+ .{ .import = "learn_kit_generate", .path = "examples/learn_generate_suites.py" },+ .{ .import = "learn_kit_scorer", .path = "scripts/score_run.py" },+ }) |asset| {+ exe.root_module.addAnonymousImport(asset.import, .{ .root_source_file = b.path(asset.path) });+ unit_tests.root_module.addAnonymousImport(asset.import, .{ .root_source_file = b.path(asset.path) });+ }+// --- spike (branch: spike/zigzag-repl): zigzag-based REPL ---// Also reachable as the `graff repl` subcommand of the main binary (see// src/main.zig). This standalone exe + `repl-test` step are kept fordiff --git a/docs/learning-privacy.md b/docs/learning-privacy.mdindex 53ebb9d7..8302e71c 100644--- a/docs/learning-privacy.md+++ b/docs/learning-privacy.md@@ -11,7 +11,11 @@ when the configured model provider is remote.## Modes-The default is `local`. Change the session ceiling interactively:+The default is `aggregate`: local trials publish signed, prompt-free grades so+the fleet loop has something to aggregate. A session says so once per machine+before anything is sent. Nothing above that tier is automatic — reusable+template text still needs an exact per-artifact approval. Change the session+ceiling interactively:```text/privacy@@ -28,7 +32,14 @@ GRAFF_LEARNING_PRIVACY=aggregate graff```Only exact lowercase environment values are recognized. Unknown, padded, or-case-varied values fail closed to `local`.+case-varied values fail closed to `local` — a garbled setting never falls back+to the aggregate default.++```sh+graff --learning-privacy local # this session contributes nothing+GRAFF_LEARNING_PRIVACY=local graff+GRAFF_FLEET=off graff # master kill switch, learning included+```| Mode | Learning data admitted | Additional consent || --- | --- | --- |diff --git a/docs/local-learning.md b/docs/local-learning.mdindex adbee6fb..bfc0b7eb 100644--- a/docs/local-learning.md+++ b/docs/local-learning.md@@ -6,8 +6,77 @@ agent prompt. It implements a complete local cycle:```textactive parent → deterministic mutation seeds → paired evaluation→ Zig-side verification/aggregation → select → promote or reject+ → the promoted genome becomes this workspace's root prompt```+## Closing the loop in one command++```sh+graff learn init # generate the whole pinned setup for this workspace+```++A bare `init` writes `.graff/learn-kit`: the bundled mutation/evaluation+adapters, a 60-case primary suite, a freshly randomized 40-case holdout, a+parent genome snapshotted from this build's root prompt, a copy of the running+binary, and the pinned configuration that ties them together. It then+initializes the store exactly as a hand-written `--parent/--config` pair would.+`--provider`/`--model` pick what the adapters drive (default: this session's+saved model, else any provider with a credential, else the hosted default), and+`--candidates N` sets the arms per trial.++Requirements and consequences worth knowing:++- `python3` must be on `PATH`; the bundled adapters are Python and the suite+ generator runs once at init.+- The binary is *copied* into the kit and pinned there, so `graff update` never+ invalidates the configuration. The kit keeps evaluating that copy until you+ re-initialize.+- The generated configuration enables the two-key automatic promotion policy+ (`auto.enabled`), so a trial that clears every statistical gate promotes+ without a human step.+- Re-running `init` in an initialized workspace fails instead of rewriting the+ pinned files out from under the existing store.++## Automatic trials++Once a workspace has a store, sessions feed it. When a session that made at+least one model call ends, graff counts it and — every 5 sessions, and at most+once every 6 hours — starts one detached trial in the background:++```text+↺ learning trial started in the background — `graff learn status`, log .graff/learn/auto.log+```++The trial is an ordinary `graff learn run --auto`, resuming an existing+checkpoint rather than restarting it, and publishing prompt-free aggregate+grades when learning privacy and a local signing key both allow it. It holds+the engine lock, so a second session cannot start a competing trial. Turn the+trigger off with `GRAFF_LEARN_AUTO=off`.++## The learned root policy++A promoted genome named `graff-root` (what `learn init` generates) becomes the+root system prompt for later sessions in that workspace, not just a subagent+persona. Generation 0 — the untouched snapshot of some build's own prompt —+never takes over, so an initialized-but-unpromoted store changes nothing.+Sessions using a learned policy say so at startup:++```text+root policy: learned generation 3 (9f2c1a7b0d44)+```++`--system-prompt` still wins, `GRAFF_LEARNED_PROMPT=off` ignores the learned+policy for one session, and `graff learn rollback` reverts the promotion+itself.++## Credentials++Adapters run with a scrubbed environment and a scratch `HOME`, so a `graff+login` credential on disk is invisible to them. `learn run` resolves the+credential names the configuration already declares in `pass_env` from the same+local key store the session uses, and passes only those. An undeclared name is+never resolved, and an exported value always wins.+It does **not** infer semantic success from ordinary interactive traces, and itdoes not turn behavioral telemetry into promotion authority. Mutators andevaluators are explicit local adapters with pinned inputs and typed JSON@@ -470,11 +539,15 @@ 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 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+Prompt genomes, suites, evidence, and traces never leave the machine. Signed+aggregate grades do: the learning ceiling defaults to aggregate, so an explicit+`--submit`, `learn submit`, or automatic trial publishes them when a local+signing key exists. `--learning-privacy local`, `GRAFF_LEARNING_PRIVACY=local`,+`/privacy local`, `GRAFF_FLEET=off`, and `GRAFF_NO_TELEMETRY=1` each turn that+off, and the first session that could contribute says so once per machine.++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` publishes the existing signed score plus a separately signed`codegraff.learn.grade.v3` receipt: fixed aggregate pass/delta/significance,regression, tool/cost/latency, recomputed behavioral score, gate (including economy-gate enablement), anddiff --git a/examples/learn_generate_suites.py b/examples/learn_generate_suites.pynew file mode 100644index 00000000..2a038a1c--- /dev/null+++ b/examples/learn_generate_suites.py@@ -0,0 +1,61 @@+#!/usr/bin/env python3+"""Write one pinned primary suite and one freshly randomized holdout suite.++`graff learn init` materializes this next to learn_graff_suites.py and runs it+once, so a workspace gets independent suites without a repository checkout.+"""++from __future__ import annotations++import json+from pathlib import Path+import secrets+import sys++from learn_graff_suites import (+ fresh_holdout,+ primary_cases,+ statistical_unit_count,+ validate_case_catalog,+)+++def write_json(path: Path, value: object) -> None:+ path.write_text(json.dumps(value, separators=(",", ":")) + "\n", encoding="utf-8")+ path.chmod(0o600)+++def main() -> None:+ if len(sys.argv) != 3:+ print("usage: learn_generate_suites.py PRIMARY HOLDOUT", file=sys.stderr)+ raise SystemExit(2)+ primary_path, holdout_path = Path(sys.argv[1]), Path(sys.argv[2])+ public_cases, hidden_cases = primary_cases(), fresh_holdout()+ validate_case_catalog(public_cases, 60)+ validate_case_catalog(hidden_cases, 40)+ primary_units = statistical_unit_count(public_cases)+ holdout_units = statistical_unit_count(hidden_cases)+ if primary_units < 40 or holdout_units < 40:+ raise SystemExit("primary and holdout each require 40 independent statistical units")+ write_json(primary_path, {+ "schema": "codegraff.learn.suite.v1",+ "suite_id": "graff-primary-v7",+ "cases": public_cases,+ })+ # A per-workspace random suite_id keeps the holdout distinct from the+ # primary suite and from every other workspace's holdout.+ write_json(holdout_path, {+ "schema": "codegraff.learn.suite.v1",+ "suite_id": "fresh-" + secrets.token_hex(8),+ "cases": hidden_cases,+ })+ print(json.dumps({+ "primary_cases": len(public_cases),+ "holdout_cases": len(hidden_cases),+ "primary_units": primary_units,+ "holdout_units": holdout_units,+ }))+++if __name__ == "__main__":+ main()diff --git a/examples/learn_graff_evaluator.py b/examples/learn_graff_evaluator.pyold mode 100755new mode 100644index e2b496a3..085350bc--- a/examples/learn_graff_evaluator.py+++ b/examples/learn_graff_evaluator.py@@ -170,9 +170,12 @@ def clear_attempt(path: Path) -> None: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"}:+ if not isinstance(value.get("provider"), str) or not value["provider"]:+ fail("evaluator must pin a provider")+ if not isinstance(value.get("model"), str) or not value["model"]:+ fail("evaluator must pin a model")+ # Absent effort means the pinned provider cannot apply one.+ if value.get("effort") is not None and value["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:@@ -239,7 +242,7 @@ def run_variant(env.pop("OTEL_EXPORTER_OTLP_ENDPOINT", None)env.pop("GRAFF_OTEL_ENDPOINT", None)argv = [- str(graff), "--json", "--model", "codex", "--no-resume", "--no-telemetry", "--yolo",+ str(graff), "--json", "--model", settings["provider"], "--no-resume", "--no-telemetry", "--yolo","--max-model-calls", str(settings["max_model_calls"]),"--max-tool-calls", str(settings["max_tool_calls"]),]@@ -263,9 +266,10 @@ def run_variant(}, "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")+ if settings.get("effort") is not None:+ 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 Noneproc.stdin.write(json.dumps({"type": "user", "text": case["task"]}, separators=(",", ":")) + "\n")proc.stdin.flush()diff --git a/examples/learn_graff_mutator.py b/examples/learn_graff_mutator.pyold mode 100755new mode 100644index 85356c99..74ff2535--- a/examples/learn_graff_mutator.py+++ b/examples/learn_graff_mutator.py@@ -56,17 +56,21 @@ def validate_arms(value: Any) -> tuple[list[dict[str, Any]], list[str], dict[strfor 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")+ if not isinstance(arms, list) or not 1 <= len(arms) <= 16:+ fail("between one and sixteen 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")+ required = ("id", "provider", "model", "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")+ # An absent effort means this provider cannot pin one; a present one is+ # still verified against the running harness below.+ if arm.get("effort") is not None and arm["effort"] not in EFFORTS:+ fail(f"arm {index} has an unsupported effort")+ if arm["id"] in seen:+ fail(f"arm {index} is a duplicate")if arm["placement"] not in {"append", "replace"}:fail(f"arm {index} has an unsupported placement")fixed_clause = arm.get("fixed_clause")@@ -75,10 +79,6 @@ def validate_arms(value: Any) -> tuple[list[dict[str, Any]], list[str], dict[strif 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@@ -160,10 +160,10 @@ def mutate(arms_path: Path, graff: Path, request_path: Path, response_path: Pathrequest_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))+ index = request_value.get("candidate_index")+ if not isinstance(index, int) or not 0 <= index < len(arms):+ fail("candidate_index is outside the configured arms")arm = arms[index]parent_path = request_value.get("parent", {}).get("path")child_path = request_value.get("child_path")@@ -224,7 +224,7 @@ Target paragraph:env.pop("GRAFF_OTEL_ENDPOINT", None)graff_executable = executable_snapshot(graff)argv = [- str(graff_executable), "--json", "--model", "codex", "--no-resume", "--no-telemetry",+ str(graff_executable), "--json", "--model", arm["provider"], "--no-resume", "--no-telemetry","--max-model-calls", "2", "--max-tool-calls", "0", "--system-prompt", system,]proc = subprocess.Popen(@@ -237,9 +237,10 @@ Target paragraph:}, "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']}")+ if arm.get("effort") is not None:+ 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,@@ -281,7 +282,7 @@ Target paragraph:"child_path": child_path,"child_sha256": hashlib.sha256(child_bytes).hexdigest(),"description": (- f"{arm['id']} ({arm['model']}/{arm['effort']})"+ f"{arm['id']} ({arm['model']}/{arm.get('effort') or 'default'})"+ ("; frozen confirmation" if fixed_clause is not None else "")+ ("; validation fallback: parent" if validation_fallback else "")),diff --git a/scripts/openai_mock.py b/scripts/openai_mock.pynew file mode 100644index 00000000..4dedea80--- /dev/null+++ b/scripts/openai_mock.py@@ -0,0 +1,104 @@+#!/usr/bin/env python3+"""A tiny OpenAI-compatible mock server for offline end-to-end runs.++Binds 127.0.0.1:1234 (the fixed `lmstudio` provider URL) and answers+/v1/chat/completions with either a streamed or non-streamed reply. The reply is+deliberately dumb: learning end-to-end tests need the *plumbing* exercised+(mutation adapter, paired evaluation, gates), not a model that solves tasks.++ python3 scripts/openai_mock.py [--port 1234]+"""++from __future__ import annotations++import argparse+import http.server+import json+import threading+++CLAUSE = "Prefer one exact read before an edit, then stop after verified success."+++def reply_for(body: dict) -> str:+ """The mutation adapter needs strict JSON; everything else gets prose."""+ text = json.dumps(body)+ if "Draft one behavioral clause" in text or "corrected JSON object" in text:+ return json.dumps({"clause": CLAUSE})+ return "done"+++class Handler(http.server.BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def _read_body(self) -> dict:+ length = int(self.headers.get("content-length", 0))+ if not length:+ return {}+ try:+ return json.loads(self.rfile.read(length))+ except (ValueError, UnicodeDecodeError):+ return {}++ def _send(self, payload: bytes, content_type: str) -> None:+ self.send_response(200)+ self.send_header("content-type", content_type)+ self.send_header("content-length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def do_GET(self) -> None: # noqa: N802 — /v1/models probes+ self._send(json.dumps({"data": [{"id": "mock"}]}).encode(), "application/json")++ def do_POST(self) -> None: # noqa: N802+ body = self._read_body()+ content = reply_for(body)+ if body.get("stream"):+ self.send_response(200)+ self.send_header("content-type", "text/event-stream")+ self.send_header("cache-control", "no-cache")+ self.send_header("connection", "close")+ self.end_headers()+ for chunk in (+ {"choices": [{"index": 0, "delta": {"role": "assistant", "content": content}, "finish_reason": None}]},+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 8, "completion_tokens": 4, "total_tokens": 12}},+ ):+ payload = dict(chunk, id="mock", object="chat.completion.chunk", model="mock")+ self.wfile.write(b"data: " + json.dumps(payload).encode() + b"\n\n")+ self.wfile.write(b"data: [DONE]\n\n")+ self.wfile.flush()+ self.close_connection = True+ return+ self._send(json.dumps({+ "id": "mock",+ "object": "chat.completion",+ "model": "mock",+ "choices": [{"index": 0, "message": {"role": "assistant", "content": content}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 8, "completion_tokens": 4, "total_tokens": 12},+ }).encode(), "application/json")++ def log_message(self, *_a) -> None:+ pass+++def serve(port: int = 1234) -> http.server.ThreadingHTTPServer:+ server = http.server.ThreadingHTTPServer(("127.0.0.1", port), Handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ return server+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("--port", type=int, default=1234)+ args = parser.parse_args()+ server = serve(args.port)+ print(f"mock openai server on 127.0.0.1:{args.port}", flush=True)+ try:+ threading.Event().wait()+ except KeyboardInterrupt:+ server.shutdown()+++if __name__ == "__main__":+ main()diff --git a/src/commands_privacy.zig b/src/commands_privacy.zigindex 1dc76dff..d1d31319 100644--- a/src/commands_privacy.zig+++ b/src/commands_privacy.zig@@ -22,6 +22,29 @@ fn printStatus(out: *Io.Writer) !void {);}+/// Marker for the one-time contribution disclosure. Per machine, not per+/// workspace: the fact that learning contributes by default is a property of+/// the install.+const notice_file = ".simple-harness-learning-notice";++/// Say it once, out loud, the first time a session could contribute: a default+/// that ships silently is not consent. Best-effort — if the marker cannot be+/// written the notice simply appears again next time.+pub fn firstRunNotice(io: Io, arena: std.mem.Allocator, home: []const u8, out: *Io.Writer) void {+ if (home.len == 0 or !privacy.allowsAggregate()) return;+ const path = std.fmt.allocPrint(arena, "{s}/{s}", .{ home, notice_file }) catch return;+ const file = Io.Dir.cwd().createFile(io, path, .{ .exclusive = true }) catch return;+ file.close(io);+ out.writeAll(+ \\learning: this build contributes prompt-free aggregate grades (counts, deltas,+ \\significance, fingerprints) from local learning trials — never prompt text, code,+ \\paths, or traces. Turn it off with /privacy local, GRAFF_LEARNING_PRIVACY=local,+ \\or GRAFF_FLEET=off. Shown once.+ \\+ ) catch return;+ out.flush() catch {};+}+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");diff --git a/src/learn_assets.zig b/src/learn_assets.zignew file mode 100644index 00000000..bdf632f6--- /dev/null+++ b/src/learn_assets.zig@@ -0,0 +1,47 @@+//! Files the zero-configuration learning bootstrap writes into a workspace.+//!+//! `graff learn init` (no flags) has to produce a *pinned* setup: every adapter+//! and suite is content-addressed in the immutable configuration, so the bytes+//! must come from somewhere stable. Embedding the shipped adapters means a+//! workspace never needs a repository checkout, and the pin matches whatever+//! binary wrote the kit.++const std = @import("std");++pub const Asset = struct {+ /// File name inside the materialized kit directory. Adapters keep their+ /// module names: the evaluator imports learn_graff_case/learn_behavior_metrics+ /// by path, and the suite generator imports learn_graff_suites by name.+ name: []const u8,+ bytes: []const u8,+};++pub const mutator_name = "learn_graff_mutator.py";+pub const evaluator_name = "learn_graff_evaluator.py";+pub const case_name = "learn_graff_case.py";+pub const behavior_name = "learn_behavior_metrics.py";+pub const suites_name = "learn_graff_suites.py";+pub const generate_name = "learn_generate_suites.py";+pub const scorer_name = "score_run.py";++pub const kit = [_]Asset{+ .{ .name = mutator_name, .bytes = @embedFile("learn_kit_mutator") },+ .{ .name = evaluator_name, .bytes = @embedFile("learn_kit_evaluator") },+ .{ .name = case_name, .bytes = @embedFile("learn_kit_case") },+ .{ .name = behavior_name, .bytes = @embedFile("learn_kit_behavior") },+ .{ .name = suites_name, .bytes = @embedFile("learn_kit_suites") },+ .{ .name = generate_name, .bytes = @embedFile("learn_kit_generate") },+ .{ .name = scorer_name, .bytes = @embedFile("learn_kit_scorer") },+};++test "every embedded learning asset is a non-empty executable Python script" {+ var seen: usize = 0;+ for (kit) |asset| {+ try std.testing.expect(asset.bytes.len > 128);+ try std.testing.expect(std.mem.startsWith(u8, asset.bytes, "#!/usr/bin/env python3"));+ try std.testing.expect(std.mem.endsWith(u8, asset.name, ".py"));+ for (kit[0..seen]) |prior| try std.testing.expect(!std.mem.eql(u8, prior.name, asset.name));+ seen += 1;+ }+ try std.testing.expectEqual(kit.len, seen);+}diff --git a/src/learn_auto.zig b/src/learn_auto.zignew file mode 100644index 00000000..67131d38--- /dev/null+++ b/src/learn_auto.zig@@ -0,0 +1,244 @@+//! The automatic half of the learning loop.+//!+//! `graff learn` shipped as a complete engine that nothing ever called: every+//! trial needed a human to type it, so no workspace ever produced a second+//! generation. This module is the missing edge. When a session that did real+//! model work ends in a workspace with a configured learning store, it counts+//! the session and — on cadence — starts one detached trial in the background.+//!+//! Deliberate limits, because a trial spends real model calls:+//! * it never runs without a configured store (`graff learn init` is the+//! opt-in),+//! * automatic promotion still needs `auto.enabled` in the immutable+//! configuration plus every statistical gate,+//! * one trial per cadence window, never two at once, and+//! * `GRAFF_LEARN_AUTO=off` disables the trigger outright.++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const posix_process_groups = switch (builtin.os.tag) {+ .windows, .wasi => false,+ else => true,+};++const store_mod = @import("learn_store.zig");+const checkpoint = @import("learn_checkpoint.zig");+const scoring = @import("scoring.zig");+const util = @import("util.zig");++pub const schema = "codegraff.learn.auto.v1";+pub const file_name = "auto.json";+pub const log_name = "auto.log";++/// Sessions between trials, and the floor on wall-clock between them. A busy+/// day of short sessions should not queue up a trial per session.+pub const default_every_sessions: u64 = 5;+pub const default_minimum_interval_ms: i64 = 6 * 60 * 60 * 1000;++pub const Record = struct {+ schema: []const u8 = schema,+ sessions_since_trial: u64 = 0,+ trials_started: u64 = 0,+ last_started_unix_ms: i64 = 0,+};++pub const Skip = enum {+ /// GRAFF_LEARN_AUTO said no.+ disabled,+ /// Nothing to learn from: the session made no model calls.+ idle_session,+ /// This workspace has no learning store (`graff learn init`).+ unconfigured,+ /// The configuration keeps promotion manual, so a background trial would+ /// only pile up evidence nobody reads.+ manual_only,+ /// Another learning operation holds the engine lock.+ busy,+ /// Cadence not reached yet.+ not_due,+};++pub const Outcome = union(enum) {+ skipped: Skip,+ started: struct { resumed: bool, contribute: bool },+ /// This workspace does real work but has no learning store yet. Said once+ /// per workspace — a loop nobody knows about is not on by default.+ suggest,+};++/// Marker for the one-time `learn init` hint.+const hint_file = ".graff/learn-hint";+/// Enough model calls that this is a working repository, not a one-liner.+const hint_minimum_calls: u64 = 5;++fn suggestOnce(io: Io, model_calls: u64) Outcome {+ if (model_calls < hint_minimum_calls) return .{ .skipped = .unconfigured };+ const file = Io.Dir.cwd().createFile(io, hint_file, .{ .exclusive = true }) catch+ return .{ .skipped = .unconfigured };+ file.close(io);+ return .suggest;+}++pub const Options = struct {+ /// Model calls this session made; zero means there is nothing new to learn+ /// from and the trigger stays quiet.+ model_calls: u64,+ /// Fleet + learning-privacy allow publishing prompt-free aggregate grades.+ contribute: bool,+ every_sessions: u64 = default_every_sessions,+ minimum_interval_ms: i64 = default_minimum_interval_ms,+};++/// Off only when explicitly turned off: the loop is on by default in a+/// workspace that has already opted into learning by initializing a store.+pub fn enabled(value: ?[]const u8) bool {+ const raw = value orelse return true;+ if (std.ascii.eqlIgnoreCase(raw, "off") or std.mem.eql(u8, raw, "0") or+ std.ascii.eqlIgnoreCase(raw, "false") or std.ascii.eqlIgnoreCase(raw, "no")) return false;+ return true;+}++pub fn due(record: Record, now_unix_ms: i64, options: Options) bool {+ if (record.sessions_since_trial < options.every_sessions) return false;+ // A never-run store is due as soon as the session count says so; a clock+ // that jumped backwards must not make a trial unreachable forever.+ if (record.last_started_unix_ms <= 0) return true;+ const elapsed = now_unix_ms -| record.last_started_unix_ms;+ return elapsed < 0 or elapsed >= options.minimum_interval_ms;+}++pub fn load(arena: Allocator, store: *store_mod.Store) Record {+ const bytes = store_mod.readFileNoFollow(store.io, store.refs, file_name, arena, 4096) catch return .{};+ const record = std.json.parseFromSliceLeaky(Record, arena, bytes, .{}) catch return .{};+ if (!std.mem.eql(u8, record.schema, schema)) return .{};+ return record;+}++pub fn save(gpa: Allocator, store: *store_mod.Store, record: Record) !void {+ const bytes = try store_mod.jsonBytes(gpa, record);+ defer gpa.free(bytes);+ try store.writeAtomicReplace(store.refs, file_name, bytes);+}++fn hasPendingTrial(store: *store_mod.Store) bool {+ const file = store.refs.openFile(store.io, checkpoint.file_name, .{ .follow_symlinks = false, .resolve_beneath = true }) catch return false;+ file.close(store.io);+ return true;+}++/// Build the trial command. Kept separate from spawning so the shape of an+/// automatic trial is testable without starting one.+pub fn trialArgv(argv: *[8][]const u8, exe_path: []const u8, resumed: bool, contribute: bool) []const []const u8 {+ var argc: usize = 0;+ for ([_][]const u8{ exe_path, "--learning-privacy", if (contribute) "aggregate" else "local", "learn", "run", "--auto" }) |arg| {+ argv[argc] = arg;+ argc += 1;+ }+ // A checkpointed tournament must continue, not restart: restarting would+ // re-expose the holdout it already reserved.+ if (resumed) {+ argv[argc] = "--resume";+ argc += 1;+ }+ if (contribute) {+ argv[argc] = "--submit";+ argc += 1;+ }+ return argv[0..argc];+}++fn openLog(store: *store_mod.Store) ?Io.File {+ return store.root.createFile(store.io, log_name, .{ .truncate = true }) catch null;+}++/// Count this session and, when due, start one detached trial. Never fails the+/// session: every error path is a skip.+pub fn maybeStart(gpa: Allocator, arena: Allocator, io: Io, environ: *const std.process.Environ.Map, options: Options) Outcome {+ if (!enabled(environ.get("GRAFF_LEARN_AUTO"))) return .{ .skipped = .disabled };+ if (options.model_calls == 0) return .{ .skipped = .idle_session };+ var store = store_mod.Store.openAt(io, Io.Dir.cwd()) catch return suggestOnce(io, options.model_calls);+ defer store.deinit();+ var lock = store.acquireLock(0) catch return .{ .skipped = .busy };+ var lock_held = true;+ defer if (lock_held) lock.deinit();++ const config = store.loadConfig(arena) catch return .{ .skipped = .unconfigured };+ if (!config.value.auto.enabled) return .{ .skipped = .manual_only };++ var record = load(arena, &store);+ record.sessions_since_trial +|= 1;+ const now = util.unixMs(io);+ if (!due(record, now, options)) {+ save(gpa, &store, record) catch {};+ return .{ .skipped = .not_due };+ }++ // Contribution needs a signing key as well as consent. Asking for+ // `--submit` without one fails the whole trial in preflight, so a machine+ // that cannot sign simply learns locally.+ const contribute = options.contribute and scoring.loadScoreKey(io, arena, environ) != null;+ const resumed = hasPendingTrial(&store);+ const exe_path = std.process.executablePathAlloc(io, gpa) catch return .{ .skipped = .unconfigured };+ defer gpa.free(exe_path);+ var argv_buf: [8][]const u8 = undefined;+ const argv = trialArgv(&argv_buf, exe_path, resumed, contribute);++ record.sessions_since_trial = 0;+ record.trials_started +|= 1;+ record.last_started_unix_ms = now;+ save(gpa, &store, record) catch {};++ const log = openLog(&store);+ defer if (log) |file| file.close(io);+ // Release the engine lock before the child asks for it.+ lock.deinit();+ lock_held = false;++ _ = std.process.spawn(io, .{+ .argv = argv,+ .stdin = .ignore,+ .stdout = if (log) |file| .{ .file = file } else .ignore,+ .stderr = if (log) |file| .{ .file = file } else .ignore,+ // Its own process group: the trial outlives this session, and a+ // Ctrl-C aimed at the shell's foreground group afterwards must not+ // kill a tournament mid-holdout.+ .pgid = if (posix_process_groups) 0 else null,+ }) catch return .{ .skipped = .busy };+ // Deliberately not waited on. The trial reports through+ // `graff learn status` and .graff/learn/auto.log.+ return .{ .started = .{ .resumed = resumed, .contribute = contribute } };+}++test "the trigger is on unless it is explicitly turned off" {+ try std.testing.expect(enabled(null));+ try std.testing.expect(enabled("1"));+ try std.testing.expect(enabled("on"));+ try std.testing.expect(!enabled("off"));+ try std.testing.expect(!enabled("OFF"));+ try std.testing.expect(!enabled("0"));+ try std.testing.expect(!enabled("false"));+ try std.testing.expect(!enabled("no"));+}++test "cadence needs both the session count and the interval" {+ const options: Options = .{ .model_calls = 1, .contribute = false };+ const hour = 60 * 60 * 1000;+ try std.testing.expect(!due(.{ .sessions_since_trial = 4 }, 100 * hour, options));+ // Never run before: the session count alone is enough.+ try std.testing.expect(due(.{ .sessions_since_trial = 5 }, 100 * hour, options));+ try std.testing.expect(!due(.{ .sessions_since_trial = 9, .last_started_unix_ms = 99 * hour }, 100 * hour, options));+ try std.testing.expect(due(.{ .sessions_since_trial = 9, .last_started_unix_ms = 90 * hour }, 100 * hour, options));+ // A backwards clock jump must not wedge the loop permanently.+ try std.testing.expect(due(.{ .sessions_since_trial = 9, .last_started_unix_ms = 200 * hour }, 100 * hour, options));+}++test "an automatic trial always carries the two-key auto flag and never restarts a checkpoint" {+ var argv: [8][]const u8 = undefined;+ const local = trialArgv(&argv, "graff", false, false);+ try std.testing.expectEqualSlices([]const u8, &.{ "graff", "--learning-privacy", "local", "learn", "run", "--auto" }, local);+ const resumed = trialArgv(&argv, "graff", true, true);+ try std.testing.expectEqualSlices([]const u8, &.{ "graff", "--learning-privacy", "aggregate", "learn", "run", "--auto", "--resume", "--submit" }, resumed);+}diff --git a/src/learn_bootstrap.zig b/src/learn_bootstrap.zignew file mode 100644index 00000000..52e9a277--- /dev/null+++ b/src/learn_bootstrap.zig@@ -0,0 +1,434 @@+//! Zero-configuration `graff learn init`.+//!+//! The learning engine only accepts a fully pinned configuration: absolute+//! adapter paths, SHA-256 pins, an evaluation suite, and an independent+//! holdout. Writing that by hand is why the engine shipped without ever+//! running anywhere. This module produces the whole thing from the running+//! binary: it materializes the embedded adapter kit into `.graff/learn-kit`,+//! generates a fresh primary/holdout suite pair, snapshots the parent genome+//! from this build's root prompt, and emits the pinned configuration that+//! `learn init` then bootstraps.+//!+//! Everything it writes stays inside the workspace and stays local; the+//! generated configuration turns automatic promotion on, because a loop that+//! needs a human to type `promote` is not a loop.++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const assets = @import("learn_assets.zig");+const store_mod = @import("learn_store.zig");+const prompts = @import("prompts.zig");+const jobs = @import("jobs.zig");+const util = @import("util.zig");++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);++pub const kit_dir_name = "learn-kit";+pub const kit_path = ".graff/" ++ kit_dir_name;+const active_ref_path = ".graff/learn/refs/active.json";+/// The agent name a learned genome must carry to become this workspace's root+/// policy. Any other name stays an ordinary learned subagent persona.+pub const root_policy_agent = "graff-root";+pub const parent_file = "parent.md";+pub const config_file = "config.json";+pub const primary_file = "primary.json";+pub const holdout_file = "holdout.json";+pub const arms_file = "arms.json";+pub const evaluator_settings_file = "evaluator.json";+pub const binary_file = "graff-pinned";++pub const Options = struct {+ provider: []const u8,+ model: []const u8,+ /// Whether this provider/model honors a reasoning-effort pin. When it does+ /// not, the adapters must not claim one: an unpinnable effort recorded in+ /// the cohort would describe a comparison that never happened.+ pin_effort: bool = false,+ candidates: usize = 2,+ repetitions: usize = 1,+};++pub const Prepared = struct {+ kit: []const u8,+ parent: []const u8,+ config: []const u8,+ provider: []const u8,+ model: []const u8,+ candidates: usize,+};++/// Anchors are matched against this build's root prompt; the first one that+/// occurs exactly once becomes the mutation target. Ordering is deliberate:+/// the last sentence is the safest place to accumulate learned clauses, and+/// the alternates only matter if a future prompt drops it.+const anchor_candidates = [_][]const u8{+ "Be direct and concise.",+ "Work directly for small sequential steps.",+ "Use todo_write to\ntrack multi-step work.",+};++/// Invariants a mutation must never disturb. The kit ships the superset; only+/// the ones actually present in the parent genome are configured, so a prompt+/// edit upstream cannot wedge every future trial.+const protected_candidates = [_][]const u8{+ "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`",+};++const arm_focus = [_][]const u8{+ "Tool economy: reach the same verified outcome with fewer redundant reads, repeated searches, and post-success verification calls.",+ "Exactness: preserve exact bytes and terminal-newline state on every edit, and prefer the smallest edit that satisfies the request.",+ "Parallelism: batch independent lookups into one response instead of serializing round trips that have no dependency between them.",+ "Stop conditions: treat an exact successful edit or command as complete, and re-read only after reported staleness, ambiguity, or failure.",+ "Discovery: choose the structural navigation tool for symbol/caller questions and reserve broad text scans for genuinely unknown phrasing.",+ "Reporting: state what was verified and what was not, without restating the plan or re-listing files already summarized.",+};++const arm_effort = [_][]const u8{ "high", "medium" };++fn writePrivateFile(io: Io, dir: Io.Dir, name: []const u8, bytes: []const u8) !void {+ dir.deleteFile(io, name) catch {};+ const file = try dir.createFile(io, name, .{ .exclusive = true, .permissions = file_permissions });+ defer file.close(io);+ try file.writeStreamingAll(io, bytes);+ try file.sync(io);+}++/// Copy the running executable into the kit and pin *that* copy. Pinning the+/// installed path instead would make every `graff update` invalidate the+/// configuration, and the configuration is immutable by design.+fn copyExecutable(io: Io, source_path: []const u8, dir: Io.Dir, name: []const u8) !void {+ const source = try Io.Dir.openFileAbsolute(io, source_path, .{});+ defer source.close(io);+ const stat = try source.stat(io);+ if (stat.kind != .file) return error.NotRegularFile;+ if (stat.size > store_mod.max_program_bytes) return error.FileTooBig;+ dir.deleteFile(io, name) catch {};+ const dest = try dir.createFile(io, name, .{ .exclusive = true, .permissions = file_permissions });+ defer dest.close(io);+ var buffer: [64 << 10]u8 = undefined;+ var offset: u64 = 0;+ while (offset < stat.size) {+ const want: usize = @intCast(@min(@as(u64, buffer.len), stat.size - offset));+ const got = try source.readPositionalAll(io, buffer[0..want], offset);+ if (got != want) return error.UnexpectedEndOfFile;+ try dest.writeStreamingAll(io, buffer[0..got]);+ offset += got;+ }+ try dest.sync(io);+}++fn joinPath(arena: Allocator, root: []const u8, name: []const u8) ![]const u8 {+ return std.fmt.allocPrint(arena, "{s}{c}{s}", .{ root, std.fs.path.sep, name });+}++fn pinFor(io: Io, arena: Allocator, root: []const u8, name: []const u8) !store_mod.PinnedFile {+ const path = try joinPath(arena, root, name);+ const digest = try store_mod.hashFileNoFollow(io, path);+ return .{ .path = path, .sha256 = try arena.dupe(u8, &digest) };+}++pub fn selectAnchor(parent: []const u8) ![]const u8 {+ for (anchor_candidates) |candidate| {+ if (std.mem.indexOf(u8, parent, candidate) == null) continue;+ if (std.mem.count(u8, parent, candidate) != 1) continue;+ return candidate;+ }+ return error.NoMutationAnchor;+}++pub fn selectProtected(arena: Allocator, parent: []const u8) ![]const []const u8 {+ var list: std.ArrayList([]const u8) = .empty;+ for (protected_candidates) |candidate| {+ if (std.mem.indexOf(u8, parent, candidate) == null) continue;+ try list.append(arena, candidate);+ }+ if (list.items.len == 0) return error.NoProtectedInvariants;+ return list.items;+}++const Arm = struct {+ index: usize,+ id: []const u8,+ provider: []const u8,+ model: []const u8,+ effort: ?[]const u8,+ target: []const u8,+ placement: []const u8,+ focus: []const u8,+};++const ArmsFile = struct {+ schema: []const u8 = "codegraff.learn.graff-arms.v1",+ template_egress: bool = true,+ maximum_changed_bytes: usize = 512,+ maximum_total_bytes: usize = 16384,+ protected_substrings: []const []const u8,+ targets: struct { root_workflow: []const u8 },+ arms: []const Arm,+};++const EvaluatorSettings = struct {+ schema: []const u8 = "codegraff.learn.graff-evaluator.v1",+ provider: []const u8,+ model: []const u8,+ effort: ?[]const u8,+ max_model_calls: usize = 8,+ max_tool_calls: usize = 8,+ max_attempts: usize = 2,+ task_timeout_seconds: usize = 120,+};++fn buildArms(arena: Allocator, options: Options, anchor: []const u8, protected: []const []const u8) !ArmsFile {+ const arms = try arena.alloc(Arm, options.candidates);+ for (arms, 0..) |*arm, index| {+ arm.* = .{+ .index = index,+ .id = try std.fmt.allocPrint(arena, "arm-{d}", .{index}),+ .provider = options.provider,+ .model = options.model,+ .effort = if (options.pin_effort) arm_effort[index % arm_effort.len] else null,+ .target = "root_workflow",+ // Appending after a stable anchor keeps every configured invariant+ // byte-identical; a replacement arm could delete one outright.+ .placement = "append",+ .focus = arm_focus[index % arm_focus.len],+ };+ }+ return .{+ .protected_substrings = protected,+ .targets = .{ .root_workflow = anchor },+ .arms = arms,+ };+}++/// `-B` keeps a __pycache__ directory out of the pinned kit: an unpinned file+/// appearing next to pinned ones is noise at best and confusing at worst.+fn pythonArgv(program: []const u8, primary: []const u8, holdout: []const u8) [5][]const u8 {+ return .{ program, "-B", assets.generate_name, primary, holdout };+}++/// Generate the primary suite plus a workspace-unique holdout. The generator+/// is one of the pinned kit files and runs in the kit directory so its sibling+/// case catalog imports by name.+fn generateSuites(gpa: Allocator, io: Io, kit: Io.Dir) !void {+ const interpreters = [_][]const u8{ "python3", "/usr/bin/python3", "python" };+ var last_error: ?anyerror = null;+ for (interpreters) |program| {+ const argv = pythonArgv(program, primary_file, holdout_file);+ const run = jobs.runCappedWithOptions(gpa, io, &argv, 8 << 10, 32 << 10, 120_000, .{+ .cwd = .{ .dir = kit },+ .kill_process_tree = true,+ }) catch |err| {+ last_error = err;+ continue;+ };+ defer gpa.free(run.stdout);+ defer gpa.free(run.stderr);+ if (run.timed_out) return error.SuiteGenerationTimedOut;+ if (run.term != .exited or run.term.exited != 0) return error.SuiteGenerationFailed;+ return;+ }+ return last_error orelse error.PythonUnavailable;+}++fn buildConfig(+ arena: Allocator,+ io: Io,+ root: []const u8,+ options: Options,+ arms_pin: store_mod.PinnedFile,+ settings_pin: store_mod.PinnedFile,+ binary_pin: store_mod.PinnedFile,+ pass_env: []const []const u8,+) !store_mod.Config {+ const mutator_pin = try pinFor(io, arena, root, assets.mutator_name);+ const evaluator_pin = try pinFor(io, arena, root, assets.evaluator_name);+ const behavior_pin = try pinFor(io, arena, root, assets.behavior_name);+ const scorer_pin = try pinFor(io, arena, root, assets.scorer_name);+ const case_pin = try pinFor(io, arena, root, assets.case_name);+ const primary_pin = try pinFor(io, arena, root, primary_file);+ const holdout_pin = try pinFor(io, arena, root, holdout_file);++ const mutator_inputs = try arena.dupe(store_mod.PinnedFile, &.{ arms_pin, binary_pin });+ // Input order is protocol: the evaluator reads GRAFF_LEARN_INPUT_2 for the+ // behavioral auditor and GRAFF_LEARN_INPUT_4 for the case helper.+ const evaluator_inputs = try arena.dupe(store_mod.PinnedFile, &.{ settings_pin, binary_pin, behavior_pin, scorer_pin, case_pin });+ const mutator_args = try arena.dupe([]const u8, &.{ arms_pin.path, binary_pin.path });+ const evaluator_args = try arena.dupe([]const u8, &.{ settings_pin.path, binary_pin.path });++ return .{+ .schema = store_mod.config_schema,+ .agent_name = root_policy_agent,+ .agent_description = "learned root coding policy for this workspace",+ .mutation_instruction = "Add one concise behavioral clause that measurably improves task outcomes or tool economy. Preserve every safety, authority, and attribution invariant byte-for-byte.",+ .mutator = .{+ .program = mutator_pin.path,+ .sha256 = mutator_pin.sha256,+ .args = mutator_args,+ .inputs = mutator_inputs,+ .pass_env = pass_env,+ },+ .evaluator = .{+ .program = evaluator_pin.path,+ .sha256 = evaluator_pin.sha256,+ .args = evaluator_args,+ .inputs = evaluator_inputs,+ .pass_env = pass_env,+ },+ .evaluation_suite = .{ .path = primary_pin.path, .sha256 = primary_pin.sha256 },+ .holdout_suite = .{ .path = holdout_pin.path, .sha256 = holdout_pin.sha256 },+ .limits = .{ .mutator_timeout_ms = 600_000, .evaluator_timeout_ms = 3_600_000 },+ .gate = .{+ .minimum_pairs = 40,+ .economy_gate_enabled = true,+ .promotion_mode = .economy,+ .minimum_tool_reduction_ppm = 100_000,+ .minimum_economy_pairs = 10,+ .require_all_candidates = false,+ .default_candidates = options.candidates,+ .default_repetitions = options.repetitions,+ },+ // Two-key automatic promotion: this flag plus an explicit+ // `learn run --auto`, and every statistical gate still has to pass.+ .auto = .{ .enabled = true },+ .cohort = .{+ .provider = options.provider,+ .model = options.model,+ .task_family = "coding-flow",+ .adapter_version = "graff-kit-v1",+ .verifier_version = "behavior-audited-v7",+ },+ };+}++/// Materialize the kit and return the parent/config paths `learn init` needs.+pub fn prepare(gpa: Allocator, arena: Allocator, io: Io, options: Options, pass_env: []const []const u8, out: *Io.Writer) !Prepared {+ if (options.candidates == 0 or options.candidates > 16) return error.InvalidCandidateCount;+ const base = Io.Dir.cwd();+ // Refuse before touching anything. Regenerating the kit under an existing+ // store would rewrite the exact files that store's immutable configuration+ // pins — a fresh holdout alone would fail every later verification.+ if (base.openFile(io, active_ref_path, .{ .follow_symlinks = false })) |file| {+ file.close(io);+ return error.AlreadyInitialized;+ } else |_| {}+ base.createDir(io, ".graff", dir_permissions) catch |err| switch (err) {+ error.PathAlreadyExists => {},+ else => return err,+ };+ var graff_dir = try base.openDir(io, ".graff", .{ .iterate = true, .follow_symlinks = false });+ defer graff_dir.close(io);+ graff_dir.createDir(io, kit_dir_name, dir_permissions) catch |err| switch (err) {+ error.PathAlreadyExists => {},+ else => return err,+ };+ var kit = try graff_dir.openDir(io, kit_dir_name, .{ .iterate = true, .follow_symlinks = false });+ defer kit.close(io);+ if (builtin.os.tag != .windows) try kit.setPermissions(io, dir_permissions);++ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const real_len = try kit.realPath(io, &real_buf);+ const root = try arena.dupe(u8, real_buf[0..real_len]);++ try out.writeAll("writing the learning kit into " ++ kit_path ++ "\n");+ for (assets.kit) |asset| try writePrivateFile(io, kit, asset.name, asset.bytes);++ const exe_path = try std.process.executablePathAlloc(io, gpa);+ defer gpa.free(exe_path);+ try copyExecutable(io, exe_path, kit, binary_file);++ const parent = try std.fmt.allocPrint(arena, "{s}\n", .{prompts.main_system_prompt});+ try writePrivateFile(io, kit, parent_file, parent);+ const anchor = try selectAnchor(parent);+ const protected = try selectProtected(arena, parent);++ const arms = try buildArms(arena, options, anchor, protected);+ const arms_bytes = try store_mod.jsonBytes(gpa, arms);+ defer gpa.free(arms_bytes);+ try writePrivateFile(io, kit, arms_file, arms_bytes);++ const settings: EvaluatorSettings = .{+ .provider = options.provider,+ .model = options.model,+ // Grading is a judgment call about a finished task, not the task: the+ // cheapest effort the provider offers is the right one.+ .effort = if (options.pin_effort) "low" else null,+ };+ const settings_bytes = try store_mod.jsonBytes(gpa, settings);+ defer gpa.free(settings_bytes);+ try writePrivateFile(io, kit, evaluator_settings_file, settings_bytes);++ try out.writeAll("generating a primary suite and a fresh independent holdout\n");+ try generateSuites(gpa, io, kit);++ const arms_pin = try pinFor(io, arena, root, arms_file);+ const settings_pin = try pinFor(io, arena, root, evaluator_settings_file);+ const binary_pin = try pinFor(io, arena, root, binary_file);+ const config = try buildConfig(arena, io, root, options, arms_pin, settings_pin, binary_pin, pass_env);+ try store_mod.validateConfig(config);+ const config_bytes = try store_mod.jsonBytes(gpa, config);+ defer gpa.free(config_bytes);+ try writePrivateFile(io, kit, config_file, config_bytes);++ return .{+ .kit = root,+ .parent = try joinPath(arena, root, parent_file),+ .config = try joinPath(arena, root, config_file),+ .provider = options.provider,+ .model = options.model,+ .candidates = options.candidates,+ };+}++test "the mutation anchor and protected invariants come from the live root prompt" {+ const parent = prompts.main_system_prompt;+ const anchor = try selectAnchor(parent);+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, parent, anchor));++ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const protected = try selectProtected(arena_state.allocator(), parent);+ try std.testing.expect(protected.len >= 3);+ for (protected) |item| try std.testing.expect(std.mem.indexOf(u8, parent, item) != null);+}++test "generated arms stay inside the adapter's validation envelope" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const parent = prompts.main_system_prompt;+ const arms = try buildArms(arena, .{+ .provider = "codegraff",+ .model = "deepseek-v4-pro",+ .candidates = 4,+ }, try selectAnchor(parent), try selectProtected(arena, parent));+ try std.testing.expectEqual(@as(usize, 4), arms.arms.len);+ try std.testing.expect(arms.template_egress);+ try std.testing.expect(arms.maximum_changed_bytes >= 64 and arms.maximum_changed_bytes <= 4096);+ try std.testing.expect(arms.maximum_total_bytes >= parent.len);+ for (arms.arms, 0..) |arm, index| {+ try std.testing.expectEqual(index, arm.index);+ try std.testing.expectEqualStrings("root_workflow", arm.target);+ try std.testing.expectEqualStrings("append", arm.placement);+ try std.testing.expect(arm.focus.len > 0);+ try std.testing.expect(arm.effort == null);+ for (arms.arms[0..index]) |prior| try std.testing.expect(!std.mem.eql(u8, prior.id, arm.id));+ }+}++test "a suite generation command names the pinned kit generator" {+ const argv = pythonArgv("python3", primary_file, holdout_file);+ try std.testing.expectEqualStrings("python3", argv[0]);+ try std.testing.expectEqualStrings("-B", argv[1]);+ try std.testing.expectEqualStrings(assets.generate_name, argv[2]);+ try std.testing.expectEqualStrings("primary.json", argv[3]);+ try std.testing.expectEqualStrings("holdout.json", argv[4]);+}diff --git a/src/learn_cli.zig b/src/learn_cli.zigindex c1f5cd5a..44e44dbf 100644--- a/src/learn_cli.zig+++ b/src/learn_cli.zig@@ -18,12 +18,15 @@ const learn_run = @import("learn_run.zig");const learn_delete = @import("learn_delete.zig");const submit = @import("learn_submit.zig");const tournament = @import("learn_tournament.zig");+const learn_init = @import("learn_init.zig");+const credentials = @import("learn_credentials.zig");const util = @import("util.zig");pub const usage =\\graff learn — safe local prompt-policy learning\\\\usage:+ \\ graff learn init [--candidates N] [--provider ID] [--model NAME]\\ graff learn init --parent PATH --config PATH\\ graff learn run [--candidates N] [--repetitions N] [--resume | --restart] [--submit] [--auto] [--show-adapter-stderr] [--lock-timeout-ms N]\\ graff learn submit RUN_ID [--lock-timeout-ms N]@@ -40,7 +43,9 @@ pub const usage =\\;-const InitArgs = struct { parent: []const u8, config: []const u8 };+/// A bare `learn init` bootstraps everything from the running binary; an+/// explicit pair of paths keeps the hand-authored workflow unchanged.+const InitArgs = learn_init.Args;const RunArgs = struct {candidates: ?usize = null,repetitions: ?usize = null,@@ -92,6 +97,9 @@ pub fn parse(args: []const []const u8) !Parsed {if (std.mem.eql(u8, command_name, "init")) {var parent: ?[]const u8 = null;var config: ?[]const u8 = null;+ var candidates: ?usize = null;+ var provider: ?[]const u8 = null;+ var model: ?[]const u8 = null;var index: usize = 1;while (index < args.len) : (index += 1) {const arg = args[index];@@ -105,9 +113,29 @@ pub fn parse(args: []const []const u8) !Parsed {index += 1;if (index >= args.len) return error.MissingOptionValue;config = args[index];+ } else if (std.mem.eql(u8, arg, "--candidates")) {+ if (candidates != null) return error.DuplicateOption;+ index += 1;+ if (index >= args.len) return error.MissingOptionValue;+ candidates = try parseUnsigned(usize, args[index]);+ if (candidates.? == 0 or candidates.? > 16) return error.InvalidNumber;+ } else if (std.mem.eql(u8, arg, "--provider")) {+ if (provider != null) return error.DuplicateOption;+ index += 1;+ if (index >= args.len) return error.MissingOptionValue;+ provider = args[index];+ } else if (std.mem.eql(u8, arg, "--model")) {+ if (model != null) return error.DuplicateOption;+ index += 1;+ if (index >= args.len) return error.MissingOptionValue;+ model = args[index];} else return error.UnknownOption;}- return .{ .init = .{ .parent = parent orelse return error.MissingOption, .config = config orelse return error.MissingOption } };+ // A generated configuration is generated whole: mixing one hand-written+ // half with a generated other half would silently unpin the pair.+ if ((parent == null) != (config == null)) return error.MissingOption;+ if (parent != null and (candidates != null or provider != null or model != null)) return error.ConflictingOptions;+ return .{ .init = .{ .parent = parent, .config = config, .candidates = candidates, .provider = provider, .model = model } };}if (std.mem.eql(u8, command_name, "run")) {var result: RunArgs = .{};@@ -210,23 +238,6 @@ pub fn parse(args: []const []const u8) !Parsed {return error.UnknownCommand;}-fn verifyPins(io: Io, arena: Allocator, config: store_mod.Config) !void {- try store_mod.verifyProgram(io, config.mutator);- try store_mod.verifyProgram(io, config.evaluator);- const primary_suite = try store_mod.loadSuite(io, arena, config.evaluation_suite);- try store_mod.validateSuitePower(primary_suite.manifest, config.gate);- if (config.holdout_suite) |suite| {- const holdout_suite = try store_mod.loadSuite(io, arena, suite);- try store_mod.validateHoldoutIndependence(- config.evaluation_suite.sha256,- primary_suite.manifest,- suite.sha256,- holdout_suite.manifest,- );- try store_mod.validateSuitePower(holdout_suite.manifest, config.gate);- }-}-fn verifyRun(arena: Allocator,io: Io,@@ -246,7 +257,7 @@ fn verifyRun(try store_mod.validateTransaction(parent_tx);if (parent_tx.generation != run.parent_generation or !std.mem.eql(u8, parent_tx.next_genome_id, run.parent_genome_id)) return error.ParentTransactionMismatch;_ = try store.readGenome(arena, run.parent_genome_id, config.value.limits.genome_bytes);- try verifyPins(io, arena, config.value);+ try learn_init.verifyPins(io, arena, config.value);const current_schema = std.mem.eql(u8, run.schema, eval.run_schema);var baseline_response: ?eval.PrimaryBaselineResponse = null;@@ -340,28 +351,6 @@ fn activeMatchesRun(active: store_mod.ActiveRef, run: eval.RunRecord) bool {std.mem.eql(u8, active.transaction_id, run.parent_transaction_id);}-fn initCommand(gpa: Allocator, arena: Allocator, io: Io, args: InitArgs, out: *Io.Writer) !void {- const config_bytes = try store_mod.readFileNoFollow(io, Io.Dir.cwd(), args.config, arena, store_mod.max_config_bytes);- const config = try std.json.parseFromSliceLeaky(store_mod.Config, arena, config_bytes, .{});- try store_mod.validateConfig(config);- try verifyPins(io, arena, config);- try learn_run.verifyTrialPower(io, arena, config, config.gate.default_candidates);- const parent = try store_mod.readFileNoFollow(io, Io.Dir.cwd(), args.parent, arena, config.limits.genome_bytes);- // Validate the genome BEFORE creating the store tree: a rejected parent- // must not leave a half-initialized .graff/learn behind (which used to- // wedge every later init with AlreadyInitialized).- if (!std.unicode.utf8ValidateSlice(parent) or- std.mem.indexOfScalar(u8, parent, 0) != null or- std.mem.trim(u8, parent, " \t\r\n").len == 0) return error.InvalidParentGenome;-- var store = try store_mod.Store.initAt(io, Io.Dir.cwd());- defer store.deinit();- var lock = try store.acquireLock(0);- defer lock.deinit();- const genome_id = try store.bootstrap(gpa, arena, config_bytes, parent, util.unixMs(io));- try out.print("initialized learned agent '{s}'\nactive genome {s}\n", .{ config.agent_name, genome_id });-}-fn runCommand(gpa: Allocator, arena: Allocator, io: Io, environ: *const std.process.Environ.Map, args: RunArgs, out: *Io.Writer) !void {diagnostics.setDetailed(args.show_adapter_stderr);defer diagnostics.setDetailed(false);@@ -371,14 +360,19 @@ fn runCommand(gpa: Allocator, arena: Allocator, io: Io, environ: *const std.procdefer lock.deinit();const config = try store.loadConfig(arena);const active = try store.loadActive(arena, config);- try verifyPins(io, arena, config.value);+ try learn_init.verifyPins(io, arena, config.value);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);+ // The adapters see a scrubbed environment, so a `graff login` credential+ // has to be handed to the names this configuration already declares.+ var adapter_env = try credentials.withResolvedCredentials(gpa, arena, io, environ, config.value);+ defer adapter_env.deinit();+try out.writeAll("warning: mutator and evaluator execute as your OS user; scratch isolation is not a sandbox\n");- const result = try learn_run.execute(gpa, arena, io, environ, &store, config, active, .{+ const result = try learn_run.execute(gpa, arena, io, &adapter_env, &store, config, active, .{.candidates = args.candidates,.repetitions = args.repetitions,.submit = args.submit,@@ -410,7 +404,7 @@ fn statusCommand(arena: Allocator, io: Io, timeout_ms: u64, out: *Io.Writer, verconst active = try store.loadActive(arena, config);const pending = try checkpoint.load(arena, &store);if (verify_all) {- try verifyPins(io, arena, config.value);+ try learn_init.verifyPins(io, arena, config.value);if (pending) |item| _ = try learn_run.restorePending(arena, io, &store, config, active, item);}const Status = struct {@@ -521,7 +515,10 @@ pub fn command(io: Io, gpa: Allocator, arena: Allocator, init: std.process.Init,defer out.flush() catch {};switch (parsed) {.help => try out.writeAll(usage),- .init => |args| try initCommand(gpa, arena, io, args, out),+ .init => |args| if (args.config == null)+ try learn_init.zeroConfig(gpa, arena, io, init.environ_map, args, out)+ else+ try learn_init.fromPaths(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),diff --git a/src/learn_credentials.zig b/src/learn_credentials.zignew file mode 100644index 00000000..c010f5b1--- /dev/null+++ b/src/learn_credentials.zig@@ -0,0 +1,164 @@+//! Provider/model selection and credential plumbing for zero-configuration+//! learning.+//!+//! Learning adapters run with a scrubbed environment and a scratch HOME, so a+//! `graff login` credential on disk is invisible to them: only the names a+//! configuration explicitly declares in `pass_env` cross that boundary, and+//! only if the parent process has them. Requiring every user to re-export a+//! secret before the loop can run is exactly the friction that kept it from+//! running at all, so `learn run` resolves the declared names from the same+//! local key store the session itself uses and hands them to the pinned+//! adapters. Nothing else is added, and an undeclared name is never resolved.++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const provider_mod = @import("provider.zig");+const keys_cli = @import("keys_cli.zig");+const oauth = @import("oauth.zig");+const pricing = @import("pricing.zig");+const schema = @import("schema.zig");+const serde = @import("serde.zig");+const store_mod = @import("learn_store.zig");++pub const Target = struct {+ provider: []const u8,+ model: []const u8,+};++/// Free tier first: a workspace with no configured key still gets a working+/// loop after `graff login`.+const fallback_provider = "codegraff";++/// Pick the provider/model the learning adapters should drive. The session's+/// own saved model wins, then any provider with a usable credential, then the+/// hosted default.+pub fn resolveTarget(io: Io, arena: Allocator, environ: *const std.process.Environ.Map) Target {+ const home = keys_cli.homeEnv(environ) orelse "";+ if (serde.loadModel(io, arena, home)) |saved| {+ if (provider_mod.specFor(saved.pid)) |spec| {+ if (saved.model.len > 0) return .{ .provider = spec.id, .model = saved.model };+ }+ }+ for (provider_mod.provider_specs) |spec| {+ if (!hasCredential(io, arena, environ, home, spec)) continue;+ return .{ .provider = spec.id, .model = pricing.providerDefaultModel(spec.id, spec.default_model) };+ }+ const spec = provider_mod.specFor(fallback_provider).?;+ return .{ .provider = spec.id, .model = pricing.providerDefaultModel(spec.id, spec.default_model) };+}++fn hasCredential(io: Io, arena: Allocator, environ: *const std.process.Environ.Map, home: []const u8, spec: provider_mod.ProviderSpec) bool {+ if (std.mem.eql(u8, spec.id, "codex")) return codexHome(io, arena, environ, home) != null;+ if (environ.get(spec.env_key) != null) return true;+ if (home.len == 0) return false;+ if (std.mem.eql(u8, spec.id, "codegraff")) {+ if (oauth.loadCodegraffKey(io, arena, home)) |_| return true;+ }+ return keys_cli.loadStoredKey(io, arena, home, spec.id) != null;+}++/// Whether this provider/model honors a reasoning-effort pin. The learning+/// adapters verify a pin they send, so a configuration must only declare one+/// the provider can actually apply.+pub fn pinsEffort(provider_id: []const u8, model: []const u8) bool {+ const spec = provider_mod.specFor(provider_id) orelse return false;+ return schema.providerTakesEffort(spec.kind, spec.id, model);+}++/// The model an explicitly named provider learns with when none is given.+pub fn defaultModelFor(provider_id: []const u8) []const u8 {+ const spec = provider_mod.specFor(provider_id) orelse return provider_id;+ return pricing.providerDefaultModel(spec.id, spec.default_model);+}++/// The environment names a configuration must declare for this provider. Codex+/// authenticates from a directory rather than a key variable.+pub fn passEnvFor(arena: Allocator, provider_id: []const u8) ![]const []const u8 {+ if (std.mem.eql(u8, provider_id, "codex")) return arena.dupe([]const u8, &.{"CODEX_HOME"});+ const spec = provider_mod.specFor(provider_id) orelse return arena.dupe([]const u8, &.{});+ return arena.dupe([]const u8, &.{spec.env_key});+}++fn codexHome(io: Io, arena: Allocator, environ: *const std.process.Environ.Map, home: []const u8) ?[]const u8 {+ const path = environ.get("CODEX_HOME") orelse blk: {+ if (home.len == 0) return null;+ break :blk std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch return null;+ };+ _ = oauth.loadCodexAuthFrom(io, arena, path) orelse return null;+ return path;+}++/// Resolve one declared `pass_env` name from local credentials. Returns null+/// when the name is not a known provider credential or nothing is stored.+fn resolveName(io: Io, arena: Allocator, environ: *const std.process.Environ.Map, name: []const u8) ?[]const u8 {+ const home = keys_cli.homeEnv(environ) orelse "";+ if (std.mem.eql(u8, name, "CODEX_HOME")) return codexHome(io, arena, environ, home);+ if (home.len == 0) return null;+ for (provider_mod.provider_specs) |spec| {+ if (!std.mem.eql(u8, spec.env_key, name)) continue;+ if (std.mem.eql(u8, spec.id, "codegraff")) {+ if (oauth.loadCodegraffKey(io, arena, home)) |key| return key;+ }+ return keys_cli.loadStoredKey(io, arena, home, spec.id);+ }+ return null;+}++fn declares(config: store_mod.Config, name: []const u8) bool {+ for (config.mutator.pass_env) |declared| if (std.mem.eql(u8, declared, name)) return true;+ for (config.evaluator.pass_env) |declared| if (std.mem.eql(u8, declared, name)) return true;+ return false;+}++/// A copy of the parent environment plus any credential the configuration+/// declares and the parent lacks. The caller owns the returned map.+pub fn withResolvedCredentials(+ gpa: Allocator,+ arena: Allocator,+ io: Io,+ parent: *const std.process.Environ.Map,+ config: store_mod.Config,+) !std.process.Environ.Map {+ var env = std.process.Environ.Map.init(gpa);+ errdefer env.deinit();+ for (parent.keys(), parent.values()) |key, value| try env.put(key, value);+ for ([_][]const []const u8{ config.mutator.pass_env, config.evaluator.pass_env }) |declared| {+ for (declared) |name| {+ if (env.get(name) != null) continue;+ if (resolveName(io, arena, parent, name)) |value| try env.put(name, value);+ }+ }+ return env;+}++test "pass_env names follow the provider's credential shape" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const codex = try passEnvFor(arena, "codex");+ try std.testing.expectEqual(@as(usize, 1), codex.len);+ try std.testing.expectEqualStrings("CODEX_HOME", codex[0]);+ const codegraff = try passEnvFor(arena, "codegraff");+ try std.testing.expectEqualStrings("CODEGRAFF_API_KEY", codegraff[0]);+ const unknown = try passEnvFor(arena, "not-a-provider");+ try std.testing.expectEqual(@as(usize, 0), unknown.len);+}++test "only configuration-declared names are eligible for credential resolution" {+ const config: store_mod.Config = .{+ .schema = store_mod.config_schema,+ .agent_name = "graff-root",+ .mutation_instruction = "improve",+ .mutator = .{ .program = "/x", .sha256 = "a" ** 64, .pass_env = &.{"CODEGRAFF_API_KEY"} },+ .evaluator = .{ .program = "/y", .sha256 = "b" ** 64, .pass_env = &.{"CODEX_HOME"} },+ .evaluation_suite = .{ .path = "/z", .sha256 = "c" ** 64 },+ .cohort = .{ .provider = "codegraff", .model = "m", .task_family = "f", .adapter_version = "v", .verifier_version = "v" },+ };+ try std.testing.expect(declares(config, "CODEGRAFF_API_KEY"));+ try std.testing.expect(declares(config, "CODEX_HOME"));+ try std.testing.expect(!declares(config, "ANTHROPIC_API_KEY"));+ try std.testing.expect(!declares(config, "PATH"));+}diff --git a/src/learn_init.zig b/src/learn_init.zignew file mode 100644index 00000000..24d84e36--- /dev/null+++ b/src/learn_init.zig@@ -0,0 +1,110 @@+//! `graff learn init`, both shapes: the hand-written parent/config pair and the+//! zero-configuration bootstrap that generates that pair from this binary.+//! Split out of learn_cli.zig (600-line goal).++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const store_mod = @import("learn_store.zig");+const learn_run = @import("learn_run.zig");+const bootstrap = @import("learn_bootstrap.zig");+const credentials = @import("learn_credentials.zig");+const util = @import("util.zig");++pub const Args = struct {+ parent: ?[]const u8 = null,+ config: ?[]const u8 = null,+ candidates: ?usize = null,+ provider: ?[]const u8 = null,+ model: ?[]const u8 = null,+};++/// Default arms per trial. Two is the smallest count that is still a+/// tournament, and every extra arm costs a full suite of paired evaluations.+const default_candidates: usize = 2;++/// Generate the whole pinned setup from this binary, then initialize the store+/// from it exactly as a hand-written pair would.+pub fn zeroConfig(+ gpa: Allocator,+ arena: Allocator,+ io: Io,+ environ: *const std.process.Environ.Map,+ args: Args,+ out: *Io.Writer,+) !void {+ const detected = credentials.resolveTarget(io, arena, environ);+ const provider = args.provider orelse detected.provider;+ const model = args.model orelse if (args.provider) |id| credentials.defaultModelFor(id) else detected.model;+ const pass_env = try credentials.passEnvFor(arena, provider);+ const prepared = try bootstrap.prepare(gpa, arena, io, .{+ .provider = provider,+ .model = model,+ .pin_effort = credentials.pinsEffort(provider, model),+ .candidates = args.candidates orelse default_candidates,+ }, pass_env, out);+ try fromPaths(gpa, arena, io, .{ .parent = prepared.parent, .config = prepared.config }, out);+ try out.print(+ \\learning target {s}/{s} with {d} candidate arm(s)+ \\kit {s}+ \\next: graff learn run --auto (or let the automatic trigger start it)+ \\+ , .{ prepared.provider, prepared.model, prepared.candidates, prepared.kit });+}++/// Every configured pin is re-verified here and at every later promotion+/// boundary, so a changed or deleted adapter/suite fails closed.+pub 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);+ const primary_suite = try store_mod.loadSuite(io, arena, config.evaluation_suite);+ try store_mod.validateSuitePower(primary_suite.manifest, config.gate);+ if (config.holdout_suite) |suite| {+ const holdout_suite = try store_mod.loadSuite(io, arena, suite);+ try store_mod.validateHoldoutIndependence(+ config.evaluation_suite.sha256,+ primary_suite.manifest,+ suite.sha256,+ holdout_suite.manifest,+ );+ try store_mod.validateSuitePower(holdout_suite.manifest, config.gate);+ }+}++pub fn fromPaths(+ gpa: Allocator,+ arena: Allocator,+ io: Io,+ args: Args,+ out: *Io.Writer,+) !void {+ const config_bytes = try store_mod.readFileNoFollow(io, Io.Dir.cwd(), args.config.?, arena, store_mod.max_config_bytes);+ const config = try std.json.parseFromSliceLeaky(store_mod.Config, arena, config_bytes, .{});+ try store_mod.validateConfig(config);+ try verifyPins(io, arena, config);+ try learn_run.verifyTrialPower(io, arena, config, config.gate.default_candidates);+ const parent = try store_mod.readFileNoFollow(io, Io.Dir.cwd(), args.parent.?, arena, config.limits.genome_bytes);+ // Validate the genome BEFORE creating the store tree: a rejected parent+ // must not leave a half-initialized .graff/learn behind (which used to+ // wedge every later init with AlreadyInitialized).+ if (!std.unicode.utf8ValidateSlice(parent) or+ std.mem.indexOfScalar(u8, parent, 0) != null or+ std.mem.trim(u8, parent, " \t\r\n").len == 0) return error.InvalidParentGenome;++ var store = try store_mod.Store.initAt(io, Io.Dir.cwd());+ defer store.deinit();+ var lock = try store.acquireLock(0);+ defer lock.deinit();+ const genome_id = try store.bootstrap(gpa, arena, config_bytes, parent, util.unixMs(io));+ try out.print("initialized learned agent '{s}'\nactive genome {s}\n", .{ config.agent_name, genome_id });+}++test {+ // build.zig's test root is main.zig, which reaches learn_cli and therefore+ // this module; the automatic-loop modules hang off here so their tests run.+ _ = @import("learn_assets.zig");+ _ = @import("learn_bootstrap.zig");+ _ = @import("learn_credentials.zig");+ _ = @import("learn_auto.zig");+}diff --git a/src/learning_privacy.zig b/src/learning_privacy.zigindex d4dec7cb..19abf1b8 100644--- a/src/learning_privacy.zig+++ b/src/learning_privacy.zig@@ -34,7 +34,14 @@ pub const Mode = enum(u8) {}};-var mode_value: std.atomic.Value(u8) = .init(@intFromEnum(Mode.local));+/// Aggregate is the default ceiling: the fleet loop only improves anything if+/// prompt-free signed grades actually reach it, and this tier carries counts,+/// deltas, significance, and fingerprints — never prompt text, tasks, code,+/// paths, or traces. Every higher tier (template/example text) still requires+/// an explicit per-artifact approval, and `--learning-privacy local`,+/// `GRAFF_LEARNING_PRIVACY=local`, `/privacy local`, `GRAFF_FLEET=off`, or+/// `--no-telemetry` each turn contribution off.+var mode_value: std.atomic.Value(u8) = .init(@intFromEnum(Mode.aggregate));var approvals_mu: Io.Mutex = .init;const max_approved_templates = 64;var approved_hashes: [max_approved_templates][32]u8 = undefined;@@ -42,7 +49,9 @@ 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().+/// configuration fails closed to Local when passed through init(): a garbled+/// setting must never silently raise the ceiling, even though an absent one+/// leaves the Aggregate default in place.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;@@ -51,8 +60,10 @@ pub fn parse(value: []const u8) ?Mode {return null;}+pub const default_mode: Mode = .aggregate;+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;+ const selected = cli_mode orelse if (env_value) |value| parse(value) orelse .local else default_mode;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.@@ -185,12 +196,19 @@ 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" {+test "learning privacy defaults to aggregate, fails closed, and modes form a ceiling" {init(null, null);+ try std.testing.expectEqual(Mode.aggregate, current());+ try std.testing.expect(allowsAggregate());+ try std.testing.expect(!allowsTemplateReview());+ init(null, "local");try std.testing.expectEqual(Mode.local, current());try std.testing.expect(!allowsAggregate());+ // A garbled value must not silently raise the ceiling to the default.init(null, "AGGREGATE");try std.testing.expectEqual(Mode.local, current());+ 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());diff --git a/src/main.zig b/src/main.zigindex 9ae8f4ae..898adc67 100644--- a/src/main.zig+++ b/src/main.zig@@ -406,19 +406,11 @@ pub fn main(init: std.process.Init) !void {// Root system-prompt layering (base + AGENTS.md/HARNESS.md/CLAUDE.md + --append-system-prompt + active-skill lines + connected-MCP notes) lives// in startup.zig as buildSystemPrompt() — pure over io/arena, returns both prompt strings by value.- const sys_prompt = try startup.buildSystemPrompt(- io,- arena,- out,- flags.system_prompt_flag,- flags.append_system_flag,- json_mode or flags.oneshot_prompt != null,- mcp_tools,- g_codedbpro_licensed,- );+ const sys_prompt = try startup.buildSystemPrompt(io, arena, out, flags.system_prompt_flag, flags.append_system_flag, json_mode or flags.oneshot_prompt != null, mcp_tools, g_codedbpro_licensed, init.environ_map.get("GRAFF_LEARNED_PROMPT"));const sys_normal = sys_prompt.sys_normal;const sys_strict = sys_prompt.sys_strict;boot.mark(io, "system prompt");+ session_run.learningNotice(io, arena, init.environ_map, out, json_mode or flags.oneshot_prompt != null);var snaps: Snapshots = .{ .gpa = gpa, .io = io };defer snaps.deinit();@@ -488,6 +480,9 @@ pub fn main(init: std.process.Init) !void {});session_run.compactResumedSession(&root);+ // Closing the learning loop: this session counts toward the next trial.+ defer session_run.startBackgroundLearning(gpa, arena, io, init.environ_map, &invocation_budget);+// `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL agent loop — each prompt runs a full root turn (tools + MCP) via// replTurnCb, reusing the root agent's tool set + registry + system prompt. Self-contained — exits after.if (try session_run.runReplCommand(gpa, io, init.environ_map, &root, &keys, &client, in, out, arena, flags)) return;diff --git a/src/session_run.zig b/src/session_run.zigindex 0731ad82..459a0ba0 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -54,6 +54,10 @@ const messages_mod = @import("messages.zig");const session = @import("session.zig");const fleet = @import("fleet.zig");const hooks = @import("hooks.zig");+const learn_auto = @import("learn_auto.zig");+const run_budget_mod = @import("run_budget.zig");+const learning_privacy = @import("learning_privacy.zig");+const commands_privacy = @import("commands_privacy.zig");/// `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL/// agent loop — each prompt runs a full root turn (tools + MCP) via@@ -517,3 +521,34 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:anim.loadDevSpinnerOptOut(io, arena, environ_map);return .{ .theme_on = theme_on, .limyuxi_glam = limyuxi_glam, .should_exit = false };}++/// Contribution is on by default, so say it once per machine before anything+/// can be sent. Quiet in --json/-p, where stdout is protocol output.+pub fn learningNotice(io: Io, arena: Allocator, environ_map: anytype, out: *Io.Writer, quiet: bool) void {+ if (quiet or !main_mod.g_fleet) return;+ commands_privacy.firstRunNotice(io, arena, keys_cli.homeEnv(environ_map) orelse "", out);+}++/// Closing the learning loop: a session that did real model work counts toward+/// this workspace's next trial and, on cadence, starts one in the background.+/// Workspaces with no learning store skip silently.+pub fn startBackgroundLearning(gpa: Allocator, arena: Allocator, io: Io, environ_map: *const std.process.Environ.Map, budget: *const run_budget_mod.RunBudget) void {+ switch (learn_auto.maybeStart(gpa, arena, io, environ_map, .{+ .model_calls = budget.used(),+ .contribute = main_mod.g_fleet and learning_privacy.allowsAggregate(),+ })) {+ .started => |started| std.debug.print(+ "↺ learning trial started in the background{s}{s} — `graff learn status`, log .graff/learn/{s}\n",+ .{+ if (started.resumed) " (resuming a checkpoint)" else "",+ if (started.contribute) " (contributing prompt-free aggregate grades)" else "",+ learn_auto.log_name,+ },+ ),+ .suggest => std.debug.print(+ "↺ this workspace can learn from sessions like this one: `graff learn init`\n",+ .{},+ ),+ .skipped => {},+ }+}diff --git a/src/startup.zig b/src/startup.zigindex 01217fed..b09367b9 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -41,6 +41,9 @@ const subagent_selection = @import("subagent_selection.zig");const serde = @import("serde.zig");const skills = @import("skills.zig");const prompts = @import("prompts.zig");+const learn_store = @import("learn_store.zig");+const learn_bootstrap = @import("learn_bootstrap.zig");+const learn_auto = @import("learn_auto.zig");pub const ResolvedKeys = struct {keys: provider_mod.Keys,@@ -312,6 +315,20 @@ pub const SystemPrompt = struct {/// to gate it: json_mode or a one-shot prompt). Carved out of main()'s/// former inline block verbatim — pure over io/arena, returns everything by/// value, so it's safe to call from outside main()'s own stack frame.+/// The last edge of the learning loop: a genome this workspace actually+/// promoted becomes the root prompt, not just a subagent persona. Generation 0+/// is the unmodified snapshot of some build's own prompt, so only a promoted+/// generation takes over — otherwise a freshly initialized store would pin an+/// older build's wording forever. Corrupt or foreign state fails closed.+fn learnedRootPolicy(io: Io, arena: Allocator) ?learn_store.ActiveAgent {+ const learned = learn_store.loadActiveAgent(io, arena) orelse return null;+ if (learned.generation == 0) return null;+ if (!std.mem.eql(u8, learned.name, learn_bootstrap.root_policy_agent)) return null;+ if (std.mem.trim(u8, learned.prompt, " \t\r\n").len == 0) return null;+ if (!learn_store.validId(learned.genome_id)) return null;+ return learned;+}+pub fn buildSystemPrompt(io: Io,arena: Allocator,@@ -321,8 +338,16 @@ pub fn buildSystemPrompt(quiet: bool,mcp_tools: []const mcp.Tool,codedbpro_licensed: bool,+ learned_policy_env: ?[]const u8,) !SystemPrompt {- const base_prompt: []const u8 = system_prompt_flag orelse prompts.main_system_prompt;+ // A learned policy is used unless this session opted out of it.+ const learned: ?learn_store.ActiveAgent = if (system_prompt_flag == null and learn_auto.enabled(learned_policy_env)) learnedRootPolicy(io, arena) else null;+ if (learned) |policy| if (!quiet) {+ try out.print("root policy: learned generation {d} ({s})\n", .{ policy.generation, policy.genome_id[0..12] });+ try out.flush();+ };+ const base_prompt: []const u8 = system_prompt_flag orelse+ if (learned) |policy| policy.prompt else prompts.main_system_prompt;var sys_normal: []const u8 = base_prompt;for ([_][]const u8{ "AGENTS.md", "HARNESS.md", "CLAUDE.md" }) |fname| {const body = Io.Dir.cwd().readFileAlloc(io, fname, arena, .limited(64 * 1024)) catch continue;diff --git a/tests/learn_bootstrap_e2e.py b/tests/learn_bootstrap_e2e.pynew file mode 100644index 00000000..25d1eda4--- /dev/null+++ b/tests/learn_bootstrap_e2e.py@@ -0,0 +1,144 @@+#!/usr/bin/env python3+"""Zero-configuration `graff learn init` end-to-end (no model calls).++Covers the setup half of the automatic loop: one command has to produce a store+whose every pin verifies, an independent holdout, and a configuration that+enables automatic promotion — and it must refuse to regenerate that setup under+an existing store, which would invalidate the pins it already made.++ python3 tests/learn_bootstrap_e2e.py --graff zig-out/bin/graff+"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile+++def run(graff: Path, workspace: Path, env: dict[str, str], *args: str, succeeds: bool = True) -> subprocess.CompletedProcess[str]:+ result = subprocess.run(+ [str(graff), "learn", *args],+ cwd=workspace,+ env=env,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ timeout=300,+ check=False,+ )+ if succeeds and result.returncode != 0:+ raise AssertionError(f"learn {' '.join(args)} failed\n{result.stdout}\n{result.stderr}")+ if not succeeds and result.returncode == 0:+ raise AssertionError(f"learn {' '.join(args)} unexpectedly succeeded\n{result.stdout}")+ return result+++def digest(path: Path) -> str:+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def units(suite: dict) -> set[str]:+ return {case.get("statistical_unit_id", case["id"]) for case in suite["cases"]}+++def assert_pins(config: dict) -> None:+ """Every configured path must be absolute, private, and match its digest."""+ pins = [+ (config["mutator"]["program"], config["mutator"]["sha256"]),+ (config["evaluator"]["program"], config["evaluator"]["sha256"]),+ (config["evaluation_suite"]["path"], config["evaluation_suite"]["sha256"]),+ (config["holdout_suite"]["path"], config["holdout_suite"]["sha256"]),+ ]+ pins += [(item["path"], item["sha256"]) for item in config["mutator"]["inputs"]]+ pins += [(item["path"], item["sha256"]) for item in config["evaluator"]["inputs"]]+ for raw, sha256 in pins:+ path = Path(raw)+ assert path.is_absolute(), f"pinned path is not absolute: {raw}"+ assert path.is_file(), f"pinned path is missing: {raw}"+ assert digest(path) == sha256, f"pin mismatch for {raw}"+ assert not path.stat().st_mode & 0o022, f"pinned file is group/world writable: {raw}"+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("--graff", type=Path, default=Path("zig-out/bin/graff"))+ args = parser.parse_args()+ graff = args.graff.resolve()+ if not graff.is_file():+ raise SystemExit(f"missing graff binary: {graff}")+ if shutil.which("python3") is None:+ raise SystemExit("python3 is required for the bundled learning kit")++ with tempfile.TemporaryDirectory(prefix="learn-bootstrap-") as raw:+ root = Path(raw)+ home = root / "home"+ home.mkdir(mode=0o700)+ workspace = root / "workspace"+ workspace.mkdir(mode=0o700)+ env = {+ **os.environ,+ "HOME": str(home),+ "GRAFF_NO_TELEMETRY": "1",+ "GRAFF_FLEET": "off",+ "LMSTUDIO_API_KEY": "local",+ }+ env.pop("CODEX_HOME", None)++ out = run(graff, workspace, env, "init", "--provider", "lmstudio", "--model", "mock", "--candidates", "2").stdout+ assert "initialized learned agent 'graff-root'" in out, out+ assert "lmstudio/mock with 2 candidate arm(s)" in out, out++ kit = workspace / ".graff" / "learn-kit"+ config = json.loads((kit / "config.json").read_text(encoding="utf-8"))+ assert config["agent_name"] == "graff-root"+ assert config["auto"]["enabled"] is True, "the generated loop must be able to promote on its own"+ assert config["gate"]["default_candidates"] == 2+ assert config["cohort"]["provider"] == "lmstudio" and config["cohort"]["model"] == "mock"+ assert config["mutator"]["pass_env"] == ["LMSTUDIO_API_KEY"], config["mutator"]["pass_env"]+ assert_pins(config)++ arms = json.loads((kit / "arms.json").read_text(encoding="utf-8"))+ assert len(arms["arms"]) == 2+ parent = (kit / "parent.md").read_text(encoding="utf-8")+ target = arms["targets"]["root_workflow"]+ assert parent.count(target) == 1, "the mutation target must occur exactly once in the parent"+ assert arms["protected_substrings"], "at least one invariant must be protected"+ for item in arms["protected_substrings"]:+ assert item in parent, f"protected substring is missing from the parent: {item}"+ for arm in arms["arms"]:+ # lmstudio cannot apply a reasoning-effort pin, so none is claimed.+ assert arm.get("effort") is None, arm+ settings = json.loads((kit / "evaluator.json").read_text(encoding="utf-8"))+ assert settings["effort"] is None, settings++ primary = json.loads((kit / "primary.json").read_text(encoding="utf-8"))+ holdout = json.loads((kit / "holdout.json").read_text(encoding="utf-8"))+ assert primary["suite_id"] != holdout["suite_id"]+ assert not units(primary) & units(holdout), "the holdout must be independent of the primary suite"+ assert len(units(primary)) >= config["gate"]["minimum_pairs"]+ assert len(units(holdout)) >= config["gate"]["minimum_pairs"]++ verified = json.loads(run(graff, workspace, env, "verify").stdout)+ assert verified["integrity"] == "ok" and verified["pins_verified"] is True, verified+ assert verified["agent_name"] == "graff-root" and verified["generation"] == 0++ # A second init must not touch the pinned files the store depends on.+ before = {name: digest(kit / name) for name in ("primary.json", "holdout.json", "parent.md", "config.json")}+ again = run(graff, workspace, env, "init", succeeds=False)+ assert "AlreadyInitialized" in again.stderr, again.stderr+ assert {name: digest(kit / name) for name in before} == before, "re-init rewrote pinned files"+ still = json.loads(run(graff, workspace, env, "verify").stdout)+ assert still["pins_verified"] is True and still["config_id"] == verified["config_id"]++ print("learning bootstrap E2E passed", file=sys.stdout)+++if __name__ == "__main__":+ main()diff --git a/tests/learn_e2e.py b/tests/learn_e2e.pyindex 47e9fcfd..efb592da 100644--- a/tests/learn_e2e.py+++ b/tests/learn_e2e.py@@ -249,10 +249,12 @@ def verify_grade_submit(graff: Path, workspace: Path, env: dict[str, 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:+ # Aggregate is the default ceiling, so Local is now the *selected*+ # state that must still fail before any network egress.local = subprocess.run([str(graff), "learn", "submit", run_id],cwd=workspace,- env=submit_env,+ env={**submit_env, "GRAFF_LEARNING_PRIVACY": "local"},text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,@@ -261,11 +263,38 @@ def verify_grade_submit(graff: Path, workspace: Path, env: dict[str, str], root:)assert local.returncode != 0 and "LearningPrivacyLocal" in local.stderrassert not GradeCapture.payloads, "local privacy must fail before network egress"+ # A garbled ceiling must fail closed to Local rather than fall back to+ # the aggregate default.+ garbled = subprocess.run(+ [str(graff), "learn", "submit", run_id],+ cwd=workspace,+ env={**submit_env, "GRAFF_LEARNING_PRIVACY": "AGGREGATE"},+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ timeout=60,+ check=False,+ )+ assert garbled.returncode != 0 and "LearningPrivacyLocal" in garbled.stderr+ assert not GradeCapture.payloads, "a garbled privacy value must not enable 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.stderrassert not GradeCapture.payloads, "fleet master-off must block learning egress"- output = invoke(graff, workspace, submit_env, "submit", run_id).stdout+ # No flag and no environment value: the default ceiling is Aggregate,+ # which is the only reason an automatic trial can contribute anything.+ default_submit = 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 default_submit.returncode == 0, default_submit.stderr+ output = default_submit.stdoutassert "submitted 2 signed aggregate grade(s)" in outputdelete_env = {**submit_env, "GRAFF_NO_TELEMETRY": "1", "GRAFF_FLEET": "off"}deleted = invoke(graff, workspace, delete_env, "delete-remote", run_id).stdout