Skip to content

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

Python

feat: complete behavioral learning harness

Rach Pradhan90a365bfa4ad
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 9de6fef0..c498c87c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -58,6 +58,12 @@ jobs:
- name: Local learning lifecycle and security regression
run: python3 tests/learn_e2e.py --graff zig-out/bin/graff
+ - name: Evolutionary tournament and behavioral metric regression
+ run: |
+ python3 tests/learn_tournament_e2e.py --graff zig-out/bin/graff
+ python3 tests/learn_graff_adapters.py
+ python3 tests/learn_graff_evaluator_retries.py
+
- name: Behavioral trace stream, re-scorer, and replay round trip
run: python3 scripts/test-behavior-trace.py zig-out/bin/graff
diff --git a/README.md b/README.md
index 8e9ea323..4df59208 100644
--- a/README.md
+++ b/README.md
@@ -840,8 +840,10 @@ agent session can write an exclusively-created
envelope. The local JSONL is never uploaded wholesale. Local capture defaults on
and is independently disabled with `GRAFF_BEHAVIOR_TRACE=off`. Set
`GRAFF_BEHAVIOR_TRACE=full` to additionally record tool names/arguments and
-completed assistant text in that local file (opt-in, capped, and never
-uploaded).
+completed assistant text in that local file (opt-in and capped). That plaintext
+file is never uploaded wholesale. Metadata upload still receives only a
+separately built, content-free projection; exact rich fields require the
+additional `GRAFF_BEHAVIOR_UPLOAD=content` opt-in.
When ordinary telemetry is enabled, Codegraff also defaults to one bounded,
end-of-run **field-allowlisted metadata** POST. A terminal `/v1/logs` path is
@@ -855,6 +857,9 @@ bounded `x-harness-key` token to both OTLP and behavioral requests. Metadata mod
includes lifecycle/correlation fields, a controlled client class (`harness`,
`sdk-ts`, or `sdk-py`), an initial run-start provider/model/effort snapshot,
drop/completeness status, and content-free per-turn API/tool-category aggregates.
+When rich capture is enabled, that allowlist can also carry rich-event
+correlation, broad tool class, byte/duration/error counters, and truncation
+flags—never exact tool names, arguments, results, or assistant text.
The local prompt fingerprint is omitted from default metadata because a
low-entropy prompt can be recovered by enumeration. It has no dedicated fields for prompts, generated text or hidden
reasoning, source code or diffs, filesystem paths or repository names, tool
@@ -862,8 +867,10 @@ arguments/results, commands, arbitrary environment values, or exact private MCP
names. Provider and model identifiers are included exactly as configured; Phase
1 does not inspect, classify, or redact those identifier values.
-Most Phase 1 runs contain lifecycle events only (plus tool/action/text
-events with `GRAFF_BEHAVIOR_TRACE=full`, local-only in every upload mode).
+Most Phase 1 runs contain lifecycle events only. With
+`GRAFF_BEHAVIOR_TRACE=full`, tool/action/text events are added locally and their
+content-free projections become eligible for metadata upload; their exact
+names, arguments, and text are sent only in explicit content mode.
The eval-driven loop (`--eval`/`--until`) is the first built-in caller of the
typed commitment/misprediction APIs, committing to a target before running
the scoring command and recording a misprediction only on a nonzero exit or a
diff --git a/architecture.md b/architecture.md
index c10bd6f0..c1d1d398 100644
--- a/architecture.md
+++ b/architecture.md
@@ -457,13 +457,20 @@ is omitted from every network projection because low-entropy prompt variants can
be enumerated. With ordinary telemetry enabled,
the upload defaults to a fixed-field allowlisted metadata projection, including
only a controlled client class rather than arbitrary `HARNESS_CLIENT` content;
-only an explicit content opt-in can serialize opaque fields supplied through the
-typed commitment/misprediction APIs. Provider/tool plumbing does not infer dedicated
+rich-event metadata is limited to correlation, controlled tool class,
+byte/duration/error counters, and truncation flags. Only an explicit content
+opt-in can serialize opaque fields supplied through the typed
+commitment/misprediction APIs or exact rich tool/text fields. Provider/tool
+plumbing does not infer dedicated
prompt-text, generated-output, hidden-reasoning, source, path, argument, result,
or task-state fields. Initial provider and model identifiers are serialized
-exactly as configured and are not inspected or value-redacted. No built-in
-production adapter invokes the typed APIs yet, and automatic
-verification, behavioral scoring, repair, and fleet consumption remain deferred.
+exactly as configured and are not inspected or value-redacted. The eval-driven
+loop is the first production producer of typed commitment/misprediction events:
+it stops on red, preserves an incomplete repair state, and requires a fresh
+green verifier result before completion. The local tournament recomputes a
+bounded behavior score from closed rich traces. General task adapters,
+automatic semantic verification, and fleet-wide behavioral consumption remain
+deferred.
The pre-existing append-only `Trajectory` DGM ledger and its record shapes remain
unchanged. See
[`docs/behavioral-trajectories.md`](docs/behavioral-trajectories.md).
diff --git a/docs/behavioral-trajectories.md b/docs/behavioral-trajectories.md
index 9d924bdc..f5d3bd78 100644
--- a/docs/behavioral-trajectories.md
+++ b/docs/behavioral-trajectories.md
@@ -5,9 +5,10 @@ schema-harness traces discussed in [issue #246](https://github.com/justrach/code
It establishes an ordered per-run envelope and explicit APIs for caller-asserted
commitments and mispredictions. Here, a **run** means an initialized agent
session; utility invocations such as help, version, and `graff title` return
-before behavioral tracing starts. Phase 1 does **not** yet implement the complete
-generic predict → act → verify → repair loop, replayable task state, behavioral
-scoring, or fleet/DGM selection from those scores.
+before behavioral tracing starts. The configured eval loop now implements one
+enforceable predict → act → verify → repair producer. The broader stream does
+**not** yet provide replayable task state, a generic verifier for every task
+adapter, or fleet/DGM selection from general behavioral scores.
## Three different local streams
@@ -27,6 +28,23 @@ exits nonzero or the parsed score misses `--until`. Every other invocation path
still contains lifecycle events only. Adapter rows in the example below are
illustrative.
+For an eval-driven session, `eval` is a verifier boundary and must be the only
+tool in its batch. A red result marks the current expectation as contradicted,
+drops the remaining plan, and ends that model turn. The next turn is a repair
+turn. A green result permits completion only while the workspace remains
+unchanged; any subsequent workspace-changing tool makes the result stale and
+requires another eval. Read-only tools do not stale it.
+
+The loop maintains bounded task-class memory at
+`.graff/eval-notes/<run_id>.md`. The task class is `--niche` when configured and
+`general` otherwise. Its CONFIRMED, GUESSES, HYPOTHESES TO TEST, FACTS, and
+verifier-history template is re-injected every turn, including after context
+compaction. Eval `note` values can carry labeled belief updates. The directory
+and file use private POSIX permissions, no-follow directory/file opens, bounded
+reads, and atomic replacement. This file is not uploaded by the behavioral or
+learning telemetry mechanisms. It *is* prompt context, so its contents are sent
+to the selected model provider on each eval-driven turn.
+
## Behavioral network upload
The network destination is not a fourth local file and the local JSONL is never
@@ -88,13 +106,12 @@ disables both OTLP and behavioral upload.
Metadata admission is field-based; values of allowed fields are not scanned or
redacted. In particular, initial provider and model identifiers are transmitted
exactly as configured and can themselves contain private labels or path/repository
-fragments. The schema has no dedicated fields for user/system prompts, generated
-model text or hidden reasoning, source, diffs, filesystem paths or repository
-names, tool arguments or results, shell commands, arbitrary environment values,
-credentials, headers, identity, prompt fingerprints, or free-text adapter
-content. Content mode changes typed adapter events: it may include
-`commitment_id`, `action`, `expect`, `reason`, `predicted`, `actual`, and `detail`
-exactly as supplied. There
+fragments. Lifecycle metadata has no dedicated fields for prompts, generated
+text, source, paths, arguments/results, commands, credentials, identity, prompt
+fingerprints, or adapter free text. Rich metadata adds only broad tool class,
+call IDs, byte/duration/error counters, and truncation flags. Content mode may
+add `commitment_id`, `action`, `expect`, `reason`, `predicted`, `actual`,
+`detail`, exact tool names/arguments, and bounded assistant text. There
is no redactor, sanitizer, or secret scanner. The eval-driven loop is the only
built-in production adapter that currently supplies those fields, and it
supplies only static/opaque values (`{kind:"eval"}`, `{pass:<bool>}`,
@@ -106,7 +123,10 @@ endpoint; its public stats expose aggregate totals only. Content-opt-in fields
are isolated from event metadata and expire after 30 days. Metadata rows do not
currently have an automatic expiry. The separately transmitted signed score
signal can carry the same `run_id` for trusted correlation, but uploaded
-behavioral events are not themselves scores and do not enter fleet selection.
+behavioral events are not themselves scores or remote promotion authority. A
+local tournament can submit only its separately signed recomputed aggregates.
+Eval-note memory is a separate local prompt-context file and is never part of
+this behavioral batch.
## File and ordering contract
@@ -248,8 +268,9 @@ observation contradicted a prediction:
The typed call serializes opaque values synchronously rather than borrowing
caller memory. The local file retains their serialized form; explicit content
upload can retain a second copy under the 30-day policy above. Codegraff does not
-check semantic equivalence, prove that a verifier is correct, maintain a
-commitment registry, cancel a plan, or initiate a repair turn.
+check semantic equivalence or prove that a verifier is correct. The eval producer
+binds commitments to verifier outcomes and enforces stop-on-red repair; other
+task adapters must define their own semantics.
### Opt-in rich capture (`GRAFF_BEHAVIOR_TRACE=full`)
@@ -259,11 +280,9 @@ opted into with `GRAFF_BEHAVIOR_TRACE=full`. The default lifecycle-only
posture (any other enabling value, including unset) never emits them — do not
interpret their absence as an empty tool/action history.
-**These four kinds are local-file only.** The Phase 1 collector rejects
-unrecognized kinds for the whole batch, not just one event, so `BehaviorTrace`
-never offers them to the uploader regardless of `GRAFF_BEHAVIOR_UPLOAD` mode.
-This is a documented exclusion, not a drop: it is not counted in
-`dropped_events`, and `local_sink`/`local_dropped` accounting is unaffected.
+The versioned collector accepts all four kinds. Metadata mode receives only the
+content-free projection described above; exact names/arguments/text require the
+separate `GRAFF_BEHAVIOR_UPLOAD=content` opt-in and expire after 30 days.
#### `tool_started`
@@ -310,15 +329,15 @@ once per root turn rather than once per intermediate segment. Fields:
- `text` — the text, capped at 2,048 bytes.
- `text_truncated` — `true` when the text exceeded the cap.
-#### Local privacy posture in full mode
+#### Privacy posture in full mode
In lifecycle-only mode (the default), automatic events never include tool
arguments or model text, as described below. `GRAFF_BEHAVIOR_TRACE=full`
-changes that for the **local plaintext file only**: tool names and arguments,
+changes that for the local plaintext file: tool names and arguments,
and completed assistant text, land there in cleartext, subject only to the
4,096/2,048-byte caps above. There is no redaction or secret scanning. Rich
-capture never changes what is uploaded — the four kinds stay local-only
-regardless of `GRAFF_BEHAVIOR_UPLOAD`.
+capture also enables typed upload projections: metadata stays content-free,
+while exact content requires the second explicit opt-in.
## Local retention and privacy
@@ -348,9 +367,10 @@ explicit content upload scans or sanitizes any of this.
`.graff/behavior/` when they are no longer needed. Git ignore rules do not
prevent backups, artifact collectors, support bundles, workspace-capable
agent tools, or manual uploads from reading or copying them.
-- Behavioral events are not consumed for fleet/DGM selection in Phase 1.
- Public collector visibility is aggregate-only, but the collector retains
- private metadata rows and retains explicit content for up to 30 days.
+- The local tournament consumes only recomputed aggregate tool/behavior scores
+ and keeps manual promotion as the default. Public collector visibility is
+ aggregate-only; private metadata remains, while explicit content expires
+ after 30 days.
## Example
@@ -384,7 +404,7 @@ the converted stream reproduces its published 100.0 RHAE exactly (the issue
#246 validation criterion). CI runs a hermetic version of the same round trip
plus the live-session audit in `scripts/test-behavior-trace.py`.
-## Deferred work for the full issue
+## Remaining extensions
A complete predict–verify implementation still needs:
@@ -395,10 +415,13 @@ A complete predict–verify implementation still needs:
still only fires once per root turn (the one choke point common to every
provider streaming path), not once per intermediate assistant text
segment — a real per-segment hook remains open work.
-3. Explicit expectation binding, verification, surprise interruption, and
- repair behavior wired to a production producer.
-4. Versioned Zig-side behavioral score events plus recipe/eval identity and
- trace-integrity metadata (the stdlib auditor above recomputes metrics and
- replay scores, but no built-in run emits a score-bearing outcome yet).
-5. Admission of only trusted recomputed scores into eval, fleet, MAP-Elites,
- and DGM selection.
+3. The eval producer now has explicit expectation binding, verification,
+ stop-on-red interruption, task-class notes, repair resumption, and a
+ completion gate. Equivalent semantics for non-eval task adapters remain
+ open.
+4. The bundled prompt tournament now recomputes and audits tool-call counts
+ and a bounded successful-tool-completion score from each closed rich
+ behavioral stream. Tool economy remains the first tie-break after
+ correctness; the behavioral score is the next tie-break and is surfaced in
+ local aggregate evidence and the signed aggregate receipt. General
+ task-specific behavioral scores still need trusted task adapters.
diff --git a/docs/local-learning.md b/docs/local-learning.md
index c85b0f40..adbee6fb 100644
--- a/docs/local-learning.md
+++ b/docs/local-learning.md
@@ -476,8 +476,8 @@ requires an aggregate-or-higher learning ceiling, selected with
`/privacy aggregate`. The root-only `learn_candidate` tool can instead request
one explicit bundled aggregate submission without changing the session mode. An explicit `--submit` or
`learn submit` publishes the existing signed score plus a separately signed
-`codegraff.learn.grade.v1` receipt: fixed aggregate pass/delta/significance,
-regression, tool/cost/latency, gate (including economy-gate enablement), and
+`codegraff.learn.grade.v3` receipt: fixed aggregate pass/delta/significance,
+regression, tool/cost/latency, recomputed behavioral score, gate (including economy-gate enablement), and
eligibility fields; short parent/child fingerprints; run/suite/cohort metadata;
and content-addressed evidence IDs. It
does not publish prompt text, tasks, adapter input/output, repository data, raw
@@ -498,6 +498,18 @@ The bundled evaluator transfers parent and child prompts to its local Graff
process through the JSON stdin control channel, not command-line arguments, so
the full prompt is not exposed by ordinary process listings.
+Each inner evaluation enables a rich behavioral trace only inside its disposable
+private scratch workspace while disabling network telemetry. After a terminal
+turn, the pinned stdlib scorer audits sequence integrity and clean closure,
+recomputes the tool-call count from paired tool events, and requires it to match
+the evaluator protocol count. It also derives a bounded successful-tool-
+completion score from those events. The recomputed count is the first
+tool-economy input after correctness ties; the behavioral score is the next
+tie-break and appears in local candidate summaries. An absent, incomplete,
+invalid, or disagreeing stream fails the bounded attempt instead of silently
+trusting the process counter; the scratch workspace and content-bearing trace
+are then removed.
+
Once activated, the learned prompt is used like any other agent prompt:
- it is sent to the selected model provider when that agent runs;
@@ -536,7 +548,9 @@ arm map uses `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, and
`gpt-5.4-mini`; all prompts are evaluated by the same pinned cohort. The
mutator intentionally sends the parent prompt to those providers, while inner
agent telemetry is disabled and only prompt-free signed aggregate tournament
-grades are submitted. The generated config keeps automatic promotion off.
+grades are submitted. The generated config pins both the behavioral auditor and
+its scorer as evaluator inputs. The generated config keeps automatic promotion
+off.
## Collective learning: aggregate receipts, not promotion authority
diff --git a/docs/releases/v0.0.215.md b/docs/releases/v0.0.215.md
index 0516abb6..3df2a998 100644
--- a/docs/releases/v0.0.215.md
+++ b/docs/releases/v0.0.215.md
@@ -21,6 +21,21 @@ and connects Streamable HTTP tools without a Node bridge.
- Adapter programs and declared inputs are hashed, copied into private scratch,
and executed from the verified snapshots. Timeouts clean up descendant
processes as well as their parent.
+- Inner evaluations now audit a clean, closed behavioral stream and recompute
+ tool calls plus successful-tool-completion scores from paired events.
+ Correctness still ranks first, then tool economy, then behavioral score.
+ Local reports surface the aggregate evidence; protocol/trace disagreement
+ fails the attempt.
+
+## Enforceable eval repair loop
+
+- `eval` runs as a solo verifier boundary. Red results drop the current plan
+ and stop the model turn; the next turn resumes in repair mode.
+- Completion requires a green verifier result for the latest workspace state.
+ A later mutating tool makes that result stale.
+- Private, atomic task-class eval notes are re-injected every turn so confirmed
+ facts and hypotheses survive compaction. They are not telemetry, but they are
+ sent to the selected model provider as prompt context.
## Explicit, revocable aggregate sharing
diff --git a/examples/learn_behavior_metrics.py b/examples/learn_behavior_metrics.py
new file mode 100644
index 00000000..aa828ddc
--- /dev/null
+++ b/examples/learn_behavior_metrics.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python3
+"""Recompute trusted tournament metrics from a completed behavioral stream."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+
+def audited_behavior_metrics(workspace: Path, observed_tool_calls: int) -> dict[str, int | bool]:
+ """Return bounded metrics recomputed from one closed behavioral stream."""
+ scorer = os.environ.get("GRAFF_LEARN_INPUT_3")
+ if not scorer:
+ return {"measured": False, "tool_calls": observed_tool_calls, "score_ppm": 0}
+ traces = sorted((workspace / ".graff" / "behavior").glob("*.jsonl"))
+ if len(traces) != 1:
+ raise RuntimeError("expected exactly one behavioral stream")
+ completed = subprocess.run(
+ [sys.executable, scorer, str(traces[0])],
+ text=True,
+ capture_output=True,
+ timeout=15,
+ check=False,
+ )
+ if completed.returncode != 0:
+ raise RuntimeError("behavioral stream failed its recomputable audit")
+ try:
+ report = json.loads(completed.stdout)
+ except json.JSONDecodeError as exc:
+ raise RuntimeError("behavioral scorer returned invalid JSON") from exc
+ if not isinstance(report, dict) or report.get("ok") is not True:
+ raise RuntimeError("behavioral scorer did not attest the stream")
+ if report.get("complete") is not True or report.get("terminal_status") != "closed":
+ raise RuntimeError("behavioral stream did not close cleanly")
+ tool_calls = report.get("tool_calls")
+ if not isinstance(tool_calls, int) or tool_calls < 0:
+ raise RuntimeError("behavioral scorer omitted tool_calls")
+ if tool_calls != observed_tool_calls:
+ raise RuntimeError("protocol and behavioral tool counts disagree")
+ tool_errors = report.get("tool_errors")
+ if not isinstance(tool_errors, int) or not 0 <= tool_errors <= tool_calls:
+ raise RuntimeError("behavioral scorer returned invalid tool_errors")
+ score_ppm = 1_000_000 if tool_calls == 0 else round(
+ (tool_calls - tool_errors) * 1_000_000 / tool_calls
+ )
+ return {"measured": True, "tool_calls": tool_calls, "score_ppm": score_ppm}
+
+
+def audited_tool_calls(workspace: Path, observed_tool_calls: int) -> int:
+ """Backward-compatible exact-count adapter."""
+ return int(audited_behavior_metrics(workspace, observed_tool_calls)["tool_calls"])
diff --git a/examples/learn_graff_case.py b/examples/learn_graff_case.py
new file mode 100644
index 00000000..0b2570fe
--- /dev/null
+++ b/examples/learn_graff_case.py
@@ -0,0 +1,32 @@
+#!/usr/bin/env python3
+"""Case-verdict and cost helpers for the pinned Graff tournament evaluator."""
+
+from __future__ import annotations
+
+from pathlib import Path
+import subprocess
+from typing import Any
+
+
+def check_case(case: dict[str, Any], text: str, cwd: Path) -> bool:
+ check = case.get("check")
+ if not isinstance(check, dict):
+ raise ValueError("case check must be an object")
+ if isinstance(check.get("exact"), str):
+ return text.strip() == check["exact"]
+ if isinstance(check.get("substring"), str):
+ return check["substring"] in text
+ if isinstance(check.get("cmd"), str):
+ completed = subprocess.run(
+ ["sh", "-c", check["cmd"]], cwd=cwd,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10, check=False,
+ )
+ return completed.returncode == 0
+ raise ValueError("case has no supported check")
+
+
+def reported_cost_micros(event: dict[str, Any]) -> int:
+ try:
+ return max(0, round(float(event.get("cost_usd", 0.0) or 0.0) * 1_000_000))
+ except (TypeError, ValueError, OverflowError):
+ return 0
diff --git a/examples/learn_graff_evaluator.py b/examples/learn_graff_evaluator.py
index 10c97a87..e2b496a3 100755
--- a/examples/learn_graff_evaluator.py
+++ b/examples/learn_graff_evaluator.py
@@ -7,6 +7,7 @@ import hashlib
import json
import os
from pathlib import Path
+import runpy
import shutil
import subprocess
import sys
@@ -15,7 +16,6 @@ import threading
import time
from typing import Any, Callable
-
REQUEST_SCHEMA = "codegraff.learn.evaluation.request.v1"
RESPONSE_SCHEMA = "codegraff.learn.evaluation.response.v1"
BASELINE_REQUEST_SCHEMA = "codegraff.learn.primary-baseline.request.v1"
@@ -27,7 +27,6 @@ ATTEMPT_SCHEMA = "codegraff.learn.evaluator-attempt.v1"
METRIC_FIELDS = ("latency_ms", "tool_calls", "cost_micros")
MAX_EXACT_INTEGER = 9_007_199_254_740_991
-
class EvaluationAttemptError(Exception):
"""A bounded model turn failed before producing gradeable evidence."""
@@ -44,26 +43,22 @@ class EvaluationAttemptError(Exception):
self.tool_calls = max(0, tool_calls)
self.cost_micros = max(0, cost_micros)
-
def fail(message: str) -> "NoReturn":
print(f"learn_graff_evaluator: {message}", file=sys.stderr)
raise SystemExit(2)
-
def load_json(path: Path) -> Any:
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
fail(f"cannot read {path}: {exc}")
-
def request_pairs(request: dict[str, Any]) -> list[dict[str, Any]]:
pairs = request.get("pairs")
if not isinstance(pairs, list) or any(not isinstance(pair, dict) for pair in pairs):
fail("request pairs must be an object array")
return pairs
-
def load_progress(
path: Path,
request_path: Path,
@@ -85,7 +80,6 @@ def load_progress(
fail("evaluator progress is not a valid pair prefix")
return request_sha256, results
-
def save_json_atomic(path: Path, value: Any) -> None:
temporary = path.with_name(path.name + ".tmp")
with temporary.open("w", encoding="utf-8") as output:
@@ -100,7 +94,6 @@ def save_json_atomic(path: Path, value: Any) -> None:
finally:
os.close(directory)
-
def save_progress(path: Path, request_sha256: str, results: list[dict[str, Any]]) -> None:
save_json_atomic(path, {
"schema": PROGRESS_SCHEMA,
@@ -108,18 +101,15 @@ def save_progress(path: Path, request_sha256: str, results: list[dict[str, Any]]
"results": results,
})
-
def zero_metrics() -> dict[str, int]:
return {field: 0 for field in METRIC_FIELDS}
-
def add_metrics(left: dict[str, int], right: dict[str, int]) -> dict[str, int]:
return {
field: min(MAX_EXACT_INTEGER, max(0, left[field]) + max(0, right[field]))
for field in METRIC_FIELDS
}
-
def attempt_key(
request_sha256: str,
pair: dict[str, Any],
@@ -135,7 +125,6 @@ def attempt_key(
], separators=(",", ":")).encode("utf-8")
return hashlib.sha256(b"codegraff-learn/attempt/v1\0" + framed).hexdigest()
-
def load_attempt(path: Path, key: str) -> tuple[dict[str, int], dict[str, Any] | None]:
if not path.exists():
return zero_metrics(), None
@@ -161,7 +150,6 @@ def load_attempt(path: Path, key: str) -> tuple[dict[str, int], dict[str, Any] |
fail("invalid completed evaluator attempt")
return normalized, dict(result)
-
def save_attempt(
path: Path,
key: str,
@@ -176,11 +164,9 @@ def save_attempt(
"result": result,
})
-
def clear_attempt(path: Path) -> None:
path.unlink(missing_ok=True)
-
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")
@@ -195,7 +181,6 @@ def validate_settings(value: Any) -> dict[str, Any]:
fail("max_attempts must be at most 3")
return value
-
def send(proc: subprocess.Popen[str], value: dict[str, Any], expected: str) -> dict[str, Any]:
assert proc.stdin is not None and proc.stdout is not None
proc.stdin.write(json.dumps(value, separators=(",", ":")) + "\n")
@@ -213,7 +198,6 @@ def send(proc: subprocess.Popen[str], value: dict[str, Any], expected: str) -> d
return event
fail(f"Graff exited before {expected}")
-
def safe_setup(root: Path, files: Any) -> None:
if files is None:
return
@@ -238,30 +222,6 @@ def executable_snapshot(source: Path) -> Path:
return target
-def check_case(case: dict[str, Any], text: str, cwd: Path) -> bool:
- check = case.get("check")
- if not isinstance(check, dict):
- fail("case check must be an object")
- if isinstance(check.get("exact"), str):
- return text.strip() == check["exact"]
- if isinstance(check.get("substring"), str):
- return check["substring"] in text
- if isinstance(check.get("cmd"), str):
- completed = subprocess.run(
- ["sh", "-c", check["cmd"]], cwd=cwd,
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10, check=False,
- )
- return completed.returncode == 0
- fail("case has no supported check")
-
-
-def reported_cost_micros(event: dict[str, Any]) -> int:
- try:
- return max(0, round(float(event.get("cost_usd", 0.0) or 0.0) * 1_000_000))
- except (TypeError, ValueError, OverflowError):
- return 0
-
-
def run_variant(
graff: Path,
settings: dict[str, Any],
@@ -270,9 +230,11 @@ def run_variant(
cwd: Path,
observe: Callable[[dict[str, int]], None] | None = None,
) -> dict[str, Any]:
+ support_path = os.environ.get("GRAFF_LEARN_INPUT_4")
+ support = runpy.run_path(support_path or str(Path(__file__).with_name("learn_graff_case.py")))
env = os.environ.copy()
env["GRAFF_NO_TELEMETRY"] = "1"
- env["GRAFF_BEHAVIOR_TRACE"] = "0"
+ env["GRAFF_BEHAVIOR_TRACE"] = "full"
env["HARNESS_CLIENT"] = "learn-evaluator"
env.pop("OTEL_EXPORTER_OTLP_ENDPOINT", None)
env.pop("GRAFF_OTEL_ENDPOINT", None)
@@ -315,7 +277,7 @@ def run_variant(
if not isinstance(event, dict):
continue
if "cost_usd" in event:
- cost_micros = reported_cost_micros(event)
+ cost_micros = support["reported_cost_micros"](event)
if event.get("type") == "tool_call":
tool_calls += 1
if observe is not None:
@@ -363,13 +325,29 @@ def run_variant(
tool_calls=tool_calls,
cost_micros=cost_micros,
)
- passed = check_case(case, str(final.get("text", "")), cwd)
+ behavior = {"measured": False, "score_ppm": 0}
+ metrics_module = os.environ.get("GRAFF_LEARN_INPUT_2")
+ if metrics_module:
+ try:
+ behavior = runpy.run_path(metrics_module)["audited_behavior_metrics"](cwd, tool_calls)
+ tool_calls = behavior["tool_calls"]
+ except (OSError, RuntimeError, subprocess.SubprocessError) as exc:
+ raise EvaluationAttemptError(
+ f"behavioral metric audit failed: {exc}",
+ latency_ms=latency_ms, tool_calls=tool_calls, cost_micros=cost_micros,
+ ) from exc
+ try:
+ passed = support["check_case"](case, str(final.get("text", "")), cwd)
+ except ValueError as exc:
+ fail(str(exc))
return {
"pass": passed,
"score_ppm": 1_000_000 if passed else 0,
"cost_micros": cost_micros,
"latency_ms": latency_ms,
"tool_calls": tool_calls,
+ "behavior_measured": behavior["measured"],
+ "behavior_score_ppm": behavior["score_ppm"],
}
@@ -468,6 +446,8 @@ def evaluate(settings_path: Path, graff: Path, request_path: Path, response_path
"latency_measured": True,
"tool_calls_measured": True,
"parent_tool_calls": parent_run["tool_calls"], "child_tool_calls": child_run["tool_calls"],
+ "behavior_measured": bool(parent_run.get("behavior_measured")) and bool(child_run.get("behavior_measured")),
+ "parent_behavior_score_ppm": parent_run.get("behavior_score_ppm", 0), "child_behavior_score_ppm": child_run.get("behavior_score_ppm", 0),
})
save_progress(progress_path, request_sha256, results)
clear_attempt(Path(".attempt-parent.json"))
@@ -506,6 +486,7 @@ def evaluate_baseline(settings_path: Path, graff: Path, request_path: Path, resp
"cost_micros": run["cost_micros"], "latency_ms": run["latency_ms"],
"latency_measured": True, "tool_calls_measured": True,
"tool_calls": run["tool_calls"],
+ "behavior_measured": bool(run.get("behavior_measured")), "behavior_score_ppm": run.get("behavior_score_ppm", 0),
})
save_progress(progress_path, request_sha256, results)
clear_attempt(journal)
@@ -554,6 +535,8 @@ def evaluate_primary(settings_path: Path, graff: Path, request_path: Path, respo
"latency_measured": bool(parent_run.get("latency_measured")),
"tool_calls_measured": bool(parent_run.get("tool_calls_measured")),
"parent_tool_calls": parent_run.get("tool_calls", 0), "child_tool_calls": child_run["tool_calls"],
+ "behavior_measured": bool(parent_run.get("behavior_measured")) and bool(child_run.get("behavior_measured")),
+ "parent_behavior_score_ppm": parent_run.get("behavior_score_ppm", 0), "child_behavior_score_ppm": child_run.get("behavior_score_ppm", 0),
})
save_progress(progress_path, request_sha256, results)
clear_attempt(journal)
diff --git a/examples/prepare_graff_tournament.py b/examples/prepare_graff_tournament.py
index cf43b2cb..5ab175c2 100755
--- a/examples/prepare_graff_tournament.py
+++ b/examples/prepare_graff_tournament.py
@@ -70,7 +70,10 @@ def main() -> None:
arms = (repo / "examples" / "learn_graff_arms.json").resolve()
evaluator = (repo / "examples" / "learn_graff_evaluator.py").resolve()
evaluator_settings = (repo / "examples" / "learn_graff_evaluator.json").resolve()
- for path in (graff, mutator, arms, evaluator, evaluator_settings):
+ behavior_metrics = (repo / "examples" / "learn_behavior_metrics.py").resolve()
+ behavior_scorer = (repo / "scripts" / "score_run.py").resolve()
+ case_support = (repo / "examples" / "learn_graff_case.py").resolve()
+ for path in (graff, mutator, arms, evaluator, evaluator_settings, behavior_metrics, behavior_scorer, case_support):
if not path.is_file():
raise FileNotFoundError(path)
@@ -100,7 +103,8 @@ def main() -> None:
},
"evaluator": {
**program_pin(evaluator), "args": [str(evaluator_settings), str(graff)],
- "inputs": [pin(evaluator_settings), pin(graff)], "pass_env": ["CODEX_HOME"],
+ "inputs": [pin(evaluator_settings), pin(graff), pin(behavior_metrics), pin(behavior_scorer), pin(case_support)],
+ "pass_env": ["CODEX_HOME"],
},
"evaluation_suite": pin(primary),
"holdout_suite": pin(holdout),
@@ -118,7 +122,7 @@ def main() -> None:
"default_repetitions": 1,
},
"auto": {"enabled": False},
- "cohort": {"provider": "codex", "model": "gpt-5.4-mini", "task_family": "coding-flow", "adapter_version": "graff-eval-v7", "verifier_version": "clustered-exact-v6"},
+ "cohort": {"provider": "codex", "model": "gpt-5.4-mini", "task_family": "coding-flow", "adapter_version": "graff-eval-v8", "verifier_version": "behavior-audited-v7"},
}
config_path = output / "config.json"
write_json(config_path, config)
diff --git a/src/agent.zig b/src/agent.zig
index de1bad32..8f72135c 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -138,6 +138,8 @@ pub const Agent = struct {
eval_judge: ?[]const u8 = null, // --judge: LLM-as-judge rubric, min()-blended with the --eval score (runJudge). Dormant until a CLI flag sets it.
eval_iter: u32 = 0, // eval-loop iteration counter (scores log)
eval_best: f64 = -1, // best score seen this session (-1 = none yet)
+ eval_verified: bool = false, // latest workspace state has a target-meeting verifier result
+ eval_repair_pending: bool = false, // a contradiction blocks completion until a fresh green eval
strict: bool = false,
completed: ?[]const u8 = null,
last_context_tokens: u64 = 0,
diff --git a/src/agent_eval.zig b/src/agent_eval.zig
index 1ab07e18..9e7e8b77 100644
--- a/src/agent_eval.zig
+++ b/src/agent_eval.zig
@@ -19,6 +19,7 @@ const signScore = scoring.signScore;
const telemetry = @import("telemetry.zig");
const runCapped = @import("jobs.zig").runCapped;
const judgeTask = @import("subagent.zig").judgeTask;
+const eval_memory = @import("eval_memory.zig");
test {
_ = @import("agent_eval_tests.zig");
@@ -53,6 +54,9 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {
// leaving a dangling turn_committed that a scorer would misread as
// an unresolved success.
if (behavior) |bt| bt.recordMisprediction(eval_turn, commitment_id, .{ .pass = true }, .{ .pass = false, .exit = @as(i32, -1) }, "eval command could not run");
+ self.eval_verified = false;
+ self.eval_repair_pending = true;
+ eval_memory.record(self, note, null, -1, false);
return .{ .text = try std.fmt.allocPrint(self.arena, "eval command could not run: {t}", .{e}), .is_error = true };
};
defer self.gpa.free(run.stdout);
@@ -83,6 +87,8 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {
if (self.eval_best < 0 or s > self.eval_best) self.eval_best = s;
}
const met = if (combined) |s| s >= target_f else false;
+ self.eval_repair_pending = exit_code != 0 or !met;
+ self.eval_verified = !self.eval_repair_pending;
// Resolve the commitment made above: a nonzero exit or an unmet/unparsed
// target contradicts "this command will meet the target", so it is a
// misprediction. Meeting the target leaves the commitment unresolved by
@@ -91,6 +97,7 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {
if (behavior) |bt| if (exit_code != 0 or !met)
bt.recordMisprediction(eval_turn, commitment_id, .{ .pass = true }, .{ .pass = false, .exit = exit_code }, "target not met");
self.appendEvalLog(note, det, judge, combined, exit_code, met) catch {};
+ eval_memory.record(self, note, combined, exit_code, met);
// Feed the eval-driven score into the fleet (docs/hyperagents.md §9.B):
// on a NEW BEST, submit the genome (this agent's persona) with its achieved
@@ -162,11 +169,11 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {
try w.print("eval #{d}: score {d:.1}/100 (best {d:.1}, target {d}). ", .{ self.eval_iter, s, self.eval_best, self.eval_target });
}
if (met)
- try w.writeAll("TARGET MET - finish and report the final scores.")
+ try w.writeAll("TARGET MET - verifier gate is green; finish only if no workspace-changing tool runs after this eval.")
else if (improved)
- try w.writeAll("Improved - keep going: fix the next biggest failure with one focused change.")
+ try w.writeAll("Improved, but still red - the prior plan is dropped. Make one focused repair, then run eval again; completion is blocked.")
else
- try w.writeAll("No gain over the best - try a different change; do not build on a regression.");
+ try w.writeAll("No gain - the prior plan is dropped. Repair from current evidence and re-run eval; completion is blocked.");
} else if (self.eval_judge != null and det != null and judge == null) {
try w.print("eval #{d}: deterministic score {d:.1}/100, but the judge returned no parseable score (it may have errored). Re-run after checking the rubric. ", .{ self.eval_iter, det.? });
} else {
diff --git a/src/agent_eval_control.zig b/src/agent_eval_control.zig
new file mode 100644
index 00000000..740cc716
--- /dev/null
+++ b/src/agent_eval_control.zig
@@ -0,0 +1,35 @@
+//! Tool-batch policy for the eval-driven predict -> verify -> repair loop.
+
+const std = @import("std");
+const ToolCall = @import("tools.zig").ToolCall;
+const isMetaName = @import("schema.zig").isMetaName;
+const companionReadOnly = @import("skills.zig").companionReadOnly;
+
+pub const verifier_boundary =
+ "eval is a verifier boundary and must run alone; this tool was not executed";
+pub const verifier_hard_stop =
+ "VERIFIER RED: the committed plan was dropped. Start a repair turn, make one focused repair, then rerun eval before completion.";
+
+pub fn evalCallIndex(calls: []const ToolCall) ?usize {
+ for (calls, 0..) |call, index| {
+ if (std.mem.eql(u8, call.name, "eval")) return index;
+ }
+ return null;
+}
+
+pub fn shouldStopAfterBatch(calls: []const ToolCall, repair_pending: bool) bool {
+ return repair_pending and evalCallIndex(calls) != null;
+}
+
+pub fn toolInvalidatesEval(call: ToolCall) bool {
+ if (isMetaName(call.name)) return false;
+ if (std.mem.eql(u8, call.name, "read_file") or
+ std.mem.eql(u8, call.name, "codedb") or
+ std.mem.eql(u8, call.name, "bash_output") or
+ std.mem.eql(u8, call.name, "bash_kill"))
+ {
+ return false;
+ }
+ if (std.mem.startsWith(u8, call.name, "mcp__")) return !companionReadOnly(call.name, call.input);
+ return true;
+}
diff --git a/src/agent_eval_control_tests.zig b/src/agent_eval_control_tests.zig
new file mode 100644
index 00000000..680bca06
--- /dev/null
+++ b/src/agent_eval_control_tests.zig
@@ -0,0 +1,116 @@
+//! Enforceable predict -> verify -> repair controller tests.
+
+const std = @import("std");
+const Agent = @import("agent.zig").Agent;
+const agent_tools = @import("agent_tools.zig");
+const eval_control = @import("agent_eval_control.zig");
+const repl_glue = @import("repl_glue.zig");
+const ToolCall = @import("tools.zig").ToolCall;
+
+fn call(arena: std.mem.Allocator, name: []const u8, input: []const u8) !ToolCall {
+ const value = try std.json.parseFromSliceLeaky(std.json.Value, arena, input, .{});
+ return .{ .id = "control-test", .name = name, .input = value };
+}
+
+test "attempt_completion is blocked until the latest verifier result is green" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var agent: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = arena,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = true,
+ .label = "test",
+ .out = null,
+ .eval_cmd = "verify",
+ };
+ const completion = try call(arena, "attempt_completion", "{\"result\":\"done\"}");
+
+ const unverified = try agent.handleMeta(completion);
+ try std.testing.expect(unverified.is_error);
+ try std.testing.expect(agent.completed == null);
+
+ agent.eval_verified = true;
+ agent.eval_repair_pending = true;
+ const red = try agent.handleMeta(completion);
+ try std.testing.expect(red.is_error);
+ try std.testing.expect(agent.completed == null);
+
+ agent.eval_repair_pending = false;
+ const green = try agent.handleMeta(completion);
+ try std.testing.expect(!green.is_error);
+ try std.testing.expectEqualStrings("done", agent.completed.?);
+}
+
+test "workspace-changing tools stale verification while read-only tools do not" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ try std.testing.expect(agent_tools.toolInvalidatesEval(try call(arena, "edit_file", "{}")));
+ try std.testing.expect(agent_tools.toolInvalidatesEval(try call(arena, "bash", "{}")));
+ try std.testing.expect(agent_tools.toolInvalidatesEval(try call(arena, "subagent", "{}")));
+ try std.testing.expect(!agent_tools.toolInvalidatesEval(try call(arena, "read_file", "{}")));
+ try std.testing.expect(!agent_tools.toolInvalidatesEval(try call(arena, "codedb", "{}")));
+ try std.testing.expect(!agent_tools.toolInvalidatesEval(try call(arena, "mcp__codedbpro__read", "{}")));
+ try std.testing.expect(agent_tools.toolInvalidatesEval(try call(arena, "mcp__codedbpro__edit", "{}")));
+}
+
+test "eval is a solo verifier boundary in a tool batch" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const calls = [_]ToolCall{
+ try call(arena, "edit_file", "{}"),
+ try call(arena, "eval", "{}"),
+ try call(arena, "read_file", "{}"),
+ };
+ try std.testing.expectEqual(@as(?usize, 1), eval_control.evalCallIndex(&calls));
+ try std.testing.expectEqualStrings(
+ "eval is a verifier boundary and must run alone; this tool was not executed",
+ eval_control.verifier_boundary,
+ );
+ try std.testing.expect(eval_control.shouldStopAfterBatch(&calls, true));
+ try std.testing.expect(!eval_control.shouldStopAfterBatch(&calls, false));
+
+ var output: std.Io.Writer.Allocating = .init(std.testing.allocator);
+ defer output.deinit();
+ var agent: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = arena,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = true,
+ .label = "test",
+ .out = &output.writer,
+ };
+ const results = try agent.runTools(&calls);
+ try std.testing.expect(results[0].is_error);
+ try std.testing.expectEqualStrings(eval_control.verifier_boundary, results[0].text);
+ try std.testing.expect(results[1].is_error);
+ try std.testing.expect(std.mem.indexOf(u8, results[1].text, "no eval command configured") != null);
+ try std.testing.expect(results[2].is_error);
+ try std.testing.expectEqualStrings(eval_control.verifier_boundary, results[2].text);
+}
+
+test "eval steering carries controller state and local belief memory" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const note = try repl_glue.evalSteeringNote(
+ arena_state.allocator(),
+ "verify",
+ 90,
+ false,
+ true,
+ true,
+ "## CONFIRMED\n- compiler failed",
+ );
+ try std.testing.expect(std.mem.indexOf(u8, note, "Verifier state: RED") != null);
+ try std.testing.expect(std.mem.indexOf(u8, note, "prior plan is dropped") != null);
+ try std.testing.expect(std.mem.indexOf(u8, note, "compiler failed") != null);
+}
diff --git a/src/agent_eval_tests.zig b/src/agent_eval_tests.zig
index fc2e7103..fbe175aa 100644
--- a/src/agent_eval_tests.zig
+++ b/src/agent_eval_tests.zig
@@ -74,11 +74,23 @@ test "runEval: commits before the command runs, mispredicts on a missed target,
const failure = try agent.runEval("");
try std.testing.expect(!failure.is_error);
try std.testing.expectEqual(@as(u32, 1), agent.eval_iter);
+ try std.testing.expect(!agent.eval_verified);
+ try std.testing.expect(agent.eval_repair_pending);
+ try std.testing.expect(agent.completed == null);
agent.eval_cmd = "printf 'score: 100\\n'";
const success = try agent.runEval("");
try std.testing.expect(!success.is_error);
try std.testing.expectEqual(@as(u32, 2), agent.eval_iter);
+ try std.testing.expect(agent.eval_verified);
+ try std.testing.expect(!agent.eval_repair_pending);
+ try std.testing.expect(agent.completed == null);
+ const notes = try Io.Dir.cwd().readFileAlloc(io, ".graff/eval-notes/session.md", gpa, .limited(16 * 1024));
+ defer gpa.free(notes);
+ try std.testing.expect(std.mem.indexOf(u8, notes, "eval #1") != null);
+ try std.testing.expect(std.mem.indexOf(u8, notes, "met=no") != null);
+ try std.testing.expect(std.mem.indexOf(u8, notes, "eval #2") != null);
+ try std.testing.expect(std.mem.indexOf(u8, notes, "met=yes") != null);
const out = aw.writer.buffered();
var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, out, "\n"), '\n');
diff --git a/src/agent_request.zig b/src/agent_request.zig
index ded9f488..356a336a 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -92,7 +92,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
self.last_request_context_overflow = false;
self.last_request_write_failed = false;
self.last_usage_includes_output = false;
- var force = self.strict and tools != null;
+ var force = (self.strict or self.eval_cmd != null) and tools != null;
var stream_usage = true; // openai stream_options; dropped if rejected
var auth_refreshed = false; // #148: at most one forced token refresh + retry
// #124: reclaim last request's transient parse garbage FIRST, so everything
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index 91eb5dfe..68ff9964 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -19,6 +19,7 @@ const ToolCall = tools_mod.ToolCall;
const messages_mod = @import("messages.zig");
const util = @import("util.zig");
+const eval_control = @import("agent_eval_control.zig");
const toolResultMessage = messages_mod.toolResultMessage;
fn surfaceUnstreamedText(self: *Agent, text: []const u8) !void {
@@ -92,6 +93,7 @@ pub fn stepResponses(self: *Agent, response: std.json.ObjectMap) !?[]const u8 {
const fco = try toolResultMessage(self.arena, .responses, call.id, r.text, r.is_error);
try self.messages.append(fco);
}
+ if (eval_control.shouldStopAfterBatch(calls.items, self.eval_repair_pending)) return eval_control.verifier_hard_stop;
if (self.completed) |result| return result;
return null;
}
@@ -147,6 +149,7 @@ pub fn stepAnthropic(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
try user_msg.put(self.arena, "content", .{ .array = blocks });
try self.messages.append(.{ .object = user_msg });
+ if (eval_control.shouldStopAfterBatch(calls.items, self.eval_repair_pending)) return eval_control.verifier_hard_stop;
if (self.completed) |result| return result;
return null; // loop again
}
@@ -201,6 +204,7 @@ pub fn stepOpenAI(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
const tool_msg = try toolResultMessage(self.arena, .openai, call.id, r.text, r.is_error);
try self.messages.append(tool_msg);
}
+ if (eval_control.shouldStopAfterBatch(calls.items, self.eval_repair_pending)) return eval_control.verifier_hard_stop;
if (self.completed) |result| return result;
return null;
}
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 7d5295d9..28d4cbc8 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -28,6 +28,8 @@ const tty = terminal.tty;
const schema = @import("schema.zig");
const isMetaName = schema.isMetaName;
+const eval_control = @import("agent_eval_control.zig");
+pub const toolInvalidatesEval = eval_control.toolInvalidatesEval;
pub const gateTool = @import("agent_tool_gate.zig").gateTool;
pub const firstWord = @import("agent_tool_gate.zig").firstWord;
@@ -44,6 +46,10 @@ const tool_results_dir = ".graff/tool-results";
pub const tool_preview_chars: usize = 2_000;
var tool_result_seq: std.atomic.Value(u64) = .init(0);
+test {
+ _ = @import("agent_eval_control_tests.zig");
+}
+
pub fn toolPreviewText(arena: std.mem.Allocator, text: []const u8, path: ?[]const u8) ![]const u8 {
if (text.len <= tool_preview_chars) return arena.dupe(u8, text);
const marker = if (path) |p|
@@ -81,11 +87,30 @@ const rawNonblockStdin = Agent.rawNonblockStdin;
/// are returned in call order, arena-owned.
pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
const results = try self.arena.alloc(ExecResult, calls.len);
+ const eval_index = eval_control.evalCallIndex(calls);
+ var batch_may_change_workspace = false;
+ for (calls) |call| {
+ if (toolInvalidatesEval(call)) {
+ batch_may_change_workspace = true;
+ break;
+ }
+ }
// Collect the indices of external (non-meta) calls for parallel exec.
var ext_idx: std.ArrayList(usize) = .empty;
defer ext_idx.deinit(self.gpa);
for (calls, 0..) |call, i| {
+ if (eval_index) |verifier| if (i != verifier) {
+ self.emitToolRejected(call, "verifier_boundary", eval_control.verifier_boundary);
+ results[i] = .{ .text = eval_control.verifier_boundary, .is_error = true };
+ continue;
+ };
+ if (batch_may_change_workspace and std.mem.eql(u8, call.name, "attempt_completion")) {
+ const message = "attempt_completion must be a separate post-verification action; this batch also contains a workspace-changing tool";
+ self.emitToolRejected(call, "eval_stale", message);
+ results[i] = .{ .text = message, .is_error = true };
+ continue;
+ }
if (try self.rejectToolCall(call)) |denied| {
results[i] = denied;
continue;
@@ -150,6 +175,10 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
// inspectable on disk and the short preview carries its pointer.
const detail = persistToolResult(self, output.text);
results[i] = .{ .text = try toolPreviewText(self.arena, output.text, detail), .is_error = output.is_error, .ms = output.ms };
+ if (self.eval_cmd != null and toolInvalidatesEval(calls[i])) {
+ self.eval_verified = false;
+ self.eval_repair_pending = false;
+ }
}
}
// Show a compact ✓/✗ + preview for each non-meta call (no-op for subs).
@@ -244,6 +273,13 @@ fn clockSleepInterruptedText(arena: std.mem.Allocator, elapsed_ms: i64) ![]const
/// Handle a meta tool inline on the agent's own thread.
pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
if (std.mem.eql(u8, call.name, "attempt_completion")) {
+ if (self.eval_cmd != null and (!self.eval_verified or self.eval_repair_pending)) {
+ const message = if (self.eval_repair_pending)
+ "completion blocked: the latest verifier contradicted the plan; repair the failure and run eval until it meets the target"
+ else
+ "completion blocked: workspace state is not verified; run eval and meet the target after the final change";
+ return .{ .text = message, .is_error = true };
+ }
const result = if (call.input.object.get("result")) |r| r.string else "";
self.completed = try self.arena.dupe(u8, result);
// Skip the re-print only when the result streamed live in full.
diff --git a/src/behavior_trace.zig b/src/behavior_trace.zig
index f6116b19..773f56f3 100644
--- a/src/behavior_trace.zig
+++ b/src/behavior_trace.zig
@@ -9,6 +9,7 @@ const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const behavior_upload = @import("behavior_upload.zig");
+const types = @import("behavior_trace_types.zig");
const session_start = @import("session_start.zig");
const scoring = @import("scoring.zig");
const trace = @import("trace.zig");
@@ -29,30 +30,12 @@ test {
pub const behavior_dir = ".graff/behavior";
pub const behavior_schema = "codegraff.behavior.v1";
-/// Task-agnostic behavioral records. Per-kind fields stay flat, matching the
-/// schema-harness event shape; state/action/expect values remain opaque JSON.
-pub const BehaviorKind = enum {
- run_started,
- turn_started,
- text_delta,
- tool_started,
- tool_finished,
- turn_committed,
- action_taken,
- model_mispredicted,
- run_finished,
-};
-
-/// Kinds the deployed collector accepts (Phase 1 contract). The four rich
-/// opt-in kinds (#255, GRAFF_BEHAVIOR_TRACE=full) are local-file only:
-/// offering an unrecognized kind fails the whole upload batch, not just one
-/// event, so this gate runs before eventLocked ever calls the uploader.
-fn uploadEligible(kind: BehaviorKind) bool {
- return switch (kind) {
- .run_started, .turn_started, .turn_committed, .model_mispredicted, .run_finished => true,
- .text_delta, .tool_started, .tool_finished, .action_taken => false,
- };
-}
+pub const BehaviorKind = types.BehaviorKind;
+pub const BehaviorRunStatus = types.BehaviorRunStatus;
+pub const LineResult = types.LineResult;
+pub const max_local_behavior_event_bytes = types.max_local_behavior_event_bytes;
+pub const max_tool_args_bytes = types.max_tool_args_bytes;
+pub const max_text_delta_bytes = types.max_text_delta_bytes;
/// Byte-cap a string without splitting a multi-byte UTF-8 sequence, so a
/// truncated payload can never desync the JSON string encoder mid-codepoint
@@ -65,28 +48,13 @@ fn utf8SafeClip(text: []const u8, max_len: usize) []const u8 {
return t;
}
-/// Typed lifecycle status; `.failed` is serialized as the JSON value `error`.
-pub const BehaviorRunStatus = enum {
- closed,
- failed,
-};
-
-pub const max_local_behavior_event_bytes = 64 * 1024;
-
-/// Opt-in rich capture caps (#255). A tool's arguments and a completed text
-/// segment are the two content-bearing rich fields; both are bounded so one
-/// huge adapter payload cannot dominate the local file the way
-/// max_local_behavior_event_bytes already bounds a whole line.
-pub const max_tool_args_bytes = 4096;
-pub const max_text_delta_bytes = 2048;
+fn jsonSafeCount(value: usize) u64 {
+ return @intCast(@min(@as(u128, value), @as(u128, behavior_upload.max_safe_json_integer)));
+}
-/// How one local write attempt ended. `dropped` failures happen before any
-/// byte reaches the file (allocation, serialization, or the size cap), so the
-/// stream stays healthy and later events may follow; the drop is counted and
-/// declared on `run_finished` as `local_dropped`. `sink_failed` means the
-/// file write itself failed and a partial tail may exist, so the caller must
-/// stop using the sink.
-pub const LineResult = enum { written, dropped, sink_failed };
+fn jsonSafeMillis(value: i64) u64 {
+ return @intCast(@min(@as(u128, @intCast(@max(value, 0))), @as(u128, behavior_upload.max_safe_json_integer)));
+}
/// Serialize a behavioral event as one flat JSON object. `fields` must be a
/// struct; its fields are appended after the common envelope. Building the
@@ -194,10 +162,7 @@ pub const BehaviorTrace = struct {
/// describe a batch whose terminal event was dropped during admission.
fn eventLocked(self: *BehaviorTrace, kind: BehaviorKind, local_fields: anytype, metadata_fields: anytype, content_fields: anytype) bool {
if (self.closed or self.seq == std.math.maxInt(u64)) return false;
- // Rich kinds (#255) never reach the uploader (see uploadEligible), so
- // an upload-only sink with no local file is not a viable sink for them.
- const upload_eligible = uploadEligible(kind);
- const uploader_active = if (self.upload) |uploader| (upload_eligible and uploader.active()) else false;
+ const uploader_active = if (self.upload) |uploader| uploader.active() else false;
if (self.out == null and !uploader_active) return false;
// This is the logical source sequence, reserved before either
@@ -219,10 +184,8 @@ pub const BehaviorTrace = struct {
.sink_failed => self.out = null,
}
}
- if (upload_eligible) {
- if (self.upload) |uploader| {
- return uploader.appendEvent(@tagName(kind), next, ts, metadata_fields, content_fields);
- }
+ if (self.upload) |uploader| {
+ return uploader.appendEvent(@tagName(kind), next, ts, metadata_fields, content_fields);
}
return false;
}
@@ -389,7 +352,14 @@ pub const BehaviorTrace = struct {
.args = args_value,
.args_truncated = truncated,
};
- _ = self.eventLocked(.tool_started, fields, .{}, .{});
+ const clipped_args = utf8SafeClip(args_json, max_tool_args_bytes);
+ _ = self.eventLocked(.tool_started, fields, .{
+ .turn = turn,
+ .call_id = call_id,
+ .tool_class = @tagName(behavior_upload.toolClass(name)),
+ .args_bytes = clipped_args.len,
+ .args_truncated = truncated,
+ }, fields);
}
/// Record a tool's outcome (#255, opt-in rich capture only). Only
@@ -407,7 +377,14 @@ pub const BehaviorTrace = struct {
.is_error = is_error,
.result_bytes = result_bytes,
};
- _ = self.eventLocked(.tool_finished, fields, .{}, .{});
+ _ = self.eventLocked(.tool_finished, fields, .{
+ .turn = turn,
+ .call_id = call_id,
+ .tool_class = @tagName(behavior_upload.toolClass(name)),
+ .ms = jsonSafeMillis(ms),
+ .is_error = is_error,
+ .result_bytes = jsonSafeCount(result_bytes),
+ }, fields);
}
/// The generic coding-task action mapping (#255): a state mutation after
@@ -423,7 +400,12 @@ pub const BehaviorTrace = struct {
else => return,
}
const fields = .{ .turn = turn, .call_id = call_id, .name = name, .is_error = is_error };
- _ = self.eventLocked(.action_taken, fields, .{}, .{});
+ _ = self.eventLocked(.action_taken, fields, .{
+ .turn = turn,
+ .call_id = call_id,
+ .tool_class = @tagName(behavior_upload.toolClass(name)),
+ .is_error = is_error,
+ }, fields);
}
/// Record one completed assistant text segment (#255, opt-in rich
@@ -434,12 +416,17 @@ pub const BehaviorTrace = struct {
defer self.mutex.unlock(self.io);
if (!self.rich or !self.started or self.closed or !self.turn_active or turn == 0 or turn != self.current_turn or text.len == 0) return;
const truncated = text.len > max_text_delta_bytes;
+ const clipped = utf8SafeClip(text, max_text_delta_bytes);
const fields = .{
.turn = turn,
- .text = utf8SafeClip(text, max_text_delta_bytes),
+ .text = clipped,
.text_truncated = truncated,
};
- _ = self.eventLocked(.text_delta, fields, .{}, .{});
+ _ = self.eventLocked(.text_delta, fields, .{
+ .turn = turn,
+ .text_bytes = clipped.len,
+ .text_truncated = truncated,
+ }, fields);
}
/// Attach content-free operational aggregates to the active root turn.
diff --git a/src/behavior_trace_rich_tests.zig b/src/behavior_trace_rich_tests.zig
index e5e32323..92b2aeb1 100644
--- a/src/behavior_trace_rich_tests.zig
+++ b/src/behavior_trace_rich_tests.zig
@@ -141,7 +141,7 @@ test "BehaviorTrace: rich caps truncate args and text without corrupting JSON (#
try std.testing.expect(lines.next() == null);
}
-test "BehaviorTrace: rich kinds never reach the uploader (#255)" {
+test "BehaviorTrace: rich metadata reaches uploader without content (#246)" {
const gpa = std.testing.allocator;
const io = std.testing.io;
var local: Io.Writer.Allocating = .init(gpa);
@@ -155,7 +155,7 @@ test "BehaviorTrace: rich kinds never reach the uploader (#255)" {
.client_name = "harness",
.service_version = "test",
.run_id = "0123456789abcdef",
- .mode = .content, // the most permissive collector mode
+ .mode = .metadata,
};
defer upload.deinit();
var behavior: BehaviorTrace = .{
@@ -168,7 +168,6 @@ test "BehaviorTrace: rich kinds never reach the uploader (#255)" {
};
behavior.start("test", 1);
try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));
- // run_started + turn_started are upload-eligible.
try std.testing.expectEqual(@as(usize, 2), upload.events.items.len);
const call_id = behavior.reserveCallId();
@@ -177,11 +176,17 @@ test "BehaviorTrace: rich kinds never reach the uploader (#255)" {
behavior.actionTaken(1, call_id, "bash", false);
behavior.textDelta(1, "hello");
- // The local file grew by four lines, but the uploader saw nothing new,
- // and none of it counted as a drop — a documented exclusion, not a loss.
- try std.testing.expectEqual(@as(usize, 2), upload.events.items.len);
+ try std.testing.expectEqual(@as(usize, 6), upload.events.items.len);
try std.testing.expectEqual(@as(u64, 0), upload.dropped_events);
try std.testing.expectEqual(@as(u64, 6), behavior.seq);
+ const payload = upload.events.items[2];
+ try std.testing.expect(std.mem.indexOf(u8, payload, "\"tool_class\":\"shell\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, payload, "\"args_bytes\":16") != null);
+ for (upload.events.items[2..]) |event| {
+ try std.testing.expect(std.mem.indexOf(u8, event, "\"name\"") == null);
+ try std.testing.expect(std.mem.indexOf(u8, event, "\"command\"") == null);
+ try std.testing.expect(std.mem.indexOf(u8, event, "hello") == null);
+ }
}
test "BehaviorTrace.reserveCallId: monotonic per run, independent of lifecycle state (#255)" {
diff --git a/src/behavior_trace_types.zig b/src/behavior_trace_types.zig
new file mode 100644
index 00000000..53556d34
--- /dev/null
+++ b/src/behavior_trace_types.zig
@@ -0,0 +1,27 @@
+//! Public schema types and limits shared by the behavioral trace producer.
+
+pub const BehaviorKind = enum {
+ run_started,
+ turn_started,
+ text_delta,
+ tool_started,
+ tool_finished,
+ turn_committed,
+ action_taken,
+ model_mispredicted,
+ run_finished,
+};
+
+/// Typed lifecycle status; `.failed` is serialized as the JSON value `error`.
+pub const BehaviorRunStatus = enum {
+ closed,
+ failed,
+};
+
+pub const max_local_behavior_event_bytes = 64 * 1024;
+pub const max_tool_args_bytes = 4096;
+pub const max_text_delta_bytes = 2048;
+
+/// A dropped line failed before any byte reached the file. A sink failure may
+/// have written a partial tail, so the producer must stop using that sink.
+pub const LineResult = enum { written, dropped, sink_failed };
diff --git a/src/behavior_upload.zig b/src/behavior_upload.zig
index b37bb349..c225baf8 100644
--- a/src/behavior_upload.zig
+++ b/src/behavior_upload.zig
@@ -162,6 +162,15 @@ fn isMetadataField(comptime name: []const u8) bool {
std.mem.eql(u8, name, "parent_turn") or
std.mem.eql(u8, name, "trajectory_node") or
std.mem.eql(u8, name, "commitment_ref") or
+ std.mem.eql(u8, name, "call_id") or
+ std.mem.eql(u8, name, "tool_class") or
+ std.mem.eql(u8, name, "args_bytes") or
+ std.mem.eql(u8, name, "args_truncated") or
+ std.mem.eql(u8, name, "ms") or
+ std.mem.eql(u8, name, "is_error") or
+ std.mem.eql(u8, name, "result_bytes") or
+ std.mem.eql(u8, name, "text_bytes") or
+ std.mem.eql(u8, name, "text_truncated") or
std.mem.eql(u8, name, "status") or
// Sink-health diagnostics: whether the local JSONL opened at run start
// and how many events it dropped before write. Counters and booleans
diff --git a/src/eval_memory.zig b/src/eval_memory.zig
new file mode 100644
index 00000000..08a602b6
--- /dev/null
+++ b/src/eval_memory.zig
@@ -0,0 +1,208 @@
+//! Local, run-scoped memory for the predict -> verify -> repair loop.
+//!
+//! The file is deliberately outside telemetry and trajectory payloads. It is
+//! re-injected as append-only user-turn context, so it survives compaction
+//! without mutating the cache-heavy system-prompt prefix.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+
+pub const max_notes_bytes: usize = 16 * 1024;
+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);
+const notes_body =
+ \\## CONFIRMED
+ \\- Nothing confirmed yet.
+ \\
+ \\## GUESSES
+ \\- None.
+ \\
+ \\## HYPOTHESES TO TEST
+ \\- Establish the current verifier baseline.
+ \\
+ \\## FACTS
+ \\- The harness, not the model, runs the configured verifier.
+ \\
+ \\## VERIFIER HISTORY
+ \\
+;
+pub const notes_template = "# Predict–Verify Notes\n\nTask class: general\n\n" ++ notes_body;
+
+fn safeRunId(self: anytype) []const u8 {
+ const tracer = self.tracer orelse return "session";
+ const run_id = tracer.identity.run_id;
+ if (run_id.len == 0 or run_id.len > 64) return "session";
+ for (run_id) |ch| {
+ if (!std.ascii.isAlphanumeric(ch) and ch != '-' and ch != '_') return "session";
+ }
+ return run_id;
+}
+
+fn noteName(self: anytype, buf: []u8) []const u8 {
+ return std.fmt.bufPrint(buf, "{s}.md", .{safeRunId(self)}) catch "session.md";
+}
+
+fn initialNotes(self: anytype) []const u8 {
+ if (self.eval_niche.len == 0) return notes_template;
+ var class_buf: [64]u8 = undefined;
+ const task_class = oneLine(&class_buf, self.eval_niche);
+ return std.fmt.allocPrint(
+ self.arena,
+ "# Predict–Verify Notes\n\nTask class: {s}\n\n{s}",
+ .{ if (task_class.len > 0) task_class else "general", notes_body },
+ ) catch notes_template;
+}
+
+fn openNotesDir(self: anytype, base: Io.Dir) ?Io.Dir {
+ base.createDir(self.io, ".graff", dir_permissions) catch |err| switch (err) {
+ error.PathAlreadyExists => {},
+ else => return null,
+ };
+ const graff = base.openDir(self.io, ".graff", .{ .iterate = true, .follow_symlinks = false }) catch return null;
+ defer graff.close(self.io);
+ graff.createDir(self.io, "eval-notes", dir_permissions) catch |err| switch (err) {
+ error.PathAlreadyExists => {},
+ else => return null,
+ };
+ const notes = graff.openDir(self.io, "eval-notes", .{ .iterate = true, .follow_symlinks = false }) catch return null;
+ if (builtin.os.tag != .windows) notes.setPermissions(self.io, dir_permissions) catch {
+ notes.close(self.io);
+ return null;
+ };
+ return notes;
+}
+
+fn readNotes(self: anytype, dir: Io.Dir, name: []const u8) ![]u8 {
+ const file = try dir.openFile(self.io, name, .{
+ .follow_symlinks = false,
+ .resolve_beneath = true,
+ });
+ defer file.close(self.io);
+ const stat = try file.stat(self.io);
+ if (stat.kind != .file) return error.InvalidNotesFile;
+ if (builtin.os.tag != .windows) try file.setPermissions(self.io, file_permissions);
+ var reader = file.reader(self.io, &.{});
+ return reader.interface.allocRemaining(self.arena, .limited(max_notes_bytes));
+}
+
+fn writeNotes(self: anytype, dir: Io.Dir, name: []const u8, text: []const u8) !void {
+ var atomic = try dir.createFileAtomic(self.io, name, .{
+ .permissions = file_permissions,
+ .replace = true,
+ });
+ defer atomic.deinit(self.io);
+ try atomic.file.writeStreamingAll(self.io, text);
+ try atomic.file.sync(self.io);
+ try atomic.replace(self.io);
+}
+
+fn loadAt(self: anytype, base: Io.Dir) []const u8 {
+ if (self.eval_cmd == null) return "";
+ const initial = initialNotes(self);
+ const dir = openNotesDir(self, base) orelse return initial;
+ defer dir.close(self.io);
+ var name_buf: [72]u8 = undefined;
+ const name = noteName(self, &name_buf);
+ return readNotes(self, dir, name) catch {
+ writeNotes(self, dir, name, initial) catch {};
+ return initial;
+ };
+}
+
+/// Return bounded local notes, creating the fixed template on first use.
+pub fn load(self: anytype) []const u8 {
+ return loadAt(self, Io.Dir.cwd());
+}
+
+fn recordAt(self: anytype, base: Io.Dir, note: []const u8, score: ?f64, exit_code: i32, met: bool) void {
+ if (self.eval_cmd == null) return;
+ const existing = loadAt(self, base);
+ var note_buf: [512]u8 = undefined;
+ const clean_note = oneLine(&note_buf, note);
+ var line_buf: [768]u8 = undefined;
+ const line = if (score) |value|
+ std.fmt.bufPrint(&line_buf, "- eval #{d}: score={d:.2}, target={d}, exit={d}, met={s}; change={s}\n", .{
+ self.eval_iter,
+ value,
+ self.eval_target,
+ exit_code,
+ if (met) "yes" else "no",
+ if (clean_note.len > 0) clean_note else "(not supplied)",
+ }) catch return
+ else
+ std.fmt.bufPrint(&line_buf, "- eval #{d}: score=unparsed, target={d}, exit={d}, met=no; change={s}\n", .{
+ self.eval_iter,
+ self.eval_target,
+ exit_code,
+ if (clean_note.len > 0) clean_note else "(not supplied)",
+ }) catch return;
+
+ var aw: Io.Writer.Allocating = .init(self.arena);
+ const keep = if (existing.len + line.len <= max_notes_bytes) existing else initialNotes(self);
+ aw.writer.writeAll(keep) catch return;
+ if (keep.len > 0 and keep[keep.len - 1] != '\n') aw.writer.writeByte('\n') catch return;
+ aw.writer.writeAll(line) catch return;
+ const dir = openNotesDir(self, base) orelse return;
+ defer dir.close(self.io);
+ var name_buf: [72]u8 = undefined;
+ writeNotes(self, dir, noteName(self, &name_buf), aw.writer.buffered()) catch {};
+}
+
+const TestTracer = struct {
+ identity: struct { run_id: []const u8 },
+};
+
+test "eval notes are private, atomic, and do not follow symlinks" {
+ if (builtin.os.tag == .windows) return;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var state = .{
+ .arena = arena_state.allocator(),
+ .io = io,
+ .eval_cmd = @as(?[]const u8, "verify"),
+ .tracer = @as(?*TestTracer, null),
+ .eval_iter = @as(u32, 1),
+ .eval_target = @as(u8, 90),
+ .eval_niche = "",
+ };
+ try std.testing.expectEqualStrings(notes_template, loadAt(&state, tmp.dir));
+ recordAt(&state, tmp.dir, "fixed\nsecret", 100, 0, true);
+
+ const graff = try tmp.dir.openDir(io, ".graff", .{});
+ defer graff.close(io);
+ const notes = try graff.openDir(io, "eval-notes", .{});
+ defer notes.close(io);
+ try std.testing.expectEqual(@as(u32, 0), (try notes.stat(io)).permissions.toMode() & 0o077);
+ const file = try notes.openFile(io, "session.md", .{ .follow_symlinks = false });
+ defer file.close(io);
+ try std.testing.expectEqual(@as(u32, 0), (try file.stat(io)).permissions.toMode() & 0o077);
+ const content = try notes.readFileAlloc(io, "session.md", std.testing.allocator, .limited(max_notes_bytes));
+ defer std.testing.allocator.free(content);
+ try std.testing.expect(std.mem.indexOf(u8, content, "fixed secret") != null);
+
+ try tmp.dir.writeFile(io, .{ .sub_path = "outside", .data = "do not overwrite" });
+ try notes.deleteFile(io, "session.md");
+ try notes.symLink(io, "../../outside", "session.md", .{});
+ _ = loadAt(&state, tmp.dir);
+ const outside = try tmp.dir.readFileAlloc(io, "outside", std.testing.allocator, .limited(64));
+ defer std.testing.allocator.free(outside);
+ try std.testing.expectEqualStrings("do not overwrite", outside);
+}
+
+fn oneLine(buf: []u8, value: []const u8) []const u8 {
+ const source = value[0..@min(value.len, buf.len)];
+ for (source, 0..) |ch, index| {
+ buf[index] = if (ch < 0x20 or ch == 0x7f) ' ' else ch;
+ }
+ return std.mem.trim(u8, buf[0..source.len], " ");
+}
+
+/// Append one prompt-safe verifier fact. Command output and paths are never
+/// copied here; only the model's bounded note plus numeric verifier state.
+pub fn record(self: anytype, note: []const u8, score: ?f64, exit_code: i32, met: bool) void {
+ recordAt(self, Io.Dir.cwd(), note, score, exit_code, met);
+}
diff --git a/src/learn_comparison.zig b/src/learn_comparison.zig
index 02068b21..66e381a8 100644
--- a/src/learn_comparison.zig
+++ b/src/learn_comparison.zig
@@ -46,13 +46,18 @@ pub fn computeComparison(
var child_cost: u64 = 0;
var parent_tool_calls: u64 = 0;
var child_tool_calls: u64 = 0;
+ var parent_behavior_score: u64 = 0;
+ var child_behavior_score: u64 = 0;
var parent_latency: u64 = 0;
var child_latency: u64 = 0;
var tool_calls_measured = true;
+ var behavior_measured = true;
var latency_measured = true;
for (response.pairs, requested) |result, pair| {
if (!std.mem.eql(u8, result.case_id, pair.case_id) or !std.mem.eql(u8, result.seed, pair.seed)) return error.PairMismatch;
if (result.parent_score_ppm > 1_000_000 or result.child_score_ppm > 1_000_000) return error.InvalidScore;
+ if (result.parent_behavior_score_ppm > 1_000_000 or result.child_behavior_score_ppm > 1_000_000) return error.InvalidScore;
+ if (!result.behavior_measured and (result.parent_behavior_score_ppm != 0 or result.child_behavior_score_ppm != 0)) return error.InvalidMetric;
if (result.parent_cost_micros > stats.js_exact_max or result.child_cost_micros > stats.js_exact_max or result.parent_latency_ms > stats.js_exact_max or result.child_latency_ms > stats.js_exact_max or result.parent_tool_calls > stats.js_exact_max or result.child_tool_calls > stats.js_exact_max) return error.InvalidMetric;
if (result.parent_pass) parent_passes += 1;
if (result.child_pass) child_passes += 1;
@@ -66,9 +71,12 @@ pub fn computeComparison(
child_cost = try stats.checkedMetricAdd(child_cost, result.child_cost_micros);
parent_tool_calls = try stats.checkedMetricAdd(parent_tool_calls, result.parent_tool_calls);
child_tool_calls = try stats.checkedMetricAdd(child_tool_calls, result.child_tool_calls);
+ parent_behavior_score = try stats.checkedMetricAdd(parent_behavior_score, result.parent_behavior_score_ppm);
+ child_behavior_score = try stats.checkedMetricAdd(child_behavior_score, result.child_behavior_score_ppm);
parent_latency = try stats.checkedMetricAdd(parent_latency, result.parent_latency_ms);
child_latency = try stats.checkedMetricAdd(child_latency, result.child_latency_ms);
tool_calls_measured = tool_calls_measured and result.tool_calls_measured;
+ behavior_measured = behavior_measured and result.behavior_measured;
latency_measured = latency_measured and result.latency_measured;
}
@@ -111,6 +119,8 @@ pub fn computeComparison(
const correctness_significant = correctness_p * correction <= alpha;
const tool_significant = tool_p * correction <= alpha;
const tool_delta = reductionPpm(parent_tool_calls, child_tool_calls);
+ const parent_behavior_mean: u32 = if (behavior_measured) @intCast(parent_behavior_score / pair_count) else 0;
+ const child_behavior_mean: u32 = if (behavior_measured) @intCast(child_behavior_score / pair_count) else 0;
const tool_discordant = tool_wins + tool_losses;
const economy_eligible = config.gate.economy_gate_enabled and
child_critical_failures == 0 and statistical_units >= config.gate.minimum_pairs and
@@ -171,6 +181,9 @@ pub fn computeComparison(
.tool_calls_measured = tool_calls_measured,
.parent_tool_calls = parent_tool_calls,
.child_tool_calls = child_tool_calls,
+ .behavior_measured = behavior_measured,
+ .parent_behavior_score_ppm = parent_behavior_mean,
+ .child_behavior_score_ppm = child_behavior_mean,
.tool_wins = tool_wins,
.tool_losses = tool_losses,
.tool_ties = if (tool_calls_measured) statistical_units - tool_wins - tool_losses else 0,
diff --git a/src/learn_eval.zig b/src/learn_eval.zig
index bc952d8d..95f0bcf2 100644
--- a/src/learn_eval.zig
+++ b/src/learn_eval.zig
@@ -484,6 +484,9 @@ pub fn comparisonEqual(a: ComparisonRecord, b: ComparisonRecord) bool {
a.parent_cost_micros == b.parent_cost_micros and a.child_cost_micros == b.child_cost_micros and
a.tool_calls_measured == b.tool_calls_measured and
a.parent_tool_calls == b.parent_tool_calls and a.child_tool_calls == b.child_tool_calls and
+ a.behavior_measured == b.behavior_measured and
+ a.parent_behavior_score_ppm == b.parent_behavior_score_ppm and
+ a.child_behavior_score_ppm == b.child_behavior_score_ppm and
a.tool_wins == b.tool_wins and a.tool_losses == b.tool_losses and a.tool_ties == b.tool_ties and
a.tool_delta_ppm == b.tool_delta_ppm and a.tool_p_value_ppb == b.tool_p_value_ppb and
a.latency_measured == b.latency_measured and a.parent_latency_ms == b.parent_latency_ms and a.child_latency_ms == b.child_latency_ms and
diff --git a/src/learn_eval_tests.zig b/src/learn_eval_tests.zig
index 0c32a963..91007026 100644
--- a/src/learn_eval_tests.zig
+++ b/src/learn_eval_tests.zig
@@ -61,6 +61,14 @@ test "paired gate rejects critical regressions and requires corrected significan
results[0].parent_cost_micros = 0;
results[1].parent_cost_micros = 0;
+ results[0].parent_behavior_score_ppm = 1;
+ try std.testing.expectError(error.InvalidMetric, computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1));
+ results[0].behavior_measured = true;
+ results[0].parent_behavior_score_ppm = 1_000_001;
+ try std.testing.expectError(error.InvalidScore, computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1));
+ results[0].behavior_measured = false;
+ results[0].parent_behavior_score_ppm = 0;
+
for (0..10) |i| {
requested[i].case_id = "repeated-case";
results[i].case_id = "repeated-case";
diff --git a/src/learn_eval_types.zig b/src/learn_eval_types.zig
index 54af0338..7681cbc1 100644
--- a/src/learn_eval_types.zig
+++ b/src/learn_eval_types.zig
@@ -78,6 +78,11 @@ pub const PairResult = struct {
tool_calls_measured: bool = false,
parent_tool_calls: u64 = 0,
child_tool_calls: u64 = 0,
+ /// Trusted evaluator score derived from a closed behavioral stream:
+ /// successful tool completions divided by completed tool calls.
+ behavior_measured: bool = false,
+ parent_behavior_score_ppm: u32 = 0,
+ child_behavior_score_ppm: u32 = 0,
};
pub const EvaluationResponse = struct {
@@ -101,6 +106,8 @@ pub const BaselinePairResult = struct {
latency_measured: bool = false,
tool_calls_measured: bool = false,
tool_calls: u64 = 0,
+ behavior_measured: bool = false,
+ behavior_score_ppm: u32 = 0,
};
pub const PrimaryBaselineRequest = struct {
@@ -193,6 +200,9 @@ pub const ComparisonRecord = struct {
tool_calls_measured: bool = false,
parent_tool_calls: u64 = 0,
child_tool_calls: u64 = 0,
+ behavior_measured: bool = false,
+ parent_behavior_score_ppm: u32 = 0,
+ child_behavior_score_ppm: u32 = 0,
tool_wins: usize = 0,
tool_losses: usize = 0,
tool_ties: usize = 0,
diff --git a/src/learn_primary.zig b/src/learn_primary.zig
index a412f51b..fd7ee747 100644
--- a/src/learn_primary.zig
+++ b/src/learn_primary.zig
@@ -51,6 +51,8 @@ fn validateBaselinePairs(response: eval.PrimaryBaselineResponse, requested: []co
for (response.pairs, requested) |result, pair| {
if (!std.mem.eql(u8, result.case_id, pair.case_id) or !std.mem.eql(u8, result.seed, pair.seed)) return error.PairMismatch;
if (result.score_ppm > 1_000_000) return error.InvalidScore;
+ if (result.behavior_score_ppm > 1_000_000) return error.InvalidScore;
+ if (!result.behavior_measured and result.behavior_score_ppm != 0) return error.InvalidMetric;
if (result.cost_micros > eval.js_exact_max or result.latency_ms > eval.js_exact_max or result.tool_calls > eval.js_exact_max) return error.InvalidMetric;
}
}
@@ -98,7 +100,9 @@ fn validateParentProjection(baseline: eval.PrimaryBaselineResponse, response: ev
pair.parent_latency_ms != parent.latency_ms or
pair.latency_measured != parent.latency_measured or
pair.parent_tool_calls != parent.tool_calls or
- pair.tool_calls_measured != parent.tool_calls_measured) return error.BaselineProjectionMismatch;
+ pair.tool_calls_measured != parent.tool_calls_measured or
+ pair.parent_behavior_score_ppm != parent.behavior_score_ppm or
+ pair.behavior_measured != parent.behavior_measured) return error.BaselineProjectionMismatch;
}
}
diff --git a/src/learn_receipt.zig b/src/learn_receipt.zig
index b8a2864e..3c128c1e 100644
--- a/src/learn_receipt.zig
+++ b/src/learn_receipt.zig
@@ -7,7 +7,7 @@ const eval = @import("learn_eval.zig");
const scoring = @import("scoring.zig");
const store = @import("learn_store.zig");
-pub const schema = "codegraff.learn.grade.v2";
+pub const schema = "codegraff.learn.grade.v3";
pub const delete_token_domain = "codegraff.learn.delete.v1\n";
pub const Grade = struct {
@@ -24,6 +24,9 @@ pub const Grade = struct {
tool_calls_measured: bool,
parent_tool_calls: u64,
child_tool_calls: u64,
+ behavior_measured: bool,
+ parent_behavior_score_ppm: u32,
+ child_behavior_score_ppm: u32,
tool_wins: usize,
tool_losses: usize,
tool_ties: usize,
@@ -62,6 +65,9 @@ pub fn fromComparison(gate: store.Gate, comparison: eval.ComparisonRecord, multi
.tool_calls_measured = comparison.tool_calls_measured,
.parent_tool_calls = comparison.parent_tool_calls,
.child_tool_calls = comparison.child_tool_calls,
+ .behavior_measured = comparison.behavior_measured,
+ .parent_behavior_score_ppm = comparison.parent_behavior_score_ppm,
+ .child_behavior_score_ppm = comparison.child_behavior_score_ppm,
.tool_wins = comparison.tool_wins,
.tool_losses = comparison.tool_losses,
.tool_ties = comparison.tool_ties,
@@ -124,6 +130,9 @@ fn format(
@intFromBool(grade.tool_calls_measured),
@intCast(grade.parent_tool_calls),
@intCast(grade.child_tool_calls),
+ @intFromBool(grade.behavior_measured),
+ grade.parent_behavior_score_ppm,
+ grade.child_behavior_score_ppm,
@intCast(grade.tool_wins),
@intCast(grade.tool_losses),
@intCast(grade.tool_ties),
@@ -204,6 +213,9 @@ test "learning grade message is deterministic and prompt-free" {
.tool_calls_measured = true,
.parent_tool_calls = 100,
.child_tool_calls = 80,
+ .behavior_measured = true,
+ .parent_behavior_score_ppm = 1_000_000,
+ .child_behavior_score_ppm = 900_000,
.tool_wins = 8,
.tool_losses = 1,
.tool_ties = 11,
@@ -242,7 +254,7 @@ test "learning grade message is deterministic and prompt-free" {
defer scoring.g_score_key = saved_key;
scoring.g_score_key = "test-key";
const signature = sign(prompt, parent, 0.75, run, "learn-primary-v2", artifact, suite, niche, "frontier", delete_token, created_unix_ms, grade);
- try std.testing.expectEqualStrings("e4d78b0a0236fb9719272a016f41685a10d93a4f488cb704e0f7f8c963b546bb", &signature);
+ try std.testing.expectEqualStrings("9ec3275573e1e3f661c73ab6a54a3e499baf1b9686583ceab92509cfc21e96c7", &signature);
const token = deletionToken(run, "2222222222222222222222222222222222222222222222222222222222222222");
try std.testing.expectEqualStrings("5abd1867608b678b6679e00f24f7f457eccef7977a4df149f03c002a1885f5d9", &token);
diff --git a/src/learn_report.zig b/src/learn_report.zig
index e2cd9d23..64df9089 100644
--- a/src/learn_report.zig
+++ b/src/learn_report.zig
@@ -37,6 +37,13 @@ fn writeComparison(out: *Io.Writer, label: []const u8, comparison: eval.Comparis
})
else
try out.writeAll("calls unmeasured; ");
+ if (comparison.behavior_measured)
+ try out.print("behavior {d} -> {d} ppm; ", .{
+ comparison.parent_behavior_score_ppm,
+ comparison.child_behavior_score_ppm,
+ })
+ else
+ try out.writeAll("behavior unmeasured; ");
if (comparison.latency_measured)
try out.print("latency {d} -> {d} ms; ", .{ comparison.parent_latency_ms, comparison.child_latency_ms })
else
@@ -87,6 +94,9 @@ test "candidate summary reports actionable aggregate evidence without content" {
.tool_calls_measured = true,
.parent_tool_calls = 23,
.child_tool_calls = 29,
+ .behavior_measured = true,
+ .parent_behavior_score_ppm = 1_000_000,
+ .child_behavior_score_ppm = 750_000,
.tool_wins = 2,
.tool_losses = 1,
.tool_ties = 12,
@@ -120,6 +130,7 @@ test "candidate summary reports actionable aggregate evidence without content" {
try std.testing.expect(std.mem.indexOf(u8, rendered, "wins/losses/ties 1/0/14") != null);
try std.testing.expect(std.mem.indexOf(u8, rendered, "regressions 1") != null);
try std.testing.expect(std.mem.indexOf(u8, rendered, "calls 23 -> 29") != null);
+ try std.testing.expect(std.mem.indexOf(u8, rendered, "behavior 1000000 -> 750000 ppm") != null);
try std.testing.expect(std.mem.indexOf(u8, rendered, "latency 100 -> 80 ms") != null);
try std.testing.expect(std.mem.indexOf(u8, rendered, "decision: not_significant") != null);
try std.testing.expect(std.mem.indexOf(u8, rendered, "suite") == null);
diff --git a/src/learn_tournament.zig b/src/learn_tournament.zig
index c20edc25..37f7dd9e 100644
--- a/src/learn_tournament.zig
+++ b/src/learn_tournament.zig
@@ -46,6 +46,9 @@ pub fn primaryOutranks(a: eval.CandidateRecord, b: eval.CandidateRecord) bool {
// only compare exact call counts when both adapters supplied them.
if (ac.tool_calls_measured != bc.tool_calls_measured) return ac.tool_calls_measured;
if (ac.tool_calls_measured and ac.child_tool_calls != bc.child_tool_calls) return ac.child_tool_calls < bc.child_tool_calls;
+ if (ac.behavior_measured != bc.behavior_measured) return ac.behavior_measured;
+ if (ac.behavior_measured and ac.child_behavior_score_ppm != bc.child_behavior_score_ppm)
+ return ac.child_behavior_score_ppm > bc.child_behavior_score_ppm;
if (ac.child_cost_micros != bc.child_cost_micros) return ac.child_cost_micros < bc.child_cost_micros;
if (a.mutation.genome_bytes != 0 and b.mutation.genome_bytes != 0 and a.mutation.genome_bytes != b.mutation.genome_bytes)
return a.mutation.genome_bytes < b.mutation.genome_bytes;
@@ -155,6 +158,9 @@ fn fakeComparison(delta: i64, score_delta: i64, p: u64, cost: u64, eligible: boo
.tool_calls_measured = true,
.parent_tool_calls = 10,
.child_tool_calls = 10,
+ .behavior_measured = true,
+ .parent_behavior_score_ppm = 1_000_000,
+ .child_behavior_score_ppm = 1_000_000,
.latency_measured = true,
.parent_latency_ms = 100,
.child_latency_ms = 100,
@@ -174,7 +180,7 @@ fn fakeCandidate(id: []const u8, primary: ?eval.ComparisonRecord) eval.Candidate
};
}
-test "primary winner is correctness-first then tool calls, cost, and genome ID" {
+test "primary winner is correctness-first then tools, behavior, cost, and genome ID" {
var candidates = [_]eval.CandidateRecord{
fakeCandidate("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", fakeComparison(20, 10, 5, 1, true, "eligible")),
fakeCandidate("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", fakeComparison(30, 10, 5, 100, false, "not_significant")),
@@ -191,6 +197,11 @@ test "primary winner is correctness-first then tool calls, cost, and genome ID"
try std.testing.expectEqual(@as(?usize, 1), primaryWinnerIndex("parent", &candidates));
candidates[0].primary.?.child_tool_calls = 8;
+ candidates[0].primary.?.child_behavior_score_ppm = 900_000;
+ candidates[1].primary.?.child_behavior_score_ppm = 1_000_000;
+ try std.testing.expectEqual(@as(?usize, 1), primaryWinnerIndex("parent", &candidates));
+
+ candidates[0].primary.?.child_behavior_score_ppm = 1_000_000;
candidates[1].primary.?.child_cost_micros = 50;
try std.testing.expectEqual(@as(?usize, 1), primaryWinnerIndex("parent", &candidates));
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 779cc9c3..97346154 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -23,6 +23,7 @@ const fleet = @import("fleet.zig");
const jobs = @import("jobs.zig");
const session = @import("session.zig");
const repl_glue = @import("repl_glue.zig");
+const eval_memory = @import("eval_memory.zig");
const mainloop_score = @import("mainloop_score.zig");
const mainloop_trace = @import("mainloop_trace.zig");
const scoring = @import("scoring.zig");
@@ -296,7 +297,15 @@ pub fn run(ctx: *Ctx) !void {
// resumes the plan instead of re-deriving it (assembled by goalSteeringNote).
const todos_render: []const u8 = if (ctx.root.todos.items.len > 0) ctx.root.renderTodos() else "";
const goal_note = try repl_glue.goalSteeringNote(ctx.arena, ctx.root.goal, todos_render);
- const eval_note = try repl_glue.evalSteeringNote(ctx.arena, ctx.root.eval_cmd, ctx.root.eval_target, ctx.root.eval_judge != null);
+ const eval_note = try repl_glue.evalSteeringNote(
+ ctx.arena,
+ ctx.root.eval_cmd,
+ ctx.root.eval_target,
+ ctx.root.eval_judge != null,
+ ctx.root.eval_verified,
+ ctx.root.eval_repair_pending,
+ eval_memory.load(ctx.root),
+ );
var goal_msg: []const u8 = base_msg;
if (goal_note.len > 0) goal_msg = try std.fmt.allocPrint(ctx.arena, "{s}\n\n{s}", .{ goal_msg, goal_note });
if (eval_note.len > 0) goal_msg = try std.fmt.allocPrint(ctx.arena, "{s}\n\n{s}", .{ goal_msg, eval_note });
@@ -509,7 +518,7 @@ pub fn run(ctx: *Ctx) !void {
.session_arena_kb = if (main_mod.g_session_arena) |a| a.queryCapacity() / 1024 else 0,
.scratch_arena_kb = if (ctx.root.scratch_arena) |a| a.queryCapacity() / 1024 else 0,
});
- ctx.root.emit(.{ .type = "turn", .text = emitted_text, .context_tokens = context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = true, .metadata_complete = context_tokens > 0 });
+ ctx.root.emit(.{ .type = "turn", .text = emitted_text, .context_tokens = context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = !ctx.root.eval_repair_pending, .metadata_complete = context_tokens > 0 });
}
// Apply only if already complete; poll never waits for title generation.
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 18cf4239..ed0aa6d8 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -141,13 +141,33 @@ fn normalizeScore(v: f64) f64 {
/// Steering injected each turn when --eval is set: the eval-driven loop
/// discipline (score -> one focused change -> re-score -> log -> stop at
/// target). Returns "" when no eval command is configured.
-pub fn evalSteeringNote(arena: Allocator, eval_cmd: ?[]const u8, target: u8, has_judge: bool) ![]const u8 {
+pub fn evalSteeringNote(
+ arena: Allocator,
+ eval_cmd: ?[]const u8,
+ target: u8,
+ has_judge: bool,
+ verified: bool,
+ repair_pending: bool,
+ notes: []const u8,
+) ![]const u8 {
if (eval_cmd == null) return "";
const gate = if (has_judge)
" An LLM judge is also configured, so the target is met only when BOTH the deterministic score AND the judge score reach it - read both numbers the `eval` tool reports."
else
"";
- return std.fmt.allocPrint(arena, "[eval-driven loop active. A scoring command is configured. Work it as a scored improvement loop: (1) call the `eval` tool to score the current state - the harness runs the command and logs to .graff/eval-log.tsv, so do NOT run it yourself via bash; (2) read the score, best-so-far, and output; (3) find the SINGLE biggest failure (inspect any artifacts or images directly); (4) make ONE focused change targeting it; (5) call `eval` again. Continue until `eval` reports the target ({d}/100) is met.{s} Do not stop at the first passing result, and do not revert unless `eval` shows a clear regression. After each `eval`, briefly note what you changed.]", .{ target, gate });
+ const state = if (repair_pending)
+ "RED: the last committed expectation was contradicted. The prior plan is dropped; make one repair and re-run eval. attempt_completion is blocked."
+ else if (verified)
+ "GREEN: the latest workspace state met the target. Any workspace-changing tool makes this state stale and requires another eval."
+ else
+ "UNVERIFIED: establish or refresh the verifier baseline before completion.";
+ return std.fmt.allocPrint(arena,
+ \\[eval-driven loop active. A scoring command is configured. Verifier state: {s}
+ \\Work it as a predict→act→verify→repair loop: (1) call `eval` to score the current state—the harness runs the command and logs it, so do NOT run it via bash; (2) state one hypothesis; (3) make ONE focused change; (4) call `eval` again. Continue until the latest eval reaches {d}/100.{s} A failed eval drops the prior plan. Use the eval `note` field to append CONFIRMED/GUESS/HYPOTHESIS/FACT belief updates; this task-class memory is re-injected after compaction.
+ \\
+ \\Local run-scoped notes (never uploaded by this mechanism):
+ \\{s}]
+ , .{ state, target, gate, notes });
}
test "goalSteeringNote: active-only gate + checklist assembly, no (no todos) leak" {
diff --git a/src/schema.zig b/src/schema.zig
index 68562eaa..6c651c37 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -173,7 +173,7 @@ const meta_specs = [_]ToolSpec{
},
.{
.name = "eval",
- .desc = "Run the configured scoring command (graff --eval) on the current output and record the result. The HARNESS runs it and logs the score to .graff/eval-log.tsv - do not run the eval command yourself via bash. Returns the score (0-100), best so far, target, and whether the target is met. Call after each focused change in an eval-driven loop. Pass `note` describing what you just changed.",
+ .desc = "Run the configured scoring command (graff --eval) alone and record the result. The HARNESS runs it and logs the score to .graff/eval-log.tsv - do not run it via bash. Returns score, best, target, and gate state. Red drops the current plan and ends the turn; repair next turn and re-evaluate. In `note`, describe the focused change and label new CONFIRMED/GUESS/HYPOTHESIS/FACT beliefs.",
.schema =
\\{"type": "object", "properties": {"note": {"type": "string", "description": "What you changed since the last eval"}}}
,
diff --git a/src/session_run.zig b/src/session_run.zig
index e81211b4..5d1c3002 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -48,6 +48,7 @@ const title_mod = @import("title.zig");
const repl = @import("repl.zig");
const pickers = @import("pickers.zig");
const repl_glue = @import("repl_glue.zig");
+const eval_memory = @import("eval_memory.zig");
const providers = @import("providers.zig");
const messages_mod = @import("messages.zig");
const session = @import("session.zig");
@@ -117,7 +118,15 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m
if (telemetry.g_telem) |t| t.ultracode();
}
const goal_note = try repl_glue.goalSteeringNote(arena, root.goal, if (root.todos.items.len > 0) root.renderTodos() else "");
- const eval_note = try repl_glue.evalSteeringNote(arena, root.eval_cmd, root.eval_target, root.eval_judge != null);
+ const eval_note = try repl_glue.evalSteeringNote(
+ arena,
+ root.eval_cmd,
+ root.eval_target,
+ root.eval_judge != null,
+ root.eval_verified,
+ root.eval_repair_pending,
+ eval_memory.load(root),
+ );
var oneshot_user = if (goal_note.len > 0) try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ ultracode_msg.text, goal_note }) else ultracode_msg.text;
if (eval_note.len > 0) oneshot_user = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ oneshot_user, eval_note });
try root.messages.append(try messages_mod.textMessage(arena, "user", oneshot_user));
diff --git a/src/telemetry_score.zig b/src/telemetry_score.zig
index 69feea1c..e0e2ec87 100644
--- a/src/telemetry_score.zig
+++ b/src/telemetry_score.zig
@@ -30,14 +30,15 @@ fn attr(s: *std.json.Stringify, key: []const u8, value: AttrVal) !void {
}
const metric_names = [_][]const u8{
- "pairs", "statistical_units", "parent_passes", "child_passes",
- "child_critical_failures", "critical_regressions", "correctness_regressions", "delta_ppm",
- "mean_score_delta_ppm", "p_value_ppb", "tool_calls_measured", "parent_tool_calls",
- "child_tool_calls", "tool_wins", "tool_losses", "tool_ties",
- "tool_delta_ppm", "tool_p_value_ppb", "parent_cost_micros", "child_cost_micros",
- "latency_measured", "parent_latency_ms", "child_latency_ms", "economy_eligible",
- "eligible", "economy_gate_enabled", "alpha_ppm", "minimum_delta_ppm",
- "minimum_pairs", "minimum_tool_reduction_ppm", "minimum_economy_pairs", "multiplicity",
+ "pairs", "statistical_units", "parent_passes", "child_passes",
+ "child_critical_failures", "critical_regressions", "correctness_regressions", "delta_ppm",
+ "mean_score_delta_ppm", "p_value_ppb", "tool_calls_measured", "parent_tool_calls",
+ "child_tool_calls", "behavior_measured", "parent_behavior_score_ppm", "child_behavior_score_ppm",
+ "tool_wins", "tool_losses", "tool_ties", "tool_delta_ppm",
+ "tool_p_value_ppb", "parent_cost_micros", "child_cost_micros", "latency_measured",
+ "parent_latency_ms", "child_latency_ms", "economy_eligible", "eligible",
+ "economy_gate_enabled", "alpha_ppm", "minimum_delta_ppm", "minimum_pairs",
+ "minimum_tool_reduction_ppm", "minimum_economy_pairs", "multiplicity",
};
pub fn write(s: *std.json.Stringify, event: anytype) !void {
@@ -58,7 +59,9 @@ pub fn write(s: *std.json.Stringify, event: anytype) !void {
const grade_sig = parts.next() orelse return error.InvalidScoreProvenance;
var delete_token: []const u8 = "";
var run_created_unix_ms: ?i64 = null;
- if (std.mem.eql(u8, grade_schema, "codegraff.learn.grade.v2")) {
+ if (std.mem.eql(u8, grade_schema, "codegraff.learn.grade.v2") or
+ std.mem.eql(u8, grade_schema, "codegraff.learn.grade.v3"))
+ {
delete_token = parts.next() orelse return error.InvalidScoreProvenance;
const raw_created = parts.next() orelse return error.InvalidScoreProvenance;
run_created_unix_ms = std.fmt.parseInt(i64, raw_created, 10) catch return error.InvalidScoreProvenance;
diff --git a/tests/learn_graff_adapters.py b/tests/learn_graff_adapters.py
index 4f84925b..106925bd 100755
--- a/tests/learn_graff_adapters.py
+++ b/tests/learn_graff_adapters.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import hashlib
import json
+import os
from pathlib import Path
import runpy
import subprocess
@@ -15,6 +16,8 @@ import tempfile
ROOT = Path(__file__).resolve().parents[1]
MUTATOR = ROOT / "examples" / "learn_graff_mutator.py"
EVALUATOR = ROOT / "examples" / "learn_graff_evaluator.py"
+BEHAVIOR_METRICS = ROOT / "examples" / "learn_behavior_metrics.py"
+CASE_SUPPORT = ROOT / "examples" / "learn_graff_case.py"
ARMS = ROOT / "examples" / "learn_graff_arms.json"
SETTINGS = ROOT / "examples" / "learn_graff_evaluator.json"
PREPARE = ROOT / "examples" / "prepare_graff_tournament.py"
@@ -102,8 +105,58 @@ def assert_patch_boundaries() -> None:
assert any(expected in violation for violation in violations)
+def assert_behavior_metrics() -> None:
+ metrics = runpy.run_path(str(BEHAVIOR_METRICS))
+ audited_tool_calls = metrics["audited_tool_calls"]
+ audited_behavior_metrics = metrics["audited_behavior_metrics"]
+ with tempfile.TemporaryDirectory(prefix="learn-behavior-") as raw:
+ root = Path(raw)
+ behavior = root / ".graff" / "behavior"
+ behavior.mkdir(parents=True)
+ envelope = lambda kind, seq: {
+ "kind": kind, "seq": seq, "ts": float(seq),
+ "run_id": "0123456789abcdef", "schema": "codegraff.behavior.v1",
+ }
+ events = [
+ envelope("run_started", 1),
+ {**envelope("turn_started", 2), "turn": 1, "parent_turn": 0},
+ {**envelope("tool_started", 3), "turn": 1, "call_id": 1},
+ {**envelope("tool_finished", 4), "turn": 1, "call_id": 1, "is_error": False},
+ {**envelope("run_finished", 5), "status": "closed", "local_dropped": 0},
+ ]
+ (behavior / "run.jsonl").write_text(
+ "".join(json.dumps(event, separators=(",", ":")) + "\n" for event in events),
+ encoding="utf-8",
+ )
+ prior = os.environ.get("GRAFF_LEARN_INPUT_3")
+ os.environ["GRAFF_LEARN_INPUT_3"] = str(ROOT / "scripts" / "score_run.py")
+ try:
+ assert audited_tool_calls(root, 1) == 1
+ assert audited_behavior_metrics(root, 1) == {
+ "measured": True, "tool_calls": 1, "score_ppm": 1_000_000,
+ }
+ events[3]["is_error"] = True
+ (behavior / "run.jsonl").write_text(
+ "".join(json.dumps(event, separators=(",", ":")) + "\n" for event in events),
+ encoding="utf-8",
+ )
+ assert audited_behavior_metrics(root, 1)["score_ppm"] == 0
+ try:
+ audited_tool_calls(root, 2)
+ except RuntimeError as exc:
+ assert "disagree" in str(exc)
+ else:
+ raise AssertionError("tool-count disagreement was accepted")
+ finally:
+ if prior is None:
+ os.environ.pop("GRAFF_LEARN_INPUT_3", None)
+ else:
+ os.environ["GRAFF_LEARN_INPUT_3"] = prior
+
+
def run() -> None:
assert_patch_boundaries()
+ assert_behavior_metrics()
with tempfile.TemporaryDirectory(prefix="learn-adapters-") as raw:
root = Path(raw)
fake = root / "graff"
@@ -230,8 +283,12 @@ def run() -> None:
assert config["gate"]["require_all_candidates"] is True
assert config["gate"]["minimum_pairs"] <= preparation["primary_units"]
assert config["gate"]["minimum_pairs"] <= preparation["holdout_units"]
- assert config["cohort"]["adapter_version"] == "graff-eval-v7"
- assert config["cohort"]["verifier_version"] == "clustered-exact-v6"
+ assert config["cohort"]["adapter_version"] == "graff-eval-v8"
+ assert config["cohort"]["verifier_version"] == "behavior-audited-v7"
+ assert [item["path"] for item in config["evaluator"]["inputs"]][-3:] == [
+ str(BEHAVIOR_METRICS.resolve()), str((ROOT / "scripts" / "score_run.py").resolve()),
+ str(CASE_SUPPORT.resolve()),
+ ]
assert config["auto"] == {"enabled": False}
suite = root / "suite.json"
@@ -266,6 +323,8 @@ def run() -> None:
assert result["tool_calls_measured"] is True
assert result["latency_measured"] is True
assert result["parent_tool_calls"] == result["child_tool_calls"] == 1
+ assert result["behavior_measured"] is False
+ assert result["parent_behavior_score_ppm"] == result["child_behavior_score_ppm"] == 0
assert result["parent_cost_micros"] == result["child_cost_micros"] == 2000
baseline_request = root / "baseline-request.json"
@@ -292,6 +351,7 @@ def run() -> None:
"pass": True, "score_ppm": 1_000_000,
"cost_micros": 2000, "latency_ms": baseline["pairs"][0]["latency_ms"],
"latency_measured": True, "tool_calls_measured": True, "tool_calls": 1,
+ "behavior_measured": False, "behavior_score_ppm": 0,
}]
primary_request = root / "primary-request.json"
@@ -324,6 +384,7 @@ def run() -> None:
assert primary_result["parent_cost_micros"] == baseline_result["cost_micros"]
assert primary_result["parent_latency_ms"] == baseline_result["latency_ms"]
assert primary_result["parent_tool_calls"] == baseline_result["tool_calls"]
+ assert primary_result["parent_behavior_score_ppm"] == baseline_result["behavior_score_ppm"]
assert primary_result["child_pass"] is True
diff --git a/tests/learn_tournament_e2e.py b/tests/learn_tournament_e2e.py
index 64792bc6..ee6eda72 100755
--- a/tests/learn_tournament_e2e.py
+++ b/tests/learn_tournament_e2e.py
@@ -19,6 +19,7 @@ import threading
import time
from learning_receipt_assertions import assert_learning_records
+from learn_tournament_fixtures import MUTATOR
from learn_e2e import (
GradeCapture,
@@ -34,44 +35,6 @@ from learn_e2e import (
)
-MUTATOR = r'''import hashlib, json, os, pathlib, sys, time
-operation, request_path, response_path = sys.argv[1:4]
-assert operation == "mutate"
-request = json.loads(pathlib.Path(request_path).read_text())
-index = request["candidate_index"]
-barrier = pathlib.Path(os.environ["TOURNAMENT_BARRIER"])
-(barrier / f"mutation-{index}").write_text("started")
-deadline = time.monotonic() + 10
-while len(list(barrier.glob("mutation-*"))) != 4:
- assert time.monotonic() < deadline, "mutations did not run concurrently"
- time.sleep(0.01)
-attempt_path = barrier / f"mutator-attempts-{index}"
-attempts = int(attempt_path.read_text()) if attempt_path.exists() else 0
-attempt_path.write_text(str(attempts + 1))
-retry_marker = barrier / f"mutator-retried-{index}"
-if index == 0 and not retry_marker.exists():
- retry_marker.write_text("retry")
- raise SystemExit(19)
-if (barrier / f"fail-mutator-{index}").exists():
- print("PRIVATE_ADAPTER_CANARY_DO_NOT_EXPOSE /Users/private/repository", file=sys.stderr)
- raise SystemExit(31)
-parent = pathlib.Path(request["parent"]["path"]).read_text()
-child = parent.rstrip() + f"\n\nTournament variant {index}.\n"
-child_bytes = child.encode()
-pathlib.Path(request["child_path"]).write_bytes(child_bytes)
-response = {
- "schema": "codegraff.learn.mutation.response.v1",
- "trial_id": request["trial_id"],
- "candidate_index": index,
- "parent_id": request["parent"]["id"],
- "child_path": request["child_path"],
- "child_sha256": hashlib.sha256(child_bytes).hexdigest(),
- "description": f"PRIVATE_MUTATION_DESCRIPTION_{index}_DO_NOT_RENDER",
-}
-pathlib.Path(response_path).write_text(json.dumps(response, separators=(",", ":")) + "\n")
-'''
-
-
EVALUATOR = r'''import hashlib, json, os, pathlib, sys, time
operation, request_path, response_path = sys.argv[1:4]
request = json.loads(pathlib.Path(request_path).read_text())
@@ -87,6 +50,7 @@ if operation == "baseline":
"case_id": pair["case_id"], "seed": pair["seed"],
"pass": False, "score_ppm": 0, "cost_micros": 100,
"tool_calls_measured": True, "tool_calls": 10,
+ "behavior_measured": True, "behavior_score_ppm": 500000,
} for pair in request["pairs"]]
response = {
"schema": "codegraff.learn.primary-baseline.response.v1",
@@ -115,6 +79,7 @@ elif operation == "evaluate_primary":
retry_marker.write_text("retry")
raise SystemExit(17)
calls = [9, 7, 3, 5][index]
+ behavior_score = [900000, 950000, 800000, 1000000][index]
assert [(p["case_id"], p["seed"]) for p in baseline["pairs"]] == [
(p["case_id"], p["seed"]) for p in request["pairs"]
]
@@ -125,6 +90,9 @@ elif operation == "evaluate_primary":
"parent_cost_micros": parent["cost_micros"], "child_cost_micros": calls,
"tool_calls_measured": parent["tool_calls_measured"],
"parent_tool_calls": parent["tool_calls"], "child_tool_calls": calls,
+ "behavior_measured": parent["behavior_measured"],
+ "parent_behavior_score_ppm": parent["behavior_score_ppm"],
+ "child_behavior_score_ppm": behavior_score,
} for parent in baseline["pairs"]]
response = {
"schema": "codegraff.learn.primary-evaluation.response.v1",
@@ -149,12 +117,15 @@ elif operation == "evaluate":
if (barrier / "fail-holdout").exists():
raise SystemExit(23)
calls = [9, 7, 3, 5][index]
+ behavior_score = [900000, 950000, 800000, 1000000][index]
pairs = [{
"case_id": pair["case_id"], "seed": pair["seed"],
"parent_pass": False, "child_pass": True,
"parent_score_ppm": 0, "child_score_ppm": 1000000,
"parent_cost_micros": 100, "child_cost_micros": calls,
"tool_calls_measured": True, "parent_tool_calls": 10, "child_tool_calls": calls,
+ "behavior_measured": True,
+ "parent_behavior_score_ppm": 500000, "child_behavior_score_ppm": behavior_score,
} for pair in request["pairs"]]
response = {
"schema": "codegraff.learn.evaluation.response.v1",
@@ -265,6 +236,8 @@ def exercise(graff: Path, root: Path) -> None:
assert sum(candidate["holdout"] is not None for candidate in record["candidates"]) == 1
winner = next(candidate for candidate in record["candidates"] if candidate["holdout"] is not None)
assert winner["primary"]["child_tool_calls"] == 24
+ assert winner["primary"]["child_behavior_score_ppm"] == 800000
+ assert max(candidate["primary"]["child_behavior_score_ppm"] for candidate in record["candidates"]) == 1000000
assert all(
candidate["primary"]["correctness_regressions"] == 0
for candidate in record["candidates"]
@@ -274,10 +247,11 @@ def exercise(graff: Path, root: Path) -> None:
candidate["primary"]["parent_passes"],
candidate["primary"]["parent_tool_calls"],
candidate["primary"]["parent_cost_micros"],
+ candidate["primary"]["parent_behavior_score_ppm"],
)
for candidate in record["candidates"]
}
- assert parent_projections == {(0, 80, 800)}
+ assert parent_projections == {(0, 80, 800, 500000)}
assert winner["genome_id"] == record["primary_winner_genome_id"] == record["selected_genome_id"]
assert "manual promotion:" in output
assert "PRIVATE_MUTATION_DESCRIPTION" not in output
diff --git a/tests/learn_tournament_fixtures.py b/tests/learn_tournament_fixtures.py
new file mode 100644
index 00000000..64409159
--- /dev/null
+++ b/tests/learn_tournament_fixtures.py
@@ -0,0 +1,38 @@
+"""Adapter source fixtures shared by the tournament end-to-end test."""
+
+MUTATOR = r'''import hashlib, json, os, pathlib, sys, time
+operation, request_path, response_path = sys.argv[1:4]
+assert operation == "mutate"
+request = json.loads(pathlib.Path(request_path).read_text())
+index = request["candidate_index"]
+barrier = pathlib.Path(os.environ["TOURNAMENT_BARRIER"])
+(barrier / f"mutation-{index}").write_text("started")
+deadline = time.monotonic() + 10
+while len(list(barrier.glob("mutation-*"))) != 4:
+ assert time.monotonic() < deadline, "mutations did not run concurrently"
+ time.sleep(0.01)
+attempt_path = barrier / f"mutator-attempts-{index}"
+attempts = int(attempt_path.read_text()) if attempt_path.exists() else 0
+attempt_path.write_text(str(attempts + 1))
+retry_marker = barrier / f"mutator-retried-{index}"
+if index == 0 and not retry_marker.exists():
+ retry_marker.write_text("retry")
+ raise SystemExit(19)
+if (barrier / f"fail-mutator-{index}").exists():
+ print("PRIVATE_ADAPTER_CANARY_DO_NOT_EXPOSE /Users/private/repository", file=sys.stderr)
+ raise SystemExit(31)
+parent = pathlib.Path(request["parent"]["path"]).read_text()
+child = parent.rstrip() + f"\n\nTournament variant {index}.\n"
+child_bytes = child.encode()
+pathlib.Path(request["child_path"]).write_bytes(child_bytes)
+response = {
+ "schema": "codegraff.learn.mutation.response.v1",
+ "trial_id": request["trial_id"],
+ "candidate_index": index,
+ "parent_id": request["parent"]["id"],
+ "child_path": request["child_path"],
+ "child_sha256": hashlib.sha256(child_bytes).hexdigest(),
+ "description": f"PRIVATE_MUTATION_DESCRIPTION_{index}_DO_NOT_RENDER",
+}
+pathlib.Path(response_path).write_text(json.dumps(response, separators=(",", ":")) + "\n")
+'''
diff --git a/tests/learning_receipt_assertions.py b/tests/learning_receipt_assertions.py
index c218cdcd..533a69e6 100644
--- a/tests/learning_receipt_assertions.py
+++ b/tests/learning_receipt_assertions.py
@@ -7,12 +7,14 @@ import hmac
import re
from typing import Any
-SCHEMA = "codegraff.learn.grade.v2"
+SCHEMA = "codegraff.learn.grade.v3"
INTEGER_FIELDS = (
"pairs", "statistical_units", "parent_passes", "child_passes",
"child_critical_failures", "critical_regressions", "correctness_regressions",
"delta_ppm", "mean_score_delta_ppm", "p_value_ppb", "tool_calls_measured",
- "parent_tool_calls", "child_tool_calls", "tool_wins", "tool_losses", "tool_ties",
+ "parent_tool_calls", "child_tool_calls",
+ "behavior_measured", "parent_behavior_score_ppm", "child_behavior_score_ppm",
+ "tool_wins", "tool_losses", "tool_ties",
"tool_delta_ppm", "tool_p_value_ppb", "parent_cost_micros", "child_cost_micros",
"latency_measured", "parent_latency_ms", "child_latency_ms", "economy_eligible",
"eligible", "economy_gate_enabled", "alpha_ppm", "minimum_delta_ppm", "minimum_pairs",
@@ -124,6 +126,11 @@ def assert_learning_records(
assert values["tool_wins"] + values["tool_losses"] + values["tool_ties"] == values["statistical_units"]
else:
assert values["tool_wins"] == values["tool_losses"] == values["tool_ties"] == 0
+ assert values["behavior_measured"] in (0, 1)
+ for field in ("parent_behavior_score_ppm", "child_behavior_score_ppm"):
+ assert 0 <= values[field] <= 1_000_000
+ if not values["behavior_measured"]:
+ assert values["parent_behavior_score_ppm"] == values["child_behavior_score_ppm"] == 0
_assert_decision(values)
score_lines = [