Files
harness-lab/experiments/pi-supervisor/tests/persistence.test.mjs
T

373 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { SessionManager } from '@earendil-works/pi-coding-agent';
import supervisorExtension from '../src/index.ts';
import { SupervisorObserver } from '../src/observer.ts';
import { SupervisorStorage, sessionMetadata } from '../src/storage.ts';
import { configure, readSettings, writeJson } from '../src/settings.ts';
function fixture(t) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'supervisor-persistence-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
return { root, cwd: path.join(root, 'project') };
}
const event = (id) => ({ id, type: 'message', content: `Synthetic ${id}` });
const snapshot = (...ids) => ({ sourceId: 'worker-session', events: ids.map(event) });
const model = {
provider: 'local',
id: 'test',
baseUrl: 'http://localhost:8080/v1',
contextWindow: 262144,
maxTokens: 8192,
};
const answer = () => ({
role: 'assistant',
content: [{ type: 'text', text: '{"observations":[]}' }],
api: 'openai-completions',
provider: 'local',
model: 'test',
stopReason: 'stop',
timestamp: Date.now(),
usage: {
input: 100,
output: 20,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 120,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
},
});
const metadata = {
model: 'local/test',
sourceId: 'worker-session',
sourceFile: '',
sourceTools: ['read', 'bash'],
};
function observer(storage, calls, meta = metadata) {
return new SupervisorObserver({
contextWindow: 262144,
request: async (request) => {
calls.push(request);
return answer();
},
onCommit: (saved) => storage.save(saved, meta),
});
}
test('settings survive reload; cancelled and invalid edits preserve the last valid file', async (t) => {
const { root } = fixture(t);
assert.equal(readSettings(root).timeoutSeconds, 240);
const choices = ['Модель: текущая модель Pi', 'local/test'];
const ctx = {
modelRegistry: { getAvailable: () => [model] },
ui: {
select: async () => choices.shift(),
notify: () => {},
},
};
await configure(root, ctx);
assert.equal(readSettings(root).model, 'local/test');
await configure(root, ctx);
assert.equal(readSettings(root).model, 'local/test');
ctx.ui.select = async () => 'Таймаут: 240 с';
ctx.ui.input = async () => 'NaN';
await assert.rejects(configure(root, ctx), /invalid-settings/);
assert.equal(readSettings(root).timeoutSeconds, 240);
const file = path.join(root, 'supervisor/settings.json');
fs.writeFileSync(file, '{broken');
assert.throws(() => readSettings(root), /storage-failed/);
assert.equal(fs.readFileSync(file, 'utf8'), '{broken');
});
test('native Pi session restores cursor and exact history without repeating completed evidence', async (t) => {
const { root, cwd } = fixture(t);
const store = new SupervisorStorage(root, cwd);
const calls = [];
const first = observer(store, calls);
first.start(snapshot('a'));
await first.idle();
const file = store.latest('worker-session');
const prefix = first.checkpoint().messages;
const discussion = store.discussion('worker-session', path.join(root, 'later-source.jsonl'));
assert.equal(
sessionMetadata(SessionManager.open(discussion)).sourceFile,
path.join(root, 'later-source.jsonl'),
);
const original = fs.readFileSync(file, 'utf8');
const native = SessionManager.open(file);
assert.equal(sessionMetadata(native).model, 'local/test');
assert.equal(
native.buildSessionContext().messages.filter((m) => m.role === 'assistant').length,
1,
);
const nextStore = new SupervisorStorage(root, cwd);
const restored = observer(nextStore, calls);
restored.resume(nextStore.load('worker-session').saved, snapshot('a'));
await restored.idle();
assert.equal(calls.length, 1);
assert.equal(restored.status().reviewed, 1);
restored.offer(snapshot('a', 'b'));
await restored.idle();
assert.equal(calls.length, 2);
assert.deepEqual(calls[1].messages.slice(0, prefix.length), prefix);
assert.deepEqual(JSON.parse(calls[1].messages.at(-1).content).entries, [event('b')]);
assert.notEqual(nextStore.latest('worker-session'), file);
assert.equal(fs.readFileSync(file, 'utf8'), original);
});
test('resume rejects changed branch and clear preserves its explicit boundary across restarts', async (t) => {
const { root, cwd } = fixture(t);
const store = new SupervisorStorage(root, cwd);
const calls = [];
const first = observer(store, calls);
first.start(snapshot('a'));
await first.idle();
const saved = store.load('worker-session').saved;
const second = observer(new SupervisorStorage(root, cwd), calls);
assert.throws(() => second.resume(saved, snapshot('different')), /source-changed/);
assert.equal(calls.length, 1);
first.clear(snapshot('a'));
const thirdStore = new SupervisorStorage(root, cwd);
const third = observer(thirdStore, calls);
third.resume(thirdStore.load('worker-session').saved, snapshot('a', 'b'));
await third.idle();
assert.equal(third.status().reviewed, 1);
assert.equal(calls.length, 2);
assert.deepEqual(JSON.parse(calls[1].messages.at(-1).content).entries, [event('b')]);
});
test('failed persistence pauses observation and keeps the accepted report', async () => {
const instance = new SupervisorObserver({
contextWindow: 262144,
request: async () => answer(),
onCommit: () => {
throw new Error('synthetic secret must not escape');
},
});
instance.start(snapshot('a', 'b'));
await instance.idle();
assert.equal(instance.status().paused, 'storage-failed');
assert.equal(instance.status().reviews, 1);
});
function integration(t) {
const { root, cwd } = fixture(t);
const events = new Map();
const commands = new Map();
const notices = [];
const state = { tools: ['read', 'bash'], calls: 0 };
const worker = SessionManager.create(cwd, path.join(root, 'worker'));
worker.appendMessage({ role: 'user', content: 'Synthetic task', timestamp: Date.now() });
const ctx = {
cwd,
hasUI: true,
model,
sessionManager: worker,
getSystemPrompt: () => 'Synthetic worker',
waitForIdle: async () => {},
modelRegistry: {
find: () => model,
getAvailable: () => [model],
getApiKeyAndHeaders: async () => ({ ok: true }),
complete: async (_model, _context, options) => {
state.options = options;
state.calls++;
return answer();
},
},
ui: { notify: (text) => notices.push(text), setWidget: () => {}, setStatus: () => {} },
};
const pi = {
on: (name, handler) => events.set(name, [...(events.get(name) ?? []), handler]),
registerCommand: (name, command) => commands.set(name, command),
getActiveTools: () => state.tools,
setActiveTools: (tools) => {
state.tools = tools;
},
};
const emit = async (name, event = {}) => {
let result;
for (const handler of events.get(name) ?? []) {
result = await handler(event, ctx);
}
return result;
};
ctx.switchSession = async (file) => {
ctx.sessionManager = SessionManager.open(file);
await emit('session_start');
return { cancelled: false };
};
supervisorExtension(pi, root);
return {
root,
cwd,
ctx,
worker,
state,
notices,
emit,
reload: () => {
events.clear();
commands.clear();
supervisorExtension(pi, root);
},
command: (args) => commands.get('supervisor').handler(args, ctx),
};
}
async function waitSaved(h) {
const store = new SupervisorStorage(h.root, h.cwd);
for (let attempt = 0; attempt < 100; attempt++) {
if (store.latest(h.worker.getSessionId())) {
return;
}
await new Promise((done) => {
setTimeout(done, 10);
});
}
assert.fail('Synthetic response was not saved');
}
test('open creates a normal resumable discussion, blocks tools, and back returns to the worker', async (t) => {
const h = integration(t);
writeJson(path.join(h.root, 'supervisor/settings.json'), {
model: 'local/test',
timeoutSeconds: 15,
maxOutputTokens: 1024,
});
await h.command('start');
await waitSaved(h);
assert.equal(h.state.options.maxTokens, 1024);
await h.command('open');
const discussionFile = h.ctx.sessionManager.getSessionFile();
assert.notEqual(discussionFile, h.worker.getSessionFile());
assert.match(h.ctx.sessionManager.getSessionName(), /обсуждение/);
assert.deepEqual(h.state.tools, []);
assert.match((await h.emit('before_agent_start')).systemPrompt, /обычным текстом/);
assert.equal((await h.emit('tool_call')).block, true);
assert.equal((await h.emit('input')).action, 'continue');
h.ctx.sessionManager.appendMessage({
role: 'user',
content: 'Synthetic follow-up question',
timestamp: Date.now(),
});
assert.match(
JSON.stringify(SessionManager.open(discussionFile).buildSessionContext()),
/Synthetic follow-up/,
);
await h.command('start');
assert.match(h.notices.at(-1), /уже диалог супервизора/);
h.reload();
await h.emit('session_start');
await h.command('back');
assert.equal(h.ctx.sessionManager.getSessionFile(), h.worker.getSessionFile());
assert.deepEqual(h.state.tools, ['read', 'bash']);
await h.command('resume');
assert.equal(h.state.calls, 1);
await h.emit('session_shutdown');
await h.command('resume');
assert.equal(h.state.calls, 1);
});
test('discussion rejects a public model before submitting a user prompt', async (t) => {
const h = integration(t);
await h.command('start');
await waitSaved(h);
await h.command('open');
h.ctx.model = { ...model, baseUrl: 'https://example.com/v1' };
assert.equal((await h.emit('input')).action, 'handled');
assert.match(h.notices.at(-1), /локальную модель/);
});
test('a damaged checkpoint or pointer is rejected without overwriting archived evidence', async (t) => {
const { root, cwd } = fixture(t);
const store = new SupervisorStorage(root, cwd);
const instance = observer(store, []);
instance.start(snapshot('a'));
await instance.idle();
const file = store.latest('worker-session');
const manager = SessionManager.open(file);
manager.appendCustomEntry('harness-supervisor-checkpoint', { version: 1, keys: 42 });
const damaged = fs.readFileSync(file, 'utf8');
assert.throws(() => store.load('worker-session'), /invalid-checkpoint/);
assert.equal(fs.readFileSync(file, 'utf8'), damaged);
const pointer = path.join(
root,
'supervisor/sources',
fs.readdirSync(path.join(root, 'supervisor/sources'))[0],
);
writeJson(pointer, path.join(root, 'outside.jsonl'));
assert.throws(() => store.latest('worker-session'), /invalid-checkpoint/);
});
test('opening discussion cancels an in-flight analysis and discards its late response', async (t) => {
const h = integration(t);
await h.command('start');
await waitSaved(h);
let finish;
h.ctx.modelRegistry.complete = () =>
new Promise((resolve) => {
finish = resolve;
});
h.worker.appendMessage({ role: 'user', content: 'Synthetic next task', timestamp: Date.now() });
await h.emit('agent_settled');
await new Promise((resolve) => {
setImmediate(resolve);
});
assert.equal(typeof finish, 'function');
await h.command('open');
finish(answer());
await new Promise((resolve) => {
setImmediate(resolve);
});
const assistants = h.ctx.sessionManager
.buildSessionContext()
.messages.filter((message) => message.role === 'assistant');
assert.equal(assistants.length, 1);
});
test('retry after a save failure persists accepted history without repeating inference', async () => {
let writes = 0;
let calls = 0;
const instance = new SupervisorObserver({
contextWindow: 262144,
request: async () => {
calls++;
return answer();
},
onCommit: () => {
writes++;
if (writes === 1) {
throw new Error('synthetic failure');
}
},
});
instance.start(snapshot('a'));
await instance.idle();
assert.equal(instance.status().paused, 'storage-failed');
instance.retry(snapshot('a'));
await instance.idle();
assert.equal(instance.status().paused, '');
assert.equal(calls, 1);
assert.equal(writes, 2);
});
test('supervisor identity survives a branch made before the first assistant response', async (t) => {
const { root, cwd } = fixture(t);
const store = new SupervisorStorage(root, cwd);
const instance = observer(store, []);
instance.start(snapshot('a'));
await instance.idle();
const native = SessionManager.open(store.latest('worker-session'));
const firstUser = native
.getBranch()
.find((entry) => entry.type === 'message' && entry.message.role === 'user');
assert.ok(firstUser);
const earlyBranch = { getBranch: () => native.getBranch(firstUser.id) };
assert.equal(sessionMetadata(earlyBranch).sourceId, 'worker-session');
});