Разделить библиотеку, эксперименты, результаты и принятые инструменты. Сохранить профиль качества TypeScript и практики проверки навыков, убрать обёртки Pi и создавать handoff только по запросу.
542 lines
18 KiB
JavaScript
542 lines
18 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { setImmediate as tick } from 'node:timers/promises';
|
|
import retroExtension, { isLocalEndpoint } from '../src/index.ts';
|
|
import { captureSession, parseReport } from '../src/evidence.ts';
|
|
import { RetroObserver } from '../src/observer.ts';
|
|
|
|
const event = (id, text = id) => ({ id, type: 'message', role: 'user', content: text });
|
|
const snapshot = (...events) => ({ sourceId: 'synthetic-session', events });
|
|
const note = (id, summary = 'Проверка результата пропущена') => ({
|
|
summary,
|
|
evidence: [id],
|
|
confidence: 'observed',
|
|
suggestion: 'Добавить проверку результата в точке завершения.',
|
|
check: 'Неверный результат должен быть обнаружен; корректный должен пройти.',
|
|
});
|
|
const reply = (observations = [], changes = {}) => ({
|
|
role: 'assistant',
|
|
content: [{ type: 'text', text: JSON.stringify({ observations }) }],
|
|
api: 'openai-completions',
|
|
provider: 'local',
|
|
model: 'synthetic-model',
|
|
usage: { input: 1000, output: 100, cacheRead: 2000, cacheWrite: 0 },
|
|
stopReason: 'stop',
|
|
timestamp: 1,
|
|
...changes,
|
|
});
|
|
const deferred = () => Promise.withResolvers();
|
|
const createObserver = (options = {}) =>
|
|
new RetroObserver({
|
|
contextWindow: 262144,
|
|
request: async () => reply(),
|
|
...options,
|
|
});
|
|
|
|
test('observer appends only new evidence and preserves the complete cached prefix', async () => {
|
|
const calls = [];
|
|
const responses = [];
|
|
const observer = createObserver({
|
|
request: async (request) => {
|
|
calls.push(structuredClone({ ...request, signal: undefined }));
|
|
const response = reply([note('a')]);
|
|
responses.push(structuredClone(response));
|
|
return response;
|
|
},
|
|
});
|
|
observer.start(snapshot(event('a')));
|
|
await observer.idle();
|
|
observer.offer(snapshot(event('a'), event('b')));
|
|
await observer.idle();
|
|
assert.equal(calls.length, 2);
|
|
assert.equal(calls[0].sessionId, calls[1].sessionId);
|
|
assert.equal(calls[0].systemPrompt, calls[1].systemPrompt);
|
|
assert.deepEqual(calls[1].messages.slice(0, 2), [...calls[0].messages, responses[0]]);
|
|
assert.deepEqual(JSON.parse(calls[1].messages[2].content).entries, [event('b')]);
|
|
assert.equal(observer.status().reviewed, 2);
|
|
assert.equal(observer.status().contextTokens, 3228);
|
|
});
|
|
|
|
test('events arriving during a request are coalesced; requests never overlap', async () => {
|
|
const gate = deferred();
|
|
const calls = [];
|
|
let active = 0;
|
|
let maximum = 0;
|
|
const observer = createObserver({
|
|
request: async (request) => {
|
|
active += 1;
|
|
maximum = Math.max(active, maximum);
|
|
calls.push(request);
|
|
if (calls.length === 1) {
|
|
await gate.promise;
|
|
}
|
|
active -= 1;
|
|
return reply();
|
|
},
|
|
});
|
|
observer.start(snapshot(event('a')));
|
|
await tick();
|
|
observer.offer(snapshot(event('a'), event('b')));
|
|
observer.offer(snapshot(event('a'), event('b'), event('c')));
|
|
observer.offer(snapshot(event('a'), event('b'), event('c')));
|
|
gate.resolve();
|
|
await observer.idle();
|
|
assert.equal(maximum, 1);
|
|
assert.equal(calls.length, 2);
|
|
assert.deepEqual(
|
|
JSON.parse(calls[1].messages.at(-1).content).entries.map((item) => item.id),
|
|
['b', 'c'],
|
|
);
|
|
observer.offer(snapshot(event('a'), event('b'), event('c')));
|
|
await observer.idle();
|
|
assert.equal(calls.length, 2);
|
|
});
|
|
|
|
test('batching retains complete events including a large tool result', async () => {
|
|
const calls = [];
|
|
const observer = createObserver({
|
|
batchBytes: 300,
|
|
request: async ({ messages }) => {
|
|
calls.push(JSON.parse(messages.at(-1).content).entries);
|
|
return reply();
|
|
},
|
|
});
|
|
const events = [event('a', 'a'.repeat(200)), event('b', 'b'.repeat(1200)), event('c')];
|
|
observer.start(snapshot(...events));
|
|
await observer.idle();
|
|
assert.equal(calls.length, 3);
|
|
assert.deepEqual(calls.flat(), events);
|
|
});
|
|
|
|
test('switching a branch cancels old work and rejects a late response', async () => {
|
|
const old = deferred();
|
|
const calls = [];
|
|
const observer = createObserver({
|
|
request: async (request) => {
|
|
calls.push(request);
|
|
return calls.length === 1 ? old.promise : reply([note('b', 'Новая ветка')]);
|
|
},
|
|
});
|
|
observer.start(snapshot(event('a')));
|
|
await tick();
|
|
observer.offer(snapshot(event('b')));
|
|
await observer.idle();
|
|
assert.equal(calls[0].signal.aborted, true);
|
|
assert.notEqual(calls[0].sessionId, calls[1].sessionId);
|
|
assert.equal(calls[1].messages.length, 1);
|
|
old.resolve(reply([note('a', 'Старая ветка')]));
|
|
await tick();
|
|
assert.equal(observer.status().report[0].summary, 'Новая ветка');
|
|
assert.equal(observer.status().reviewed, 1);
|
|
});
|
|
|
|
test('same IDs with changed content or a different session invalidate history', async () => {
|
|
const calls = [];
|
|
const observer = createObserver({
|
|
request: async (request) => {
|
|
calls.push(request);
|
|
return reply();
|
|
},
|
|
});
|
|
observer.start(snapshot(event('a', 'before')));
|
|
await observer.idle();
|
|
observer.offer(snapshot(event('a', 'after')));
|
|
await observer.idle();
|
|
observer.offer({ ...snapshot(event('a', 'after')), sourceId: 'other-session' });
|
|
await observer.idle();
|
|
assert.equal(new Set(calls.map((call) => call.sessionId)).size, 3);
|
|
assert.ok(calls.every((call) => call.messages.length === 1));
|
|
});
|
|
|
|
test('stop cancels immediately even when transport ignores AbortSignal', async () => {
|
|
const gate = deferred();
|
|
let signal;
|
|
const observer = createObserver({
|
|
request: async (request) => {
|
|
signal = request.signal;
|
|
return gate.promise;
|
|
},
|
|
});
|
|
observer.start(snapshot(event('a')));
|
|
await tick();
|
|
observer.stop();
|
|
await observer.idle();
|
|
assert.equal(signal.aborted, true);
|
|
gate.resolve(reply([note('a')]));
|
|
await tick();
|
|
assert.equal(observer.status().active, false);
|
|
assert.deepEqual(observer.status().report, []);
|
|
assert.equal(observer.messages.length, 0);
|
|
});
|
|
|
|
test('errors pause without consuming evidence, leaking errors or retrying automatically', async () => {
|
|
let requests = 0;
|
|
const states = [];
|
|
const observer = createObserver({
|
|
onChange: (state) => states.push(state),
|
|
request: async () => {
|
|
requests += 1;
|
|
if (requests === 1) {
|
|
throw new Error('synthetic-private-request-body');
|
|
}
|
|
return reply();
|
|
},
|
|
});
|
|
observer.start(snapshot(event('a')));
|
|
await observer.idle();
|
|
observer.offer(snapshot(event('a'), event('b')));
|
|
await observer.idle();
|
|
assert.equal(requests, 1);
|
|
assert.equal(observer.status().reviewed, 0);
|
|
assert.equal(observer.status().pending, 2);
|
|
assert.equal(observer.status().paused, 'request-failed');
|
|
assert.ok(!JSON.stringify(states).includes('synthetic-private'));
|
|
observer.retry(snapshot(event('a'), event('b')));
|
|
await observer.idle();
|
|
assert.equal(observer.status().reviewed, 2);
|
|
assert.equal(observer.status().paused, '');
|
|
});
|
|
|
|
test('timeout pauses, aborts transport and ignores late success', async () => {
|
|
const gate = deferred();
|
|
let signal;
|
|
const observer = createObserver({
|
|
timeoutMs: 20,
|
|
request: async (request) => {
|
|
signal = request.signal;
|
|
return gate.promise;
|
|
},
|
|
});
|
|
observer.start(snapshot(event('a')));
|
|
await observer.idle();
|
|
assert.equal(observer.status().paused, 'timeout');
|
|
assert.equal(signal.aborted, true);
|
|
gate.resolve(reply([note('a')]));
|
|
await tick();
|
|
assert.equal(observer.status().reviewed, 0);
|
|
});
|
|
|
|
test('unknown evidence and incomplete replies are rejected, including tool calls', () => {
|
|
const known = new Set(['a']);
|
|
assert.deepEqual(parseReport(reply([note('a')]), known), [note('a')]);
|
|
assert.deepEqual(parseReport(reply(), known), []);
|
|
for (const bad of [
|
|
reply([note('unknown')]),
|
|
reply([note('a')], { stopReason: 'length' }),
|
|
reply([note('a')], { stopReason: 'error' }),
|
|
reply([], { content: [{ type: 'text', text: 'not json' }] }),
|
|
reply([], { content: [...reply().content, { type: 'toolCall', name: 'write' }] }),
|
|
reply([{ ...note('a'), confidence: 'certain' }]),
|
|
reply([{ ...note('a'), evidence: [] }]),
|
|
reply(Array.from({ length: 7 }, () => note('a'))),
|
|
]) {
|
|
assert.throws(() => parseReport(bad, known), /invalid-response/);
|
|
}
|
|
});
|
|
|
|
test('a malformed review preserves the previous valid report and unreviewed evidence', async () => {
|
|
let calls = 0;
|
|
const observer = createObserver({
|
|
request: async () => (++calls === 1 ? reply([note('a')]) : reply([note('missing')])),
|
|
});
|
|
observer.start(snapshot(event('a')));
|
|
await observer.idle();
|
|
observer.offer(snapshot(event('a'), event('b')));
|
|
await observer.idle();
|
|
assert.equal(observer.status().paused, 'invalid-response');
|
|
assert.equal(observer.status().reviewed, 1);
|
|
assert.equal(observer.status().pending, 1);
|
|
assert.deepEqual(observer.status().report, [note('a')]);
|
|
});
|
|
|
|
test('context budget pauses before a request, with no silent truncation', async () => {
|
|
let calls = 0;
|
|
const observer = createObserver({
|
|
contextWindow: 12000,
|
|
request: async () => {
|
|
calls += 1;
|
|
return reply();
|
|
},
|
|
});
|
|
observer.start(snapshot(event('a', 'я'.repeat(15000))));
|
|
await observer.idle();
|
|
assert.equal(calls, 0);
|
|
assert.equal(observer.status().paused, 'context-limit');
|
|
assert.equal(observer.status().pending, 1);
|
|
assert.throws(() => createObserver({ contextWindow: 100 }), /invalid-config/);
|
|
});
|
|
|
|
test('clear begins at a new boundary, reports skipped work honestly and rejects old evidence', async () => {
|
|
const calls = [];
|
|
const observer = createObserver({
|
|
request: async (request) => {
|
|
calls.push(request);
|
|
return reply();
|
|
},
|
|
});
|
|
observer.start(snapshot(event('a')));
|
|
await observer.idle();
|
|
const previousId = calls[0].sessionId;
|
|
observer.clear(snapshot(event('a')));
|
|
assert.equal(observer.status().reviewed, 0);
|
|
assert.equal(observer.status().pending, 0);
|
|
observer.offer(snapshot(event('a'), event('b')));
|
|
await observer.idle();
|
|
assert.notEqual(calls[1].sessionId, previousId);
|
|
assert.equal(JSON.parse(calls[1].messages[0].content).skippedEarlierEvents, 1);
|
|
assert.deepEqual(JSON.parse(calls[1].messages[1].content).entries, [event('b')]);
|
|
assert.equal(observer.knownIds.has('a'), false);
|
|
assert.equal(observer.status().reviewed, 1);
|
|
});
|
|
|
|
function harness(complete = async () => reply()) {
|
|
const handlers = new Map();
|
|
const commands = new Map();
|
|
const notices = [];
|
|
const widgets = new Map();
|
|
const statuses = [];
|
|
const calls = [];
|
|
const model = {
|
|
provider: 'local',
|
|
id: 'worker',
|
|
baseUrl: 'http://localhost:8080/v1',
|
|
contextWindow: 262144,
|
|
maxTokens: 8192,
|
|
};
|
|
const state = {
|
|
entries: [{ id: 'a', type: 'message', message: { role: 'user', content: 'Synthetic task' } }],
|
|
};
|
|
const ctx = {
|
|
hasUI: true,
|
|
model,
|
|
getSystemPrompt: () => 'Synthetic instructions',
|
|
sessionManager: { getSessionId: () => 'synthetic-session', getBranch: () => state.entries },
|
|
modelRegistry: {
|
|
find: (provider, id) => (provider === 'local' ? { ...model, id } : undefined),
|
|
getApiKeyAndHeaders: async () => ({ ok: true }),
|
|
complete: async (...args) => {
|
|
calls.push(args);
|
|
return complete(...args);
|
|
},
|
|
},
|
|
ui: {
|
|
notify: (text) => notices.push(text),
|
|
setWidget: (key, lines) => widgets.set(key, lines),
|
|
setStatus: (_key, text) => statuses.push(text),
|
|
},
|
|
};
|
|
const pi = {
|
|
on: (name, handler) => handlers.set(name, handler),
|
|
registerCommand: (name, command) => commands.set(name, command),
|
|
sendMessage: () => assert.fail('Observer must not add to the main transcript'),
|
|
sendUserMessage: () => assert.fail('Observer must not start a main-agent turn'),
|
|
appendEntry: () => assert.fail('Observer must not persist raw data or reports'),
|
|
};
|
|
retroExtension(pi);
|
|
return {
|
|
handlers,
|
|
notices,
|
|
widgets,
|
|
statuses,
|
|
calls,
|
|
ctx,
|
|
state,
|
|
command: (args) => commands.get('retro').handler(args, ctx),
|
|
};
|
|
}
|
|
|
|
test('capture preserves roles and tool outcomes; omits binary and thinking explicitly', () => {
|
|
const h = harness();
|
|
h.state.entries.push(
|
|
{
|
|
id: 'b',
|
|
type: 'message',
|
|
message: {
|
|
role: 'assistant',
|
|
content: [
|
|
{ type: 'thinking', thinking: 'synthetic-hidden-reasoning' },
|
|
{ type: 'toolCall', id: 'call1', name: 'read', arguments: { path: 'example.txt' } },
|
|
],
|
|
},
|
|
},
|
|
{
|
|
id: 'c',
|
|
type: 'message',
|
|
message: {
|
|
role: 'toolResult',
|
|
toolCallId: 'call1',
|
|
toolName: 'read',
|
|
isError: true,
|
|
content: [
|
|
{ type: 'text', text: 'File missing' },
|
|
{ type: 'image', data: 'synthetic-binary-data' },
|
|
],
|
|
},
|
|
},
|
|
{ id: 'd', type: 'compaction', summary: 'Synthetic summary' },
|
|
);
|
|
const captured = captureSession(h.ctx);
|
|
h.state.entries[0].message.content = 'changed after capture';
|
|
assert.equal(captured.events[1].content[0].text, 'Synthetic task');
|
|
assert.equal(captured.events[3].isError, true);
|
|
assert.equal(captured.events[3].toolCallId, captured.events[2].content[1].id);
|
|
assert.equal(captured.events[4].type, 'compaction');
|
|
assert.ok(!JSON.stringify(captured).includes('synthetic-hidden-reasoning'));
|
|
assert.ok(!JSON.stringify(captured).includes('synthetic-binary-data'));
|
|
assert.equal(captured.events[2].content[0].originalType, 'thinking');
|
|
});
|
|
|
|
test('local endpoint checks reject public addresses and misleading hostnames', () => {
|
|
for (const url of [
|
|
'http://localhost:8080/v1',
|
|
'http://127.0.0.1/v1',
|
|
'http://[::1]/v1',
|
|
'http://192.168.1.2/v1',
|
|
'http://10.0.0.2/v1',
|
|
'http://172.16.0.2/v1',
|
|
'http://[fd00::1]/v1',
|
|
]) {
|
|
assert.equal(isLocalEndpoint(url), true, url);
|
|
}
|
|
for (const url of [
|
|
'https://api.example.com/v1',
|
|
'https://localhost.example.com/v1',
|
|
'http://203.0.113.1/v1',
|
|
'http://172.32.0.1/v1',
|
|
'file:///example',
|
|
'',
|
|
undefined,
|
|
]) {
|
|
assert.equal(isLocalEndpoint(url), false, String(url));
|
|
}
|
|
});
|
|
|
|
test('extension is opt-in, uses a pinned local model and never blocks settled events', async () => {
|
|
const h = harness(async () => reply([note('a')]));
|
|
h.handlers.get('agent_settled')({}, h.ctx);
|
|
await tick();
|
|
assert.equal(h.calls.length, 0);
|
|
await h.command('start local/models/observer');
|
|
await tick();
|
|
assert.equal(h.calls[0][0].id, 'models/observer');
|
|
assert.equal(h.ctx.model.id, 'worker');
|
|
assert.equal(h.calls[0][1].tools, undefined);
|
|
assert.equal(h.calls[0][2].cacheRetention, 'long');
|
|
h.state.entries.push({
|
|
id: 'b',
|
|
type: 'message',
|
|
message: { role: 'user', content: 'Next task' },
|
|
});
|
|
const returned = h.handlers.get('agent_settled')({}, h.ctx);
|
|
assert.equal(returned, undefined);
|
|
await tick();
|
|
assert.equal(h.calls.length, 2);
|
|
await h.command('show');
|
|
assert.ok(h.widgets.get('retro').some((line) => line.includes('Основание')));
|
|
await h.command('hide');
|
|
assert.equal(h.widgets.get('retro'), undefined);
|
|
await h.command('stop');
|
|
});
|
|
|
|
test('a public resolved endpoint never receives a retro request', async () => {
|
|
const h = harness();
|
|
h.ctx.modelRegistry.getApiKeyAndHeaders = async () => ({
|
|
ok: true,
|
|
baseUrl: 'https://api.example.com/v1',
|
|
});
|
|
await h.command('start');
|
|
await tick();
|
|
assert.equal(h.calls.length, 0);
|
|
assert.ok(h.notices.some((text) => text.includes('локальный endpoint')));
|
|
});
|
|
|
|
test('endpoint changes are rechecked before each request', async () => {
|
|
const h = harness();
|
|
await h.command('start');
|
|
await tick();
|
|
h.ctx.modelRegistry.getApiKeyAndHeaders = async () => ({
|
|
ok: true,
|
|
baseUrl: 'https://api.example.com/v1',
|
|
});
|
|
h.state.entries.push({
|
|
id: 'b',
|
|
type: 'message',
|
|
message: { role: 'user', content: 'New evidence' },
|
|
});
|
|
h.handlers.get('agent_settled')({}, h.ctx);
|
|
await tick();
|
|
assert.equal(h.calls.length, 1);
|
|
assert.ok(h.notices.some((text) => text.includes('локальный endpoint')));
|
|
await h.command('stop');
|
|
});
|
|
|
|
test('session teardown aborts work and clears UI; a late response cannot restore it', async () => {
|
|
const gate = deferred();
|
|
const h = harness(() => gate.promise);
|
|
await h.command('start');
|
|
await tick();
|
|
h.handlers.get('session_shutdown')({ reason: 'reload' }, h.ctx);
|
|
assert.equal(h.calls[0][2].signal.aborted, true);
|
|
gate.resolve(reply([note('a')]));
|
|
await tick();
|
|
assert.equal(h.widgets.get('retro'), undefined);
|
|
assert.equal(h.statuses.at(-1), undefined);
|
|
});
|
|
|
|
test('stop cancels a pending start before authentication completes', async () => {
|
|
const gate = deferred();
|
|
const h = harness();
|
|
h.ctx.modelRegistry.getApiKeyAndHeaders = () => gate.promise;
|
|
const starting = h.command('start');
|
|
await h.command('stop');
|
|
gate.resolve({ ok: true });
|
|
await starting;
|
|
await tick();
|
|
assert.equal(h.calls.length, 0);
|
|
});
|
|
|
|
test('observer validates all token and scheduling limits before starting a request', () => {
|
|
for (const field of ['maxOutputTokens', 'contextWindow', 'batchBytes', 'timeoutMs']) {
|
|
for (const invalid of [0, -1, 0.5, NaN, Infinity]) {
|
|
assert.throws(() => createObserver({ [field]: invalid }), /invalid-config/);
|
|
}
|
|
}
|
|
assert.throws(() => createObserver({ contextWindow: 6144 }), /invalid-config/);
|
|
assert.doesNotThrow(() => createObserver({ contextWindow: 6145 }));
|
|
});
|
|
|
|
test('malformed runtime response shapes are rejected and bounded fields accept equality only', () => {
|
|
const known = new Set(['a']);
|
|
for (const invalid of [
|
|
null,
|
|
1,
|
|
{},
|
|
reply([], { content: [null] }),
|
|
reply([], { content: [{ type: 'text', text: 1 }] }),
|
|
]) {
|
|
assert.throws(() => parseReport(invalid, known), /invalid-response/);
|
|
}
|
|
for (const [field, limit] of Object.entries({ summary: 600, suggestion: 1600, check: 1000 })) {
|
|
const valid = { ...note('a'), [field]: 'x'.repeat(limit) };
|
|
assert.deepEqual(parseReport(reply([valid]), known), [valid]);
|
|
assert.throws(
|
|
() => parseReport(reply([{ ...valid, [field]: 'x'.repeat(limit + 1) }]), known),
|
|
/invalid-response/,
|
|
);
|
|
}
|
|
const fenced = reply([note('a')]);
|
|
fenced.content[0].text = '```json\n' + fenced.content[0].text + '\n```';
|
|
assert.deepEqual(parseReport(fenced, known), [note('a')]);
|
|
});
|
|
|
|
test('a non-Error transport failure pauses safely without leaking its payload', async () => {
|
|
const gate = deferred();
|
|
const observer = createObserver({ request: () => gate.promise });
|
|
observer.start(snapshot(event('a')));
|
|
gate.reject({ body: 'synthetic-private-body' });
|
|
await observer.idle();
|
|
assert.equal(observer.status().paused, 'request-failed');
|
|
assert.equal(observer.status().pending, 1);
|
|
assert(!JSON.stringify(observer.status()).includes('synthetic-private-body'));
|
|
});
|