Files
Agent-Workbench/tests/code-tools.test.mjs
2026-10-29 17:59:35 +08:00

76 lines
7.3 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fixture, compatibleFixture, completion, call, until, assertToolPairs, launchWorkbench } from './helpers.mjs';
import { Runtime, validateToolArgs } from '../src/server/runtime.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Store } from '../src/server/store.mjs';
import { applyChange, hash } from '../src/server/files.mjs';
test('model code tools keep Task/Run ownership, index evidence and exact proposals across storage recovery', async t => {
const f = fixture(t), target = path.join(f.projectRoot, 'compute.ts'), original = '\uFEFF// protected banner\r\nexport function compute() { return 1; }\r\n';
fs.writeFileSync(target, original); let rounds = 0, fileSha = '';
const model = await compatibleFixture(t, (_url, input) => {
assertToolPairs(input.messages); rounds++;
const output = id => JSON.parse(input.messages.find(value => value.tool_call_id === id).content);
if (rounds === 1) {
for (const name of ['index_project', 'query_code', 'propose_patch']) assert.ok(input.tools.some(value => value.function.name === name));
return completion([call('index', 'index_project', {}), call('query', 'query_code', { query: 'compute', kind: 'symbols', limit: 5 })]);
}
if (rounds === 2) {
assert.equal(output('index').projectId, f.project.id); assert.equal(output('query').results[0].line, 2);
assert.ok(output('index').artifact_id); assert.equal(output('query').results[0].evidenceMethod, 'javascript-typescript-ast');
return completion([call('read', 'read_file', { path: 'compute.ts', start_line: 2, end_line: 2 })]);
}
if (rounds === 3) {
fileSha = output('read').sha256; assert.equal(output('read').bom, true);
return completion([call('patch', 'propose_patch', { path: 'compute.ts', base_sha256: fileSha, reason: 'Repair precise implementation', edits: [{ old_text: 'return 1;', new_text: 'return 2;' }] })]);
}
assert.equal(output('patch').status, 'awaiting_review'); assert.equal(output('patch').patch.lineEnding, 'crlf');
return completion([], '精确补丁已准备,请审核当前项目的差异。');
});
f.store.saveConfig({ ...f.store.config, mode: 'compatible', baseUrl: model.baseUrl, model: 'index-tool-fixture' });
const provider = new Provider(); provider.setKey('synthetic-index-key'); const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, 'Use project index and exact patches'); await until(() => !runtime.isActive(f.session.id), 15000);
assert.equal(rounds, 4); assert.equal(f.session.changes.length, 1); assert.equal(fs.readFileSync(target, 'utf8'), original);
const change = f.session.changes[0], run = f.store.executionSnapshot(f.session).run;
assert.equal(change.editKind, 'exact-patch'); assert.equal(change.runId, run.id); assert.equal(change.taskId, run.taskId); assert.equal(change.baseSha256, fileSha);
const artifact = f.store.executionSnapshot(f.session).artifacts.find(value => value.kind === 'project-index');
const owned = f.store.owned('artifact', artifact.id, f.session.id), content = f.store.artifactStore.read(owned), index = JSON.parse(content);
assert.equal(owned.runId, run.id); assert.equal(owned.taskId, run.taskId); assert.equal(owned.sha256, hash(Buffer.from(content))); assert.equal(index.projectId, f.project.id);
assert.ok(!content.includes('synthetic-index-key')); assert.equal(index.symbols.find(value => value.name === 'compute').sha256, fileSha);
const other = f.store.createSession(f.project.id); assert.throws(() => f.store.owned('artifact', artifact.id, other.id));
applyChange(f.store, f.session, change.id); assert.equal(fs.readFileSync(target, 'utf8'), original.replace('return 1;', 'return 2;'));
f.store.close(); const recovered = new Store(f.data); f.onCleanup(() => recovered.close());
assert.deepEqual(recovered.session(f.session.id).changes[0].patch, change.patch);
assert.equal(recovered.artifactStore.read(recovered.owned('artifact', artifact.id, f.session.id)), content);
});
test('bundled code APIs isolate project results, validate queries and create review-only patches with conflicts', async t => {
const f = fixture(t); fs.writeFileSync(path.join(f.projectRoot, 'code.mjs'), 'export const currentOnly = 1;\n');
const otherRoot = path.join(f.root, 'other'); fs.mkdirSync(otherRoot); fs.writeFileSync(path.join(otherRoot, 'code.mjs'), 'export const otherOnly = 1;\n');
const other = f.store.addProject(otherRoot), server = await launchWorkbench(t, f.data);
assert.equal(server.bootstrap.capabilities.codeIndex, 'bounded-ast-and-candidates'); assert.equal(server.bootstrap.capabilities.exactPatches, 'sha256-unique-anchors');
assert.equal((await fetch(server.url + '/api/projects/' + f.project.id + '/code-index')).status, 403);
const index = await server.api('/projects/' + f.project.id + '/code-index'); assert.equal(index.projectId, f.project.id); assert.equal(index.coverage.astFiles, 1);
const own = await server.api('/projects/' + f.project.id + '/code-query?query=currentOnly&kind=symbols'); assert.equal(own.results[0].path, 'code.mjs'); assert.equal(own.results[0].line, 1);
const separate = await server.api('/projects/' + other.id + '/code-query?query=currentOnly'); assert.equal(separate.results.length, 0); assert.equal(separate.index.projectId, other.id);
for (const query of ['kind=references', 'limit=0', 'limit=61', 'limit=abc', 'query=' + 'a'.repeat(201)]) await assert.rejects(server.api('/projects/' + f.project.id + '/code-query?' + query), { status: 400 });
const args = { path: 'code.mjs', base_sha256: own.results[0].sha256, reason: 'Exact API edit', edits: [{ old_text: 'currentOnly = 1', new_text: 'currentOnly = 2' }] };
const proposed = await server.api('/sessions/' + f.session.id + '/patch-proposals', args); assert.equal(proposed.changes[0].editKind, 'exact-patch');
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'code.mjs'), 'utf8'), 'export const currentOnly = 1;\n');
fs.writeFileSync(path.join(f.projectRoot, 'code.mjs'), 'export const owner = 3;\n');
await assert.rejects(server.api('/sessions/' + f.session.id + '/patch-proposals', args), { status: 409 });
await assert.rejects(server.api('/sessions/' + f.session.id + '/changes/' + proposed.changes[0].id + '/apply', {}), { status: 409 });
const refreshed = await server.api('/projects/' + f.project.id + '/code-query?query=owner'); assert.equal(refreshed.results[0].name, 'owner'); assert.notEqual(refreshed.index.indexFingerprint, own.index.indexFingerprint);
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'code.mjs'), 'utf8'), 'export const owner = 3;\n');
});
test('code tool arguments reject malformed ownership-independent inputs before side effects', () => {
for (const [name, args] of [['query_code', { query: 'q', kind: 'references' }], ['query_code', { query: [] }], ['query_code', { query: 'q', limit: 1.5 }],
['propose_patch', { path: 'a', base_sha256: 'invalid', reason: 'x', edits: [] }], ['propose_patch', { path: 'a', base_sha256: 'a'.repeat(64), reason: 'x', edits: [] }]]) assert.throws(() => validateToolArgs(name, args));
validateToolArgs('query_code', { query: 'compute', kind: 'symbols', limit: 5 });
validateToolArgs('propose_patch', { path: 'a', base_sha256: 'a'.repeat(64), reason: 'x', edits: [{ old_text: 'a', new_text: 'b' }] });
});