graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(compact): no note when the harness is salvaging, not rolling over
Rach Pradhan232f092ce60e
diff --git a/scripts/codex_ws_test.py b/scripts/codex_ws_test.pyindex a48a5ee3..74defd37 100644--- a/scripts/codex_ws_test.py+++ b/scripts/codex_ws_test.py@@ -44,6 +44,39 @@ TRANSACTIONAL_FINAL = "done after transactional compaction failure"TRANSACTIONAL_REASONING_MARKER = "transactional-active-reasoning:"TRANSACTIONAL_CALL_ID = "call_transactional_1"+# #391: compaction now spends one extra quiet turn writing a note to self+# before the summary. Both synthetic turns are identified by the head of their+# instruction so the fixtures below can be keyed on CONTENT rather than on a+# request ordinal — see midturn_events for why that matters.+NOTE_INSTRUCTION_HEAD = "Your context is about to be compacted"+COMPACT_INSTRUCTION_HEAD = "Summarize this entire conversation"+NOTE_BLOCK_HEADER = "NOTES TO SELF"+MIDTURN_NOTE = (+ "SUBGOAL: exercise the server-side context meter\n"+ "ANCHORS: src/agent_compact.zig:130\n"+ "DEAD ENDS: none yet"+)+TRANSACTIONAL_NOTE = (+ "SUBGOAL: prove the transactional rollback\nANCHORS: src/agent_compact.zig:152"+)+++def user_text(item: object) -> str | None:+ if not isinstance(item, dict) or item.get("role") != "user":+ return None+ content = item.get("content")+ return content if isinstance(content, str) else None+++def last_user_text(request: RecordedRequest) -> str:+ """The final user turn of a Responses request, or "" — how the two+ synthetic compaction turns are told apart without counting ordinals."""+ for item in reversed(request.body.get("input") or []):+ text = user_text(item)+ if text is not None:+ return text+ return ""+def response_events(item: dict | list[dict], response_id: str, total_tokens: int@@ -95,7 +128,28 @@ def active_reasoning_item() -> dict:def midturn_events(request: RecordedRequest) -> list[dict]:- """Script tool call -> compaction summary -> final answer."""+ """Script tool call -> #391 note to self -> compaction summary -> answer.++ Keyed on the request's LAST USER TURN, not on its ordinal. Compaction+ gained a step in #391, and an ordinal-keyed fixture re-targets silently+ when that happens: the summary reply lands on the note turn, the note reply+ becomes the handoff summary, and the scenario still goes green while+ proving something else entirely. Content keying makes the fixture describe+ what each reply is FOR.+ """+ tail = last_user_text(request)+ if tail.startswith(NOTE_INSTRUCTION_HEAD):+ return response_events(+ message_item(MIDTURN_NOTE, "msg_midturn_note"),+ "resp_midturn_note",+ 1_050,+ )+ if tail.startswith(COMPACT_INSTRUCTION_HEAD):+ return response_events(+ message_item(MIDTURN_SUMMARY, "msg_midturn_summary"),+ "resp_midturn_summary",+ 1_100,+ )if request.ordinal == 1:item = {"type": "function_call",@@ -114,12 +168,6 @@ def midturn_events(request: RecordedRequest) -> list[dict]:"resp_midturn_1",MIDTURN_TOTAL_TOKENS,)- if request.ordinal == 2:- return response_events(- message_item(MIDTURN_SUMMARY, "msg_midturn_summary"),- "resp_midturn_summary",- 1_100,- )return response_events(message_item(MIDTURN_FINAL, "msg_midturn_final"),f"resp_midturn_{request.ordinal}",@@ -140,7 +188,25 @@ def transactional_reasoning_item() -> dict:def transactional_events(request: RecordedRequest) -> list[dict]:- """Script tool call -> empty summary -> answer from restored live history."""+ """Script tool call -> note to self -> EMPTY summary -> answer from the+ restored live history. Content-keyed for the same reason midturn_events is:+ the empty reply has to land on the SUMMARY request specifically, and an+ ordinal would have quietly moved it onto the #391 note turn instead."""+ tail = last_user_text(request)+ if tail.startswith(NOTE_INSTRUCTION_HEAD):+ return response_events(+ message_item(TRANSACTIONAL_NOTE, "msg_transactional_note"),+ "resp_transactional_note",+ 1_050,+ )+ if tail.startswith(COMPACT_INSTRUCTION_HEAD):+ # A syntactically valid Responses answer with no summary text exercises+ # compact()'s EmptySummary rollback, rather than a transport failure.+ return response_events(+ message_item("", "msg_transactional_empty_summary"),+ "resp_transactional_empty_summary",+ 1_100,+ )if request.ordinal == 1:call = {"type": "function_call",@@ -155,14 +221,6 @@ def transactional_events(request: RecordedRequest) -> list[dict]:"resp_transactional_1",MIDTURN_TOTAL_TOKENS,)- if request.ordinal == 2:- # A syntactically valid Responses answer with no summary text exercises- # compact()'s EmptySummary rollback, rather than a transport failure.- return response_events(- message_item("", "msg_transactional_empty_summary"),- "resp_transactional_empty_summary",- 1_100,- )return response_events(message_item(TRANSACTIONAL_FINAL, "msg_transactional_final"),f"resp_transactional_{request.ordinal}",@@ -170,13 +228,6 @@ def transactional_events(request: RecordedRequest) -> list[dict]:)-def user_text(item: object) -> str | None:- if not isinstance(item, dict) or item.get("role") != "user":- return None- content = item.get("content")- return content if isinstance(content, str) else None--def assert_compaction_meter(label: str, rendered: str) -> None:match = COMPACTING_RE.search(rendered)if match is None:@@ -273,22 +324,52 @@ def run_scenario(def assert_midturn_requests(mock: CodexMock) -> None:requests = mock.recorded_requests()- if len(requests) != 3:+ # Four, since #391: the real turn, the pre-compaction note-to-self, the+ # compaction summary, then the continuation. This scenario is a PLANNED+ # rollover by construction (the server meter is 90% — over compact@ 80%,+ # under the 95% recovery boundary; see MIDTURN_TOTAL_TOKENS above), which+ # is exactly the case #391's note fires on. On the salvage paths — a+ # provider over-window rejection, or >=95% where compactOrRecover may drop+ # real history — compact_note.decideContext refuses it and this stays three.+ if len(requests) != 4:raise AssertionError(- f"midturn: expected exactly 3 model requests, got {len(requests)}: {requests!r}"+ f"midturn: expected exactly 4 model requests, got {len(requests)}: {requests!r}")- first, compact, final = requests+ first, note, compact, final = requestsif any("max_output_tokens" in request.body for request in requests):raise AssertionError("midturn: Responses requests must omit max_output_tokens")transports = [request.transport for request in requests]- if transports != ["ws", "sse", "ws"]:- raise AssertionError(f"midturn: expected WS -> SSE -> WS, got {transports!r}")- if mock.ws_turns != 2 or mock.sse_turns != 1 or mock.ws_connections != 2:+ if transports != ["ws", "sse", "sse", "ws"]:+ raise AssertionError(+ f"midturn: expected WS -> SSE(note) -> SSE(summary) -> WS, got {transports!r}"+ )+ if mock.ws_turns != 2 or mock.sse_turns != 2 or mock.ws_connections != 2:raise AssertionError(- "midturn: expected two turns on two fresh WS connections plus one SSE "- f"turn; ws_turns={mock.ws_turns} sse_turns={mock.sse_turns} "+ "midturn: expected two turns on two fresh WS connections plus two quiet "+ f"SSE turns; ws_turns={mock.ws_turns} sse_turns={mock.sse_turns} "f"ws_connections={mock.ws_connections}")+ # The two synthetic turns are identified by CONTENT, not position, so this+ # cannot silently pass if their order ever swaps.+ if not last_user_text(note).startswith("Your context is about to be compacted"):+ raise AssertionError(+ f"midturn: request 2 is not the #391 note turn: {last_user_text(note)[:120]!r}"+ )+ if not last_user_text(compact).startswith("Summarize this entire conversation"):+ raise AssertionError(+ f"midturn: request 3 is not the compaction summary: {last_user_text(compact)[:120]!r}"+ )+ # #195's invariant, checked rather than assumed: the note turn is a quiet+ # SSE request that opens NO WebSocket. It runs inside runTurn's existing+ # closeCodexWs bracket, against a throwaway clone of history, so it must+ # not appear in the WS choreography at all — ws_connections stays 2 and+ # the post-compaction turn still re-anchors on a socket the pre-compaction+ # turn never used.+ if note.connection_id is not None:+ raise AssertionError(+ f"midturn: the note turn opened a WebSocket (conn {note.connection_id}); "+ "it must stay off the WS session it is compacting around"+ )if first.connection_id == final.connection_id:raise AssertionError("midturn: final request reused the pre-compaction WS")for request in requests:@@ -298,6 +379,39 @@ def assert_midturn_requests(mock: CodexMock) -> None:f"{request.body['previous_response_id']!r}")+ # The note turn is a bounded, tool-less auxiliary call on its own persona —+ # never the root prompt, which would hand it the whole tool catalog and its+ # own previous note.+ if "tools" in note.body or not str(note.body.get("instructions", "")).startswith(+ "You are writing a private note to your future self"+ ):+ raise AssertionError(+ f"midturn: the note turn was not the bounded tool-less persona call: {note.body!r}"+ )++ # #391 END TO END, on the wire. The note is written before the summary, so+ # every request AFTER it must carry it in `instructions` — the system+ # prompt, which compaction cannot rewrite — while the request before it+ # carries nothing.+ if NOTE_BLOCK_HEADER in str(first.body.get("instructions", "")):+ raise AssertionError("midturn: a note block existed before any note was written")+ for label, request in (("summary", compact), ("post-compaction", final)):+ instructions = str(request.body.get("instructions", ""))+ if NOTE_BLOCK_HEADER not in instructions or MIDTURN_NOTE not in instructions:+ raise AssertionError(+ f"midturn: the {label} request did not carry the note-to-self VERBATIM "+ f"in its system prompt: {instructions[-400:]!r}"+ )+ # …and it is STATE, not conversation: the post-compaction turn's history is+ # the handoff summary alone. If the note ever appears in `input` it has+ # become something a later compaction can summarize away.+ final_json = json.dumps(final.body.get("input") or [], separators=(",", ":"))+ if NOTE_BLOCK_HEADER in final_json or MIDTURN_NOTE in final_json:+ raise AssertionError(+ "midturn: the note leaked into conversation history, where the next "+ f"compaction would paraphrase it away: {final_json[:400]!r}"+ )+first_input = first.body.get("input")if (first.body.get("type") != "response.create"@@ -365,25 +479,38 @@ def assert_midturn_requests(mock: CodexMock) -> None:def assert_transactional_requests(mock: CodexMock) -> None:requests = mock.recorded_requests()- if len(requests) != 3:+ # Four since #391 — the note turn precedes the summary here too. The note+ # is written and kept even though this compaction then FAILS: it is state+ # about the live conversation, not about the summary, and the rollback+ # restores history the note still describes correctly.+ if len(requests) != 4:raise AssertionError(- "transactional: expected exactly 3 model requests, "+ "transactional: expected exactly 4 model requests, "f"got {len(requests)}: {requests!r}")- first, compact, final = requests+ first, note, compact, final = requestsif any("max_output_tokens" in request.body for request in requests):raise AssertionError("transactional: Responses requests must omit max_output_tokens")transports = [request.transport for request in requests]- if transports != ["ws", "sse", "ws"]:+ if transports != ["ws", "sse", "sse", "ws"]:raise AssertionError(- f"transactional: expected WS -> SSE -> WS, got {transports!r}"+ f"transactional: expected WS -> SSE(note) -> SSE(summary) -> WS, got {transports!r}")- if mock.ws_turns != 2 or mock.sse_turns != 1 or mock.ws_connections != 2:+ if mock.ws_turns != 2 or mock.sse_turns != 2 or mock.ws_connections != 2:raise AssertionError("transactional: expected two turns on two fresh WS connections plus "- f"one SSE turn; ws_turns={mock.ws_turns} sse_turns={mock.sse_turns} "+ f"two quiet SSE turns; ws_turns={mock.ws_turns} sse_turns={mock.sse_turns} "f"ws_connections={mock.ws_connections}")+ if not last_user_text(note).startswith(NOTE_INSTRUCTION_HEAD):+ raise AssertionError(+ f"transactional: request 2 is not the #391 note turn: {last_user_text(note)[:120]!r}"+ )+ if note.connection_id is not None or "tools" in note.body:+ raise AssertionError(+ "transactional: the note turn must be a tool-less SSE request that "+ f"opens no WebSocket: {note.body!r}"+ )if first.connection_id == final.connection_id:raise AssertionError("transactional: final request reused the pre-compaction WS"diff --git a/src/compact_note.zig b/src/compact_note.zigindex 36ec8fe2..7c357806 100644--- a/src/compact_note.zig+++ b/src/compact_note.zig@@ -109,6 +109,15 @@ pub const Decision = enum {skip_budget,/// No token buffer left for the note turn under this model's window.skip_no_headroom,+ /// The harness is SALVAGING, not rolling over. #391 is about a planned+ /// rollover: context is filling, so reserve a buffer and spend one call+ /// before the window turns over. Once the provider has actually rejected a+ /// request for exceeding the window, or the meter is at the destructive-+ /// recovery boundary where compactOrRecover may drop real history, the+ /// session has demonstrably run out of room — and spending a call there is+ /// the exact opposite of the budget discipline the rest of this file+ /// enforces. Recovery gets the tokens; the note waits for a calmer one.+ skip_recovering,/// The turn ran and produced nothing usable — a transport failure, an/// explicit "none", or a store that could not be written. Distinct from/// the gates above because this one COST a call; compaction proceeds@@ -151,19 +160,41 @@ pub fn decideCalls(in: Inputs) Decision {return .fire;}-/// The token half: is there room under the window for the note turn's reply?-/// An unknown window (0) cannot prove there is not, and the summary request-/// this precedes is about to ship the same input anyway.-pub fn decideRoom(window_tokens: u64, effective_tokens: u64) Decision {- if (window_tokens == 0) return .fire;- return if (effective_tokens +| note_reserve_tokens > window_tokens) .skip_no_headroom else .fire;+/// What the context looks like at the moment compaction was decided on.+pub const Context = struct {+ /// The model's advertised window; 0 when unknown.+ window_tokens: u64,+ /// Best current estimate of occupancy (Agent.effectiveContextTokens).+ effective_tokens: u64,+ /// The provider has already REJECTED a request for exceeding the window+ /// (Agent.last_request_context_overflow). Not a threshold reading — a+ /// concrete bounce off the wall.+ over_window_rejection: bool,+ /// The meter is at or past the destructive-recovery boundary, where+ /// compactOrRecover is authorized to drop real history+ /// (Provider.nearContextLimit, 95%).+ near_limit: bool,+};++/// The context half. Salvage is refused OUTRIGHT, before the buffer question+/// is even asked: at 95% the arithmetic still leaves room for the note under+/// the window, so a token buffer alone would happily fire one into a session+/// that is being rescued. The distinction that matters is not how many tokens+/// are left, it is whether this compaction is planned or a rescue.+///+/// An unknown window (0) cannot prove there is no room, and the summary+/// request this precedes is about to ship the same input anyway.+pub fn decideContext(c: Context) Decision {+ if (c.over_window_rejection or c.near_limit) return .skip_recovering;+ if (c.window_tokens == 0) return .fire;+ return if (c.effective_tokens +| note_reserve_tokens > c.window_tokens) .skip_no_headroom else .fire;}/// The whole ladder, in the order the call site runs it.-pub fn decide(in: Inputs, window_tokens: u64, effective_tokens: u64) Decision {+pub fn decide(in: Inputs, c: Context) Decision {const calls = decideCalls(in);if (calls != .fire) return calls;- return decideRoom(window_tokens, effective_tokens);+ return decideContext(c);}/// A model reply that carries no note. The prompt asks for exactly "none"diff --git a/src/compact_note_glue.zig b/src/compact_note_glue.zigindex 4e9d4610..bee843e0 100644--- a/src/compact_note_glue.zig+++ b/src/compact_note_glue.zig@@ -51,6 +51,24 @@ pub fn gateCalls(self: *const Agent) Decision {});}+/// The context half of the gate, read off the live agent. Serializes history+/// (effectiveContextTokens), so it runs only after gateCalls has cleared.+///+/// `last_request_context_overflow` and `nearContextLimit` are the two signals+/// that separate a PLANNED rollover from a rescue, and they are the same two+/// compactOrRecover itself uses to decide whether it may trim destructively.+/// Reading the same signals is deliberate: the note fires exactly when+/// compaction is a scheduled event and never when it is damage control.+pub fn contextOf(self: *Agent) compact_note.Context {+ const effective = self.effectiveContextTokens();+ return .{+ .window_tokens = self.provider.context,+ .effective_tokens = effective,+ .over_window_rejection = self.last_request_context_overflow,+ .near_limit = self.provider.nearContextLimit(effective),+ };+}+/// Write one note to self, if this is a moment that deserves one. Returns the/// decision so a caller (and a test) can see WHICH refusal happened rather/// than only that nothing was written. Never throws: every failure below is a@@ -58,7 +76,7 @@ pub fn gateCalls(self: *const Agent) Decision {pub fn maybeWrite(self: *Agent) Decision {const cheap = gateCalls(self);if (cheap != .fire) return cheap;- const room = compact_note.decideRoom(self.provider.context, self.effectiveContextTokens());+ const room = compact_note.decideContext(contextOf(self));if (room != .fire) return room;// Latch the generation BEFORE the call. A note turn that fails has stilldiff --git a/src/compact_note_glue_tests.zig b/src/compact_note_glue_tests.zigindex 99f84dcc..c416d4d9 100644--- a/src/compact_note_glue_tests.zig+++ b/src/compact_note_glue_tests.zig@@ -97,6 +97,68 @@ test "maybeWrite (#391): the other refusals also come back named, and none of thtry std.testing.expectEqual(compact_note.Decision.fire, glue.gateCalls(&ready));}+/// An agent whose context is measurable: contextOf() serializes history, so+/// unlike the gateCalls-only stubs above this one needs a real provider and a+/// real (small) message array.+fn measurable(arena: std.mem.Allocator, budget: *run_budget.RunBudget, window: u64) !Agent {+ var agent = stub(arena, budget);+ agent.provider = .{+ .id = "codex",+ .kind = .responses,+ .auth = .bearer,+ .url = "",+ .api_key = "",+ .model = "gpt-5",+ .context = window,+ };+ agent.sys_normal = "";+ agent.sys_strict = "";+ agent.tools_responses = "";+ agent.messages = std.json.Array.init(arena);+ try agent.messages.append(try messages_mod.textMessage(arena, "user", "hello"));+ return agent;+}++test "contextOf (#391): reads the same planned-vs-salvage signals compactOrRecover trims on" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var budget: run_budget.RunBudget = .{ .max_model_calls = 0 };+ const window: u64 = 200_000;+ var agent = try measurable(arena, &budget, window);++ // A planned rollover: over compact@ (80%), under nearContextLimit (95%).+ // This is the band the codex PTY midturn scenario runs in by construction+ // ("Cross compact@ (80%) but stay below the destructive recovery boundary"),+ // and it is the case #391 exists for.+ agent.last_context_tokens = window * 9 / 10;+ var ctx = glue.contextOf(&agent);+ try std.testing.expectEqual(window, ctx.window_tokens);+ try std.testing.expect(!ctx.near_limit);+ try std.testing.expect(!ctx.over_window_rejection);+ try std.testing.expectEqual(compact_note.Decision.fire, compact_note.decideContext(ctx));+ try std.testing.expectEqual(compact_note.Decision.fire, glue.gateCalls(&agent));++ // Push past 95% and the SAME agent stops buying notes — contextOf derives+ // near_limit from Provider.nearContextLimit, the very predicate+ // compactOrRecover uses to authorize destructive trimming.+ agent.last_context_tokens = window * 96 / 100;+ ctx = glue.contextOf(&agent);+ try std.testing.expect(ctx.near_limit);+ try std.testing.expect(agent.provider.nearContextLimit(ctx.effective_tokens));+ try std.testing.expectEqual(compact_note.Decision.skip_recovering, compact_note.decideContext(ctx));+ // Through the production entry point, with provider/client live: still a+ // refusal, so no request is attempted.+ try std.testing.expectEqual(compact_note.Decision.skip_recovering, glue.maybeWrite(&agent));+ try std.testing.expect(agent.precompact_note_gen == null); // nothing latched++ // A concrete provider overflow rejection is salvage even well under 95%.+ agent.last_context_tokens = window * 9 / 10;+ agent.last_request_context_overflow = true;+ try std.testing.expectEqual(compact_note.Decision.skip_recovering, glue.maybeWrite(&agent));+ try std.testing.expect(agent.precompact_note_gen == null);+}+test "#391: the note is STATE — a wiped history cannot touch it, and it re-injects verbatim" {try inScratch(struct {fn body(io: Io, arena: std.mem.Allocator) !void {diff --git a/src/compact_note_tests.zig b/src/compact_note_tests.zigindex 8c29bc26..8abaecce 100644--- a/src/compact_note_tests.zig+++ b/src/compact_note_tests.zig@@ -45,42 +45,88 @@ fn baseInputs() compact_note.Inputs {};}-test "decide (#391): fires exactly once when compaction is imminent, and not otherwise" {- const window: u64 = 200_000;- const at_compact_threshold: u64 = 160_000; // 80% — where compaction actually fires+const window: u64 = 200_000;- // The one case that fires: a root, with a session, mid-compaction, with- // budget and window headroom.- try std.testing.expectEqual(compact_note.Decision.fire, compact_note.decide(baseInputs(), window, at_compact_threshold));+/// The band the note is FOR: over compact@ (80%, where compaction fires) but+/// under nearContextLimit (95%, where the harness starts salvaging). The codex+/// PTY scenario sits here on purpose — see codex_ws_test.py's own comment,+/// "Cross compact@ (80%) but stay below the destructive recovery boundary".+fn plannedRollover() compact_note.Context {+ return .{+ .window_tokens = window,+ .effective_tokens = window * 9 / 10, // 90%+ .over_window_rejection = false,+ .near_limit = false,+ };+}++test "decide (#391): fires exactly once when compaction is imminent, and not otherwise" {+ // The one case that fires: a root, with a session, on a planned rollover,+ // with budget and window headroom.+ try std.testing.expectEqual(compact_note.Decision.fire, compact_note.decide(baseInputs(), plannedRollover()));// ONCE: the same history generation never buys a second note, however// often compaction is retried after a transient failure (#379's loop).var noted = baseInputs();noted.last_written = 0;- try std.testing.expectEqual(compact_note.Decision.skip_already, compact_note.decide(noted, window, at_compact_threshold));+ try std.testing.expectEqual(compact_note.Decision.skip_already, compact_note.decide(noted, plannedRollover()));// …and the NEXT compaction (history_rewrites has advanced) buys one again.noted.history_rewrites = 1;- try std.testing.expectEqual(compact_note.Decision.fire, compact_note.decide(noted, window, at_compact_threshold));+ try std.testing.expectEqual(compact_note.Decision.fire, compact_note.decide(noted, plannedRollover()));// No durable session: nothing would ever read the note back.var homeless = baseInputs();homeless.session_name = "";- try std.testing.expectEqual(compact_note.Decision.skip_no_session, compact_note.decide(homeless, window, at_compact_threshold));+ try std.testing.expectEqual(compact_note.Decision.skip_no_session, compact_note.decide(homeless, plannedRollover()));- // No token buffer left: the window is already inside the reserve, so the- // tokens have to go to the compaction that must happen regardless.- try std.testing.expectEqual(- compact_note.Decision.skip_no_headroom,- compact_note.decide(baseInputs(), window, window - compact_note.note_reserve_tokens + 1),- );+ // No token buffer left: the tokens have to go to the compaction that must+ // happen regardless.+ var cramped = plannedRollover();+ cramped.effective_tokens = window - compact_note.note_reserve_tokens + 1;+ try std.testing.expectEqual(compact_note.Decision.skip_no_headroom, compact_note.decide(baseInputs(), cramped));// Exactly at the buffer boundary still fires — the reserve is what it says.- try std.testing.expectEqual(- compact_note.Decision.fire,- compact_note.decide(baseInputs(), window, window - compact_note.note_reserve_tokens),- );+ cramped.effective_tokens = window - compact_note.note_reserve_tokens;+ try std.testing.expectEqual(compact_note.Decision.fire, compact_note.decide(baseInputs(), cramped));// An unknown window cannot prove there is no room, and the summary request// this precedes is about to ship the same input anyway.- try std.testing.expectEqual(compact_note.Decision.fire, compact_note.decide(baseInputs(), 0, 10_000_000));+ var unknown = plannedRollover();+ unknown.window_tokens = 0;+ unknown.effective_tokens = 10_000_000;+ try std.testing.expectEqual(compact_note.Decision.fire, compact_note.decide(baseInputs(), unknown));+}++test "decideContext (#391): a planned rollover buys a note; a SALVAGE never does" {+ // The whole point of this gate. #391 is about a SCHEDULED rollover: context+ // is filling, so spend one call before the window turns over. Once the+ // harness is rescuing a session, that same call is the last thing it can+ // afford — and the token buffer alone would NOT catch it, because at 95%+ // of a 200k window there are still 10k tokens of nominal room.+ try std.testing.expectEqual(compact_note.Decision.fire, compact_note.decideContext(plannedRollover()));++ // The destructive-recovery boundary: compactOrRecover may drop real+ // history here, so this is damage control, not a rollover.+ var rescuing = plannedRollover();+ rescuing.near_limit = true;+ rescuing.effective_tokens = window * 95 / 100;+ try std.testing.expectEqual(compact_note.Decision.skip_recovering, compact_note.decideContext(rescuing));+ // …refused BEFORE the buffer question, which would have said yes. This is+ // the assertion that would fail if the salvage gate were ever folded into+ // the token arithmetic instead of preceding it.+ var buffer_only = rescuing;+ buffer_only.near_limit = false;+ try std.testing.expectEqual(compact_note.Decision.fire, compact_note.decideContext(buffer_only));++ // A concrete provider rejection — the request already bounced off the wall.+ var bounced = plannedRollover();+ bounced.over_window_rejection = true;+ try std.testing.expectEqual(compact_note.Decision.skip_recovering, compact_note.decideContext(bounced));+ // Salvage outranks even an unknown window, which otherwise always fires.+ bounced.window_tokens = 0;+ try std.testing.expectEqual(compact_note.Decision.skip_recovering, compact_note.decideContext(bounced));++ // And salvage is a CONTEXT verdict, not a call-budget one: the ledger is+ // untouched by it, so the two halves stay independently readable.+ try std.testing.expectEqual(compact_note.Decision.fire, compact_note.decideCalls(baseInputs()));}test "decide (#391): a WORKER never writes a note, whatever else is true" {@@ -89,12 +135,15 @@ test "decide (#391): a WORKER never writes a note, whatever else is true" {// Checked FIRST, so a subagent is refused even in the case that would// otherwise fire — and still refused when every other gate would also// have refused, which is what makes the ordering observable.- try std.testing.expectEqual(compact_note.Decision.skip_worker, compact_note.decide(worker, 200_000, 160_000));+ try std.testing.expectEqual(compact_note.Decision.skip_worker, compact_note.decide(worker, plannedRollover()));try std.testing.expectEqual(compact_note.Decision.skip_worker, compact_note.decideCalls(worker));worker.session_name = "child";worker.cap = 8;worker.remaining = 1;- try std.testing.expectEqual(compact_note.Decision.skip_worker, compact_note.decide(worker, 8_000, 7_999));+ var dire = plannedRollover();+ dire.near_limit = true;+ dire.over_window_rejection = true;+ try std.testing.expectEqual(compact_note.Decision.skip_worker, compact_note.decide(worker, dire));}test "decideCalls (#391): the budget gate IS #390's landing reserve, not a second one" {