okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221rc1 merge ds-coder (d6a5a7837)4fb068a8c

main
12.6 KiB185 linesraw
1// AGENT-LOST (11-01): a reply the length limit cut inside a tool call used to vanish: no file, no card, no sentence.
2// Pure parts always run; the end-to-end ones need a built Harness (STRATA_HARNESS_DIR) and use the scripted model server.
3import test from 'node:test';
4import assert from 'node:assert/strict';
5import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync } from 'node:fs';
6import { tmpdir } from 'node:os';
7import { join } from 'node:path';
8import { replyCap, unescapeJsonTail, ToolDraft, cutCalls, cutNotice, cutNudge } from '../server/agent/reply-cut.mjs';
9import { TurnProjector } from '../server/agent/events.mjs';
10import { startScriptedWorker } from './helpers/scripted-worker.mjs';
11import { createAgentBridge, MAX_CUT_RETRIES } from '../server/agent/agent-bridge.mjs';
12import { resolveHarness } from '../server/agent/harness-runtime.mjs';
13import { localOutputBudget } from '../server/agent/profile.mjs';
14
15const HARNESS = process.env.STRATA_HARNESS_DIR;
16const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
17
18test('the reply ceiling is half the window up to 64K tokens and never below what compaction reserves', () => {
19  assert.equal(replyCap(65536, localOutputBudget(65536)), 32768);
20  assert.ok(replyCap(65536, localOutputBudget(65536)) > localOutputBudget(65536), '19,660 was the cut that lost the pagoda');
21  assert.equal(replyCap(131072, localOutputBudget(131072)), 65536);
22  assert.equal(replyCap(262144, localOutputBudget(262144)), 65536, 'at most 64K tokens, so a loop cannot run for an hour');
23  assert.equal(replyCap(8192, localOutputBudget(8192)), 4096);
24  assert.equal(replyCap(0, 5000), 16384, 'no window known: 32K is assumed');
25  assert.equal(replyCap(4096, 4096), 4096, 'never below the reserve');
26});
27
28test('JSON text is read back for the preview, and a half-written escape is dropped', () => {
29  assert.equal(unescapeJsonTail('a\\nb\\t\\"c\\"\\\\d'), 'a\nb\t"c"\\d');
30  assert.equal(unescapeJsonTail('line\\'), 'line');
31  assert.equal(unescapeJsonTail('x\\u00e9y'), 'xéy');
32  assert.equal(unescapeJsonTail('x\\u00'), 'x');
33});
34
35test('a call being written knows its file, its size, its lines and the tail of its text', () => {
36  const d = new ToolDraft('c1', 'write');
37  for (const piece of ['{"file_pa', 'th":"C:\\\\work\\\\pagoda.html","con', 'tent":"<!doctype html>\\n<html>\\n']) d.add(piece);
38  assert.equal(d.target, 'C:\\work\\pagoda.html');
39  assert.equal(d.lines, 2);
40  assert.equal(d.preview(), '<!doctype html>\n<html>\n');
41  for (let i = 0; i < 400; i++) d.add(`<div class=\\"row${i}\\">text ${i}</div>\\n`);
42  assert.ok(d.bytes > 10_000);
43  assert.equal(d.lines, 402);
44  const p = d.preview(1000);
45  assert.ok(p.length <= 1000 && p.endsWith('</div>\n') && !p.includes('\\n') && p.includes('class="row'), 'the tail, read back, ends where the model is');
46  const f = d.frame({ scope: 'write', verb: 'Writing' });
47  assert.deepEqual(Object.keys(f.draft).sort(), ['bytes', 'done', 'id', 'lines', 'name', 'preview', 'scope', 'target', 'verb']);
48  assert.equal(d.frame({ done: true }).draft.preview, '', 'a finished draft carries no text');
49});
50
51test('the file is found when the model writes its name after the text, or split between two pieces', () => {
52  const d = new ToolDraft('c2', 'write');
53  d.add('{"content":"line one\nline two\n');
54  assert.equal(d.target, '');
55  d.add('more","file_pa'); d.add('th":"/w/big.txt"}');
56  assert.equal(d.target, '/w/big.txt');
57});
58
59test('the sentences name the file and the size, say what to do, and the nudge asks for smaller parts', () => {
60  const draft = new ToolDraft('a', 'write'); draft.add('{"file_path":"/w/pagoda.html","content":"'); draft.bytes = 52_300;
61  const calls = cutCalls([draft]);
62  assert.deepEqual(calls, [{ name: 'write', target: '/w/pagoda.html', bytes: 52_300 }]);
63  const again = cutNotice({ calls, tokens: 19660, retrying: true });
64  assert.match(again.text, /reached its length limit \(19,660 tokens\) while writing pagoda\.html \(52 KB\), so that write did not happen\. I asked the assistant to look at what is on disk and write the rest in smaller parts\./);
65  const last = cutNotice({ calls, tokens: 19660 });
66  assert.match(last.text, /Say “continue”/);
67  assert.match(cutNotice({ tokens: 500 }).text, /^The reply reached its length limit \(500 tokens\) and was cut off\. Say “continue”/);
68  assert.match(cutNudge({ calls, tokens: 19660 }), /writing \/w\/pagoda\.html in one tool call, so that call did not run[\s\S]*Do not delete or start over a file that is already complete[\s\S]*smaller parts/);
69  assert.match(cutNudge({}), /cut off by the output limit/);
70  for (const n of [again, last]) assert.equal(n.text, n.key.replace(/\{(\d)\}/g, (_, i) => n.values[i]), 'the key and its values make the sentence');
71});
72
73// ------------------------------------------------------------------------------------------------ the projector
74
75const chunk = (c, attemptId = 'a1') => ({ type: 'assistant-stream', frame: { type: 'chunk', attemptId, chunk: c } });
76const event = (type, data = {}) => ({ type: 'event', event: { type, time: Date.now(), data } });
77
78test('the projector streams a growing draft frame for a call being written, and the whole call ends it', () => {
79  const p = new TurnProjector();
80  const frames = [];
81  const head = '{"file_path":"big.txt","content":"';
82  frames.push(...p.consume(chunk({ type: 'tool-call-delta', id: 'c1', name: 'write', argumentsDelta: head })));
83  assert.equal(frames.filter(f => f.type === 'agent-tool-draft').length, 1, 'the first piece shows at once');
84  const first = frames.find(f => f.type === 'agent-tool-draft').draft;
85  assert.equal(first.name, 'write'); assert.equal(first.target, 'big.txt'); assert.equal(first.scope, 'write'); assert.equal(first.verb, 'Writing a file');
86  // A burst inside 200 ms sends no more frames, but the next one after the pause carries everything so far.
87  for (let i = 0; i < 20; i++) p.consume(chunk({ type: 'tool-call-delta', id: 'c1', argumentsDelta: `entry ${i}\\n` }));
88  assert.equal(p.composing.get('c1').lines, 20);
89  p.composing.get('c1').at = 0;
90  const later = p.consume(chunk({ type: 'tool-call-delta', id: 'c1', argumentsDelta: 'entry 20\\n' })).find(f => f.type === 'agent-tool-draft').draft;
91  assert.equal(later.lines, 21); assert.match(later.preview, /entry 20\n$/);
92  const out = p.consume(event('tool/call', { callId: 'c1', name: 'write', arguments: '{"file_path":"big.txt","content":"x"}' }));
93  assert.ok(out.some(f => f.type === 'agent-tool'), 'the ordinary card takes over');
94  assert.equal(out.find(f => f.type === 'agent-tool-draft')?.draft.done, true, 'and the draft is closed');
95  assert.equal(p.composing.size, 0);
96});
97
98test('a reply cut in a call: the done frame says length and what was lost, and the draft is taken down', () => {
99  const p = new TurnProjector();
100  p.consume(chunk({ type: 'tool-call-delta', id: 'c9', name: 'write', argumentsDelta: '{"file_path":"/w/pagoda.html","content":"abc' }));
101  p.consume(chunk({ type: 'usage', usage: { inputTokens: 6000, outputTokens: 19660 } }));
102  p.consume(event('turn/end', { reason: { kind: 'max-tokens' } }));
103  assert.deepEqual(p.cut(), { tokens: 19660, calls: [{ name: 'write', target: '/w/pagoda.html', bytes: p.composing.get('c9').bytes }] });
104  const frames = p.finish({ model: 'm', contextMax: 65536 });
105  const drop = frames.find(f => f.type === 'agent-tool-draft');
106  assert.ok(drop && drop.draft.done && drop.draft.lost, 'the writing card goes away');
107  const done = frames.at(-1);
108  assert.equal(done.type, 'done'); assert.equal(done.finishReason, 'length');
109  assert.equal(done.cut.tokens, 19660); assert.equal(done.cut.calls[0].target, '/w/pagoda.html');
110});
111
112test('a call nobody writes a card for (a helper agent) makes no draft', () => {
113  const p = new TurnProjector();
114  const out = p.consume(chunk({ type: 'tool-call-delta', id: 's1', name: 'subagent', argumentsDelta: '{"prompt":"x' }));
115  assert.equal(out.filter(f => f.type === 'agent-tool-draft').length, 0);
116});
117
118// ------------------------------------------------------------------------------------------------ with the real Harness
119
120async function rig(t, { window = 65536 } = {}) {
121  const worker = await startScriptedWorker({ chunkDelayMs: 5 });
122  const dir = mkdtempSync(join(tmpdir(), 'strata-lost-'));
123  const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
124  const logs = [];
125  const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: window, slots: 2 }], connections: () => [],
126    env: process.env, startTimeoutMs: 90_000, log: l => logs.push(l) });
127  t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } });
128  return { worker, bridge, ws, logs, base: (chatId, onFrame) => ({ chatId, workspacePath: ws, mode: 'bypass', thinking: 'Off', onFrame }) };
129}
130const words = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');
131const capOf = q => q.params.max_tokens ?? q.params.max_completion_tokens;
132const writes = r => r.worker.requests.filter(q => q.directive === 'cutwrite' || q.directive === 'cutalways');
133
134test('every model request may produce half the window, not the 30 percent the Harness reserves for compaction', { skip }, async (t) => {
135  const r = await rig(t);
136  const out = [];
137  await r.bridge.runTurn({ ...r.base('c0', f => out.push(f)), message: 'SCRIPT:echo hello' });
138  const asked = r.worker.requests.find(q => q.directive === 'echo');
139  assert.ok(asked, 'the model was asked');
140  assert.equal(capOf(asked), 32768, `the request carried ${capOf(asked)}; the pagoda's carried 19660`);
141});
142
143test('a small window still gets a request that fits it (the Harness clamps to the room left)', { skip }, async (t) => {
144  const r = await rig(t, { window: 8192 });
145  await r.bridge.runTurn({ ...r.base('c0s', () => {}), message: 'SCRIPT:echo hello' });
146  const asked = r.worker.requests.find(q => q.directive === 'echo');
147  assert.ok(capOf(asked) > 0 && capOf(asked) <= 4096, `max_tokens ${capOf(asked)} for an 8K window`);
148});
149
150test('a reply cut inside a file write: the chat says so, the agent is asked to go on in smaller parts, and the file gets written', { skip }, async (t) => {
151  const r = await rig(t);
152  const out = [];
153  await r.bridge.runTurn({ ...r.base('c1', f => out.push(f)), message: 'SCRIPT:cutwrite big.txt' });
154  const said = out.find(f => f.type === 'delta' && f.noteReason === 'cut');
155  assert.ok(said, 'a sentence about the cut');
156  assert.match(said.text, /while writing big\.txt/); assert.match(said.text, /that write did not happen. I asked the assistant to look at what is on disk and write the rest in smaller parts/);
157  assert.equal(out.filter(f => f.type === 'error').length, 0);
158  const done = out.filter(f => f.type === 'done').at(-1);
159  assert.equal(done.finishReason, 'stop', 'the turn ends on the agent\'s own finish, not on the cut');
160  assert.ok(existsSync(join(r.ws, 'big.txt')), 'the file is on disk');
161  assert.match(readFileSync(join(r.ws, 'big.txt'), 'utf8'), /entry 0001/);
162  assert.match(words(out), /Written in parts/);
163  assert.equal(writes(r).length, 3, 'the cut reply, the nudged write, the closing words');
164  assert.ok(writes(r)[1].raw.includes('cut off by the output limit'), 'the second request carries the nudge');
165  const drafts = out.filter(f => f.type === 'agent-tool-draft');
166  assert.ok(drafts.length >= 2, 'the writing was shown live');
167  assert.ok(drafts.some(f => !f.draft.done && f.draft.name === 'write'), 'a writing card opened as soon as the model named the call');
168  // The Harness hands the streamed pieces over in batches (a few a second at most), so a short script may show only the first and the last.
169  assert.ok(drafts.some(f => f.draft.done && f.draft.lost && f.draft.target === 'big.txt' && f.draft.bytes > 1000), 'and taken down, with its file and size, when it was lost');
170});
171
172test(`a model that is cut every time is asked ${MAX_CUT_RETRIES} times, then the turn ends with a plain sentence, never silently`, { skip }, async (t) => {
173  const r = await rig(t);
174  const out = [];
175  await r.bridge.runTurn({ ...r.base('c2', f => out.push(f)), message: 'SCRIPT:cutalways big.txt' });
176  assert.equal(writes(r).length, MAX_CUT_RETRIES + 1);
177  const notes = out.filter(f => f.type === 'delta' && f.noteReason === 'cut');
178  assert.equal(notes.length, MAX_CUT_RETRIES + 1, 'one sentence per cut');
179  assert.match(notes.at(-1).text, /that write did not happen\. Say “continue”/);
180  const done = out.filter(f => f.type === 'done').at(-1);
181  assert.ok(done, 'the turn ended');
182  assert.equal(done.finishReason, 'length');
183  assert.equal(done.cut.calls[0].target, 'big.txt');
184  assert.equal(existsSync(join(r.ws, 'big.txt')), false, 'nothing half-written is left behind');
185});