okami.mom/strata

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

Niko1221Merge f-020-int into f-020-rel3d9c21509

main
19.8 KiB284 linesraw
1/**
2 * Helper agents (the Harness's subagents) in the chat: rows, concurrency, one approval card, Stop, and /goal.
3 *
4 * Pure tests always run; the rest need a built Harness (STRATA_HARNESS_DIR) and skip loudly without it.
5 * The model is scripted; the Harness, its subagent runtime, its approval service, the gate and the bridge are real.
6 */
7import test from 'node:test';
8import assert from 'node:assert/strict';
9import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
10import { tmpdir } from 'node:os';
11import { join } from 'node:path';
12import { startScriptedWorker } from './helpers/scripted-worker.mjs';
13import { createAgentBridge, plainBlocker, goalEnding, plainGoalError } from '../server/agent/agent-bridge.mjs';
14import { resolveHarness } from '../server/agent/harness-runtime.mjs';
15import { ChildProjector, activityOf } from '../server/agent/children.mjs';
16
17const HARNESS = process.env.STRATA_HARNESS_DIR;
18const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
19const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } };
20const fwd = p => p.replaceAll('\\', '/');
21
22// ---------------------------------------------------------------------------------------------------------- pure
23
24const ev = (type, data, extra = {}) => ({ type: 'event', event: { seq: 1, time: extra.time ?? 1000, type, data } });
25
26test('a helper row follows its helper: queued, working, completed with its closing words, tokens counted', () => {
27  let t = 0;
28  const cp = new ChildProjector({ id: 'c1', name: 'Check the tests', task: 'Run the unit tests and report', now: () => (t += 100) });
29  assert.equal(cp.agent().status, 'queued');
30  assert.equal(cp.agent().description, 'Waiting for its turn. Run the unit tests and report');
31  cp.consume(ev('step/start', { turn: 1, step: 1 }));
32  assert.equal(cp.agent().status, 'queued', 'a request that was sent is still waiting until the engine says its first word');
33  cp.consume({ type: 'assistant-stream', frame: { type: 'chunk', chunk: { type: 'text-delta', text: 'Running' } } });
34  assert.equal(cp.agent().status, 'working');
35  assert.equal(cp.agent().description, 'Run the unit tests and report');
36  cp.consume({ type: 'assistant-stream', frame: { type: 'chunk', chunk: { type: 'usage', usage: { inputTokens: 100, outputTokens: 20 } } } });
37  assert.equal(cp.agent().tokens, 120);
38  cp.consume(ev('assistant/message', { message: { content: [{ type: 'text', text: 'All 12 tests pass.' }] } }));
39  cp.consume(ev('turn/end', { turn: 1, reason: { kind: 'completed' } }));
40  const row = cp.agent();
41  assert.equal(row.status, 'completed'); assert.equal(row.description, 'All 12 tests pass.');
42  assert.ok(row.durationMs > 0);
43  assert.ok(['id', 'name', 'description', 'status', 'durationMs', 'tokens', 'updatedAt'].every(k => k in row), 'exactly the fields the existing rows read');
44});
45
46test('a helper that failed or was stopped says so in plain words', () => {
47  const failed = new ChildProjector({ id: 'f', name: 'A' });
48  failed.consume(ev('step/start', {}));
49  failed.consume(ev('turn/end', { reason: { kind: 'error', error: { message: 'fetch failed: ECONNREFUSED' } } }));
50  assert.equal(failed.agent().status, 'failed'); assert.match(failed.agent().description, /not reachable/);
51  const stopped = new ChildProjector({ id: 's', name: 'B' });
52  stopped.consume(ev('turn/end', { reason: { kind: 'aborted' } }));
53  assert.deepEqual([stopped.agent().status, stopped.agent().description], ['cancelled', 'Stopped.']);
54});
55
56test('only a helper request that needs the person becomes a card, and its id names the helper', () => {
57  const cp = new ChildProjector({ id: 'child-1', name: 'Writer' });
58  assert.deepEqual(cp.consume(ev('tool/call', { callId: 'k1', name: 'read', arguments: '{"file_path":"a"}' })).frames, [], 'a read is not a card');
59  cp.consume(ev('tool/result', { message: { toolCallId: 'k1', content: [{ type: 'text', text: 'x' }] } }));
60  cp.consume(ev('tool/call', { callId: 'k2', name: 'write', arguments: '{"file_path":"C:/a.txt","content":"x"}' }));
61  const asked = cp.consume(ev('approval/asked', { id: 'a1', callId: 'k2', reason: 'Create or replace the file C:/a.txt' })).frames[0].tool;
62  assert.equal(asked.id, 'child-1:k2'); assert.equal(asked.state, 'proposed'); assert.match(asked.effect, /^Writer asks: Create or replace the file/);
63  assert.equal(cp.consume(ev('approval/decided', { id: 'a1', outcome: 'rejected' })).frames[0].tool.result, 'Denied. Nothing ran.');
64  const done = cp.consume(ev('tool/result', { message: { toolCallId: 'k2', isError: true, content: [{ type: 'text', text: 'Error: the user rejected tool "write"' } ] } })).frames[0].tool;
65  assert.equal(done.state, 'denied'); assert.equal(done.result, 'Denied. Nothing ran.');
66  assert.equal(activityOf('pwsh'), 'Running a command');
67});
68
69test('goal wording: plain, never a code', () => {
70  assert.match(plainBlocker({ code: 'round-limit' }), /most steps/);
71  assert.match(goalEnding({ phase: 'complete' }), /complete/);
72  assert.match(plainGoalError(new Error('goal "x" is not finished; an unfinished goal must be edited')), /already has a goal/);
73  assert.doesNotMatch(plainGoalError(new Error('boom')), /boom/);
74});
75
76// ------------------------------------------------------------------------------------------------- real Harness
77
78async function rig(t, { slots = 4, serial = false, onGoal } = {}) {
79  const worker = await startScriptedWorker({ serial });
80  const dir = mkdtempSync(join(tmpdir(), 'strata-kids-'));
81  const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
82  const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots }];
83  const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000, ...(onGoal ? { onGoal } : {}) });
84  t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
85  const run = async (chatId, message, { mode = 'bypass', answer, onFrame, goal } = {}) => {
86    const frames = [];
87    const on = f => {
88      frames.push({ ...f, at: Date.now() }); onFrame?.(f);
89      if (answer && f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId, callId: f.tool.id, decision: answer }).catch(e => frames.push({ type: 'test-error', message: e.message }));
90    };
91    const result = goal ? await bridge.runTurn({ chatId, workspacePath: ws, mode, goal, onFrame: on }) : await bridge.runTurn({ chatId, message, workspacePath: ws, mode, onFrame: on });
92    return { frames, result };
93  };
94  return { worker, bridge, dir, ws, run };
95}
96const rows = frames => { const m = new Map(); for (const f of frames.filter(x => x.type === 'agent')) m.set(f.agent.id, [...(m.get(f.agent.id) ?? []), f.agent]); return m; };
97const text = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');
98
99test('two helpers run at the same time as two rows, the run ends when both have reported, and the delegation tool shows no raw card', { skip }, async (t) => {
100  const r = await rig(t);
101  const { frames } = await r.run('kids', 'SCRIPT:spawn 2 slow 40');
102  const byId = rows(frames);
103  assert.equal(byId.size, 2);
104  const names = [...byId.values()].map(history => history.at(-1).name).sort();
105  assert.deepEqual(names, ['Helper 1', 'Helper 2']);
106  for (const history of byId.values()) {
107    assert.ok(history.some(a => a.status === 'working'), 'it worked');
108    assert.equal(history.at(-1).status, 'completed');
109    assert.ok(history.at(-1).tokens > 0 && history.at(-1).durationMs > 0);
110    assert.match(history[1]?.description ?? history[0].description, /SCRIPT:slow 40/, 'the row names its task');
111  }
112  // concurrent: both were working before either finished (by the order the frames arrived in, not by the clock: a loaded computer delays a frame, it does not reorder it)
113  const agentFrames = frames.filter(f => f.type === 'agent');
114  const firstDone = agentFrames.findIndex(f => f.agent.status === 'completed');
115  for (const id of byId.keys()) {
116    const working = agentFrames.findIndex(f => f.agent.id === id && f.agent.status === 'working');
117    assert.ok(working >= 0 && working < firstDone, `helper ${id} was working before the first helper finished`);
118  }
119  assert.equal(frames.filter(f => f.type === 'agent-tool').length, 0, 'no card for the delegation tool itself');
120  assert.match(text(frames), /Noted/, 'the parent answered after the helpers reported back');
121  assert.equal(frames.at(-1).type, 'done');
122  assert.ok(frames.at(-1).at >= Math.max(...frames.filter(f => f.type === 'agent' && f.agent.status === 'completed').map(f => f.at)), 'done comes after the last helper');
123  assert.equal(r.bridge.isRunning('kids'), false);
124  assert.equal(r.worker.requests.filter(q => q.directive === 'slow').length, 2);
125});
126
127test('helpers are limited to the Harness cap (4, or the slot count if larger); the fifth is refused with a message the model reads', { skip }, async (t) => {
128  const r = await rig(t, { slots: 2 });
129  const { frames } = await r.run('few', 'SCRIPT:spawn 5 slow 30');
130  assert.equal(rows(frames).size, 4);
131});
132
133test('Manual: a helper that wants to change a file reaches the person as the same single Approve card, and the answer is honoured', { skip }, async (t) => {
134  const r = await rig(t);
135  const approved = join(r.ws, 'from-helper.txt'), denied = join(r.ws, 'denied.txt');
136  const ok = await r.run('kid-ok', `SCRIPT:spawn 1 call write ${JSON.stringify({ file_path: fwd(approved), content: 'by helper' })}`, { mode: 'manual', answer: 'approve' });
137  const okCards = ok.frames.filter(f => f.type === 'agent-tool').map(f => f.tool);
138  assert.deepEqual([...new Set(okCards.map(c => c.state))], ['proposed', 'running', 'done']);
139  assert.equal(new Set(okCards.map(c => c.id)).size, 1); assert.match(okCards[0].id, /^[0-9a-f-]{36}:/);
140  assert.match(okCards[0].effect, /^Helper 1 asks: Create or replace the file/);
141  assert.equal(readFileSync(approved, 'utf8').trim(), 'by helper');
142  const no = await r.run('kid-no', `SCRIPT:spawn 1 call write ${JSON.stringify({ file_path: fwd(denied), content: 'x' })}`, { mode: 'manual', answer: 'deny' });
143  assert.equal(existsSync(denied), false);
144  assert.equal(no.frames.filter(f => f.type === 'agent-tool').at(-1).tool.state, 'denied');
145  assert.equal(no.frames.filter(f => f.type === 'agent-tool').at(-1).tool.result, 'Denied. Nothing ran.');
146  assert.equal(rows(no.frames).size, 1);
147});
148
149test("a chat cannot answer another chat's helper question", { skip }, async (t) => {
150  const r = await rig(t);
151  let asked = null;
152  const file = join(r.ws, 'x.txt');
153  const run = r.run('owner', `SCRIPT:spawn 1 call write ${JSON.stringify({ file_path: fwd(file), content: 'x' })}`, { mode: 'manual', onFrame: f => { if (f.type === 'agent-tool' && f.tool.state === 'proposed') asked = f.tool; } });
154  for (let i = 0; i < 200 && !asked; i++) await new Promise(res => setTimeout(res, 50));
155  assert.ok(asked, 'the question reached the person');
156  await assert.rejects(r.bridge.approve({ chatId: 'someone-else', callId: asked.id, decision: 'approve' }), /no longer waiting/);
157  assert.equal(r.bridge.pendingFor('owner').length, 1);
158  await r.bridge.approve({ chatId: 'owner', callId: asked.id, decision: 'deny' });
159  await run;
160  assert.equal(existsSync(file), false);
161});
162
163test('Stop on the chat stops its helpers, ends the run quickly and starts no further turn', { skip }, async (t) => {
164  const r = await rig(t);
165  const started = Date.now();
166  let stopped = null;
167  const { frames } = await r.run('stopper', 'SCRIPT:spawn 2 slow 2000', { onFrame: f => {
168    if (f.type === 'agent' && f.agent.status === 'working' && !stopped) stopped = new Promise(res => setTimeout(res, 300)).then(() => r.bridge.stop('stopper'));
169  } });
170  const result = await stopped;
171  assert.equal(result.stopped, true);
172  const final = [...rows(frames).values()].map(h => h.at(-1).status);
173  assert.deepEqual(final, ['cancelled', 'cancelled']);
174  assert.ok(Date.now() - started < 40_000, 'seconds, not the 80 s the helpers would have taken (a generous bound: a loaded computer is slow, never that slow)');
175  const done = frames.at(-1);
176  assert.equal(done.type, 'done'); assert.equal(done.cancelled, true);
177  assert.equal(r.bridge.isRunning('stopper'), false);
178  assert.ok(!/Noted/.test(text(frames)), 'the parent was not woken to comment on stopped helpers');
179});
180
181test('/goal: sets a goal, runs its rounds in the chat, says how it ended, refuses a second unfinished goal, and Stop pauses it', { skip }, async (t) => {
182  const r = await rig(t);
183  const frames = [];
184  const say = line => { const out = []; return r.bridge.goalCommand({ chatId: 'g', line, workspacePath: r.ws, mode: 'bypass', onFrame: f => { out.push(f); frames.push(f); } }).then(() => out); };
185  assert.match(text(await say('')), /No goal is set/);
186  const ran = await r.run('g', null, { goal: { action: 'create', objective: 'say hello a few times', maxRounds: 3 } });
187  // The round is a live status now (it used to be an italic line of text that stayed on screen after the model moved on).
188  assert.ok(!/Working on the goal/.test(text(ran.frames)), 'no goal-step text in the message');
189  assert.ok(ran.frames.some(f => f.type === 'status' && f.phase === 'goal' && f.code === 'goal-step' && /^Working on the goal…$/.test(f.text) && f.args.round >= 1), 'a goal-step status was sent');
190  const goalFrames = ran.frames.filter(f => f.type === 'goal');
191  assert.ok(goalFrames.length >= 2 && goalFrames[0].goal.objective === 'say hello a few times' && goalFrames[0].goal.maxRounds === 3, 'the goal frame carries the objective and the round limit');
192  assert.equal(goalFrames.at(-1).goal.phase, 'blocked'); assert.match(goalFrames.at(-1).goal.blocked, /most steps/);
193  assert.equal(ran.frames.filter(f => f.type === 'status').at(-1).phase, 'idle', 'the status line is cleared before the end');
194  assert.ok(ran.frames.findIndex(f => f.type === 'status' && f.phase === 'idle') < ran.frames.findIndex(f => f.type === 'done'));
195  assert.match(text(ran.frames), /The goal stopped: it worked for the most steps/);
196  assert.equal(ran.frames.at(-1).type, 'done');
197  assert.match(text(await say('')), /stopped/);
198  assert.match((await say('a different goal')).find(f => f.type === 'error').message, /already has a goal/);
199  assert.match(text(await say('clear')), /cleared/);
200  // a long goal is paused by Stop, and can be resumed
201  const slowGoal = r.run('g2', null, { goal: { action: 'create', objective: 'keep going', maxRounds: 50 } });
202  r.worker.requests.length = 0;
203  await new Promise(res => setTimeout(res, 3500));
204  const stop = await r.bridge.stop('g2');
205  assert.equal(stop.stopped, true);
206  await slowGoal;
207  const before = r.worker.requests.length;
208  await new Promise(res => setTimeout(res, 1500));
209  assert.equal(r.worker.requests.length, before, 'no further round starts after Stop');
210  assert.match(text(await r.bridge.goalCommand({ chatId: 'g2', line: '', workspacePath: r.ws, mode: 'bypass', onFrame: f => frames.push(f) }).then(() => frames.filter(f => f.type === 'delta').slice(-1))), /paused/);
211});
212
213test('one request slot: the second helper shows as waiting for its turn, then works, and the run still ends cleanly', { skip }, async (t) => {
214  const r = await rig(t, { slots: 1, serial: true });
215  const { frames } = await r.run('queue', 'SCRIPT:spawn 2 slow 25');
216  const byId = rows(frames);
217  assert.equal(byId.size, 2, 'both helpers exist (they are not refused)');
218  const histories = [...byId.values()];
219  // walk the frames in order: at some moment one helper was working while the other was waiting for its turn
220  const now = new Map(); let overlap = null;
221  for (const f of frames.filter(x => x.type === 'agent')) {
222    now.set(f.agent.id, f.agent);
223    const all = [...now.values()];
224    const waiting = all.find(a => a.status === 'queued' && a.description.startsWith('Waiting for its turn.'));
225    if (waiting && all.some(a => a.status === 'working')) overlap ??= waiting;
226  }
227  assert.ok(overlap, 'one helper visibly waited for its turn while the other worked');
228  for (const h of histories) assert.equal(h.at(-1).status, 'completed');
229  assert.equal(frames.at(-1).type, 'done');
230});
231
232test('goal bar: the state, pause, edit and remove work from outside a turn, and every change is announced', { skip }, async (t) => {
233  const announced = [];
234  const r = await rig(t, { onGoal: (chatId, goal) => announced.push({ chatId, goal }) });
235  assert.equal(await r.bridge.goalState('bar'), null, 'no goal in a chat that never had one');
236  await assert.rejects(r.bridge.goalControl({ chatId: 'bar', action: 'pause' }), /no goal/i);
237  await r.run('bar', null, { goal: { action: 'create', objective: 'say hello a few times', maxRounds: 1 } });
238  const shown = await r.bridge.goalState('bar');
239  assert.equal(shown.objective, 'say hello a few times'); assert.equal(shown.maxRounds, 1); assert.ok(['blocked', 'complete', 'paused', 'active'].includes(shown.phase));
240  await assert.rejects(r.bridge.goalControl({ chatId: 'bar', action: 'edit', text: '  ' }), /few words/);
241  const edited = await r.bridge.goalControl({ chatId: 'bar', action: 'edit', text: 'say goodbye instead' });
242  assert.equal(edited.goal.objective, 'say goodbye instead');
243  assert.equal(announced.at(-1).goal.objective, 'say goodbye instead', 'the edit was announced for the bar');
244  const cleared = await r.bridge.goalControl({ chatId: 'bar', action: 'clear' });
245  assert.deepEqual(cleared, { goal: null }); assert.equal(announced.at(-1).goal, null);
246  assert.equal(await r.bridge.goalState('bar'), null);
247  await assert.rejects(r.bridge.goalControl({ chatId: 'bar', action: 'explode' }), /no goal|not known/i);
248});
249
250test('mode change mid-run: Manual to Bypass settles the question already waiting and the very next tool call does not ask again', { skip }, async (t) => {
251  const r = await rig(t);
252  const first = join(r.ws, 'before.txt');
253  let asked = null; const cards = [];
254  const run = r.run('mid', `SCRIPT:spawn 1 call write ${JSON.stringify({ file_path: fwd(first), content: 'one' })}`, { mode: 'manual', onFrame: f => { if (f.type === 'agent-tool') { cards.push(f.tool); if (f.tool.state === 'proposed') asked = f.tool; } } });
255  for (let i = 0; i < 200 && !asked; i++) await new Promise(res => setTimeout(res, 50));
256  assert.ok(asked, 'Manual asked first');
257  const switched = await r.bridge.setMode('mid', 'bypass');
258  assert.deepEqual({ applied: switched.applied, mode: switched.mode }, { applied: true, mode: 'bypass' });
259  assert.equal(switched.settled, 1, 'the waiting question was settled by the new mode');
260  await run;
261  assert.equal(readFileSync(first, 'utf8').trim(), 'one');
262  assert.equal(r.bridge.pendingFor('mid').length, 0);
263  // Bypass then Plan: nothing waiting, and the chat now reports Plan to the next call.
264  assert.equal((await r.bridge.setMode('mid', 'plan')).mode, 'plan');
265  assert.deepEqual(await r.bridge.setMode('nobody-yet', 'manual'), { applied: false, mode: 'manual', reason: 'no session yet' });
266});
267
268test('the gate stops a helper asking once the chat has left Manual', async () => {
269  const { apply, MANUAL_PRESET } = await import('../server/agent/plugins/strata-gate.mjs');
270  let handler; const appended = [];
271  const parent = { header: { origin: 'user' } };
272  const child = { header: { origin: 'subagent', parentSession: 'p' }, append: (type, data) => appended.push([type, data.policy]) };
273  let preset = MANUAL_PRESET; let override = 'ask';
274  apply({ on: (_e, h) => { handler = h; }, inject: () => {}, sessions: new Map([['p', parent]]), permissionPresets: { current: () => preset }, approval: { overrideOf: () => override } });
275  const exec = { name: 'write', agent: { session: child }, input: { file_path: 'x' } };
276  await handler(exec, async () => ({ kind: 'allow' }));
277  assert.deepEqual(appended, [], 'in Manual the helper keeps asking');
278  preset = 'strata-bypass-ish';
279  await handler(exec, async () => ({ kind: 'allow' }));
280  assert.deepEqual(appended, [['approval/policy', 'never']], 'the first call after the switch un-pins the helper');
281  override = 'never';
282  await handler(exec, async () => ({ kind: 'allow' }));
283  assert.equal(appended.length, 1, 'and does it once');
284});