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
6.8 KiB116 linesraw
1/**
2 * Tasks as the agent: a scheduled task runs in a Harness session of its own, under the mode it was given, and its result and a
3 * notification reach the person. Pure tests always run; the rest need a built Harness (STRATA_HARNESS_DIR).
4 */
5import test from 'node:test';
6import assert from 'node:assert/strict';
7import { existsSync, mkdtempSync, mkdirSync, rmSync } from 'node:fs';
8import { tmpdir } from 'node:os';
9import { join } from 'node:path';
10import { startScriptedWorker } from './helpers/scripted-worker.mjs';
11import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
12import { createAgentTaskRunner } from '../server/agent/task-run.mjs';
13import { resolveHarness } from '../server/agent/harness-runtime.mjs';
14import { createTaskService, validateTask, nextRun, TASK_MODES } from '../server/tasks.mjs';
15import { taskReport, cardLine } from '../server/task-report.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('\\', '/');
21const base = { title: 'Open downloads', prompt: 'open my downloads folder', frequency: 'daily', at: '09:00', timeZone: 'UTC' };
22
23test('a task carries the mode it was created with: plan by default, manual and bypass on request, nothing else', () => {
24  assert.deepEqual(TASK_MODES, ['plan', 'manual', 'bypass']);
25  assert.equal(validateTask(base).mode, 'plan');
26  assert.equal(validateTask({ ...base, mode: 'bypass' }).mode, 'bypass');
27  assert.throws(() => validateTask({ ...base, mode: 'auto' }), /what this task may do/);
28});
29
30test('the result lists what it did in plain words and says exactly what needed a yes', () => {
31  const report = taskReport({ text: 'Done.', cards: [
32    { name: 'pwsh', state: 'done', effect: 'List the files', preview: 'Get-ChildItem' },
33    { name: 'pwsh', state: 'denied', effect: 'Run a command that may change things: open the folder', preview: 'explorer.exe C:/Users/x/Downloads' },
34  ] });
35  assert.match(report.text, /^Done\./);
36  assert.match(report.text, /\*\*What it did\*\*/);
37  assert.match(report.text, /- List the files \(Get-ChildItem\)/);
38  assert.match(report.text, /Could not do this by itself: Run a command that may change things: open the folder/);
39  assert.match(report.attention, /needed a yes, which nobody could give while it ran by itself/);
40  assert.match(report.attention, /Nothing was changed/);
41  assert.equal(taskReport({ text: '', cards: [] }).text, 'The task ran and had nothing to report.');
42  assert.equal(taskReport({ text: 'ok', cards: [] }).attention, null);
43  assert.match(cardLine({ state: 'error', effect: 'Opens a web page.', preview: 'https://x' }), /It did not work/);
44});
45
46test('a task scheduled two minutes ahead runs when its minute comes (fake clock), is reported through notify, and the schedule moves on', async () => {
47  let clock = Date.parse('2026-10-16T10:00:20Z');
48  const stored = [];
49  const notified = [];
50  const at = new Date(clock + 2 * 60_000).toISOString().slice(11, 16);   // 10:02
51  const service = createTaskService({
52    read: () => stored, write: records => { stored.length = 0; stored.push(...records); }, now: () => clock,
53    notify: task => notified.push({ title: task.title, status: task.status, attention: task.attention }),
54    run: async () => ({ text: 'Opened.', attention: null, demo: false }),
55  });
56  const task = service.put({ ...base, at, mode: 'bypass' });
57  assert.equal(task.nextRunAt, `2026-10-16T${at}:00.000Z`);
58  service.tick(); await new Promise(r => setTimeout(r, 20));
59  assert.equal(notified.length, 0, 'not yet');
60  clock = Date.parse(`2026-10-16T${at}:05Z`);
61  service.tick(); await new Promise(r => setTimeout(r, 50));
62  assert.deepEqual(notified, [{ title: 'Open downloads', status: 'done', attention: null }]);
63  assert.equal(service.list()[0].output, 'Opened.');
64  assert.equal(service.list()[0].nextRunAt, nextRun({ ...base, at }, clock), 'tomorrow, not again now');
65  service.close();
66});
67
68async function rig(t, { slots = 2 } = {}) {
69  const worker = await startScriptedWorker({});
70  const dir = mkdtempSync(join(tmpdir(), 'strata-task-'));
71  const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
72  const local = [{ id: 'inst-1', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots }];
73  const agent = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });
74  t.after(async () => { await agent.close(); await worker.close(); cleanup(dir); });
75  const runner = createAgentTaskRunner({ agent, workspace: ws, choice: () => ({ instanceId: 'inst-1' }) });
76  return { worker, agent, ws, runner, dir };
77}
78
79test('a task runs as the agent in each mode: Plan changes nothing, Manual stops at the first change and says so, Bypass does it', { skip }, async (t) => {
80  const r = await rig(t);
81  const file = join(r.ws, 'made-by-task.txt');
82  const prompt = `SCRIPT:call write ${JSON.stringify({ file_path: fwd(file), content: 'task was here' })}`;
83
84  const plan = await r.runner({ id: 'tp', prompt, mode: 'plan' });
85  assert.equal(existsSync(file), false); assert.equal(plan.attention, null, 'Plan refuses without asking anybody');
86
87  const manual = await r.runner({ id: 'tm', prompt, mode: 'manual' });
88  assert.equal(existsSync(file), false, 'nobody was there to say yes');
89  assert.match(manual.attention, /needed a yes/); assert.match(manual.text, /Could not do this by itself: Create or replace the file/);
90  assert.equal(r.agent.status().pendingApprovals, 0, 'nothing is left waiting for an answer');
91
92  const bypass = await r.runner({ id: 'tb', prompt, mode: 'bypass' });
93  assert.equal(existsSync(file), true); assert.equal(bypass.attention, null);
94  assert.match(bypass.text, /What it did/);
95});
96
97test('every run of a task starts a session of its own, and a model that is not ready falls back to the caller', { skip }, async (t) => {
98  const r = await rig(t);
99  await r.runner({ id: 'ts', prompt: 'SCRIPT:echo one', mode: 'plan' });
100  assert.equal(r.agent.sessionOf('task:ts'), null, 'the mapping is dropped after the run');
101  const first = r.worker.requests.length;
102  await r.runner({ id: 'ts', prompt: 'SCRIPT:echo two', mode: 'plan' });
103  assert.ok(r.worker.requests.length > first);
104  const none = createAgentTaskRunner({ agent: r.agent, workspace: r.ws, choice: () => null });
105  assert.equal(await none({ id: 'x', prompt: 'hi' }), null);
106});
107
108test('Stop on the task ends its agent run', { skip }, async (t) => {
109  const r = await rig(t);
110  const controller = new AbortController();
111  const run = r.runner({ id: 'tstop', prompt: 'SCRIPT:slow 300', mode: 'plan' }, controller.signal);
112  await new Promise(res => setTimeout(res, 3500));
113  controller.abort();
114  await assert.rejects(run);
115  assert.equal(r.agent.status().activeTurns, 0);
116});