graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Recover rejected compaction input and tolerate short TLS outages
justrachf81c91d14b1a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0ef1febe..8d427c5f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,11 @@ The release workflow uses a tag's section here as its release notes (ahand-written `docs/releases/<tag>.md` wins if present), so keeping this filecurrent is part of cutting a release.+## v0.302.74++- Rejected encrypted compaction state can recover from a private pre-compaction checkpoint without losing later conversation. New server compactions retain exact input before replacing it; unavailable or invalid checkpoints leave history unchanged (#1822, ADR 0316).+- Short TLS-construction outages receive a longer bounded recovery window. Ordinary network retries, cancellation and certificate verification remain unchanged.+## v0.302.73- ACP clients can mark explicitly selected commands with per-prompt intent metadata. Literal slash-prefixed prose now reaches the agent instead of being consumed as a command, including goal, review, issue, loop and side-request expansion. Clients that omit the marker retain their existing command syntax (#1817, ADR 0315).diff --git a/build.zig b/build.zigindex 767116b4..00f3db80 100644--- a/build.zig+++ b/build.zig@@ -179,6 +179,9 @@ pub fn build(b: *std.Build) void {const acp_meta_status_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-meta-tool-status.py" });acp_meta_status_test.addArtifactArg(exe);test_step.dependOn(&acp_meta_status_test.step);+ const encrypted_recovery_test = b.addSystemCommand(&.{ "python3", "scripts/test-encrypted-recovery.py" });+ encrypted_recovery_test.addArtifactArg(exe);+ test_step.dependOn(&encrypted_recovery_test.step);const acp_yield_once_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-yield-once.py" });acp_yield_once_test.addArtifactArg(exe);test_step.dependOn(&acp_yield_once_test.step);diff --git a/docs/adr/0316-rejected-compaction-restores-exact-input.md b/docs/adr/0316-rejected-compaction-restores-exact-input.mdnew file mode 100644index 00000000..be19dc36--- /dev/null+++ b/docs/adr/0316-rejected-compaction-restores-exact-input.md@@ -0,0 +1,39 @@+# 0316. Rejected compaction restores exact input++Status: accepted 2026-11-08++## Context++Reanchoring a request cannot repair an opaque compaction item that the server+rejects even in full input. The prior failure diagnostic preserved that item+but left continuation blocked. A transcript is useful for recall, not proof of+an exact pre-compaction window: deduplication, rewrites and rotation can change+its ordering or coverage. Silently dropping opaque state loses context.++## Decision++Before replacing a durable root conversation with server-compacted input,+atomically retain its exact prior input and the complete replacement window+in a private, bounded checkpoint under the session's local artifact directory.+An automatic prune checkpoints the folded prefix; standalone compaction+checkpoints all input and all canonical output items. Checkpoint failure+prevents the destructive replacement. Files are immutable, content-checked,+and cannot follow symlinks outside the workspace.++After a full-input encrypted-state rejection, restore a checkpoint only if+its complete replacement window still exactly matches the current prefix.+Append all subsequent conversation verbatim. Reset transport and token-meter+anchors, then rebuild the request. At most eight checkpoint restorations are+allowed per request, independently of transport retries. Missing, changed or+invalid checkpoints preserve the live history and surface the blocked state.+This shared engine path applies to both REPL and ACP.++## Consequences++New compactions have a history-preserving recovery path across process restarts.+Older opaque state without a checkpoint cannot be reconstructed automatically;+a new process or model switch must not be described as restoring that state.+Checkpoints contain private conversation data, never appear in telemetry or+public reports, and follow the existing local session-artifact lifecycle.+Non-durable auxiliary agents do not acquire durable root-session checkpoints.+This adds local disk I/O at actual compaction boundaries, not ordinary calls.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 740a6112..c762ba40 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -340,6 +340,7 @@ record only when you need the evidence or the edge cases.| [0313](0313-graff-does-not-load-codex-computer-use.md) | Graff does not load Codex's `computer-use` or `unified-computer-use` plugins; every MCP elicitation is declined. Supersedes 0036 and 0119. || [0314](0314-nanocua-is-grafts-computer-use.md) | Computer use on macOS is nanocua, a signed app shipped beside graff and offered as one MCP server; it works inside one app in the background, and the app's panel, not graff, says what it may do: graff and Harness can read its state and turn things off, but turning anything on takes a person's click in its window. nanoui's copy is generated from codegraff's and keeps codegraff's license. || [0315](0315-acp-explicit-command-intent.md) | Harness carries explicit command completion intent in ACP `_meta["harness/command"]`; literal slash prose bypasses dispatch and expansion, while legacy clients retain their syntax. |+| [0316](0316-rejected-compaction-restores-exact-input.md) | Server-compaction replacements retain private exact-input checkpoints; rejected state restores only a matching window plus its later tail, within a bounded recovery budget. || [0302](0302-sse-idle-watchdogs-follow-body-byte-progress.md) | SSE idle watchdogs observe partial body-byte progress, while separate unfinished-event time and size bounds preserve recovery. |diff --git a/docs/releases/v0.302.74.md b/docs/releases/v0.302.74.mdnew file mode 100644index 00000000..9274e801--- /dev/null+++ b/docs/releases/v0.302.74.md@@ -0,0 +1,6 @@+# v0.302.74++- Rejected encrypted compaction state can recover from a private checkpoint containing the exact input and all later conversation. New server compactions retain that checkpoint before replacing history. Missing, changed or invalid checkpoints leave history unchanged and report the blocked state (#1822).+- Short TLS-construction outages have a longer bounded recovery window, without changing ordinary retry limits, cancellation or certificate verification (#1826).++Existing encrypted state created before this release cannot be reconstructed automatically unless an exact checkpoint is available. Detailed diagnostics and conversation contents remain local.diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex 20640864..2fe10704 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -80,6 +80,7 @@{"id": "list-dir-near-miss-hint", "why": "ADR 0093: a misspelled list_dir path should name the closest sibling while retaining error status.", "prompt": "what is in the demo-server folder", "workspace_seed": {"demos-servers/README.md": "# runbook\n"}, "script": [{"tool": "codedb", "arguments": {"command": "list_dir demo-server"}}, {"text": "the folder is demos-servers"}], "assert": [{"event": {"type": "tool_result", "name": "codedb", "is_error": true}}, {"request_contains": {"index": 1, "text": "was not found. Closest match: demos-servers/."}}, {"final_text_contains": "demos-servers"}]}{"id": "subagent-activity-isolated-sink", "why": "Frontendless workers must publish their streamed progress, tool identity and final report to a separate bounded activity feed without emitting child prose as parent text.", "workspace_seed": {"example.txt": "fixture content\n", "check_activity.py": "import json, pathlib\nsnapshots = [json.loads(p.read_text()) for p in pathlib.Path('.graff/live').glob('activity-*/*.json')]\nassert len(snapshots) == 1, len(snapshots)\ns = snapshots[0]\nassert s['agent']['status'] == 'completed', s['agent']\nassert s['response'] == 'Child review complete.', s['response']\nassert any(e['type'] == 'text' and 'Child is inspecting.' in e['text'] for e in s['events']), s['events']\nassert any(e['type'] == 'tool_call' and e['name'] == 'read_file' and e['text'] == 'example.txt' and e['input_key'] == 'path' for e in s['events']), s['events']\nassert any(e['type'] == 'tool_result' and 'fixture content' in e['text'] for e in s['events']), s['events']\nassert not any('Parent has finished.' in e['text'] for e in s['events'])\nprint('child-activity-verified')\n"}, "prompt": "Use one subagent to inspect example.txt, then verify its activity feed with check_activity.py.", "script": [{"tool": "subagent", "arguments": {"description": "Inspect example", "prompt": "Read example.txt and report your findings.", "isolation": "shared_cwd"}}, {"text": "Child is inspecting.", "tool": "read_file", "arguments": {"path": "example.txt"}}, {"text": "Child review complete."}, {"tool": "bash", "arguments": {"command": "python3 check_activity.py"}}, {"text": "Parent has finished."}], "assert": [{"event": {"type": "tool_result", "name": "bash", "text": "child-activity-verified\n"}}, {"events_at_most": {"match": {"type": "text", "text": "Child is inspecting."}, "count": 0}}, {"final_text_contains": "Parent has finished."}]}{"id":"opaque-compaction-is-not-success-804","why":"An unsupported local fallback must report that opaque history needs server compaction, not emit successful zero-work compaction or discard the preserved context.","args":["--resume","compact-fixture"],"workspace_seed":{".graff/sessions/compact-fixture.session.json":"{\"provider\":\"lmstudio\",\"model\":\"mock\",\"messages\":[{\"type\":\"compaction\",\"encrypted_content\":\"opaque-fixture-804\"},{\"role\":\"user\",\"content\":\"retained-context-804\"}]}"},"controls_before_prompt":[{"type":"compact"}],"prompt":"Continue using the retained context.","script":[{"text":"Retained context is available."}],"assert":[{"event":{"type":"error","message":"compaction failed: ServerCompactionRequired"}},{"events_at_most":{"match":{"type":"compact","ok":true},"count":0}},{"request_contains":{"index":0,"text":"retained-context-804"}},{"request_contains":{"index":0,"text":"opaque-fixture-804"}},{"final_text_contains":"Retained context is available."}]}+{"id":"encrypted-state-no-checkpoint-preserves-history-1822","why":"A rejected opaque state without an exact checkpoint must stop once rather than retry unchanged ciphertext or discard retained conversation.","args":["--resume","rejected-fixture"],"workspace_seed":{".graff/sessions/rejected-fixture.session.json":"{\"provider\":\"lmstudio\",\"model\":\"mock\",\"messages\":[{\"type\":\"compaction\",\"encrypted_content\":\"rejected-fixture-1822\"},{\"role\":\"user\",\"content\":\"retained-fixture-1822\"}]}"},"prompt":"Continue the retained conversation.","script":[{"stream_error":{"type":"invalid_request_error","code":"invalid_encrypted_content","message":"Encrypted content could not be decrypted or parsed."}}],"assert":[{"request_count":1},{"request_contains":{"index":0,"text":"rejected-fixture-1822"}},{"request_contains":{"index":0,"text":"retained-fixture-1822"}},{"event":{"type":"error","message":"api error (invalid_request_error invalid_encrypted_content): Encrypted content could not be decrypted or parsed."}}]}{"id": "completion-search-citations-clean", "why": "#819: the authoritative completion must remove search citation control spans while preserving human prose; the release regression also covers byte-fragmented line output.", "args": ["--old"], "prompt": "Return the scripted final result.", "script": [{"tool": "attempt_completion", "arguments": {"result": "Read the docsciteturn0search0turn1search2 today."}, "argument_chunk_size": 1}], "assert": [{"final_text_contains": "Read the docs today."}]}{"id": "render-html-hands-back-an-opaque-view", "why": "The model's own drawing surface must be advertised, dispatch to the snapshot writer, and put only the opaque path into the transcript - a page the model drew must never come back to it as a second copy of the markup.", "args": [], "prompt": "draw the retry flow as a page", "script": [{"tool": "render_html", "arguments": {"html": "<h1 id=\"flow\">Retry flow</h1><p>the second attempt is declined</p>"}}, {"text": "drawn above"}], "assert": [{"request_contains": {"index": 0, "text": "render_html"}}, {"events_at_least": {"match": {"type": "tool_call", "name": "render_html"}, "count": 1}}, {"event": {"type": "tool_result"}}, {"request_contains": {"index": -1, "text": "[Rendered view]"}}, {"request_contains": {"index": -1, "text": "/.graff/views/"}}, {"final_text_contains": "drawn above"}]}{"id": "bundled-mcp-skill-loads", "why": "The bundled invocation skill must be discoverable and load its connection instructions after adding an MCP server.", "prompt": "Load the bundled mcp skill before adding a server.", "script": [{"tool": "skill", "arguments": {"name": "mcp"}}, {"text": "MCP instructions loaded."}], "assert": [{"event": {"type": "tool_call", "name": "skill"}}, {"request_contains": {"index": -1, "text": "graff mcp add"}}, {"request_contains": {"index": -1, "text": "/mcp trust"}}, {"final_text_contains": "MCP instructions loaded."}]}diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex b604dcd7..102072bf 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -14,7 +14,7 @@"src/main.zig","src/repl.zig"],- "test_count_baseline": 3620,+ "test_count_baseline": 3652,"test_count_slack": 25,"required_invariants": [{diff --git a/scripts/test-encrypted-recovery.py b/scripts/test-encrypted-recovery.pynew file mode 100644index 00000000..f90ccd95--- /dev/null+++ b/scripts/test-encrypted-recovery.py@@ -0,0 +1,119 @@+#!/usr/bin/env python3+"""Offline real-engine regression: rejected compaction expands exact input."""+from __future__ import annotations++import hashlib+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile++from codex_ws_mock import CodexMock, turn_events+++def wire(value):+ return json.dumps(value, separators=(",", ":"), ensure_ascii=False).encode()+++def seed(root, with_checkpoint):+ before = [{"role": "user", "content": "exact-earlier-context-fixture"}]+ window = [{"type": "compaction", "encrypted_content": "rejected-state-fixture"}]+ tail = [{"role": "user", "content": "retained-followup-fixture"}]+ sessions = root / ".graff" / "sessions"+ sessions.mkdir(parents=True)+ (sessions / "recovery.session.json").write_bytes(wire({+ "provider": "codex", "model": "gpt-6-astra", "messages": window + tail,+ }))+ if with_checkpoint:+ blob = hashlib.sha256(wire(window[0])).hexdigest()+ history = hashlib.sha256(wire({"before": before, "window": window})).hexdigest()+ folder = sessions / "recovery" / "compaction"+ folder.mkdir(parents=True)+ (folder / (blob + ".json")).write_bytes(wire({+ "version": 1, "blob_sha256": blob, "history_sha256": history,+ "before": before, "window": window,+ }))+ (folder / (blob + ".json")).chmod(0o600)+ auth = root / "codex-home"+ auth.mkdir()+ (auth / "auth.json").write_text(json.dumps({"tokens": {+ "access_token": "local-regression-token", "account_id": "local-fixture",+ }}))+ settings = root / ".harness"+ settings.mkdir()+ (settings / "settings.json").write_text(json.dumps({+ "ai_title": False, "session_recap": False,+ }))+ (root / "mcp.json").write_text('{"mcpServers":{}}')+ return auth+++def run(binary, with_checkpoint, create_checkpoint=False):+ def reply(request):+ if create_checkpoint and request.ordinal == 1:+ events = turn_events("resp_compacted")+ events[0]["item"] = {"type": "compaction", "encrypted_content": "rejected-state-fixture"}+ return events+ data = wire(request.body)+ if b"rejected-state-fixture" in data:+ return [{"type": "error", "error": {+ "code": "invalid_encrypted_content",+ "message": "Encrypted content could not be decrypted or parsed.",+ }}]+ events = turn_events("resp_recovered")+ events[0]["item"]["content"][0]["text"] = "recovered-exact-history"+ return events++ with tempfile.TemporaryDirectory(prefix="graff-encrypted-recovery-") as tmp:+ root = Path(tmp)+ auth = seed(root, with_checkpoint and not create_checkpoint)+ if create_checkpoint:+ session_file = root / ".graff/sessions/recovery.session.json"+ session = json.loads(session_file.read_text())+ session["messages"][0] = {"role": "user", "content": "exact-earlier-context-fixture"}+ session_file.write_bytes(wire(session))+ mock = CodexMock(events_for_request=reply)+ port = mock.start()+ env = {k: v for k, v in os.environ.items()+ if not k.endswith("_API_KEY") and not k.startswith(("GRAFF_", "CODEX_"))}+ env.update(HOME=tmp, CODEX_HOME=str(auth), CODEGRAFF_API_KEY="local-fixture",+ GRAFF_CODEX_URL=f"http://127.0.0.1:{port}/backend-api/codex/responses",+ GRAFF_CODEX_WS="off", GRAFF_NO_TELEMETRY="1", GRAFF_FLEET="off",+ GRAFF_MCP_CONFIG=str(root / "mcp.json"), GRAFF_NO_CODEDB_GUARD="1")+ try:+ args = [binary, "--model", "codex", "--resume", "recovery", "--json", "--no-telemetry"]+ prompt = "Continue the exact retained conversation."+ controls = None+ if create_checkpoint:+ controls = json.dumps({"type": "compact"}) + "\n" + json.dumps({"type": "user", "text": prompt}) + "\n"+ else:+ args += ["-p", prompt]+ result = subprocess.run(args, input=controls, cwd=tmp, env=env,+ capture_output=True, text=True, timeout=45)+ finally:+ mock.stop()+ requests = mock.recorded_requests()+ if with_checkpoint:+ assert result.returncode == 0, result.stderr + result.stdout+ assert "recovered-exact-history" in result.stdout, result.stdout+ assert len(requests) == (3 if create_checkpoint else 2), len(requests)+ restored = wire(requests[-1].body)+ assert b"exact-earlier-context-fixture" in restored, restored+ assert b"retained-followup-fixture" in restored, restored+ assert b"Continue the exact retained conversation." in restored, restored+ assert b"rejected-state-fixture" not in restored, restored+ else:+ assert result.returncode != 0, result.stdout+ assert len(requests) == 1, len(requests)+ assert "history is unchanged" in result.stdout + result.stderr+ print("PASS encrypted recovery:", "exact input and tail restored" if with_checkpoint+ else "missing checkpoint preserves history and stops once", flush=True)+++if __name__ == "__main__":+ binary = str(Path(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff").resolve())+ run(binary, True)+ run(binary, False)+ run(binary, True, create_checkpoint=True)diff --git a/src/agent_encrypted_recovery.zig b/src/agent_encrypted_recovery.zignew file mode 100644index 00000000..bb69c489--- /dev/null+++ b/src/agent_encrypted_recovery.zig@@ -0,0 +1,21 @@+//! Rejected opaque state is recoverable only from exact retained input.+//! Never retry the same blob unchanged or infer its contents from a summary.+const Agent = @import("agent.zig").Agent;+const checkpoint = @import("compaction_checkpoint.zig");+const window = @import("compaction_window.zig");++pub const max_restores = 8;++pub fn recover(self: *Agent, message: []const u8, code: ?[]const u8, restores: *u8) bool {+ if (!window.rejectedByProvider(message, code) or restores.* >= max_restores) return false;+ if (!(checkpoint.restore(self) catch false)) return false;+ restores.* += 1;+ self.closeCodexWs();+ self.last_context_tokens = 0;+ self.context_local_tokens = 0;+ self.last_usage_includes_output = false;+ self.goal_note_fp = 0;+ self.history_rewrites +%= 1;+ if (self.tracer) |tr| tr.note("encrypted_state_recovery", "restored exact pre-compaction input; subsequent conversation retained");+ return true;+}diff --git a/src/agent_request.zig b/src/agent_request.zigindex 87b7c5db..2ccd6bdd 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -1,8 +1,4 @@-//! Provider round trip and retry loop.-//!-//! Request policy, context accounting, Responses reassembly, and body-//! serialization live in focused sibling modules and are re-exported here so-//! Agent's public method aliases remain source-compatible.+//! Provider round trip and retry loop; focused policy helpers are re-exported below.const std = @import("std");const Io = std.Io;@@ -171,21 +167,8 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {@import("history_wire.zig").prepare(message_arena, self.provider.kind, &self.messages);// ADR 0221: on the ChatGPT plan route loaded tools ride additional_tools items, so `tools` never changes.if (!self.compaction_request and !self.server_compaction_request) @import("additional_tools.zig").sync(self);- // #193 follow-up: bound any single oversized tool output (an uncapped MCP- // result, a huge fetch on a small-window model) before send. The responses- // path already hard-caps output above (normalizeResponsesHistory); this is the- // provider-agnostic sibling so one pathological result can't alone overflow the- // window past what the in-turn recovery below can reclaim (it keeps the most- // recent outputs verbatim). Window-proportional, so large-context models keep- // full tool results untouched.- //- // #440 narrowed this to a BACKSTOP. Every tool result this process produced- // already met the handle contract at tool time, under a threshold clamped to- // this very cap (tool_handle.effectiveThreshold), so nothing from runTools can- // reach here oversized. What still can: a session resumed from a build that- // predates #440, and any future path that appends a tool output without going- // through runTools. Both are exactly the cases where destroying the bytes- // would be the alternative, so the pass stays.+ // #193/#440: window-proportional backstop for resumed legacy or externally+ // appended outputs; runTools already meets the durable handle contract.const spills_before = tool_spill.spillCount();const capped = self.capOversizedToolOutputs(self.provider.perOutputCap());if (capped > 0) {@@ -206,6 +189,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {}}var context_retried = false; // #193: at most one in-turn overflow recovery per request+ var encrypted_restores: u8 = 0;// #56: bounded stream-stall / drop reconnect budget (codex's stream_max_retries analog), outside the rebuild loop so a WS reanchor can't reset it.self.stall = .{}; // #680: a fresh widen ladder + tripped budget per requestvar stall_retries: usize = 0;@@ -215,6 +199,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {var openai404_retries: usize = 0; // #opencode-parity: bounded retries for OpenAI's spurious model 404sconst max_openai404_retries: usize = 2;var gw_retry = policy.GatewayRetryState{}; // #gateway-artifact state (agent_gateway_retry.zig)+ var tls_failures: usize = 0; // Construction-only budget survives every body/WS rebuild.@import("cache_ttl.zig").begin(self); // #1320: before request_started movesvar call: @import("model_call.zig").Call = .{}; // #1665: pairs every started attempterrdefer call.fail(self, false);@@ -249,9 +234,10 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {// few times with a fresh connection; on persistent failure surface// error.ApiError so the REPL returns to the prompt, never crashes.const resp_body = blk: {- var attempt: usize = 0;+ var ordinary_attempts: usize = 0;var retry_limit: ?usize = null;- while (true) : (attempt += 1) {+ while (true) {+ ordinary_attempts += 1;var conv_buf: [96]u8 = undefined;const conv = http_headers.requestCacheKey(self.io, self.label, self, self.provider, &conv_buf);usage_attempts.begin();@@ -340,18 +326,21 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {if (telemetry.g_telem) |t| t.errorEvent("openai_404", self.last_api_error orelse "openai 404");return error.ApiError;}- // 429/5xx: the server asked us to back off — wait- // (1s·2ⁿ, capped at 8s; Esc cancels) and allow a few- // more attempts than a plain transport flake gets.+ const construction_tls = err == error.TlsRequestConstructionFailed or err == error.TlsRequestConstructionCaWarmFailed;+ if (construction_tls) {+ ordinary_attempts -= 1;+ tls_failures += 1;+ }+ const attempt = if (construction_tls) tls_failures - 1 else ordinary_attempts - 1;const throttled = err == error.RateLimited or err == error.ServerError;- const max_attempts = retry_limit orelse RetryPlan.maxAttempts(throttled);- retry_limit = max_attempts;+ const max_attempts = if (construction_tls) RetryPlan.tls_construction_attempts else retry_limit orelse RetryPlan.maxAttempts(throttled);+ if (!construction_tls) retry_limit = max_attempts;// A proxy may wrap a billing/auth refusal in 429 OR 5xx.// Terminal account faults outrank the generic retry status.if (throttled and main_mod.g_5xx_body_len > 0) {if (try quota.handle(self, "", null, main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len], &auth_refreshed)) continue;}- if (err == error.TlsRequestConstructionFailed or err == error.TlsRequestConstructionCaWarmFailed) if (self.tracer) |tr| tr.note(+ if (construction_tls) if (self.tracer) |tr| tr.note("tls_request_construction",if (err == error.TlsRequestConstructionCaWarmFailed) "rotated shared HTTP client generation; replacement CA prewarm failed" else "rotated shared HTTP client generation",);@@ -372,8 +361,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {policy.noteRetry(self, what);self.sleepInterruptible(delay_ms) catch return error.Interrupted;} else {- // Transport flakes back off; rapid retries against a- // just-closed keep-alive re-fail (#86). Cap: 4s/6 tries.+ // Ordinary flakes keep six attempts; only construction TLS gets a longer outage window.const delay_ms = jitter.ms(self.io, RetryPlan.delayMs(throttled, attempt));if (scratch.showRecoveredTransportRetry(self.call_kind))@import("turn_chrome.zig").emitRetryNotice(self.io, @errorName(err), attempt + 1, max_attempts);@@ -450,6 +438,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {if (self.tracer) |tr| tr.note("ws", "server dropped previous_response_id — re-anchoring with full input");continue :rebuild;}+ if (@import("agent_encrypted_recovery.zig").recover(self, msg, failure.code, &encrypted_restores)) continue :rebuild;// #174: a context-window rejection means the true input// size blew past the wall while the chained meter lagged —// and the rejected request never returns usage to correctdiff --git a/src/agent_server_compact.zig b/src/agent_server_compact.zigindex be416349..ffc5ccbb 100644--- a/src/agent_server_compact.zig+++ b/src/agent_server_compact.zig@@ -19,9 +19,8 @@//! (serverOnly); GRAFF_SERVER_COMPACT=0 is the opt-out.//! - every other provider kind: unchanged legacy policy.//!-//! The opaque blob's server-side lifetime under store:false is unknown; if a-//! resumed session's blob is ever rejected, the ordinary overflow recovery-//! ladder (agent_overflow.zig) is the safety net.+//! Before replacing history, retain a private checkpoint so rejected opaque+//! state can be expanded back into its original input without losing context.const std = @import("std");const Io = std.Io;@@ -179,6 +178,7 @@ pub fn compactBody(self: *const Agent) ![]u8 {fn installItems(self: *Agent, items: []const std.json.Value) !void {var fresh = std.json.Array.init(self.arena);try fresh.appendSlice(items);+ try @import("compaction_checkpoint.zig").preserve(self, self.messages.items, fresh.items);self.messages = fresh;self.last_context_tokens = 0;self.context_local_tokens = 0;@@ -403,6 +403,7 @@ pub fn pruneIf(self: *Agent, server_arm: bool) bool {const dropped = k;var fresh = std.json.Array.init(self.arena);fresh.appendSlice(items[k..]) catch return false;+ @import("compaction_checkpoint.zig").preserve(self, items[0..k], fresh.items[0..1]) catch return false;self.messages = fresh;self.compaction_window = .{}; // a newer in-stream blob supersedes the canonical window// Mirror compact()'s post-install meter reset: both anchors recompute@@ -524,6 +525,7 @@ pub fn installCompactionItem(self: *Agent, resp: []const u8) bool {const dropped = self.messages.items.len;var fresh = std.json.Array.init(self.arena);fresh.append(blob) catch return false;+ @import("compaction_checkpoint.zig").preserve(self, self.messages.items, fresh.items) catch return false;self.messages = fresh;// Mirror pruneIf's meter/goal reset: both anchors recompute lazily, the// goal note died with the folded history (#318), and pasted-state readersdiff --git a/src/agent_tls_retry_tests.zig b/src/agent_tls_retry_tests.zignew file mode 100644index 00000000..18980fba--- /dev/null+++ b/src/agent_tls_retry_tests.zig@@ -0,0 +1,252 @@+//! Offline production request-loop coverage for the construction-only TLS outage budget.+const std = @import("std");+const Io = std.Io;+const Agent = @import("agent.zig").Agent;+const http = @import("http.zig");+const clients = @import("http_client.zig");+const transport = @import("http_client_integration_tests.zig");+const trace = @import("trace.zig");++// Replace only this test owner's backoff sleeps, not concurrent HTTP watchdogs.+// All other I/O keeps the real testing Io and its original userdata.+var current_probe: ?*SleepProbe = null;+const SleepProbe = struct {+ owner: std.Thread.Id,+ runtime: *clients.Runtime,+ waited_ms: u64 = 0,+ cancel_generation: u64 = 0,+ cancel_io: bool = false,++ fn sleep(ctx: ?*anyopaque, timeout: Io.Timeout) Io.Cancelable!void {+ const probe = current_probe.?;+ if (std.Thread.getCurrentId() != probe.owner)+ return std.testing.io.vtable.sleep(ctx, timeout);+ probe.waited_ms += @intCast(timeout.duration.raw.toMilliseconds());+ if (probe.cancel_generation > 0 and probe.runtime.recovery.stats().active_id >= probe.cancel_generation) {+ if (probe.cancel_io) return error.Canceled;+ Agent.esc_cancel.store(true, .release);+ }+ }+};++const Fixture = struct {+ runtime: clients.Runtime,+ arena: std.heap.ArenaAllocator,+ server: std.Io.net.Server,+ server_future: ?Io.Future(void),+ accepted: std.atomic.Value(usize),+ url: [64]u8,+ vtable: Io.VTable,+ probe: SleepProbe,+ agent: Agent,+ trace_output: Io.Writer.Allocating,+ tracer: trace.Tracer,+ previous_cancel: bool,++ fn init(self: *Fixture) !void {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ self.runtime.init(gpa, io);+ errdefer self.runtime.deinit(io);+ http.waitForClientReady(io);+ self.arena = .init(gpa);+ errdefer self.arena.deinit();+ var address = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");+ self.server = try std.Io.net.IpAddress.listen(&address, io, .{});+ self.server_future = null;+ self.accepted = .init(0);+ self.vtable = io.vtable.*;+ self.vtable.sleep = SleepProbe.sleep;+ self.probe = .{ .owner = std.Thread.getCurrentId(), .runtime = &self.runtime };+ current_probe = &self.probe;+ self.previous_cancel = Agent.esc_cancel.swap(false, .acq_rel);+ self.trace_output = .init(gpa);+ const agent_io: Io = .{ .userdata = io.userdata, .vtable = &self.vtable };+ self.tracer = .{ .io = agent_io, .gpa = gpa, .out = &self.trace_output.writer, .start = .now(io, .awake) };+ const url = try std.fmt.bufPrint(&self.url, "http://127.0.0.1:{d}/v1/test", .{self.server.socket.address.getPort()});+ self.agent = .{+ .gpa = gpa,+ .arena = self.arena.allocator(),+ .io = agent_io,+ .client = &self.runtime.client,+ .provider = transport.provider(url),+ .messages = std.json.Array.init(self.arena.allocator()),+ .sub = true,+ .label = "tls-budget-test",+ .tracer = &self.tracer,+ .out = null,+ };+ }++ fn serve(self: *Fixture, replies: []const transport.Reply) void {+ self.server_future = std.testing.io.async(transport.serveReplies, .{ std.testing.io, &self.server, replies, &self.accepted });+ }++ fn deinit(self: *Fixture) void {+ const io = std.testing.io;+ if (self.server_future) |*future| {+ transport.releaseAccept(io, &self.server);+ future.await(io);+ }+ self.server.deinit(io);+ @import("agent_render.zig").deinitMarkdown(&self.agent);+ self.trace_output.deinit();+ self.runtime.deinit(io);+ self.arena.deinit();+ Agent.esc_cancel.store(self.previous_cancel, .release);+ current_probe = null;+ }++ fn expectReleased(self: *Fixture) !void {+ try std.testing.expectEqual(@as(usize, 0), self.runtime.recovery.stats().total_refs);+ try std.testing.expectEqual(@as(usize, 0), self.runtime.recovery.stats().retired);+ }++ fn tlsNotes(self: *Fixture) usize {+ return std.mem.count(u8, self.trace_output.written(), "\"ev\":\"tls_request_construction\"");+ }+};++test "TLS outage budget: eight constructor failures recover in the same production request" {+ for ([_]bool{ false, true }) |sub| {+ var fixture: Fixture = undefined;+ try fixture.init();+ defer fixture.deinit();+ fixture.agent.sub = sub;+ const replies = [_]transport.Reply{.{ .body = transport.chat_body }};+ fixture.serve(&replies);+ clients.injectConstructionTlsThroughGenerationForTest(7);+ clients.injectReplacementCaWarmFailureForTest();++ const response = try fixture.agent.request(null);+ const content = response.get("choices").?.array.items[0].object.get("message").?.object.get("content").?.string;+ try std.testing.expectEqualStrings("child-ok", content);+ try std.testing.expectEqual(@as(u64, 8), fixture.runtime.recovery.stats().active_id);+ try std.testing.expectEqual(@as(usize, 8), fixture.tlsNotes());+ try std.testing.expectEqual(@as(usize, 1), fixture.accepted.load(.acquire));+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, fixture.trace_output.written(), "replacement CA prewarm failed"));+ // Eight retry waits cross the old six-attempt window, with real policy jitter.+ try std.testing.expect(fixture.probe.waited_ms >= 19_750);+ try std.testing.expect(fixture.probe.waited_ms <= 24_688);+ try fixture.expectReleased();+ }+}++test "TLS outage budget: permanent failure is bounded and preserves recovery for a later request" {+ var fixture: Fixture = undefined;+ try fixture.init();+ defer fixture.deinit();+ const limit = http.RetryPlan.tls_construction_attempts;+ clients.injectConstructionTlsThroughGenerationForTest(limit - 1);++ try std.testing.expectError(error.ApiError, fixture.agent.request(null));+ try std.testing.expectEqual(@as(u64, limit), fixture.runtime.recovery.stats().active_id);+ try std.testing.expectEqual(limit, fixture.tlsNotes());+ try std.testing.expectEqual(@as(usize, 0), fixture.accepted.load(.acquire));+ try std.testing.expect(std.mem.indexOf(u8, fixture.agent.last_api_error.?, "gave up after 16 attempts") != null);+ try std.testing.expect(fixture.probe.waited_ms >= 47_750);+ try std.testing.expect(fixture.probe.waited_ms <= 59_688);+ try fixture.expectReleased();++ const replies = [_]transport.Reply{.{ .body = transport.chat_body }};+ fixture.serve(&replies);+ _ = try fixture.agent.request(null);+ try std.testing.expectEqual(@as(usize, 1), fixture.accepted.load(.acquire));+ try fixture.expectReleased();+}++test "TLS outage budget: request rebuild cannot reset the construction failure counter" {+ var fixture: Fixture = undefined;+ try fixture.init();+ defer fixture.deinit();+ const replies = [_]transport.Reply{.{+ .status = "400 Bad Request",+ .body = "{\"error\":{\"message\":\"unsupported stream_options\"}}",+ // First eight TLS failures recover; the parsed rejection then rebuilds+ // the request with stream_options dropped while TLS starts failing again.+ .fail_tls_through_generation = 1000,+ }};+ fixture.serve(&replies);+ clients.injectConstructionTlsThroughGenerationForTest(7);++ try std.testing.expectError(error.ApiError, fixture.agent.request(null));+ try std.testing.expectEqual(@as(u64, 16), fixture.runtime.recovery.stats().active_id);+ try std.testing.expectEqual(@as(usize, 16), fixture.tlsNotes());+ try std.testing.expectEqual(@as(usize, 1), fixture.accepted.load(.acquire));+ try std.testing.expect(fixture.probe.waited_ms >= 47_750);+ try std.testing.expect(fixture.probe.waited_ms <= 59_688);+ try fixture.expectReleased();+}++test "TLS outage budget: Esc and I/O cancellation stop the extended ladder without a replacement attempt" {+ for ([_]bool{ false, true }) |cancel_io| {+ var fixture: Fixture = undefined;+ try fixture.init();+ defer fixture.deinit();+ fixture.probe.cancel_generation = 9;+ fixture.probe.cancel_io = cancel_io;+ clients.injectConstructionTlsThroughGenerationForTest(1000);++ try std.testing.expectError(error.Interrupted, fixture.agent.request(null));+ try std.testing.expectEqual(@as(u64, 9), fixture.runtime.recovery.stats().active_id);+ try std.testing.expectEqual(@as(usize, 9), fixture.tlsNotes());+ try std.testing.expectEqual(@as(usize, 0), fixture.accepted.load(.acquire));+ // Cancellation at the first chunk of wait nine, rather than its full 4–5 seconds.+ try std.testing.expect(fixture.probe.waited_ms <= 24_788);+ try fixture.expectReleased();+ }+}++test "TLS outage budget: ordinary transport still gets exactly six attempts after TLS recovery" {+ var fixture: Fixture = undefined;+ try fixture.init();+ defer fixture.deinit();+ // URI construction fails deterministically, without a network call, after the injected TLS failures.+ fixture.agent.provider.url = ":invalid";+ clients.injectConstructionTlsThroughGenerationForTest(7);++ try std.testing.expectError(error.ApiError, fixture.agent.request(null));+ try std.testing.expectEqual(@as(usize, 8), fixture.tlsNotes());+ try std.testing.expect(std.mem.indexOf(u8, fixture.agent.last_api_error.?, "gave up after 6 attempts") != null);+ // Eight TLS retries plus five ordinary retries, not a new 16-attempt transport budget.+ try std.testing.expectEqual(@as(usize, 13), std.mem.count(u8, fixture.trace_output.written(), "\"ev\":\"retry\""));+ try fixture.expectReleased();+}++test "TLS outage budget: throttles still get exactly five attempts after TLS recovery" {+ for ([_][]const u8{ "429 Too Many Requests", "503 Service Unavailable" }) |status| {+ var fixture: Fixture = undefined;+ try fixture.init();+ defer fixture.deinit();+ const reply: transport.Reply = .{ .status = status, .body = "{\"error\":{\"message\":\"try later\"}}" };+ const replies = [_]transport.Reply{ reply, reply, reply, reply, reply };+ fixture.serve(&replies);+ clients.injectConstructionTlsThroughGenerationForTest(7);++ try std.testing.expectError(error.ApiError, fixture.agent.request(null));+ try std.testing.expectEqual(@as(usize, 8), fixture.tlsNotes());+ try std.testing.expectEqual(@as(usize, 5), fixture.accepted.load(.acquire));+ try std.testing.expect(std.mem.indexOf(u8, fixture.agent.last_api_error.?, "gave up after 5 attempts") != null);+ try fixture.expectReleased();+ }+}++test "TLS outage budget: terminal authentication and quota remain fail-fast after TLS recovery" {+ const cases = [_]struct { reply: transport.Reply, err: anyerror }{+ .{ .reply = .{ .status = "401 Unauthorized", .body = "{}" }, .err = error.ProviderAuthenticationFailed },+ .{ .reply = .{ .status = "429 Too Many Requests", .body = "{\"error\":{\"code\":\"insufficient_quota\"}}" }, .err = error.ProviderQuotaExceeded },+ };+ for (cases) |case| {+ var fixture: Fixture = undefined;+ try fixture.init();+ defer fixture.deinit();+ const replies = [_]transport.Reply{case.reply};+ fixture.serve(&replies);+ clients.injectConstructionTlsThroughGenerationForTest(7);++ try std.testing.expectError(case.err, fixture.agent.request(null));+ try std.testing.expectEqual(@as(usize, 8), fixture.tlsNotes());+ try std.testing.expectEqual(@as(usize, 1), fixture.accepted.load(.acquire));+ try fixture.expectReleased();+ }+}diff --git a/src/agent_ws_reuse_test.zig b/src/agent_ws_reuse_test.zigindex 6dc2732f..f21ae287 100644--- a/src/agent_ws_reuse_test.zig+++ b/src/agent_ws_reuse_test.zig@@ -243,7 +243,8 @@ test "#692: a generic error frame is returned as the terminal API body before pevar server = try std.Io.net.IpAddress.listen(&addr, io, .{});defer server.deinit(io);var done: std.atomic.Value(bool) = .init(false);- var fut = io.async(Mock.run, .{ io, &server, Mock.Mode.generic_error_then_close, &done });+ // The peer must start before dialing; async may defer it until await.+ var fut = try io.concurrent(Mock.run, .{ io, &server, Mock.Mode.generic_error_then_close, &done });defer fut.await(io);defer done.store(true, .release);diff --git a/src/cli_text_source.zig b/src/cli_text_source.zigindex b080b29e..34aa5a6a 100644--- a/src/cli_text_source.zig+++ b/src/cli_text_source.zig@@ -5,6 +5,10 @@pub const changelog_text =\\What's new\\──────────+ \\0.302.74+ \\ • rejected compaction state restores exact input when a private checkpoint is available+ \\ • short TLS-construction outages get a longer bounded recovery window+ \\\\0.302.71\\ • computer use on macOS: graff ships nanocua, an app that lets agents work in other apps\\ • graff computer and /computer: status, stop, switches; turning input on takes your clickdiff --git a/src/compaction_checkpoint.zig b/src/compaction_checkpoint.zignew file mode 100644index 00000000..f4bd6610--- /dev/null+++ b/src/compaction_checkpoint.zig@@ -0,0 +1,228 @@+//! Private, verbatim pre-compaction history. No summaries and no network IO.+//! A checkpoint only reverses an exact prefix replacement; changed windows+//! fail closed. Root recovery owns transport/meter resets after installation.+const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;+const Value = std.json.Value;+const Agent = @import("agent.zig").Agent;+const Allocator = std.mem.Allocator;+const windows = @import("compaction_window.zig");++pub const max_checkpoint_bytes = 64 * 1024 * 1024;+const private_file: Io.File.Permissions = if (builtin.os.tag == .windows) .default_file else .fromMode(0o600);+const private_dir: Io.File.Permissions = if (builtin.os.tag == .windows) .default_dir else .fromMode(0o700);+const Payload = struct { before: []const Value, window: []const Value };+const Snapshot = struct {+ version: u32,+ blob_sha256: []const u8,+ history_sha256: []const u8,+ before: []const Value,+ window: []const Value,+};++pub fn safeSessionName(name: []const u8) bool {+ if (name.len == 0 or name.len > 160 or name[0] == '.') return false;+ for (name) |c| if (!std.ascii.isAlphanumeric(c) and c != '-' and c != '_' and c != '.') return false;+ return true;+}++fn hash(bytes: []const u8) [64]u8 {+ var digest: [32]u8 = undefined;+ std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{});+ return std.fmt.bytesToHex(digest, .lower);+}++fn valueHash(a: Allocator, value: anytype) ![64]u8 {+ const bytes = try std.json.Stringify.valueAlloc(a, value, .{});+ defer a.free(bytes);+ return hash(bytes);+}++fn openChild(io: Io, parent: Io.Dir, name: []const u8, create: bool) !Io.Dir {+ if (create) {+ parent.createDir(io, name, private_dir) catch |err| if (err != error.PathAlreadyExists) return err;+ try syncDirectory(io, parent);+ }+ // Walk one component at a time, never following a symlink, so even an+ // existing .graff/sessions tree cannot redirect a checkpoint outside cwd.+ return parent.openDir(io, name, .{ .follow_symlinks = false });+}++fn directory(io: Io, session: []const u8, create: bool) !Io.Dir {+ const graff = try openChild(io, .cwd(), ".graff", create);+ defer graff.close(io);+ const sessions = try openChild(io, graff, "sessions", create);+ defer sessions.close(io);+ const session_dir = try openChild(io, sessions, session, create);+ defer session_dir.close(io);+ return openChild(io, session_dir, "compaction", create);+}++/// Move ONLY the checkpoint subtree when the root session acquires its AI+/// title. No history/name mutation here. Existing destinations are never+/// replaced, even when empty or created concurrently. Fork/save-as needs a+/// separate copy policy: moving these checkpoints would strand the source.+pub fn rename(self: *Agent, old_name: []const u8, new_name: []const u8) !void {+ if (self.sub or old_name.len == 0) return;+ if (!safeSessionName(old_name) or !safeSessionName(new_name)) return error.UnsafeCheckpointSession;+ if (std.mem.eql(u8, old_name, new_name)) return;+ const graff = openChild(self.io, .cwd(), ".graff", false) catch |err| {+ if (err == error.FileNotFound) return;+ return err;+ };+ defer graff.close(self.io);+ const sessions = openChild(self.io, graff, "sessions", false) catch |err| {+ if (err == error.FileNotFound) return;+ return err;+ };+ defer sessions.close(self.io);+ const old_dir = openChild(self.io, sessions, old_name, false) catch |err| {+ if (err == error.FileNotFound) return;+ return err;+ };+ defer old_dir.close(self.io);+ const source = openChild(self.io, old_dir, "compaction", false) catch |err| {+ if (err == error.FileNotFound) return;+ return err;+ };+ defer source.close(self.io);+ const new_dir = try openChild(self.io, sessions, new_name, true);+ defer new_dir.close(self.io);+ try old_dir.renamePreserve("compaction", new_dir, "compaction", self.io);+ // If durability fails, retain the old name's mapping when rollback is+ // possible. Never overwrite a concurrently installed mapping on rollback.+ errdefer new_dir.renamePreserve("compaction", old_dir, "compaction", self.io) catch {};+ try syncDirectory(self.io, new_dir);+ try syncDirectory(self.io, old_dir);+}++fn readBounded(io: Io, dir: Io.Dir, a: Allocator, name: []const u8) ![]u8 {+ const file = try dir.openFile(io, name, .{ .follow_symlinks = false, .resolve_beneath = true });+ defer file.close(io);+ const stat = try file.stat(io);+ if (stat.kind != .file or stat.size > max_checkpoint_bytes) return error.InvalidCheckpointFile;+ if (builtin.os.tag != .windows and (stat.permissions.toMode() & 0o077) != 0) return error.InsecureCheckpointFile;+ const bytes = try a.alloc(u8, @intCast(stat.size));+ errdefer a.free(bytes);+ if (try file.readPositionalAll(io, bytes, 0) != bytes.len) return error.TruncatedCheckpoint;+ const after = try file.stat(io);+ if (after.kind != .file or after.size != stat.size) return error.CheckpointChanged;+ return bytes;+}++fn syncDirectory(io: Io, dir: Io.Dir) !void {+ if (builtin.os.tag == .windows) return;+ const file = try dir.openFile(io, ".", .{ .allow_directory = true, .follow_symlinks = false, .resolve_beneath = true });+ defer file.close(io);+ try file.sync(io);+}++fn filename(buf: []u8, digest: []const u8) ![]const u8 {+ return std.fmt.bufPrint(buf, "{s}.json", .{digest});+}++fn containsBlob(a: Allocator, items: []const Value, digest: []const u8) !bool {+ for (items) |item| {+ if (windows.latestBlob(&.{item}) == null) continue;+ const existing = try valueHash(a, item);+ if (std.mem.eql(u8, &existing, digest)) return true;+ }+ return false;+}++/// Call BEFORE replacing history. A duplicate blob is not sufficient evidence+/// of identical ancestry: the complete immutable payload must also agree.+/// Non-durable test/auxiliary agents and subagents have no root-session mapping.+pub fn preserve(self: *Agent, before: []const Value, window: []const Value) !void {+ if (self.sub or self.session_name.len == 0) return;+ if (!safeSessionName(self.session_name)) return error.UnsafeCheckpointSession;+ const k = windows.latestBlob(window) orelse return error.MissingCompactionItem;+ const digest = try valueHash(self.gpa, window[k]);+ if (try containsBlob(self.gpa, before, &digest)) return error.NonExpandingCheckpoint;+ const history_digest = try valueHash(self.gpa, Payload{ .before = before, .window = window });+ const bytes = try std.json.Stringify.valueAlloc(self.gpa, Snapshot{+ .version = 1,+ .blob_sha256 = &digest,+ .history_sha256 = &history_digest,+ .before = before,+ .window = window,+ }, .{});+ defer self.gpa.free(bytes);+ if (bytes.len > max_checkpoint_bytes) return error.CheckpointTooLarge;+ const dir = try directory(self.io, self.session_name, true);+ defer dir.close(self.io);+ var name_buf: [69]u8 = undefined;+ const name = try filename(&name_buf, &digest);+ var atomic = try dir.createFileAtomic(self.io, name, .{ .permissions = private_file, .replace = false });+ defer atomic.deinit(self.io);+ try atomic.file.writeStreamingAll(self.io, bytes);+ try atomic.file.sync(self.io);+ atomic.link(self.io) catch |err| switch (err) {+ error.PathAlreadyExists => {+ const existing = try readBounded(self.io, dir, self.gpa, name);+ defer self.gpa.free(existing);+ if (!std.mem.eql(u8, existing, bytes)) return error.ImmutableCheckpointConflict;+ },+ else => return err,+ };+ try syncDirectory(self.io, dir);+}++fn sameValues(a: Allocator, lhs: []const Value, rhs: []const Value) !bool {+ const left = try std.json.Stringify.valueAlloc(a, lhs, .{});+ defer a.free(left);+ const right = try std.json.Stringify.valueAlloc(a, rhs, .{});+ defer a.free(right);+ return std.mem.eql(u8, left, right);+}++/// Expands exactly the newest opaque item, preserving its entire later tail.+/// Missing, unsafe, corrupt or changed checkpoints never change live history.+/// Allocation failures propagate; callers may bound repeated ancestor restores.+/// Only messages/provenance change here; the root recovery coordinator must+/// closeCodexWs and reset meters, goal fingerprint and history_rewrites.+pub fn restore(self: *Agent) !bool {+ if (self.sub or self.session_name.len == 0 or !safeSessionName(self.session_name)) return false;+ const latest = windows.latestBlob(self.messages.items) orelse return false;+ const digest = try valueHash(self.gpa, self.messages.items[latest]);+ const dir = directory(self.io, self.session_name, false) catch return false;+ defer dir.close(self.io);+ var name_buf: [69]u8 = undefined;+ const name = try filename(&name_buf, &digest);+ const bytes = readBounded(self.io, dir, self.gpa, name) catch |err| {+ if (err == error.OutOfMemory) return err;+ return false;+ };+ defer self.gpa.free(bytes);+ var parsed = std.json.parseFromSlice(Snapshot, self.gpa, bytes, .{ .allocate = .alloc_always }) catch |err| {+ if (err == error.OutOfMemory) return err;+ return false;+ };+ defer parsed.deinit();+ const saved = parsed.value;+ if (saved.version != 1 or !std.mem.eql(u8, saved.blob_sha256, &digest)) return false;+ const blob = windows.latestBlob(saved.window) orelse return false;+ const saved_digest = try valueHash(self.gpa, saved.window[blob]);+ if (!std.mem.eql(u8, &saved_digest, &digest)) return false;+ const history_digest = try valueHash(self.gpa, Payload{ .before = saved.before, .window = saved.window });+ if (!std.mem.eql(u8, saved.history_sha256, &history_digest)) return false;+ if (try containsBlob(self.gpa, saved.before, &digest)) return false;+ // Canonical windows may retain items on BOTH sides of the blob. Match+ // the whole prefix, not merely the blob, and never guess about prepends.+ if (latest != blob or saved.window.len > self.messages.items.len) return false;+ if (!try sameValues(self.gpa, saved.window, self.messages.items[0..saved.window.len])) return false;++ // Stage every fallible allocation before installing. Parsed values belong+ // to the temporary parser arena; transfer via an owned session-arena copy.+ var staged = std.json.Array.init(self.gpa);+ defer staged.deinit();+ try staged.appendSlice(saved.before);+ try staged.appendSlice(self.messages.items[saved.window.len..]);+ const encoded = try std.json.Stringify.valueAlloc(self.gpa, staged.items, .{});+ defer self.gpa.free(encoded);+ const fresh = try std.json.parseFromSliceLeaky(Value, self.arena, encoded, .{ .allocate = .alloc_always });+ self.messages = fresh.array;+ self.compaction_window = .{};+ return true;+}diff --git a/src/compaction_checkpoint_tests.zig b/src/compaction_checkpoint_tests.zignew file mode 100644index 00000000..20debe80--- /dev/null+++ b/src/compaction_checkpoint_tests.zig@@ -0,0 +1,376 @@+//! Verbatim checkpoint regressions; imported by the main unit-test root.+const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;+const Value = std.json.Value;+const Agent = @import("agent.zig").Agent;+const checkpoint = @import("compaction_checkpoint.zig");+const io = std.testing.io;++const Fixture = struct {+ arena: std.heap.ArenaAllocator,+ name: [48]u8,++ fn init() !Fixture {+ var raw: [16]u8 = undefined;+ try io.randomSecure(&raw);+ const hex = std.fmt.bytesToHex(raw, .lower);+ var f: Fixture = .{ .arena = .init(std.testing.allocator), .name = undefined };+ @memcpy(f.name[0..16], "checkpoint-test-");+ @memcpy(f.name[16..], &hex);+ return f;+ }++ fn deinit(f: *Fixture) void {+ var buf: [128]u8 = undefined;+ const session_path = std.fmt.bufPrint(&buf, ".graff/sessions/{s}", .{f.name}) catch unreachable;+ Io.Dir.cwd().deleteTree(io, session_path) catch {};+ f.arena.deinit();+ }++ fn agent(f: *Fixture) Agent {+ var agent_: Agent = undefined;+ agent_.gpa = f.arena.allocator();+ agent_.arena = f.arena.allocator();+ agent_.io = io;+ agent_.sub = false;+ agent_.session_name = &f.name;+ agent_.messages = std.json.Array.init(agent_.arena);+ agent_.compaction_window = .{};+ return agent_;+ }++ fn values(f: *Fixture, json: []const u8) ![]Value {+ return (try std.json.parseFromSliceLeaky(Value, f.arena.allocator(), json, .{ .allocate = .alloc_always })).array.items;+ }++ fn path(f: *Fixture, blob: Value) ![]const u8 {+ const a = f.arena.allocator();+ const bytes = try std.json.Stringify.valueAlloc(a, blob, .{});+ var digest: [32]u8 = undefined;+ std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{});+ const hex = std.fmt.bytesToHex(digest, .lower);+ return std.fmt.allocPrint(a, ".graff/sessions/{s}/compaction/{s}.json", .{ f.name, hex });+ }+};++const window_json = "[{\"type\":\"compaction\",\"encrypted_content\":\"opaque-test\"}]";++fn expectJson(expected: []const u8, values: []const Value) !void {+ const bytes = try std.json.Stringify.valueAlloc(std.testing.allocator, values, .{});+ defer std.testing.allocator.free(bytes);+ try std.testing.expectEqualStrings(expected, bytes);+}++test "compaction checkpoint restores verbatim prior history plus later tail" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const before = try f.values("[{\"role\":\"user\",\"content\":\"verbatim \\n λ\"},{\"type\":\"function_call\",\"arguments\":\"{\\\"x\\\":1}\"},{\"type\":\"function_call_output\",\"output\":\"untouched\"}]");+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, before, window);+ try agent.messages.appendSlice(window);+ try agent.messages.appendSlice(try f.values("[{\"role\":\"user\",\"content\":\"later\"}]"));+ try std.testing.expect(try checkpoint.restore(&agent));+ try expectJson("[{\"role\":\"user\",\"content\":\"verbatim \\n λ\"},{\"type\":\"function_call\",\"arguments\":\"{\\\"x\\\":1}\"},{\"type\":\"function_call_output\",\"output\":\"untouched\"},{\"role\":\"user\",\"content\":\"later\"}]", agent.messages.items);+ try std.testing.expect(agent.compaction_window.canonical_blob == null);+}++test "compaction checkpoint matches entire canonical standalone window" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const before = try f.values("[\"prior\"]");+ const window = try f.values("[\"retained prefix\",{\"type\":\"compaction_summary\",\"encrypted_content\":\"canonical\"},\"retained suffix\"]");+ try checkpoint.preserve(&agent, before, window);+ try agent.messages.appendSlice(window);+ try agent.messages.append(.{ .string = "later" });+ try std.testing.expect(try checkpoint.restore(&agent));+ try expectJson("[\"prior\",\"later\"]", agent.messages.items);+}++test "compaction checkpoint refuses prepended or changed canonical items" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const before = try f.values("[\"prior\"]");+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, before, window);+ try agent.messages.append(.{ .string = "unexpected prefix" });+ try agent.messages.appendSlice(window);+ const ptr = agent.messages.items.ptr;+ try std.testing.expect(!try checkpoint.restore(&agent));+ try std.testing.expectEqual(ptr, agent.messages.items.ptr);+ try expectJson("[\"unexpected prefix\",{\"type\":\"compaction\",\"encrypted_content\":\"opaque-test\"}]", agent.messages.items);++ const canonical = try f.values("[\"retained\",{\"type\":\"compaction\",\"encrypted_content\":\"other\"},\"suffix\"]");+ try checkpoint.preserve(&agent, before, canonical);+ agent.messages = std.json.Array.fromOwnedSlice(agent.arena, try agent.arena.dupe(Value, canonical));+ agent.messages.items[0] = .{ .string = "changed" };+ try std.testing.expect(!try checkpoint.restore(&agent));+ try std.testing.expectEqualStrings("changed", agent.messages.items[0].string);+ agent.messages.items[0] = canonical[0];+ agent.messages.items.len = 2;+ try std.testing.expect(!try checkpoint.restore(&agent));+}++test "compaction checkpoint missing and corrupt files leave history untouched" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const window = try f.values(window_json);+ try agent.messages.appendSlice(window);+ const ptr = agent.messages.items.ptr;+ try std.testing.expect(!try checkpoint.restore(&agent));+ try checkpoint.preserve(&agent, try f.values("[\"prior\"]"), window);+ const path = try f.path(window[0]);+ for ([_][]const u8{ "", "{", "{}", "{\"version\":1,\"before\":[", "null", "[]" }) |bad| {+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = bad });+ try std.testing.expect(!try checkpoint.restore(&agent));+ try std.testing.expectEqual(ptr, agent.messages.items.ptr);+ try expectJson(window_json, agent.messages.items);+ }+}++test "compaction checkpoint verifies history checksum and blob identity" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, try f.values("[\"prior\"]"), window);+ try agent.messages.appendSlice(window);+ const path = try f.path(window[0]);+ const original = try Io.Dir.cwd().readFileAlloc(io, path, f.arena.allocator(), .limited(checkpoint.max_checkpoint_bytes));+ const changed = try f.arena.allocator().dupe(u8, original);+ const index = std.mem.indexOf(u8, changed, "prior").?;+ changed[index] = 'X';+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = changed });+ try std.testing.expect(!try checkpoint.restore(&agent));+ @memcpy(changed, original);+ const blob_index = std.mem.indexOf(u8, changed, "opaque-test").?;+ changed[blob_index] = 'X';+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = changed });+ try std.testing.expect(!try checkpoint.restore(&agent));+ try expectJson(window_json, agent.messages.items);+}++test "compaction checkpoint immutable identity also binds complete ancestry" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const before = try f.values("[\"original\"]");+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, before, window);+ try checkpoint.preserve(&agent, before, window);+ try std.testing.expectError(error.ImmutableCheckpointConflict, checkpoint.preserve(&agent, try f.values("[\"different\"]"), window));+ try agent.messages.appendSlice(window);+ try std.testing.expect(try checkpoint.restore(&agent));+ try expectJson("[\"original\"]", agent.messages.items);+ try std.testing.expectError(error.NonExpandingCheckpoint, checkpoint.preserve(&agent, window, window));+}++test "compaction checkpoint unsafe session names and nondurable agents fail closed" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const window = try f.values(window_json);+ try agent.messages.appendSlice(window);+ for ([_][]const u8{ "..", "../escape", "a/b", "a\\b", "/absolute", ".hidden", "x\x00y", "x\ny" }) |name| {+ agent.session_name = name;+ try std.testing.expectError(error.UnsafeCheckpointSession, checkpoint.preserve(&agent, &.{}, window));+ try std.testing.expect(!try checkpoint.restore(&agent));+ }+ agent.session_name = "";+ try checkpoint.preserve(&agent, &.{}, window);+ try std.testing.expect(!try checkpoint.restore(&agent));+ agent.session_name = &f.name;+ agent.sub = true;+ try checkpoint.preserve(&agent, &.{}, window);+ try std.testing.expect(!try checkpoint.restore(&agent));+ try expectJson(window_json, agent.messages.items);+}++test "compaction checkpoint ignores symlinked session directory" {+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, try f.values("[\"prior\"]"), window);+ try agent.messages.appendSlice(window);+ const session_path = try std.fmt.allocPrint(agent.arena, ".graff/sessions/{s}", .{f.name});+ try Io.Dir.cwd().deleteTree(io, session_path);+ // A link to an existing cwd directory is rejected too: no redirected IO.+ try Io.Dir.cwd().symLink(io, ".", session_path, .{ .is_directory = true });+ defer Io.Dir.cwd().deleteFile(io, session_path) catch {};+ var rejected = false;+ checkpoint.preserve(&agent, try f.values("[\"prior\"]"), window) catch {+ rejected = true;+ };+ try std.testing.expect(rejected);+ try std.testing.expect(!try checkpoint.restore(&agent));+ try expectJson(window_json, agent.messages.items);+}++test "compaction checkpoint supports bounded expansion through actual ancestors" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const first = try f.values(window_json);+ const second = try f.values("[{\"type\":\"compaction\",\"encrypted_content\":\"newer\"}]");+ try checkpoint.preserve(&agent, try f.values("[\"original\"]"), first);+ var ancestor = std.json.Array.init(agent.arena);+ try ancestor.appendSlice(first);+ try ancestor.append(.{ .string = "between" });+ try checkpoint.preserve(&agent, ancestor.items, second);+ try agent.messages.appendSlice(second);+ try agent.messages.append(.{ .string = "tail" });+ try std.testing.expect(try checkpoint.restore(&agent));+ try std.testing.expect(try checkpoint.restore(&agent));+ try std.testing.expect(!try checkpoint.restore(&agent));+ try expectJson("[\"original\",\"between\",\"tail\"]", agent.messages.items);+}++test "compaction checkpoint restores fresh Agent from saved history without original memory" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, try f.values("[\"prior\"]"), window);+ try agent.messages.appendSlice(window);+ try agent.messages.append(.{ .string = "saved tail" });+ const saved = try std.json.Stringify.valueAlloc(std.testing.allocator, agent.messages.items, .{});+ defer std.testing.allocator.free(saved);+ const path = try std.fmt.allocPrint(agent.arena, ".graff/sessions/{s}/resume.json", .{f.name});+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = saved });+ var reloaded_arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer reloaded_arena.deinit();+ const a = reloaded_arena.allocator();+ const bytes = try Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1024));+ var reloaded = f.agent();+ reloaded.gpa = a;+ reloaded.arena = a;+ reloaded.messages = (try std.json.parseFromSliceLeaky(Value, a, bytes, .{ .allocate = .alloc_always })).array;+ // Destroy all original message/snapshot memory, not just the Agent value.+ f.arena.deinit();+ f.arena = .init(std.testing.allocator);+ try std.testing.expect(try checkpoint.restore(&reloaded));+ try expectJson("[\"prior\",\"saved tail\"]", reloaded.messages.items);+ // The parsed checkpoint's temporary arena has been released already.+ try reloaded.messages.append(.{ .string = "still owned" });+ try expectJson("[\"prior\",\"saved tail\",\"still owned\"]", reloaded.messages.items);+}++test "compaction checkpoint oversized file is rejected before loading" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, try f.values("[\"prior\"]"), window);+ try agent.messages.appendSlice(window);+ const file = try Io.Dir.cwd().openFile(io, try f.path(window[0]), .{ .mode = .read_write });+ defer file.close(io);+ try file.setLength(io, checkpoint.max_checkpoint_bytes + 1);+ try std.testing.expect(!try checkpoint.restore(&agent));+ try expectJson(window_json, agent.messages.items);+}++test "compaction checkpoint private snapshot and worker isolation" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, try f.values("[\"root prior\"]"), window);+ const stat = try Io.Dir.cwd().statFile(io, try f.path(window[0]), .{});+ if (builtin.os.tag != .windows) try std.testing.expectEqual(@as(u32, 0o600), @as(u32, @intCast(stat.permissions.toMode() & 0o777)));+ var child = f.agent();+ child.sub = true;+ try checkpoint.preserve(&child, try f.values("[\"worker prior\"]"), window);+ try agent.messages.appendSlice(window);+ try std.testing.expect(try checkpoint.restore(&agent));+ try expectJson("[\"root prior\"]", agent.messages.items);+}++test "compaction checkpoint never skips an unmatched newest opaque item" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, try f.values("[\"prior\"]"), window);+ try agent.messages.appendSlice(window);+ try agent.messages.appendSlice(try f.values("[{\"type\":\"compaction\",\"encrypted_content\":\"missing-newer\"}]"));+ const ptr = agent.messages.items.ptr;+ try std.testing.expect(!try checkpoint.restore(&agent));+ try std.testing.expectEqual(ptr, agent.messages.items.ptr);+ try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);+}++test "compaction checkpoint rename moves only checkpoints and preserves recovery" {+ var f = try Fixture.init();+ defer f.deinit();+ var titled = try Fixture.init();+ defer titled.deinit();+ var agent = f.agent();+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, try f.values("[\"prior\"]"), window);+ const marker_path = try std.fmt.allocPrint(agent.arena, ".graff/sessions/{s}/artifact", .{f.name});+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = marker_path, .data = "leave in place" });+ try checkpoint.rename(&agent, &f.name, &titled.name);+ try std.testing.expectEqualStrings(&f.name, agent.session_name);+ const marker = try Io.Dir.cwd().readFileAlloc(io, marker_path, agent.arena, .limited(100));+ try std.testing.expectEqualStrings("leave in place", marker);+ agent.session_name = &titled.name;+ try agent.messages.appendSlice(window);+ try std.testing.expect(try checkpoint.restore(&agent));+ try expectJson("[\"prior\"]", agent.messages.items);+}++test "compaction checkpoint rename existing destination keeps both ancestries" {+ var f = try Fixture.init();+ defer f.deinit();+ var other = try Fixture.init();+ defer other.deinit();+ var agent = f.agent();+ var destination = other.agent();+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, try f.values("[\"first ancestry\"]"), window);+ try checkpoint.preserve(&destination, try f.values("[\"second ancestry\"]"), window);+ var rejected = false;+ checkpoint.rename(&agent, &f.name, &other.name) catch {+ rejected = true;+ };+ try std.testing.expect(rejected);+ try agent.messages.appendSlice(window);+ try destination.messages.appendSlice(window);+ try std.testing.expect(try checkpoint.restore(&agent));+ try std.testing.expect(try checkpoint.restore(&destination));+ try expectJson("[\"first ancestry\"]", agent.messages.items);+ try expectJson("[\"second ancestry\"]", destination.messages.items);+}++test "compaction checkpoint rename absent source is harmless and unsafe names fail" {+ var f = try Fixture.init();+ defer f.deinit();+ var other = try Fixture.init();+ defer other.deinit();+ var agent = f.agent();+ try checkpoint.rename(&agent, &f.name, &other.name);+ try std.testing.expectError(error.UnsafeCheckpointSession, checkpoint.rename(&agent, "../escape", &other.name));+ try std.testing.expectError(error.UnsafeCheckpointSession, checkpoint.rename(&agent, &f.name, "../escape"));+ try checkpoint.rename(&agent, &f.name, &f.name);+}++test "compaction checkpoint allocation failure never installs partial history" {+ var f = try Fixture.init();+ defer f.deinit();+ var agent = f.agent();+ const window = try f.values(window_json);+ try checkpoint.preserve(&agent, try f.values("[\"prior\"]"), window);+ try agent.messages.appendSlice(window);+ const ptr = agent.messages.items.ptr;+ var failing = std.testing.FailingAllocator.init(agent.arena, .{ .fail_index = 0 });+ agent.arena = failing.allocator();+ try std.testing.expectError(error.OutOfMemory, checkpoint.restore(&agent));+ try std.testing.expectEqual(ptr, agent.messages.items.ptr);+ try expectJson(window_json, agent.messages.items);+}diff --git a/src/compaction_window.zig b/src/compaction_window.zigindex e59f8a67..e3e1f113 100644--- a/src/compaction_window.zig+++ b/src/compaction_window.zig@@ -17,14 +17,14 @@ pub fn latestBlob(items: []const Value) ?usize {}/// The provider could not consume its opaque compaction state. A chained-/// request may re-anchor once with full input; an unchained rejection is-/// terminal for that context and must not enter a generic retry ladder.+/// request may re-anchor once with full input, then restore an exact local+/// checkpoint. Without one it must not enter a generic retry ladder.pub fn rejectedByProvider(message: []const u8, code: ?[]const u8) bool {if (code) |c| return std.ascii.eqlIgnoreCase(c, "invalid_encrypted_content");return std.mem.indexOf(u8, message, "invalid_encrypted_content") != null;}-pub const rejection_hint = " — history is unchanged; retrying the same encrypted compaction state will not recover it. Start a new session or restore an earlier saved session.";+pub const rejection_hint = " — history is unchanged; no usable pre-compaction checkpoint was available within the recovery limit. Retrying the same encrypted state will not recover it. Restore an earlier saved session or start a new session.";fn fingerprint(a: Allocator, item: Value) ![32]u8 {const bytes = try std.json.Stringify.valueAlloc(a, item, .{});diff --git a/src/http.zig b/src/http.zigindex 5a403f82..6f46bc6a 100644--- a/src/http.zig+++ b/src/http.zig@@ -246,6 +246,10 @@ pub var head_stall_ms: u64 = 30 * 1000;/// dead pooled connection could fail all 6 tries). 429/5xx throttles keep their longer/// server-directed waits.pub const RetryPlan = struct {+ /// #1826: only rotated request-construction TLS failures: 15 waits, 47.75s base+ /// (at most ~60s with jitter), still interruptible. Never shared with 429/auth/read failures.+ pub const tls_construction_attempts: usize = 16;+/// Total attempts before the turn gives up.pub fn maxAttempts(throttled: bool) usize {return if (throttled) 5 else 6;diff --git a/src/http_client_integration_tests.zig b/src/http_client_integration_tests.zigindex 7340b108..8ce00b2b 100644--- a/src/http_client_integration_tests.zig+++ b/src/http_client_integration_tests.zig@@ -18,6 +18,7 @@ pub const Reply = struct {status: []const u8 = "200 OK",content_type: []const u8 = "application/json",body: []const u8,+ fail_tls_through_generation: ?u64 = null,};pub const chat_body =@@ -72,6 +73,7 @@ pub fn serveReplies(io: Io, server: *std.Io.net.Server, replies: []const Reply,_ = accepted.fetchAdd(1, .acq_rel);const reply = replies[served];served += 1;+ if (reply.fail_tls_through_generation) |last| http_client.injectConstructionTlsThroughGenerationForTest(last);var head_buf: [256]u8 = undefined;const head = std.fmt.bufPrint(&head_buf,@@ -345,12 +347,13 @@ test "later root and child recover after the retry ladder exhausts TLS generatioroot.label = "test-root";root.out = &output.writer;root.tracer = &tracer;- http_client.injectConstructionTlsThroughGenerationForTest(5);+ const limit = http.RetryPlan.tls_construction_attempts;+ http_client.injectConstructionTlsThroughGenerationForTest(limit - 1);try std.testing.expectError(error.ApiError, root.request(null));try std.testing.expectEqual(@as(usize, 0), accepted.load(.acquire));- try std.testing.expectEqual(@as(u64, 6), runtime.recovery.stats().active_id);- try std.testing.expectEqual(@as(usize, 6), std.mem.count(u8, trace_output.written(), "\"ev\":\"tls_request_construction\""));- try std.testing.expect(std.mem.indexOf(u8, root.last_api_error.?, "gave up after 6 attempts") != null);+ try std.testing.expectEqual(@as(u64, limit), runtime.recovery.stats().active_id);+ try std.testing.expectEqual(limit, std.mem.count(u8, trace_output.written(), "\"ev\":\"tls_request_construction\""));+ try std.testing.expect(std.mem.indexOf(u8, root.last_api_error.?, "gave up after 16 attempts") != null);_ = try root.request(null);try std.testing.expect(std.mem.indexOf(u8, output.written(), "root-ok") != null);diff --git a/src/main.zig b/src/main.zigindex beacc7c8..d199e74a 100644--- a/src/main.zig+++ b/src/main.zig@@ -567,7 +567,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = .{ @import("repo_map.zig"), @import("cli_text.zig") };_ = @import("agent_overflow_tests.zig"); // #414: and, through it, agent_overflow.zig's table tests_ = @import("agent_gateway_retry.zig"); // #1019: flake vs overflow classification must stay reachable- _ = @import("agent_responses.zig"); // #1019: type:error frame message extraction+ _ = .{ @import("agent_responses.zig"), @import("compaction_checkpoint_tests.zig") }; // Responses failures and exact checkpoint recovery_ = @import("agent_server_compact.zig"); // server-side autocompact (codex Responses)_ = .{ @import("compact_status.zig"), @import("compact_mix.zig"), @import("compact_backoff.zig") }; // compact status + GRAFF_COMPACT_MIX mixture arm + #1686 backoff_ = .{ @import("agent_clef_compact.zig"), @import("agent_clef_compact_tests.zig"), @import("agent_clef_archive.zig") }; // gateway /v1/compact client (Clef pruning) + archive mode@@ -576,7 +576,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("agent_ws_steer.zig");_ = @import("agent_ws_signal.zig");_ = .{ @import("agent_ws_prewarm.zig"), @import("agent_ws_headers.zig") };- _ = .{ @import("http2_pool.zig"), @import("agent_stream_h2.zig"), @import("agent_stream_h2_transport_test.zig"), @import("agent_stream_progress_test.zig"), @import("agent_stream_h2_progress_test.zig"), @import("stream_read_progress.zig"), @import("http_send.zig"), @import("http_send_test.zig") }; // transport contracts, partial-event byte progress, staged send budgets+ _ = .{ @import("http2_pool.zig"), @import("agent_stream_h2.zig"), @import("agent_stream_h2_transport_test.zig"), @import("agent_stream_progress_test.zig"), @import("agent_stream_h2_progress_test.zig"), @import("stream_read_progress.zig"), @import("http_send.zig"), @import("http_send_test.zig"), @import("agent_tls_retry_tests.zig") }; // transport contracts, partial-event byte progress, staged send budgets_ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root_ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_session_load.zig"), @import("acp_session_fork.zig"), @import("session_fork.zig"), @import("acp_elicit.zig"), @import("hot_context.zig"), @import("history_translate.zig"), @import("mcp_notify.zig"), @import("mcp_wait.zig"), @import("mcp_pages.zig"), @import("mcp_mrtr.zig"), @import("ask_user_args.zig"), @import("mcp_add.zig"), @import("mcp_lazy.zig"), @import("mcp_share.zig"), @import("acp_room.zig"), @import("mcp_catalog.zig"), @import("mcp_watch.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig"), @import("ask_user_answers.zig"), @import("job_class.zig"), @import("startup_claim.zig") };_ = @import("task_outcome.zig"); // goal-outcome telemetry eventsdiff --git a/src/session.zig b/src/session.zigindex 14d4479d..91ab49b7 100644--- a/src/session.zig+++ b/src/session.zig@@ -94,7 +94,9 @@ pub fn renameSession(root: *Agent, arena: Allocator, slug: []const u8) void {} else |_| break; // free}const old_name = root.session_name;- root.session_name = arena.dupe(u8, name) catch return;+ const next_name = arena.dupe(u8, name) catch return;+ @import("compaction_checkpoint.zig").rename(root, old_name, next_name) catch return;+ root.session_name = next_name;@import("subagent_interactive.zig").rename(root.io, old_name, root.session_name);saveSession(root, arena, root.session_name) catch {};if (sessionPath(arena, old_name)) |op| (Io.Dir.cwd().deleteFile(root.io, op) catch {}) else |_| {}