Skip to content

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

Python

feat(learn): a workspace configures its own learning store

Rach Pradhan649ec73a57f4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0437a09b..bdd62dd3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -82,6 +82,9 @@ jobs:
- name: Isolated read-only review regression
run: python3 scripts/test-review-mode.py zig-out/bin/graff
+ - name: Automatic learning bootstrap and its idle-workspace guard
+ run: python3 scripts/test-learn-auto-init.py zig-out/bin/graff
+
- name: Streamable HTTP MCP handshake and session regression
run: python3 scripts/test-mcp-streamable-http.py --graff zig-out/bin/graff
diff --git a/docs/local-learning.md b/docs/local-learning.md
index 2578de04..18fc7faa 100644
--- a/docs/local-learning.md
+++ b/docs/local-learning.md
@@ -9,7 +9,27 @@ active parent → deterministic mutation seeds → paired evaluation
→ the promoted genome becomes this workspace's root prompt
```
-## Closing the loop in one command
+## Nothing to run
+
+Learning is on by default. The first session in a workspace that does real
+model work (at least 5 calls, so a one-off question never triggers it) sets the
+workspace up on its way out:
+
+```text
+↺ setting this workspace up to learn from sessions like this one
+↺ learning on for this workspace: a trial runs in the background every 5 sessions
+ and spends real model calls — `graff learn status`, off with GRAFF_LEARN_AUTO=off
+```
+
+That is the same work `graff learn init` does, so run it by hand only to choose
+a provider, model, or arm count other than the detected defaults. A workspace
+gets exactly one automatic attempt: if it fails here (no `python3`, no usable
+credential) the loop stays quiet instead of retrying at the end of every
+session, and `graff learn init` remains available to retry deliberately.
+
+`GRAFF_LEARN_AUTO=off` turns the whole thing off, setup included.
+
+## What init writes
```sh
graff learn init # generate the whole pinned setup for this workspace
@@ -41,7 +61,9 @@ Requirements and consequences worth knowing:
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:
+once every 6 hours — starts one detached trial in the background. The session
+that configured the store counts as the first, so the earliest a trial can run
+is the fifth working session in that workspace:
```text
↺ learning trial started in the background — `graff learn status`, log .graff/learn/auto.log
@@ -56,8 +78,10 @@ trigger off with `GRAFF_LEARN_AUTO=off`.
Budget it deliberately: one trial runs the parent once over the whole primary
suite plus every candidate arm over the same suite, so the default two-arm
configuration is roughly 180 short agent runs against the configured learning
-model. Point `learn init --provider/--model` at a cheap model, or use
-`--candidates 1`, before letting the trigger run against an expensive one.
+model. Since setup is automatic, the way to control that is to run
+`graff learn init --provider/--model` (or `--candidates 1`) in a workspace
+*before* it accumulates enough sessions to start one, or to set
+`GRAFF_LEARN_AUTO=off` where you never want trials at all.
## The learned root policy
diff --git a/scripts/test-learn-auto-init.py b/scripts/test-learn-auto-init.py
new file mode 100644
index 00000000..03d2cf10
--- /dev/null
+++ b/scripts/test-learn-auto-init.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python3
+"""A workspace that does real model work configures its own learning store.
+
+The learning loop is on by default, so the trigger that creates a store is a
+default-on path that spends real money later. Both halves are asserted here:
+a working session bootstraps itself, and a trivial one is left alone.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import tempfile
+
+from codex_ws_mock import CodexMock, turn_events
+from pty_harness import PtySession
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+REPLY = "LEARN_AUTO_OK"
+# learn_auto.bootstrap_minimum_calls: below this a workspace is left alone.
+MINIMUM_CALLS = 5
+
+
+def run_session(tmp: str, port: int, prompts: int) -> str:
+ codex_home = os.path.join(tmp, "codex-home")
+ os.makedirs(codex_home, exist_ok=True)
+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:
+ json.dump({"tokens": {"access_token": "learn-auto-mock", "account_id": "acct"}}, fh)
+ harness_dir = os.path.join(tmp, ".harness")
+ os.makedirs(harness_dir, exist_ok=True)
+ with open(os.path.join(harness_dir, "settings.json"), "w", encoding="utf-8") as fh:
+ # Keep the model-call count exactly equal to the prompt count.
+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)
+
+ env = {
+ "HOME": tmp,
+ "CODEX_HOME": codex_home,
+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",
+ "GRAFF_CODEX_WS": "off",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ }
+ ambient = tuple(
+ name
+ for name in os.environ
+ if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR")
+ and name not in env
+ )
+ workspace = os.path.join(tmp, "workspace")
+ os.makedirs(workspace, exist_ok=True)
+ with PtySession(
+ GRAFF,
+ ["--model", "codex", "--no-telemetry"],
+ cwd=workspace,
+ env=env,
+ unset_env=ambient,
+ timeout=30.0,
+ ) as session:
+ session.wait_for_literal("] ›")
+ for _ in range(prompts):
+ cursor = len(session.raw)
+ session.send_line("do a little work")
+ session.wait_for_literal(REPLY, start=cursor)
+ session.wait_for_literal("] ›", start=cursor)
+ session.send_key("ctrl-d")
+ # Bootstrapping materializes a kit and generates two suites, so the
+ # exit path is slower than an ordinary session's.
+ result = session.read_until_exit(60.0)
+ if result.timed_out or result.exit_code != 0:
+ raise AssertionError(
+ f"session exit={result.exit_code} timed_out={result.timed_out}"
+ )
+ return session.text
+
+
+def main() -> None:
+ def events(request):
+ result = turn_events(f"resp_learn_{request.ordinal}")
+ result[0]["item"]["content"][0]["text"] = REPLY
+ return result
+
+ mock = CodexMock(events_for_request=events)
+ port = mock.start()
+ try:
+ # A one-question session must not drop a kit into someone's repository.
+ with tempfile.TemporaryDirectory(prefix="graff-learn-idle-") as tmp:
+ run_session(tmp, port, prompts=1)
+ store = os.path.join(tmp, "workspace", ".graff", "learn")
+ if os.path.exists(store):
+ raise AssertionError("a single-call session configured a learning store")
+ print(f"ok a session under {MINIMUM_CALLS} model calls leaves the workspace alone")
+
+ with tempfile.TemporaryDirectory(prefix="graff-learn-auto-") as tmp:
+ text = run_session(tmp, port, prompts=MINIMUM_CALLS)
+ workspace = os.path.join(tmp, "workspace")
+ active = os.path.join(workspace, ".graff", "learn", "refs", "active.json")
+ if not os.path.exists(active):
+ raise AssertionError(f"no learning store was configured\n{text[-3000:]}")
+ if "learning on for this workspace" not in text:
+ raise AssertionError(f"the session never said it turned learning on\n{text[-3000:]}")
+ if not os.path.exists(os.path.join(workspace, ".graff", "learn-auto-init")):
+ raise AssertionError("the one-shot bootstrap marker was not claimed")
+
+ with open(os.path.join(workspace, ".graff", "learn-kit", "config.json"), encoding="utf-8") as fh:
+ config = json.load(fh)
+ if not config.get("auto", {}).get("enabled"):
+ raise AssertionError("a self-configured store cannot promote anything")
+
+ # The bootstrapping session counts as the first toward the cadence,
+ # and must not itself spend a trial's worth of model calls.
+ auto_json = os.path.join(workspace, ".graff", "learn", "refs", "auto.json")
+ with open(auto_json, encoding="utf-8") as fh:
+ record = json.load(fh)
+ if record.get("sessions_since_trial") != 1:
+ raise AssertionError(f"bootstrapping session was not counted: {record}")
+ if record.get("trials_started"):
+ raise AssertionError(f"a trial ran on the bootstrapping session: {record}")
+ print("ok a working session configured its own store and started the cadence")
+ finally:
+ mock.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/learn_auto.zig b/src/learn_auto.zig
index 67131d38..46bdce30 100644
--- a/src/learn_auto.zig
+++ b/src/learn_auto.zig
@@ -3,12 +3,12 @@
//! `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
+//! model work ends, it configures the workspace's store if it has none, 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),
+//! * a workspace earns a store only once it has done real model work, and it
+//! gets exactly one automatic attempt at creating one,
//! * automatic promotion still needs `auto.enabled` in the immutable
//! configuration plus every statistical gate,
//! * one trial per cadence window, never two at once, and
@@ -50,7 +50,8 @@ pub const Skip = enum {
disabled,
/// Nothing to learn from: the session made no model calls.
idle_session,
- /// This workspace has no learning store (`graff learn init`).
+ /// This workspace has no learning store and has not earned an automatic
+ /// one: too little model work, or its one bootstrap attempt already ran.
unconfigured,
/// The configuration keeps promotion manual, so a background trial would
/// only pile up evidence nobody reads.
@@ -61,25 +62,40 @@ pub const Skip = enum {
not_due,
};
+pub const Started = struct { resumed: bool, contribute: bool };
+
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,
+ started: Started,
+ /// This workspace does real work and has no learning store yet, so the
+ /// caller should create one now. Claimed once per workspace: a bootstrap
+ /// that cannot succeed here (no python3, no usable credential) must not
+ /// retry at the end of every session forever.
+ needs_store,
};
-/// Marker for the one-time `learn init` hint.
-const hint_file = ".graff/learn-hint";
+/// Marker claiming the single automatic bootstrap this workspace gets.
+const bootstrap_marker = ".graff/learn-auto-init";
/// Enough model calls that this is a working repository, not a one-liner.
-const hint_minimum_calls: u64 = 5;
+const bootstrap_minimum_calls: u64 = 5;
+
+const dir_permissions: Io.File.Permissions =
+ if (builtin.os.tag == .windows) .default_dir else .fromMode(0o700);
-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
+/// Claim this workspace's one automatic bootstrap. The marker is created
+/// exclusively, so two sessions ending at once cannot both start materializing
+/// a kit into the same tree.
+pub fn claimBootstrap(io: Io, base: Io.Dir, model_calls: u64) Outcome {
+ if (model_calls < bootstrap_minimum_calls) return .{ .skipped = .unconfigured };
+ // A workspace that has never written a session has no .graff yet.
+ base.createDir(io, ".graff", dir_permissions) catch |err| switch (err) {
+ error.PathAlreadyExists => {},
+ else => return .{ .skipped = .unconfigured },
+ };
+ const file = base.createFile(io, bootstrap_marker, .{ .exclusive = true }) catch
return .{ .skipped = .unconfigured };
file.close(io);
- return .suggest;
+ return .needs_store;
}
pub const Options = struct {
@@ -159,7 +175,8 @@ fn openLog(store: *store_mod.Store) ?Io.File {
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);
+ var store = store_mod.Store.openAt(io, Io.Dir.cwd()) catch
+ return claimBootstrap(io, Io.Dir.cwd(), options.model_calls);
defer store.deinit();
var lock = store.acquireLock(0) catch return .{ .skipped = .busy };
var lock_held = true;
@@ -235,6 +252,28 @@ test "cadence needs both the session count and the interval" {
try std.testing.expect(due(.{ .sessions_since_trial = 9, .last_started_unix_ms = 200 * hour }, 100 * hour, options));
}
+test "a workspace bootstraps itself once, and only after real model work" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+
+ // A one-liner session is not worth an 11MB kit and a spending cadence.
+ try std.testing.expectEqual(
+ Outcome{ .skipped = .unconfigured },
+ claimBootstrap(io, tmp.dir, bootstrap_minimum_calls - 1),
+ );
+ // Real work: claimed, and .graff is created for a workspace that has none.
+ try std.testing.expectEqual(
+ Outcome.needs_store,
+ claimBootstrap(io, tmp.dir, bootstrap_minimum_calls),
+ );
+ // Claimed exactly once: a bootstrap that failed must not retry forever.
+ try std.testing.expectEqual(
+ Outcome{ .skipped = .unconfigured },
+ claimBootstrap(io, tmp.dir, 1000),
+ );
+}
+
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);
diff --git a/src/session_run.zig b/src/session_run.zig
index 775d78e4..616337f2 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -55,6 +55,7 @@ const session = @import("session.zig");
const fleet = @import("fleet.zig");
const hooks = @import("hooks.zig");
const learn_auto = @import("learn_auto.zig");
+const learn_init = @import("learn_init.zig");
const run_budget_mod = @import("run_budget.zig");
const learning_privacy = @import("learning_privacy.zig");
const commands_privacy = @import("commands_privacy.zig");
@@ -529,28 +530,62 @@ pub fn learningNotice(io: Io, arena: Allocator, environ_map: anytype, out: *Io.W
commands_privacy.firstRunNotice(io, arena, keys_cli.homeEnv(environ_map) orelse "", out);
}
+fn reportTrialStarted(started: learn_auto.Started) void {
+ 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,
+ },
+ );
+}
+
+/// Configure this workspace's learning store from the running binary, the same
+/// way `graff learn init` would. Best effort by design: a machine with no
+/// python3 or no usable credential simply does not learn, and the marker
+/// learn_auto already claimed keeps that from being retried every session.
+fn autoInitLearning(gpa: Allocator, arena: Allocator, io: Io, environ_map: *const std.process.Environ.Map) bool {
+ std.debug.print("↺ setting this workspace up to learn from sessions like this one\n", .{});
+ // learn init narrates its own progress; the session's closing lines below
+ // are the useful summary, so its output goes to a buffer instead.
+ var buf: [16 * 1024]u8 = undefined;
+ var sink = std.Io.Writer.fixed(&buf);
+ learn_init.zeroConfig(gpa, arena, io, environ_map, .{}, &sink) catch |err| {
+ std.debug.print(
+ "↺ learning setup skipped ({s}) — `graff learn init` to retry\n",
+ .{@errorName(err)},
+ );
+ return false;
+ };
+ std.debug.print(
+ "↺ learning on for this workspace: a trial runs in the background every {d} sessions and spends real model calls — `graff learn status`, off with GRAFF_LEARN_AUTO=off\n",
+ .{learn_auto.default_every_sessions},
+ );
+ return true;
+}
+
/// 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.
+/// The first such session in a workspace also creates the store it counts into.
pub fn startBackgroundLearning(gpa: Allocator, arena: Allocator, io: Io, environ_map: *const std.process.Environ.Map, budget: *const run_budget_mod.RunBudget, telemetry_allowed: bool) void {
- switch (learn_auto.maybeStart(gpa, arena, io, environ_map, .{
+ const options: learn_auto.Options = .{
.model_calls = budget.used(),
// A session launched with --no-telemetry keeps its trial local, even
// though the child process would not inherit that flag.
.contribute = telemetry_allowed and 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",
- .{},
- ),
+ };
+ switch (learn_auto.maybeStart(gpa, arena, io, environ_map, options)) {
+ .started => |started| reportTrialStarted(started),
+ // First real session here: build the store, then count this session
+ // against it so the cadence starts from this one rather than the next.
+ .needs_store => {
+ if (!autoInitLearning(gpa, arena, io, environ_map)) return;
+ switch (learn_auto.maybeStart(gpa, arena, io, environ_map, options)) {
+ .started => |started| reportTrialStarted(started),
+ else => {},
+ }
+ },
.skipped => {},
}
}