okami.mom/strata

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

Niko1221Merge f-027-i18n: French as the ninth app language and the Polish README52ba0b781

main
10.5 KiB154 linesraw
1// The turn guard: a search-heavy /plan that keeps failing searches and rewriting its plan is stopped by the app and ends with a plain message;
2// a context at 100% never ends silently. The pure counting always runs; the end-to-end ones need a built Harness (STRATA_HARNESS_DIR) and
3// run the real search code on a pretend web that refuses (no network).
4import test from 'node:test';
5import assert from 'node:assert/strict';
6import { mkdtempSync, mkdirSync, rmSync, readFileSync } from 'node:fs';
7import { tmpdir } from 'node:os';
8import { join } from 'node:path';
9import { TurnGuard, GUARD_LIMITS, GUARD_NOTES, guardNote } from '../server/agent/turn-guard.mjs';
10import { startScriptedWorker } from './helpers/scripted-worker.mjs';
11import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
12import { resolveHarness } from '../server/agent/harness-runtime.mjs';
13
14const HARNESS = process.env.STRATA_HARNESS_DIR;
15const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
16
17const search = (id, state, result = '') => ({ id, name: 'web_search', state, result });
18const LIMITED = 'Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings → Tools → Web search. Do not retry this search';
19
20test('three failed searches in a row stop the turn; a search that worked starts the count again', () => {
21  const g = new TurnGuard({ plan: true, contextMax: 32768 });
22  assert.equal(g.card(search('a', 'running')), null, 'a running search is not counted yet');
23  assert.equal(g.card(search('a', 'error', LIMITED)), null);
24  assert.equal(g.card(search('a', 'error', LIMITED)), null, 'the same card twice is one search');
25  assert.equal(g.card(search('b', 'done', 'three results')), null);
26  assert.equal(g.card(search('c', 'error', LIMITED)), null);
27  assert.equal(g.card(search('d', 'done', LIMITED)), null, 'a refusal that arrives as a normal result still counts');
28  assert.equal(g.card(search('e', 'error', LIMITED)), 'searches-failed');
29  assert.equal(g.card(search('f', 'error', LIMITED)), 'searches-failed', 'once stopped it stays stopped');
30  assert.equal(g.searches, 5);
31});
32
33test('other tools are not searches; too many searches in one turn stop it even when they work', () => {
34  const g = new TurnGuard({ plan: true });
35  for (let i = 0; i < 50; i++) assert.equal(g.card({ id: `r${i}`, name: 'read', state: 'done' }), null);
36  for (let i = 0; i < GUARD_LIMITS.searchesPlan - 1; i++) assert.equal(g.card(search(`s${i}`, 'done', 'ok')), null);
37  assert.equal(g.card(search('last', 'done', 'ok')), 'searches');
38  const t = new TurnGuard({ plan: false });
39  for (let i = 0; i < GUARD_LIMITS.searchesTurn - 1; i++) assert.equal(t.card(search(`s${i}`, 'done', 'ok')), null);
40  assert.equal(t.card(search('last', 'done', 'ok')), 'searches');
41});
42
43test('a plan turn that writes its numbered plan from 1. again and again is stopped; a single plan is not', () => {
44  const g = new TurnGuard({ plan: true });
45  const plan = '## Plan\n\n1. First\n2. Second\n3. Third\n\n';
46  let reason = null;
47  for (let i = 0; i < GUARD_LIMITS.planRewrites - 1; i++) reason ??= g.text(plan);
48  assert.equal(reason, null, `${GUARD_LIMITS.planRewrites - 1} versions are fine`);
49  assert.equal(g.text(plan), 'rewrites');
50  const one = new TurnGuard({ plan: true });
51  for (const piece of ['Some looking around.\n\n## Plan\n\n', '1. First\n', '2. Second\n', '   1. a sub point\n', '3. Third\n']) assert.equal(one.text(piece), null, piece);
52  const ordinary = new TurnGuard({ plan: false });
53  for (let i = 0; i < 10; i++) assert.equal(ordinary.text(plan), null, 'only a plan turn counts rewrites');
54});
55
56test('a nearly full context stops the turn; a normal one does not', () => {
57  const g = new TurnGuard({ contextMax: 10000 });
58  assert.equal(g.context(5000), null);
59  assert.equal(g.context(9200), null);
60  assert.equal(g.context(9300), 'context');
61  assert.equal(new TurnGuard({ contextMax: 0 }).context(1e9), null, 'an unknown window is never guessed');
62});
63
64test('a turn that ends with no words always gets a plain message: out of room, or nothing written', () => {
65  const g = new TurnGuard({ contextMax: 10000 });
66  const done = { kind: 'completed' };
67  assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 9700 }), 'context');
68  assert.equal(g.silent({ ended: { kind: 'max-tokens' }, wrote: false, contextTokens: 9000 }), 'context');
69  assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 3000 }), 'empty');
70  assert.equal(g.silent({ ended: done, wrote: false, acted: true, contextTokens: 3000 }), null, 'cards of finished work are an answer of a kind');
71  assert.equal(g.silent({ ended: done, wrote: false, acted: true, contextTokens: 9700 }), 'context', 'but a full context is never silent');
72  assert.equal(g.silent({ ended: done, wrote: true, contextTokens: 9700 }), null, 'there are words: nothing to add');
73  assert.equal(g.silent({ ended: { kind: 'error', error: { message: 'x' } }, wrote: false, contextTokens: 9700 }), null, 'an error says why by itself');
74  assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 9700, stoppedByPerson: true }), null, 'Stop is the person\'s own');
75});
76
77test('every message is a plain sentence with a next step, carries its interface key, and is in the catalog in all nine languages', () => {
78  const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr'];
79  const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(readFileSync(new URL(`../src/locales/${l}.json`, import.meta.url), 'utf8'))]));
80  const idOf = text => Object.entries(catalogs.en).find(([, v]) => v === text)?.[0];
81  for (const [reason, text] of Object.entries(GUARD_NOTES)) {
82    const frame = guardNote(reason);
83    assert.equal(frame.type, 'delta'); assert.equal(frame.key, text); assert.equal(frame.own, true);
84    assert.ok(text.length < 220, reason);
85    assert.match(text, /(Try again|Tell me|Say|Send|approve)/i, `${reason} gives a next step`);
86    const id = idOf(text);
87    assert.ok(id, `${reason} is in the English catalog`);
88    for (const l of langs) assert.ok(catalogs[l][id]?.trim(), `${reason} in ${l}`);
89  }
90  assert.match(GUARD_NOTES.context, /ran out of room/);
91});
92
93// ------------------------------------------------------------------------------------------------ with the real Harness
94
95async function rig(t, options = {}) {
96  const worker = await startScriptedWorker({ chunkDelayMs: 5 });
97  const dir = mkdtempSync(join(tmpdir(), 'strata-guard-'));
98  const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
99  const logs = [];
100  const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: options.context ?? 32768, slots: 2 }], connections: () => [],
101    // these chats are in Manual and search without a person at the card: the Settings switch that skips the web question is on
102    tools: () => ({ off: new Set(), search: { provider: 'builtin', key: '' }, servers: {}, webWithoutAsking: true }),
103    env: process.env, startTimeoutMs: 90_000, searchMock: 'limited', log: l => logs.push(l) });
104  t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } });
105  return { worker, bridge, ws, logs, base: (chatId, onFrame) => ({ chatId, workspacePath: ws, mode: 'manual', onFrame }) };
106}
107const words = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');
108
109test('a search-heavy /plan on a web that keeps refusing stops after 3 failed searches, proposes the plan it has, and says why', { skip }, async (t) => {
110  const r = await rig(t);
111  const out = [];
112  await r.bridge.planCommand({ ...r.base('p1', f => out.push(f)), line: 'SCRIPT:searchloop' });
113  const cards = out.filter(f => f.type === 'agent-tool' && f.tool.name === 'web_search' && ['done', 'error'].includes(f.tool.state));
114  assert.ok(cards.length >= 3 && cards.length <= 4, `searches stopped at the limit (${cards.length})`);
115  assert.ok(cards.some(f => /Web search is limited right now/.test(f.tool.result ?? '')), 'the tool said web search is limited');
116  assert.equal(out.filter(f => f.type === 'error').length, 0, 'not an error: a normal end');
117  const done = out.find(f => f.type === 'done');
118  assert.ok(done && !done.cancelled, 'the turn ended normally');
119  const plan = out.find(f => f.type === 'plan');
120  assert.equal(plan?.event, 'proposed', 'the plan it had is offered');
121  assert.equal(plan.plan.steps.length, 3);
122  assert.equal(plan.plan.caution, GUARD_NOTES['searches-failed'], 'and the card says why it stopped early');
123  const requests = r.worker.requests.filter(q => q.directive === 'searchloop');
124  assert.ok(requests.length <= 5, `the model was not asked again and again (${requests.length} requests)`);
125  assert.ok(r.logs.some(l => /turn guard: searches-failed/.test(l)));
126});
127
128test('an ordinary turn whose searches keep failing ends with the plain sentence as its last words', { skip }, async (t) => {
129  const r = await rig(t);
130  const out = [];
131  await r.bridge.runTurn({ ...r.base('c1', f => out.push(f)), message: 'SCRIPT:searchloop' });
132  assert.equal(out.filter(f => f.type === 'error').length, 0);
133  assert.ok(out.find(f => f.type === 'done'));
134  const note = out.filter(f => f.type === 'delta' && f.key).at(-1);
135  assert.equal(note?.key, GUARD_NOTES['searches-failed']);
136  assert.match(words(out), /Settings → Tools → Web search/);
137  assert.ok(out.findIndex(f => f.key) < out.findIndex(f => f.type === 'done'), 'the sentence comes before the end of the turn');
138});
139
140test('a context at 100% with no answer is never silent: the plain message comes, and the older messages are summarised', { skip }, async (t) => {
141  const r = await rig(t, { context: 32768 });
142  const out = [];
143  await r.bridge.runTurn({ ...r.base('f1', f => out.push(f)), message: 'SCRIPT:bloat 32000' });
144  assert.equal(out.filter(f => f.type === 'error').length, 0);
145  assert.ok(out.find(f => f.type === 'done'));
146  assert.equal(out.filter(f => f.type === 'delta' && f.key).at(-1)?.key, GUARD_NOTES.context);
147  assert.match(words(out), /ran out of room/);
148  await new Promise(res => setTimeout(res, 1500));
149  const compacted = r.logs.find(l => /compact after a stopped turn/.test(l));
150  assert.match(compacted ?? '', /compact after a stopped turn: \w+/, `compaction was asked for and the Harness answered (${compacted})`);
151  const out2 = [];
152  await r.bridge.runTurn({ ...r.base('f2', f => out2.push(f)), message: 'SCRIPT:bloat 3000' });
153  assert.equal(out2.filter(f => f.type === 'delta' && f.key).at(-1)?.key, GUARD_NOTES.empty, 'no words at all, plenty of room: still a message');
154});