"use strict";
const assert = require("node:assert/strict");
const { createHash } = require("node:crypto");
const { AGENT_ACTIONS, AGENT_ACTION_TOOL, AGENT_FILE_TOOLS } = require("../AgentWorker/action-proposal");
const { BOT_OPENAI_TOOL_DEFINITIONS } = require("../utils/bot-ai-tools");
const server = "review-fixture";
const prefix = `/var/lib/node/servers/${server}`;
const paperProperties = "# Minecraft server properties\nonline-mode=true\nserver-ip=\nserver-port=25565\ngamemode=survival\ndifficulty=normal\nmax-players=20\nenable-rcon=false\n";
const examples = {
start: {}, stop: {}, restart: {}, kill: {}, console_command: { command: "list" },
write_file: { path: "settings.yml", oldText: "enabled: false", newText: "enabled: true" },
replace_file: { path: "server.properties", content: paperProperties },
revert_file: { path: "server.properties" },
create_file: { path: "notes.txt", content: "reviewed notes\n" }, create_folder: { path: "configs" },
delete_file: { path: "old.txt" }, create_backup: { name: "Before changes", description: "Fixture" },
restore_backup: { backup: "fixture-backup", deleteOldFiles: true }, delete_backup: { backup: "fixture-backup" },
};
const reviewPrompt = "Review fixture: ";
const rejectedPrompt = "Fixture file request the provider cannot process.";
const followUpPrompt = "Can we continue normally in this chat?";
const followUpReply = "Yes, this chat can continue.";
const diagnosticPrompt = "Check the fixture diagnostics.";
const diagnosticReply = "All fixture diagnostics returned.";
const initialFileText = "# Fixture settings\nenabled: false\nmax-players: 20\n";
const changedFileText = initialFileText.replace("enabled: false", "enabled: true");
const automaticEdits = ["planner_send", "scheduler_planner_next", "scheduler_prompt"].map((source) => ({
source, path: `${source}.ini`, prompt: `Fixture automatic edit: change enabled to true in ${source}.ini.`,
}));
const uncertainEdit = { path: "uncertain.ini", prompt: "Fixture automatic edit: change enabled to true in uncertain.ini." };
const externalFileText = `${initialFileText}# changed externally\n`;
const emptyFileEdit = { path: "empty-notes.txt", oldText: "", newText: "Notes for the next update.\n" };
const originalProperties = "# Generated fixture\r\nonline-mode=true\r\nmax-players=20\r\nmotd=Keep this\r\n";
const changedProperties = originalProperties.replace("online-mode=true", "online-mode=false");
const multiStepPrompt = 'Reverse online-mode in server.properties, check the console and notify players if needed, then make folder "Hey" with hey.py and five more empty files.';
const prematurePrompt = 'go and write a new file named "hes.py" and write random python in there and then create a folder named "ges" and write hey.bb in there with random content';
const prematureActions = [
{ action: "create_file", path: "hes.py", content: 'print("hello from hes")\n' },
{ action: "create_folder", path: "ges" },
{ action: "create_file", path: "ges/hey.bb", content: "Fixture random content\n" },
];
const trackedPrompt = 'Add a small feature of your choice to "hes.py", then create the folder "sample-notes" and write new text in "sample-notes/summary.txt".';
const trackedActions = [
{ action: "create_folder", path: "sample-notes" },
{ action: "create_file", path: "sample-notes/summary.txt", content: "Fixture summary\n" },
{ action: "write_file", path: "hes.py", oldText: prematureActions[0].content.trimEnd(),
newText: `${prematureActions[0].content}\n\ndef triple(value):\n return value * 3` },
];
const trackedTasks = [trackedActions[2], ...trackedActions.slice(0, 2)].map(({ action, path }) => ({ action, path }));
const queuedPrompt = 'Create the "reports" folder, add a default greeting to "welcome.txt", change the title in "banner.txt" and the notice in "notice.txt", and put a note in "reports/summary.txt".';
const queuedActions = [
{ action: "create_folder", path: "reports" },
{ action: "create_file", path: "welcome.txt", content: "Welcome to the server.\n", changeSummary: "Added a default welcome message for players." },
{ action: "write_file", path: "banner.txt", oldText: "title=Old", newText: "title=Updated", changeSummary: "Updated the banner title as requested." },
{ action: "write_file", path: "notice.txt", oldText: "notice=Old", newText: "notice=Updated", changeSummary: "Updated the server notice as requested." },
{ action: "create_file", path: "reports/summary.txt", content: "Reviewed server messages.\n", changeSummary: "Added a short note about the updated messages." },
];
const historyFollowUp = "Keep the changes already made. Read ges/hey.bb and tell me what it says.";
const replacePlanPrompt = 'write a normal minecraft paper server.properties instead of what\'s now in that file and then create a "hey" folder jn the root';
const replacePlanRefusal = "I cannot edit files or create folders as these actions are not available.";
const partialPlanPrompt = "Create a folder, replace server.properties, change a setting, then create another folder.";
const declinedPlanPrompt = 'Review a setting edit and the independent folder "Other".';
const readOnlyPrompt = "Inspect this server in Read only mode.";
const multiStepActions = [
{ action: "write_file", path: "server.properties", oldText: "online-mode=true", newText: "online-mode=false" },
{ action: "console_command", command: "say Configuration updated" },
{ action: "create_folder", path: "Hey" },
...["hey.py", "two.py", "three.py", "four.py", "five.py", "six.py"].map((file) => ({ action: "create_file", path: `Hey/${file}`, content: "" })),
];
const diagnostics = [
{ name: "list_accessible_servers", args: {}, marker: '"servers":[' },
{ name: "inspect_server", args: { server }, marker: '"permissions":{' },
{ name: "get_server_status", args: { server }, marker: '"status":"running","template":"custom"' },
{ name: "query_console", args: { server, limit: 10 }, marker: "Fixture console output" },
{ name: "list_backups", args: { server }, marker: "fixture-backup" },
{ name: "list_server_files", args: { path: "." }, marker: "settings.yml" },
{ name: "read_server_file", args: { path: "settings.yml" }, marker: "# changed externally" },
{ name: "read_server_file", args: { path: "not-found.yml" }, refusal: "not-found.yml" },
{ name: "list_server_files", args: { path: "/invalid" }, refusal: "server-relative path" },
];
const readReasoning = "Fixture reasoning for reading the source text.";
const readReasoningDetails = [{ type: "reasoning.text", text: readReasoning, index: 0 }];
function createActionChecks() {
const mutations = [];
const files = new Map([[`${prefix}/settings.yml`, initialFileText], [`${prefix}/old.txt`, "remove this\n"],
[`${prefix}/server.properties`, originalProperties], [`${prefix}/${emptyFileEdit.path}`, ""]]);
for (const { path } of [...automaticEdits, uncertainEdit]) files.set(`${prefix}/${path}`, initialFileText);
const backups = [{ id: "fixture-backup", name: "Fixture backup" }];
const hash = (content) => createHash("sha256").update(content).digest("hex");
let writeReply = "acknowledge";
let replacementRefusals = 0;
let replacementRetries = 0;
let prematureReplies = 0;
let repeatedCreations = 0;
let queuedProviderRequests = 0;
function provider(request, response) {
const finish = (message) => {
response.end(JSON.stringify({ choices: [{ message: { role: "assistant", ...message }, finish_reason: message.tool_calls ? "tool_calls" : "stop" }] }));
return true;
};
const call = (name, args, id = "fixture-next-action") => finish({ tool_calls: [{ id, type: "function",
function: { name, arguments: JSON.stringify(args) } }] });
const proposeNext = (proposal) => {
if (proposal.action === "write_file") {
const read = request.messages.find(({ tool_call_id }) => tool_call_id === "fixture-read-target");
if (!read) return call("read_server_file", { path: proposal.path }, "fixture-read-target");
assert.match(read.content, /"ok":true/);
}
return call(AGENT_ACTION_TOOL.name, proposal);
};
const prompts = request.messages?.filter((message) => message.role === "user").map((message) => message.content);
const prompt = prompts?.at(-1);
const automatic = [...automaticEdits, uncertainEdit].find((edit) => prompt?.includes(edit.prompt));
if (automatic) {
const tool = request.tools?.find(({ function: entry }) => entry.name === AGENT_ACTION_TOOL.name)?.function;
assert.deepEqual(tool?.parameters.properties.action.enum, ["write_file"]);
const applied = request.messages.find(({ tool_call_id }) => tool_call_id === "fixture-automatic-edit");
if (applied) {
if (automatic === uncertainEdit) {
assert.match(applied.content, /could not confirm/);
return finish({ content: "The fixture edit was not confirmed." });
}
assert.match(applied.content, /"ok":true/);
return finish({ content: "The fixture setting is enabled." });
}
const read = request.messages.find(({ tool_call_id }) => tool_call_id === "fixture-automatic-read");
if (!read) return call("read_server_file", { path: automatic.path }, "fixture-automatic-read");
assert.match(read.content, /enabled: false/);
assert.doesNotMatch(read.content, /editVersion/);
return call(AGENT_ACTION_TOOL.name, { action: "write_file", path: automatic.path,
oldText: "enabled: false", newText: "enabled: true" }, "fixture-automatic-edit");
}
if (prompts?.includes(rejectedPrompt)) {
response.writeHead(400, { "Content-Type": "application/json" });
response.end(JSON.stringify({ error: { message: "The fixture cannot process this message." } }));
return true;
}
if (prompt === followUpPrompt) {
response.end(JSON.stringify({ choices: [{ message: { role: "assistant", content: followUpReply }, finish_reason: "stop" }] }));
return true;
}
const evidenceMessage = request.messages?.find(({ role, content }) => role === "system" && content.startsWith("Continue the latest user request."));
const outcomes = evidenceMessage ? JSON.parse(evidenceMessage.content.split("\n").at(-1)) : [];
if (outcomes.length) {
assert.ok(request.tools.some(({ function: tool }) => tool.name === AGENT_ACTION_TOOL.name));
assert.ok(request.tools.every(({ function: tool }) => tool.name !== "propose_server_plan"));
for (const facts of outcomes) {
assert.equal(facts.server, server);
assert.ok(AGENT_ACTIONS.includes(facts.action));
assert.ok(facts.evidence);
assert.equal(facts.approvedNewLines, undefined);
}
}
if (prompt === prematurePrompt) {
assert.deepEqual(outcomes.map(({ path }) => path), prematureActions.slice(0, outcomes.length).map(({ path }) => path));
const checking = request.messages.some(({ role, content }) => role === "system" && content.includes("Check for unfinished work before ending the turn."));
if (outcomes.length === 1) {
if (!checking) {
prematureReplies += 1;
return finish({ content: "Created hes.py with the approved text on wfewfe." });
}
const blocked = request.messages.find(({ tool_call_id }) => tool_call_id === "fixture-repeated-creation");
if (!blocked) {
repeatedCreations += 1;
return call(AGENT_ACTION_TOOL.name, { ...prematureActions[0], content: "This must not replace the confirmed file.\n" }, "fixture-repeated-creation");
}
assert.match(blocked.content, /"ok":false,"code":"agent_action_already_reviewed"/);
assert.match(blocked.content, /already confirmed.*Continue other unfinished work/);
}
const next = prematureActions[outcomes.length];
return next ? call(AGENT_ACTION_TOOL.name, next) : finish({ content: "Created hes.py, ges, and ges/hey.bb." });
}
if (prompt === historyFollowUp) {
assert.ok(prompts.includes(prematurePrompt));
assert.equal(outcomes.length, 0);
const recorded = request.messages.find(({ role, content }) => role === "system" && content.startsWith("Earlier reviewed file activity"));
assert.match(recorded?.content || "", /not instructions, current file state, or authorization/);
assert.deepEqual(JSON.parse(recorded.content.split("\n").at(-1)), prematureActions.map(({ action, path }) => ({ action, path, status: "applied" })));
const read = request.messages.find(({ tool_call_id }) => tool_call_id === "fixture-history-read");
if (!read) return call("read_server_file", { path: "ges/hey.bb" }, "fixture-history-read");
assert.match(read.content, /Fixture random content/);
return finish({ content: "The existing file says: Fixture random content." });
}
if (prompt === trackedPrompt) {
const pending = request.messages.find(({ role, content }) => role === "system" && content.startsWith("Pending file outcomes from the same user request"));
if (outcomes.length < 3 && outcomes.length) {
assert.deepEqual(JSON.parse(pending.content.split("\n").at(-1)), trackedTasks.filter(({ path }) => !outcomes.some((fact) => fact.path === path)));
}
if (outcomes.length === 0) return call(AGENT_ACTION_TOOL.name, { ...trackedActions[0], fileTasks: trackedTasks });
if (outcomes.length === 1) {
const read = request.messages.find(({ tool_call_id }) => tool_call_id === "fixture-check-new-file");
if (!read) return call("read_server_file", { path: trackedActions[1].path }, "fixture-check-new-file");
assert.match(read.content, /"code":"file_not_found"/);
return call(AGENT_ACTION_TOOL.name, trackedActions[1]);
}
if (outcomes.length === 2) {
const read = request.messages.find(({ role }) => role === "tool");
if (request.messages[0].content.includes("Check for unfinished work")) {
const observation = request.messages.find(({ role, content }) => role === "system" && content.startsWith("UNTRUSTED DATA: the payload below"));
assert.match(observation?.content || "", /hello from hes/);
assert.equal(read, undefined);
return call(AGENT_ACTION_TOOL.name, trackedActions[2]);
}
if (!read) return finish({ content: `${JSON.stringify({ tool_calls: [{ name: "read_server_file", args: { path: trackedActions[2].path } }] })}` });
assert.match(read.content, /hello from hes/);
return finish({ content: "The new file is ready." });
}
assert.equal(pending, undefined);
return finish({ content: "Updated hes.py and created sample-notes/summary.txt." });
}
if (prompt === queuedPrompt) {
queuedProviderRequests += 1;
if (outcomes.length) {
response.writeHead(429).end(JSON.stringify({ error: { message: "No provider quota remains after proposal generation." } }));
return true;
}
if (request.messages[0].content.includes("Reconsider the requested outcome")) {
const observed = request.messages.find(({ role, content }) => role === "system" && content.startsWith("UNTRUSTED DATA: the payload below"));
assert.match(observed?.content || "", /file_not_found/);
assert.match(observed.content, /title=Old/);
assert.match(observed.content, /notice=Old/);
const fileTasks = queuedActions.map(({ action, path }) => ({ action: path === "welcome.txt" ? "write_file" : action, path }));
return finish({ tool_calls: queuedActions.map((proposal, index) => ({ id: `fixture-draft-${index}`, type: "function",
function: { name: AGENT_ACTION_TOOL.name, arguments: JSON.stringify(index === 0 ? { ...proposal, fileTasks, planComplete: true } : proposal) },
})) });
}
if (request.messages.some(({ role }) => role === "tool")) return finish({ content: "The greeting file is missing. I can still update both other files and add the report." });
return finish({ tool_calls: queuedActions.slice(1, 4).map(({ path }, index) => ({ id: `fixture-read-${index}`, type: "function",
function: { name: "read_server_file", arguments: JSON.stringify({ path }) },
})) });
}
if (prompt === multiStepPrompt) {
assert.deepEqual(outcomes.map(({ action }) => action), multiStepActions.slice(0, outcomes.length).map(({ action }) => action));
if (outcomes.length === 1) {
const consoleResult = request.messages.find(({ tool_call_id }) => tool_call_id === "fixture-after-edit");
if (!consoleResult) return call("query_console", { server, limit: 10 }, "fixture-after-edit");
assert.match(consoleResult.content, /Configuration notification pending/);
}
const next = multiStepActions[outcomes.length];
return next ? proposeNext(next) : finish({
content: "Fixture finished: updated one setting, sent the console notification, and created Hey with six files including Hey/hey.py.",
});
}
if (prompt === replacePlanPrompt) {
if (outcomes.at(-1)?.decision === "refused") return finish({ content: "The replacement was refused because the file changed. The folder was not requested." });
if (outcomes.length === 2) return finish({ content: "Fixture finished: replaced server.properties and created the root hey folder." });
if (outcomes.length === 1) return call(AGENT_ACTION_TOOL.name, { action: "create_folder", path: "hey" });
const retry = request.messages.some(({ role, content }) => role === "system" && content.includes("The previous answer missed the available file tools."));
if (!retry) {
replacementRefusals += 1;
return finish({ content: replacePlanRefusal });
}
replacementRetries += 1;
return call(AGENT_ACTION_TOOL.name, { action: "replace_file", ...examples.replace_file });
}
if (prompt === partialPlanPrompt) {
const actions = [{ action: "create_folder", path: "completed" }, { action: "replace_file", ...examples.replace_file },
{ action: "write_file", ...examples.write_file }];
const next = actions[outcomes.length];
if (next) return proposeNext(next);
assert.deepEqual(outcomes.map(({ decision }) => decision), ["accepted", "accepted", "refused"]);
return finish({ content: "The first two changes completed, but the setting changed on disk. The last folder was not created." });
}
if (prompt === declinedPlanPrompt) {
if (!outcomes.length) return proposeNext(multiStepActions[0]);
assert.equal(outcomes[0].decision, "declined");
return outcomes.length === 1 ? call(AGENT_ACTION_TOOL.name, { action: "create_folder", path: "Other" })
: finish({ content: "Fixture finished: the edit was declined and Other was created." });
}
if (prompt === readOnlyPrompt) {
const tools = request.tools.map(({ function: tool }) => tool.name);
assert.ok(tools.includes("read_server_file"));
assert.ok(!tools.includes(AGENT_ACTION_TOOL.name) && !tools.includes("propose_server_plan"));
const refusal = request.messages.find(({ role }) => role === "tool");
const message = refusal ? { content: "The Agent stayed in Read only mode." } : { tool_calls: [{ id: "fixture-denied", type: "function",
function: { name: AGENT_ACTION_TOOL.name, arguments: JSON.stringify({ action: "create_folder", path: "NotAllowed" }) } }] };
if (refusal) assert.match(refusal.content, /Read only mode does not allow change proposals/);
response.end(JSON.stringify({ choices: [{ message: { role: "assistant", ...message } }] }));
return true;
}
if (prompt === diagnosticPrompt) {
const toolResults = request.messages.filter(({ role }) => role === "tool");
let message;
if (toolResults.length) {
assert.equal(toolResults.length, diagnostics.length);
diagnostics.forEach(({ name, marker, refusal }, index) => {
const result = toolResults.find(({ tool_call_id }) => tool_call_id === `diagnostic-${index}`);
assert.ok(result, name);
assert.ok(result.content.includes(refusal || marker), name);
assert.ok(result.content.includes(refusal ? '"ok":false' : '"ok":true'), `${name}: ${result.content}`);
});
message = { content: diagnosticReply };
} else {
message = { tool_calls: diagnostics.map(({ name, args }, index) => ({
id: `diagnostic-${index}`, type: "function", function: { name, arguments: JSON.stringify(args) },
})) };
}
response.end(JSON.stringify({ choices: [{ message: { role: "assistant", ...message }, finish_reason: message.tool_calls ? "tool_calls" : "stop" }] }));
return true;
}
if (typeof prompt !== "string" || !prompt.startsWith(reviewPrompt)) return false;
const [action, output = "native"] = prompt.slice(reviewPrompt.length).split(" ");
assert.ok(Object.hasOwn(examples, action));
if (outcomes.length) {
response.writeHead(401).end(JSON.stringify({ error: { message: "No provider call should follow this review." } }));
return true;
}
assert.ok(request.messages.some((message) => message.role === "system" && message.content.includes("Do not switch to normal chat, monitor mode")));
if (request.tools) assert.ok(request.tools.some((tool) => tool.function.name === AGENT_ACTION_TOOL.name));
if (output !== "tagged" && output !== "quoted") assert.ok(request.tools, "native fixture must receive tool definitions");
const fields = action === "write_file" && output === "empty" ? emptyFileEdit : examples[action];
if (action === "write_file" && output !== "tagged" && output !== "quoted") {
const toolResult = request.messages.find(({ role, tool_call_id }) => role === "tool" && tool_call_id === "fixture-read");
if (!toolResult) {
const read = { id: "fixture-read", type: "function", function: {
name: "read_server_file", arguments: JSON.stringify({ path: fields.path }),
} };
response.end(JSON.stringify({ choices: [{ message: { role: "assistant", tool_calls: [read],
reasoning_content: readReasoning, reasoning_details: readReasoningDetails }, finish_reason: "tool_calls" }] }));
return true;
}
const assistant = request.messages.find(({ tool_calls }) => tool_calls?.some(({ id }) => id === "fixture-read"));
if (assistant?.reasoning_content !== readReasoning || JSON.stringify(assistant.reasoning_details) !== JSON.stringify(readReasoningDetails)) {
response.writeHead(400, { "Content-Type": "application/json" });
response.end(JSON.stringify({ error: { message: "The file tool continuation is missing reasoning metadata." } }));
return true;
}
assert.ok(toolResult.content.includes('"ok":true'), "edit must receive the current file before proposing new content");
if (output === "empty") assert.match(toolResult.content, /the file exists and is empty/);
}
const tool = { id: "review-fixture-call", type: "function", function: {
name: AGENT_ACTION_TOOL.name, arguments: JSON.stringify({ action, ...fields,
planComplete: true, ...(fields.path && { fileTasks: [{ action, path: fields.path }] }),
...(action === "write_file" && output === "matching" ? { oldText: "enabled: true" } : {}) }),
} };
const plan = `${JSON.stringify({ tool_calls: [{ name: tool.function.name, args: JSON.parse(tool.function.arguments) }] })}`;
const result = output === "tagged" || output === "quoted" ? { content: output === "quoted" ? `Example: \n\`\`\`\n${plan}\n\`\`\`` : plan } : { tool_calls: [tool] };
response.end(JSON.stringify({ choices: [{ message: { role: "assistant", ...result }, finish_reason: result.tool_calls ? "tool_calls" : "stop" }] }));
return true;
}
function node(request, response) {
request.on("error", () => {});
response.on("error", () => {});
const route = new URL(request.url, "http://127.0.0.1").pathname;
const serverRoute = `/v1/servers/${server}`;
const isMutation = request.method === "POST" && ["start", "stop", "restart", "kill", "command", "backups", "backups/fixture-backup/restore"]
.some((operation) => route === `${serverRoute}/${operation}`) || request.method === "DELETE" && route === `${serverRoute}/backups/fixture-backup`;
const send = (status, value) => response.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(value));
let raw = "";
request.on("data", (chunk) => { raw += chunk; });
request.on("end", () => {
const data = raw ? JSON.parse(raw) : {};
if (route === serverRoute && request.method === "GET") return send(200, { ok: true, baseDir: prefix, status: "running" });
if (route === `${serverRoute}/runtime`) return send(200, { ok: true });
if (route === `${serverRoute}/backups` && request.method === "GET") return send(200, { ok: true, backups });
if (route === `${serverRoute}/logs/snapshot`) return send(200, { lines: [{ line: "Fixture console output" },
...(files.get(`${prefix}/server.properties`) === changedProperties ? [{ line: "Configuration notification pending" }] : [])] });
if (route === "/v1/fs/list") {
assert.equal(data.server, server);
assert.equal(data.path, prefix);
return send(200, { ok: true, entries: [{ name: "settings.yml", size: 16 }] });
}
if (route === "/v1/fs/read") {
if (data.path === `${prefix}/${uncertainEdit.path}` && files.get(data.path) === changedFileText) return response.destroy();
return files.has(data.path) ? send(200, { ok: true, content: Buffer.from(files.get(data.path)).toString("base64") })
: send(404, { ok: false, error: "file not found" });
}
if (route === "/v1/fs/write" || route === "/v1/fs/delete") {
assert.equal(data.server, server);
assert.ok(data.path.startsWith(`${prefix}/`));
mutations.push({ route, data });
if (route === "/v1/fs/write" && data.expectedSha256 && writeReply === "legacy") {
return send(400, { ok: false, error: "bad json or content too large (max 10MB)" });
}
if (data.expectedSha256 && (!files.has(data.path) || hash(files.get(data.path)) !== data.expectedSha256)) {
return send(409, { ok: false, code: "file_changed_on_disk" });
}
if (data.mode === "create" && files.has(data.path)) return send(409, { ok: false, existed: true });
if (route === "/v1/fs/write" && data.expectedSha256 && writeReply === "no-write-ack") return response.destroy();
if (route === "/v1/fs/delete") files.delete(data.path);
else files.set(data.path, data.content);
if (route === "/v1/fs/write" && data.path === `${prefix}/${uncertainEdit.path}`) return response.destroy();
if (route === "/v1/fs/write" && data.expectedSha256 && writeReply === "lost") return response.destroy();
return send(200, { ok: true });
}
if (isMutation) {
mutations.push({ route, data, method: request.method });
return send(200, { ok: true, backup: { id: "fixture-created", name: data.name } });
}
return send(404, { ok: false });
});
}
async function seedServer(query) {
await query(`INSERT INTO nodes (id, name, address, api_port, ports, token) VALUES
('review-node', 'review-node', '127.0.0.1', 3101, '{}', 'synthetic-review-node-token')`);
await query("INSERT INTO servers (name, bot, status, node_id) VALUES (?, ?, 'offline', 'review-node')", [server, server]);
}
async function exercise({ query, browsers, nonOwner, createRun, resumeRun }) {
await seedServer(query);
let browser;
let runs = 0;
const sendPrompt = async (prompt, chatId = null, accessMode = "general") => {
browser = browsers[Math.floor(runs / 4)];
runs += 1;
assert.ok(browser, "fixture account budget");
const run = createRun({ server, chatId, prompt, accessMode, provider: "openai-compatible", model: "synthetic" }, { fetcher: browser });
const { jobId, chatId: acceptedChatId } = await run.accepted;
const job = await run.result();
const history = await browser(`/api/ai/chats/${acceptedChatId}`);
assert.equal(history.status, 200);
const { chat } = await history.json();
return { job, chat, jobId, chatId: acceptedChatId };
};
const runPrompt = (action, output = "native") => sendPrompt(`${reviewPrompt}${action} ${output}`);
const propose = async (action, output) => {
const { job, chat, jobId, chatId } = await runPrompt(action, output);
assert.equal(job.review_job_id, String(jobId));
assert.equal(chat.review_job_id, String(jobId));
assert.match(job.content, /Action prepared/);
return { route: `/api/ai/jobs/${jobId}/review`, chatId };
};
const preview = async (route, request = browser) => request(`${route}?server=${server}`);
const apply = (route, details, decision = "apply") => browser(route, {
method: "POST", headers: { "content-type": "application/json", "x-action-token": details.token },
body: JSON.stringify({ server, decision, expectedSha256: details.expectedSha256 }),
});
const conclude = async (result, action, state = "applied") => {
assert.equal(result.state, state, action);
assert.match(result.conclusionJobId, /^\d+$/, action);
const conclusion = await resumeRun(result.conclusionJobId, result.chatId, { fetcher: browser }).result();
assert.match(conclusion.content, /^\*\*Status:\*\*[^\n]+\n\*\*(?:Changed|Unchanged|Acknowledged|Not completed):\*\*/);
assert.doesNotMatch(conclusion.content, /\n\n|Git \/ Repository State|Verification & Testing|Next Steps/);
assert.equal(conclusion.review_job_id, null);
const { messages } = await (await browser(`/api/ai/chats/${result.chatId}`)).json();
assert.deepEqual(messages.map(({ role }) => role), ["user", "assistant"]);
assert.equal(messages.at(-1).content, conclusion.content);
return conclusion;
};
assert.deepEqual(Object.keys(examples).sort(), [...AGENT_ACTIONS].sort());
for (const [action, args] of Object.entries(examples)) {
if (action === "revert_file" || action === "replace_file") continue;
const before = mutations.length;
const { route, chatId } = await propose(action, action === "stop" ? "tagged" : "native");
assert.equal(mutations.length, before);
assert.equal((await preview(route, nonOwner)).status, 404);
const response = await preview(route);
assert.equal(response.status, 200);
const details = await response.json();
assert.deepEqual(details.proposal, { action, ...args });
if (action === "create_file") assert.match(details.diff, /\+reviewed notes/);
if (action === "delete_file") assert.match(details.diff, /-remove this/);
if (action === "write_file") {
assert.equal(details.before, initialFileText);
assert.equal(details.proposedText, changedFileText);
assert.match(details.diff, /-enabled: false\n\+enabled: true/);
}
assert.equal((await apply(route, { ...details, token: "" })).status, 403);
assert.equal(mutations.length, before);
const result = await apply(route, details);
assert.equal(result.status, 200, `apply ${action}`);
await conclude(await result.json(), action);
assert.equal((await apply(route, details)).status, 409);
assert.equal(mutations.length, before + 1, `${action}: ${mutations.slice(before).map(({ route }) => route).join(", ")}`);
const { chat } = await (await browser(`/api/ai/chats/${chatId}`)).json();
assert.equal(chat.review_job_id, null);
}
assert.equal(files.get(`${prefix}/settings.yml`), changedFileText);
assert.equal(files.get(`${prefix}/notes.txt`), "reviewed notes\n");
assert.equal(files.get(`${prefix}/configs/.keep`), "");
assert.equal(files.has(`${prefix}/old.txt`), false);
assert.equal(mutations.find(({ route }) => route.endsWith("/restore")).data.deleteOldFiles, true);
files.set(`${prefix}/settings.yml`, initialFileText);
const { route: stale, chatId: staleChat } = await propose("write_file");
const details = await (await preview(stale)).json();
files.set(`${prefix}/settings.yml`, externalFileText);
const result = await (await apply(stale, details)).json();
assert.equal(result.state, "refused");
assert.equal(result.code, "file_changed_on_disk");
assert.equal(result.chatId, String(staleChat));
assert.match(result.receipt, /file changed after review/);
assert.equal(files.get(`${prefix}/settings.yml`), externalFileText);
await conclude(result, "write_file", "refused");
const command = await propose("console_command", "declined");
const count = mutations.length;
const commandPreview = await (await preview(command.route)).json();
assert.equal(commandPreview.proposal.command, examples.console_command.command);
const declined = await (await apply(command.route, commandPreview, "dismiss")).json();
assert.equal(declined.chatId, String(command.chatId));
assert.match((await conclude(declined, "console_command", "dismissed")).content, /Declined console command; no change sent/);
assert.equal((await apply(command.route, commandPreview)).status, 409);
const missing = await propose("write_file", "declined");
files.delete(`${prefix}/settings.yml`);
const unavailable = await (await preview(missing.route)).json();
assert.equal(unavailable.expectedSha256, null);
assert.match(unavailable.previewError, /file was not found/);
assert.equal((await apply(missing.route, unavailable)).status, 400);
assert.equal((await apply(missing.route, { ...unavailable, expectedSha256: hash(externalFileText) })).status, 403);
const declinedEdit = await (await apply(missing.route, unavailable, "dismiss")).json();
assert.match((await conclude(declinedEdit, "write_file", "dismissed")).content, /Declined file edit; no change sent/);
assert.equal(files.has(`${prefix}/settings.yml`), false);
files.set(`${prefix}/settings.yml`, externalFileText);
assert.equal(mutations.length, count);
console.log("PASS: declining a console command or an unverifiable file edit continued the chat without any server mutation.");
const quoted = await runPrompt("start", "quoted");
assert.equal(quoted.job.review_job_id, null);
assert.equal(quoted.chat.review_job_id, null);
const { route: concurrent } = await propose("restart");
const previews = await Promise.all([preview(concurrent), preview(concurrent)]);
const tokens = await Promise.all(previews.map((item) => item.json()));
const decisions = await Promise.all(tokens.map((item) => apply(concurrent, item)));
assert.deepEqual(decisions.map(({ status }) => status).sort(), [200, 409]);
await conclude(await decisions.find(({ status }) => status === 200).json(), "restart");
assert.equal(mutations.length, count + 1);
const { route: replaced } = await propose("kill");
const displaced = await (await preview(replaced)).json();
await query("DELETE FROM servers WHERE name = ?", [server]);
await query("INSERT INTO servers (name, bot, status, node_id) VALUES (?, ?, 'offline', 'review-node')", [server, server]);
assert.equal((await apply(replaced, displaced)).status, 409);
assert.equal(mutations.length, count + 1);
console.log(`PASS: ${AGENT_ACTIONS.length - 2} reviewed actions each reached a stored conclusion; stale, quoted and concurrent reviews did not replay mutations.`);
const chatClient = browsers.at(-1);
const submit = (prompt, chatId = null) => createRun({ server, chatId, prompt, provider: "openai-compatible", model: "synthetic" }, { fetcher: chatClient });
assert.deepEqual(new Set(diagnostics.filter(({ marker }) => marker).map(({ name }) => name)),
new Set([...BOT_OPENAI_TOOL_DEFINITIONS.map(({ function: tool }) => tool.name), ...AGENT_FILE_TOOLS.map(({ name }) => name)]));
const diagnosed = await submit(diagnosticPrompt).result();
assert.equal(diagnosed.content, diagnosticReply);
assert.equal(diagnosed.review_job_id, null);
assert.equal(mutations.length, count + 1);
console.log("PASS: all seven read-only tools returned fixture data; live status reported running despite the offline inventory label.");
const rejected = submit(rejectedPrompt);
const rejectedJob = await rejected.accepted;
await assert.rejects(rejected.result(), { code: "agent_provider_rejected", message: /AI provider rejected this request/ });
const [failed] = await query("SELECT status, error, result_message_id FROM ai_agent_jobs WHERE id = ?", [rejectedJob.jobId]);
assert.deepEqual(failed, { status: "failed", error: "agent_provider_rejected", result_message_id: null });
const followUp = submit(followUpPrompt, rejectedJob.chatId);
assert.equal(String((await followUp.accepted).chatId), String(rejectedJob.chatId));
assert.equal((await followUp.result()).content, followUpReply);
const history = await chatClient(`/api/ai/chats/${rejectedJob.chatId}`);
assert.deepEqual((await history.json()).messages.map(({ role, content }) => [role, content]), [
["user", rejectedPrompt], ["user", followUpPrompt], ["assistant", followUpReply],
]);
assert.equal(mutations.length, count + 1);
console.log("PASS: the chat kept its failed prompt in history and answered the next ordinary message without a node mutation.");
const legacy = await propose("write_file");
writeReply = "legacy";
const legacyResult = await (await apply(legacy.route, await (await preview(legacy.route)).json())).json();
assert.equal(legacyResult.state, "refused");
assert.equal(legacyResult.code, "node_review_update_required");
assert.equal(legacyResult.chatId, String(legacy.chatId));
assert.match(legacyResult.receipt, /Update the node daemon/);
assert.equal(files.get(`${prefix}/settings.yml`), externalFileText);
const legacyChat = await (await browser(`/api/ai/chats/${legacy.chatId}`)).json();
assert.match(legacyChat.messages.at(-1).content, /Update the node daemon/);
await conclude(legacyResult, "write_file", "refused");
const lost = await propose("write_file");
writeReply = "lost";
const beforeLost = mutations.length;
const lostResult = await (await apply(lost.route, await (await preview(lost.route)).json())).json();
assert.match((await conclude(lostResult, "write_file")).content, /readback verified the exact approved bytes/);
assert.equal(mutations.length, beforeLost + 1);
const alreadyMatching = await propose("write_file", "matching");
const beforeNoop = mutations.length;
const matchingResult = await (await apply(alreadyMatching.route, await (await preview(alreadyMatching.route)).json())).json();
assert.match((await conclude(matchingResult, "write_file")).content, /No write was sent/);
assert.equal(mutations.length, beforeNoop);
files.set(`${prefix}/settings.yml`, externalFileText);
const unconfirmed = await propose("write_file");
writeReply = "no-write-ack";
const unconfirmedResult = await (await apply(unconfirmed.route, await (await preview(unconfirmed.route)).json())).json();
assert.equal(unconfirmedResult.state, "unknown");
assert.equal(unconfirmedResult.conclusionJobId, undefined);
assert.match(unconfirmedResult.receipt, /did not confirm.*not retried/);
assert.equal(files.get(`${prefix}/settings.yml`), externalFileText);
assert.equal(mutations.length, beforeNoop + 1);
const localConclusion = await propose("start", "no-conclusion");
const beforeFailure = mutations.length;
const confirmed = await (await apply(localConclusion.route, await (await preview(localConclusion.route)).json())).json();
assert.equal(confirmed.state, "applied");
assert.match((await conclude(confirmed, "start")).content, /start sent and acknowledged\. Final running state not verified/);
assert.equal(mutations.length, beforeFailure + 1);
console.log("PASS: old node refusal, verified readback, unchanged and unconfirmed writes, and acknowledged power requests remained distinct without billable summaries.");
runs = Math.ceil(runs / 4) * 4;
writeReply = "acknowledge";
const turn = await sendPrompt(multiStepPrompt);
const turnClient = browser;
const base = mutations.length;
let reviewId = turn.job.review_job_id;
for (const [index, step] of multiStepActions.entries()) {
const route = `/api/ai/jobs/${reviewId}/review`;
const details = await (await preview(route)).json();
assert.deepEqual(details.proposal, step);
assert.equal(details.plan, undefined);
assert.equal(details.remaining, 0);
assert.equal(mutations.length, base + index);
if (index === 0) assert.equal(details.proposedText, changedProperties);
const decision = await (await apply(route, details)).json();
assert.equal(decision.state, "applied");
assert.equal(decision.chatId, String(turn.chatId));
const next = await resumeRun(decision.conclusionJobId, decision.chatId, { fetcher: browser }).result();
({ review_job_id: reviewId } = next);
assert.equal(await (await apply(route, details)).status, 409);
if (index + 1 < multiStepActions.length) assert.equal(reviewId, String(decision.conclusionJobId));
else assert.match(next.content, /updated one setting.*console notification.*created Hey with six files/);
}
assert.equal(reviewId, null);
assert.equal(files.get(`${prefix}/server.properties`), changedProperties);
assert.equal(files.get(`${prefix}/Hey/.keep`), "");
for (const action of multiStepActions.filter(({ action }) => action === "create_file")) assert.equal(files.get(`${prefix}/${action.path}`), "");
const turnHistory = await (await browser(`/api/ai/chats/${turn.chatId}`)).json();
assert.deepEqual(turnHistory.messages.map(({ role }) => role), ["user", "assistant"]);
const logged = JSON.parse(turnHistory.messages.at(-1).agent_actions);
assert.deepEqual(logged.map(({ action, status }) => [action, status]), multiStepActions.map(({ action }) => [action, "applied"]));
assert.deepEqual(logged.filter(({ action }) => action === "create_file").map(({ target }) => target),
multiStepActions.filter(({ action }) => action === "create_file").map(({ path }) => path));
assert.equal(logged[0].target, "server.properties");
assert.equal(logged[0].addedLines, 1);
assert.equal(logged[0].removedLines, 1);
assert.equal(logged[1].command, multiStepActions[1].command);
assert.match(logged[1].detail, /output was not verified/);
assert.doesNotMatch(JSON.stringify(logged), /online-mode|Fixture console output/);
console.log("PASS: a confirmed edit led to a console read, a newly discovered reviewed command, and six file creations in one chat turn without a stored plan.");
const reverted = await sendPrompt(`${reviewPrompt}revert_file native`, turn.chatId);
assert.equal(browser, turnClient);
const undoRoute = `/api/ai/jobs/${reverted.jobId}/review`;
const undoPreview = await (await preview(undoRoute)).json();
assert.equal(undoPreview.before, changedProperties);
assert.equal(undoPreview.proposedText, originalProperties);
const undoResult = await (await apply(undoRoute, undoPreview)).json();
assert.equal(undoResult.state, "applied");
assert.match((await resumeRun(undoResult.conclusionJobId, undoResult.chatId, { fetcher: browser }).result()).content, /Restored recorded contents/);
assert.equal(files.get(`${prefix}/server.properties`), originalProperties);
const afterUndo = base + multiStepActions.length + 1;
assert.equal(mutations.length, afterUndo);
console.log("PASS: preserved all other server.properties bytes, separately approved Hey and empty hey.py, and reverted the recorded edit in the same chat.");
const unrelatedEdit = await propose("revert_file");
const unrelatedPreview = await (await preview(unrelatedEdit.route)).json();
assert.equal(unrelatedPreview.expectedSha256, null);
assert.match(unrelatedPreview.previewError, /no recorded original text/);
assert.equal((await apply(unrelatedEdit.route, unrelatedPreview)).status, 400);
assert.equal(mutations.length, afterUndo);
const declinedPlan = await sendPrompt(declinedPlanPrompt);
const firstRoute = `/api/ai/jobs/${declinedPlan.jobId}/review`;
const rejectedEdit = await (await apply(firstRoute, await (await preview(firstRoute)).json(), "dismiss")).json();
const independentStep = await resumeRun(rejectedEdit.conclusionJobId, declinedPlan.chatId, { fetcher: browser }).result();
assert.equal(mutations.length, afterUndo);
const independentRoute = `/api/ai/jobs/${independentStep.review_job_id}/review`;
const independentPreview = await (await preview(independentRoute)).json();
assert.deepEqual(independentPreview.proposal, { action: "create_folder", path: "Other" });
const independentResult = await (await apply(independentRoute, independentPreview)).json();
assert.match((await resumeRun(independentResult.conclusionJobId, declinedPlan.chatId, { fetcher: browser }).result()).content, /edit was declined and Other was created/);
assert.equal(files.get(`${prefix}/server.properties`), originalProperties);
assert.equal(files.get(`${prefix}/Other/.keep`), "");
console.log("PASS: a different chat could not revert unrecorded contents, and rejecting one step postponed the next independent step until separately accepted.");
const readOnly = await sendPrompt(readOnlyPrompt, null, "read_only");
assert.equal(readOnly.job.review_job_id, null);
assert.equal(readOnly.chat.review_job_id, null);
assert.match(readOnly.job.content, /stayed in Read only mode/);
assert.equal(mutations.length, afterUndo + 1);
console.log("PASS: Read only retained diagnostics and refused even a model-generated proposal that was not advertised.");
runs = Math.ceil(runs / 4) * 4;
const replacement = await sendPrompt(replacePlanPrompt, null, "file_plan");
assert.equal(replacementRefusals, 1);
assert.equal(replacementRetries, 1);
const replacementClient = browser;
const replaceRoute = `/api/ai/jobs/${replacement.jobId}/review`;
const replacePreview = await (await preview(replaceRoute)).json();
assert.deepEqual(replacePreview.proposal, { action: "replace_file", ...examples.replace_file });
assert.equal(replacePreview.plan, undefined);
assert.equal(replacePreview.before, originalProperties);
assert.equal(replacePreview.proposedText, paperProperties);
assert.equal(replacePreview.expectedSha256, hash(originalProperties));
assert.equal((await apply(replaceRoute, { ...replacePreview, expectedSha256: [hash(paperProperties), ""] })).status, 400);
assert.equal((await apply(replaceRoute, { ...replacePreview, expectedSha256: hash(paperProperties) })).status, 403);
assert.equal(mutations.length, afterUndo + 1);
const replaceResult = await (await apply(replaceRoute, replacePreview)).json();
assert.equal(replaceResult.state, "applied");
assert.equal(files.get(`${prefix}/server.properties`), paperProperties);
assert.equal(files.has(`${prefix}/hey/.keep`), false);
const pendingFolder = await resumeRun(replaceResult.conclusionJobId, replacement.chatId, { fetcher: browser }).result();
const folderRoute = `/api/ai/jobs/${pendingFolder.review_job_id}/review`;
const folder = await (await preview(folderRoute)).json();
assert.deepEqual(folder.proposal, { action: "create_folder", path: "hey" });
const createdFolder = await (await apply(folderRoute, folder)).json();
const conclusion = await resumeRun(createdFolder.conclusionJobId, replacement.chatId, { fetcher: browser }).result();
assert.equal(files.get(`${prefix}/hey/.keep`), "");
assert.equal(conclusion.review_job_id, null);
assert.match(conclusion.content, /replaced server.properties and created the root hey folder/);
assert.equal((await apply(replaceRoute, replacePreview)).status, 409);
const undoReplacement = await sendPrompt(`${reviewPrompt}revert_file native`, replacement.chatId);
assert.equal(browser, replacementClient);
const undoReplacementRoute = `/api/ai/jobs/${undoReplacement.jobId}/review`;
const undoReplacementPreview = await (await preview(undoReplacementRoute)).json();
assert.equal(undoReplacementPreview.proposedText, originalProperties);
const undone = await (await apply(undoReplacementRoute, undoReplacementPreview)).json();
assert.equal(undone.state, "applied");
await resumeRun(undone.conclusionJobId, replacement.chatId, { fetcher: browser }).result();
assert.equal(files.get(`${prefix}/server.properties`), originalProperties);
const afterReplacement = afterUndo + 4;
assert.equal(mutations.length, afterReplacement);
console.log("PASS: the Agent recovered from the exact false edit/folder refusal, proposed the folder after the approved replacement, and restored the original bytes on undo.");
files.set(`${prefix}/settings.yml`, initialFileText);
const partial = await sendPrompt(partialPlanPrompt, null, "file_plan");
let partialId = partial.jobId;
for (const action of ["create_folder", "replace_file"]) {
const route = `/api/ai/jobs/${partialId}/review`;
const previewed = await (await preview(route)).json();
assert.equal(previewed.proposal.action, action);
const confirmed = await (await apply(route, previewed)).json();
assert.equal(confirmed.state, "applied");
partialId = (await resumeRun(confirmed.conclusionJobId, partial.chatId, { fetcher: browser }).result()).review_job_id;
}
const partialRoute = `/api/ai/jobs/${partialId}/review`;
const partialPreview = await (await preview(partialRoute)).json();
assert.equal(partialPreview.expectedSha256, hash(initialFileText));
files.set(`${prefix}/settings.yml`, externalFileText);
const stopped = await (await apply(partialRoute, partialPreview)).json();
assert.equal(stopped.state, "refused");
assert.equal(stopped.code, "file_changed_on_disk");
assert.match(stopped.receipt, /changed after review/);
const partialConclusion = await resumeRun(stopped.conclusionJobId, partial.chatId, { fetcher: browser }).result();
assert.match(partialConclusion.content, /first two changes completed.*last folder was not created/);
assert.equal(partialConclusion.review_job_id, null);
assert.equal(files.get(`${prefix}/completed/.keep`), "");
assert.equal(files.get(`${prefix}/server.properties`), paperProperties);
assert.equal(files.get(`${prefix}/settings.yml`), externalFileText);
assert.equal(files.has(`${prefix}/skipped/.keep`), false);
assert.equal(mutations.length, afterReplacement + 2);
const undoPartial = await sendPrompt(`${reviewPrompt}revert_file native`, partial.chatId);
const undoPartialRoute = `/api/ai/jobs/${undoPartial.jobId}/review`;
const undoPartialPreview = await (await preview(undoPartialRoute)).json();
assert.equal(undoPartialPreview.proposedText, originalProperties);
const undonePartial = await (await apply(undoPartialRoute, undoPartialPreview)).json();
assert.equal(undonePartial.state, "applied");
await resumeRun(undonePartial.conclusionJobId, partial.chatId, { fetcher: browser }).result();
assert.equal(files.get(`${prefix}/server.properties`), originalProperties);
assert.equal(mutations.length, afterReplacement + 3);
console.log("PASS: the model received a stale-file refusal, reported unfinished work, and kept the earlier confirmed write available for undo.");
const staleReplacement = await sendPrompt(replacePlanPrompt, null, "file_plan");
const staleReplacementRoute = `/api/ai/jobs/${staleReplacement.jobId}/review`;
const staleReplacementPreview = await (await preview(staleReplacementRoute)).json();
const modifiedProperties = `${originalProperties}# external change\r\n`;
files.set(`${prefix}/server.properties`, modifiedProperties);
const refusedReplacement = await (await apply(staleReplacementRoute, staleReplacementPreview)).json();
assert.equal(refusedReplacement.state, "refused");
assert.equal(refusedReplacement.code, "file_changed_on_disk");
const afterStale = await resumeRun(refusedReplacement.conclusionJobId, staleReplacement.chatId, { fetcher: browser }).result();
assert.equal(afterStale.review_job_id, null);
assert.match(afterStale.content, /The folder was not requested/);
assert.equal(files.get(`${prefix}/server.properties`), modifiedProperties);
assert.equal(mutations.length, afterReplacement + 3);
console.log("PASS: a stale replacement sent no writes or folder creations.");
const resumed = await sendPrompt(prematurePrompt);
let now = resumed.job;
for (const [index, action] of prematureActions.entries()) {
const route = `/api/ai/jobs/${now.review_job_id}/review`;
const details = await (await preview(route)).json();
assert.deepEqual(details.proposal, action);
assert.equal(mutations.length, afterReplacement + 3 + index);
const result = await (await apply(route, details)).json();
assert.equal(result.state, "applied");
assert.deepEqual(result.activity.map(({ action: kind, target, status }) => [kind, target, status]), [[action.action, action.path, "applied"]]);
now = await resumeRun(result.conclusionJobId, resumed.chatId, { fetcher: browser }).result();
assert.equal(now.chat_id, resumed.job.chat_id);
assert.equal(JSON.parse(now.agent_actions).length, index + 1);
}
assert.equal(prematureReplies, 1);
assert.equal(repeatedCreations, 1);
assert.equal(now.review_job_id, null);
assert.match(now.content, /Created hes.py, ges, and ges\/hey.bb\./);
assert.match(now.content, /\*\*Changed:\*\*.*`hes\.py` - Created.*`ges` - Created folder.*`ges\/hey\.bb` - Created/);
assert.equal(files.get(`${prefix}/hes.py`), prematureActions[0].content);
assert.equal(files.get(`${prefix}/ges/.keep`), "");
assert.equal(files.get(`${prefix}/ges/hey.bb`), prematureActions[2].content);
const reopened = await (await browser(`/api/ai/chats/${resumed.chatId}`)).json();
assert.deepEqual(reopened.messages.map(({ role }) => role), ["user", "assistant"]);
assert.equal(reopened.messages.at(-1).content, now.content);
assert.deepEqual(JSON.parse(reopened.messages.at(-1).agent_actions).map(({ target }) => target), ["hes.py", "ges", "ges/hey.bb"]);
assert.equal((await nonOwner(`/api/ai/jobs/${resumed.jobId}`)).status, 404);
console.log("PASS: after the exact first-file reply, a duplicate was rejected before review and the Agent continued with the folder and remaining file. All three approved actions survived history reload.");
const beforeFollowUp = mutations.length;
const historyReply = await createRun({ server, chatId: resumed.chatId, prompt: historyFollowUp, provider: "openai-compatible", model: "synthetic" }, { fetcher: browser }).result();
assert.equal(historyReply.chat_id, resumed.job.chat_id);
assert.equal(historyReply.review_job_id, null);
assert.equal(historyReply.content, "The existing file says: Fixture random content.");
assert.equal(mutations.length, beforeFollowUp);
console.log("PASS: a new message in the same chat received bounded prior outcomes, verified the current file, and made no change.");
const { route: emptyRoute } = await propose("write_file", "empty");
const emptyPreview = await (await preview(emptyRoute)).json();
assert.equal(emptyPreview.before, "");
assert.equal(emptyPreview.expectedSha256, hash(""));
assert.equal(emptyPreview.proposedText, emptyFileEdit.newText);
assert.equal(mutations.length, beforeFollowUp);
await conclude(await (await apply(emptyRoute, emptyPreview)).json(), "write_file");
assert.equal(files.get(`${prefix}/${emptyFileEdit.path}`), emptyFileEdit.newText);
assert.equal(mutations.length, beforeFollowUp + 1);
assert.equal(mutations.at(-1).data.expectedSha256, hash(""));
assert.equal(mutations.at(-1).data.mode, "update");
console.log("PASS: a reviewed edit of an existing empty file wrote the exact model-proposed text once.");
const tracked = await sendPrompt(trackedPrompt);
const beforeTracked = mutations.length;
let trackedJob = tracked.job;
for (const [index, proposal] of trackedActions.entries()) {
assert.match(trackedJob.review_job_id, /^\d+$/);
const route = `/api/ai/jobs/${trackedJob.review_job_id}/review`;
const details = await (await preview(route)).json();
assert.deepEqual(details.proposal, proposal);
assert.equal(details.plan, undefined);
assert.equal(mutations.length, beforeTracked + index);
const result = await (await apply(route, details)).json();
assert.equal(result.state, "applied");
trackedJob = await resumeRun(result.conclusionJobId, tracked.chatId, { fetcher: browser }).result();
}
assert.equal(trackedJob.review_job_id, null);
assert.equal(mutations.length, beforeTracked + trackedActions.length);
assert.equal(files.get(`${prefix}/${trackedActions[1].path}`), trackedActions[1].content);
assert.equal(files.get(`${prefix}/${trackedActions[2].path}`), prematureActions[0].content.replace(trackedActions[2].oldText, trackedActions[2].newText));
console.log("PASS: an unfinished edit survived two approved creations and used a standalone text read before its own approval.");
const existingMarker = "Existing folder marker\n";
files.set(`${prefix}/reports/.keep`, existingMarker);
for (const { path, oldText } of queuedActions.filter(({ action }) => action === "write_file")) files.set(`${prefix}/${path}`, `${oldText}\n`);
const queued = await sendPrompt(queuedPrompt, null, "file_plan");
const beforeQueued = mutations.length;
const requestsBeforeReview = queuedProviderRequests;
assert.equal(requestsBeforeReview, 3, "one read batch, one premature reply, and one corrective draft");
let queuedJob = queued.job;
let previousToken;
for (const [index, proposal] of queuedActions.entries()) {
assert.match(queuedJob.review_job_id, /^\d+$/);
const history = await (await browser(`/api/ai/chats/${queued.chatId}`)).json();
assert.equal(history.chat.review_job_id, queuedJob.review_job_id);
assert.equal(history.chat.review_message_id, String(history.messages.at(-1).id));
const route = `/api/ai/jobs/${queuedJob.review_job_id}/review`;
const details = await (await preview(route)).json();
assert.deepEqual(details.proposal, proposal);
assert.equal(details.plan, undefined);
assert.equal(details.remaining, queuedActions.length - index - 1);
if (previousToken) assert.equal((await apply(route, { ...details, token: previousToken })).status, 403);
assert.equal(mutations.length, beforeQueued + index);
const result = await (await apply(route, details)).json();
assert.equal(result.state, index === 0 ? "refused" : "applied");
if (index === 0) {
assert.equal(result.code, "review_path_exists");
assert.doesNotMatch(result.receipt, /skipped/);
}
previousToken = details.token;
queuedJob = await resumeRun(result.conclusionJobId, queued.chatId, { fetcher: browser }).result();
}
assert.equal(queuedJob.review_job_id, null);
assert.equal(queuedProviderRequests, requestsBeforeReview, "approvals and the final report must not contact the provider");
assert.deepEqual(JSON.parse(queuedJob.agent_actions).map(({ target, status }) => [target, status]),
queuedActions.map(({ path }, index) => [path, index === 0 ? "refused" : "applied"]));
assert.equal(mutations.length, beforeQueued + queuedActions.length);
for (const { action, path, content, newText, changeSummary } of queuedActions) {
assert.ok(queuedJob.content.includes(`\`${path}\``), `the conclusion must name ${path}`);
if (changeSummary) assert.ok(queuedJob.content.includes(changeSummary), `the conclusion must describe ${path}`);
assert.equal(files.get(`${prefix}/${path}${action === "create_folder" ? "/.keep" : ""}`), content ?? (newText ? `${newText}\n` : existingMarker));
}
assert.match(queuedJob.content, /^\*\*Status:\*\* \[\u2713\] Task completed successfully/);
assert.match(queuedJob.content, /\*\*Unchanged:\*\* `reports` - Folder already existed; nothing was overwritten\./);
assert.equal(queuedJob.content.split("\n").length, 3);
assert.doesNotMatch(queuedJob.content, /request limit|Git \/ Repository State|Verification & Testing|Next Steps/);
console.log("PASS: an existing-folder refusal preserved four separately reviewed writes and a compact conclusion with zero follow-up provider requests.");
}
function assertAutomaticEdits() {
for (const edit of automaticEdits) {
const path = `${prefix}/${edit.path}`;
const writes = mutations.filter(({ data }) => data.path === path);
assert.equal(writes.length, 1);
const [write] = writes;
assert.equal(write.route, "/v1/fs/write");
assert.equal(write.data.mode, "update");
assert.equal(write.data.expectedSha256, hash(initialFileText));
assert.equal(files.get(path), changedFileText);
}
}
return { provider, node, exercise, seedServer, automaticEdits, assertAutomaticEdits, server,
uncertainEdit, uncertainWriteCount: () => mutations.filter(({ data }) => data.path === `${prefix}/${uncertainEdit.path}`).length };
}
module.exports = { createActionChecks };