iterate.com / stdlib

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

stdlib / agent-tests / state-cell.test.mjsmain at 41005ca

// 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);
});