graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(agent): harden concurrent long-running sessions
Rach Pradhan13ce9fc66c71
diff --git a/Agentic_Operating_System.md b/Agentic_Operating_System.mdindex 70d6d591..51bcd024 100644--- a/Agentic_Operating_System.md+++ b/Agentic_Operating_System.md@@ -90,8 +90,8 @@ Codegraff's design maps naturally onto operating-system concepts.| Scheduler | Workflow/fanout orchestration | `workflow`, parallel subagents || Memory manager | Context/history manager | compaction, session save/resume || Filesystem | Durable context substrate | repo files, `.harness/`, trace files |-| Profiler | Execution trace | `harness.trace.jsonl` |-| Process tree | Agent trajectory | `harness.trajectory.jsonl` |+| Profiler | Execution trace | `.graff/traces/<run-id>.jsonl` |+| Process tree | Agent trajectory | `.graff/trajectories/<run-id>.jsonl` || Program binary | Agent genome | system prompt / persona prompt || Package update | Fleet elite pull | `pullElites` |@@ -237,8 +237,8 @@ An AOS needs multiple memory tiers:|---|---|---|| L1 working memory | Current prompt/history inside the model context | active messages || L2 session memory | Durable state for the current run | `last.session.json` |-| L3 trace memory | Profiling and debugging history | `harness.trace.jsonl` |-| L4 trajectory memory | Evolutionary lineage and scores | `harness.trajectory.jsonl` |+| L3 trace memory | Profiling and debugging history | `.graff/traces/<run-id>.jsonl` |+| L4 trajectory memory | Evolutionary lineage and scores | `.graff/trajectories/<run-id>.jsonl` || L5 project/user memory | Cross-session task knowledge | proposed `.harness/memory/` || L6 fleet memory | Shared behavioral improvements | promoted personas/elites |@@ -265,14 +265,14 @@ A key design rule from Codegraff's memory docs is that memory should not mutateAn AOS must be observable. If the agent is a process, then we need process telemetry.-Codegraff writes a session trace to `harness.trace.jsonl`. The trace records API calls, tool calls, latency, byte counts, context token counts, and errors. This lets the agent inspect its own execution behavior.+Codegraff writes a run-exclusive trace to `.graff/traces/<run-id>.jsonl`. The trace records API calls, tool calls, latency, byte counts, context token counts, errors, and correlation identity. This lets the agent inspect its own execution behavior without colliding with another process.That creates a feedback loop:```mermaidsequenceDiagramparticipant Agent- participant Trace as harness.trace.jsonl+ participant Trace as .graff/traces/run-id.jsonlparticipant UserAgent->>Trace: record API/tool eventsdiff --git a/README.md b/README.mdindex e89020c7..78cf437e 100644--- a/README.md+++ b/README.md@@ -231,8 +231,9 @@ and points at the one-line install; everything else keeps working without it.graff doesn't just run an agent; it records every run as a node in a**Darwin Gödel Machine-style archive tree** ([arXiv:2505.22954](https://arxiv.org/abs/2505.22954)),-so the harness itself is the substrate for agent self-improvement. Each session-appends to `harness.trajectory.jsonl` (truncated per session, like the trace):+so the harness itself is the substrate for agent self-improvement. Each run+writes a unique `.graff/trajectories/<run-id>.jsonl`; archive readers aggregate+the directory, so concurrent processes never share a truncate/append cursor:- **A lineage tree, not a flat log.** Root turns form a spine (each turn'sparent is the previous one); every subagent and workflow task hangs off the@@ -359,6 +360,7 @@ flags:--timing show per-tool wall-clock on result lines (✓ (312ms) …)--cost show running session spend in the prompt ([model · 12k tok · $0.0042])--json structured stdio protocol (JSON in, JSONL events out, SDK transport)+ --max-model-calls N cap provider calls across root, children, retries, titles, compaction, and judges (default 256)-h, --help usage-V, --version version```@@ -426,7 +428,7 @@ other animation names remain available./paste attach the clipboard image (macOS); also Ctrl-V (⌘V can't be captured)/strict toggle "every message is a tool" mode/yolo toggle bash auto-approval (skip permission prompts)-/trace toggle the JSONL event trace (harness.trace.jsonl)+/trace toggle this run's JSONL event trace and show its path/compact summarize history into a fresh context/save | /resume | /sessions session persistence; bare /resume → interactive picker/todo show the current task list@@ -740,7 +742,7 @@ real Anthropic API the harness also sets an explicit `cache_control` breakpoint.Cache reads are surfaced: `recordUsage` parses `cache_read_input_tokens`(Anthropic) and `prompt_cache_hit_tokens` / `prompt_tokens_details.cached_tokens`(OpenAI/DeepSeek), and every `api` trace line carries a `cache_read_tokens` field-so you can see the hit rate in `harness.trace.jsonl`.+so you can see the hit rate in the current `.graff/traces/<run-id>.jsonl`.The one deliberate exception is `set_system_prompt` (--json protocol / SDK`setSystemPrompt`): the system prompt is the *first* token of the cached prefix,@@ -759,11 +761,20 @@ and forth inside an agent loop.**Tracing: the harness can debug itself.** Every API round trip (latency,request/response bytes, context tokens) and every tool execution (duration,-result size, errors, root-vs-subagent) is appended as one JSON line to-`harness.trace.jsonl` in the cwd, truncated at startup so it always covers the-current session. The system prompt tells the agent the file exists, so "profile-yourself" or "why was that slow?" makes the agent read its own trace and answer-from data. `/trace` toggles it.+result size, errors, root-vs-subagent) is appended as one JSON line to the+run's unique `.graff/traces/<run-id>.jsonl`. Every line carries the run id, PID,+and runtime session id; concurrent processes therefore remain independently+inspectable. The system prompt tells the agent how to locate the file, so+"profile yourself" or "why was that slow?" makes it answer from data. `/trace`+toggles tracing and prints the exact path.++Long tool results are stored exactly under `.graff/tool-results/`; model history+receives a short preview and an inspectable file pointer instead. Responses+requests are explicitly capped at 16k output tokens (4k for compaction and 64+for titles), while compaction carries the latest clean ~8k-token user-turn+suffix forward verbatim. A shared atomic run budget allows at most four model+calls concurrently and one subagent level; set the total provider-call ceiling+with `--max-model-calls N` or the lower-precedence `GRAFF_MAX_MODEL_CALLS`.**Telemetry, pseudonymous, opt-out, on by default.** *Every* build (release,source, and dev) bakes in a default OTLP endpoint (pass `-Dtelemetry-endpoint=""`diff --git a/architecture.md b/architecture.mdindex a23e3ec1..ff1207c4 100644--- a/architecture.md+++ b/architecture.md@@ -420,15 +420,17 @@ prompt — and it keeps the per-call cost of the disabled case at one## Tracing-One shared `Tracer` (an `Io.Mutex`, an `Io.Writer` over `harness.trace.jsonl`,-and a monotonic `Io.Timestamp` start) is threaded through every agent and+One shared `Tracer` (an `Io.Mutex`, an `Io.Writer` over the run-exclusive+`.graff/traces/<run-id>.jsonl`, and a monotonic `Io.Timestamp` start) is+threaded through every agent and`ToolCtx`, the same way as `Approvals`. `Agent.request` records each API call(latency ms, request/response bytes, context tokens, error flag, agentlabel); `execTool` wraps every external tool with timing. Events are structsserialized by `std.json.Stringify` — one line each, flushed immediately, so-the file is always valid JSONL mid-session. The system prompt points the-agent at the file, which is what makes self-debugging work: the agent reads-its own trace with `read_file` and analyzes it. `/trace` toggles, best-effort+the file is always valid JSONL mid-session. Every line carries the run id,+PID, and runtime session id. The system prompt points the agent at the file,+which is what makes self-debugging work: the agent reads its own trace with+`read_file` and analyzes it. `/trace` locates and toggles it, best-effort(a failed open just disables tracing).## Compactiondiff --git a/docs/hyperagents.md b/docs/hyperagents.mdindex e1a9bfe5..dfeab5cb 100644--- a/docs/hyperagents.md+++ b/docs/hyperagents.md@@ -32,8 +32,8 @@ visible in the trajectory log —## 2. Trajectory mapping (the DGM archive tree)-`harness.trajectory.jsonl` (truncated per session, like the trace) holds one-JSON node per agent run, in exactly the shape of the DGM's archive tree:+Each run-scoped `.graff/trajectories/<run-id>.jsonl` holds one JSON node per+agent run, in exactly the shape of the DGM's archive tree:nodes are agents, edges are parent→child, and every node carries thefingerprint of the program (here: system prompt) it ran with.@@ -55,10 +55,11 @@ fingerprint of the program (here: system prompt) it ran with.fingerprint is captured once per session as a `kind:"prompt"` record, sothe archive is self-contained: any lineage can be replayed or re-mutatedfrom the file alone.-- **Append-only archive**: unlike the trace, the trajectory file is never- truncated — sessions accumulate, each opening with a `kind:"session"`- header (node ids restart per session; cross-session lineage threads- through `prompt_sha`). Delete the file any time to reset the archive.+- **Append-only aggregate archive**: each process exclusively creates one+ run file, so concurrent sessions never share a cursor. Readers scan all+ `.graff/trajectories/*.jsonl` files (plus the old single-file archive during+ migration). Node ids restart per run; cross-run lineage threads through+ `prompt_sha`. Delete the directory any time to reset the archive.- **Scores**: the evaluation phase writes back through the --json protocol —`{"type":"score","prompt_sha":"…","score":0.7,"notes":"…"}` appends a`kind:"score"` record (SDK: `h.score(prompt_or_sha, value, notes)`, with@@ -88,7 +89,7 @@ code (Python/TS), not in the harness:- **Evaluate** = run the child on a task set; score its reports (anLLM-judge subagent, exit-code checks, benchmark diffs — whatever fits thedomain). Write scores back as an annotation file keyed by `prompt_sha`.-- **Archive** = the union of `harness.trajectory.jsonl` files across runs+- **Archive** = the union of `.graff/trajectories/*.jsonl` files across runsplus the score annotations. The trajectory gives lineage (`parent`,`prompt_sha`, `prompt_mutated`); the annotations give `performance(aᵢ)`and children counts — everything DGM-H's parent selection needs:@@ -105,17 +106,17 @@ Sketch of the driver loop (Python SDK) — everything below is wired today:```pythonfrom harness_sdk import Harness, prompt_fingerprint-archive = load("harness.trajectory.jsonl") # prompt records + nodes + scores+archive = load_all(".graff/trajectories/*.jsonl") # prompts + nodes + scoresh = Harness(yolo=True)for _ in range(iterations):parent = sample(archive, key=lambda a: sigmoid(a.score) / (1 + a.children))child = h.ask(f"Mutate this agent prompt to fix its weakest behavior:\n{parent.text}")report = h.ask(f'Use the subagent tool: prompt "{task}", system_prompt "{child}"')h.score(child, judge(report)) # kind:"score" appended, keyed by sha- archive = load("harness.trajectory.jsonl") # node+prompt+score all captured+ archive = load_all(".graff/trajectories/*.jsonl") # all captured```-The archive file is the single source of truth: the harness captures the+The aggregate archive is the single source of truth: the harness captures thelineage (`kind:"turn"/"subagent"` nodes), the genomes (`kind:"prompt"`),and the fitness (`kind:"score"`); the driver only decides what to mutateand how to judge.@@ -199,7 +200,7 @@ lineage chain intact in `parent_sha`, and each child's tool sequence(`bash,bash`) recorded against its fingerprint.Tool-sequence mining then works on either store: locally,-`jq 'select(.kind=="subagent")' harness.trajectory.jsonl` joined to scores+`jq 'select(.kind=="subagent")' .graff/trajectories/*.jsonl` joined to scoresby sha; in D1, `run` events land in `harness_events` (attrs JSON includes`tools`, `ok`, `variant`) and `harness_variant_children` gives the noveltyterm. Patterns with positive lift feed back as prompt instructions or as@@ -209,8 +210,8 @@ per-niche tool grants (`agent_variants.tools`).The four-agent debate (and the honest threat model) converged on one crux:the fitness float was both *ungrounded* (an LLM grading a self-report) and-*unauthenticated* — a forged `{"kind":"score",…}` row appended to-`harness.trajectory.jsonl` via `write_file` (cwd is inside `confinedPath`)+*unauthenticated* — a forged `{"kind":"score",…}` row appended to a+trajectory JSONL via `write_file` (cwd is inside `confinedPath`)or `echo >>` manufactures fitness AND `parent_sha` lineage that selectionthen rewards. A perfect judge doesn't matter if nothing forces the loopthrough it. So Step 0 authenticates the channel; it's the precondition for@@ -221,8 +222,10 @@ where `msg` is the canonical, version-tagged, newline-joined tuple`v2\n{prompt_sha}\n{parent_sha}\n{score:.6f}\n{run_id}\n{judge_id}\n{artifact_sha}\n{eval_set_hash}\n{niche}\n{provider_class}`(score fixed to 6 decimals so Zig/Python/JS agree byte-for-byte —`src/scoring.zig scoreSigMessage`, `harness_sdk.score_signature`, the worker's-`scoreSignature`). Records gain `run_id` (per-session), `judge_id`,-`artifact_sha`, `eval_set_hash` so the evaluator, the artifact it judged,+`scoreSignature`). Run-scoped files reserve top-level `run_id` for invocation+identity and store the signed score provenance as `score_run_id` (legacy/D1+rows use `run_id`). Records also gain `judge_id`, `artifact_sha`, and+`eval_set_hash` so the evaluator, the artifact it judged,and the held-out eval are all bound into the signature; v2 (issue #168 Gap 2)additionally binds `niche` and `provider_class` so a score can't be replayedinto another MAP-Elites cell. Verifiers still accept the legacy `v1` envelopediff --git a/docs/memory-architecture.md b/docs/memory-architecture.mdindex 6a563a16..bd3ab548 100644--- a/docs/memory-architecture.md+++ b/docs/memory-architecture.md@@ -20,7 +20,7 @@ minimal memory layer native, with engram as one backend among several.|---|---|---|| purpose | solve the current & future *tasks* better | improve the *agent itself* over generations || unit | an episode / fact / note | a genome (prompt + tools + memory design) + its fitness |-| store | `.harness/memory/` (this doc) | `harness.trajectory.jsonl` + `harness_scores` |+| store | `.harness/memory/` (this doc) | `.graff/trajectories/*.jsonl` + `harness_scores` || lifetime | reused across turns/sessions/projects | append-only archive, fleet-aggregated |They interact (the memory Design is a *slot in the genome* — §8), but they are@@ -188,4 +188,3 @@ The minimal version is small — a meta-tool pair + a JSONL episode store + asession-start scratchpad — and it immediately makes long-horizon runs lessamnesiac without touching the hot path or the KV-cache.```-diff --git a/examples/dgm_loop.py b/examples/dgm_loop.pyindex 035d3577..4a54d72b 100644--- a/examples/dgm_loop.py+++ b/examples/dgm_loop.py@@ -6,7 +6,7 @@ The least things a DGM needs, and where each lives:1. genome a system prompt(auto-captured: kind:"prompt" records in the archive)2. archive+lineage variants, their fitness, and who-was-mutated-from-whom- (auto-captured: harness.trajectory.jsonl; lineage via+ (auto-captured: .graff/trajectories/*.jsonl; lineage viascore(parent=…))3. evaluate grounded, Step 1: a held-out replay judge in a separateprocess is the primary gradient (replay_eval below);@@ -37,7 +37,24 @@ import syssys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "sdk", "py"))from harness_sdk import Harness, prompt_fingerprint, verify_score # noqa: E402-ARCHIVE = "harness.trajectory.jsonl"+ARCHIVE_DIR = os.path.join(".graff", "trajectories")+LEGACY_ARCHIVE = "harness.trajectory.jsonl"+++def archive_paths():+ """Current run-scoped archive files plus the pre-migration legacy file."""+ paths = []+ try:+ paths.extend(+ os.path.join(ARCHIVE_DIR, name)+ for name in sorted(os.listdir(ARCHIVE_DIR))+ if name.endswith(".jsonl")+ )+ except FileNotFoundError:+ pass+ if os.path.isfile(LEGACY_ARCHIVE):+ paths.append(LEGACY_ARCHIVE)+ return pathsdef _score_key():@@ -62,28 +79,27 @@ def load_archive():"""genomes: sha → prompt text; scores: sha → [values]; children: sha → n.When GRAFF_SCORE_KEY_FILE is set, score rows must carry a valid HMAC or- they are dropped (and counted) — a forged `echo >> harness.trajectory.jsonl`- row can't poison fitness or manufacture lineage."""+ they are dropped (and counted) — a forged trajectory score row can't+ poison fitness or manufacture lineage."""key = _score_key()genomes, scores, children = {}, collections.defaultdict(list), collections.Counter()seen_edges = set()rejected = 0- try:- for ln in open(ARCHIVE):- o = json.loads(ln)- if o.get("kind") == "prompt":- genomes[o["prompt_sha"]] = o["text"]- elif o.get("kind") == "score":- if key is not None and not verify_score(key, o):- rejected += 1- continue- scores[o["prompt_sha"]].append(o["score"])- p = o.get("parent_sha")- if p and (p, o["prompt_sha"]) not in seen_edges:- seen_edges.add((p, o["prompt_sha"]))- children[p] += 1- except FileNotFoundError:- pass+ for path in archive_paths():+ with open(path, encoding="utf-8") as archive:+ for ln in archive:+ o = json.loads(ln)+ if o.get("kind") == "prompt":+ genomes[o["prompt_sha"]] = o["text"]+ elif o.get("kind") == "score":+ if key is not None and not verify_score(key, o):+ rejected += 1+ continue+ scores[o["prompt_sha"]].append(o["score"])+ p = o.get("parent_sha")+ if p and (p, o["prompt_sha"]) not in seen_edges:+ seen_edges.add((p, o["prompt_sha"]))+ children[p] += 1if rejected:print(f" [archive] rejected {rejected} unsigned/forged score row(s)")return genomes, scores, childrendiff --git a/scripts/test-pty-codex-ws.py b/scripts/test-pty-codex-ws.pyindex e794a7ac..ce6fc057 100644--- a/scripts/test-pty-codex-ws.py+++ b/scripts/test-pty-codex-ws.py@@ -278,6 +278,8 @@ def assert_midturn_requests(mock: CodexMock) -> None:f"midturn: expected exactly 3 model requests, got {len(requests)}: {requests!r}")first, compact, final = requests+ if [request.body.get("max_output_tokens") for request in requests] != [16000, 4096, 16000]:+ raise AssertionError("midturn: expected root/compaction/root output caps 16k/4k/16k")transports = [request.transport for request in requests]if transports != ["ws", "sse", "ws"]:raise AssertionError(f"midturn: expected WS -> SSE -> WS, got {transports!r}")@@ -350,7 +352,7 @@ def assert_midturn_requests(mock: CodexMock) -> None:or len(final_input) != 1or len(final_texts) != 1or not final_texts[0].startswith(- "Context: the prior conversation was compacted"+ "Context: the earlier conversation was compacted")or MIDTURN_SUMMARY not in final_texts[0]or "tools" not in final.body@@ -369,6 +371,8 @@ def assert_transactional_requests(mock: CodexMock) -> None:f"got {len(requests)}: {requests!r}")first, compact, final = requests+ if [request.body.get("max_output_tokens") for request in requests] != [16000, 4096, 16000]:+ raise AssertionError("transactional: expected root/compaction/root output caps 16k/4k/16k")transports = [request.transport for request in requests]if transports != ["ws", "sse", "ws"]:raise AssertionError(@@ -615,12 +619,20 @@ def main() -> None:"ok codex WS primary: mock reply + ctx meter over WebSocket",),(- "ws-forced-fallback",+ "ws-clean-retry",{"GRAFF_WS_FORCE_FAIL_ONCE": "1"},+ 1,+ 0,+ "WebSocket primary with automatic SSE fallback",+ "ok codex first WS failure: clean WS retry succeeded without latching fallback",+ ),+ (+ "ws-forced-fallback",+ {"GRAFF_WS_FORCE_FAIL_COUNT": "2"},0,1,"SSE fallback (WebSocket failed this session)",- "ok codex forced WS failure: SSE fallback reply + ctx meter + latched health",+ "ok codex second WS failure: persistent SSE fallback reply + latched health",),("ws-off",diff --git a/scripts/test-run-budget.py b/scripts/test-run-budget.pynew file mode 100644index 00000000..898bbf74--- /dev/null+++ b/scripts/test-run-budget.py@@ -0,0 +1,96 @@+#!/usr/bin/env python3+"""Smoke the run-wide budget's root-priority behavior at a one-call ceiling."""++from __future__ import annotations++import json+import os+import sys+import tempfile++from codex_ws_mock import CodexMock, turn_events+from pty_harness import PtySession+++_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg+ROOT_REPLY = "RUN_BUDGET_ROOT_OK"+++def main() -> None:+ def events(request):+ result = turn_events(f"resp_budget_{request.ordinal}")+ result[0]["item"]["content"][0]["text"] = ROOT_REPLY+ return result++ mock = CodexMock(events_for_request=events)+ port = mock.start()+ try:+ with tempfile.TemporaryDirectory(prefix="graff-run-budget-") as tmp:+ codex_home = os.path.join(tmp, "codex-home")+ os.makedirs(codex_home)+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:+ json.dump(+ {+ "tokens": {+ "access_token": "run-budget-mock",+ "account_id": "acct-run-budget",+ }+ },+ fh,+ )+ harness_dir = os.path.join(tmp, ".harness")+ os.makedirs(harness_dir)+ with open(os.path.join(harness_dir, "settings.json"), "w", encoding="utf-8") as fh:+ json.dump({"ai_title": True, "skills": {"codedbpro": False}}, fh)++ env = {+ "HOME": tmp,+ "CODEX_HOME": codex_home,+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",+ "GRAFF_CODEX_WS": "off",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_TELEMETRY": "1",+ # The explicit CLI ceiling below must win over this default.+ "GRAFF_MAX_MODEL_CALLS": "0",+ }+ ambient = tuple(+ name+ for name in os.environ+ if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR")+ and name not in env+ )+ with PtySession(+ GRAFF,+ ["--model", "codex", "--max-model-calls", "1", "--no-telemetry"],+ cwd=tmp,+ env=env,+ unset_env=ambient,+ timeout=10.0,+ ) as session:+ session.wait_for_literal("] ›")+ cursor = len(session.raw)+ session.send_line("answer even though AI titles are enabled")+ session.wait_for_literal(ROOT_REPLY, start=cursor)+ session.wait_for_literal("] ›", start=cursor)+ session.send_key("ctrl-d")+ result = session.read_until_exit(5.0)+ if result.timed_out or result.exit_code != 0:+ raise AssertionError(+ f"session exit={result.exit_code} timed_out={result.timed_out}"+ )+ finally:+ mock.stop()++ requests = mock.recorded_requests()+ if len(requests) != 1:+ raise AssertionError(f"one-call ceiling admitted {len(requests)} requests")+ if "You summarize what a coding session is about" in requests[0].body.get(+ "instructions", ""+ ):+ raise AssertionError("cosmetic title consumed the root's final call")+ print("ok one-call run budget reserved its final slot for the root answer")+++if __name__ == "__main__":+ main()diff --git a/scripts/test-run-isolation.py b/scripts/test-run-isolation.pynew file mode 100644index 00000000..ff16a461--- /dev/null+++ b/scripts/test-run-isolation.py@@ -0,0 +1,141 @@+#!/usr/bin/env python3+"""Prove simultaneous graff processes write isolated, correlated JSONL."""++from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile++from codex_ws_mock import CodexMock+++_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg+++def records(path: str) -> list[dict]:+ with open(path, "rb") as fh:+ raw = fh.read()+ if not raw or b"\x00" in raw:+ raise AssertionError(f"empty/corrupt JSONL: {path}")+ parsed = []+ for number, line in enumerate(raw.splitlines(), 1):+ try:+ parsed.append(json.loads(line))+ except json.JSONDecodeError as exc:+ raise AssertionError(f"{path}:{number}: invalid JSON: {exc}") from exc+ return parsed+++def validate_run_file(path: str) -> tuple[str, int, str]:+ run_id = os.path.basename(path).removesuffix(".jsonl")+ rows = records(path)+ identity = (run_id, rows[0].get("pid"), rows[0].get("session_id"))+ if not isinstance(identity[1], int) or not isinstance(identity[2], str):+ raise AssertionError(f"missing PID/session identity: {path}")+ if len(identity[2]) != 32 or any(c not in "0123456789abcdef" for c in identity[2]):+ raise AssertionError(f"malformed session id in {path}: {identity[2]!r}")+ for row in rows:+ current = (row.get("run_id"), row.get("pid"), row.get("session_id"))+ if current != identity:+ raise AssertionError(f"mixed identity in {path}: {current!r} != {identity!r}")+ return identity+++def main() -> None:+ mock = CodexMock()+ port = mock.start()+ try:+ with tempfile.TemporaryDirectory(prefix="graff-run-isolation-") as tmp:+ codex_home = os.path.join(tmp, "codex-home")+ os.makedirs(codex_home)+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:+ json.dump(+ {+ "tokens": {+ "access_token": "run-isolation-mock",+ "account_id": "acct-run-isolation",+ }+ },+ fh,+ )+ harness_dir = os.path.join(tmp, ".harness")+ os.makedirs(harness_dir)+ with open(os.path.join(harness_dir, "settings.json"), "w", encoding="utf-8") as fh:+ json.dump({"skills": {"codedbpro": False}}, fh)++ env = {+ key: value+ for key, value in os.environ.items()+ if not key.startswith("GRAFF_") and not key.startswith("CODEX_")+ }+ env.update(+ {+ "HOME": tmp,+ "CODEX_HOME": codex_home,+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",+ "GRAFF_CODEX_WS": "off",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_TELEMETRY": "1",+ }+ )+ processes = [+ subprocess.Popen(+ [+ GRAFF,+ "--model",+ "codex",+ "--no-telemetry",+ "--no-resume",+ "-p",+ f"reply to simultaneous run {index}",+ ],+ cwd=tmp,+ env=env,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ )+ for index in range(2)+ ]+ expected_pids = {process.pid for process in processes}+ for process in processes:+ stdout, stderr = process.communicate(timeout=15)+ if process.returncode != 0:+ raise AssertionError(+ f"graff pid {process.pid} exited {process.returncode}\n"+ f"stdout:\n{stdout}\nstderr:\n{stderr}"+ )++ trace_dir = os.path.join(tmp, ".graff", "traces")+ trajectory_dir = os.path.join(tmp, ".graff", "trajectories")+ traces = sorted(os.path.join(trace_dir, name) for name in os.listdir(trace_dir))+ trajectories = sorted(+ os.path.join(trajectory_dir, name) for name in os.listdir(trajectory_dir)+ )+ if len(traces) != 2 or len(trajectories) != 2:+ raise AssertionError(+ f"expected two trace + trajectory files, got {traces!r}, {trajectories!r}"+ )++ trace_ids = {validate_run_file(path) for path in traces}+ trajectory_ids = {validate_run_file(path) for path in trajectories}+ if trace_ids != trajectory_ids:+ raise AssertionError(+ f"trace/trajectory correlation mismatch: {trace_ids!r} != {trajectory_ids!r}"+ )+ if {pid for _run_id, pid, _session_id in trace_ids} != expected_pids:+ raise AssertionError(+ f"record PIDs do not match child processes: {trace_ids!r}, {expected_pids!r}"+ )+ finally:+ mock.stop()++ print("ok two simultaneous runs produced isolated, fully correlated JSONL")+++if __name__ == "__main__":+ main()diff --git a/scripts/test-title-parallel.py b/scripts/test-title-parallel.pyindex 6306c4cd..dc0dd268 100644--- a/scripts/test-title-parallel.py+++ b/scripts/test-title-parallel.py@@ -15,6 +15,7 @@ from pty_harness import PtySession_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"GRAFF = os.path.abspath(_arg) if os.sep in _arg else _argMAIN_REPLY = "PARALLEL_TITLE_MAIN_OK"+TITLE_DELAY_SECONDS = 1.5def message_item(text: str, item_id: str) -> dict:@@ -45,6 +46,11 @@ def main() -> None:barrier.wait(timeout=3.0)except threading.BrokenBarrierError:pass+ # The title deliberately finishes well after the main reply. A detached+ # implementation paints the next prompt immediately; an end-of-turn+ # join makes the user wait for this sleep.+ if is_title:+ time.sleep(TITLE_DELAY_SECONDS)text = "Parallel title generation" if is_title else MAIN_REPLYreturn [{@@ -114,7 +120,7 @@ def main() -> None:)with PtySession(GRAFF,- ["--model", "codex", "--no-telemetry"],+ ["--model", "codex", "--max-model-calls", "2", "--no-telemetry"],cwd=tmp,env=env,unset_env=ambient,@@ -122,9 +128,16 @@ def main() -> None:) as session:session.wait_for_literal("] ›")cursor = len(session.raw)+ sent_at = time.monotonic()session.send_line("make the title and answer overlap")session.wait_for_literal(MAIN_REPLY, start=cursor)session.wait_for_literal("] ›", start=cursor)+ prompt_elapsed = time.monotonic() - sent_at+ if prompt_elapsed >= TITLE_DELAY_SECONDS - 0.4:+ raise AssertionError(+ "next prompt waited for detached title "+ f"({prompt_elapsed:.2f}s)"+ )session.send_key("ctrl-d")result = session.read_until_exit(5.0)if result.timed_out or result.exit_code != 0:@@ -138,10 +151,26 @@ def main() -> None:observed = sorted(arrivals)if len(observed) != 2 or {kind for _, kind in observed} != {"title", "main"}:raise AssertionError(f"expected one title and one main request: {observed!r}")+ requests = mock.recorded_requests()+ limits = {+ (+ "title"+ if "You summarize what a coding session is about"+ in request.body.get("instructions", "")+ else "main"+ ): request.body.get("max_output_tokens")+ for request in requests+ }+ if limits != {"title": 64, "main": 16000}:+ raise AssertionError(f"unexpected Responses output caps: {limits!r}")delta_ms = (observed[1][0] - observed[0][0]) * 1000if delta_ms > 750:raise AssertionError(f"title/main requests serialized ({delta_ms:.1f}ms apart)")- print(f"ok AI title and main turn overlapped ({delta_ms:.1f}ms apart)")+ print(+ "ok AI title and main turn overlapped "+ f"({delta_ms:.1f}ms apart); prompt returned in {prompt_elapsed:.2f}s "+ f"while title stayed busy for {TITLE_DELAY_SECONDS:.1f}s"+ )if __name__ == "__main__":diff --git a/scripts/test-tool-preview.py b/scripts/test-tool-preview.pynew file mode 100644index 00000000..d99fac93--- /dev/null+++ b/scripts/test-tool-preview.py@@ -0,0 +1,158 @@+#!/usr/bin/env python3+"""Prove large tool output is persisted while model history stays concise."""++from __future__ import annotations++import json+import os+import re+import sys+import tempfile++from codex_ws_mock import CodexMock, RecordedRequest+from pty_harness import PtySession+++_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg+FINAL_REPLY = "TOOL_PREVIEW_OK"+PAYLOAD = "large-tool-result:" + "x" * 6000+++def message_item(text: str, item_id: str) -> dict:+ return {+ "type": "message",+ "id": item_id,+ "status": "completed",+ "role": "assistant",+ "content": [{"type": "output_text", "text": text, "annotations": []}],+ }+++def response_events(item: dict, response_id: str) -> list[dict]:+ return [+ {"type": "response.output_item.done", "item": item},+ {+ "type": "response.completed",+ "response": {+ "id": response_id,+ "usage": {+ "input_tokens": 100,+ "input_tokens_details": {"cached_tokens": 0},+ "output_tokens": 10,+ "total_tokens": 110,+ },+ },+ },+ ]+++def events(request: RecordedRequest) -> list[dict]:+ if request.ordinal == 1:+ return response_events(+ {+ "type": "function_call",+ "id": "fc_large_read",+ "call_id": "call_large_read",+ "name": "read_file",+ "arguments": json.dumps({"path": "large.txt"}),+ "status": "completed",+ },+ "resp_large_read",+ )+ return response_events(message_item(FINAL_REPLY, "msg_preview_done"), "resp_preview_done")+++def main() -> None:+ mock = CodexMock(events_for_request=events)+ port = mock.start()+ try:+ with tempfile.TemporaryDirectory(prefix="graff-tool-preview-") as tmp:+ with open(os.path.join(tmp, "large.txt"), "w", encoding="utf-8") as fh:+ fh.write(PAYLOAD)+ codex_home = os.path.join(tmp, "codex-home")+ os.makedirs(codex_home)+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:+ json.dump(+ {+ "tokens": {+ "access_token": "tool-preview-mock",+ "account_id": "acct-tool-preview",+ }+ },+ fh,+ )+ harness_dir = os.path.join(tmp, ".harness")+ os.makedirs(harness_dir)+ with open(os.path.join(harness_dir, "settings.json"), "w", encoding="utf-8") as fh:+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)++ env = {+ "HOME": tmp,+ "CODEX_HOME": codex_home,+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",+ "GRAFF_CODEX_WS": "off",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_TELEMETRY": "1",+ }+ ambient = tuple(+ name+ for name in os.environ+ if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR")+ and name not in env+ )+ with PtySession(+ GRAFF,+ ["--model", "codex", "--no-telemetry"],+ cwd=tmp,+ env=env,+ unset_env=ambient,+ timeout=10.0,+ ) as session:+ session.wait_for_literal("] ›")+ cursor = len(session.raw)+ session.send_line("read the large file, then finish")+ session.wait_for_literal(FINAL_REPLY, start=cursor)+ session.wait_for_literal("] ›", start=cursor)+ session.send_key("ctrl-d")+ result = session.read_until_exit(5.0)+ if result.timed_out or result.exit_code != 0:+ raise AssertionError(+ f"session exit={result.exit_code} timed_out={result.timed_out}"+ )++ requests = mock.recorded_requests()+ if len(requests) != 2:+ raise AssertionError(f"expected tool loop in two requests: {requests!r}")+ second_input = requests[1].body.get("input")+ outputs = [+ item.get("output")+ for item in second_input+ if isinstance(item, dict) and item.get("type") == "function_call_output"+ ] if isinstance(second_input, list) else []+ if len(outputs) != 1 or not isinstance(outputs[0], str):+ raise AssertionError(f"missing function_call_output: {second_input!r}")+ preview = outputs[0]+ if len(preview) > 2000:+ raise AssertionError(f"model-facing preview is {len(preview)} chars")+ match = re.search(+ r"\[full tool result: (\.graff/tool-results/[0-9a-f]+-\d+\.txt) — inspect with read_file\]",+ preview,+ )+ if match is None:+ raise AssertionError(f"preview has no inspect pointer: {preview!r}")+ detail_path = os.path.join(tmp, match.group(1))+ with open(detail_path, encoding="utf-8") as fh:+ persisted = fh.read()+ if persisted != PAYLOAD:+ raise AssertionError(+ f"persisted tool result changed ({len(persisted)} != {len(PAYLOAD)})"+ )+ finally:+ mock.stop()++ print("ok large tool output persisted exactly; model history received a <=2k preview")+++if __name__ == "__main__":+ main()diff --git a/sdk/generate.py b/sdk/generate.pyindex 1b883d4d..f47ed667 100644--- a/sdk/generate.py+++ b/sdk/generate.py@@ -89,8 +89,8 @@ export type Event =| {{ type: "score"; ok: boolean; prompt_sha: string }}| {{ type: "error"; message: string }};-/** Fingerprint of a system prompt as used in harness.trajectory.jsonl —- * the append-only DGM-style archive — and by `Harness.score()`:+/** Fingerprint of a system prompt as used in `.graff/trajectories` —+ * the aggregate DGM-style archive — and by `Harness.score()`:* first 8 bytes of SHA-256, hex (16 chars). */export function promptFingerprint(text: string): string {{return createHash("sha256").update(text).digest("hex").slice(0, 16);@@ -115,6 +115,8 @@ export interface HarnessOptions {{appendSystemPrompt?: string;/** Hard per-turn root tool-call budget. */maxToolCalls?: number;+ /** Invocation-wide provider-call ceiling shared by all agent work. */+ maxModelCalls?: number;/** Reject duplicate root tool name+normalized-input calls per turn. */dedupeToolCalls?: boolean;/** Extra raw flags. `--json` is always added. */@@ -142,6 +144,7 @@ function spawnArgs(o: HarnessOptions): string[] {{if (o.yolo) a.push("--yolo");if (o.model) a.push("--model", o.model);if (o.maxToolCalls !== undefined) a.push("--max-tool-calls", String(o.maxToolCalls));+ if (o.maxModelCalls !== undefined) a.push("--max-model-calls", String(o.maxModelCalls));if (o.dedupeToolCalls) a.push("--dedupe-tool-calls");if (o.systemPrompt) a.push("--system-prompt", o.systemPrompt);if (o.appendSystemPrompt) a.push("--append-system-prompt", o.appendSystemPrompt);@@ -367,7 +370,7 @@ export class Harness {{appendSystemPrompt(text: string): Promise<void> {{ return this.setSystemPrompt(text, true); }}/** Record an evaluation score for an agent/prompt variant in the- * trajectory archive (harness.trajectory.jsonl) — the DGM evaluation+ * aggregate `.graff/trajectories` archive — the DGM evaluation* phase writing back. `promptOrSha` is either the full system-prompt* text (fingerprinted for you) or an existing 16-hex fingerprint.* Pass `parent` (text or sha) when the variant was mutated from another@@ -547,6 +550,8 @@ export interface RemoteOptions {{appendSystemPrompt?: string;/** Hard per-turn root tool-call budget for the child session. */maxToolCalls?: number;+ /** Invocation-wide provider-call ceiling shared by all agent work. */+ maxModelCalls?: number;/** Reject duplicate root tool name+normalized-input calls per turn. */dedupeToolCalls?: boolean;/** Attach to an existing session instead of creating one. */@@ -636,6 +641,7 @@ export class RemoteHarness {{if (opts.systemPrompt) body.system_prompt = opts.systemPrompt;if (opts.appendSystemPrompt) body.append_system_prompt = opts.appendSystemPrompt;if (opts.maxToolCalls !== undefined) body.maxToolCalls = opts.maxToolCalls;+ if (opts.maxModelCalls !== undefined) body.maxModelCalls = opts.maxModelCalls;if (opts.dedupeToolCalls !== undefined) body.dedupeToolCalls = opts.dedupeToolCalls;const res = await this.req("POST", "/v1/sessions", body);const data = (await res.json()) as {{ session_id: string }};@@ -884,8 +890,8 @@ def _fleet_signal(kind: str, attrs: Optional[dict] = None) -> None:def prompt_fingerprint(text: str) -> str:- """Fingerprint of a system prompt as used in harness.trajectory.jsonl —- the append-only DGM-style archive — and by `Harness.score()`:+ """Fingerprint of a system prompt as used in `.graff/trajectories` —+ the aggregate DGM-style archive — and by `Harness.score()`:first 8 bytes of SHA-256, hex (16 chars)."""return hashlib.sha256(text.encode()).hexdigest()[:16]@@ -917,9 +923,13 @@ def verify_score(key: bytes, rec: dict) -> bool:sig = rec.get("sig") or ""if not sig:return False+ # Run-scoped JSONL reserves top-level `run_id` for invocation identity.+ # Score provenance therefore uses `score_run_id`; legacy/D1 records still+ # carry the signed value as `run_id`.+ signed_run_id = rec.get("score_run_id", rec.get("run_id", ""))want = score_signature(key, rec.get("prompt_sha", ""), rec.get("parent_sha", "") or "",- float(rec.get("score", "nan")), rec.get("run_id", ""),+ float(rec.get("score", "nan")), signed_run_id,rec.get("judge_id", ""), rec.get("artifact_sha", ""),rec.get("eval_set_hash", ""),# D1 returns NULL (None) for an empty niche/provider_class — "{{}}"@@ -930,7 +940,7 @@ def verify_score(key: bytes, rec: dict) -> bool:return Truelegacy = "v1\\n{{}}\\n{{}}\\n{{:.6f}}\\n{{}}\\n{{}}\\n{{}}\\n{{}}".format(rec.get("prompt_sha", ""), rec.get("parent_sha", "") or "",- float(rec.get("score", "nan")), rec.get("run_id", ""),+ float(rec.get("score", "nan")), signed_run_id,rec.get("judge_id", ""), rec.get("artifact_sha", ""),rec.get("eval_set_hash", ""))return hmac.compare_digest(@@ -950,7 +960,8 @@ class Harness:system_prompt: Optional[str] = None,append_system_prompt: Optional[str] = None,max_tool_calls: Optional[int] = None,- dedupe_tool_calls: bool = False):+ dedupe_tool_calls: bool = False,+ max_model_calls: Optional[int] = None):binary = binary or _default_binary()argv = [binary, "--json"]if yolo:@@ -959,6 +970,8 @@ class Harness:argv += ["--model", model]if max_tool_calls is not None:argv += ["--max-tool-calls", str(max_tool_calls)]+ if max_model_calls is not None:+ argv += ["--max-model-calls", str(max_model_calls)]if dedupe_tool_calls:argv.append("--dedupe-tool-calls")if system_prompt:@@ -1069,7 +1082,7 @@ class Harness:artifact_sha: str = "", eval_set_hash: str = "",niche: str = "", scale: str = "") -> None:"""Record an evaluation score for an agent/prompt variant in the- trajectory archive (harness.trajectory.jsonl) — the DGM evaluation+ aggregate trajectory archive (`.graff/trajectories`) — the DGM evaluationphase writing back. `prompt_or_sha` is either the full system-prompttext (fingerprinted for you) or an existing 16-hex fingerprint.Pass `parent` (text or sha) when the variant was mutated from@@ -1196,7 +1209,8 @@ class RemoteHarness:append_system_prompt: Optional[str] = None,max_tool_calls: Optional[int] = None,dedupe_tool_calls: bool = False,- session_id: Optional[str] = None):+ session_id: Optional[str] = None,+ max_model_calls: Optional[int] = None):self.base = url.rstrip("/")self.token = tokenif session_id is not None:@@ -1213,6 +1227,8 @@ class RemoteHarness:opts["append_system_prompt"] = append_system_promptif max_tool_calls is not None:opts["maxToolCalls"] = max_tool_calls+ if max_model_calls is not None:+ opts["maxModelCalls"] = max_model_callsif dedupe_tool_calls:opts["dedupeToolCalls"] = Trueresp = self._request("POST", "/v1/sessions", opts)diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.pyindex 95ced6c2..efe0f3a1 100644--- a/sdk/py/harness_sdk.py+++ b/sdk/py/harness_sdk.py@@ -138,8 +138,8 @@ def _fleet_signal(kind: str, attrs: Optional[dict] = None) -> None:def prompt_fingerprint(text: str) -> str:- """Fingerprint of a system prompt as used in harness.trajectory.jsonl —- the append-only DGM-style archive — and by `Harness.score()`:+ """Fingerprint of a system prompt as used in `.graff/trajectories` —+ the aggregate DGM-style archive — and by `Harness.score()`:first 8 bytes of SHA-256, hex (16 chars)."""return hashlib.sha256(text.encode()).hexdigest()[:16]@@ -171,9 +171,13 @@ def verify_score(key: bytes, rec: dict) -> bool:sig = rec.get("sig") or ""if not sig:return False+ # Run-scoped JSONL reserves top-level `run_id` for invocation identity.+ # Score provenance therefore uses `score_run_id`; legacy/D1 records still+ # carry the signed value as `run_id`.+ signed_run_id = rec.get("score_run_id", rec.get("run_id", ""))want = score_signature(key, rec.get("prompt_sha", ""), rec.get("parent_sha", "") or "",- float(rec.get("score", "nan")), rec.get("run_id", ""),+ float(rec.get("score", "nan")), signed_run_id,rec.get("judge_id", ""), rec.get("artifact_sha", ""),rec.get("eval_set_hash", ""),# D1 returns NULL (None) for an empty niche/provider_class — "{}"@@ -184,7 +188,7 @@ def verify_score(key: bytes, rec: dict) -> bool:return Truelegacy = "v1\n{}\n{}\n{:.6f}\n{}\n{}\n{}\n{}".format(rec.get("prompt_sha", ""), rec.get("parent_sha", "") or "",- float(rec.get("score", "nan")), rec.get("run_id", ""),+ float(rec.get("score", "nan")), signed_run_id,rec.get("judge_id", ""), rec.get("artifact_sha", ""),rec.get("eval_set_hash", ""))return hmac.compare_digest(@@ -204,7 +208,8 @@ class Harness:system_prompt: Optional[str] = None,append_system_prompt: Optional[str] = None,max_tool_calls: Optional[int] = None,- dedupe_tool_calls: bool = False):+ dedupe_tool_calls: bool = False,+ max_model_calls: Optional[int] = None):binary = binary or _default_binary()argv = [binary, "--json"]if yolo:@@ -213,6 +218,8 @@ class Harness:argv += ["--model", model]if max_tool_calls is not None:argv += ["--max-tool-calls", str(max_tool_calls)]+ if max_model_calls is not None:+ argv += ["--max-model-calls", str(max_model_calls)]if dedupe_tool_calls:argv.append("--dedupe-tool-calls")if system_prompt:@@ -323,7 +330,7 @@ class Harness:artifact_sha: str = "", eval_set_hash: str = "",niche: str = "", scale: str = "") -> None:"""Record an evaluation score for an agent/prompt variant in the- trajectory archive (harness.trajectory.jsonl) — the DGM evaluation+ aggregate trajectory archive (`.graff/trajectories`) — the DGM evaluationphase writing back. `prompt_or_sha` is either the full system-prompttext (fingerprinted for you) or an existing 16-hex fingerprint.Pass `parent` (text or sha) when the variant was mutated from@@ -450,7 +457,8 @@ class RemoteHarness:append_system_prompt: Optional[str] = None,max_tool_calls: Optional[int] = None,dedupe_tool_calls: bool = False,- session_id: Optional[str] = None):+ session_id: Optional[str] = None,+ max_model_calls: Optional[int] = None):self.base = url.rstrip("/")self.token = tokenif session_id is not None:@@ -467,6 +475,8 @@ class RemoteHarness:opts["append_system_prompt"] = append_system_promptif max_tool_calls is not None:opts["maxToolCalls"] = max_tool_calls+ if max_model_calls is not None:+ opts["maxModelCalls"] = max_model_callsif dedupe_tool_calls:opts["dedupeToolCalls"] = Trueresp = self._request("POST", "/v1/sessions", opts)diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex 633b5638..fa6c2707 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -38,8 +38,8 @@ export type Event =| { type: "score"; ok: boolean; prompt_sha: string }| { type: "error"; message: string };-/** Fingerprint of a system prompt as used in harness.trajectory.jsonl —- * the append-only DGM-style archive — and by `Harness.score()`:+/** Fingerprint of a system prompt as used in `.graff/trajectories` —+ * the aggregate DGM-style archive — and by `Harness.score()`:* first 8 bytes of SHA-256, hex (16 chars). */export function promptFingerprint(text: string): string {return createHash("sha256").update(text).digest("hex").slice(0, 16);@@ -64,6 +64,8 @@ export interface HarnessOptions {appendSystemPrompt?: string;/** Hard per-turn root tool-call budget. */maxToolCalls?: number;+ /** Invocation-wide provider-call ceiling shared by all agent work. */+ maxModelCalls?: number;/** Reject duplicate root tool name+normalized-input calls per turn. */dedupeToolCalls?: boolean;/** Extra raw flags. `--json` is always added. */@@ -91,6 +93,7 @@ function spawnArgs(o: HarnessOptions): string[] {if (o.yolo) a.push("--yolo");if (o.model) a.push("--model", o.model);if (o.maxToolCalls !== undefined) a.push("--max-tool-calls", String(o.maxToolCalls));+ if (o.maxModelCalls !== undefined) a.push("--max-model-calls", String(o.maxModelCalls));if (o.dedupeToolCalls) a.push("--dedupe-tool-calls");if (o.systemPrompt) a.push("--system-prompt", o.systemPrompt);if (o.appendSystemPrompt) a.push("--append-system-prompt", o.appendSystemPrompt);@@ -316,7 +319,7 @@ export class Harness {appendSystemPrompt(text: string): Promise<void> { return this.setSystemPrompt(text, true); }/** Record an evaluation score for an agent/prompt variant in the- * trajectory archive (harness.trajectory.jsonl) — the DGM evaluation+ * aggregate `.graff/trajectories` archive — the DGM evaluation* phase writing back. `promptOrSha` is either the full system-prompt* text (fingerprinted for you) or an existing 16-hex fingerprint.* Pass `parent` (text or sha) when the variant was mutated from anotherdiff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex 5964f7d5..59bc65f7 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -58,6 +58,8 @@ export interface RemoteOptions {appendSystemPrompt?: string;/** Hard per-turn root tool-call budget for the child session. */maxToolCalls?: number;+ /** Invocation-wide provider-call ceiling shared by all agent work. */+ maxModelCalls?: number;/** Reject duplicate root tool name+normalized-input calls per turn. */dedupeToolCalls?: boolean;/** Attach to an existing session instead of creating one. */@@ -147,6 +149,7 @@ export class RemoteHarness {if (opts.systemPrompt) body.system_prompt = opts.systemPrompt;if (opts.appendSystemPrompt) body.append_system_prompt = opts.appendSystemPrompt;if (opts.maxToolCalls !== undefined) body.maxToolCalls = opts.maxToolCalls;+ if (opts.maxModelCalls !== undefined) body.maxModelCalls = opts.maxModelCalls;if (opts.dedupeToolCalls !== undefined) body.dedupeToolCalls = opts.dedupeToolCalls;const res = await this.req("POST", "/v1/sessions", body);const data = (await res.json()) as { session_id: string };diff --git a/src/agent.zig b/src/agent.zigindex bd68d086..c4e3966b 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -37,6 +37,7 @@ const schema = @import("schema.zig");const pricing = @import("pricing.zig");const models_cache = @import("models_cache.zig");const keys_cli = @import("keys_cli.zig");+const run_budget_mod = @import("run_budget.zig");const ansi = @import("ansi.zig");const style = &ansi.style;@@ -133,6 +134,9 @@ pub const Agent = struct {registry: ?*mcp.Registry = null,approvals: ?*approvals_mod.Approvals = null, // shared bash-approval state, set by main()tracer: ?*trace.Tracer = null, // shared JSONL event trace, set by main()+ run_budget: ?*run_budget_mod.RunBudget = null, // shared invocation-wide call/concurrency ceiling+ depth: u8 = 0, // root/auxiliary = 0; delegated child = 1+ call_kind: run_budget_mod.CallKind = .root,last_cache_read: u64 = 0, // KV-cache read tokens from the latest responsesys_normal: []const u8 = prompts.main_system_prompt, // root system prompt (+ project instructions)sys_override: ?[]const u8 = null, // subagent-only: per-child system prompt (swarm prompt variants)@@ -190,10 +194,12 @@ pub const Agent = struct {partial_text: std.ArrayList(u8) = .empty,stream_quiet: bool = false, // suppress live streaming (one-shot and internal requests)compaction_request: bool = false, // the current model call is the synthetic compaction-summary request+ responses_output_limit: ?u32 = null, // auxiliary override (title=64); compaction always uses 4096last_request_context_overflow: bool = false, // explicit provider rejection, not an inferred meter thresholdlast_request_write_failed: bool = false, // transport gave up specifically with WriteFailed this requestcompact_transport_failures: u8 = 0, // bounded escape for repeated opaque over-cap WriteFailed/network failuresws_off: bool = false, // codex ws transport disabled for this session after a handshake/transport fallback to SSE (#codex-ws)+ ws_transport_failures: u8 = 0, // consecutive WS failures; retry once before latching persistent SSEstreamed_text: bool = false, // the last request printed its text livethinking_open: bool = false, // a live "Thinking" reasoning block is currently streaming (/thinking)thinking_rows: usize = 0, // on-screen rows the live Thinking block spans (#75 collapse)@@ -202,6 +208,7 @@ pub const Agent = struct {thinking_folded: bool = false, // user folded the live Thinking block (#92)thinking_text: std.ArrayList(u8) = .empty, // buffered reasoning, so a fold can unfold (#92)ai_title_done: bool = false, // the one-time AI tab-title call has run this session+ title_generation: u64 = 0, // invalidates detached results across /clear, /new, and manual /renamearg_live: ArgLive = .{}, // live attempt_completion/ask_user argument textstreamed_args: ArgTool = .none, // which meta tool's prose streamed live this requeststreamed_args_len: usize = 0, // raw bytes emitted for it (gates re-print suppression)@@ -498,6 +505,7 @@ pub const Agent = struct {pub const appendEvalLog = @import("agent_compact.zig").appendEvalLog;pub const runJudge = @import("agent_compact.zig").runJudge;pub const compact = @import("agent_compact.zig").compact;+ pub const recentContextStart = @import("agent_compact.zig").recentContextStart;pub const cleanUserTurn = @import("agent_compact.zig").cleanUserTurn;pub const emergencyCutIndex = @import("agent_compact.zig").emergencyCutIndex;pub const emergencyTrim = @import("agent_compact.zig").emergencyTrim;diff --git a/src/agent_compact.zig b/src/agent_compact.zigindex fcdaba2d..1bba75c4 100644--- a/src/agent_compact.zig+++ b/src/agent_compact.zig@@ -2,6 +2,7 @@//! recovery when a summary request cannot run.const std = @import("std");+const Io = std.Io;const Value = std.json.Value;const Allocator = std.mem.Allocator;const utf8Prefix = @import("util.zig").utf8Prefix;@@ -23,6 +24,35 @@ pub const runEval = agent_eval.runEval;pub const appendEvalLog = agent_eval.appendEvalLog;pub const runJudge = agent_eval.runJudge;+pub const recent_context_tokens: u64 = 8_000;++fn serializedTokens(value: Value) u64 {+ var buf: [256]u8 = undefined;+ var d: Io.Writer.Discarding = .init(&buf);+ var s: std.json.Stringify = .{ .writer = &d.writer };+ s.write(value) catch {};+ return @intCast(d.fullCount() / 4);+}++/// Pick the earliest clean user-turn boundary whose suffix fits in the recent+/// context budget. Returning items.len means "summarize everything". We never+/// split at a tool output, so retained call/result history stays valid.+pub fn recentContextStart(items: []const Value, token_budget: u64) usize {+ if (items.len == 0 or token_budget == 0) return items.len;+ var total: u64 = 0;+ var start = items.len;+ var i = items.len;+ while (i > 0) {+ i -= 1;+ total +|= serializedTokens(items[i]);+ if (total > token_budget) break;+ if (cleanUserTurn(items[i])) start = i;+ }+ // If the entire conversation fits, summarizing all is the only operation+ // that can actually reduce context; otherwise compaction would be a no-op.+ return if (start == 0) items.len else start;+}+/// Ask the model for a context-handoff summary (no tools), then restart/// history from that summary.pub fn summaryResponseComplete(self: *Agent, root: std.json.ObjectMap) bool {@@ -75,7 +105,13 @@ pub fn compact(self: *Agent) anyerror!usize {const live_context_tokens = self.last_context_tokens;const live_context_local_tokens = self.context_local_tokens;const live_effective_context = self.effectiveContextTokens();- self.messages = try cloneJsonArray(compact_arena, live_messages);+ const recent_start = recentContextStart(live_messages.items, recent_context_tokens);+ const recent_messages = live_messages.items[recent_start..];+ var summary_messages = std.json.Array.init(compact_arena);+ try summary_messages.ensureTotalCapacity(recent_start);+ for (live_messages.items[0..recent_start]) |item|+ try summary_messages.append(try cloneJsonValue(compact_arena, item));+ self.messages = summary_messages;var installed_summary = false;defer if (!installed_summary) {self.messages = live_messages;@@ -124,14 +160,17 @@ pub fn compact(self: *Agent) anyerror!usize {var fresh = std.json.Array.init(self.arena);const handoff = try std.fmt.allocPrint(self.arena,- \\Context: the prior conversation was compacted to save space.- \\Summary of everything so far:+ \\Context: the earlier conversation was compacted to save space.+ \\Summary of the earlier work:\\\\{s}\\\\Continue assisting the user based on this summary., .{summary});try fresh.append(try textMessage(self.arena, "user", handoff));+ // Preserve a valid recent suffix verbatim (up to ~8k estimated tokens),+ // including its user boundary and paired tool calls/results.+ for (recent_messages) |message| try fresh.append(message);self.messages = fresh;self.last_context_tokens = 0;self.context_local_tokens = 0;diff --git a/src/agent_compact_test.zig b/src/agent_compact_test.zigindex 1c9bf340..0b1c60e3 100644--- a/src/agent_compact_test.zig+++ b/src/agent_compact_test.zig@@ -14,6 +14,7 @@ const trimOldestToolOutputsAlloc = compact.trimOldestToolOutputsAlloc;const repeatedOpaqueCompactionFailure = compact.repeatedOpaqueCompactionFailure;const trimOldestToolOutputs = compact.trimOldestToolOutputs;const capOversizedToolOutputs = compact.capOversizedToolOutputs;+const recentContextStart = compact.recentContextStart;const cleanUserTurn = compact.cleanUserTurn;const emergencyCutIndex = compact.emergencyCutIndex;const emergencyTrim = compact.emergencyTrim;@@ -232,6 +233,27 @@ test "trimOldestToolOutputs recovers a runaway tool-loop history (#163)" {try std.testing.expectEqual(@as(usize, 11), agent.messages.items.len); // no message dropped}+test "recentContextStart keeps a clean recent suffix and never orphans tool output" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var msgs = std.json.Array.init(a);+ try msgs.append(try textMessage(a, "user", "old request"));+ try msgs.append(try textMessage(a, "assistant", "x" ** 36_000));+ try msgs.append(try textMessage(a, "user", "recent request"));+ try msgs.append(try std.json.parseFromSliceLeaky(Value, a, "{\"type\":\"function_call_output\",\"call_id\":\"c1\",\"output\":\"recent result\"}", .{}));+ try msgs.append(try textMessage(a, "assistant", "recent answer"));++ const start = recentContextStart(msgs.items, 8_000);+ try std.testing.expectEqual(@as(usize, 2), start);+ try std.testing.expect(cleanUserTurn(msgs.items[start]));+ try std.testing.expectEqualStrings("recent request", msgs.items[start].object.get("content").?.string);++ // A short entire conversation must still compact rather than retain all+ // messages and perform a no-op summary.+ try std.testing.expectEqual(msgs.items[2..].len, recentContextStart(msgs.items[2..], 8_000));+}+test "capOversizedToolOutputs (#193): bounds an oversized output in every wire format, leaves small ones + non-tool msgs" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();diff --git a/src/agent_eval.zig b/src/agent_eval.zigindex f853fc2f..9c2b9a43 100644--- a/src/agent_eval.zig+++ b/src/agent_eval.zig@@ -183,6 +183,8 @@ pub fn runJudge(self: *Agent, rubric: []const u8, eval_output: []const u8, note:.from_sub = self.sub,.approvals = self.approvals,.tracer = self.tracer,+ .run_budget = self.run_budget,+ .depth = self.depth,.snapshots = self.snapshots,.tools_used = &self.tools_used,};diff --git a/src/agent_request.zig b/src/agent_request.zigindex 61e3d736..cf453bbc 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -25,6 +25,7 @@ const tools_mod = @import("tools.zig");const apiErrorMessage = tools_mod.apiErrorMessage;const mentionsReasoningEffort = tools_mod.mentionsReasoningEffort;const telemetry = @import("telemetry.zig");+const run_budget_mod = @import("run_budget.zig");const policy = @import("agent_request_policy.zig");const errorCode = policy.errorCode;@@ -74,6 +75,20 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {// Startup paints the prompt while CA loading continues. The root turn and// title task rendezvous here, then issue their requests concurrently.http.waitForClientReady(self.io);+ var budget_permit: ?run_budget_mod.Permit = null;+ if (self.run_budget) |budget| {+ const kind: run_budget_mod.CallKind = if (self.compaction_request) .compaction else self.call_kind;+ budget_permit = budget.acquire(self.io, self.depth, kind) catch |err| {+ self.last_api_error = switch (err) {+ error.RunBudgetExhausted => "model-call budget exhausted for this graff run — restart or raise --max-model-calls",+ error.AgentDepthExceeded => "agent depth limit reached (max depth 1)",+ else => @errorName(err),+ };+ if (self.tracer) |tr| tr.note("budget", self.last_api_error.?);+ return err;+ };+ }+ defer if (budget_permit) |*permit| permit.release();self.last_request_context_overflow = false;self.last_request_write_failed = false;self.last_usage_includes_output = false;@@ -153,8 +168,11 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {};self.streamed_text = false;self.streamed_args = .none;- // Esc is a deliberate stop, not a flaky network — no retry.+ // Esc and task cancellation are deliberate stops, not flaky+ // transport. In particular, session-close cancellation of a+ // detached title must not launch a replacement request.if (err == error.Interrupted) return error.Interrupted;+ if (err == error.Canceled) return error.Canceled;// #56: a mid-stream idle stall or a connection drop (the// provider closed/reset before its terminal event) — NOT a// user Esc, which is handled above. Usually transient, sodiff --git a/src/agent_request_body.zig b/src/agent_request_body.zigindex 6d0266fc..6eb80b59 100644--- a/src/agent_request_body.zig+++ b/src/agent_request_body.zig@@ -11,6 +11,11 @@ const serde = @import("serde.zig");const writeAnthropicMessages = serde.writeAnthropicMessages;const writeOpenAIMessageNormalized = serde.writeOpenAIMessageNormalized;+pub fn responsesOutputLimit(self: *const Agent) u32 {+ if (self.compaction_request) return 4096;+ return self.responses_output_limit orelse max_tokens;+}+pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bool, stream_usage: bool) ![]u8 {var aw: Io.Writer.Allocating = .init(self.gpa);errdefer aw.deinit();@@ -175,6 +180,11 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bootry s.endArray();try s.objectField("store");try s.write(false);+ // Bound every Responses request explicitly. The normal agent keeps+ // the existing 16k ceiling; compaction gets a focused 4k handoff+ // and title generation can override this to 64 tokens.+ try s.objectField("max_output_tokens");+ try s.write(responsesOutputLimit(self));try s.objectField("stream");try s.write(true);},diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex 446413dc..2d4d627e 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -47,6 +47,32 @@ const execTool = exec.execTool;const util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurement+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);++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|+ try std.fmt.allocPrint(arena, "[full tool result: {s} — inspect with read_file]", .{p})+ else+ "[tool result truncated: full-result persistence failed]";+ const head = util.utf8Prefix(text, tool_preview_chars -| (marker.len + 2));+ return std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ head, marker });+}++fn persistToolResult(self: *Agent, text: []const u8) ?[]const u8 {+ if (text.len <= tool_preview_chars) return null;+ // createDir reports PathAlreadyExists, which is the normal case because+ // trace setup creates `.graff` at launch. createDirPath is idempotent.+ Io.Dir.cwd().createDirPath(self.io, tool_results_dir) catch return null;+ const seq = tool_result_seq.fetchAdd(1, .monotonic);+ const run_id = if (self.tracer) |tr| tr.identity.run_id else "untraced";+ const path = std.fmt.allocPrint(self.arena, "{s}/{s}-{d}.txt", .{ tool_results_dir, run_id, seq }) catch return null;+ Io.Dir.cwd().writeFile(self.io, .{ .sub_path = path, .data = text, .flags = .{ .exclusive = true } }) catch return null;+ return path;+}+// escWatchTask/drainStdin/rawNonblockStdin live in agent_interrupt.zig;// Agent.esc_watch_done is a struct-level pub var that STAYS declared inside the// Agent struct in main.zig (never alias a var — see esc_cancel/@@ -94,6 +120,8 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {.from_sub = self.sub,.approvals = self.approvals,.tracer = self.tracer,+ .run_budget = self.run_budget,+ .depth = self.depth,.snapshots = self.snapshots,.tools_used = &self.tools_used,};@@ -125,7 +153,10 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {for (futures, outputs) |*fut, *output| output.* = fut.await(self.io);defer for (outputs) |output| self.gpa.free(output.text);for (ext_idx.items, outputs) |i, output| {- results[i] = .{ .text = try self.arena.dupe(u8, output.text), .is_error = output.is_error, .ms = output.ms };+ // Keep the model-facing history compact. The exact output remains+ // 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 };}}// Show a compact ✓/✗ + preview for each non-meta call (no-op for subs).@@ -133,6 +164,15 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {return results;}+test "toolPreviewText caps context and preserves an inspect pointer" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const preview = try toolPreviewText(arena_state.allocator(), "x" ** 5000, ".graff/tool-results/run-1.txt");+ try std.testing.expect(preview.len <= tool_preview_chars);+ try std.testing.expect(std.mem.indexOf(u8, preview, ".graff/tool-results/run-1.txt") != null);+ try std.testing.expect(std.unicode.utf8ValidateSlice(preview));+}+pub fn rejectToolCall(self: *Agent, call: ToolCall) !?ExecResult {if (self.sub) return null;if (std.mem.eql(u8, call.name, "attempt_completion")) return null;@@ -347,7 +387,6 @@ fn clockSleepInterruptedText(arena: std.mem.Allocator, elapsed_ms: i64) ![]constreturn std.fmt.allocPrint(arena, "sleep interrupted after {d} ms by user input", .{elapsed_ms});}-/// 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")) {diff --git a/src/agent_ws.zig b/src/agent_ws.zigindex 5fb11dc1..34f3159b 100644--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@ -6,13 +6,14 @@//! completion logic are shared with the SSE path.//!//! postLive() is the transport selector called by request(): codex root turns-//! try ws (postResponsesWs); a handshake/transport failure disables ws for the-//! session and falls back to postStream (SSE) — a genuine Esc/stall propagates.+//! try ws (postResponsesWs), retry one failed WS with a clean full-history+//! re-anchor, then latch onto the launch-scoped prewarmed HTTP client for SSE.//!//! Observability (issue #134's ask): every ws lifecycle step is routed to the//! tracer ("ws" notes: connecting/connected/completed/stall/fallback/errors),-//! which lands in harness.trace.jsonl so an agent can debug a ws turn after the-//! fact; GRAFF_WS_DEBUG=1 additionally dumps the handshake + frames to stderr.+//! which lands in the run's file under .graff/traces so an agent can debug a+//! ws turn after the fact; GRAFF_WS_DEBUG=1 additionally dumps the handshake ++//! frames to stderr.const std = @import("std");const Io = std.Io;@@ -65,9 +66,15 @@ fn nowAwakeMs(io: Io) i64 {return @intCast(@divTrunc(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_ms));}-/// Transport selector: try ws for eligible codex turns, else SSE (postStream).-/// A ws transport/handshake failure disables ws for the session and falls back-/// to SSE; a deliberate Esc/stall propagates unchanged.+const ws_failures_before_fallback: u8 = 2;++pub fn wsShouldFallback(consecutive_failures: u8) bool {+ return consecutive_failures >= ws_failures_before_fallback;+}++/// Transport selector: try ws for eligible codex turns, else persistent SSE.+/// The first WS transport/handshake failure rebuilds full input and retries a+/// fresh socket. The second latches SSE for the session. Esc/stall propagates.pub fn postLive(self: *Agent, body: []const u8) ![]u8 {// #134/#132 test seam: force a one-shot stall/drop on a live turn so the// end-to-end "[response ended early: …]" path (never "[response interrupted@@ -105,9 +112,15 @@ pub fn postLive(self: *Agent, body: []const u8) ![]u8 {};return error.StreamDropped;}- if (!wsEligible(self)) return if (self.ws_off) postStreamFresh(self, body) else self.postStream(body);- return postResponsesWs(self, body) catch |e| {+ if (!wsEligible(self)) return self.postStream(body);+ const response = postResponsesWs(self, body) catch |e| {if (e == error.Interrupted or e == error.StreamStalled) return e;+ // Preemptive idle expiry is not a failed transport attempt; it only asks+ // request() to rebuild the already-created delta as full input.+ if (e == error.CodexWsReanchor) return e;+ self.closeCodexWs();+ self.ws_transport_failures +|= 1;+ const fallback = wsShouldFallback(self.ws_transport_failures);// (#codex-ws) A delta body carries previous_response_id + only the new// messages, anchored to the WS session that just died — the codex HTTP// endpoint rejects previous_response_id outright ("Unsupported@@ -119,21 +132,23 @@ pub fn postLive(self: *Agent, body: []const u8) ![]u8 {// request() to rebuild + retry (a fresh WS re-anchors with full history)// instead of falling back to a stale SSE replay.if (std.mem.indexOf(u8, body, "\"previous_response_id\"") != null) {- self.closeCodexWs();- if (self.tracer) |tr| tr.note("ws", "reuse failed — re-anchoring with full input");+ if (fallback) self.ws_off = true;+ if (self.tracer) |tr| tr.note("ws", if (fallback)+ "reuse failed twice — rebuilding full input for persistent SSE"+ else+ "reuse failed — retrying a fresh WS with full input");+ return error.CodexWsReanchor;+ }+ if (!fallback) {+ if (self.tracer) |tr| tr.note("ws", "transport error — retrying one fresh WS");return error.CodexWsReanchor;}self.ws_off = true;- if (self.tracer) |tr| tr.note("ws", "transport error — falling back to fresh-client SSE for this session");- return postStreamFresh(self, body);+ if (self.tracer) |tr| tr.note("ws", "transport failed twice — using persistent prewarmed SSE for this session");+ return self.postStream(body);};-}--fn postStreamFresh(self: *Agent, body: []const u8) ![]u8 {- var client: std.http.Client = .{ .allocator = self.gpa, .io = self.io };- defer client.deinit();- if (self.tracer) |tr| tr.note("sse_fallback", "fresh HTTP client");- return self.postStreamWithClient(&client, body);+ self.ws_transport_failures = 0;+ return response;}fn wssUrl(arena: std.mem.Allocator, https_url: []const u8) ![]u8 {diff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zigindex 17c13213..dc4df2ac 100644--- a/src/agent_ws_test.zig+++ b/src/agent_ws_test.zig@@ -46,6 +46,13 @@ test "codexWsIdleExpired: fires only strictly past the idle limit (codex-ws)" {try std.testing.expect(agent_ws.codexWsIdleExpired(1_000_000 + 510 * std.time.ms_per_s, 1_000_000)); // the real 8.5-min trace gap}+test "WS fallback latches only after a retry" {+ try std.testing.expect(!agent_ws.wsShouldFallback(0));+ try std.testing.expect(!agent_ws.wsShouldFallback(1));+ try std.testing.expect(agent_ws.wsShouldFallback(2));+ try std.testing.expect(agent_ws.wsShouldFallback(255));+}+// (#codex-ws) End-to-end regression for the reanchor fix: buildBody's// .responses branch must emit previous_response_id + a message-slice delta// while a WS session + prev id are held, and after closeCodexWs (called by@@ -84,6 +91,7 @@ test "buildBody (.responses): delta while WS live; full input after closeCodexWstry std.testing.expect(std.mem.indexOf(u8, delta_body, "\"previous_response_id\":\"resp_live\"") != null);try std.testing.expect(std.mem.indexOf(u8, delta_body, "third — not yet sent") != null);try std.testing.expect(std.mem.indexOf(u8, delta_body, "\"first\"") == null); // NOT resent — already on the server+ try std.testing.expect(std.mem.indexOf(u8, delta_body, "\"max_output_tokens\":16000") != null);// Simulate closeCodexWs's effect (covered by its own unit test above)// without invoking it directly: it would call ws.WsClient.deinit on@@ -100,4 +108,15 @@ test "buildBody (.responses): delta while WS live; full input after closeCodexWstry std.testing.expect(std.mem.indexOf(u8, rebuilt_body, "\"previous_response_id\"") == null);try std.testing.expect(std.mem.indexOf(u8, rebuilt_body, "\"first\"") != null); // full history restoredtry std.testing.expect(std.mem.indexOf(u8, rebuilt_body, "third — not yet sent") != null);++ agent.compaction_request = true;+ const compact_body = try agent.buildBody(null, false, false, false);+ defer std.testing.allocator.free(compact_body);+ try std.testing.expect(std.mem.indexOf(u8, compact_body, "\"max_output_tokens\":4096") != null);++ agent.compaction_request = false;+ agent.responses_output_limit = 64;+ const title_body = try agent.buildBody(null, false, false, false);+ defer std.testing.allocator.free(title_body);+ try std.testing.expect(std.mem.indexOf(u8, title_body, "\"max_output_tokens\":64") != null);}diff --git a/src/args.zig b/src/args.zigindex 235d7e34..51dd7915 100644--- a/src/args.zig+++ b/src/args.zig@@ -14,8 +14,8 @@//! Back-imports main (as main_mod, the established convention — see//! mainloop.zig/tools.zig/etc.) for the handful of globals that STAY in//! main.zig and were only ever *set* (never read) by the parse loop itself:-//! show_timing/show_cost/json_mode/max_tool_calls/dedupe_tool_calls (`--timing`-//! /`--cost`/`--json`/`--max-tool-calls`/`--dedupe-tool-calls`) and+//! show_timing/show_cost/json_mode/max_tool_calls/max_model_calls/dedupe_tool_calls (`--timing`+//! /`--cost`/`--json`/`--max-tool-calls`/`--max-model-calls`/`--dedupe-tool-calls`) and//! g_worktree_autocommit (`--no-autocommit`). These are mutable globals, so//! per the mod-prefix rule they are written through `main_mod.` — never//! aliased (aliasing a `var` freezes its value at import time).@@ -106,6 +106,9 @@ pub fn parse(init: std.process.Init) !Flags {} else if (std.mem.eql(u8, arg, "--max-tool-calls")) {const mv = it.next() orelse std.process.fatal("--max-tool-calls needs a non-negative integer — harness --help", .{});main_mod.max_tool_calls = std.fmt.parseInt(u64, mv, 10) catch std.process.fatal("--max-tool-calls needs a non-negative integer, got '{s}'", .{mv});+ } else if (std.mem.eql(u8, arg, "--max-model-calls")) {+ const mv = it.next() orelse std.process.fatal("--max-model-calls needs a non-negative integer — graff --help", .{});+ main_mod.max_model_calls = std.fmt.parseInt(u64, mv, 10) catch std.process.fatal("--max-model-calls needs a non-negative integer, got '{s}'", .{mv});} else if (std.mem.eql(u8, arg, "--dedupe-tool-calls")) {main_mod.dedupe_tool_calls = true;} else if (std.mem.eql(u8, arg, "--clock-sleep")) {diff --git a/src/cli.zig b/src/cli.zigindex f74d02fc..5a02bfaf 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -91,6 +91,7 @@ pub const usage_text =\\ --cost show running session spend in the prompt\\ --json structured stdio protocol (JSON in, JSONL events out)\\ --max-tool-calls N reject root tool calls after N per turn (JSON-safe budget)+ \\ --max-model-calls N total provider calls allowed across this run (default 256; includes children/title/judges)\\ --dedupe-tool-calls reject duplicate root tool name+input calls per turn\\ --no-telemetry disable anonymous usage telemetry for this run\\ -h, --help this helpdiff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 6c373459..322b9d83 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -41,7 +41,7 @@ pub const commands = [_]Item{.{ .name = "/title", .desc = "name the tab from your first prompt (AI session title; toggle, persists)" },.{ .name = "/strict", .desc = "toggle \"every message is a tool\" mode" },.{ .name = "/yolo", .desc = "toggle bash auto-approval (skip permission prompts)" },- .{ .name = "/trace", .desc = "toggle the JSONL event trace (harness.trace.jsonl)" },+ .{ .name = "/trace", .desc = "toggle this run's JSONL event trace (and show its path)" },.{ .name = "/trajectory", .desc = "show this session's agent tree — turns + spawned subagents" },.{ .name = "/agents", .desc = "list agent types — builtin personas + .harness/agents/*.md" },.{ .name = "/skills", .usage = "/skills [remove <name>]", .desc = "list available skills; /skills remove <name> disables one" },diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex 39815458..9c32417c 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -51,7 +51,6 @@ const PickItem = pickers.PickItem;const listPicker = pickers.listPicker;const trace = @import("trace.zig");-const trace_path = trace.trace_path;fn providerModelCount(provider_id: []const u8) usize {var count: usize = 0;@@ -353,7 +352,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,if (std.mem.eql(u8, line, "/trace")) {if (root.tracer) |tr| {const on = tr.toggle();- try out.print("tracing {s} → {s}\n", .{ if (on) "ON" else "off", trace_path });+ try out.print("tracing {s} → {s}\n", .{ if (on) "ON" else "off", tr.path });} else {try out.writeAll("no trace file (failed to open at startup)\n");}diff --git a/src/commands_model.zig b/src/commands_model.zigindex 98dc9a72..78889b7e 100644--- a/src/commands_model.zig+++ b/src/commands_model.zig@@ -320,7 +320,9 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,return true;}if (std.mem.eql(u8, line, "/title") or std.mem.eql(u8, line, "/title on") or std.mem.eql(u8, line, "/title off")) {+ const was_on = root.ai_title;root.ai_title = if (std.mem.eql(u8, line, "/title on")) true else if (std.mem.eql(u8, line, "/title off")) false else !root.ai_title;+ if (was_on and !root.ai_title) root.title_generation +%= 1; // discard any detached result already in flightconst saved = saveThinkingSettings(root.io, root.gpa, root.reasoning, root.fast, root.ultracode_mode, root.show_thinking, root.ai_title);try out.print("AI session title: {s} ({s}){s}\n", .{if (root.ai_title) "on" else "off",diff --git a/src/commands_session.zig b/src/commands_session.zigindex 6a469445..6fd7ff8c 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -39,7 +39,6 @@ const approvals_mod = @import("approvals.zig");const Approvals = approvals_mod.Approvals;const trace = @import("trace.zig");-const trajectory_path = trace.trajectory_path;const skills = @import("skills.zig");const skillIndex = skills.skillIndex;@@ -84,6 +83,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,root.tui_header_shown = false;root.session_title = null; // re-summarize the now-empty conversationroot.ai_title_done = false;+ root.title_generation +%= 1;root.todos.clearRetainingCapacity();const had_goal = root.goal != null;resetConversationSteering(root);@@ -104,6 +104,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,resetConversationSteering(root);root.session_title = null;root.ai_title_done = false; // let the new session earn its own AI title+ root.title_generation +%= 1;root.tui_header_shown = false;root.session_name = try std.fmt.allocPrint(arena, "session-{d}", .{unixMs(root.io)});saveSession(root, arena, root.session_name) catch {};@@ -118,6 +119,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,} else {root.session_title = try arena.dupe(u8, title);root.ai_title_done = true; // a manual /rename wins over the auto-titler+ root.title_generation +%= 1; // discard any still-running AI resultsaveSession(root, arena, root.session_name) catch {};try out.print("session title → {s}\n", .{title});}@@ -198,7 +200,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,}if (std.mem.startsWith(u8, line, "/agents promote")) {const personal = std.mem.indexOf(u8, line, "--personal") != null or std.mem.indexOf(u8, line, "--global") != null;- try out.print("{s}promoting local champions{s} → {s} tier (from {s})\n", .{ style.bold, style.reset, if (personal) "personal ~/.harness/agents" else "private ./.harness/agents", trajectory_path });+ try out.print("{s}promoting local champions{s} → {s} tier (from {s})\n", .{ style.bold, style.reset, if (personal) "personal ~/.harness/agents" else "private ./.harness/agents", trace.trajectories_dir });const n = promoteAgents(root.io, root.gpa, out, fleet.g_home, personal);if (n > 0) try out.print("{s}✓ promoted {d} niche(s) — they load on next start{s}\n", .{ style.green, n, style.reset });try out.flush();@@ -392,7 +394,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,return true;}if (std.mem.eql(u8, line, "/trajectory")) {- const data = Io.Dir.cwd().readFileAlloc(root.io, trajectory_path, arena, .limited(4 << 20)) catch "";+ const data = trace.readTrajectoryArchive(root.io, arena, 4 << 20);const S = struct {fn str(o: std.json.ObjectMap, k: []const u8) []const u8 {const v = o.get(k) orelse return "";@@ -429,24 +431,21 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,const v = std.json.parseFromSliceLeaky(Value, arena, ln, .{ .allocate = .alloc_always }) catch continue;if (v == .object) objs.append(arena, v.object) catch {};}- // Tree shows the CURRENT session (ids restart per session); scores- // come from the whole archive.- var session_start: usize = 0;- for (objs.items, 0..) |o, i| {- if (std.mem.eql(u8, S.str(o, "kind"), "session")) session_start = i + 1;- }- const session = objs.items[session_start..];+ // Tree shows this invocation; scores still come from the whole archive.+ const current_run_id = if (root.tracer) |tr| tr.identity.run_id else if (trace.g_traj) |tj| tj.identity.run_id else "";var turns: usize = 0;- for (session) |o| {+ for (objs.items) |o| {+ if (!std.mem.eql(u8, S.str(o, "run_id"), current_run_id)) continue;if (std.mem.eql(u8, S.str(o, "kind"), "turn")) turns += 1;}if (turns == 0) {- try out.writeAll("no trajectory recorded yet — run a turn first (the archive lives in harness.trajectory.jsonl)\n");+ try out.print("no trajectory recorded yet — run a turn first (current file: {s})\n", .{if (trace.g_traj) |tj| tj.path else trace.trajectories_dir});try out.flush();return true;}- try out.print("{s}session trajectory{s} — {d} turn(s); archive: {s} ({d} record(s) total)\n", .{ style.bold, style.reset, turns, trajectory_path, objs.items.len });- for (session) |o| {+ try out.print("{s}session trajectory{s} — {d} turn(s); current: {s}; archive: {s} ({d} record(s) total)\n", .{ style.bold, style.reset, turns, if (trace.g_traj) |tj| tj.path else "", trace.trajectories_dir, objs.items.len });+ for (objs.items) |o| {+ if (!std.mem.eql(u8, S.str(o, "run_id"), current_run_id)) continue;if (!std.mem.eql(u8, S.str(o, "kind"), "turn")) continue;const turn_id = S.int(o, "id");out.print("{s}●{s} turn {d} {s} {d}ms · prompt {s}{s}{s}{s} · {s}", .{@@ -466,10 +465,12 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,out.writeAll("\n") catch {};// children: subagents / workflow tasks spawned during this turnvar remaining: usize = 0;- for (session) |c| {+ for (objs.items) |c| {+ if (!std.mem.eql(u8, S.str(c, "run_id"), current_run_id)) continue;if (S.int(c, "parent") == turn_id and !std.mem.eql(u8, S.str(c, "kind"), "turn")) remaining += 1;}- for (session) |c| {+ for (objs.items) |c| {+ if (!std.mem.eql(u8, S.str(c, "run_id"), current_run_id)) continue;if (S.int(c, "parent") != turn_id or std.mem.eql(u8, S.str(c, "kind"), "turn")) continue;remaining -= 1;out.print(" {s} {s} {s} {d}ms · prompt {s}{s}{s}{s} · {s}", .{diff --git a/src/fleet.zig b/src/fleet.zigindex cbe95e28..d1dbeac6 100644--- a/src/fleet.zig+++ b/src/fleet.zig@@ -3,7 +3,7 @@//! backgrounded elite pull from the fleet worker, /agents promote, and the//! niche/override resolvers for subagent + workflow spawns. Split out of//! main.zig (#123). Owns the session agent-type globals; back-imports main for-//! the Telemetry sink (fleet signals), trajectory_path, and the live g_fleet toggle.+//! the Telemetry sink (fleet signals), trajectory archive, and the live g_fleet toggle.const std = @import("std");const Io = std.Io;@@ -21,7 +21,6 @@ const trace = @import("trace.zig");const telemetry_mod = @import("telemetry.zig");const Telemetry = telemetry_mod.Telemetry;const http = @import("http.zig");-const trajectory_path = trace.trajectory_path;// ── Agent types (the MAP-Elites niches) ─────────────────────────────────────@@ -144,7 +143,7 @@ fn loadAgentDir(io: Io, arena: Allocator, list: *std.ArrayList(AgentType), dir_p}/// Local single-tenant promote — the "grow for me" loop. Mine-/// harness.trajectory.jsonl (prompt records → genome text, subagent records →+/// the run-scoped trajectory archive (prompt records → genome text, subagent records →/// niche, score records → fitness), and for each MAP-Elites niche write the/// highest-mean-scoring genome that has captured text into the chosen tier/// (personal ~/.harness/agents or private ./.harness/agents) as <niche>.md. No@@ -155,10 +154,11 @@ pub fn promoteAgents(io: Io, gpa: Allocator, out: *Io.Writer, home: ?[]const u8,defer arena_state.deinit();const arena = arena_state.allocator();- const data = Io.Dir.cwd().readFileAlloc(io, trajectory_path, arena, .limited(64 << 20)) catch {- out.print(" {s}no {s} yet — run some scored agents first{s}\n", .{ style.dim, trajectory_path, style.reset }) catch {};+ const data = trace.readTrajectoryArchive(io, arena, 64 << 20);+ if (data.len == 0) {+ out.print(" {s}no {s} yet — run some scored agents first{s}\n", .{ style.dim, trace.trajectories_dir, style.reset }) catch {};return 0;- };+ }const Cell = struct { sha: []const u8, text: []const u8, niche: []const u8, sum: f64, n: u32 };var cells: std.ArrayList(Cell) = .empty;diff --git a/src/main.zig b/src/main.zigindex d66f8155..e0c4d57a 100644--- a/src/main.zig+++ b/src/main.zig@@ -12,8 +12,8 @@//! only; /yolo disables it); strict mode (/strict) forces a tool call every//! turn, ending via attempt_completion instead of plain text.//!-//! Every round trip and tool call is traced to harness.trace.jsonl (/trace-//! toggles it). std.http.Client for HTTPS, std.json for both wire formats,+//! Every round trip and tool call is traced to the run's unique JSONL under+//! .graff/traces (/trace toggles it). std.http.Client for HTTPS, std.json for both wire formats,//! std.Io's thread pool for parallel execution, and client-side compaction//! as the conversation grows.const std = @import("std");@@ -59,6 +59,7 @@ const agent_steps = @import("agent_steps.zig");const agent_compact = @import("agent_compact.zig");const agent_compact_test = @import("agent_compact_test.zig");const agent_ws_test = @import("agent_ws_test.zig");+const run_budget_mod = @import("run_budget.zig");const agent_tools = @import("agent_tools.zig");const agent_request = @import("agent_request.zig");const agent_interrupt = @import("agent_interrupt.zig");@@ -80,6 +81,7 @@ pub var g_force_drop_once: bool = false; // #132/#133 test seam (GRAFF_FORCE_DROpub var g_force_stall_always: bool = false; // #56 test seam (GRAFF_FORCE_STALL_ALWAYS=1): EVERY live attempt stalls, so the reconnect budget exhausts and the turn ends as a stall — exercises the give-up path offlinepub var g_force_drop_always: bool = false; // #56 test seam (GRAFF_FORCE_DROP_ALWAYS=1): EVERY live attempt dropspub var max_tool_calls: ?u64 = null; // --max-tool-calls: hard per-turn root tool budget+pub var max_model_calls: u64 = run_budget_mod.default_max_model_calls; // invocation-wide, shared by root/children/title/judgespub var dedupe_tool_calls = false; // --dedupe-tool-calls: reject duplicate root calls in a turnpub var plan_mode = false; // /plan: read-only — mutating tools are denied, the model proposespub var unattended = false; // -p one-shot: no human to prompt; unapproved tool calls are denied@@ -159,12 +161,10 @@ const Keys = provider_mod.Keys;// Approvals (command/tool approval gate) + confinedPath/noSymlinkEscape live in approvals.zig; main() constructs one directly for the session.const approvals_mod = @import("approvals.zig");const Approvals = approvals_mod.Approvals;-// Session tracing (harness.trace.jsonl Tracer) + the DGM trajectory archive (harness.trajectory.jsonl Trajectory) + the per-line JSON writer live in trace.zig; trajectory_path locates the archive file.+// Run-scoped session tracing + DGM trajectory files live in trace.zig.const trace = @import("trace.zig");const Tracer = trace.Tracer;const Trajectory = trace.Trajectory;-const trajectory_path = trace.trajectory_path;-const trace_path = trace.trace_path;// Agent types / fleet (MAP-Elites niches): the AgentType registry, backgrounded elite pull, /agents promote, and niche/override resolvers live in fleet.zig.const fleet = @import("fleet.zig");const joinElites = fleet.joinElites;@@ -283,8 +283,15 @@ pub fn main(init: std.process.Init) !void {g_mem_debug = init.environ_map.get("GRAFF_MEM_DEBUG") != null;// Windows: let the console interpret ANSI/VT escapes so the harness's color and cursor sequences render instead of literal text.if (builtin.os.tag == .windows) tty.enableVtOutput();+ // Environment supplies the default; an explicit CLI flag parsed below has+ // the usual higher precedence for this invocation.+ if (init.environ_map.get("GRAFF_MAX_MODEL_CALLS")) |raw| {+ max_model_calls = std.fmt.parseInt(u64, raw, 10) catch+ std.process.fatal("GRAFF_MAX_MODEL_CALLS needs a non-negative integer, got '{s}'", .{raw});+ }// CLI flags: the Flags struct + parsing loop live in args.zig; downstream code reads flags.<name> in place of ~27 locals this block used to declare.const flags = try args.parse(init);+ var invocation_budget: run_budget_mod.RunBudget = .{ .max_model_calls = max_model_calls };bootMark(init.io, boot_started, boot_debug, "args");// GRAFF_CODEX_URL: override the codex responses endpoint (localhost mocks / integration tests). Parsed BEFORE subcommand dispatch and// resolveKeys — `graff models [refresh]` fetches the catalog inside runSubcommand and the initial Keys.build runs inside resolveKeys.@@ -322,32 +329,47 @@ pub fn main(init: std.process.Init) !void {const out = &stdout_writer.interface;g_out = out;- if (try session_start.runTitleCommand(io, gpa, arena, &client, default_provider, out, flags)) return;- try session_start.setupWorktreeAndBanner(io, gpa, arena, init.environ_map, flags, out, trace_path, codex_account, stale_saved_model, preferred_provider, default_provider);+ if (try session_start.runTitleCommand(io, gpa, arena, &client, default_provider, out, flags, &invocation_budget)) return;+ // Generate identity before opening either JSONL. The score channel and both+ // files share this run id; session_id is a separate runtime correlation id.+ session_start.initScoreRunId(io);+ const runtime_session_id = trace.newSessionId(io);+ const identity: trace.Identity = .{+ .run_id = &scoring.g_run_id,+ .pid = trace.currentPid(),+ .session_id = &runtime_session_id,+ };+ const run_trace_path = try trace.tracePath(arena, identity.run_id);+ const run_trajectory_path = try trace.trajectoryPath(arena, identity.run_id);+ try session_start.setupWorktreeAndBanner(io, gpa, arena, init.environ_map, flags, out, run_trace_path, codex_account, stale_saved_model, preferred_provider, default_provider);+ session_start.loadScoreSigningKey(io, arena, init.environ_map);bootMark(io, boot_started, boot_debug, "banner");// Session trace (best-effort: a failed open just disables tracing).var trace_buf: [8 * 1024]u8 = undefined;- var trace_open = session_start.openTraceFile(io, trace_path, &trace_buf);+ var trace_open = session_start.openTraceFile(io, run_trace_path, &trace_buf);defer if (trace_open.file) |f| f.close(io);var tracer: Tracer = .{.io = io,.gpa = gpa,.out = if (trace_open.file != null) &trace_open.writer.interface else null,.start = Io.Timestamp.now(io, .awake),+ .identity = identity,+ .path = run_trace_path,};- // Trajectory archive (DGM-style tree; best-effort like the trace) — unlike the trace it is APPEND-ONLY: it accumulates across sessions and IS- // the archive a DGM-style driver selects parents from. Each session starts with a `kind:"session"` header; node ids restart per session,- // cross-session lineage threads through prompt_sha.+ // One trajectory file per run; the archive reader scans the directory.+ // Node ids restart per run and cross-run lineage threads through prompt_sha.var traj_buf: [8 * 1024]u8 = undefined;- var traj_open = session_start.openTrajFile(io, trajectory_path, &traj_buf);+ var traj_open = session_start.openTrajFile(io, run_trajectory_path, &traj_buf);defer if (traj_open.file) |f| f.close(io);var traj: Trajectory = .{.io = io,.gpa = gpa,.out = if (traj_open.file != null) &traj_open.writer.interface else null,.start = Io.Timestamp.now(io, .awake),+ .identity = identity,+ .path = run_trajectory_path,};trace.g_traj = &traj;defer {@@ -356,8 +378,6 @@ pub fn main(init: std.process.Init) !void {}traj.node(.{ .kind = "session", .version = harness_version, .unix_ms = unixMs(io) });- session_start.initScoreSigning(io, arena, init.environ_map);-var telem = session_start.initTelemetry(io, gpa, &client, init.environ_map, flags, default_telemetry_endpoint);telemetry.g_telem = &telem;// Fleet contribution opt-out, independent of telemetry: GRAFF_FLEET=off|0|false|no.@@ -430,6 +450,7 @@ pub fn main(init: std.process.Init) !void {// backgrounded fleet-champion pull live in session_start.zig. `root`'s pointer fields (snapshots/client/tracer/approvals/registry) all reference// already-stable main()-owned storage passed in by address, so returning the constructed Agent by value here is safe.var root = try session_run.buildRootAgent(gpa, arena, io, &client, default_provider, init.environ_map, out, in, registry, &approvals, &tracer, sys_normal, sys_strict, &snaps, flags, telem.endpoint);+ root.run_budget = &invocation_budget;root.model_catalog = resolved_keys.model_catalog;root.stored_keys_loaded = resolved_keys.stored_keys_loaded;root.scratch_arena = &scratch_state; // #124: route the root's transient parse garbage here; reset per request()diff --git a/src/mainloop.zig b/src/mainloop.zigindex 8204e150..cdc44014 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -77,24 +77,90 @@ pub const Ctx = struct {sys_strict: []const u8,};-/// Apply the backgrounded AI session title (titleTask) to the redrawable-/// window title + saved session filename. Called from BOTH the happy-path-/// post-turn step and the end-of-iteration `defer`, so an interrupted /-/// stalled / dropped / errored turn — which `continue`s before the post-turn-/// step — still lands the title instead of generating it then throwing it away-/// (ai_title_done is already set, so it would otherwise never regenerate and-/// the window title stays stuck on the prompt-derived fallback). Awaits once.-fn applyAiTitle(ctx: *Ctx, f: *Io.Future(?[]const u8)) void {- if (f.await(ctx.io)) |t| {- ctx.root.session_title = ctx.arena.dupe(u8, t) catch null;- ctx.gpa.free(t);- if (ctx.root.session_title) |st| {- title_mod.setTerminalTitle(ctx.out, st, main_mod.g_cwd_display);- session.renameSession(ctx.root, ctx.arena, session.slugifyTitle(ctx.arena, st));- }+fn applyAiTitle(ctx: *Ctx, title: []const u8) void {+ ctx.root.session_title = ctx.arena.dupe(u8, title) catch null;+ if (ctx.root.session_title) |st| {+ title_mod.setTerminalTitle(ctx.out, st, main_mod.g_cwd_display);+ session.renameSession(ctx.root, ctx.arena, session.slugifyTitle(ctx.arena, st));}}+const TitleJob = struct {+ future: ?Io.Future(void) = null,+ prompt: []const u8, // gpa-owned: readline storage may be reused next turn+ result: ?[]const u8 = null, // gpa-owned, published before done.release+ done: std.atomic.Value(bool) = .init(false),+ generation: u64,+};++fn detachedTitleTask(job: *TitleJob, gpa: Allocator, io: Io, client: *std.http.Client, provider: provider_mod.Provider, budget: ?*@import("run_budget.zig").RunBudget, tracer: ?*@import("trace.zig").Tracer) void {+ job.result = title_mod.titleTask(gpa, io, client, provider, job.prompt, budget, tracer);+ job.done.store(true, .release);+}++/// Owns title tasks for the whole interactive session. Completed jobs are+/// polled without waiting; outstanding work is canceled only when mainloop+/// closes. Multiple generations allow `/new` while an old title is still live.+const TitleJobs = struct {+ items: std.ArrayList(*TitleJob) = .empty,++ fn start(self: *TitleJobs, ctx: *Ctx, prompt: []const u8) void {+ // An explicitly tiny budget still owes the user a real answer. Do not+ // let cosmetic title work consume the final provider-call slot before+ // the root request has a chance to acquire it.+ if (ctx.root.run_budget) |budget| if (budget.remaining() <= 1) {+ if (ctx.root.tracer) |tr| tr.note("budget", "AI title skipped to reserve the final model call for the root turn");+ return;+ };+ const job = ctx.gpa.create(TitleJob) catch return;+ const owned_prompt = ctx.gpa.dupe(u8, prompt) catch {+ ctx.gpa.destroy(job);+ return;+ };+ job.* = .{ .prompt = owned_prompt, .generation = ctx.root.title_generation };+ const args = .{ job, ctx.gpa, ctx.io, ctx.root.client, ctx.root.provider, ctx.root.run_budget, ctx.root.tracer };+ job.future = ctx.io.concurrent(detachedTitleTask, args) catch ctx.io.async(detachedTitleTask, args);+ self.items.append(ctx.gpa, job) catch {+ if (job.future) |*future| future.cancel(ctx.io);+ if (job.result) |title| ctx.gpa.free(title);+ ctx.gpa.free(job.prompt);+ ctx.gpa.destroy(job);+ };+ }++ fn poll(self: *TitleJobs, ctx: *Ctx) void {+ var i: usize = 0;+ while (i < self.items.items.len) {+ const job = self.items.items[i];+ if (!job.done.load(.acquire)) {+ i += 1;+ continue;+ }+ if (job.future) |*future| future.await(ctx.io); // done=true: never blocks+ job.future = null;+ if (job.result) |title| {+ // Manual rename/session reset wins over an older detached result.+ if (job.generation == ctx.root.title_generation and ctx.root.session_title == null)+ applyAiTitle(ctx, title);+ ctx.gpa.free(title);+ }+ ctx.gpa.free(job.prompt);+ _ = self.items.orderedRemove(i);+ ctx.gpa.destroy(job);+ }+ }++ fn deinit(self: *TitleJobs, ctx: *Ctx) void {+ for (self.items.items) |job| {+ if (job.future) |*future| future.cancel(ctx.io);+ if (job.result) |title| ctx.gpa.free(title);+ ctx.gpa.free(job.prompt);+ ctx.gpa.destroy(job);+ }+ self.items.deinit(ctx.gpa);+ }+};+/// #226: true only when the model has a live checklist and every item is marked/// completed — a "work asserted done" signal for the /loop continuation gate/// (alongside attempt_completion / root.completed). An empty checklist is NOT done.@@ -109,6 +175,8 @@ fn allTodosDone(root: *agent_mod.Agent) bool {/// resumes right after this returns and does its own final-save/worktree/// cleanup (unchanged, still in main.zig).pub fn run(ctx: *Ctx) !void {+ var title_jobs: TitleJobs = .{};+ defer title_jobs.deinit(ctx);// Trajectory spine state: each turn's parent is the previous turn, and a// changed prompt fingerprint marks a set_system_prompt mutation edge.var prev_turn_id: u64 = 0;@@ -123,6 +191,9 @@ pub fn run(ctx: *Ctx) !void {var loop_continue_armed = false; // a continuation turn is queued for the next readlinewhile (true) {+ // Nonblocking completion pump: a title can land between any two user+ // interactions, but it is never joined on the turn-response path.+ title_jobs.poll(ctx);// Steering drain: prompts typed while the previous turn streamed// were captured into g_steer_queue. Run them now, one after// another, in place of reading a fresh line — Codex-style@@ -154,6 +225,9 @@ pub fn run(ctx: *Ctx) !void {try ctx.root.prompt();break :blk (try readline.readLine(ctx.root, ctx.in, ctx.out, ctx.gpa, ctx.history, ctx.linebuf)) orelse break;} else (try ctx.in.takeDelimiter('\n')) orelse break;+ // The title may have completed while readline was waiting. Apply it+ // before starting the newly-entered turn, still without ever waiting.+ title_jobs.poll(ctx);const line = std.mem.trim(u8, raw_line, " \t\r");if (line.len == 0) continue;const loop_prompt: ?[]const u8 = if (!main_mod.json_mode and std.mem.startsWith(u8, line, "/loop "))@@ -378,22 +452,12 @@ pub fn run(ctx: *Ctx) !void {// model can see (otherwise it only gets the path and resorts to OCR).vision.stageGuiImageAttachment(ctx.root, msg);- // Generate the AI tab-title concurrently, spawned BEFORE the header and- // root turn. `concurrent` guarantees an independent execution slot on- // supported Io backends; async preserves portability as the fallback.- // Applied after the turn on the happy path (below); the defer is the fallback for- // an interrupted/stalled/dropped/errored turn (those `continue` before the- // apply step) so the generated title is never silently discarded.- var title_fut: ?Io.Future(?[]const u8) = null;+ // Generate the AI title before the root turn and publish it through the+ // session-scoped nonblocking completion queue.if (!main_mod.json_mode and ctx.root.ai_title and !ctx.root.ai_title_done) {ctx.root.ai_title_done = true;- const title_args = .{ ctx.gpa, ctx.io, ctx.root.client, ctx.root.provider, base_msg };- title_fut = ctx.io.concurrent(title_mod.titleTask, title_args) catch- ctx.io.async(title_mod.titleTask, title_args);+ title_jobs.start(ctx, base_msg);}- defer if (title_fut) |*f| {- applyAiTitle(ctx, f);- };// TUI/session header: once the first real prompt materializes the chat,// show what this terminal tab is working on and the exact folder, and@@ -619,14 +683,8 @@ pub fn run(ctx: *Ctx) !void {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 });}- // Apply the AI summary title + fleet champions that ran in the background- // overlapping the turn — both off the critical path. The printed header kept- // the fast prompt title; the summary now lands on the redrawable window title- // and the saved session filename. Usually already resolved by here.- if (title_fut) |*f| {- applyAiTitle(ctx, f);- title_fut = null;- }+ // Apply only if already complete; poll never waits for title generation.+ title_jobs.poll(ctx);fleet.joinElites(ctx.io); // publish backgrounded fleet champions for the next turn (no-op once joined)// turn_end lifecycle hooks (best-effort; interrupted/errored turnsdiff --git a/src/mainloop_score.zig b/src/mainloop_score.zigindex ca4399e3..8ba4f3ed 100644--- a/src/mainloop_score.zig+++ b/src/mainloop_score.zig@@ -94,7 +94,9 @@ pub fn handle(root: *agent_mod.Agent, obj: std.json.ObjectMap) void {.parent_sha = parent,.score = score,.notes = util.utf8Prefix(notes, 200),- .run_id = run_id,+ // `run_id` is reserved for the trajectory file's invocation identity.+ // A score request may name external provenance, so keep that distinct.+ .score_run_id = run_id,.judge_id = judge_id,.artifact_sha = artifact_sha,.eval_set_hash = eval_set_hash,diff --git a/src/pickers.zig b/src/pickers.zigindex 4907094a..e8ddad5f 100644--- a/src/pickers.zig+++ b/src/pickers.zig@@ -510,7 +510,7 @@ test "fuzzyScore ranks basename prefix above substring above subsequence" {const readme = fuzzyScore("README.md", "dem").?;try std.testing.expect(demo > readme);// substring beats subsequence- const sub = fuzzyScore("harness.trace.jsonl", "trace").?;+ const sub = fuzzyScore(".graff/traces/run.jsonl", "trace").?;const seq = fuzzyScore("t-r-a-c-e.txt", "trace").?;try std.testing.expect(sub > seq);// basename prefix beats mid-path substringdiff --git a/src/prompts.zig b/src/prompts.zigindex 8bce9e42..7f18975f 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -32,13 +32,14 @@ pub const main_system_prompt =\\{{prev}} carrying each phase's results into the next. Use todo_write to\\track multi-step work. Work directly for small sequential steps.\\- \\The harness writes a JSONL event trace of this session to- \\harness.trace.jsonl in the working directory: one object per line with+ \\The harness writes this run's JSONL event trace beneath+ \\.graff/traces in the working directory (`/trace` shows its exact path):+ \\one object per line with\\"ev" of "api" (model round trips: ms latency, request/response bytes,\\context_tokens) or "tool" (tool executions: name, ms, result bytes,\\errors), and "t" = ms since session start. When asked to debug, profile,- \\or explain the harness's own behavior — including your own — read that- \\file and analyze it.+ \\or explain the harness's own behavior — including your own — use `/trace`+ \\to locate that run's file, then read and analyze it.\\\\If you hit a bug or limitation in the harness itself (this graff/codegraff\\agent — its tools, prompts, streaming, sessions, or behavior — as opposeddiff --git a/src/providers.zig b/src/providers.zigindex fe842e73..4bef9cf5 100644--- a/src/providers.zig+++ b/src/providers.zig@@ -100,6 +100,7 @@ fn applyProviderInner(root: *Agent, arena: Allocator, p: Provider, persist: boolroot.cap_new = false; // per-provider token-cap quirk; relearn on rejectionroot.effort_rejected = false; // new model may accept reasoning_effort; relearnroot.ws_off = false; // a previous Codex WS fallback must not leak across switches+ root.ws_transport_failures = 0;root.compact_transport_failures = 0;root.last_context_tokens = root.fullRequestEstimateTokens();root.context_local_tokens = root.last_context_tokens;@@ -429,6 +430,7 @@ test "applyProviderInner preserves the server meter on an exact model re-selectiroot.cap_new = true;root.effort_rejected = true;root.ws_off = true;+ root.ws_transport_failures = 2;_ = try applyProviderInner(&root, a, p, false);try std.testing.expect(root.tools_responses.len > 0);try std.testing.expectEqual(@as(usize, 0), root.tools_anthropic.len);@@ -448,6 +450,7 @@ test "applyProviderInner preserves the server meter on an exact model re-selectitry std.testing.expect(!root.cap_new);try std.testing.expect(!root.effort_rejected);try std.testing.expect(!root.ws_off);+ try std.testing.expectEqual(@as(u8, 0), root.ws_transport_failures);var changed_format = changed;changed_format.id = "deepseek";diff --git a/src/repl_glue.zig b/src/repl_glue.zigindex c807c272..971689ad 100644--- a/src/repl_glue.zig+++ b/src/repl_glue.zig@@ -50,6 +50,8 @@ pub const ReplCtx = struct {fallback_active: bool,fallback_blocked: bool,registry: ?*mcp.Registry,+ tracer: ?*@import("trace.zig").Tracer,+ run_budget: ?*@import("run_budget.zig").RunBudget,sys_normal: []const u8,tools_anthropic: []const u8,tools_openai: []const u8,@@ -271,6 +273,8 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu.in = null, // never prompt for tool approval / ask_user.stream_quiet = false, // stream tokens live into the repl pane.registry = c.registry,+ .tracer = c.tracer,+ .run_budget = c.run_budget,.approvals = &approvals,.sys_normal = sys,.tools_anthropic = c.tools_anthropic,diff --git a/src/run_budget.zig b/src/run_budget.zignew file mode 100644index 00000000..61ffdbe5--- /dev/null+++ b/src/run_budget.zig@@ -0,0 +1,110 @@+//! Invocation-wide model-call and concurrency budget shared by the root,+//! subagents, workflow retries, judges, compaction, and AI title generation.+//! Every Agent borrows the same instance; atomics make admission safe across+//! the Io pool without serializing network calls behind a mutex.++const std = @import("std");+const Io = std.Io;++pub const default_max_concurrency: u32 = 4;+pub const default_max_depth: u8 = 1;+pub const default_max_model_calls: u64 = 256;++pub const CallKind = enum {+ root,+ child,+ workflow_retry,+ judge,+ title,+ compaction,+};++pub const Permit = struct {+ budget: *RunBudget,+ call_number: u64,+ kind: CallKind,+ released: bool = false,++ pub fn release(self: *Permit) void {+ if (self.released) return;+ self.released = true;+ const before = self.budget.active.fetchSub(1, .release);+ std.debug.assert(before > 0);+ }+};++pub const RunBudget = struct {+ max_model_calls: u64 = default_max_model_calls,+ max_concurrency: u32 = default_max_concurrency,+ max_depth: u8 = default_max_depth,+ model_calls: std.atomic.Value(u64) = .init(0),+ active: std.atomic.Value(u32) = .init(0),+ peak_active: std.atomic.Value(u32) = .init(0),++ fn acquireConcurrency(self: *RunBudget, io: Io) !void {+ while (true) {+ var current = self.active.load(.acquire);+ if (current < self.max_concurrency) {+ if (self.active.cmpxchgWeak(current, current + 1, .acquire, .monotonic)) |observed| {+ current = observed;+ continue;+ }+ _ = self.peak_active.fetchMax(current + 1, .monotonic);+ return;+ }+ // Waiting is cancelable: Esc/session shutdown can stop a queued+ // title or child instead of leaving it parked behind the limiter.+ try io.sleep(.fromMilliseconds(10), .awake);+ }+ }++ fn reserveCall(self: *RunBudget) !u64 {+ var current = self.model_calls.load(.acquire);+ while (current < self.max_model_calls) {+ if (self.model_calls.cmpxchgWeak(current, current + 1, .acq_rel, .acquire)) |observed| {+ current = observed;+ continue;+ }+ return current + 1;+ }+ return error.RunBudgetExhausted;+ }++ /// Admit one logical provider request. Transport retries remain inside the+ /// same permit; a workflow retry constructs a new Agent and therefore takes+ /// a new call from the same shared ceiling.+ pub fn acquire(self: *RunBudget, io: Io, depth: u8, kind: CallKind) !Permit {+ if (depth > self.max_depth) return error.AgentDepthExceeded;+ try self.acquireConcurrency(io);+ errdefer {+ const before = self.active.fetchSub(1, .release);+ std.debug.assert(before > 0);+ }+ const call_number = try self.reserveCall();+ return .{ .budget = self, .call_number = call_number, .kind = kind };+ }++ pub fn used(self: *const RunBudget) u64 {+ return self.model_calls.load(.acquire);+ }++ pub fn remaining(self: *const RunBudget) u64 {+ return self.max_model_calls -| self.used();+ }+};++test "RunBudget enforces depth, call ceiling, and releases concurrency" {+ var budget: RunBudget = .{ .max_model_calls = 2, .max_concurrency = 1, .max_depth = 1 };+ var first = try budget.acquire(std.testing.io, 0, .root);+ try std.testing.expectEqual(@as(u64, 1), first.call_number);+ try std.testing.expectEqual(@as(u32, 1), budget.active.load(.acquire));+ first.release();+ try std.testing.expectEqual(@as(u32, 0), budget.active.load(.acquire));++ var second = try budget.acquire(std.testing.io, 1, .child);+ second.release();+ try std.testing.expectError(error.RunBudgetExhausted, budget.acquire(std.testing.io, 0, .root));+ try std.testing.expectError(error.AgentDepthExceeded, budget.acquire(std.testing.io, 2, .child));+ try std.testing.expectEqual(@as(u64, 0), budget.remaining());+ try std.testing.expectEqual(@as(u32, 1), budget.peak_active.load(.acquire));+}diff --git a/src/schema.zig b/src/schema.zigindex 16d8474f..4c0a8330 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -25,7 +25,7 @@ const schema_protocol_json =\\{\\ "transport": "newline-delimited JSON over stdin/stdout (--json)",\\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"model\":\"gpt-5.5\",\"provider\":\"codex\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"}, {\"type\":\"set_effort\",\"level\":\"low|medium|high|xhigh|max|ultra\"}, and {\"type\":\"set_fast\",\"on\":true} are live control requests acked by model/compact/mode/agent/effort/fast/ultracode events. For compatibility, set_model also accepts legacy {\"name\":\"provider model|model\"}. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",- \\ "score_request": "{\"type\":\"score\",\"prompt_sha\":\"<16 hex>\",\"score\":0.7,\"notes\":\"...\",\"parent_sha\":\"<16 hex, optional>\"} appends an evaluation record for an agent/prompt variant to harness.trajectory.jsonl (the append-only DGM-style archive; prompt_sha = first 8 bytes of SHA-256 of the system prompt, hex; parent_sha records which prompt this variant was mutated from — the lineage edge DGM parent selection counts children with) and acks with a score event",+ \\ "score_request": "{\"type\":\"score\",\"prompt_sha\":\"<16 hex>\",\"score\":0.7,\"notes\":\"...\",\"parent_sha\":\"<16 hex, optional>\"} appends an evaluation record for an agent/prompt variant to this run's file under .graff/trajectories (the aggregate append-only DGM-style archive; prompt_sha = first 8 bytes of SHA-256 of the system prompt, hex; parent_sha records which prompt this variant was mutated from — the lineage edge DGM parent selection counts children with) and acks with a score event",\\ "events": [\\ {"type": "text", "text": "assistant text delta"},\\ {"type": "reasoning", "text": "reasoning/thinking delta (GUI shows a collapsible Thinking block)"},@@ -63,7 +63,7 @@ const schema_serve_json =\\ "endpoints": [\\ {"method": "GET", "path": "/healthz", "description": "liveness + version, no auth"},\\ {"method": "GET", "path": "/v1/schema", "description": "this schema document"},- \\ {"method": "POST", "path": "/v1/sessions", "description": "create a session (a graff --json child); optional JSON body {\"model\",\"yolo\",\"system_prompt\",\"append_system_prompt\",\"maxToolCalls\",\"dedupeToolCalls\"} overrides serve-level defaults; responds {\"session_id\":\"<16 hex>\"}"},+ \\ {"method": "POST", "path": "/v1/sessions", "description": "create a session (a graff --json child); optional JSON body {\"model\",\"yolo\",\"system_prompt\",\"append_system_prompt\",\"maxToolCalls\",\"maxModelCalls\",\"dedupeToolCalls\"} overrides serve-level defaults; responds {\"session_id\":\"<16 hex>\"}"},\\ {"method": "POST", "path": "/v1/sessions/{id}", "description": "body is ONE stdio-protocol request object (user / set_system_prompt / set_model / compact / set_mode / set_agent / score / answer); non-answer requests stream application/x-ndjson events until the request's terminal event (turn/error, or the request-specific ack); answer requests return JSON ack while the original user stream continues; one non-answer request in flight per session at a time"},\\ {"method": "DELETE", "path": "/v1/sessions/{id}", "description": "graceful close: waits for any in-flight request, then EOFs the child's stdin"}\\ ]@@ -80,6 +80,7 @@ const schema_flags_json =\\ {"flag": "--append-system-prompt", "arg": "text", "description": "append extra text to the end of the system prompt"},\\ {"flag": "--json", "arg": null, "description": "structured stdio protocol (JSON in, JSONL events out)"},\\ {"flag": "--max-tool-calls", "arg": "N", "description": "hard per-turn root tool-call budget; rejected calls emit tool_rejected/tool_result"},+ \\ {"flag": "--max-model-calls", "arg": "N", "description": "invocation-wide provider-call ceiling shared by root, subagents, retries, title, compaction, and judges; default 256"},\\ {"flag": "--dedupe-tool-calls", "arg": null, "description": "reject duplicate root tool name+normalized-input calls per turn"},\\ {"flag": "--no-telemetry", "arg": null, "description": "disable anonymous OTEL usage telemetry for this run"}\\]diff --git a/src/serve.zig b/src/serve.zigindex 52b5a618..ecc00aa2 100644--- a/src/serve.zig+++ b/src/serve.zig@@ -26,6 +26,9 @@ const ServeConfig = struct {model: ?[]const u8,system_prompt: ?[]const u8,append_system_prompt: ?[]const u8,+ max_tool_calls: ?u64,+ max_model_calls: u64,+ dedupe_tool_calls: bool,};/// Cap on one child event line (a tool_result event carrying a big tool@@ -223,8 +226,9 @@ fn serveCreate(st: *ServeState, req: *std.http.Server.Request) !void {var yolo = st.cfg.yolo;var sys = st.cfg.system_prompt;var append_sys = st.cfg.append_system_prompt;- var max_tools: ?u64 = null;- var dedupe_tools = false;+ var max_tools = st.cfg.max_tool_calls;+ var max_models: ?u64 = st.cfg.max_model_calls;+ var dedupe_tools = st.cfg.dedupe_tool_calls;if (std.mem.trim(u8, body, " \t\r\n").len > 0) {const v = std.json.parseFromSliceLeaky(Value, arena, body, .{ .allocate = .alloc_always }) catchreturn respondJson(st, req, .bad_request, "{\"error\":\"body must be a JSON object\"}");@@ -244,6 +248,9 @@ fn serveCreate(st: *ServeState, req: *std.http.Server.Request) !void {if (v.object.get("maxToolCalls") orelse v.object.get("max_tool_calls")) |m| if (m == .integer and m.integer >= 0) {max_tools = @intCast(m.integer);};+ if (v.object.get("maxModelCalls") orelse v.object.get("max_model_calls")) |m| if (m == .integer and m.integer >= 0) {+ max_models = @intCast(m.integer);+ };if (v.object.get("dedupeToolCalls") orelse v.object.get("dedupe_tool_calls")) |d| if (d == .bool) {dedupe_tools = d.bool;};@@ -254,6 +261,7 @@ fn serveCreate(st: *ServeState, req: *std.http.Server.Request) !void {if (yolo) try argv.append(arena, "--yolo");if (model) |m| try argv.appendSlice(arena, &.{ "--model", m });if (max_tools) |n| try argv.appendSlice(arena, &.{ "--max-tool-calls", try std.fmt.allocPrint(arena, "{d}", .{n}) });+ if (max_models) |n| try argv.appendSlice(arena, &.{ "--max-model-calls", try std.fmt.allocPrint(arena, "{d}", .{n}) });if (dedupe_tools) try argv.append(arena, "--dedupe-tool-calls");if (sys) |s| try argv.appendSlice(arena, &.{ "--system-prompt", s });if (append_sys) |s| try argv.appendSlice(arena, &.{ "--append-system-prompt", s });diff --git a/src/session.zig b/src/session.zigindex f37f5664..0a50f154 100644--- a/src/session.zig+++ b/src/session.zig@@ -415,6 +415,7 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8root.cap_new = false; // per-provider; relearn on rejectionroot.effort_rejected = false;root.ws_off = false; // transport failures belong to the prior live session+ root.ws_transport_failures = 0;root.compact_transport_failures = 0;root.last_usage_includes_output = false;root.last_request_context_overflow = false;diff --git a/src/session_run.zig b/src/session_run.zigindex 724ccd2a..f2dfb581 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -79,6 +79,8 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent.fallback_active = root.fallback_active,.fallback_blocked = root.fallback_blocked,.registry = root.registry,+ .tracer = root.tracer,+ .run_budget = root.run_budget,.sys_normal = root.sys_normal,.tools_anthropic = root.tools_anthropic,.tools_openai = root.tools_openai,@@ -402,12 +404,14 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:} else |_| {}}ws.g_debug = environ_map.get("GRAFF_WS_DEBUG") != null;- // GRAFF_WS_FORCE_FAIL_ONCE=1|true|on|yes arms the one-shot forced WS- // connect failure (integration-test seam for the SSE fallback + ws_off- // latch). Only affirmative values arm it — =0 must leave it disarmed.+ // GRAFF_WS_FORCE_FAIL_ONCE proves a clean retry; the counted sibling proves+ // that two consecutive failures latch the SSE fallback. Test seams only.if (environ_map.get("GRAFF_WS_FORCE_FAIL_ONCE")) |v| {ws.g_force_connect_failure_once = std.mem.eql(u8, v, "1") or std.ascii.eqlIgnoreCase(v, "true") or std.ascii.eqlIgnoreCase(v, "on") or std.ascii.eqlIgnoreCase(v, "yes");}+ if (environ_map.get("GRAFF_WS_FORCE_FAIL_COUNT")) |v| {+ ws.g_force_connect_failure_count = std.fmt.parseInt(u8, std.mem.trim(u8, v, " \t"), 10) catch 0;+ }skills.loadSkillSettings(io, arena); // per-skill opt-outs, also gates the auto-connectanim.loadAnimationSetting(io, arena); // {"animation": "..."} → thinking spinner choiceanim.loadThemeSetting(io, arena); // {"theme": "<name>"} → opt-in terminal color themediff --git a/src/session_start.zig b/src/session_start.zigindex d58905e1..9ec4e03c 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -3,7 +3,7 @@//! so it lives in its own sibling file). Covers everything that happens//! AFTER credentials/model are resolved and the http.Client exists: the//! `graff title` subcommand, terminal-color/`-w`-worktree/banner setup,-//! opening the trace/trajectory files + telemetry + score-signing, the MCP+//! opening the run-scoped trace/trajectory files + telemetry + score-signing, the MCP//! registry connect (consent prompt + companion auto-activation), and the//! `graff repl`/one-shot-prompt early-exit paths.//!@@ -53,11 +53,11 @@ const session = @import("session.zig");/// that prompt (one title call, no session). For A/B-ing title prompts/styles./// Moved out of main() (600-line goal). Returns true when handled (main()/// should return immediately without going any further).-pub fn runTitleCommand(io: Io, gpa: Allocator, arena: Allocator, client: *std.http.Client, default_provider: provider_mod.Provider, out: *Io.Writer, flags: args.Flags) !bool {+pub fn runTitleCommand(io: Io, gpa: Allocator, arena: Allocator, client: *std.http.Client, default_provider: provider_mod.Provider, out: *Io.Writer, flags: args.Flags, run_budget: ?*@import("run_budget.zig").RunBudget) !bool {if (!(flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "title"))) return false;if (flags.positionals.items.len < 2) std.process.fatal("usage: graff title <prompt>", .{});const tprompt = try std.mem.join(arena, " ", flags.positionals.items[1..]);- if (title_mod.titleTask(gpa, io, client, default_provider, tprompt)) |t| {+ if (title_mod.titleTask(gpa, io, client, default_provider, tprompt, run_budget, null)) |t| {defer gpa.free(t);try out.print("{s}\n", .{t});} else try out.writeAll("(title generation failed — check your model/key)\n");@@ -165,9 +165,8 @@ pub fn setupWorktreeAndBanner(}}-/// A best-effort append-only session-log file (session trace / trajectory-/// archive): the opened file handle (null on a failed open — tracing/-/// trajectory just stays off) plus the File.Writer wrapping it. The caller+/// A best-effort run-local JSONL file: the opened file handle (null on a+/// failed open — tracing/trajectory just stays off) plus the File.Writer. The caller/// owns `buf`'s storage (a stack array in main()) and must keep it alive as/// long as the returned writer is used; the writer itself is safe to copy by/// value (see startup.zig's header) since nothing takes `&writer.interface`@@ -177,39 +176,39 @@ pub const FileWriterOpen = struct {writer: Io.File.Writer,};-/// Opens the session trace file (`harness.trace.jsonl`, truncated fresh each-/// run). Moved out of main() (600-line goal) — see FileWriterOpen's doc for-/// why this is safe despite tracer/traj's dangling-pointer trap.-pub fn openTraceFile(io: Io, path: []const u8, buf: []u8) FileWriterOpen {- const file: ?Io.File = Io.Dir.cwd().createFile(io, path, .{}) catch null;+fn openRunFile(io: Io, dir_path: []const u8, path: []const u8, buf: []u8) FileWriterOpen {+ Io.Dir.cwd().createDir(io, ".graff", .default_dir) catch {};+ Io.Dir.cwd().createDir(io, dir_path, .default_dir) catch {};+ // A random run id makes collision vanishingly unlikely; exclusive creation+ // turns even that case into a disabled writer instead of truncating another+ // process's file.+ const file: ?Io.File = Io.Dir.cwd().createFile(io, path, .{ .exclusive = true }) catch null;const writer = if (file) |f| f.writer(io, buf) else undefined;return .{ .file = file, .writer = writer };}-/// Opens the trajectory archive (`harness.trajectory.jsonl`), APPEND-ONLY-/// (never truncated — it accumulates across sessions), seeking the writer's-/// position to the current end of file so new session records land after-/// prior ones. Moved out of main() (600-line goal).+/// Opens `.graff/traces/<run-id>.jsonl` exclusively.+pub fn openTraceFile(io: Io, path: []const u8, buf: []u8) FileWriterOpen {+ return openRunFile(io, trace.traces_dir, path, buf);+}++/// Opens `.graff/trajectories/<run-id>.jsonl` exclusively. The aggregate+/// archive is the directory, not a shared append cursor.pub fn openTrajFile(io: Io, path: []const u8, buf: []u8) FileWriterOpen {- const file: ?Io.File = Io.Dir.cwd().createFile(io, path, .{ .truncate = false }) catch null;- var writer = if (file) |f| f.writer(io, buf) else undefined;- if (file != null) {- if (Io.Dir.cwd().statFile(io, path, .{})) |st| {- writer.pos = st.size; // append after prior sessions- } else |_| {}- }- return .{ .file = file, .writer = writer };+ return openRunFile(io, trace.trajectories_dir, path, buf);}-/// Score-channel signing (Step 0): a per-session run_id and, if-/// GRAFF_SCORE_KEY_FILE is set, the HMAC key — so score records written this-/// session are signed and forged trajectory rows are detectable. Moved out-/// of main() (600-line goal); writes the scoring.zig globals directly-/// (mod-prefixed, never aliased).-pub fn initScoreSigning(io: Io, arena: Allocator, environ_map: anytype) void {+/// Generate the run id before worktree setup so the banner can show the exact+/// run-scoped trace path.+pub fn initScoreRunId(io: Io) void {var raw: [8]u8 = undefined;io.random(&raw);scoring.g_run_id = std.fmt.bytesToHex(raw, .lower);+}++/// Load the optional signing key after worktree setup, preserving the prior+/// meaning of relative GRAFF_SCORE_KEY_FILE paths.+pub fn loadScoreSigningKey(io: Io, arena: Allocator, environ_map: anytype) void {scoring.g_score_key = scoring.loadScoreKey(io, arena, environ_map);}diff --git a/src/startup.zig b/src/startup.zigindex 993c7577..e1508a93 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -404,6 +404,9 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process.model = flags.model_flag,.system_prompt = flags.system_prompt_flag,.append_system_prompt = flags.append_system_flag,+ .max_tool_calls = main_mod.max_tool_calls,+ .max_model_calls = main_mod.max_model_calls,+ .dedupe_tool_calls = main_mod.dedupe_tool_calls,}, exe);return true;}diff --git a/src/subagent.zig b/src/subagent.zigindex 99547866..69f5eac2 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -156,6 +156,10 @@ fn subagentFailure(gpa: Allocator, sub_id: []const u8, err: anyerror, detail: ?[/// the turn that spawned it, with the prompt's fingerprint.pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8) !ToolOutput {const gpa = ctx.gpa;+ if (ctx.run_budget) |budget| if (ctx.depth >= budget.max_depth) return .{+ .text = try gpa.dupe(u8, "agent depth limit reached (max depth 1) — do this work in the current agent"),+ .is_error = true,+ };var arena_state = std.heap.ArenaAllocator.init(gpa);defer arena_state.deinit();const arena = arena_state.allocator();@@ -172,6 +176,14 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const.out = null,.approvals = ctx.approvals,.tracer = ctx.tracer,+ .run_budget = ctx.run_budget,+ .depth = ctx.depth + 1,+ .call_kind = if (std.mem.eql(u8, kind, "judge_task"))+ .judge+ else if (std.mem.eql(u8, kind, "workflow_retry"))+ .workflow_retry+ else+ .child,.sys_override = sys_override,};const sub_start = Io.Timestamp.now(ctx.io, .awake);@@ -256,6 +268,12 @@ pub fn workflowTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_overeturn runSub(ctx, "workflow_task", label, prompt, sys_override, niche) catch |err| failure(ctx.gpa, err);}+/// A second workflow attempt has its own explicit budget kind. It still shares+/// the same invocation-wide atomic ceiling and concurrency limiter.+pub fn workflowRetryTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8) ToolOutput {+ return runSub(ctx, "workflow_retry", label, prompt, sys_override, niche) catch |err| failure(ctx.gpa, err);+}+/// The --judge LLM-as-judge run (see runEval in main): an isolated subagent/// scores the work against the rubric and ends with a `score:` line. Mirrors/// workflowTask — a thin runSub wrapper — so the eval handler can io.async itdiff --git a/src/telemetry.zig b/src/telemetry.zigindex 3f5289ec..37aefde2 100644--- a/src/telemetry.zig+++ b/src/telemetry.zig@@ -36,7 +36,7 @@ const harness_version = root.harness_version;/// best-effort POST at session end. Off entirely unless an endpoint is/// configured (OTEL_EXPORTER_OTLP_ENDPOINT or GRAFF_OTEL_ENDPOINT env);/// GRAFF_NO_TELEMETRY or --no-telemetry forces it off regardless. Counters-/// feed from the same Tracer hooks that write harness.trace.jsonl, plus+/// feed from the same Tracer hooks that write `.graff/traces/<run-id>.jsonl`, plus/// workflow/ultracode/turn events from the orchestrator. A per-install/// anonymous id (~/.simple-harness-install-id) identifies the install; SDKs/// pass their own id via HARNESS_SDK_INSTALL_ID + HARNESS_CLIENT so SDKdiff --git a/src/title.zig b/src/title.zigindex 679a2e3b..f2d6d640 100644--- a/src/title.zig+++ b/src/title.zig@@ -330,7 +330,7 @@ test "cleanTitle: normalizes a model reply into a tab label, else null (/title)"/// own arena + a throwaway one-message sub-Agent, so it can be spawned via/// io.async and overlap the real turn instead of blocking after it. Returns a/// gpa-owned title (caller frees), or null on any failure.-pub fn titleTask(gpa: std.mem.Allocator, io: Io, client: *std.http.Client, provider: Provider, prompt: []const u8) ?[]const u8 {+pub fn titleTask(gpa: std.mem.Allocator, io: Io, client: *std.http.Client, provider: Provider, prompt: []const u8, run_budget: ?*@import("run_budget.zig").RunBudget, tracer: ?*@import("trace.zig").Tracer) ?[]const u8 {var arena_state = std.heap.ArenaAllocator.init(gpa);defer arena_state.deinit();const arena = arena_state.allocator();@@ -344,6 +344,10 @@ pub fn titleTask(gpa: std.mem.Allocator, io: Io, client: *std.http.Client, provi.sub = true, // pool thread: never touches stdout or the main agent's state.label = "title",.out = null,+ .tracer = tracer,+ .run_budget = run_budget,+ .call_kind = .title,+ .responses_output_limit = 64,.sys_override = "You summarize what a coding session is about in a short, natural phrase. Reply with only the phrase.",};defer agent.tools_used.deinit(gpa);diff --git a/src/tools.zig b/src/tools.zigindex 49ad872d..42469446 100644--- a/src/tools.zig+++ b/src/tools.zig@@ -70,6 +70,7 @@ const ToolSink = trace.ToolSink;const approvals_mod = @import("approvals.zig");const Approvals = approvals_mod.Approvals;const skills = @import("skills.zig");+const run_budget_mod = @import("run_budget.zig");pub const ToolOutput = struct {text: []u8 = &.{}, // gpa-owned@@ -162,6 +163,8 @@ pub const ToolCtx = struct {from_sub: bool,approvals: ?*Approvals,tracer: ?*Tracer,+ run_budget: ?*run_budget_mod.RunBudget = null,+ depth: u8 = 0,snapshots: ?*Snapshots = null,tools_used: ?*ToolSink = null, // the calling agent's tool log (trajectory/process mining)};diff --git a/src/trace.zig b/src/trace.zigindex f3faa84b..ddecaab1 100644--- a/src/trace.zig+++ b/src/trace.zig@@ -1,19 +1,48 @@-//! Session tracing + DGM trajectory archive: the per-line JSON writer, the-//! harness.trace.jsonl event Tracer (which also feeds the telemetry counters),-//! the append-only harness.trajectory.jsonl Trajectory (the MAP-Elites fitness-//! ledger), and the per-agent ToolSink tool-call log. Split out of main.zig-//! (600-line goal). Imports telemetry.zig for the counter sink. main aliases-//! Tracer/Trajectory/ToolSink/trace_path back, re-exports trajectory_path-//! (fleet.zig back-imports it), and mod-qualifies g_traj.+//! Session tracing + DGM trajectory archive. Every invocation writes its own+//! `.graff/traces/<run-id>.jsonl` and `.graff/trajectories/<run-id>.jsonl`, so+//! independent graff processes never truncate or seek/write through the same+//! file. Every record is stamped with the run id, process id, and runtime+//! session id before the event's own fields.const std = @import("std");const Io = std.Io;const Value = std.json.Value;const Allocator = std.mem.Allocator;+const builtin = @import("builtin");const telemetry = @import("telemetry.zig");-pub const trace_path = "harness.trace.jsonl";+pub const traces_dir = ".graff/traces";+pub const trajectories_dir = ".graff/trajectories";+pub const legacy_trajectory_path = "harness.trajectory.jsonl";++/// Stable metadata prepended to every trace and trajectory record.+pub const Identity = struct {+ run_id: []const u8 = "",+ pid: u64 = 0,+ session_id: []const u8 = "",+};++pub fn currentPid() u64 {+ return if (builtin.os.tag == .windows)+ @intCast(std.os.windows.GetCurrentProcessId())+ else+ @intCast(std.posix.system.getpid());+}++pub fn newSessionId(io: Io) [32]u8 {+ var raw: [16]u8 = undefined;+ io.random(&raw);+ return std.fmt.bytesToHex(raw, .lower);+}++pub fn tracePath(allocator: Allocator, run_id: []const u8) Allocator.Error![]const u8 {+ return std.fmt.allocPrint(allocator, "{s}/{s}.jsonl", .{ traces_dir, run_id });+}++pub fn trajectoryPath(allocator: Allocator, run_id: []const u8) Allocator.Error![]const u8 {+ return std.fmt.allocPrint(allocator, "{s}/{s}.jsonl", .{ trajectories_dir, run_id });+}/// Serialize one record as a single JSON line into an in-memory buffer, then/// write the whole line to `w` in one shot. Building the line in memory first@@ -23,18 +52,37 @@ pub const trace_path = "harness.trace.jsonl";/// truncated line plus leftover buffer bytes that the next record concatenated/// onto, corrupting the JSONL (issue #86: lines like `{"text":"You ar{"kind":…`)./// Flushing per line keeps the buffer empty between records. Best-effort.-fn writeJsonLine(gpa: Allocator, w: *Io.Writer, rec: anytype) void {+fn writeJsonLine(gpa: Allocator, w: *Io.Writer, identity: Identity, rec: anytype) void {var aw: Io.Writer.Allocating = .init(gpa);defer aw.deinit();var s: std.json.Stringify = .{ .writer = &aw.writer };- s.write(rec) catch return;+ s.beginObject() catch return;+ s.objectField("run_id") catch return;+ s.write(identity.run_id) catch return;+ s.objectField("pid") catch return;+ s.write(identity.pid) catch return;+ s.objectField("session_id") catch return;+ s.write(identity.session_id) catch return;+ const Rec = @TypeOf(rec);+ switch (@typeInfo(Rec)) {+ .@"struct" => inline for (std.meta.fields(Rec)) |field| {+ // Identity owns these top-level names. Event-specific provenance+ // must use a more precise name such as `score_run_id`.+ if (comptime std.mem.eql(u8, field.name, "run_id") or+ std.mem.eql(u8, field.name, "pid") or+ std.mem.eql(u8, field.name, "session_id")) continue;+ s.objectField(field.name) catch return;+ s.write(@field(rec, field.name)) catch return;+ },+ else => @compileError("trace records must be structs"),+ }+ s.endObject() catch return;aw.writer.writeByte('\n') catch return;w.writeAll(aw.writer.buffered()) catch return;w.flush() catch return;}-/// Session event trace: one JSON object per line, written to trace_path in-/// the cwd (truncated at startup, so it always covers the current session).+/// Session event trace: one JSON object per line in the run's unique file./// Thread-safe — agents on pool threads share it through the mutex. The/// system prompt tells the agent the file exists, so it can read its own/// trace to debug or profile the harness ("t" is ms since session start).@@ -44,6 +92,8 @@ pub const Tracer = struct {gpa: Allocator,out: ?*Io.Writer,start: Io.Timestamp,+ identity: Identity = .{},+ path: []const u8 = "",enabled: bool = true,pub fn api(self: *Tracer, label: []const u8, model: []const u8, ms: i64, req_bytes: usize, resp_bytes: usize, context_tokens: u64, cache_read: u64, is_error: bool) void {@@ -90,7 +140,7 @@ pub const Tracer = struct {defer self.mutex.unlock(self.io);const w = self.out orelse return;if (!self.enabled) return;- writeJsonLine(self.gpa, w, event);+ writeJsonLine(self.gpa, w, self.identity, event);}pub fn toggle(self: *Tracer) bool {@@ -103,8 +153,6 @@ pub const Tracer = struct {// ── Trajectory (DGM-style archive tree) ────────────────────────────────────-pub const trajectory_path = "harness.trajectory.jsonl";-/// Session trajectory in the shape of the Darwin Gödel Machine's archive/// tree (arXiv:2505.22954): one JSON node per agent run. Root turns form/// the spine (each turn's parent is the previous turn); every subagent or@@ -113,13 +161,16 @@ pub const trajectory_path = "harness.trajectory.jsonl";/// set_system_prompt on the spine, per-child system_prompt overrides on the/// fan-out — are visible as hash changes along edges, and a lineage can be/// replayed or scored offline (see docs/hyperagents.md, arXiv:2603.19461).-/// Written to harness.trajectory.jsonl, truncated at startup like the trace.+/// Written to the invocation's unique trajectory file. Archive readers scan+/// the directory and also ingest the legacy single-file archive read-only.pub const Trajectory = struct {mutex: Io.Mutex = .init,io: Io,gpa: Allocator,out: ?*Io.Writer,start: Io.Timestamp,+ identity: Identity = .{},+ path: []const u8 = "",next_id: u64 = 1, // node 0 is the session itselfturn_node: u64 = 0, // current root-turn node: parent for spawned agentsseen_shas: std.ArrayList([16]u8) = .empty, // prompts captured this session@@ -173,7 +224,7 @@ pub const Trajectory = struct {pub fn writeLocked(self: *Trajectory, rec: anytype) void {const w = self.out orelse return;- writeJsonLine(self.gpa, w, rec);+ writeJsonLine(self.gpa, w, self.identity, rec);}pub fn deinit(self: *Trajectory) void {@@ -184,6 +235,49 @@ pub const Trajectory = struct {/// Set by main(); runSub and the REPL loop record nodes through this.pub var g_traj: ?*Trajectory = null;+fn appendArchiveFile(io: Io, out: *Io.Writer, path: []const u8, remaining: *usize) bool {+ if (remaining.* == 0) return false;+ const file = Io.Dir.cwd().openFile(io, path, .{}) catch return false;+ defer file.close(io);+ const stat = file.stat(io) catch return false;+ const size = std.math.cast(usize, stat.size) orelse return false;+ if (size == 0 or size > remaining.*) return false;+ var buf: [8 * 1024]u8 = undefined;+ var reader = file.reader(io, &buf);+ reader.interface.streamExact(out, size) catch return false;+ // A harmless blank separator also repairs a legacy file missing its final+ // newline, without retaining a second full-file copy just to inspect it.+ out.writeByte('\n') catch return false;+ remaining.* -= size;+ return true;+}++/// Read the local DGM archive across all run-scoped trajectory files. The old+/// `harness.trajectory.jsonl` is included read-only so existing scores remain+/// promotable after upgrading. Best-effort and capped across the whole archive.+pub fn readTrajectoryArchive(io: Io, arena: Allocator, max_bytes: usize) []const u8 {+ var aw: Io.Writer.Allocating = .init(arena);+ defer aw.deinit();+ var remaining = max_bytes;++ var dir = Io.Dir.cwd().openDir(io, trajectories_dir, .{ .iterate = true }) catch+ return if (appendArchiveFile(io, &aw.writer, legacy_trajectory_path, &remaining)) aw.toOwnedSlice() catch "" else "";+ {+ defer dir.close(io);+ var it = dir.iterate();+ while (remaining > 0) {+ const entry = it.next(io) catch break;+ if (entry == null) break;+ if (entry.?.kind != .file or !std.mem.endsWith(u8, entry.?.name, ".jsonl")) continue;+ const path = std.fmt.allocPrint(arena, "{s}/{s}", .{ trajectories_dir, entry.?.name }) catch continue;+ _ = appendArchiveFile(io, &aw.writer, path, &remaining);+ }+ }+ // Legacy rows remain readable, but current run files receive the cap first.+ _ = appendArchiveFile(io, &aw.writer, legacy_trajectory_path, &remaining);+ return aw.toOwnedSlice() catch "";+}+/// Per-agent record of external tool calls (name + error flag, in call/// order): the process signal behind "which tool combinations work" —/// rendered into trajectory nodes and OTLP run events, joinable to scores@@ -231,8 +325,9 @@ pub const ToolSink = struct {test "writeJsonLine: one complete newline-terminated JSON record per call" {var aw: Io.Writer.Allocating = .init(std.testing.allocator);defer aw.deinit();- writeJsonLine(std.testing.allocator, &aw.writer, .{ .kind = "turn", .id = @as(u64, 7), .ok = true });- writeJsonLine(std.testing.allocator, &aw.writer, .{ .kind = "prompt", .text = "hi" });+ const identity: Identity = .{ .run_id = "run-a", .pid = 42, .session_id = "session-a" };+ writeJsonLine(std.testing.allocator, &aw.writer, identity, .{ .kind = "turn", .id = @as(u64, 7), .ok = true });+ writeJsonLine(std.testing.allocator, &aw.writer, identity, .{ .kind = "prompt", .text = "hi" });const out = aw.writer.buffered();try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, out, "\n"));var it = std.mem.splitScalar(u8, std.mem.trimEnd(u8, out, "\n"), '\n');@@ -240,5 +335,17 @@ test "writeJsonLine: one complete newline-terminated JSON record per call" {var p = try std.json.parseFromSlice(Value, std.testing.allocator, line, .{});defer p.deinit();try std.testing.expect(p.value == .object); // each line parses as valid JSON+ try std.testing.expectEqualStrings("run-a", p.value.object.get("run_id").?.string);+ try std.testing.expectEqual(@as(i64, 42), p.value.object.get("pid").?.integer);+ try std.testing.expectEqualStrings("session-a", p.value.object.get("session_id").?.string);}}++test "run-scoped paths separate traces and trajectories" {+ const trace_path = try tracePath(std.testing.allocator, "abc123");+ defer std.testing.allocator.free(trace_path);+ const trajectory_path = try trajectoryPath(std.testing.allocator, "abc123");+ defer std.testing.allocator.free(trajectory_path);+ try std.testing.expectEqualStrings(".graff/traces/abc123.jsonl", trace_path);+ try std.testing.expectEqualStrings(".graff/trajectories/abc123.jsonl", trajectory_path);+}diff --git a/src/workflow.zig b/src/workflow.zigindex 7a4076d1..a08543c2 100644--- a/src/workflow.zig+++ b/src/workflow.zig@@ -22,6 +22,7 @@ const failure = tools.failure;const subagent = @import("subagent.zig");const workflowTask = subagent.workflowTask;+const workflowRetryTask = subagent.workflowRetryTask;const runSub = subagent.runSub;const scoreVariants = subagent.scoreVariants;const max_workflow_tasks = subagent.max_workflow_tasks;@@ -118,7 +119,7 @@ fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) Toolvar out = runSub(ctx, "workflow_task", st.label, prompt, st.override, st.niche) catch |e| failure(gpa, e);if (out.is_error) {gpa.free(out.text);- out = runSub(ctx, "workflow_task", st.label, prompt, st.override, st.niche) catch |e| failure(gpa, e);+ out = runSub(ctx, "workflow_retry", st.label, prompt, st.override, st.niche) catch |e| failure(gpa, e);if (out.is_error) {gpa.free(out.text);return .{@@ -322,7 +323,7 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {const refut = try arena.alloc(Io.Future(ToolOutput), nf);for (refut, 0..) |*rf, k| {const i = fidx[k];- rf.* = ctx.io.async(workflowTask, .{ ctx, labels[i], prompts[i], overrides[i], niches[i] });+ rf.* = ctx.io.async(workflowRetryTask, .{ ctx, labels[i], prompts[i], overrides[i], niches[i] });}for (refut, 0..) |*rf, k| {const retry = rf.await(ctx.io);diff --git a/src/ws.zig b/src/ws.zigindex 16727cc5..2a6571f6 100644--- a/src/ws.zig+++ b/src/ws.zig@@ -12,7 +12,7 @@//!//! Observability: set `g_debug = true` (GRAFF_WS_DEBUG=1) to trace the//! handshake + every frame to stderr; the transport layer additionally routes-//! structured ws lifecycle events to the tracer (harness.trace.jsonl) so an+//! structured ws lifecycle events to the run's file under .graff/traces so an//! agent can debug a ws turn after the fact.const std = @import("std");@@ -25,8 +25,10 @@ const tls = std.crypto.tls;/// GRAFF_WS_DEBUG=1 → dump the handshake + frame headers to stderr.pub var g_debug: bool = false;/// Deterministic integration-test seam: fail the next WS connect so the live-/// binary can prove its SSE fallback against the real endpoint.+/// binary can prove its clean retry against the real endpoint.pub var g_force_connect_failure_once: bool = false;+/// Counted sibling used to prove the second consecutive failure latches SSE.+pub var g_force_connect_failure_count: u8 = 0;fn dbg(comptime fmt: []const u8, args: anytype) void {if (g_debug) std.debug.print("[ws] " ++ fmt ++ "\n", args);@@ -87,6 +89,11 @@ pub const WsClient = struct {/// Reader/Writer interfaces and the TLS client reference its inline buffers/// and each other).pub fn connect(gpa: Allocator, io: Io, url: []const u8, insecure: bool, headers: []const Header) Error!*WsClient {+ if (g_force_connect_failure_count > 0) {+ g_force_connect_failure_count -= 1;+ dbg("forced connect failure (GRAFF_WS_FORCE_FAIL_COUNT)", .{});+ return error.HandshakeFailed;+ }if (g_force_connect_failure_once) {g_force_connect_failure_once = false;dbg("forced connect failure (GRAFF_WS_FORCE_FAIL_ONCE)", .{});@@ -335,3 +342,15 @@ test "forced WS failure is one-shot for SSE fallback integration tests" {));try std.testing.expect(!g_force_connect_failure_once);}++test "counted forced WS failures exhaust exactly" {+ g_force_connect_failure_count = 2;+ inline for (0..2) |_| try std.testing.expectError(error.HandshakeFailed, WsClient.connect(+ std.testing.allocator,+ std.testing.io,+ "wss://unused.invalid/x",+ false,+ &.{},+ ));+ try std.testing.expectEqual(@as(u8, 0), g_force_connect_failure_count);+}