"use strict"; const assert = require("node:assert/strict"); const fs = require("node:fs"); const path = require("node:path"); const { test } = require("node:test"); const vm = require("node:vm"); const { BOT_TOOL_DEFINITIONS, BOT_OPENAI_TOOL_DEFINITIONS, BOT_GOOGLE_FUNCTION_DECLARATIONS, buildBotAssistantSystemPrompt, isBotReadonlyToolName, resolveServerFromAccessibleList } = require("../utils/bot-ai-tools"); const serverAgentHistory = require("../public/js/server-agent-history"); const agentLive = require("../public/js/agent-live"); const { createRun, resumeRun } = agentLive; const { AI_PROVIDER_CONFIGS } = require("../AgentWorker/provider-config"); const { applyAgentFileEdit, hashAgentFile, revertAgentFileEdit } = require("../AgentWorker/file-edit"); const { createAgentActionReview } = require("../AgentWorker/action-review"); const { createAgentFileDiagnostics } = require("../services/server-agent-file-diagnostics"); const { parseLiveAgentSubmission } = require("../AgentWorker/admission"); const { AGENT_ACTIONS, AGENT_ACTION_TOOL, AGENT_ACTION_INSTRUCTIONS, buildAgentActionOffer, normalizeAgentAction, getAgentCreationConflict, parseAgentReview, serializeAgentReview, remainingAgentReviewSteps, splitAgentReview, isAgentFilePlan, pendingAgentFileTasks, canAutoApproveAgentFileEdits, isAutomaticAgentFileEdit } = require("../AgentWorker/action-proposal"); const root = path.join(__dirname, ".."); const panel = fs.readFileSync(path.join(root, "index.js"), "utf8"); const browser = fs.readFileSync(path.join(root, "public/js/bot.js"), "utf8"); test("automatic Agent file edits require explicit consent and advertise only targeted edits", () => { const row = { source: "planner_send", auto_approve_file_edits: 1, server_id: "2", account_epoch: 0, read_only: 0 }; for (const source of ["planner_send", "scheduler_planner_next", "scheduler_prompt"]) { assert.equal(canAutoApproveAgentFileEdits({ ...row, source }), true); } for (const patch of [{ source: "live_chat" }, { source: "manual" }, { auto_approve_file_edits: 0 }, { auto_approve_file_edits: undefined }, { server_id: null }, { account_epoch: null }, { read_only: 1 }]) { assert.equal(canAutoApproveAgentFileEdits({ ...row, ...patch }), false); } const perms = { files_read: true, files_write: true, files_create: true, files_delete: true, console_write: true, server_start: true }; const { tool, instructions } = buildAgentActionOffer(perms, { automatic: true }); assert.deepEqual(tool.parameters.properties.action.enum, ["write_file"]); assert.deepEqual(Object.keys(tool.parameters.properties), ["action", "path", "oldText", "newText"]); assert.match(instructions, /without another prompt/); assert.equal(buildAgentActionOffer({ ...perms, files_read: false }, { automatic: true }), null); assert.equal(buildAgentActionOffer({ ...perms, files_write: false }, { automatic: true }), null); assert.equal(isAutomaticAgentFileEdit({ action: "replace_file" }), false); assert.match(buildAgentActionOffer(perms).instructions, /Only the operator can approve/); }); test("automatic Agent dispatch uses the reviewed text writer without replay or stale writes", async () => { const entry = { name: "fixture", id: 2 }; const row = { id: 3, user_id: 1, claim_token: "claim", source: "planner_send", auto_approve_file_edits: 1, server_name: entry.name, server_id: entry.id, account_epoch: 1, read_only: 0, source_ref: "42" }; const original = "enabled=false\nlimit=6\n"; const proposal = { action: "write_file", path: "config/settings.ini", oldText: "enabled=false", newText: "enabled=true" }; const calls = []; let text = original; let attempts = 0; let revoked = false; let revokeOnRead = false; let revokeOnLock = false; let currentNode = "node-a"; let fenced = false; let heldBy = null; let preflightExpired = false; let resumePreflight; let abandonedPreflight; const review = createAgentActionReview({ db: { createPanelDatabasePool: () => ({ async getConnection() { return { async query({ sql, timeout }) { assert.equal(timeout, 2000); if (sql === "ROLLBACK") fenced = false; else assert.equal(sql, "START TRANSACTION"); }, async execute(query, params) { assert.match(query.sql, /FROM servers WHERE name = \? LIMIT 1 FOR UPDATE/); assert.deepEqual(params, [entry.name]); fenced = true; if (revokeOnLock) revoked = true; return [[{ id: entry.id, name: entry.name, node_id: currentNode, status: "running", suspended: 0 }]]; }, release() {}, }; } }), async query(sql, params) { if (sql.startsWith("UPDATE server_planner_items")) { assert.equal(fenced, true); assert.match(sql, /job\.status = 'running' AND job\.claim_token = \?/); assert.deepEqual(params, [row.id, "42", row.claim_token]); heldBy = row.id; return { affectedRows: 1 }; } assert.match(sql, /job\.status = 'running'/); assert.match(sql, /job\.auto_file_edit_attempts = \?/); assert.deepEqual(params.slice(1, 3), [row.id, row.claim_token]); if (params[3] !== attempts) return { affectedRows: 0 }; attempts = params[0]; return { affectedRows: 1 }; } }, featureEnabled: () => true, isRemoteEntry: () => true, withTimeout(pending, timeout, label) { assert.equal(timeout, 2000); if (!preflightExpired) return pending; abandonedPreflight = pending; return Promise.reject(new Error(label)); }, resolveRemoteFsContext: async () => ({ remote: true, serverId: entry.id, serverName: entry.name, baseDir: "/fixture", node: {}, nodeId: "node-a" }), fsRelayDeps: { buildNodeBaseUrl: () => "http://127.0.0.1:8080", buildNodeAuthHeaders: () => ({}), async httpRequestJson(url, _method, _headers, body) { if (url.endsWith("/v1/fs/read")) { if (revokeOnRead) revoked = true; return { status: 200, json: { ok: true, content: Buffer.from(text).toString("base64") } }; } assert.ok(url.endsWith("/v1/fs/write")); assert.equal(fenced, true); assert.equal(heldBy, row.id); assert.equal(body.mode, "update"); assert.equal(body.expectedSha256, hashAgentFile(text)); assert.equal(body.path, "/fixture/config/settings.ini"); calls.push(body.content); text = body.content; return { status: 200, json: { ok: true } }; } }, recordActivity(_server, kind, detail) { assert.equal(kind, "file_edit"); assert.equal(detail.via, "agent_auto_approved"); }, }); const dispatch = (args = {}, claimedRow = row) => review.applyAutomaticFileEdit({ row: claimedRow, entry, user: { email: "editor@example.test" }, req: { async readAiAgentFilePermissions() { if (fenced && preflightExpired) await new Promise((resolve) => { resumePreflight = resolve; }); if (fenced && revokeOnLock) throw Object.assign(new Error("Fixture permission was revoked"), { status: 403 }); return { files_read: true, files_write: !revoked }; } }, args: { proposal, editVersion: { sha256: hashAgentFile(original), nodeId: "node-a", path: `/fixture/${proposal.path}` }, attempt: 1, ...args }, signal: new AbortController().signal }); await assert.rejects(dispatch({}, { ...row, auto_approve_file_edits: 0 }), { code: "agent_automatic_file_edit_denied" }); await assert.rejects(dispatch({ proposal: { action: "delete_file", path: proposal.path } }), { code: "agent_automatic_file_edit_invalid" }); assert.equal((await dispatch()).state, "applied"); await assert.rejects(dispatch(), { code: "agent_automatic_file_edit_used" }); assert.equal((await dispatch({ attempt: 2 })).state, "refused"); text = original; revokeOnRead = true; assert.equal((await dispatch({ attempt: 3 })).state, "refused"); revoked = revokeOnRead = false; currentNode = "node-b"; assert.match((await dispatch({ attempt: 4 })).receipt.text, /server moved/); currentNode = "node-a"; revokeOnLock = true; assert.match((await dispatch({ attempt: 5 })).receipt.text, /Permission to make this edit was revoked/); revoked = revokeOnLock = false; preflightExpired = true; attempts = 0; heldBy = null; assert.match((await dispatch()).receipt.text, /could not verify permissions in time/); assert.equal(fenced, false); resumePreflight(); await abandonedPreflight; assert.equal(heldBy, null); assert.deepEqual(calls, ["enabled=true\nlimit=6\n"]); }); test("Agent diagnostics give an automatic edit only the hash of complete readable text", async () => { let reply; const { executeAiAgentFileOperations } = createAgentFileDiagnostics({ env: { AI_AGENT_FILE_READ_MAX_CHARS: "2000" }, resolveRemoteFsContext: async () => ({ remote: true, serverId: "2", serverName: "fixture", baseDir: "/fixture", node: {}, nodeId: "fixture-node" }), fsRelayDeps: { buildNodeBaseUrl: () => "http://127.0.0.1:8080", buildNodeAuthHeaders: () => ({}), httpRequestJson: async () => reply }, }); const read = async (includeEditVersion) => (await executeAiAgentFileOperations({ operations: [{ action: "read", path: "config/settings.ini" }], serverName: "fixture", serverId: "2", req: { readAiAgentFilePermissions: async () => ({ files_read: true }) }, structured: true, includeEditVersion, }))[0]; for (const text of ["", "limit=6\n"]) { reply = { status: 200, json: { ok: true, content: Buffer.from(text).toString("base64") } }; assert.deepEqual((await read(true)).editVersion, { sha256: hashAgentFile(text), nodeId: "fixture-node", path: "/fixture/config/settings.ini" }); assert.equal((await read(false)).editVersion, undefined); } reply = { status: 200, json: { ok: true, content: Buffer.from("A".repeat(2001)).toString("base64") } }; assert.equal((await read(true)).editVersion, undefined); reply = { status: 404, json: { ok: false } }; assert.equal((await read(true)).editVersion, undefined); }); test("a reviewed Agent edit distinguishes a missing file from a readable empty file", async () => { const account = { id: 1, session_epoch: 1, admin: true, email: "operator@example.test" }; const entry = { name: "fixture", id: 2 }; const proposal = { action: "write_file", path: "config/settings.ini", oldText: "enabled=false", newText: "enabled=true" }; const row = { id: 3, user_id: account.id, account_epoch: account.session_epoch, server_name: entry.name, server_id: entry.id, action_proposal: serializeAgentReview(proposal) }; let reply = { status: 404, json: { ok: false, error: "file not found" } }; const review = createAgentActionReview({ db: { query: async () => [row] }, featureEnabled: () => true, findServer: async () => entry, isServerSuspended: () => false, isRemoteEntry: () => true, getEffectivePermsForUserOnServer: async () => ({ files_read: true, files_write: true }), findUserById: async () => account, userCanUseAdpanelAgent: () => true, resolveRemoteFsContext: async () => ({ remote: true, serverId: entry.id, serverName: entry.name, baseDir: "/fixture" }), issueActionToken: (_req, action) => action, fsRelayDeps: { buildNodeBaseUrl: () => "http://127.0.0.1:8080", buildNodeAuthHeaders: () => ({}), httpRequestJson: async () => reply, }, }); const preview = () => review.preview({ agentAccount: account }, row.id, entry.name); const missing = await preview(); assert.equal(missing.before, null); assert.equal(missing.expectedSha256, null); assert.match(missing.token, /decline only/); assert.match(missing.previewError, /node reported that the file was not found/i); reply = { status: 200, json: { ok: true, content: "" } }; const empty = await preview(); assert.equal(empty.before, ""); assert.equal(empty.expectedSha256, null); assert.match(empty.previewError, /exact text to replace was not found/i); const requestedText = "print(6 * 7)\n"; row.action_proposal = serializeAgentReview({ ...proposal, oldText: "", newText: requestedText }); const fill = await preview(); assert.equal(fill.before, ""); assert.equal(fill.proposedText, requestedText); assert.match(fill.diff, /\+print\(6 \* 7\)/); assert.equal(fill.expectedSha256, hashAgentFile("")); assert.doesNotMatch(fill.token, /decline only/); assert.equal(fill.previewError, undefined); for (const upstream of [ { status: 404, json: { ok: false } }, { status: 200, json: { ok: true } }, { status: 200, json: { ok: true, content: "!" } }, { status: 200, json: { ok: true, content: Buffer.from([0xff]).toString("base64") } }, { status: 200, json: { ok: true, content: Buffer.from("existing settings").toString("base64") } }, ]) { reply = upstream; const blocked = await preview(); assert.equal(blocked.expectedSha256, null); assert.match(blocked.token, /decline only/); } }); test("a targeted Agent edit preserves unrelated settings and refuses an ambiguous match", () => { const original = "# Server settings\r\nonline-mode=true\r\nmax-players=20\r\n"; assert.deepEqual(applyAgentFileEdit(original, "online-mode=true", "online-mode=false", 16_000), { content: "# Server settings\r\nonline-mode=false\r\nmax-players=20\r\n", offset: original.indexOf("online-mode"), }); assert.deepEqual(applyAgentFileEdit(original, "online-mode=false", "online-mode=true", 16_000), { error: "review_edit_not_found" }); assert.deepEqual(applyAgentFileEdit(`${original}online-mode=true`, "online-mode=true", "online-mode=false", 16_000), { error: "review_edit_ambiguous" }); assert.deepEqual(applyAgentFileEdit(original, original.trim(), "online-mode=false", 16_000), { error: "review_edit_whole_file" }); assert.deepEqual(applyAgentFileEdit("abc", "b", "$&", 4), { content: "a$&c", offset: 1 }); assert.deepEqual(applyAgentFileEdit("abc", "b", "$&", 3), { error: "review_edit_too_large" }); assert.deepEqual(applyAgentFileEdit("", "", "sample\n", 16_000), { content: "sample\n", offset: 0 }); assert.deepEqual(applyAgentFileEdit("", "", "sample\n", 6), { error: "review_edit_too_large" }); assert.deepEqual(applyAgentFileEdit("\n", "", "sample\n", 16_000), { error: "review_edit_not_found" }); assert.deepEqual(applyAgentFileEdit("", "", "", 16_000), { error: "review_edit_invalid" }); }); test("a confirmed Agent replacement can restore the recorded original bytes, including an empty file", () => { const original = "# Broken settings\r\nonline-mode=false\r\n"; const replacement = "online-mode=true\nmax-players=20\n"; const snapshot = { offset: 0, afterSha256: hashAgentFile(replacement) }; for (const oldText of [original, ""]) { assert.deepEqual(revertAgentFileEdit(replacement, { oldText, newText: replacement }, snapshot, 16_000), { content: oldText }); } }); test("an Agent revert uses the recorded offset and fails closed after another file change", () => { const edit = { oldText: "online-mode=true", newText: "" }; const original = "# Some settings\nonline-mode=true\nmax-players=20\n"; const { content, offset } = applyAgentFileEdit(original, edit.oldText, edit.newText, 16_000); const snapshot = { offset, afterSha256: hashAgentFile(content) }; assert.deepEqual(revertAgentFileEdit(content, edit, snapshot, 16_000), { content: original }); assert.deepEqual(revertAgentFileEdit(`${content}motd=Changed\n`, edit, snapshot, 16_000), { error: "review_revert_changed" }); assert.deepEqual(revertAgentFileEdit(content, edit, null, 16_000), { error: "review_revert_unavailable" }); }); test("a reviewed Agent action has exact arguments and cannot smuggle authority or a new mode", () => { const legacyModule = { exports: {} }; const proposalSource = fs.readFileSync(require.resolve("../AgentWorker/action-proposal"), "utf8"); vm.runInNewContext(`String.prototype.isWellFormed = undefined;\n${proposalSource}`, { module: legacyModule, Buffer }); const legacy = legacyModule.exports; const examples = { start: {}, stop: {}, restart: {}, kill: {}, console_command: { command: "list" }, write_file: { path: "config/\u{1f4c4}.yml", oldText: "enabled: false", newText: "enabled: true\n# \u{1f4c4}\n" }, replace_file: { path: "server.properties", content: "online-mode=true\nmax-players=20\n" }, revert_file: { path: "config/settings.yml" }, create_file: { path: "README.txt", content: "" }, create_folder: { path: "maps/World 1" }, delete_file: { path: "old.txt" }, create_backup: { name: "Before update", description: "" }, restore_backup: { backup: "backup-1", deleteOldFiles: false }, delete_backup: { backup: "backup-1" }, }; assert.deepEqual(Object.keys(examples).sort(), [...AGENT_ACTIONS].sort()); for (const [action, fields] of Object.entries(examples)) { const proposal = { action, ...fields }; assert.deepEqual(normalizeAgentAction(proposal), proposal); assert.equal(JSON.stringify(legacy.normalizeAgentAction(proposal)), JSON.stringify(proposal), action); for (const forbidden of [{ approved: true }, { server: "other" }, { mode: "monitor" }]) { assert.equal(normalizeAgentAction({ ...proposal, ...forbidden }), null); } } for (const path of ["/absolute", "foo/../bar", "foo//bar", "foo\\bar", "settings\u202e.yml", "settings\n.yml"]) { assert.equal(normalizeAgentAction({ action: "write_file", path, oldText: "a", newText: "x" }), null); } assert.equal(normalizeAgentAction({ action: "write_file", path: "config.yml", oldText: "a", newText: "é".repeat(8001) }), null); assert.equal(normalizeAgentAction({ action: "write_file", path: "config.yml", content: "enabled: false" }), null); const fill = { action: "write_file", path: "sample.py", oldText: "", newText: "print(42)\n" }; assert.deepEqual(normalizeAgentAction(fill), fill); assert.equal(normalizeAgentAction({ ...fill, newText: "" }), null); assert.equal(normalizeAgentAction({ action: "replace_file", path: "server.properties", content: "" }), null); assert.equal(normalizeAgentAction({ action: "replace_file", path: "server.properties", content: "a".repeat(16_001) }), null); assert.equal(normalizeAgentAction({ action: "replace_file", path: "server.properties", content: "a", oldText: "b" }), null); assert.equal(normalizeAgentAction({ action: "console_command", command: "list\nstop" }), null); assert.equal(normalizeAgentAction({ action: "constructor" }), null); assert.equal(legacy.normalizeAgentAction({ action: "create_file", path: "bad\ud800.txt", content: "" }), null); assert.equal(legacy.normalizeAgentAction({ action: "write_file", path: "valid.txt", oldText: "a", newText: "broken\udfff" }), null); assert.equal(legacy.normalizeAgentFileTool("read_server_file", { path: "config/\u{1f4c4}.yml" }).path, "config/\u{1f4c4}.yml"); }); test("the shared Agent prompt describes review and forbids mode changes only in the live action workflow", () => { assert.deepEqual(AGENT_ACTION_TOOL.parameters.properties.action.enum, AGENT_ACTIONS); const live = buildBotAssistantSystemPrompt({ actionInstructions: AGENT_ACTION_INSTRUCTIONS }); assert.match(live, /Do not switch to normal chat, monitor mode/); assert.match(live, /Only the operator can approve it in the panel/); assert.match(live, /propose_server_action/); assert.match(live, /Infer the user's intended outcome.*operation verbs are clues to intent.*When the user delegates a choice, decide it yourself/); assert.match(live, /Do not end with an offer.*If one step is blocked, prepare the next independent requested action/); assert.match(live, /file_not_found.*does not depend on prior contents.*propose create_file for review even if the user described it as an edit/); assert.match(live, /Do not create a file if the user required an existing file or ruled out creation.*Do not treat a permission, path, format, or connectivity error as a missing file/); assert.match(live, /If the read confirms the file exists and is empty, send an empty oldText/); assert.match(live, /Do not ask the operator to paste file contents you can read/); assert.match(live, /explicitly asks to replace an existing file.*use replace_file/); assert.doesNotMatch(buildBotAssistantSystemPrompt({}), /propose_server_action/); }); test("review schemas and prompts describe only permitted actions and distinguish file reads from changes", () => { assert.equal(buildAgentActionOffer({ files_read: true, files_write: false }), null); assert.equal(buildAgentActionOffer({ files_write: true }), null); const creation = buildAgentActionOffer({ files_create: true }); assert.deepEqual(creation.tool.parameters.properties.action.enum, ["create_file", "create_folder"]); assert.deepEqual(Object.keys(creation.tool.parameters.properties), ["action", "path", "content", "fileTasks", "changeSummary", "planComplete"]); assert.deepEqual(creation.tool.parameters.properties.fileTasks.items.properties.action.enum, ["create_file", "create_folder"]); assert.match(creation.instructions, /create_folder\(path\)/); assert.doesNotMatch(creation.instructions, /write_file|read_server_file|console_command/); const editor = buildAgentActionOffer({ files_read: true, files_write: true }); const prompt = buildBotAssistantSystemPrompt({ currentServerPerms: { files_read: true }, actionInstructions: editor.instructions }); assert.deepEqual(editor.tool.parameters.properties.action.enum, ["write_file", "replace_file", "revert_file"]); assert.match(prompt, /diagnostic permissions: server status, read server files/); assert.match(prompt, /write_file\(path, oldText, newText\)/); assert.doesNotMatch(prompt, /propose create_file/); assert.doesNotMatch(prompt, /server status only|cannot change them/); }); test("Agent creation conflict checks use path boundaries and do not assume state survived deletion or restore", () => { const folder = { action: "create_folder", path: "reports" }; const file = { action: "create_file", path: "reports/week/summary.txt", content: "New content" }; const created = { action: file.action, path: file.path, decision: "accepted" }; assert.match(getAgentCreationConflict(folder, [created]).error, /already used this parent directory/); assert.equal(getAgentCreationConflict({ ...folder, path: "report" }, [created]), null); assert.equal(getAgentCreationConflict(folder, [{ ...created, decision: "declined" }]), null); assert.equal(getAgentCreationConflict(file, [created, { action: "delete_file", path: file.path, decision: "accepted" }]), null); const restored = { action: "restore_backup", decision: "accepted" }; assert.equal(getAgentCreationConflict(folder, [created, restored]), null); const declined = { ...folder, decision: "declined" }; assert.match(getAgentCreationConflict(folder, [declined, restored]).error, /operator already declined/); assert.match(getAgentCreationConflict(file, [declined]).error, /declined creation of a parent folder/); assert.match(getAgentCreationConflict({ ...folder, path: "reports/week" }, [declined]).error, /declined creation of a parent folder/); assert.equal(getAgentCreationConflict({ ...file, path: "reports-other/week/summary.txt" }, [declined]), null); assert.equal(getAgentCreationConflict({ ...file, action: "write_file" }, [created]), null); }); test("Agent plans preserve ordered proposals but cannot carry approval or exceed the step limit", () => { const actions = [{ action: "create_folder", path: "Hey" }, { action: "create_file", path: "Hey/hey.py", content: "" }]; assert.deepEqual(parseAgentReview(serializeAgentReview(actions[0], actions.slice(1))), { actions, resumeModel: false }); assert.deepEqual(parseAgentReview(serializeAgentReview(actions[0], [], true)), { actions: [actions[0]], resumeModel: true }); assert.equal(serializeAgentReview(actions[0], actions.slice(1), true), null); assert.equal(normalizeAgentAction({ ...actions[0], resumeModel: true }), null); assert.equal(parseAgentReview(JSON.stringify({ ...actions[0], approved: true })), null); assert.equal(serializeAgentReview(actions[0], [{ ...actions[1], approved: true }]), null); assert.equal(serializeAgentReview(actions[0], new Array(5).fill(actions[1])), null); assert.equal(serializeAgentReview({ action: "write_file", path: "settings.yml", content: "one truncated line" }), null); const independent = { action: "create_folder", path: "Other", requiresPrevious: false }; assert.deepEqual(remainingAgentReviewSteps([actions[1], independent], "dismissed"), [independent]); assert.deepEqual(remainingAgentReviewSteps([independent], "unknown"), []); }); test("a definite refusal preserves independently reviewable live drafts without replaying a blocked path", () => { const child = { action: "create_file", path: "reports/today.txt", content: "Notes\n" }; const sibling = { action: "create_file", path: "reports-other.txt", content: "Other\n" }; const rootFile = { action: "create_file", path: "utility.py", content: "print(42)\n" }; const remaining = [child, sibling, rootFile]; const blocked = { action: "create_folder", path: "reports", decision: "refused" }; const live = { resumeModel: true, outcome: blocked }; assert.deepEqual(remainingAgentReviewSteps(remaining, "refused", live), [sibling, rootFile]); assert.deepEqual(remainingAgentReviewSteps(remaining, "refused", { ...live, outcome: { ...blocked, code: "review_path_exists" } }), remaining); assert.deepEqual(remainingAgentReviewSteps(remaining, "stale", { ...live, outcome: { action: "write_file", path: "settings.yml" } }), remaining); for (const state of ["dismissed", "unknown"]) assert.deepEqual(remainingAgentReviewSteps(remaining, state, live), []); assert.deepEqual(remainingAgentReviewSteps(remaining, "refused", { outcome: blocked }), []); }); test("file task checklists persist but only the current proposal can enter a review", () => { const current = { action: "create_folder", path: "reports" }; const tasks = [{ action: "write_file", path: "settings.yml" }, current, { action: "create_file", path: "reports/today.txt" }]; const saved = parseAgentReview(serializeAgentReview(current, [], true, tasks)); assert.deepEqual(saved, { actions: [current], resumeModel: true, fileTasks: tasks }); assert.deepEqual(pendingAgentFileTasks(saved.fileTasks, [{ ...current, decision: "accepted" }]), [tasks[0], tasks[2]]); assert.deepEqual(pendingAgentFileTasks(saved.fileTasks, [{ ...current, decision: "accepted" }, { ...tasks[0], decision: "declined" }]), [tasks[2]]); for (const invalid of [[...tasks, current], [{ ...current, approved: true }], [{ ...current, path: "../escape" }], [{ action: "restart", path: "reports" }]]) { assert.equal(serializeAgentReview(current, [], true, invalid), null); assert.equal(parseAgentReview(JSON.stringify({ ...current, resumeModel: true, fileTasks: invalid })), null); } assert.equal(serializeAgentReview(current, [], false, tasks), null); }); test("a model's queued file changes each require a distinct review even in General access", () => { const actions = [{ action: "write_file", path: "settings.yml", oldText: "enabled: false", newText: "enabled: true", changeSummary: "Enabled the requested setting." }, { action: "create_file", path: "reports/today.txt", content: "Notes\n" }]; const fileTasks = actions.map(({ action, path }) => ({ action, path })); const saved = parseAgentReview(serializeAgentReview(actions[0], actions.slice(1), true, fileTasks, true)); assert.deepEqual(saved, { actions, resumeModel: true, fileTasks, planComplete: true }); assert.deepEqual(splitAgentReview(saved.actions, true, saved.resumeModel), { steps: actions.slice(0, 1), remainingActions: actions.slice(1) }); assert.deepEqual(splitAgentReview(saved.actions, true), { steps: actions, remainingActions: [] }); assert.equal(serializeAgentReview(actions[0], actions.slice(1), true, fileTasks.slice(0, 1)), null); assert.equal(serializeAgentReview(actions[0], [{ action: "restart" }], true, fileTasks), null); assert.equal(serializeAgentReview(actions[0], [], false, undefined, true), null); assert.equal(normalizeAgentAction({ ...actions[0], changeSummary: "First line\nSecond line" }), null); assert.equal(normalizeAgentAction({ ...actions[0], changeSummary: "a".repeat(201) }), null); assert.equal(normalizeAgentAction({ ...actions[0], approved: true }), null); }); test("a file plan can group edits and creations on distinct paths, never non-file or destructive actions", () => { const edit = { action: "replace_file", path: "server.properties", content: "online-mode=true\n" }; assert.equal(isAgentFilePlan([edit, { action: "create_folder", path: "hey" }]), true); assert.equal(isAgentFilePlan([edit]), false); assert.equal(isAgentFilePlan([edit, { ...edit, path: "SERVER.PROPERTIES" }]), false); for (const action of ["console_command", "restart", "delete_file", "revert_file", "restore_backup"]) { assert.equal(isAgentFilePlan([edit, { action, path: "other" }]), false); } }); test("the saved Agent access picker is scoped to its account and server, and cannot grant full access", () => { const view = fs.readFileSync(path.join(root, "views/bot.ejs"), "utf8"); const options = view.match(/]*\bid="aiAgentAccessMode"[^>]*>([\s\S]*?)<\/select>/)?.[1] || ""; assert.deepEqual(Array.from(options.matchAll(/