graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: pin-budget degrade once per turn; speed up eval-tier1
Cursor Agent65d713429b51
diff --git a/AGENTS.md b/AGENTS.mdindex 27d1f0d5..289eb225 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -77,6 +77,7 @@ That points `core.hooksPath` at `.githooks/`, whose `pre-push` runs **tier 1** o```bashscripts/eval-tier1.sh # run it by handscripts/eval-tier1.sh --only sdk # rerun one check+scripts/eval-tier1.sh --only tui,tuiguard # a comma-separated list (#641)scripts/eval-tier1.sh --list # the check namesgit push --no-verify # emergency skip (GRAFF_SKIP_PREPUSH=1 also works)```diff --git a/docs/releases/v0.0.279.md b/docs/releases/v0.0.279.mdindex 29ca735e..339180ca 100644--- a/docs/releases/v0.0.279.md+++ b/docs/releases/v0.0.279.md@@ -64,8 +64,24 @@ Any `bash_output` / `agent_output` `wait_ms>0` waits for exit (10h).A model that passes a mid-range "safety timeout" (60s–240s) no longergets `[job N: running]` back mid-job and a second billed hop.+## Compaction pin budget (#581)++The live unresolved prompt (and its images) stays pinned. If that+pinned suffix alone is already over the 8k keep budget, compaction+announces once and then stays quiet for the rest of the turn instead+of reprinting `[compaction skipped…]` every cycle. Server-side blob+prune / explicit compact refuse a cut that would drop that pin.++## Tier-1 wall (#641)++`eval-tier1.sh` runs the 17 tuiguard PTY probes in a 4–8 process+pool, counts the suite and the named invariants by scanning the+unfiltered test artifact (no filtered recompiles, no second suite+execution on a zig cache hit), and accepts `--only tui,tuiguard`.+## TestsUnit suite grows by the ACP translator cases (`kindFor`, thought/text-chunks, minted tool ids, EventSink) plus the #638 picker/retire and-#640 deadline cases. Floor stays **1683** from the 278 ratchet (slack 25).+chunks, minted tool ids, EventSink) plus the #638 picker/retire,+#640 deadline, and #581 pin-budget cases. Floor stays **1683** from+the 278 ratchet (slack 25).diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex 6efb1fde..44ef7f50 100755--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -1,8 +1,9 @@#!/usr/bin/env bash# Tier 1 of the internal eval set: every check here is deterministic, offline,# and free. No provider calls, no network, no model in the loop. This is what-# the pre-push hook runs, so it has to stay honest and it has to stay fast-# (~30s warm on an M-series laptop).+# the pre-push hook runs, so it has to stay honest and it has to stay fast:+# a warm fmt/reach/sdk subset is seconds; a post-src run rebuilds zig and+# the PTY pool (minutes, see #641).## Tier 2 is the model-backed behavioral eval set (scripts/eval-tier2.py). It is# deliberately NOT in the hook: it spends turns and it is slower.@@ -10,6 +11,7 @@# scripts/eval-tier1.sh run every check# scripts/eval-tier1.sh --list show the check names# scripts/eval-tier1.sh --only sdk run one check+# scripts/eval-tier1.sh --only tui,tuiguard run a comma-separated list (#641)#set -uo pipefail@@ -29,7 +31,7 @@ CHECKS=(fmt lines spec reach build tests tui tuiguard invariants sdk)usage() {cat <<'EOF'-usage: scripts/eval-tier1.sh [--only <check>] [--list]+usage: scripts/eval-tier1.sh [--only <check[,check...]>] [--list]checks, in order:fmt zig fmt --check src build.zig@@ -46,27 +48,43 @@ checks, in order:EOF}-only=""+onlys=()while (($#)); docase "$1" in--list) printf '%s\n' "${CHECKS[@]}"; exit 0 ;;- --only) only=${2:-}; shift 2 || true ;;- --only=*) only=${1#--only=}; shift ;;+ --only)+ IFS=',' read -ra _parts <<< "${2:-}"+ onlys+=("${_parts[@]}")+ shift 2 || true+ ;;+ --only=*)+ IFS=',' read -ra _parts <<< "${1#--only=}"+ onlys+=("${_parts[@]}")+ shift+ ;;-h|--help) usage; exit 0 ;;*) printf 'eval-tier1: unknown argument %s\n\n' "$1" >&2; usage >&2; exit 2 ;;esacdone-if [[ -n "$only" ]]; then- found=0- for name in "${CHECKS[@]}"; do [[ $name == "$only" ]] && found=1; done- if ((!found)); then- printf 'eval-tier1: no check named %s (try --list)\n' "$only" >&2- exit 2- fi+if ((${#onlys[@]} > 0)); then+ for only in "${onlys[@]}"; do+ [[ -n "$only" ]] || continue+ found=0+ for name in "${CHECKS[@]}"; do [[ $name == "$only" ]] && found=1; done+ if ((!found)); then+ printf 'eval-tier1: no check named %s (try --list)\n' "$only" >&2+ exit 2+ fi+ donefi-wanted() { [[ -z "$only" || "$only" == "$1" ]]; }+wanted() {+ if ((${#onlys[@]} == 0)); then return 0; fi+ local c=$1+ for only in "${onlys[@]}"; do [[ $only == "$c" ]] && return 0; done+ return 1+}failed=()warned=()@@ -184,8 +202,8 @@ if wanted tests; thenelsecount=$(suite_count "$out")if [[ -z "$count" ]]; then- printf ' the cached build printed no test summary; counting from the compiled artifact\n'- count=$(artifact_count)+ printf ' cached build; scanning the compiled artifact for the suite count\n'+ count=$(python3 scripts/eval/tier1_test_binary.py scan)fiif [[ -z "$count" ]]; thenprintf ' FAIL could not read the test count from the build summary or the test artifact\n'@@ -223,136 +241,10 @@ if wanted tuiguard; thenif ((!build_ok)); thenskip_dependent tuiguardelse- announce tuiguard "tui-pty-guard.py — mode-balance / hostile-input / kill-restore on the real binary"- # grok-build's discipline as a gate: every latched DEC mode is reset on- # every exit path, the historical crasher corpus cannot kill a session,- # and SIGTERM never strands a raw terminal. Skips itself without a pty.- if python3 scripts/tui-pty-guard.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # #529: the drag gesture the mouse-tracking modes above swallow. Paints an- # inverse band and lands on the real clipboard (restored afterwards);- # skips itself off macOS, where there is no pbcopy/pbpaste.- if python3 scripts/test-tui-selection.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # #551: the TUI renders tool activity from the engine's TYPED events. Drives- # a real tool loop against the codex mock (no network, no model) and reads- # the screen back: one folded summary, a field-backed card under it, and an- # answer line that starts with "✓ " staying an answer.- if python3 scripts/test-tui-typed-events.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # The frame painter may never show anything but the current frame. Storms- # the window size, fills the screen with glyphs terminals measure- # differently from us, then reads the SCREEN back and compares it cell for- # cell against a forced full repaint of the same frame.- if python3 scripts/test-tui-painter.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # Scrolling is a viewport SLICE of one cached layout, not a re-layout- # (TUI/layout_cache.zig). Reads the screen back on every scroll step and- # after every width change: the markers on screen must be a contiguous- # ascending run, which a stale block or a mis-offset slice cannot fake.- if python3 scripts/test-tui-layout-cache.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # The viewport must not jump when the terminal changes width: drives- # TIOCSWINSZ across five widths mid-scroll and reads the screen back. With- # the logical scroll anchor removed the marker leaves the screen on the- # FIRST width change, so this is a real gate, not a smoke test.- if python3 scripts/test-tui-resize-anchor.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # grok-build's one-column rule for ANIMATED chrome: watches the live blink- # on a background op's pending row and fails if the label beside it moves a- # column, or if a frame is not East-Asian-Narrow. TUI/glyphs.zig holds the- # same law for the frame sets; this is the pixels.- if python3 scripts/test-tui-chrome-width.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # A wheel notch must be a scroll region + SU, not a screen rewrite — and a- # storm of them must still leave the screen equal to a forced full repaint.- # With the hint refused the probe fails on the FIRST notch (verified), so- # this is a gate on both halves, not a smoke test.- if python3 scripts/test-tui-scroll-paint.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # Trackpad momentum must be COALESCED and BUDGETED, not queued. Drives 500- # SGR wheel reports twice — all at once, then spread over ~1s the way- # momentum really arrives — and reads the loop's own paint counters back.- # With the frame budget removed the paced storm paints 503 times instead of- # ~105, so this is a real gate, not a smoke test.- if python3 scripts/test-tui-event-pacing.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # Same invariants, read off a VIRTUAL SCREEN instead of raw bytes- # (scripts/ptyharness.py): the VT interpreter's own selftest, the ported- # mode-balance check, and out-of-band screen corruption fed straight to the- # tty.- if python3 scripts/test-tui-screenstate.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # A tool run's fold header reads like grok-build's: present-progressive- # while the call is in flight, past tense on settle, tinted for a second.- # Drives a real `sleep` tool loop against the codex mock and reads the- # header row's TEXT and its cell BACKGROUNDS off a virtual screen. Both- # halves fail on their own when either is removed (verified).- if python3 scripts/test-tui-fold-headers.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # Streaming markdown: the answer arrives as 1-3 codepoint deltas whose- # boundaries land mid-escape, mid-fence and mid-marker. Both the live tail- # and the settled row must be free of the model's own CR/SGR bytes.- if python3 scripts/test-tui-stream-markdown.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # A clickable row has to LOOK clickable. Runs a real tool loop against the- # codex mock, then reads CELLS off a virtual screen: the hovered summary- # takes the theme's hover background and its ◆ becomes ›, its neighbour is- # untouched, leaving restores it, a single click still expands, and a- # double click is one net toggle. With the post-pass refused the probe- # fails on the tint (verified), so this is a gate on both halves.- if python3 scripts/test-tui-hover.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # A single click has to DO something. Drives real SGR press/release bytes- # through the same virtual screen: a motionless click paints no selection- # band and copies nothing (while the same press WITH motion does), a press- # on the scroll gutter seeks and a held one drags the viewport without ever- # anchoring a band, an overlay row selects and then confirms, the backdrop- # dismisses, and the highlighted completion row runs. Each of the five is a- # verified gate: disabling the gutter, the drag branch, the overlay press,- # the slash press, or making a press anchor a band each fails a different- # check.- if python3 scripts/test-tui-click.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # The scroll gutter has to land on a CELL and then leave no trace, and the- # OSC 52 copy has to leave the process — neither is visible to a unit test.- # Reads the thumb off the last column of the virtual screen, compares that- # column against a forced full repaint once it fades, and matches the- # base64 on the wire against the rows the drag covered. Each of the three- # is a verified gate: removing the fade rule, the fade EXPIRY, or the tty- # write each fails a different check.- if python3 scripts/test-tui-scrollbar-osc52.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # Every overlay is a bordered panel with its name in the top rule, docked to- # the composer, opened at its FIRST row; and the composer no longer claims a- # clipboard image on every idle frame. Border cells and the gap between the- # panel and the input box are geometry a unit test cannot see. Each of the- # four checks is verified: unframing the panel, undocking it, opening a- # sheet at its tail, or restoring the clipboard row each fails its own.- if python3 scripts/test-tui-overlay-panels.py zig-out/bin/graff; then :; else- record_fail tuiguard- fi- # #560: the picker has to say WHO serves each model. Reads the open overlay- # off the virtual screen and checks that every row carries a provider and a- # cost badge, that gpt-5.5 draws one distinguishable row per provider with- # the right badge on each (codex plan / openai api / codegraff credits),- # and that typing a provider name filters to that provider's seats.- if python3 scripts/test-tui-model-picker.py zig-out/bin/graff; then :; else+ announce tuiguard "17 PTY probes in a 4–8 process pool (#641)"+ # Same 17 scripts as the old serial loop (pty-guard through model-picker).+ # Each owns its pty/tmp/mock; the pool is the wall-time win.+ if python3 scripts/eval/tier1_tuiguard.py zig-out/bin/graff; then :; elserecord_fail tuiguardfifi@@ -363,39 +255,19 @@ if wanted invariants; thenif ((!build_ok)); thenskip_dependent invariantselse- announce invariants "the named goal/loop/todo tests actually ran"- filters=()- counters=()- while IFS= read -r line; do- [[ -n "$line" ]] || continue- filters+=(-Dtest-filter="$line")- counters+=(--filter "$line")- done < <(python3 scripts/eval/tier1_invariants.py filters)- # Anonymous `test {}` blocks ignore -Dtest-filter and always run, so measure- # that floor with a filter that matches nothing and subtract it.- nothing="__tier1_matches_nothing__"- floor_out=$(zig build test --summary all -Dtest-filter="$nothing" 2>&1)- floor=$(suite_count "$floor_out")- # These two builds cache like any other, and a cached run prints no test- # summary (#439). Ask the artifacts instead - both are small and finish in- # under a second.- [[ -n "$floor" ]] || floor=$(artifact_count --filter "$nothing")- named_out=$(zig build test --summary all "${filters[@]}" 2>&1)- status=$?- named=$(suite_count "$named_out")- if ((status == 0)) && [[ -z "$named" ]]; then- named=$(artifact_count "${counters[@]}")+ announce invariants "the named goal/loop/todo tests are compiled into the suite"+ # #641: the unfiltered `tests` artifact already ran those names. Scanning+ # it avoids two filtered `zig build test` recompiles (~1–3 min cold).+ inv_ok=1+ if ! python3 scripts/eval/tier1_test_binary.py resolve >/dev/null 2>&1; then+ printf ' no test artifact yet; compiling the unfiltered suite once\n'+ if ! zig build test --summary all >/dev/null; then+ inv_ok=0+ record_fail invariants+ fifi- if ((status != 0)); then- printf '%s\n' "$named_out" | tail -6- printf ' one of the named invariants is failing.\n'- record_fail invariants- elif [[ -z "$floor" || -z "$named" ]]; then- printf ' FAIL could not read the filtered test counts\n'- record_fail invariants- else- printf ' filtered run: %s tests, floor %s\n' "$named" "$floor"- if python3 scripts/eval/tier1_invariants.py invariants --observed "$((named - floor))"; then :; else+ if ((inv_ok)); then+ if python3 scripts/eval/tier1_invariants.py invariants --scan; then :; elseprintf ' the required set (scripts/eval/tier1-manifest.json):\n'python3 scripts/eval/tier1_invariants.py listrecord_fail invariantsdiff --git a/scripts/eval/tier1_invariants.py b/scripts/eval/tier1_invariants.pyindex 99b0ac66..f0bc1f39 100644--- a/scripts/eval/tier1_invariants.py+++ b/scripts/eval/tier1_invariants.py@@ -17,6 +17,7 @@ Subcommands (all offline, all under a second):filters print one -Dtest-filter value per line, for the shellcount --observed N the total suite count may grow, never shrinkinvariants --observed N the filtered run must have run exactly the required set+ invariants --scan same check against the unfiltered test artifact (#641)`count` exits 3, not 1, when the suite has run far enough ahead of the baselinethat the floor no longer guards anything (#439: it sat 350 behind). That is a@@ -149,7 +150,12 @@ def main() -> None:count = sub.add_parser("count")count.add_argument("--observed", type=int, required=True)inv = sub.add_parser("invariants")- inv.add_argument("--observed", type=int, required=True)+ inv.add_argument("--observed", type=int, default=None)+ inv.add_argument(+ "--scan",+ action="store_true",+ help="count required names in the unfiltered test artifact (no recompile)",+ )skip = sub.add_parser("docs-only")skip.add_argument("paths", nargs="*")args = parser.parse_args()@@ -221,6 +227,31 @@ def main() -> None:if args.cmd == "invariants":expected = len(manifest["required_invariants"])+ if args.scan:+ # Import sibling: same directory as this file.+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))+ import tier1_test_binary # noqa: E402++ try:+ chosen = tier1_test_binary.select([])+ except tier1_test_binary.ArtifactError as exc:+ print(f" FAIL {exc}", file=sys.stderr)+ sys.exit(1)+ required = [entry["test"] for entry in manifest["required_invariants"]]+ missing = [name for name in required if name not in chosen.present]+ if missing:+ print(+ f" FAIL {len(required) - len(missing)} of {expected} named"+ " invariants present in the unfiltered test artifact.\n"+ f" missing: {missing[0]!r}",+ file=sys.stderr,+ )+ sys.exit(1)+ print(f" all {expected} named goal/loop/todo invariants compiled in")+ return+ if args.observed is None:+ print(" FAIL invariants: pass --observed N or --scan", file=sys.stderr)+ sys.exit(1)if args.observed != expected:print(f" FAIL {args.observed} of {expected} named invariants ran under"diff --git a/scripts/eval/tier1_test_binary.py b/scripts/eval/tier1_test_binary.pyindex 62537986..824cdd88 100644--- a/scripts/eval/tier1_test_binary.py+++ b/scripts/eval/tier1_test_binary.py@@ -25,6 +25,8 @@ means none of them. mtime only breaks ties.resolve [--filter TEXT]... print the artifact path for that buildcount [--filter TEXT]... run that artifact and print how many tests it holds+ scan count named + anonymous tests from the unfiltered+ artifact without executing it (#641)Both exit non-zero with a reason on stderr rather than guess. Neither builds:the caller runs `zig build test` (with the same filters) first, so a compile@@ -44,6 +46,7 @@ SRC = ROOT / "src"CACHE = ROOT / ".zig-cache" / "o"TEST_NAME = re.compile(r'^test "((?:[^"\\]|\\.)*)"', re.M)+ANON_TEST = re.compile(r"(?m)^test \{")ALL_PASSED = re.compile(r"^All (\d+) tests passed\.$", re.M)MIXED = re.compile(r"^(\d+) passed; (\d+) skipped; (\d+) failed\.$", re.M)@@ -175,6 +178,27 @@ def select(filters: list[str], declared: dict[str, str] | None = None) -> Selectreturn best+def anonymous_tests() -> int:+ """`test {}` blocks in src/*.zig. Reachability already requires every+ test-bearing file to be compiled in; adding the named-in-binary count+ reproduces the suite total without executing the artifact (#641)."""+ total = 0+ for path in sorted(SRC.glob("*.zig")):+ try:+ text = path.read_text(encoding="utf-8")+ except (OSError, UnicodeDecodeError):+ continue+ total += len(ANON_TEST.findall(text))+ return total+++def scan_count(filters: list[str] | None = None) -> int:+ """Suite size from the artifact's named tests + source anonymous tests."""+ chosen = select(filters or [])+ extra = anonymous_tests() if not filters else 0+ return len(chosen.present) + extra++def artifact_count(path: pathlib.Path) -> tuple[int, str]:"""Run the artifact and read its own tally. Raises if it does not pass."""proc = subprocess.run(@@ -201,7 +225,7 @@ def artifact_count(path: pathlib.Path) -> tuple[int, str]:def main() -> int:parser = argparse.ArgumentParser(description=__doc__)sub = parser.add_subparsers(dest="cmd", required=True)- for name in ("resolve", "count"):+ for name in ("resolve", "count", "scan"):cmd = sub.add_parser(name)cmd.add_argument("--filter",@@ -236,6 +260,11 @@ def main() -> int:print(chosen.path)return 0+ if args.cmd == "scan":+ extra = anonymous_tests() if not args.filter else 0+ print(len(chosen.present) + extra)+ return 0+try:count, _ = artifact_count(chosen.path)except ArtifactError as exc:diff --git a/scripts/eval/tier1_tuiguard.py b/scripts/eval/tier1_tuiguard.pynew file mode 100755index 00000000..86825a4d--- /dev/null+++ b/scripts/eval/tier1_tuiguard.py@@ -0,0 +1,94 @@+#!/usr/bin/env python3+"""Run the 17 tuiguard PTY probes as a process pool (#641).++Each probe owns its own pty/tmp/mock and is independent of the others. The+serial loop in eval-tier1.sh was the dominant post-src wall (2–4 min). A 4–8+worker pool brings that to roughly one long probe (fold-headers / hover).++Usage: python3 scripts/eval/tier1_tuiguard.py [path/to/graff]+Exit 0 when every probe passes (or skips itself); 1 if any fails.+GRAFF_TUIGUARD_JOBS overrides the pool size (default: min(8, cpu_count)).+"""++from __future__ import annotations++import os+import subprocess+import sys+from concurrent.futures import ProcessPoolExecutor, as_completed+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+SCRIPTS = ROOT / "scripts"++PROBES = (+ "tui-pty-guard.py",+ "test-tui-selection.py",+ "test-tui-typed-events.py",+ "test-tui-painter.py",+ "test-tui-layout-cache.py",+ "test-tui-resize-anchor.py",+ "test-tui-chrome-width.py",+ "test-tui-scroll-paint.py",+ "test-tui-event-pacing.py",+ "test-tui-screenstate.py",+ "test-tui-fold-headers.py",+ "test-tui-stream-markdown.py",+ "test-tui-hover.py",+ "test-tui-click.py",+ "test-tui-scrollbar-osc52.py",+ "test-tui-overlay-panels.py",+ "test-tui-model-picker.py",+)+++def _jobs() -> int:+ raw = os.environ.get("GRAFF_TUIGUARD_JOBS", "").strip()+ if raw.isdigit() and int(raw) > 0:+ return int(raw)+ cpus = os.cpu_count() or 4+ return max(1, min(8, cpus, len(PROBES)))+++def run_probe(script: str, binary: str) -> tuple[str, int, str]:+ path = SCRIPTS / script+ proc = subprocess.run(+ [sys.executable, str(path), binary],+ cwd=ROOT,+ capture_output=True,+ text=True,+ errors="replace",+ )+ blob = (proc.stdout + proc.stderr).rstrip()+ return script, proc.returncode, blob+++def main() -> int:+ binary = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")+ if not os.path.isfile(binary):+ print(f" tuiguard: no binary at {binary}", file=sys.stderr)+ return 1+ jobs = _jobs()+ print(f" {len(PROBES)} probes, {jobs} workers")+ failed: list[str] = []+ with ProcessPoolExecutor(max_workers=jobs) as pool:+ futs = {pool.submit(run_probe, name, binary): name for name in PROBES}+ for fut in as_completed(futs):+ script, status, blob = fut.result()+ if blob:+ for line in blob.splitlines():+ print(f" [{script}] {line}")+ if status != 0:+ failed.append(script)+ print(f" FAIL {script} (exit {status})")+ else:+ print(f" ok {script}")+ if failed:+ print(f" {len(failed)}/{len(PROBES)} probes failed: {', '.join(failed)}")+ return 1+ print(f" all {len(PROBES)} probes passed")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/pre-push.sh b/scripts/pre-push.shindex 922b5717..3f3742ed 100755--- a/scripts/pre-push.sh+++ b/scripts/pre-push.sh@@ -1,6 +1,7 @@#!/usr/bin/env bash# The pre-push gate. Runs tier 1 of the internal eval set (scripts/eval-tier1.sh):-# deterministic, offline, no model calls, ~20-30s warm.+# deterministic, offline, no model calls. Warm fmt/reach/sdk is seconds;+# a post-src run rebuilds zig and the tuiguard pool (minutes, see #641).## Install it once: scripts/install-hooks.sh# Skip it once: git push --no-verifydiff --git a/src/agent.zig b/src/agent.zigindex f2d88f2e..cf378c34 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -203,6 +203,7 @@ pub const Agent = struct {last_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 failurescompact_summary_failures: u8 = 0, // #379: consecutive complete-but-unusable (empty/truncated) summaries+ compact_pin_degraded: bool = false, // #581: pinned suffix over budget — skip+say once per unresolved turnempty_completion_retries: u8 = 0, // degenerate empty completions re-asked this turn (agent_empty_completion.zig)precompact_note_gen: ?u32 = null, // #391: history_rewrites at the last pre-compaction note-to-self, so one history generation buys at most one note however often compaction is retried (compact_note.decideCalls)ws_off: bool = false, // codex ws transport disabled for this session after a handshake/transport fallback to SSE (#codex-ws)diff --git a/src/agent_compact.zig b/src/agent_compact.zigindex 9b528bbc..df5e4c71 100644--- a/src/agent_compact.zig+++ b/src/agent_compact.zig@@ -136,14 +136,21 @@ 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();- const recent_start = recentContextStart(live_messages.items, recent_context_tokens);- compact_cut.noteCut(self.tracer, live_messages.items, recent_start);- // #581: pinning the live prompt at index 0 means there is no completed- // prefix to summarize. Dropping it would replace current images with text.- if (recent_start == 0) {- if (!main_mod.json_mode) try self.say("[compaction skipped: the current prompt's attachments must stay verbatim]\n", .{});- return error.ActivePromptPinned;+ const plan = compact_cut.pinDegrade(live_messages.items, recent_context_tokens, self.compact_pin_degraded);+ compact_cut.noteCut(self.tracer, live_messages.items, plan.start);+ // #581 residual: a pin that already exceeds the keep budget cannot be+ // summarized. Announce once per unresolved turn, then stay quiet.+ switch (plan.action) {+ .silent => return error.ActivePromptPinned,+ .announce => {+ if (!main_mod.json_mode) try self.say("[compaction skipped: the current prompt's attachments must stay verbatim]\n", .{});+ self.compact_pin_degraded = true;+ return error.ActivePromptPinned;+ },+ .proceed => {},}+ const recent_start = plan.start;+ if (plan.pin_over_budget) self.compact_pin_degraded = true;const recent_messages = live_messages.items[recent_start..];var summary_messages = std.json.Array.init(compact_arena);try summary_messages.ensureTotalCapacity(recent_start);@@ -510,6 +517,8 @@ pub fn repeatedEmptySummaryFailure(self: *Agent, err: anyerror) bool {}pub fn compactOrRecover(self: *Agent, trim_on_fail: bool) void {+ if (compact_cut.lastIsResolved(self.messages.items)) self.compact_pin_degraded = false;+ if (self.compact_pin_degraded and !trim_on_fail) return;if (self.compact()) |_| {self.compact_transport_failures = 0;return;diff --git a/src/agent_server_compact.zig b/src/agent_server_compact.zigindex bb9287ed..15ed0e73 100644--- a/src/agent_server_compact.zig+++ b/src/agent_server_compact.zig@@ -29,6 +29,7 @@ const Provider = @import("provider.zig").Provider;const http = @import("http.zig");const telemetry = @import("telemetry.zig");const goal_flow = @import("goal_flow.zig");+const compact_cut = @import("compact_cut.zig");/// GRAFF_SERVER_COMPACT=0/false/off forces the client arm, =1 the server arm/// (session_settings.applyEnvKnobs). Default: server. The #compact-ab@@ -330,6 +331,10 @@ pub fn pruneIf(self: *Agent, server_arm: bool) bool {}const k = blob_idx orelse return false;if (k == 0) return false; // already anchored on the blob+ // #581: a blob after the live unresolved prompt would drop its images.+ if (compact_cut.pinOpening(items)) |t| {+ if (k > t) return false;+ }// Collect the call_ids that survive, then reject if any surviving output// references a pruned call.var surviving: std.ArrayList([]const u8) = .empty;@@ -421,6 +426,8 @@ fn buildCompactBody(self: *Agent) ![]u8 {pub fn explicitCompact(self: *Agent) bool {const compact_url = self.provider.serverCompactUrl() orelse return false;if (self.messages.items.len == 0) return false;+ // #581: do not fold an unresolved image prompt into an opaque blob.+ if (compact_cut.pinOpening(self.messages.items) != null) return false;// Anti-thrash: a history already anchored on a blob with only a few items// after it cannot meaningfully shrink — when the threshold sits below the// standing prompt overhead (a tiny GRAFF_COMPACT_PCT), re-compacting everydiff --git a/src/agent_server_compact_tests.zig b/src/agent_server_compact_tests.zigindex 8429fdb5..a962f673 100644--- a/src/agent_server_compact_tests.zig+++ b/src/agent_server_compact_tests.zig@@ -208,6 +208,67 @@ test "pruneToLatestBlob: prunes to the newest blob and resets the meters" {try std.testing.expectEqual(@as(u64, 0), agent.context_local_tokens);}+fn imageUser(a: std.mem.Allocator) !Value {+ var image: std.json.ObjectMap = .empty;+ try image.put(a, "type", .{ .string = "image_url" });+ var image_url: std.json.ObjectMap = .empty;+ try image_url.put(a, "url", .{ .string = "data:image/png;base64,AAA" });+ try image.put(a, "image_url", .{ .object = image_url });+ var content = std.json.Array.init(a);+ var tb: std.json.ObjectMap = .empty;+ try tb.put(a, "type", .{ .string = "text" });+ try tb.put(a, "text", .{ .string = "read this" });+ try content.append(.{ .object = tb });+ try content.append(.{ .object = image });+ var user: std.json.ObjectMap = .empty;+ try user.put(a, "role", .{ .string = "user" });+ try user.put(a, "content", .{ .array = content });+ return .{ .object = user };+}++test "pruneIf: refuses a blob that would drop an unresolved image prompt (#581)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = testAgent(a, .responses);+ try agent.messages.append(try item(a, "message", null));+ try agent.messages.append(try imageUser(a)); // live pin+ try agent.messages.append(try item(a, "function_call", "c1"));+ try agent.messages.append(try item(a, "function_call_output", "c1"));+ try agent.messages.append(try item(a, "compaction", null)); // after the pin+ try std.testing.expect(!pruneIf(&agent, true));+ try std.testing.expectEqual(@as(usize, 5), agent.messages.items.len);+ try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);+}++test "pruneIf: a blob before the live image pin still prunes the prefix (#581)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = testAgent(a, .responses);+ try agent.messages.append(try item(a, "message", null));+ try agent.messages.append(try item(a, "compaction", null));+ try agent.messages.append(try imageUser(a));+ try std.testing.expect(pruneIf(&agent, true));+ try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);+ try std.testing.expectEqualStrings("compaction", agent.messages.items[0].object.get("type").?.string);+}++test "explicitCompact: refuses to fold an unresolved image prompt into a blob (#581)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = testAgent(a, .responses);+ agent.arena = a;+ agent.provider.id = "xai";+ try agent.messages.append(try imageUser(a));+ try agent.messages.append(try item(a, "function_call", "c1"));+ try agent.messages.append(try item(a, "function_call_output", "c1"));+ try std.testing.expect(!explicitCompact(&agent));+ try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);+ try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);+}+test "pruneToLatestBlob: an orphaned tool output refuses the prune" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();diff --git a/src/compact_cut.zig b/src/compact_cut.zigindex 6363e390..ddd37bc6 100644--- a/src/compact_cut.zig+++ b/src/compact_cut.zig@@ -74,12 +74,50 @@ fn mustKeepOpening(items: []const Value, t: usize) bool {return t > 0 or messageHasImage(items[t]);}-fn pinOpening(items: []const Value) ?usize {+pub fn pinOpening(items: []const Value) ?usize {if (lastIsResolved(items)) return null;const t = turnOpeningUserIndex(items) orelse return null;return if (mustKeepOpening(items, t)) t else null;}+pub fn suffixTokens(items: []const Value, start: usize) u64 {+ var total: u64 = 0;+ for (items[start..]) |m| total +|= context_tokens.estimatedTokens(m);+ return total;+}++/// True when an unresolved pin is in force and that suffix alone is already+/// over the recent-context keep budget. Compacting the completed prefix+/// cannot get the live prompt under the line.+pub fn pinOverBudget(items: []const Value, token_budget: u64) bool {+ const t = pinOpening(items) orelse return false;+ return suffixTokens(items, t) > token_budget;+}++pub const DegradeAction = enum { proceed, announce, silent };++pub const CutPlan = struct {+ start: usize,+ pin_over_budget: bool,+ action: DegradeAction,+};++/// #581 residual: budget-check the pinned suffix. Keep the pin (never drop+/// live images). If the suffix alone is over budget, compact the completed+/// prefix once, then degrade — do not spend a summarization every cycle.+/// `already` is the per-turn latch (`Agent.compact_pin_degraded`).+pub fn pinDegrade(items: []const Value, token_budget: u64, already: bool) CutPlan {+ const start = recentContextStart(items, token_budget);+ const over = pinOverBudget(items, token_budget);+ const cannot_help = start == 0 or (over and already);+ if (!cannot_help) return .{ .start = start, .pin_over_budget = over, .action = .proceed };+ return .{+ .start = start,+ .pin_over_budget = over,+ .action = if (already) .silent else .announce,+ };+}+/// 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.@@ -276,3 +314,84 @@ test "first-turn unresolved images refuse a summarize-all cut" {try std.testing.expectEqual(@as(usize, 0), recentContextStart(msgs.items, 8_000));}++fn fatImageUser(arena: std.mem.Allocator, n: usize) !Value {+ var content = std.json.Array.init(arena);+ var tb: std.json.ObjectMap = .empty;+ try tb.put(arena, "type", .{ .string = "text" });+ try tb.put(arena, "text", .{ .string = "read these screenshots" });+ try content.append(.{ .object = tb });+ var i: usize = 0;+ while (i < n) : (i += 1) {+ var image: std.json.ObjectMap = .empty;+ try image.put(arena, "type", .{ .string = "image_url" });+ var image_url: std.json.ObjectMap = .empty;+ try image_url.put(arena, "url", .{ .string = "data:image/png;base64,AAA" });+ try image.put(arena, "image_url", .{ .object = image_url });+ try content.append(.{ .object = image });+ }+ var user: std.json.ObjectMap = .empty;+ try user.put(arena, "role", .{ .string = "user" });+ try user.put(arena, "content", .{ .array = content });+ return .{ .object = user };+}++test "pinned suffix over the keep budget is reported and still pinned" {+ const a = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(a);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const textMessage = @import("messages.zig").textMessage;++ var msgs = std.json.Array.init(arena);+ try msgs.append(try textMessage(arena, "user", "old request"));+ try msgs.append(try textMessage(arena, "assistant", "old answer"));+ try msgs.append(try fatImageUser(arena, 3)); // 3 * 4096 image tokens > 8k++ try std.testing.expect(pinOverBudget(msgs.items, 8_000));+ try std.testing.expectEqual(@as(usize, 2), recentContextStart(msgs.items, 8_000));+ try std.testing.expectEqual(@as(u32, 3), countImagesFrom(msgs.items[2..]));+}++test "pinDegrade: over-budget pin announces once, then stays silent" {+ const a = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(a);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var msgs = std.json.Array.init(arena);+ try msgs.append(try fatImageUser(arena, 3));+ try toolTail(arena, &msgs, 2);++ const first = pinDegrade(msgs.items, 8_000, false);+ try std.testing.expectEqual(@as(usize, 0), first.start);+ try std.testing.expect(first.pin_over_budget);+ try std.testing.expectEqual(DegradeAction.announce, first.action);++ const again = pinDegrade(msgs.items, 8_000, true);+ try std.testing.expectEqual(@as(usize, 0), again.start);+ try std.testing.expectEqual(DegradeAction.silent, again.action);+}++test "pinDegrade: prefix still compactable once; already-degraded skips the spend" {+ const a = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(a);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const textMessage = @import("messages.zig").textMessage;+ const util = @import("util.zig");++ var msgs = std.json.Array.init(arena);+ try msgs.append(try textMessage(arena, "user", "old request"));+ try msgs.append(try textMessage(arena, "assistant", &util.repeatBytes("x", 20_000)));+ try msgs.append(try fatImageUser(arena, 3));++ const first = pinDegrade(msgs.items, 8_000, false);+ try std.testing.expectEqual(@as(usize, 2), first.start);+ try std.testing.expect(first.pin_over_budget);+ try std.testing.expectEqual(DegradeAction.proceed, first.action);++ const again = pinDegrade(msgs.items, 8_000, true);+ try std.testing.expectEqual(@as(usize, 2), again.start);+ try std.testing.expectEqual(DegradeAction.silent, again.action);+}