graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(scoring): stdlib behavioral re-scorer + schema-harness replay (#246)
Rach Pradhan79da9273e65d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9f6bfc53..06931837 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -51,6 +51,9 @@ jobs:- name: Local learning lifecycle and security regressionrun: python3 tests/learn_e2e.py --graff zig-out/bin/graff+ - name: Behavioral trace stream, re-scorer, and replay round trip+ run: python3 scripts/test-behavior-trace.py zig-out/bin/graff+- name: JSON live-control protocol testrun: python3 scripts/test-json-controls.py zig-out/bin/graffdiff --git a/scripts/replay_schema_harness.py b/scripts/replay_schema_harness.pynew file mode 100644index 00000000..2ae23d49--- /dev/null+++ b/scripts/replay_schema_harness.py@@ -0,0 +1,72 @@+#!/usr/bin/env python3+"""Replay a schema-harness trajectory into the codegraff.behavior.v1 envelope.++Issue #246 validation criterion: converting the published ft09 events.jsonl+and re-scoring the converted stream must reproduce its published RHAE of+100.0 using only the events themselves.++The conversion is intentionally mechanical. The codegraff envelope requires+kind, seq (contiguous from 1), ts, run_id, and schema on every line;+kind-specific fields stay flat and untouched, and consumers ignore top-level+fields they do not know. Nothing outside the event file is consulted, so the+converted stream stays recomputable on its own.++Usage:+ python3 scripts/replay_schema_harness.py events.jsonl converted.jsonl+ python3 scripts/score_run.py --profile replay \+ --baseline baseline_actions.csv --game ft09 converted.jsonl+"""++from __future__ import annotations++import argparse+import json+import secrets+import sys+from pathlib import Path++SCHEMA = "codegraff.behavior.v1"+ENVELOPE = ("kind", "seq", "ts", "run_id", "schema")+++def convert(src: Path, dst: Path, run_id: str) -> dict:+ seq = 0+ kinds: dict[str, int] = {}+ with src.open(encoding="utf-8") as inp, dst.open("w", encoding="utf-8") as out:+ for line_no, line in enumerate(inp, start=1):+ line = line.strip()+ if not line:+ continue+ event = json.loads(line)+ if not isinstance(event, dict) or "kind" not in event:+ raise SystemExit(f"{src}:{line_no}: not an event object with a kind")+ seq += 1+ record = {+ "kind": event["kind"],+ "seq": seq,+ "ts": float(event.get("ts", 0.0)),+ "run_id": run_id,+ "schema": SCHEMA,+ }+ for key, value in event.items():+ if key not in ENVELOPE:+ record[key] = value+ out.write(json.dumps(record, separators=(",", ":")) + "\n")+ kinds[event["kind"]] = kinds.get(event["kind"], 0) + 1+ return {"run_id": run_id, "events": seq, "kinds": dict(sorted(kinds.items()))}+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("source", type=Path, help="schema-harness events.jsonl")+ parser.add_argument("target", type=Path, help="output codegraff.behavior.v1 JSONL")+ parser.add_argument("--run-id", default=None, help="run identifier (default: random hex)")+ args = parser.parse_args()+ summary = convert(args.source, args.target, args.run_id or secrets.token_hex(8))+ json.dump(summary, sys.stdout, indent=2)+ print()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/score_run.py b/scripts/score_run.pynew file mode 100644index 00000000..4f35e38c--- /dev/null+++ b/scripts/score_run.py@@ -0,0 +1,313 @@+#!/usr/bin/env python3+"""Recompute behavioral scores from a codegraff.behavior.v1 event stream.++Stdlib-only, mirroring the schema-harness score_trajectories.py contract from+issue #246: every number this prints is derived from the event lines alone, so+the trace itself is the audit. No harness state, run record, or database is+consulted.++Usage:+ python3 scripts/score_run.py .graff/trajectories/<run_id>.jsonl+ python3 scripts/score_run.py --profile replay --baseline baseline_actions.csv \+ --game ft09-0d8bbf25 converted.jsonl++Profiles:+ codegraff (default) strict Phase 1 producer audit: contiguous seq from 1,+ constant run_id/schema, single first run_started, terminal+ run_finished, dense turns, commitment/mispredict field checks.+ replay relaxed envelope audit for streams converted from external+ schema-harness trajectories (their turn_started/turn_committed+ carry task fields codegraff does not emit, and vice versa).++With --baseline and --game, completed-level actions are read from action_taken+events (level_up=true closes a level) and scored with the reference RHAE math:+per-level min(115, 100*(baseline/actions)^2), level-index weights, and a+completion cap of 100. A full-history WIN run therefore reproduces the+published schema-harness score exactly.++Exit codes: 0 = audit passed, 1 = audit failed, 2 = usage error.+"""++from __future__ import annotations++import argparse+import csv+import json+import sys+from pathlib import Path++SCHEMA = "codegraff.behavior.v1"+KINDS = {+ "run_started",+ "turn_started",+ "text_delta",+ "tool_started",+ "tool_finished",+ "turn_committed",+ "action_taken",+ "model_mispredicted",+ "run_finished",+}+PER_LEVEL_SCORE_CAP = 115.0+GAME_SCORE_CAP = 100.0+++class AuditError(Exception):+ pass+++def read_events(path: Path):+ """Yield parsed events. A malformed final line is truncation, not+ corruption: the writer can die mid-line, and consumers must process only+ complete JSON lines."""+ lines = path.read_text(encoding="utf-8").splitlines()+ total = len(lines)+ for index, line in enumerate(lines, start=1):+ if not line.strip():+ if index == total:+ break+ raise AuditError(f"line {index}: blank line inside the stream")+ try:+ event = json.loads(line)+ except json.JSONDecodeError as exc:+ if index == total:+ yield index, None+ return+ raise AuditError(f"line {index}: invalid JSON: {exc}") from exc+ if not isinstance(event, dict):+ raise AuditError(f"line {index}: event must be a JSON object")+ yield index, event+++def audit(path: Path, profile: str) -> dict:+ strict = profile == "codegraff"+ run_id = None+ prev_seq = 0+ seq_gaps = 0+ declared_local_dropped = None+ started = False+ finished = False+ truncated_tail = False+ terminal_status = None+ current_turn = 0+ turn_active = False+ turns = 0+ commitments = 0+ committed_turns = set()+ mispredicts = 0+ repair_gaps = []+ open_mispredict_seq = None+ counts: dict[str, int] = {}+ completed_levels: list[int] = []+ level_actions = 0+ total_actions = 0+ final_state = None++ for line_no, event in read_events(path):+ if event is None:+ truncated_tail = True+ break+ if finished:+ raise AuditError(f"line {line_no}: event after run_finished")++ for field in ("kind", "seq", "ts", "run_id", "schema"):+ if field not in event:+ raise AuditError(f"line {line_no}: missing envelope field {field!r}")+ kind = event["kind"]+ if kind not in KINDS:+ # Real schema-harness traces carry kinds beyond the nine (for+ # example turn_fallback). The reference scorer ignores kinds it+ # does not know; replayed conversions get the same tolerance,+ # while Phase 1 producers stay pinned to the documented set.+ if strict:+ raise AuditError(f"line {line_no}: unknown kind {kind!r}")+ if event["schema"] != SCHEMA:+ raise AuditError(f"line {line_no}: schema {event['schema']!r} != {SCHEMA!r}")+ seq = event["seq"]+ if not isinstance(seq, int) or seq <= prev_seq:+ raise AuditError(f"line {line_no}: seq {seq!r} is not strictly increasing (previous {prev_seq})")+ if seq != prev_seq + 1:+ if strict:+ # Phase 1 producers reserve seq before writing; an event+ # rejected pre-write leaves a gap that run_finished must+ # declare in local_dropped. The reconciliation happens after+ # the stream ends. Replay conversions renumber, so any gap+ # there is corruption.+ seq_gaps += seq - prev_seq - 1+ else:+ raise AuditError(f"line {line_no}: seq {seq!r} breaks contiguity (expected {prev_seq + 1})")+ prev_seq = seq+ if not isinstance(event["ts"], (int, float)):+ raise AuditError(f"line {line_no}: ts must be a number")+ if run_id is None:+ run_id = event["run_id"]+ elif event["run_id"] != run_id:+ raise AuditError(f"line {line_no}: run_id changed mid-stream")++ counts[kind] = counts.get(kind, 0) + 1++ if kind not in KINDS:+ continue+ if kind == "run_started":+ if started:+ raise AuditError(f"line {line_no}: duplicate run_started")+ if strict and seq != 1:+ raise AuditError(f"line {line_no}: run_started must be the first event")+ started = True+ elif kind == "turn_started":+ turn = event.get("turn")+ if not isinstance(turn, int) or turn < 1:+ raise AuditError(f"line {line_no}: turn_started needs a positive integer turn")+ if strict:+ if turn != current_turn + 1:+ raise AuditError(f"line {line_no}: behavioral turns must be dense (expected {current_turn + 1}, got {turn})")+ parent = event.get("parent_turn")+ if parent != current_turn:+ raise AuditError(f"line {line_no}: parent_turn {parent!r} != previous turn {current_turn}")+ current_turn = turn+ turn_active = True+ turns += 1+ elif kind == "turn_committed":+ commitments += 1+ if open_mispredict_seq is not None:+ repair_gaps.append(seq - open_mispredict_seq)+ open_mispredict_seq = None+ if strict:+ if not turn_active or event.get("turn") != current_turn:+ raise AuditError(f"line {line_no}: turn_committed outside its active turn")+ if not event.get("commitment_id"):+ raise AuditError(f"line {line_no}: turn_committed needs a nonempty commitment_id")+ turn = event.get("turn")+ if isinstance(turn, int):+ committed_turns.add(turn)+ elif kind == "model_mispredicted":+ mispredicts += 1+ open_mispredict_seq = seq+ if strict:+ if not turn_active or event.get("turn") != current_turn:+ raise AuditError(f"line {line_no}: model_mispredicted outside its active turn")+ if not event.get("commitment_id"):+ raise AuditError(f"line {line_no}: model_mispredicted needs a nonempty commitment_id")+ elif kind == "action_taken":+ total_actions += 1+ level_actions += 1+ if event.get("state") is not None:+ final_state = str(event["state"]).upper()+ if event.get("level_up") is True:+ completed_levels.append(level_actions)+ level_actions = 0+ elif kind == "run_finished":+ finished = True+ status = event.get("status")+ state = event.get("state")+ if strict and status not in ("closed", "error"):+ raise AuditError(f"line {line_no}: run_finished status must be closed or error, got {status!r}")+ terminal_status = status+ dropped = event.get("local_dropped")+ if dropped is not None:+ if not isinstance(dropped, int) or dropped < 0:+ raise AuditError(f"line {line_no}: local_dropped must be a non-negative integer")+ declared_local_dropped = dropped+ if state is not None:+ final_state = str(state).upper()+ elif strict:+ raise AuditError(f"line {line_no}: kind {kind!r} is reserved and not emitted by Phase 1 producers")++ if prev_seq == 0:+ raise AuditError("no events found")+ if strict and not started:+ raise AuditError("stream has no run_started")+ if strict and seq_gaps:+ # Gaps are only legitimate when the terminal event accounts for every+ # one of them; anything else is truncation or tampering.+ if not finished:+ raise AuditError(f"{seq_gaps} seq gap(s) in an incomplete stream")+ if declared_local_dropped != seq_gaps:+ raise AuditError(+ f"{seq_gaps} seq gap(s) but run_finished declares local_dropped={declared_local_dropped}"+ )++ return {+ "run_id": run_id,+ "events": prev_seq,+ "counts": dict(sorted(counts.items())),+ "complete": finished,+ "truncated_tail": truncated_tail,+ "terminal_status": terminal_status,+ "seq_gaps": seq_gaps,+ "local_dropped": declared_local_dropped,+ "turns": turns,+ "commitments": commitments,+ "mispredicts": mispredicts,+ "mispredict_rate": round(mispredicts / commitments, 6) if commitments else None,+ "commitment_coverage": round(len(committed_turns) / turns, 6) if turns else None,+ "mean_repair_gap_events": round(sum(repair_gaps) / len(repair_gaps), 3) if repair_gaps else None,+ "actions": total_actions,+ "completed_level_actions": completed_levels,+ "incomplete_level_actions": level_actions if level_actions else None,+ "final_state": final_state,+ }+++def load_baseline(path: Path, game: str) -> tuple[str, list[int]]:+ with path.open(encoding="utf-8", newline="") as handle:+ for row in csv.DictReader(handle):+ if game in (row.get("game", ""), row.get("game_id", "")):+ actions = []+ for index in range(1, 11):+ value = (row.get(f"level{index}") or "").strip()+ if value:+ actions.append(int(value))+ return row.get("game_id", game), actions+ raise AuditError(f"game {game!r} not found in {path}")+++def rhae(baseline: list[int], completed: list[int]) -> tuple[list[float], float]:+ if len(completed) > len(baseline):+ raise AuditError(f"completed {len(completed)} levels but the baseline defines {len(baseline)}")+ per_level = []+ for index, human in enumerate(baseline):+ if index < len(completed):+ per_level.append(min((human / completed[index]) ** 2 * 100.0, PER_LEVEL_SCORE_CAP))+ else:+ per_level.append(0.0)+ weights = list(range(1, len(baseline) + 1))+ total_weight = sum(weights)+ raw = sum(score * weight for score, weight in zip(per_level, weights)) / total_weight+ completion_cap = sum(range(1, len(completed) + 1)) / total_weight * GAME_SCORE_CAP+ return per_level, min(raw, completion_cap)+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("stream", type=Path, help="codegraff.behavior.v1 JSONL file")+ parser.add_argument("--profile", choices=("codegraff", "replay"), default="codegraff")+ parser.add_argument("--baseline", type=Path, help="schema-harness baseline_actions.csv for RHAE scoring")+ parser.add_argument("--game", help="game or game_id row to score against (with --baseline)")+ args = parser.parse_args()+ if bool(args.baseline) != bool(args.game):+ parser.error("--baseline and --game must be used together")++ try:+ report = audit(args.stream, args.profile)+ if args.baseline:+ game_id, baseline = load_baseline(args.baseline, args.game)+ per_level, score = rhae(baseline, report["completed_level_actions"])+ report["rhae"] = {+ "game_id": game_id,+ "baseline_actions": baseline,+ "per_level_scores": [round(s, 2) for s in per_level],+ "score": round(score, 2),+ }+ except AuditError as exc:+ json.dump({"ok": False, "error": str(exc)}, sys.stdout, indent=2)+ print()+ return 1+ report_out = {"ok": True, **report}+ json.dump(report_out, sys.stdout, indent=2)+ print()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/test-behavior-trace.py b/scripts/test-behavior-trace.pynew file mode 100644index 00000000..a149afac--- /dev/null+++ b/scripts/test-behavior-trace.py@@ -0,0 +1,232 @@+#!/usr/bin/env python3+"""E2E + unit checks for the behavioral trace stream and its re-scorer.++Build first, then run:+ python3 scripts/test-behavior-trace.py zig-out/bin/graff++Covers, hermetically (network stays on 127.0.0.1 and is refused):+ 1. A real one-shot session writes `.graff/behavior/<run_id>.jsonl` AND the+ legacy DGM trajectory `.graff/trajectories/<run_id>.jsonl` for the same+ run id. Regression for the exclusive-create collision that silently+ disabled local behavioral capture when both shared one directory.+ 2. The produced stream passes the strict Phase 1 audit in score_run.py.+ 3. score_run.py behavioral metrics and RHAE math on synthesized fixtures,+ including the replay_schema_harness.py conversion round trip.+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+from pathlib import Path++SCRIPTS = Path(__file__).resolve().parent+SCORE = SCRIPTS / "score_run.py"+REPLAY = SCRIPTS / "replay_schema_harness.py"+++def run(cmd: list[str], **kwargs) -> subprocess.CompletedProcess[str]:+ return subprocess.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120, **kwargs)+++def score(stream: Path, *args: str) -> dict:+ result = run([sys.executable, str(SCORE), *args, str(stream)])+ payload = json.loads(result.stdout)+ return {"exit": result.returncode, **payload}+++def check_live_session(graff: Path, root: Path) -> None:+ workspace = root / "live"+ workspace.mkdir()+ env = os.environ.copy()+ env.update({+ "GRAFF_NO_TELEMETRY": "1",+ # Refused immediately: the discard port on localhost is closed.+ "GRAFF_LMSTUDIO_URL": "http://127.0.0.1:9",+ })+ result = run([str(graff), "--model", "lmstudio", "say hi"], cwd=workspace, env=env)+ assert result.returncode != 0, "dead-endpoint one-shot should fail"++ behavior_files = sorted((workspace / ".graff" / "behavior").glob("*.jsonl"))+ assert len(behavior_files) == 1, f"expected one behavioral file, got {behavior_files}"+ run_id = behavior_files[0].stem+ trajectory = workspace / ".graff" / "trajectories" / f"{run_id}.jsonl"+ assert trajectory.is_file(), "legacy DGM trajectory must coexist for the same run id"++ report = score(behavior_files[0])+ assert report["exit"] == 0 and report["ok"], f"strict audit failed: {report}"+ assert report["run_id"] == run_id+ assert report["complete"] and report["terminal_status"] == "error"+ assert report["counts"]["run_started"] == 1+ assert report["counts"]["turn_started"] >= 1+ first = json.loads(behavior_files[0].read_text().splitlines()[0])+ assert first["kind"] == "run_started" and first["schema"] == "codegraff.behavior.v1"+ print("live session: behavioral + trajectory streams coexist; strict audit ok")+++def write_stream(path: Path, events: list[dict]) -> None:+ run_id = "feedbeeffeedbeef"+ with path.open("w", encoding="utf-8") as out:+ for seq, event in enumerate(events, start=1):+ record = {"seq": seq, "ts": 1770000000.0 + seq, "run_id": run_id,+ "schema": "codegraff.behavior.v1", **event}+ out.write(json.dumps(record) + "\n")+++def check_scorer(root: Path) -> None:+ # Behavioral metrics: 2 turns, 2 commitments, 1 mispredict, repair after.+ stream = root / "behavioral.jsonl"+ write_stream(stream, [+ {"kind": "run_started", "version": "test", "unix_ms": 1},+ {"kind": "turn_started", "turn": 1, "parent_turn": 0, "trajectory_node": 0},+ {"kind": "turn_committed", "turn": 1, "commitment_id": "c1",+ "action": {"kind": "edit"}, "expect": {"build": "passes"}, "reason": "try fix"},+ {"kind": "model_mispredicted", "turn": 1, "commitment_id": "c1",+ "predicted": {"build": "passes"}, "actual": {"build": "fails"}, "detail": "compile error"},+ {"kind": "turn_committed", "turn": 1, "commitment_id": "c2",+ "action": {"kind": "edit"}, "expect": {"build": "passes"}, "reason": "repair"},+ {"kind": "turn_started", "turn": 2, "parent_turn": 1, "trajectory_node": 0},+ {"kind": "run_finished", "status": "closed"},+ ])+ report = score(stream)+ assert report["ok"] and report["complete"]+ assert report["turns"] == 2 and report["commitments"] == 2 and report["mispredicts"] == 1+ assert report["mispredict_rate"] == 0.5+ assert report["commitment_coverage"] == 0.5+ assert report["mean_repair_gap_events"] == 1.0++ # Audit failures: seq gap, event after run_finished, dense-turn violation.+ gap = root / "gap.jsonl"+ write_stream(gap, [{"kind": "run_started", "version": "t", "unix_ms": 1},+ {"kind": "run_finished", "status": "closed"}])+ lines = gap.read_text().splitlines()+ doctored = json.loads(lines[1]); doctored["seq"] = 5+ gap.write_text(lines[0] + "\n" + json.dumps(doctored) + "\n")+ assert score(gap)["exit"] == 1, "seq gap must fail the audit"++ # Truncated tail: incomplete final line is truncation, not corruption.+ trunc = root / "trunc.jsonl"+ write_stream(trunc, [{"kind": "run_started", "version": "t", "unix_ms": 1},+ {"kind": "turn_started", "turn": 1, "parent_turn": 0, "trajectory_node": 0}])+ with trunc.open("a", encoding="utf-8") as out:+ out.write('{"kind":"run_fin')+ report = score(trunc)+ assert report["ok"] and report["truncated_tail"] and not report["complete"]++ # Declared local drops: a strict-profile seq gap is legal exactly when+ # run_finished accounts for it; anything else is truncation or tampering.+ def write_raw(path: Path, rows: list[tuple[int, dict]]) -> None:+ with path.open("w", encoding="utf-8") as out:+ for seq, event in rows:+ record = {"seq": seq, "ts": 1770000000.0 + seq, "run_id": "feedbeeffeedbeef",+ "schema": "codegraff.behavior.v1", **event}+ out.write(json.dumps(record) + "\n")++ declared = root / "declared-gap.jsonl"+ write_raw(declared, [+ (1, {"kind": "run_started", "version": "t", "unix_ms": 1}),+ (2, {"kind": "turn_started", "turn": 1, "parent_turn": 0, "trajectory_node": 0}),+ (4, {"kind": "run_finished", "status": "closed", "local_dropped": 1}),+ ])+ report = score(declared)+ assert report["ok"] and report["seq_gaps"] == 1 and report["local_dropped"] == 1, report++ undeclared = root / "undeclared-gap.jsonl"+ write_raw(undeclared, [+ (1, {"kind": "run_started", "version": "t", "unix_ms": 1}),+ (4, {"kind": "run_finished", "status": "closed", "local_dropped": 0}),+ ])+ assert score(undeclared)["exit"] == 1, "gap without matching declaration must fail"++ # RHAE math on a synthetic replay: 2 levels, baselines 4 and 6, agent 2 and+ # 3 actions. Both levels cap at 115; the completion cap holds it to 100.+ arc = root / "arc.jsonl"+ write_stream(arc, [+ {"kind": "run_started", "game_id": "toy-1"},+ {"kind": "action_taken", "step_index": 0, "state": "NOT_FINISHED"},+ {"kind": "action_taken", "step_index": 1, "state": "NOT_FINISHED", "level_up": True},+ {"kind": "action_taken", "step_index": 2, "state": "NOT_FINISHED"},+ {"kind": "action_taken", "step_index": 3, "state": "NOT_FINISHED"},+ {"kind": "action_taken", "step_index": 4, "state": "WIN", "level_up": True},+ {"kind": "run_finished", "state": "WIN", "actions": 5},+ ])+ baseline = root / "baseline.csv"+ baseline.write_text("game,game_id,n_levels,level1,level2\ntoy,toy-1,2,4,6\n")+ report = score(arc, "--profile", "replay", "--baseline", str(baseline), "--game", "toy-1")+ assert report["ok"], report+ assert report["completed_level_actions"] == [2, 3]+ assert report["rhae"]["per_level_scores"] == [115.0, 115.0]+ assert report["rhae"]["score"] == 100.0++ # Partial run: only level 1 completed. raw = 115*1/3, cap = 1/3*100.+ partial = root / "partial.jsonl"+ write_stream(partial, [+ {"kind": "run_started", "game_id": "toy-1"},+ {"kind": "action_taken", "step_index": 0, "state": "NOT_FINISHED", "level_up": True},+ {"kind": "action_taken", "step_index": 1, "state": "NOT_FINISHED"},+ {"kind": "run_finished", "state": "NOT_FINISHED", "actions": 2},+ ])+ report = score(partial, "--profile", "replay", "--baseline", str(baseline), "--game", "toy-1")+ assert report["ok"], report+ assert report["completed_level_actions"] == [1]+ assert report["rhae"]["score"] == round(min(115.0 * 1 / 3, 1 / 3 * 100.0), 2)+ print("scorer: behavioral metrics, audit failures, truncation, RHAE math ok")+++def check_replay_round_trip(root: Path) -> None:+ source = root / "harness-events.jsonl"+ events = [+ {"kind": "run_started", "seq": 10, "ts": 5.0, "game_id": "toy-1"},+ {"kind": "turn_started", "seq": 11, "ts": 6.0, "turn": 1, "grid": [[0]]},+ {"kind": "turn_committed", "seq": 12, "ts": 7.0, "turn": 1, "plan": ["up"], "reason": "explore"},+ {"kind": "action_taken", "seq": 13, "ts": 8.0, "turn": 1, "step_index": 0,+ "state": "WIN", "level_up": True},+ {"kind": "run_finished", "seq": 14, "ts": 9.0, "state": "WIN", "actions": 1},+ ]+ with source.open("w", encoding="utf-8") as out:+ for event in events:+ out.write(json.dumps(event) + "\n")+ converted = root / "converted.jsonl"+ result = run([sys.executable, str(REPLAY), str(source), str(converted), "--run-id", "abc123"])+ assert result.returncode == 0, result.stderr+ summary = json.loads(result.stdout)+ assert summary == {"run_id": "abc123", "events": 5,+ "kinds": {"action_taken": 1, "run_finished": 1, "run_started": 1,+ "turn_committed": 1, "turn_started": 1}}+ lines = [json.loads(l) for l in converted.read_text().splitlines()]+ assert [l["seq"] for l in lines] == [1, 2, 3, 4, 5], "seq must be renumbered contiguously"+ assert all(l["run_id"] == "abc123" and l["schema"] == "codegraff.behavior.v1" for l in lines)+ assert lines[2]["plan"] == ["up"] and lines[1]["grid"] == [[0]], "task fields must pass through"+ baseline = root / "baseline.csv"+ report = score(converted, "--profile", "replay", "--baseline", str(baseline), "--game", "toy-1")+ assert report["ok"] and report["rhae"]["score"] == round(min(115.0 * 1 / 3, 1 / 3 * 100.0), 2)+ print("replay: conversion round trip + re-score ok")+++def main() -> int:+ if len(sys.argv) != 2:+ print(f"usage: {sys.argv[0]} <graff-binary>", file=sys.stderr)+ return 2+ graff = Path(sys.argv[1]).resolve()+ if not graff.is_file():+ print(f"graff binary not found: {graff}", file=sys.stderr)+ return 2+ root = Path(tempfile.mkdtemp(prefix="codegraff-behavior-e2e."))+ try:+ check_live_session(graff, root)+ check_scorer(root)+ check_replay_round_trip(root)+ except Exception:+ print(f"behavior E2E failed; fixture preserved at {root}", file=sys.stderr)+ raise+ shutil.rmtree(root)+ print("behavior E2E passed")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())