Skip to content

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

Python

Avoid redundant literal-reply retries and isolate request diagnostics

Rach Pradhan636b7849b9d9
diff --git a/docs/adr/0052-lean-oneshot-bounces-prose.md b/docs/adr/0052-lean-oneshot-bounces-prose.md
index 50075815..61b970e1 100644
--- a/docs/adr/0052-lean-oneshot-bounces-prose.md
+++ b/docs/adr/0052-lean-oneshot-bounces-prose.md
@@ -67,3 +67,14 @@ the backstop when the model writes "I fixed it" with zero tools. No
Explicit informational turns are exempt from the edit-oriented bounce. The
generic fallback now conditions edits on the actual request. Mixed change
requests retain the coding completion policy.
+
+## Literal-reply refinement
+
+A fully consumed request of the form `Reply with exactly: pong` (also
+`Respond` or `Answer`, optionally preceded by `Please`) is exempt from this
+bounce. Its payload must be a single token or one quoted literal; a trailing
+instruction keeps the coding backstop. Action words inside the quoted literal
+are data. This recognition is local to the fake-done guard: it does not change
+intent classification, tool permissions, empty-response retries, or open-work
+completion gates. Translation and ambiguous multiword requests remain outside
+this narrow exemption.
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 09158e08..2df1908a 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -124,3 +124,6 @@
{"args": ["--old"], "prompt": "Run the scripted verification fixture and report only observed results.", "id": "completion-resumed-failure", "why": "A resumed verification result admits completion only after a successful terminal exit.", "script": [{"tool": "shell", "arguments": {"command": "printf 'RESUMED_EXIT_SEVEN\\n'; exit 7", "run_in_background": true}}, {"tool": "shell", "arguments": {"command": "sleep 0.3"}}, {"tools": [{"tool": "shell", "arguments": {"action": "output", "id": 1, "wait_ms": 1000}}, {"tool": "attempt_completion", "arguments": {"result": "FAILED_COMPLETION"}}]}, {"text": "Verification failed; completion withheld."}], "assert": [{"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"event": {"type": "tool_result", "name": "shell", "is_error": true, "text": "[job 1: exited with code 7]\nRESUMED_EXIT_SEVEN\n", "id": "call_3_0"}}, {"request_contains": {"text": "exited with code 7"}}]}
{"args": ["--old"], "prompt": "Run the scripted verification fixture and report only observed results.", "id": "completion-resumed-success", "why": "A resumed verification result admits completion only after a successful terminal exit.", "script": [{"tool": "shell", "arguments": {"command": "printf 'RESUMED_EXIT_ZERO\\n'; exit 0", "run_in_background": true}}, {"tool": "shell", "arguments": {"command": "sleep 0.3"}}, {"tools": [{"tool": "shell", "arguments": {"action": "output", "id": 1, "wait_ms": 1000}}, {"tool": "attempt_completion", "arguments": {"result": "VERIFIED_COMPLETION"}}]}, {"text": "Verification failed; completion withheld."}], "assert": [{"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"final_text_contains": "VERIFIED_COMPLETION"}, {"event": {"type": "tool_result", "name": "shell", "is_error": false, "text": "[job 1: exited with code 0]\nRESUMED_EXIT_ZERO\n", "id": "call_3_0"}}]}
{"id": "malformed-edit-batch-recovers", "why": "A string-valued edits field used to panic on unchecked union access; return a tool error without writing so the next model turn can retry a valid array and finish.", "args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Create version.txt with alpha and beta, then update both lines using a batched edit. Correct any malformed arguments and verify the final file.", "script": [{"tool": "write_file", "arguments": {"path": "version.txt", "content": "alpha\nbeta\n"}}, {"tool": "edit_file", "arguments": {"path": "version.txt", "edits": "[{\"old_string\":\"alpha\",\"new_string\":\"ALPHA\"}]"}}, {"tool": "edit_file", "arguments": {"path": "version.txt", "edits": [{"old_string": "alpha", "new_string": "ALPHA"}, {"old_string": "beta", "new_string": "BETA"}]}}, {"tool": "bash", "arguments": {"command": "test \"$(cat version.txt)\" = \"$(printf 'ALPHA\\nBETA')\" && echo EDIT_BATCH_RECOVERED"}}, {"text": "The corrected batch landed and was verified."}], "assert": [{"event": {"type": "tool_call_finished", "name": "edit_file", "is_error": true}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 1}}, {"event": {"type": "tool_call_finished", "name": "edit_file", "is_error": false}}, {"request_contains": {"index": 2, "text": "edits must be an array"}}, {"event": {"type": "tool_result", "name": "bash", "text": "EDIT_BATCH_RECOVERED\n"}}, {"file_equals": {"path": "version.txt", "content": "ALPHA\nBETA\n"}}, {"final_text_contains": "The corrected batch landed and was verified."}]}
+{"id": "exact-reply-one-call", "why": "An explicit literal reply needs no edit-oriented fake-done retry.", "args": ["--lean", "-p", "Reply with exactly: pong"], "prompt": "Reply with exactly: pong", "script": [{"text": "pong"}], "assert": [{"request_count": 1}, {"stdout_equals": "pong\n"}]}
+{"id": "exact-reply-quoted-action-words", "why": "An explicit literal reply needs no edit-oriented fake-done retry.", "args": ["--lean", "-p", "Reply with exactly: \"run tests and deploy\""], "prompt": "Reply with exactly: \"run tests and deploy\"", "script": [{"text": "run tests and deploy"}], "assert": [{"request_count": 1}, {"stdout_equals": "run tests and deploy\n"}]}
+{"id": "exact-reply-mixed-coding-bounces", "why": "A trailing coding request must retain the first-response backstop and perform the actual write.", "args": ["--lean", "-p", "Reply with exactly: \"pong\"; then create target.txt containing changed."], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Reply with exactly: \"pong\"; then create target.txt containing changed.", "script": [{"text": "pong"}, {"tool": "write_file", "arguments": {"path": "target.txt", "content": "changed\n"}}, {"tool": "bash", "arguments": {"command": "test \"$(cat target.txt)\" = changed"}}, {"text": "Created and verified target.txt."}], "assert": [{"request_count": 4}, {"request_contains": {"index": 1, "text": "a description alone is not completion"}}, {"file_equals": {"path": "target.txt", "content": "changed\n"}}, {"stdout_equals": "Created and verified target.txt.\n"}]}
diff --git a/graff-evals/README.md b/graff-evals/README.md
index 8710d195..de3e1c61 100644
--- a/graff-evals/README.md
+++ b/graff-evals/README.md
@@ -161,10 +161,9 @@ python3 graff-evals/run.py --suite swe --task config-parse \
Use the identical command with the candidate binary, candidate arm, and a new
output directory. Match build optimization and effort across arms. Start with
-one case each for Astra, MiMo Pro, Claude, and Gemini to check transport and
-measurement completeness, then expand to all available aliases and six SWE
-fixtures. Availability failures remain failed/incomplete cells, never zero-cost
-wins. Interleave baseline/candidate repetitions to reduce cache/order bias.
+a fixed, explicitly selected model set to check transport and measurement
+completeness, then expand the task set while keeping those model routes fixed.
+Availability failures remain failed/incomplete cells, never zero-cost wins. Interleave baseline/candidate repetitions to reduce cache/order bias.
Receipts include binary SHA-256, evaluation-working-tree revision and patch
hash, untracked source hashes, task hash, requested provider/model, arm, wall
@@ -196,3 +195,20 @@ classmethod semantics, collection wrapping examples, and empty-Invalid
short-circuit checks. Its held-out checker independently verifies these and
remaining named contract behaviors. Compare both harness arms on the same task
version; do not pool v1 and v2 passes or rewrite earlier raw results.
+
+### Actual request capture
+
+Add `--capture-requests` to retain serialized request bodies in a private
+`requests/` directory beside the sandboxes. Each harness process uses a unique
+subdirectory. The receipt records body and rendered instruction/tool fingerprints;
+it does not contain the request text. Require `capture_evidence_ok` before using
+these fingerprints: empty, malformed, or gapped captures fail this check. Sequence
+order is per-process body construction, not global HTTP attempt order; transport
+retries can reuse a body. Capture is opt-in and identical in both
+arms; do not publish raw request files. Standalone harness diagnostics use
+`GRAFF_REQ_STATS=1` plus `GRAFF_REQ_DUMP_DIR`; statistics alone do not write files.
+
+A matching fingerprint establishes only matching request components. Prove cache
+reuse with returned cached-token usage. For warm-prefix comparisons, predetermine
+warmups, preserve their costs separately, alternate arm order, and retain every
+measured failure. Neither a warmup nor a stable cache key guarantees a hit.
diff --git a/graff-evals/request_capture.py b/graff-evals/request_capture.py
new file mode 100644
index 00000000..79f7642a
--- /dev/null
+++ b/graff-evals/request_capture.py
@@ -0,0 +1,77 @@
+"""Opt-in private body evidence; component fingerprints do not prove cache hits."""
+import hashlib
+import json
+import re
+from pathlib import Path
+
+
+def directory(sandbox):
+ path = Path(sandbox)
+ return path.parent.parent / 'requests' / path.name
+
+
+def configure(env, sandbox):
+ target = directory(sandbox)
+ target.parent.mkdir(mode=0o700, exist_ok=True)
+ target.mkdir(mode=0o700, exist_ok=False)
+ env.update(GRAFF_REQ_STATS='1', GRAFF_REQ_DUMP_DIR=str(target.resolve()))
+
+
+def digest(value):
+ return hashlib.sha256(json.dumps(value, ensure_ascii=False, separators=(',', ':')).encode()).hexdigest()
+
+
+def receipt(sandbox):
+ target = directory(sandbox)
+ rows = []
+ for path in target.rglob('body-*.json'):
+ match = re.fullmatch(r'body-([0-9]+)\.json', path.name)
+ sequence = int(match.group(1)) if match else None
+ row = {'file': str(path.relative_to(target)),
+ 'run_id': str(path.parent.relative_to(target)), 'sequence': sequence}
+ try:
+ if sequence is None or sequence < 1:
+ raise ValueError('capture filename must have a positive sequence')
+ raw = path.read_bytes()
+ row.update(body_bytes=len(raw), body_sha256=hashlib.sha256(raw).hexdigest())
+ body = json.loads(raw)
+ if not isinstance(body, dict):
+ raise ValueError('request body is not an object')
+ if 'instructions' in body:
+ instructions = body['instructions']
+ elif 'system' in body:
+ instructions = body['system']
+ else:
+ instructions = []
+ for message in body.get('messages', []):
+ if message.get('role') not in ('system', 'developer'):
+ break
+ instructions.append(message)
+ row.update(model=body.get('model'),
+ instructions_sha256=digest(instructions),
+ tools_sha256=digest(body.get('tools')),
+ prefix_components_sha256=digest([instructions, body.get('tools')]),
+ cache_key_sha256=digest(body['prompt_cache_key']) if 'prompt_cache_key' in body else None,
+ chained=bool(body.get('previous_response_id')))
+ except (OSError, ValueError, TypeError, AttributeError) as error:
+ row['capture_error'] = str(error)
+ rows.append(row)
+ # Sequence describes body construction within one process. Random run ids
+ # cannot order separate processes, and transport retries may reuse a body.
+ rows.sort(key=lambda r: (r['run_id'], r['sequence'] if r['sequence'] is not None else -1, r['file']))
+ issues = []
+ if not rows:
+ issues.append('no_captured_bodies')
+ if any('capture_error' in row for row in rows):
+ issues.append('unreadable_or_invalid_capture')
+ sequences = {}
+ for row in rows:
+ sequences.setdefault(row['run_id'], []).append(row['sequence'])
+ for run_id, seq in sequences.items():
+ if seq != list(range(1, len(seq) + 1)):
+ issues.append(f'noncontiguous_sequence:{run_id}')
+ return {'request_capture': {'enabled': True, 'count': len(rows),
+ 'valid_count': sum('capture_error' not in r for r in rows),
+ 'capture_evidence_ok': not issues, 'integrity_issues': issues,
+ 'order_scope': 'per_run_body_build', 'requests': rows,
+ 'meaning': 'nonempty parseable contiguous captured bodies, not completeness of HTTP attempts; component fingerprints do not prove cache reuse'}}
diff --git a/graff-evals/run.py b/graff-evals/run.py
index d80af6f7..3720900b 100755
--- a/graff-evals/run.py
+++ b/graff-evals/run.py
@@ -23,6 +23,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from list_price import attach as attach_list_price
import report as eval_report
import measurement
+import request_capture
ROOT = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(ROOT)
@@ -363,6 +364,8 @@ def one_run(hname, harness, task, model, rep, live=False):
for k, v in harness.get("env", {}).items()}})
if harness.get("_provider"):
env = measurement.provider_environment(harness["_provider"], sandbox, model=model)
+ if harness.get("_capture_requests"):
+ request_capture.configure(env, sandbox)
try:
p = subprocess.Popen(cmd, cwd=sandbox, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stdin=subprocess.PIPE if stdin_body is not None else None,
@@ -470,6 +473,8 @@ def one_run(hname, harness, task, model, rep, live=False):
"sandbox_bytes": dir_bytes(sandbox)}
rec.update({f"tok_{k}": v for k, v in usage.items()})
rec.update(measurement.receipt(cmd, harness, task))
+ if harness.get("_capture_requests"):
+ rec.update(request_capture.receipt(sandbox))
rec["verifiers_unchanged"] = verifiers_ok
if harness.get("_provider"):
rec.update(measurement.trace_routing(sandbox, harness["_provider"], model))
@@ -507,6 +512,7 @@ def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--harness", default="graff", help="comma-separated harness names (see harnesses.json)")
ap.add_argument("--output-root", help="new private directory for receipts and isolated sandboxes")
+ ap.add_argument("--capture-requests", action="store_true", help="save private wire evidence for cache analysis")
ap.add_argument("--binary", help="explicit graff executable for this arm")
ap.add_argument("--arm", default="baseline", help="comparison arm recorded in every result")
ap.add_argument("--provider", help="explicit graff provider; no automatic provider selection")
@@ -543,10 +549,10 @@ def main():
picked[tid] = t
work = []
for hname in args.harness.split(","):
- harness = dict(harnesses[hname], _arm=args.arm, _provider=args.provider, _receipt=code_receipt)
- if args.provider or args.binary:
+ harness = dict(harnesses[hname], _arm=args.arm, _provider=args.provider, _receipt=code_receipt, _capture_requests=args.capture_requests)
+ if args.provider or args.binary or args.capture_requests:
if not hname.startswith("graff"):
- ap.error("--provider/--binary require a graff harness")
+ ap.error("--provider/--binary/--capture-requests require a graff harness")
if args.provider and args.provider not in measurement.CREDENTIALS:
ap.error("--provider requires a supported credential route")
if args.provider and not os.environ.get(measurement.CREDENTIALS[args.provider]):
diff --git a/graff-evals/test_measurement.py b/graff-evals/test_measurement.py
index 2a555470..90d155ff 100644
--- a/graff-evals/test_measurement.py
+++ b/graff-evals/test_measurement.py
@@ -8,6 +8,7 @@ from unittest.mock import patch
import list_price
import measurement
+import request_capture
class MeasurementTests(unittest.TestCase):
@@ -109,6 +110,77 @@ class MeasurementTests(unittest.TestCase):
self.assertIn('new.zig', receipt['untracked_source_sha256'])
self.assertEqual(len(receipt['untracked_source_sha256']['new.zig']), 64)
+ def test_wire_captures_are_private_isolated_and_include_rendered_guidance(self):
+ with tempfile.TemporaryDirectory() as temp:
+ first = Path(temp) / 'sandboxes' / 'first'
+ second = Path(temp) / 'sandboxes' / 'second'
+ env = {'CODEGRAFF_API_KEY': 'fixture'}
+ request_capture.configure(env, first)
+ self.assertEqual(env['GRAFF_REQ_STATS'], '1')
+ self.assertEqual(Path(env['GRAFF_REQ_DUMP_DIR']).stat().st_mode & 0o777, 0o700)
+ request_capture.configure({}, second)
+ self.assertNotEqual(request_capture.directory(first), request_capture.directory(second))
+ run = request_capture.directory(first) / 'run-fixture'
+ run.mkdir()
+ body = {'model': 'fixture', 'instructions': 'base + rendered guidance', 'tools': [],
+ 'input': [{'role': 'user', 'content': 'first task'}], 'prompt_cache_key': 'lane'}
+ (run / 'body-001.json').write_text(json.dumps(body))
+ body['input'][0]['content'] = 'different task'
+ (run / 'body-002.json').write_text(json.dumps(body))
+ body['instructions'] = 'base + different rendered guidance'
+ (run / 'body-003.json').write_text(json.dumps(body))
+ receipt = request_capture.receipt(first)['request_capture']
+ self.assertEqual(receipt['count'], 3)
+ a, b, c = receipt['requests']
+ self.assertEqual(a['prefix_components_sha256'], b['prefix_components_sha256'])
+ self.assertNotEqual(a['body_sha256'], b['body_sha256'])
+ self.assertNotEqual(b['prefix_components_sha256'], c['prefix_components_sha256'])
+ self.assertEqual(request_capture.receipt(second)['request_capture']['count'], 0)
+ self.assertNotIn('rendered guidance', json.dumps(receipt))
+ (run / 'body-004.json').write_text('broken')
+ self.assertIn('capture_error', request_capture.receipt(first)['request_capture']['requests'][-1])
+
+ def test_capture_evidence_requires_nonempty_parseable_contiguous_bodies(self):
+ with tempfile.TemporaryDirectory() as temp:
+ sandbox = Path(temp) / 'sandboxes' / 'case'
+ request_capture.configure({}, sandbox)
+ current = lambda: request_capture.receipt(sandbox)['request_capture']
+ self.assertFalse(current()['capture_evidence_ok'])
+ run = request_capture.directory(sandbox) / 'run-fixture'
+ run.mkdir()
+ (run / 'body-001.json').write_text('{"model":"fixture"}')
+ self.assertTrue(current()['capture_evidence_ok'])
+ (run / 'body-003.json').write_text('{"model":"fixture"}')
+ self.assertFalse(current()['capture_evidence_ok'])
+ (run / 'body-002.json').write_text('broken')
+ self.assertFalse(current()['capture_evidence_ok'])
+ self.assertEqual(current()['valid_count'], 2)
+ (run / 'body-002.json').write_text('{"model":"fixture"}')
+ self.assertTrue(current()['capture_evidence_ok'])
+ (run / 'body-000.json').write_text('{}')
+ self.assertFalse(current()['capture_evidence_ok'])
+
+ def test_capture_order_is_numeric_with_independent_run_sequences(self):
+ with tempfile.TemporaryDirectory() as temp:
+ sandbox = Path(temp) / 'sandboxes' / 'case'
+ request_capture.configure({}, sandbox)
+ root = request_capture.directory(sandbox)
+ for name, count in [('run-z', 1001), ('run-a', 2)]:
+ run = root / name
+ run.mkdir()
+ for number in reversed(range(1, count + 1)):
+ (run / f'body-{number:03d}.json').write_text('{"model":"fixture"}')
+ captured = request_capture.receipt(sandbox)['request_capture']
+ self.assertTrue(captured['capture_evidence_ok'])
+ self.assertEqual(captured['order_scope'], 'per_run_body_build')
+ self.assertEqual(captured['count'], 1003)
+ for name, count in [('run-z', 1001), ('run-a', 2)]:
+ rows = [r for r in captured['requests'] if r['run_id'] == name]
+ self.assertEqual([r['sequence'] for r in rows], list(range(1, count + 1)))
+ (root / 'run-a' / 'body-002.json').unlink()
+ (root / 'run-a' / 'body-004.json').write_text('{}')
+ self.assertFalse(request_capture.receipt(sandbox)['request_capture']['capture_evidence_ok'])
+
def test_isolation_refuses_reusing_or_overwriting_a_run(self):
with tempfile.TemporaryDirectory() as temp:
target = str(Path(temp) / 'run')
diff --git a/scripts/eval-tier2.py b/scripts/eval-tier2.py
index 7364dba0..feec90c9 100644
--- a/scripts/eval-tier2.py
+++ b/scripts/eval-tier2.py
@@ -31,6 +31,8 @@ Assertions a case can make:
{"events_at_most": {"match": {...}, "count": N}}
{"request_contains": {"index": -1, "text": "..."}} what the harness sent
{"request_lacks": {"index": -1, "text": "..."}}
+ {"request_count": N} exact captured wire count (scripted only)
+ {"stdout_equals": "..."} exact raw stdout, including newlines
{"final_text_contains": "..."}
{"file_equals": {"path": "relative/file", "content": "exact bytes"}}
{"stderr_contains": "..."} what the harness printed to stderr
@@ -102,10 +104,11 @@ class Run:
"""One harness run: the events it emitted and the requests it sent."""
def __init__(self, events: list[dict[str, Any]], requests: list[dict[str, Any]],
- stderr: str, exit_code: int | None, files=None, verification=None) -> None:
+ stderr: str, exit_code: int | None, files=None, verification=None, stdout="") -> None:
self.events = events
self.requests = requests
self.stderr = stderr
+ self.stdout = stdout
self.exit_code = exit_code
self.files = files or {}
self.verification = verification
@@ -256,13 +259,13 @@ def execute(case: dict[str, Any], graff: str, port: int,
destination.mkdir(parents=True, exist_ok=True, mode=0o700)
(destination / "result.json").write_text(json.dumps(dict(
events=events, requests=list(scripted.requests), files=files,
- verification=verification, exit_code=code), indent=2))
+ verification=verification, exit_code=code, stdout=stdout), indent=2))
(destination / "stderr.log").write_text(stderr)
for folder in ("traces", "trajectories", "sessions"):
source = pathlib.Path(workspace) / ".graff" / folder
if source.exists():
shutil.copytree(source, destination / folder, dirs_exist_ok=True)
- return Run(events, list(scripted.requests), stderr, code, files, verification)
+ return Run(events, list(scripted.requests), stderr, code, files, verification, stdout)
finally:
if peer is not None:
peer.kill()
@@ -322,6 +325,12 @@ def evaluate(case: dict[str, Any], run: Run, live: bool = False) -> list[str]:
if kind == "request_lacks" and present:
failures.append(
f"request[{spec.get('index', -1)}] mentioned {spec['text']!r} and should not have")
+ elif kind == "request_count":
+ if not live and len(run.requests) != spec:
+ failures.append(f"captured {len(run.requests)} requests, wanted exactly {spec}")
+ elif kind == "stdout_equals":
+ if run.stdout != spec:
+ failures.append(f"stdout was {run.stdout!r}, wanted exactly {spec!r}")
elif kind == "final_text_contains":
if spec not in run.final_text():
failures.append(f"the final answer was {run.final_text()!r}, wanted {spec!r}")
@@ -388,7 +397,7 @@ def main() -> None:
if args.dump:
print(json.dumps({"events": run.events, "requests": run.requests,
"exit_code": run.exit_code, "stderr": run.stderr[-2000:],
- "files": run.files, "verification": run.verification},
+ "files": run.files, "verification": run.verification, "stdout": run.stdout},
indent=2))
return
problems = evaluate(case, run, live=bool(args.provider))
diff --git a/scripts/eval/test_tier2_outcomes.py b/scripts/eval/test_tier2_outcomes.py
index 57e322ec..39950c8f 100644
--- a/scripts/eval/test_tier2_outcomes.py
+++ b/scripts/eval/test_tier2_outcomes.py
@@ -45,6 +45,21 @@ class OutcomeIntegrity(unittest.TestCase):
run.requests[0]['messages'].append({'role': 'assistant', 'tool_calls': [{'function': {'name': 'edit_file'}}]})
self.assertTrue(tier2.evaluate(case, run))
+ def test_oneshot_assertions_require_actual_wire_count_and_exact_stdout(self):
+ case = {'assert': [{'request_count': 1}, {'stdout_equals': 'pong\n'}]}
+ run = tier2.Run([], [{}], '', 0, stdout='pong\n')
+ self.assertEqual([], tier2.evaluate(case, run))
+ for count in (0, 2):
+ run.requests = [{}] * count
+ self.assertTrue(tier2.evaluate(case, run))
+ run.requests = [{}]
+ for output in ('', 'pong', 'pong\nextra\n'):
+ run.stdout = output
+ self.assertTrue(tier2.evaluate(case, run))
+ run.stdout = 'pong\n'
+ run.requests = []
+ self.assertEqual([], tier2.evaluate(case, run, live=True))
+
if __name__ == '__main__':
unittest.main()
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index e8e37759..2492a0ad 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -15,7 +15,7 @@
"src/repl.zig",
"TUI/root.zig"
],
- "test_count_baseline": 2670,
+ "test_count_baseline": 2674,
"test_count_slack": 25,
"required_invariants": [
{
diff --git a/src/agent_empty_completion.zig b/src/agent_empty_completion.zig
index 2ad620e5..3bf36c27 100644
--- a/src/agent_empty_completion.zig
+++ b/src/agent_empty_completion.zig
@@ -102,6 +102,7 @@ pub fn handle(self: *Agent, final_text: []const u8, hist_len: usize) !bool {
return true;
}
if (@import("task_intent.zig").current(self) == .informational) return false;
+ if (@import("exact_reply.zig").requested(messages.latestUserText(self.messages.items))) return false;
if (no_local_tools.enabled) return false;
if (!shouldBounce(main_mod.unattended, no_local_tools.lean, self.text_only, self.review_mode, self.sub, self.tool_calls_this_turn, self.model_calls_this_turn, final_text))
return false;
@@ -332,3 +333,40 @@ test "no-local-tools lean critique is not an edit-oriented fake_done retry" {
try std.testing.expect(!try handle(&self, "The design is coherent and needs no local changes.", before));
try std.testing.expectEqual(before, self.messages.items.len);
}
+
+test "exact reply bypasses only fake done while mixed requests and empty replies still retry" {
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ const old_unattended = main_mod.unattended;
+ const old_lean = no_local_tools.lean;
+ const old_enabled = no_local_tools.enabled;
+ main_mod.unattended = true;
+ no_local_tools.lean = true;
+ no_local_tools.enabled = false;
+ defer {
+ main_mod.unattended = old_unattended;
+ no_local_tools.lean = old_lean;
+ no_local_tools.enabled = old_enabled;
+ }
+ const cases = .{
+ .{ "Reply with exactly: pong", "pong", false },
+ .{ "Reply with exactly: \"run tests and deploy\"", "run tests and deploy", false },
+ .{ "Reply with exactly: \"pong\"; then edit target.txt", "pong", true },
+ .{ "Reply with exactly: pong", " ", true },
+ };
+ inline for (cases) |case| {
+ var self = pendingFixture(state.allocator());
+ self.empty_completion_retries = 0;
+ self.codex_ws = null;
+ self.codex_prev_id = null;
+ self.call_kind = .title; // suppress fixture notices without initializing a writer
+ self.tool_calls_this_turn = 0;
+ self.model_calls_this_turn = 1;
+ try self.messages.append(try messages.textMessage(self.arena, "user", case[0]));
+ const before = self.messages.items.len;
+ try std.testing.expectEqual(case[2], try handle(&self, case[1], before));
+ const empty = std.mem.trim(u8, case[1], " \t\r\n").len == 0;
+ try std.testing.expectEqual(@as(usize, if (case[2] and !empty) before + 1 else before), self.messages.items.len);
+ try std.testing.expectEqual(@as(u8, if (empty) 1 else 0), self.empty_completion_retries);
+ }
+}
diff --git a/src/exact_reply.zig b/src/exact_reply.zig
new file mode 100644
index 00000000..42f17657
--- /dev/null
+++ b/src/exact_reply.zig
@@ -0,0 +1,59 @@
+//! Narrow fake-done exemption for a fully specified textual reply.
+//! This does not classify task intent or change any tool/goal/verification gate.
+const std = @import("std");
+
+pub fn requested(text: []const u8) bool {
+ var request = std.mem.trim(u8, text, " \t\r\n");
+ const polite = "please ";
+ if (request.len >= polite.len and std.ascii.eqlIgnoreCase(request[0..polite.len], polite))
+ request = std.mem.trimStart(u8, request[polite.len..], " \t");
+ for ([_][]const u8{ "reply with exactly:", "respond with exactly:", "answer with exactly:" }) |prefix| {
+ if (request.len < prefix.len or !std.ascii.eqlIgnoreCase(request[0..prefix.len], prefix)) continue;
+ return literal(std.mem.trim(u8, request[prefix.len..], " \t"));
+ }
+ return false;
+}
+
+fn literal(payload: []const u8) bool {
+ if (payload.len == 0 or !std.unicode.utf8ValidateSlice(payload)) return false;
+ if (payload[0] == '"' or payload[0] == '\'') {
+ const quote = payload[0];
+ var escaped = false;
+ for (payload[1..], 1..) |c, i| {
+ if (c == '\n' or c == '\r') return false;
+ if (escaped) {
+ escaped = false;
+ } else if (c == '\\') {
+ escaped = true;
+ } else if (c == quote) {
+ return i > 1 and i == payload.len - 1;
+ }
+ }
+ return false;
+ }
+ // Unquoted multiword or clause-like payloads remain ambiguous. Quoting
+ // makes action words data without exempting a following coding request.
+ for (payload) |c| if (std.ascii.isWhitespace(c) or std.mem.indexOfScalar(u8, "\"'`;|&\\:()[]{}", c) != null) return false;
+ return true;
+}
+
+test "exact reply accepts complete literals without interpreting their words as actions" {
+ for ([_][]const u8{
+ "Reply with exactly: pong", " Please RESPOND with exactly: pong ",
+ "Answer with exactly: \"run tests and deploy\"", "Reply with exactly: 'fix parser.py'",
+ "Reply with exactly: \"say \\\"run\\\"\"", "Reply with exactly: delete",
+ }) |text| try std.testing.expect(requested(text));
+}
+
+test "exact reply rejects mixed instructions and ambiguous or malformed payloads" {
+ for ([_][]const u8{
+ "Fix parser.py. Reply with exactly: pong", "Reply with exactly: pong then run tests",
+ "Reply with exactly: \"pong\"; then edit parser.py", "Reply with exactly: 'pong' and commit",
+ "Reply with exactly: pong\nRun tests", "Reply with exactly: \"unterminated",
+ "Reply with exactly: \"\"", "Reply with exactly:",
+ "Reply with exactly: run tests", "Reply with exactly: pong;deploy",
+ "Reply with exactly: \"pong\" trailing", "Translate to French: \"fix the parser\"",
+ "Answer this question", "hello",
+ "",
+ }) |text| try std.testing.expect(!requested(text));
+}
diff --git a/src/main.zig b/src/main.zig
index a333ae1e..1a797337 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -584,7 +584,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = .{ @import("acp_protocol.zig"), @import("subagent_mimo_tests.zig"), @import("gateway_picker_catalog.zig") };
_ = @import("task_outcome.zig"); // goal-outcome telemetry events
_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here
- _ = @import("additional_tests.zig");
+ _ = .{ @import("additional_tests.zig"), @import("req_stats.zig"), @import("exact_reply.zig") };
_ = @import("goal_pacing_autonomous_test.zig");
_ = @import("goal_state.zig");
_ = @import("goal_persist_tests.zig");
diff --git a/src/req_stats.zig b/src/req_stats.zig
index a9488fda..482beb58 100644
--- a/src/req_stats.zig
+++ b/src/req_stats.zig
@@ -1,5 +1,6 @@
//! GRAFF_REQ_STATS=1 request anatomy (the token-diet program's measurement
-//! hook): per-call body/tools/system byte split, a per-call body dump for
+//! hook): per-call body/tools/system byte split. GRAFF_REQ_DUMP_DIR opts into
+//! private per-run body and system dumps for
//! byte-diffing consecutive requests (cache-prefix forensics), a one-time
//! system-prompt dump for offline segment attribution (#476), and the
//! per-server tools split with the top-5 native specs. All output is stderr,
@@ -11,26 +12,64 @@ const Io = std.Io;
/// Set once at startup by session_settings.applyEnvKnobs (GRAFF_REQ_STATS).
pub var g_armed = false;
+pub var g_dump_dir: ?[]const u8 = null;
+var dump_state: Dump = .{};
+
+/// Startup-only: configuration owns no handles and uses the session arena.
+pub fn configure(arena: std.mem.Allocator, armed: bool, directory: ?[]const u8) !void {
+ const path = if (directory) |d| std.mem.trim(u8, d, " \t\r\n") else "";
+ const owned = if (path.len == 0) null else try arena.dupe(u8, path);
+ g_armed = armed;
+ g_dump_dir = owned;
+ dump_state = .{};
+}
+
+const Dump = struct {
+ mutex: Io.Mutex = .init,
+ path: [std.fs.max_path_bytes]u8 = undefined,
+ path_len: usize = 0,
+ seq: usize = 0,
+ system_written: bool = false,
+
+ fn write(self: *Dump, io: Io, root: []const u8, body: []const u8, system: []const u8) !void {
+ const private = @import("credential_store.zig");
+ if (self.path_len == 0) {
+ _ = try Io.Dir.cwd().createDirPathStatus(io, root, private.private_dir);
+ var nonce: [16]u8 = undefined;
+ io.random(&nonce);
+ const hex = std.fmt.bytesToHex(nonce, .lower);
+ const path = try std.fmt.bufPrint(&self.path, "{s}/run-{s}", .{ root, hex });
+ try Io.Dir.cwd().createDir(io, path, private.private_dir);
+ self.path_len = path.len;
+ std.debug.print(" [req] dump_dir={s}\n", .{path});
+ }
+ var dir = try Io.Dir.cwd().openDir(io, self.path[0..self.path_len], .{});
+ defer dir.close(io);
+ self.seq += 1;
+ var name: [64]u8 = undefined;
+ try writePrivate(io, dir, try std.fmt.bufPrint(&name, "body-{d:0>3}.json", .{self.seq}), body);
+ if (!self.system_written) {
+ try writePrivate(io, dir, "system.txt", system);
+ self.system_written = true;
+ }
+ }
+
+ fn writePrivate(io: Io, dir: Io.Dir, name: []const u8, bytes: []const u8) !void {
+ const file = try dir.createFile(io, name, .{ .exclusive = true, .permissions = @import("credential_store.zig").private_file });
+ defer file.close(io);
+ try file.writePositionalAll(io, bytes, 0);
+ }
+};
pub fn report(io: Io, body: []const u8, tools: ?[]const u8, sys_normal: []const u8) void {
if (!g_armed) return;
std.debug.print(" [req] body={d}B tools={d}B system={d}B messages~={d}B\n", .{ body.len, if (tools) |t| t.len else 0, sys_normal.len, body.len -| (if (tools) |t| t.len else 0) -| sys_normal.len });
- // Per-call body dump, for byte-diffing consecutive requests.
- const dump_seq = struct {
- var n: usize = 0;
- };
- dump_seq.n += 1;
- var dpath: [64]u8 = undefined;
- if (std.fmt.bufPrint(&dpath, "/tmp/graff-body-{d:0>3}.json", .{dump_seq.n})) |p| {
- Io.Dir.cwd().writeFile(io, .{ .sub_path = p, .data = body }) catch {};
- } else |_| {}
- // One dump per process: the assembled system prompt.
- const dumped = struct {
- var done: bool = false;
- };
- if (!dumped.done and sys_normal.len > 10_000) {
- dumped.done = true;
- Io.Dir.cwd().writeFile(io, .{ .sub_path = "/tmp/graff-sys.txt", .data = sys_normal }) catch {};
+ if (g_dump_dir) |root| {
+ dump_state.mutex.lockUncancelable(io);
+ defer dump_state.mutex.unlock(io);
+ dump_state.write(io, root, body, sys_normal) catch |err| {
+ std.debug.print(" [req] dump failed: {s}\n", .{@errorName(err)});
+ };
}
// Per-server split: attribute each tool's serialized span by its name
// prefix (next-"name" boundary ≈ tool size, ±separators).
@@ -75,3 +114,57 @@ pub fn report(io: Io, body: []const u8, tools: ?[]const u8, sys_normal: []const
}
}
}
+
+test "request dumps isolate configured runs and preserve emitted JSON privately" {
+ const a = std.testing.allocator;
+ const io = std.testing.io;
+ const saved_armed = g_armed;
+ const saved_dir = g_dump_dir;
+ const saved_state = dump_state;
+ defer {
+ g_armed = saved_armed;
+ g_dump_dir = saved_dir;
+ dump_state = saved_state;
+ }
+ var arena_state = std.heap.ArenaAllocator.init(a);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var temp = std.testing.tmpDir(.{});
+ defer temp.cleanup();
+ var root_buffer: [std.fs.max_path_bytes]u8 = undefined;
+ const root = root_buffer[0..try temp.dir.realPath(io, &root_buffer)];
+ var agent = try @import("agent_request_body_responses.zig").testAgentFor(arena, "codegraff", .openai, "mimo-v2.5");
+ const body = try agent.buildBody(null, false, true, true);
+ defer a.free(body);
+ var paths: [3][]const u8 = undefined;
+ for (0..3) |i| {
+ // The third invocation deliberately reuses the first output root.
+ const destination = try std.fmt.allocPrint(arena, "{s}/output-{d}", .{ root, i % 2 });
+ try configure(arena, true, destination);
+ report(io, body, null, agent.sys_normal);
+ paths[i] = try arena.dupe(u8, dump_state.path[0..dump_state.path_len]);
+ var dir = try Io.Dir.cwd().openDir(io, paths[i], .{});
+ defer dir.close(io);
+ const bytes = try dir.readFileAlloc(io, "body-001.json", arena, .limited(1024 * 1024));
+ try std.testing.expectEqualStrings(body, bytes);
+ const parsed = try std.json.parseFromSliceLeaky(std.json.Value, arena, bytes, .{});
+ try std.testing.expectEqualStrings(agent.provider.model, parsed.object.get("model").?.string);
+ const system = try dir.readFileAlloc(io, "system.txt", arena, .limited(1024 * 1024));
+ try std.testing.expectEqualStrings(agent.sys_normal, system);
+ if (@import("builtin").os.tag != .windows) {
+ try std.testing.expectEqual(@as(u32, 0o700), (try dir.stat(io)).permissions.toMode() & 0o777);
+ try std.testing.expectEqual(@as(u32, 0o600), (try dir.statFile(io, "body-001.json", .{})).permissions.toMode() & 0o777);
+ try std.testing.expectEqual(@as(u32, 0o600), (try dir.statFile(io, "system.txt", .{})).permissions.toMode() & 0o777);
+ }
+ }
+ try std.testing.expect(!std.mem.eql(u8, paths[0], paths[2]));
+ for (paths) |path| {
+ const file = try std.fmt.allocPrint(arena, "{s}/body-001.json", .{path});
+ try std.testing.expectEqualStrings(body, try Io.Dir.cwd().readFileAlloc(io, file, arena, .limited(1024 * 1024)));
+ }
+ // Statistics alone must not create an implicit shared dump destination.
+ try configure(arena, true, null);
+ report(io, body, null, agent.sys_normal);
+ try std.testing.expectEqual(@as(usize, 0), dump_state.path_len);
+ try std.testing.expectEqual(@as(usize, 0), dump_state.seq);
+}
diff --git a/src/session_settings.zig b/src/session_settings.zig
index c94b14f1..3f07bde0 100644
--- a/src/session_settings.zig
+++ b/src/session_settings.zig
@@ -149,7 +149,7 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {
// (the MCP half of the same switch) — a "0" still means lean, by design.
if (environ_map.get("GRAFF_LEAN") != null) no_local_tools.lean = true;
// GRAFF_REQ_STATS: presence-based request-anatomy print (req_stats).
- @import("req_stats.zig").g_armed = environ_map.get("GRAFF_REQ_STATS") != null;
+ try @import("req_stats.zig").configure(arena, environ_map.get("GRAFF_REQ_STATS") != null, environ_map.get("GRAFF_REQ_DUMP_DIR"));
// GRAFF_CODEX_FULL_RESEND: presence-based — never chain previous_response_id
// (codex_chain); the opencode-shape experiment for cache-hit measurement.
if (environ_map.get("GRAFF_CODEX_FULL_RESEND") != null) @import("codex_chain.zig").g_force_full_resend = true;
diff --git a/src/session_settings_tests.zig b/src/session_settings_tests.zig
index ae1286f7..df933ab5 100644
--- a/src/session_settings_tests.zig
+++ b/src/session_settings_tests.zig
@@ -33,6 +33,8 @@ const Knob = struct { name: []const u8, value: []const u8 };
/// adding it here is fine (this list is a floor, not a ceiling); REMOVING the
/// parse while the knob is still documented is what this catches.
const knobs = [_]Knob{
+ .{ .name = "GRAFF_REQ_STATS", .value = "1" },
+ .{ .name = "GRAFF_REQ_DUMP_DIR", .value = "/tmp/unused-request-dump-knob" },
.{ .name = "GRAFF_NO_CODEDB_GUARD", .value = "1" },
.{ .name = "GRAFF_FORCE_STALL_ONCE", .value = "1" },
.{ .name = "GRAFF_FORCE_DROP_ONCE", .value = "1" },
@@ -86,6 +88,8 @@ const RecordingEnv = struct {
/// runs next — the exact failure mode that made #391's note store segfault
/// three unrelated tests during the same integration.
const Saved = struct {
+ req_armed: bool,
+ req_dump_dir: ?[]const u8,
codedb_guard: bool,
stall_once: bool,
drop_once: bool,
@@ -116,6 +120,8 @@ const Saved = struct {
fn capture() Saved {
return .{
+ .req_armed = @import("req_stats.zig").g_armed,
+ .req_dump_dir = @import("req_stats.zig").g_dump_dir,
.codedb_guard = main_mod.g_codedb_guard,
.stall_once = main_mod.g_force_stall_once,
.drop_once = main_mod.g_force_drop_once,
@@ -147,6 +153,8 @@ const Saved = struct {
}
fn restore(s: Saved) void {
+ @import("req_stats.zig").g_armed = s.req_armed;
+ @import("req_stats.zig").g_dump_dir = s.req_dump_dir;
main_mod.g_codedb_guard = s.codedb_guard;
main_mod.g_force_stall_once = s.stall_once;
main_mod.g_force_drop_once = s.drop_once;