iterate.com / stdlib

git clone https://git.iterate.com/repos/stdlib

Agent: a summary by size, a summary before the next answer, and a request maker that holds a second conversation only while it fits (#3)

The port of /repos/config a439eeb and 0bcb573 to stdlib's agent.

- A summary is due when the config and two conversations (instructions and items, as JSON) reach 85% of a storage cell of 2 MB, whatever the tokens are. With few items it replaces the older half.
- No answer starts while a summary is open or due.
- The request maker holds the newest two conversations of a provider only while all that is held is under 85% of a cell; a dropped base is read from the log.

Checks on the head feab10e: `pnpm typecheck` passes, `pnpm test` 168 of 168.

Card: tasks/stop-agents-halting-at-the-2-mb-state-ceiling-and-revive-halted.md of /repos/task-board
Session: claude 34599fd3-9722-414d-8ae3-8eba6d2e1347 on beelink

๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01F4yAt5cXNpUkSxf3XaeVQH

Iterate-Run: /@1724674

jonas, 2026-11-28 11:45 UTC ยท 41005ca0c65216f33646f1f277f3d5f6d2e6dde7 ยท parent d9dbaa8

5 files changed

A agent-tests/state-cell.test.mjs
@@ -0,0 +1,238 @@
+// node --test agent-tests/state-cell.test.mjs
+// A PROCESSOR'S STATE IS ONE STORAGE CELL of 2 MB (agent/contract.ts `STATE_CELL_CHARS`). The
+// request maker holds whole conversations; past a cell its checkpoint is refused, its row halts,
+// and the agent gets no answer more. Misha, 28 Nov 2026, in Slack, of misherate.com: "At ~1 MB of
+// conversation (174k tokens for us) the request maker's checkpoint is refused". Three rules keep
+// the state under a cell, and each has its tests here: a summary is due by size (processor.ts
+// `nearsStateCell`), a summary comes before the next answer (`summaryComesFirst`), and the request
+// maker holds a second conversation only while it fits (llm-api.ts `kept`). The real reducers fold
+// every fact.
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { STATE_CELL_CHARS, SUMMARY_AT_SHARE_OF_CELL, requestMakerStateChars, serializedChars } from "../agent/contract.ts";
+import { LlmApiProcessor } from "../agent/llm-api.ts";
+import { openaiResponses } from "../agent/llm-apis/openai-responses.ts";
+import { Agent } from "../agent/processor.ts";
+
+const T = "events.iterate.com/";
+const PATH = "/agents/state-cell-test";
+const SOL = "openai/gpt-6.2-sol";
+const QUIET = "<codemode>\nitx;\n</codemode>";
+/** Words of `kB` thousand characters, with what JSON escapes in them. */
+const words = (kB) => 'He said "go on".\n'.repeat(Math.ceil((kB * 1_000) / 17));
+
+/** An agent's log, folded by the real reducer, with what it owes appended as its host does. */
+function agentOn() {
+  const agent = new Agent();
+  let state = agent.contract.stateSchema.parse({});
+  let offset = 1;
+  let nowMs = Date.parse("2026-11-28T12:00:00.000Z");
+  const log = [];
+  const appended = new Set();
+  const fold = (type, payload, idempotencyKey) => {
+    const event = { type: type.startsWith(T) ? type : `${T}${type}`, offset: offset++, path: PATH, createdAt: new Date(nowMs).toISOString(), source: {}, payload, ...(idempotencyKey ? { idempotencyKey } : {}) };
+    state = agent.reduce({ event, state });
+    log.push(event);
+    return event;
+  };
+  const appendOwed = () => {
+    for (let pass = 0; pass < 20; pass++) {
+      const owed = state.obligations.filter((o) => !appended.has(o.idempotencyKey));
+      if (owed.length === 0) return;
+      for (const o of owed) {
+        appended.add(o.idempotencyKey);
+        o.events.forEach((event, i) => fold(event.type, event.payload, event.idempotencyKey ?? (i === 0 ? o.idempotencyKey : undefined)));
+      }
+    }
+    throw new Error("the agent never stops owing");
+  };
+  const fireTimer = () => {
+    const { atMs } = state.timer;
+    if (atMs === null || atMs <= state.nowMs) return;
+    nowMs = Math.max(nowMs, atMs);
+    fold("agent/timer-fired", { atMs });
+    appendOwed();
+  };
+  const open = (purpose) => state.llmRequests.filter((request) => request.purpose === purpose);
+  const requested = (purpose) => log.filter((e) => e.type === `${T}llm-request/requested` && e.payload.purpose === purpose);
+  const say = (text = "go on") => {
+    fold("agent/context-added", { role: "user", content: text });
+    appendOwed();
+    fireTimer();
+  };
+  const settle = (purpose, result) => {
+    const [request] = open(purpose);
+    assert.ok(request, `no ${purpose} request is open`);
+    nowMs += 2_000;
+    fold("llm-request/settled", { llmRequestOffset: request.requestOffset, attempt: 0, firstEventMs: 1, durationMs: 2_000, result });
+    appendOwed();
+    for (const call of state.scriptCalls.filter((c) => c.runRequestOffset !== null && !c.answered)) {
+      fold("itx/run-settled", { requestOffset: call.runRequestOffset, settlement: { status: "succeeded" } });
+      appendOwed();
+    }
+    fireTimer();
+  };
+  const answer = (inputTokens) => settle("answer", { status: "succeeded", text: QUIET, providerItems: [], usage: { inputTokens, cachedInputTokens: 0, outputTokens: 100 } });
+  const summarise = (text = "What was said.") => settle("summary", { status: "succeeded", text, providerItems: [], usage: { inputTokens: 1_000, outputTokens: 100 } });
+  fold("agent/configured", { kind: "agent", config: { llm: { model: SOL } } });
+  /** What the request maker's state comes to for the agent's conversation now. */
+  const cellChars = () => requestMakerStateChars(state.config, state.config.instructions, [...state.copiedItems, ...state.items]).total;
+  return { fold, appendOwed, fireTimer, open, requested, say, settle, answer, summarise, cellChars, state: () => state };
+}
+
+const DUE_AT = STATE_CELL_CHARS * SUMMARY_AT_SHARE_OF_CELL;
+
+test("the count is the checkpoint's: what JSON.stringify makes of the config and of two conversations", () => {
+  const agent = agentOn();
+  agent.say(words(50));
+  agent.answer(20_000);
+  const { config, items } = agent.state();
+  const conversation = JSON.stringify(config.instructions).length + JSON.stringify(items).length;
+  const counted = agent.cellChars();
+  const exact = JSON.stringify(config).length + 2 * conversation;
+  // (the count takes one character for each item's comma, and none for the two brackets)
+  assert.ok(Math.abs(counted - exact) <= 4, `${counted} against ${exact}`);
+  assert.equal(serializedChars('a "b"\n'), JSON.stringify('a "b"\n').length);
+});
+
+test("a conversation of few tokens and much text is summarised before the request maker's state is a cell", () => {
+  const agent = agentOn();
+  // each turn reads 30,000 tokens: far under Sol's 367,000. The words are 100 kB a turn.
+  let turns = 0;
+  while (turns < 30) {
+    assert.ok(agent.cellChars() < DUE_AT, "no summary was due under 85% of a cell");
+    agent.say(words(100));
+    turns += 1;
+    if (agent.requested("summary").length > 0) break;
+    agent.answer(30_000);
+  }
+  assert.equal(agent.requested("summary").length, 1, "a summary is due by size");
+  assert.ok(agent.cellChars() >= DUE_AT);
+  assert.equal(agent.open("answer").length, 0, "the words that made it due wait for the summary");
+  // what the request maker holds at that moment, an answer's conversation and the summary's, is under a cell
+  assert.ok(agent.cellChars() < STATE_CELL_CHARS, `${agent.cellChars()} is under a cell`);
+  assert.ok(turns >= 8 && turns <= 10, `${turns} turns of 100 kB`);
+  agent.summarise();
+  assert.equal(agent.state().items[0].tag, "summary");
+  assert.ok(agent.cellChars() < DUE_AT);
+  agent.answer(30_000);
+  agent.say();
+  agent.answer(30_000);
+  assert.equal(agent.requested("summary").length, 1, "and no second summary");
+});
+
+test("a summary that is due comes before the next answer: the answer starts when the summary has ended", () => {
+  const agent = agentOn();
+  for (let i = 0; i < 9; i++) {
+    agent.say();
+    agent.answer(100_000);
+  }
+  agent.say();
+  agent.answer(375_000); // over Sol's threshold: a summary is due
+  assert.equal(agent.open("summary").length, 1);
+  agent.say("and another");
+  assert.equal(agent.open("answer").length, 0, "no answer beside the summary");
+  agent.summarise();
+  const [answer] = agent.open("answer");
+  assert.ok(answer, "the answer starts when the summary has ended");
+  // it reads the summary and the words that waited
+  const state = agent.state();
+  assert.equal(state.items[0].tag, "summary");
+  assert.ok(state.items.some((item) => item.text === "and another"));
+});
+
+// โ”€โ”€ the request maker โ”€โ”€
+
+/** The real request maker's reducer over a chain of requests, each off the one before. */
+function requestMaker() {
+  const processor = new LlmApiProcessor({
+    api: openaiResponses(),
+    getItx: () => ({ [Symbol.dispose]() {} }),
+    fetch: async () => new Response("", { status: 500 }),
+    now: () => 0,
+    report: () => {},
+    readEvents: async () => ({ events: [] }),
+  });
+  let state = processor.contract.stateSchema.parse({});
+  let offset = 1;
+  const fold = (type, payload) => {
+    const event = { type: `${T}${type}`, offset: offset++, path: PATH, createdAt: "2026-11-28T12:00:00.000Z", source: {}, payload };
+    state = processor.reduce({ event, state });
+    return event;
+  };
+  fold("agent/configured", { kind: "agent", config: {} });
+  let base = null;
+  let count = 0;
+  /** One request with `kB` of new words, off the request before, and its response. */
+  const turn = (kB, purpose = "answer") => {
+    const added = [{ role: "user", text: words(kB) }];
+    const asked = fold("llm-request/requested", {
+      model: SOL,
+      purpose,
+      expiresAtMs: 0,
+      triggerOffset: 0,
+      ...(base ? { extends: { llmRequestOffset: base, itemCount: count, response: true } } : { extends: null, instructions: "Be brief.", promptCacheKey: PATH }),
+      itemsAdded: added,
+    });
+    const open = state.requests.find((request) => request.requestOffset === asked.offset);
+    assert.ok(open, "the request is open");
+    const held = open.unresolved === null;
+    const whileOpen = JSON.stringify(state).length;
+    fold("llm-request/settled", { llmRequestOffset: asked.offset, attempt: 0, firstEventMs: 1, durationMs: 2, result: { status: "succeeded", text: "ok", providerItems: [], usage: { inputTokens: 10, outputTokens: 1 } } });
+    base = asked.offset;
+    count += 2; // the words and the response before them (the first has no response before it)
+    if (count === 2) count = 1;
+    return { held, whileOpen, after: JSON.stringify(state).length };
+  };
+  return { turn, state: () => state };
+}
+
+test("the request maker holds the newest two conversations while they fit", () => {
+  const maker = requestMaker();
+  for (let i = 0; i < 4; i++) assert.equal(maker.turn(50).held, true);
+  assert.equal(maker.state().conversations.length, 2);
+});
+
+test("a conversation of 1.2 MB: the request maker holds it once, its state stays under a cell, and each request finds its base", () => {
+  const maker = requestMaker();
+  let largest = 0;
+  for (let i = 0; i < 12; i++) {
+    const { held, whileOpen, after } = maker.turn(100);
+    assert.equal(held, true, `request ${i + 1} found its base in the state`);
+    largest = Math.max(largest, whileOpen, after);
+  }
+  const [newest] = maker.state().conversations.slice(-1);
+  const chars = JSON.stringify(newest.items).length;
+  assert.ok(chars > 1_200_000, `the conversation is ${chars} characters`);
+  // two of it are over a cell: until 28 Nov 2026 the state held two
+  assert.ok(2 * chars > STATE_CELL_CHARS);
+  assert.equal(maker.state().conversations.length, 1);
+  assert.ok(largest < STATE_CELL_CHARS, `the state was ${largest} characters at most`);
+});
+
+test("instructions that fill a cell alone start no summary: a summary cannot make them smaller", () => {
+  const agent = agentOn();
+  agent.fold("agent/configured", { kind: "agent", config: { instructions: "x".repeat(1_000_000) } });
+  for (let i = 0; i < 9; i++) {
+    agent.say();
+    agent.answer(30_000);
+  }
+  assert.ok(agent.cellChars() >= DUE_AT);
+  assert.equal(agent.requested("summary").length, 0);
+});
+
+test("few items, each large (ten inputs of 100 kB): ONE summary of the older half brings it under, and then the answer", () => {
+  // seen live on /agents/tests/state-cell-1141, 28 Nov 2026: with the newest six kept, each
+  // summary replaced one input and the next was due at once
+  const agent = agentOn();
+  for (let i = 0; i < 10; i++) agent.fold("agent/context-added", { role: "user", content: words(100), llmRequestPolicy: { behaviour: "dont-trigger-request" } });
+  agent.say("which berth is free?");
+  assert.equal(agent.open("summary").length, 1);
+  assert.equal(agent.open("answer").length, 0);
+  agent.summarise();
+  assert.ok(agent.cellChars() < DUE_AT, `${agent.cellChars()} after one summary`);
+  assert.equal(agent.open("summary").length, 0);
+  assert.equal(agent.open("answer").length, 1);
+  agent.answer(30_000);
+  assert.equal(agent.requested("summary").length, 1);
+});
M agent-tests/subagent.test.mjs
@@ -71,6 +71,8 @@
           promptCacheKey: state.config.llm.promptCacheKey ?? request.path,
           ...llm,
         },
+        // (this fake alone: a test's parent that turns the summary by size off turns it off for its fork)
+        ...(world.forkSummary && { summary: world.forkSummary }),
       }
     : model
       ? { llm }
@@ -316,6 +318,13 @@
   // so two inputs of 550,000 characters, over the 1,000,000 of one fact together)
   const world = worldOf();
   const parent = await started(world, PARENT, scripted("const a = 1;", "const b = 2;"));
+  // (a conversation of this size is summarised by its size now, processor.ts `nearsStateCell`.
+  // This parent and its fork say that their items are small, so that the copy has two parts)
+  world.forkSummary = { minInputTokens: 1_000_000 };
+  await parent.append({
+    type: `${T}agent/configured`,
+    payload: { config: { summary: world.forkSummary } },
+  });
   for (const letter of ["a", "b"]) await parent.say(letter.repeat(550_000));
   const child = await started(world, CHILD, scripted(), true);
   const before = await parent.state();
M agent/contract.ts
@@ -180,6 +180,54 @@
   return Math.floor(usable * atShareOfUsableWindow);
 }
 
+/** ONE STORAGE CELL, in characters: what a processor's reduced state may serialize to. The
+ *  platform refuses a larger checkpoint (/repos/kernel, core/lib/src/stream/processor.ts,
+ *  `REDUCE_CHECKPOINT_STATE_MAX_CHARS`, which it does not export: change the two together). The
+ *  row of the processor then halts, and an agent whose request maker halted gets no answer more:
+ *  each request fails with "no processor made the request". Misha, 28 Nov 2026, in Slack, of
+ *  misherate.com: "At ~1 MB of conversation (174k tokens for us) the request maker's checkpoint
+ *  is refused [โ€ฆ] its subscription row halts". So the token threshold above is not reached by a
+ *  conversation whose text is larger than this: the rule below comes first. */
+export const STATE_CELL_CHARS = 2 * 1024 * 1024 - 4096;
+/** A summary is due at this share of a cell, and the request maker holds no more than it. The
+ *  rest is room for what one turn adds and for what the count leaves out (how to write a script,
+ *  a request's own fields). */
+export const SUMMARY_AT_SHARE_OF_CELL = 0.85;
+/** How many whole conversations the request maker's state holds at most while a summary can
+ *  still be made: an answer's and the summary's, or the newest two (llm-api.ts `kept`). */
+const HELD_CONVERSATIONS = 2;
+
+const serializedSizes = new WeakMap<object, number>();
+let lastText = { text: "", chars: 2 };
+/** How many characters a value takes in a checkpoint (`JSON.stringify`). An object is counted
+ *  once and remembered: a reducer never changes an item, a config or a conversation in place. */
+export function serializedChars(value: unknown): number {
+  if (typeof value === "string") {
+    if (lastText.text !== value) lastText = { text: value, chars: JSON.stringify(value).length };
+    return lastText.chars;
+  }
+  if (value === null || typeof value !== "object") return JSON.stringify(value)?.length ?? 0;
+  let chars = serializedSizes.get(value);
+  if (chars === undefined) {
+    chars = JSON.stringify(value).length;
+    serializedSizes.set(value, chars);
+  }
+  return chars;
+}
+
+/** WHAT THE REQUEST MAKER'S STATE COMES TO FOR THIS CONVERSATION, in characters: the config and
+ *  two whole conversations, each the instructions and every item, and what the items alone take once (Misha's count, 28 Nov 2026:
+ *  "config + 2 x (instructions + items)"). */
+export function requestMakerStateChars(
+  config: AgentConfig,
+  instructions: string,
+  items: readonly object[],
+): { total: number; conversation: number } {
+  const conversation = items.reduce((sum, item) => sum + serializedChars(item) + 1, 0);
+  const held = HELD_CONVERSATIONS * (serializedChars(instructions) + conversation);
+  return { total: serializedChars(config) + held, conversation };
+}
+
 export const AgentConfig = z.object({
   /** What the model is told before the conversation. A change starts a new prompt cache. The
    *  default names no channel: the mind's `worker.ts` adds the fragments of the channels the agent
M agent/llm-api.ts
@@ -85,7 +85,10 @@
   costUsd,
   mergedConfig,
   ScheduleEventCatalog,
+  serializedChars,
   startsTheAgent,
+  STATE_CELL_CHARS,
+  SUMMARY_AT_SHARE_OF_CELL,
 } from "./contract.ts";
 import {
   ConversationItem,
@@ -1172,12 +1175,35 @@
   return kept({ ...state, requests: state.requests.filter((request) => !isEnded(request)) });
 }
 
+/** What one held conversation takes of the state, in characters. */
+const heldChars = (held: LlmApiState["conversations"][number]) =>
+  serializedChars(held.instructions) +
+  held.items.reduce((sum, item) => sum + serializedChars(item) + 1, 0) +
+  (held.response ? serializedChars(held.response) : 0);
+
+/** WHICH CONVERSATIONS STAY: those of the open requests, and the newest two of each provider
+ *  WHILE THEY FIT. The state is one storage cell (contract.ts `STATE_CELL_CHARS`): a checkpoint
+ *  past it is refused, this processor's row halts, and the agent gets no answer more. So a
+ *  conversation that no open request needs stays only while all that is held is under
+ *  `SUMMARY_AT_SHARE_OF_CELL` of a cell, the newest first. One that went is read from the log
+ *  when a request names it as its base, as any older base is. The conversations of the open
+ *  requests always stay: the agent keeps those under a cell (processor.ts `nearsStateCell`). */
 function kept(state: LlmApiState): LlmApiState {
   const needed = new Set(state.requests.map((request) => request.requestOffset));
-  const providers = new Set(state.conversations.map((c) => c.provider));
-  for (const provider of providers)
+  let chars = serializedChars(state.config);
+  for (const held of state.conversations)
+    if (needed.has(held.llmRequestOffset)) chars += heldChars(held);
+  const likelyBases: LlmApiState["conversations"] = [];
+  for (const provider of new Set(state.conversations.map((c) => c.provider)))
     for (const newest of state.conversations.filter((c) => c.provider === provider).slice(-2))
-      needed.add(newest.llmRequestOffset);
+      if (!needed.has(newest.llmRequestOffset)) likelyBases.push(newest);
+  likelyBases.sort((a, b) => b.llmRequestOffset - a.llmRequestOffset);
+  for (const held of likelyBases) {
+    const size = heldChars(held);
+    if (chars + size > STATE_CELL_CHARS * SUMMARY_AT_SHARE_OF_CELL) continue;
+    chars += size;
+    needed.add(held.llmRequestOffset);
+  }
   const conversations = state.conversations.filter((c) => needed.has(c.llmRequestOffset));
   return { ...state, conversations };
 }
M agent/processor.ts
@@ -51,7 +51,10 @@
 import {
   AgentContract,
   mergedConfig,
+  requestMakerStateChars,
   startsTheAgent,
+  STATE_CELL_CHARS,
+  SUMMARY_AT_SHARE_OF_CELL,
   summaryThresholdTokens,
   type AgentEventInput,
   type AgentState,
@@ -710,6 +713,7 @@
     state.pendingTriggerOffsets.length > 0 &&
     !state.paused &&
     !state.contextWindowExceeded && // a summary first
+    !summaryComesFirst(state) &&
     !state.llmRequests.some((request) => request.purpose === "answer") && // one at a time
     state.scriptCalls.every((call) => call.answered) && // a response is read whole
     state.nowMs >= Math.max(state.debounceUntilMs, state.retryNotBeforeMs.answer) &&
@@ -730,6 +734,33 @@
   );
 }
 
+/** A SUMMARY THAT IS OPEN OR DUE COMES BEFORE THE NEXT ANSWER. An answer beside it is one more
+ *  whole conversation in the request maker's state, and that state is one cell (contract.ts
+ *  `STATE_CELL_CHARS`). Misha, 28 Nov 2026, in Slack: "a summary that is due or open comes before
+ *  the next answer, because a summary with two answers beside it is three copies". An answer that
+ *  is open already goes on: a summary starts beside it and replaces what is finished. A summary
+ *  that waits for its back-off, or that failed too often, holds no answer. */
+function summaryComesFirst(state: AgentState): boolean {
+  return (
+    state.llmRequests.some((request) => request.purpose === "summary") || summaryRequestDue(state)
+  );
+}
+
+/** THE CONVERSATION NEARS A STORAGE CELL: what the request maker's state comes to for it reaches
+ *  `SUMMARY_AT_SHARE_OF_CELL` of a cell, whatever its tokens are, and its items are not small
+ *  (`summary.minInputTokens`, at four characters a token). Past a cell the request maker's row
+ *  halts and the agent gets no answer more (contract.ts `STATE_CELL_CHARS`). */
+function nearsStateCell(state: AgentState): boolean {
+  const { config } = state;
+  const items = [...state.copiedItems, ...state.items];
+  const { total, conversation } = requestMakerStateChars(config, config.instructions, items);
+  return (
+    // (as with the tokens: a summary cannot make the instructions smaller)
+    conversation >= config.summary.minInputTokens * 4 &&
+    total >= STATE_CELL_CHARS * SUMMARY_AT_SHARE_OF_CELL
+  );
+}
+
 /** A SUMMARY PAYS when the history nears the model's context window (`summaryThresholdTokens`,
  *  contract.ts), as in Claude Code. `history.inputTokens` is what the newest response read and
  *  wrote: the least that the next request reads. A provider's refusal for size pays at any size.
@@ -737,6 +768,7 @@
  *  they did, from 20,000 tokens up. */
 function summaryPays(state: AgentState): boolean {
   if (state.contextWindowExceeded) return true;
+  if (nearsStateCell(state)) return true;
   const { config, history } = state;
   return (
     replaceableTokens(state) >= config.summary.minInputTokens &&
@@ -753,7 +785,8 @@
  *  Only what is finished: before every answer request that is open, every script that is not
  *  answered and every input that waits. (A subclass that holds inputs makes no summary while it
  *  holds one.) The newest items stay as they are; when the conversation no
- *  longer fits the model, the older half goes. */
+ *  longer fits the model, or nears a storage cell with few items (its newest items are the large
+ *  ones), the older half goes. */
 function summaryBarrier(state: AgentState): number | null {
   const unfinishedFromOffset = Math.min(
     Infinity,
@@ -764,9 +797,12 @@
   const finished = state.items.filter((item) => item.atOffset < unfinishedFromOffset);
   // a forked subagent's copied items stand first; a barrier among them is 0, before every own item
   const all = [...state.copiedItems.map(() => null), ...finished];
+  const { keepNewestItems } = state.config.summary;
   const keep = state.contextWindowExceeded
     ? Math.floor(all.length / 2)
-    : state.config.summary.keepNewestItems;
+    : nearsStateCell(state)
+      ? Math.min(keepNewestItems, Math.floor(all.length / 2))
+      : keepNewestItems;
   const replaced = all.slice(0, Math.max(0, all.length - keep));
   if (replaced.length < 2) return null;
   return replaced[replaced.length - 1]?.atOffset ?? 0;