feat: оформить Harness Lab с изолированным экспериментом Pi Retro
Разделить библиотеку, эксперименты, результаты и принятые инструменты. Сохранить профиль качества TypeScript и практики проверки навыков, убрать обёртки Pi и создавать handoff только по запросу.
This commit is contained in:
@@ -0,0 +1,541 @@
|
||||
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'));
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import test from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { ESLint } from 'eslint';
|
||||
import { loadExtensions } from '../node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/loader.js';
|
||||
|
||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||
|
||||
function fixture(t) {
|
||||
// Keep synthetic sources inside the actual TS project: no substitute parser config.
|
||||
const directory = fs.mkdtempSync(path.join(root, 'src/quality-fixture-'));
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
return (name, code) => {
|
||||
const filename = path.join(directory, name);
|
||||
fs.writeFileSync(filename, code);
|
||||
return filename;
|
||||
};
|
||||
}
|
||||
|
||||
function command(script, args) {
|
||||
return spawnSync(process.execPath, [path.join(root, script), ...args], {
|
||||
cwd: root,
|
||||
encoding: 'utf8',
|
||||
timeout: 120_000,
|
||||
});
|
||||
}
|
||||
|
||||
function successful(result) {
|
||||
assert.equal(result.error, undefined);
|
||||
assert.equal(result.status, 0, result.stdout + result.stderr);
|
||||
}
|
||||
|
||||
function rejected(result) {
|
||||
assert.equal(result.error, undefined);
|
||||
assert.equal(result.status, 1, result.stdout + result.stderr);
|
||||
}
|
||||
|
||||
test('canonical ESLint accepts clean TS and rejects unsafe values, lost promises and inline disabling', async (t) => {
|
||||
const write = fixture(t);
|
||||
const examples = [
|
||||
write('clean.ts', 'export function twice(value: number): number { return value * 2; }\n'),
|
||||
write('unsafe.ts', 'export function twice(value: any): number { return value; }\n'),
|
||||
write('floating.ts', 'Promise.resolve(1);\n'),
|
||||
write('disabled.ts', '/* eslint-disable */\nPromise.resolve(1);\n'),
|
||||
write(
|
||||
'complex.ts',
|
||||
'export function nested(a: boolean, b: boolean, c: boolean, d: boolean, e: boolean): number { if (a) { if (b) { if (c) { if (d) { if (e) { return 1; } } } } } return 0; }\n',
|
||||
),
|
||||
];
|
||||
const makeFunction = (lines) =>
|
||||
[
|
||||
'export function increment(value: number): number {',
|
||||
...Array(lines - 3).fill(' value += 1;'),
|
||||
' return value;',
|
||||
'}',
|
||||
].join('\n');
|
||||
examples.push(write('limit.ts', makeFunction(80)), write('over.ts', makeFunction(81)));
|
||||
const eslint = new ESLint({ cwd: root });
|
||||
const results = await eslint.lintFiles(examples);
|
||||
assert.equal(results.length, examples.length);
|
||||
for (const result of results) {
|
||||
assert.equal(result.fatalErrorCount, 0);
|
||||
assert(
|
||||
!result.messages.some(
|
||||
(message) => message.ruleId === null && message.message.includes('ignored'),
|
||||
),
|
||||
);
|
||||
}
|
||||
assert.deepEqual(results[0].messages, []);
|
||||
const has = (index, rule) => results[index].messages.some((message) => message.ruleId === rule);
|
||||
assert(has(1, '@typescript-eslint/no-explicit-any'));
|
||||
assert(has(1, '@typescript-eslint/no-unsafe-return'));
|
||||
assert(has(2, '@typescript-eslint/no-floating-promises'));
|
||||
assert(has(3, '@typescript-eslint/no-floating-promises'));
|
||||
assert(has(4, 'sonarjs/cognitive-complexity'));
|
||||
assert(!has(5, 'max-lines-per-function'));
|
||||
assert(has(6, 'max-lines-per-function'));
|
||||
// The CLI must propagate the failure, including a directive with no other finding.
|
||||
rejected(command('node_modules/eslint/bin/eslint.js', ['--max-warnings', '0', examples[3]]));
|
||||
const directiveOnly = write('directive.ts', '/* eslint-disable */\nexport const value = 1;\n');
|
||||
rejected(command('node_modules/eslint/bin/eslint.js', ['--max-warnings', '0', directiveOnly]));
|
||||
});
|
||||
|
||||
test('canonical TypeScript and formatter reject violations and accept their clean controls', (t) => {
|
||||
const write = fixture(t);
|
||||
const file = write('types.ts', 'export const count: number = "wrong";\n');
|
||||
const invalidType = command('node_modules/typescript/bin/tsc', ['--project', 'tsconfig.json']);
|
||||
assert.equal(invalidType.error, undefined);
|
||||
assert.equal(invalidType.status, 2, invalidType.stdout + invalidType.stderr);
|
||||
assert.match(invalidType.stdout, /TS2322/);
|
||||
fs.writeFileSync(file, 'export const count: number = 1;\n');
|
||||
successful(command('node_modules/typescript/bin/tsc', ['--project', 'tsconfig.json']));
|
||||
const unformatted = write('format.ts', 'export const count=1;');
|
||||
rejected(command('node_modules/prettier/bin/prettier.cjs', ['--check', unformatted]));
|
||||
fs.writeFileSync(unformatted, 'export const count = 1;\n');
|
||||
successful(command('node_modules/prettier/bin/prettier.cjs', ['--check', unformatted]));
|
||||
});
|
||||
|
||||
test('pinned Pi loader loads the package entry and registers its real command and events', async (t) => {
|
||||
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'pi-retro-loader-'));
|
||||
t.after(() => fs.rmSync(cwd, { recursive: true, force: true }));
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
|
||||
assert.deepEqual(manifest.pi.extensions, ['./src/index.ts']);
|
||||
// An installed extension must load without this repository's devDependencies.
|
||||
fs.cpSync(path.join(root, 'src'), path.join(cwd, 'src'), {
|
||||
recursive: true,
|
||||
});
|
||||
fs.writeFileSync(
|
||||
path.join(cwd, 'package.json'),
|
||||
JSON.stringify({ type: 'module', pi: manifest.pi }),
|
||||
);
|
||||
const result = await loadExtensions(
|
||||
manifest.pi.extensions.map((entry) => path.join(cwd, entry)),
|
||||
cwd,
|
||||
);
|
||||
assert.deepEqual(result.errors, []);
|
||||
assert.equal(result.extensions.length, 1);
|
||||
const extension = result.extensions[0];
|
||||
assert.deepEqual([...extension.commands.keys()], ['retro']);
|
||||
assert.deepEqual([...extension.handlers.keys()].sort(), [
|
||||
'agent_settled',
|
||||
'session_shutdown',
|
||||
'session_start',
|
||||
'session_tree',
|
||||
]);
|
||||
const notices = [];
|
||||
await extension.commands.get('retro').handler('help', {
|
||||
hasUI: true,
|
||||
ui: { notify: (message) => notices.push(message) },
|
||||
});
|
||||
assert.equal(notices.length, 1);
|
||||
assert.match(notices[0], /\/retro start/);
|
||||
});
|
||||
Reference in New Issue
Block a user