okami.mom/strata

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

Niko1221merge f-split-s4b 0edf5cb9f (Harness in the app chat, Manual approvals, request slots) into f-split-inta16109803

main
15.9 KiB243 linesraw
1/**
2 * The chat Mode menu (Manual / Plan / Bypass) as real Harness behaviour.
3 *
4 * The Harness is real: its process, its sandbox, its approval gate, its tools, its `/permission` command.
5 * Only the model is scripted (tests/helpers/scripted-worker.mjs), and it behaves like a careful model: when the
6 * sandbox denies a change and offers an escalation, it retries the exact call once with `sandbox_permissions`.
7 * Every test checks the file on disk, not only the frames, because the frames are what the Harness reports.
8 *
9 * Needs STRATA_HARNESS_DIR (a built Harness); without it these tests skip, loudly.
10 */
11import test from 'node:test';
12import assert from 'node:assert/strict';
13import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
14import { tmpdir } from 'node:os';
15import { join } from 'node:path';
16import { startScriptedWorker } from './helpers/scripted-worker.mjs';
17import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
18import { resolveHarness } from '../server/agent/harness-runtime.mjs';
19import { MODE_PRESETS, modeOf, buildProfile } from '../server/agent/profile.mjs';
20import { NOT_IN_MODE, TurnProjector } from '../server/agent/events.mjs';
21
22const HARNESS = process.env.STRATA_HARNESS_DIR;
23const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
24const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* the Harness sandbox leaves access entries; best effort */ } };
25const sleep = ms => new Promise(r => setTimeout(r, ms));
26const lines = file => readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean).length;
27const tools = frames => frames.filter(f => f.type === 'agent-tool');
28const states = frames => tools(frames).map(f => f.tool.state);
29const text = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');
30
31async function rig(t) {
32  const worker = await startScriptedWorker({});
33  const dir = mkdtempSync(join(tmpdir(), 'strata-modes-'));
34  const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
35  const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768 }];
36  const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });
37  t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
38  /** One turn in `mode`; `answer` decides what the person says to an approval card (approve | deny | undefined = nobody answers). */
39  const run = async (chatId, message, { mode, answer, onFrame } = {}) => {
40    const frames = [];
41    await bridge.runTurn({
42      chatId, message, workspacePath: ws, mode,
43      onFrame: f => {
44        frames.push(f); onFrame?.(f);
45        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 }));
46      },
47    });
48    return frames;
49  };
50  /** The preset the Harness itself reports for the chat's session. */
51  const preset = async chatId => {
52    const { rt } = bridge._debug();
53    const r = await rt.gw.rpc('session/projections', { request: { sessionId: bridge.sessionOf(chatId), keys: ['permissions'] } });
54    return r.values.permissions.currentValue;
55  };
56  return { worker, bridge, dir, ws, run, preset };
57}
58
59test('mode mapping: three presets, Manual by default, unknown values fall back to Manual', () => {
60  assert.deepEqual(Object.keys(MODE_PRESETS), ['manual', 'plan', 'bypass']);
61  // Manual leaves the sandbox open and asks BEFORE a change through the Strata gate (plugins/strata-gate.mjs).
62  assert.deepEqual([MODE_PRESETS.manual.sandbox, MODE_PRESETS.manual.approval], ['danger-full-access', 'ask']);
63  assert.deepEqual([MODE_PRESETS.plan.sandbox, MODE_PRESETS.plan.approval], ['read-only', 'never']);
64  assert.deepEqual([MODE_PRESETS.bypass.sandbox, MODE_PRESETS.bypass.approval], ['danger-full-access', 'never']);
65  for (const v of ['manual', 'plan', 'bypass']) assert.equal(modeOf(v), v);
66  for (const v of [undefined, null, '', 'auto', 'accept-edits', 'danger-full-access', 'constructor']) assert.equal(modeOf(v), 'manual', String(v));
67  // Only Bypass gives full access WITHOUT asking, and the profile names our three and nothing else.
68  const entry = JSON.parse(buildProfile({ local: [] }).patch.split('\n').slice(1).join('\n')).find(e => e.id === 'permission');
69  assert.deepEqual(Object.keys(entry.config.presets), ['strata-manual', 'strata-plan', 'strata-bypass']);
70  assert.equal(entry.config.defaultPreset, 'strata-manual');
71  assert.deepEqual(Object.entries(entry.config.presets).filter(([, p]) => p.sandbox === 'danger-full-access' && p.approval === 'never').map(([k]) => k), ['strata-bypass']);
72  assert.deepEqual(Object.entries(entry.config.presets).filter(([, p]) => p.sandbox !== 'danger-full-access').map(([k]) => k), ['strata-plan']);
73});
74
75test('projection: under "never" no card ever offers Approve; "ask" marks the approved card', () => {
76  const call = { type: 'event', event: { seq: 1, time: 1, type: 'tool/call', data: { callId: 'c1', name: 'write', arguments: { file_path: 'x.txt', content: 'x' } } } };
77  const asked = { type: 'event', event: { seq: 2, time: 2, type: 'approval/asked', data: { id: 'a1', callId: 'c1', reason: 'escalate sandbox to workspace-write: because' } } };
78  const rejected = { type: 'event', event: { seq: 3, time: 3, type: 'approval/decided', data: { id: 'a1', outcome: 'rejected' } } };
79  const failed = { type: 'event', event: { seq: 4, time: 4, type: 'tool/result', data: { message: { toolCallId: 'c1', isError: true, content: [{ type: 'text', text: 'Error: the user rejected escalating' }] } } } };
80  const never = new TurnProjector({ policy: 'never' });
81  const frames = [call, asked, rejected, failed].flatMap(i => never.consume(i));
82  assert.deepEqual(frames.map(f => f.tool.state), ['running', 'denied', 'denied']);
83  assert.ok(frames.every(f => !f.tool.approved));
84  assert.equal(frames.at(-1).tool.result, NOT_IN_MODE);
85
86  const ask = new TurnProjector({ policy: 'ask' });
87  const ok = { type: 'event', event: { seq: 3, time: 3, type: 'approval/decided', data: { id: 'a1', outcome: 'allowed-once' } } };
88  const done = { type: 'event', event: { seq: 4, time: 4, type: 'tool/result', data: { message: { toolCallId: 'c1', isError: false, content: [{ type: 'text', text: 'Created file' }] } } } };
89  const f2 = [call, asked, ok, done].flatMap(i => ask.consume(i));
90  assert.deepEqual(f2.map(f => f.tool.state), ['running', 'proposed', 'running', 'done']);
91  assert.equal(f2.at(-1).tool.approved, true);
92  // A call that never asked finishes without the flag.
93  const plain = new TurnProjector({ policy: 'ask' });
94  const f3 = [call, done].flatMap(i => plain.consume(i));
95  assert.equal(f3.at(-1).tool.state, 'done'); assert.equal(f3.at(-1).tool.approved, undefined);
96});
97
98test('MODE Manual: an in-workspace write is held for the person, and runs once after Approve', { skip }, async t => {
99  const r = await rig(t);
100  let fileWhileAsking = null;
101  const frames = await r.run('m-manual-write', 'SCRIPT:retrywrite approved.txt hello', {
102    mode: 'manual', answer: 'approve',
103    onFrame: f => { if (f.type === 'agent-tool' && f.tool.state === 'proposed') fileWhileAsking = existsSync(join(r.ws, 'approved.txt')); },
104  });
105  assert.equal(fileWhileAsking, false, 'the file must not exist while the card is asking');
106  const final = tools(frames).at(-1).tool;
107  assert.equal(final.state, 'done'); assert.equal(final.approved, true); assert.equal(final.scope, 'write');
108  assert.ok(states(frames).includes('proposed'));
109  assert.equal(lines(join(r.ws, 'approved.txt')), 1);
110  assert.equal(frames.find(f => f.type === 'start').mode, 'manual');
111  assert.equal(await r.preset('m-manual-write'), MODE_PRESETS.manual.key);
112  assert.equal(frames.at(-1).type, 'done');
113});
114
115test('MODE Manual: Deny leaves the file absent, and a shell command that writes is held too', { skip }, async t => {
116  const r = await rig(t);
117  const denied = await r.run('m-manual-deny', 'SCRIPT:retrywrite denied.txt nope', { mode: 'manual', answer: 'deny' });
118  assert.equal(existsSync(join(r.ws, 'denied.txt')), false);
119  assert.equal(states(denied).at(-1), 'denied');
120  assert.equal(denied.at(-1).type, 'done');
121
122  const shell = await r.run('m-manual-shell', 'SCRIPT:retryshell shell.txt via-shell', { mode: 'manual', answer: 'approve' });
123  assert.ok(states(shell).includes('proposed'), 'the shell write asked first');
124  const card = tools(shell).at(-1).tool;
125  assert.equal(card.scope, 'shell'); assert.equal(card.state, 'done'); assert.equal(card.approved, true);
126  assert.equal(lines(join(r.ws, 'shell.txt')), 1);
127});
128
129test('MODE Manual: reading needs no question', { skip }, async t => {
130  const r = await rig(t);
131  writeFileSync(join(r.ws, 'notes.txt'), 'plain notes\n');
132  const frames = await r.run('m-manual-read', 'SCRIPT:read notes.txt', { mode: 'manual' });
133  assert.deepEqual([...new Set(states(frames))], ['running', 'done']);
134  assert.equal(tools(frames).at(-1).tool.approved, undefined);
135  assert.match(tools(frames).at(-1).tool.result, /plain notes/);
136});
137
138test('MODE Plan: a write is refused with no question, the file never appears, reading still works', { skip }, async t => {
139  const r = await rig(t);
140  const frames = await r.run('m-plan', 'SCRIPT:retrywrite plan.txt nope', { mode: 'plan' });
141  assert.equal(existsSync(join(r.ws, 'plan.txt')), false);
142  assert.ok(!states(frames).includes('proposed'), 'Plan never shows an Approve card');
143  assert.equal(states(frames).at(-1), 'denied');
144  assert.equal(tools(frames).at(-1).tool.result, NOT_IN_MODE);
145  assert.equal(frames.at(-1).type, 'done', 'the turn still settles; the agent answers');
146  assert.equal(await r.preset('m-plan'), MODE_PRESETS.plan.key);
147  assert.equal(r.bridge.status().pendingApprovals, 0);
148
149  const shell = await r.run('m-plan-shell', 'SCRIPT:retryshell plan-shell.txt nope', { mode: 'plan' });
150  assert.equal(existsSync(join(r.ws, 'plan-shell.txt')), false);
151  assert.ok(!states(shell).includes('proposed'));
152
153  writeFileSync(join(r.ws, 'readme.txt'), 'readable in plan mode\n');
154  const read = await r.run('m-plan-read', 'SCRIPT:read readme.txt', { mode: 'plan' });
155  assert.equal(tools(read).at(-1).tool.state, 'done');
156  assert.match(tools(read).at(-1).tool.result, /readable in plan mode/);
157});
158
159test('MODE Bypass is full access: in-workspace and outside writes run without asking', { skip }, async t => {
160  const r = await rig(t);
161  const frames = await r.run('m-bypass', 'SCRIPT:retrywrite free.txt hello', { mode: 'bypass' });
162  assert.ok(!states(frames).includes('proposed'), 'Bypass asks nothing');
163  assert.equal(lines(join(r.ws, 'free.txt')), 1);
164  const card = tools(frames).at(-1).tool;
165  assert.equal(card.state, 'done'); assert.equal(card.approved, undefined, 'it ran; nobody approved it');
166  assert.equal(await r.preset('m-bypass'), MODE_PRESETS.bypass.key);
167
168  const shell = await r.run('m-bypass-shell', 'SCRIPT:retryshell free-shell.txt hello', { mode: 'bypass' });
169  assert.ok(!states(shell).includes('proposed'));
170  assert.equal(lines(join(r.ws, 'free-shell.txt')), 1);
171
172  // Bypass is the Harness's full access with no prompts: a call that asks for danger-full-access runs, in the workspace or outside it.
173  const wide = await r.run('m-bypass-wide', 'SCRIPT:tool wide.txt x', { mode: 'bypass' });
174  assert.ok(!states(wide).includes('proposed'), 'full access asks nothing');
175  assert.equal(lines(join(r.ws, 'wide.txt')), 1);
176  assert.equal(states(wide).at(-1), 'done');
177  const outside = join(r.dir, 'outside-workspace.txt');
178  const out = await r.run('m-bypass-outside', `SCRIPT:tool ${outside} y`, { mode: 'bypass' });
179  assert.ok(!states(out).includes('proposed'));
180  assert.equal(lines(outside), 1, 'a path outside the workspace was written');
181  assert.equal(states(out).at(-1), 'done');
182});
183
184test('MODE the choice follows the chat: it changes on the next turn, keeps the session, and an unknown value is Manual', { skip }, async t => {
185  const r = await rig(t);
186  await r.run('m-switch', 'SCRIPT:echo one', { mode: 'manual' });
187  const session = r.bridge.sessionOf('m-switch');
188  assert.equal(await r.preset('m-switch'), MODE_PRESETS.manual.key);
189  await r.run('m-switch', 'SCRIPT:echo two', { mode: 'plan' });
190  assert.equal(await r.preset('m-switch'), MODE_PRESETS.plan.key);
191  const bypass = await r.run('m-switch', 'SCRIPT:retrywrite switched.txt hi', { mode: 'bypass' });
192  assert.equal(lines(join(r.ws, 'switched.txt')), 1);
193  assert.ok(!states(bypass).includes('proposed'));
194  // Back to Manual: asks again, on the same session, and the earlier turns are still its history.
195  const manual = await r.run('m-switch', 'SCRIPT:retrywrite switched-again.txt hi', { mode: 'manual', answer: 'approve' });
196  assert.ok(states(manual).includes('proposed'));
197  assert.equal(r.bridge.sessionOf('m-switch'), session);
198  // A mode the app does not offer (older stored value) or none at all is Manual, never something looser.
199  for (const [chat, mode] of [['m-odd-1', 'auto'], ['m-odd-2', undefined], ['m-odd-3', 'danger-full-access']]) {
200    const f = await r.run(chat, 'SCRIPT:retrywrite odd.txt x', { mode, answer: 'deny' });
201    assert.ok(states(f).includes('proposed'), `${mode} asks like Manual`);
202  }
203  assert.equal(existsSync(join(r.ws, 'odd.txt')), false);
204});
205
206test('MODE changing the mode while a turn runs does not touch that turn', { skip }, async t => {
207  const r = await rig(t);
208  const frames = [];
209  const slow = r.bridge.runTurn({ chatId: 'm-mid', message: 'SCRIPT:slow 120', workspacePath: r.ws, mode: 'manual', onFrame: f => frames.push(f) });
210  for (let i = 0; i < 200 && frames.filter(f => f.type === 'delta').length < 3; i++) await sleep(50);
211  assert.ok(frames.filter(f => f.type === 'delta').length >= 3, 'the turn must be live first');
212  // The person flips the menu to Bypass and sends again. The second send is refused (a chat runs one turn at a time) and,
213  // because it is refused before anything is applied, the running turn's permissions do not move.
214  await assert.rejects(r.bridge.runTurn({ chatId: 'm-mid', message: 'SCRIPT:echo x', workspacePath: r.ws, mode: 'bypass', onFrame: () => {} }), /still working/);
215  assert.equal(await r.preset('m-mid'), MODE_PRESETS.manual.key);
216  // Another chat in another mode is its own session and does not move this one either.
217  await r.run('m-mid-other', 'SCRIPT:echo y', { mode: 'bypass' });
218  assert.equal(await r.preset('m-mid'), MODE_PRESETS.manual.key);
219  await slow;
220  assert.equal(frames.filter(f => f.type === 'delta').length, 120, 'the running turn completed untouched');
221  assert.equal(frames.at(-1).finishReason, 'stop');
222  // And the new choice is what the next turn uses.
223  await r.run('m-mid', 'SCRIPT:echo z', { mode: 'bypass' });
224  assert.equal(await r.preset('m-mid'), MODE_PRESETS.bypass.key);
225});
226
227test('MODE the mode survives a restart of the agent process: the chat resumes in the mode it is asked for', { skip }, async t => {
228  const r = await rig(t);
229  await r.run('m-restart', 'SCRIPT:echo one', { mode: 'plan' });
230  const session = r.bridge.sessionOf('m-restart');
231  await r.bridge.close();
232  // A new bridge over the same data directory: the persisted session is resumed, then put in the requested mode.
233  const worker2 = r.worker;
234  const bridge2 = createAgentBridge({ dataDir: r.dir, localInstances: () => [{ id: 'inst-1', label: 'Scripted', baseUrl: worker2.url, modelId: 'scripted-model', context: 32768 }], connections: () => [], env: process.env, startTimeoutMs: 90_000 });
235  t.after(() => bridge2.close());
236  const frames = [];
237  await bridge2.runTurn({ chatId: 'm-restart', message: 'SCRIPT:retrywrite resumed.txt hi', workspacePath: r.ws, mode: 'bypass', onFrame: f => frames.push(f) });
238  assert.equal(bridge2.sessionOf('m-restart'), session, 'the same session');
239  assert.equal(lines(join(r.ws, 'resumed.txt')), 1);
240  const { rt } = bridge2._debug();
241  const now = await rt.gw.rpc('session/projections', { request: { sessionId: session, keys: ['permissions'] } });
242  assert.equal(now.values.permissions.currentValue, MODE_PRESETS.bypass.key);
243});