fix(agents): A2 review round: config check, name rule, drafts and test gaps (#1873)

The CLI agent verbs validate the instance config through loadSystem before
any read or write, and print a fixed line for errors they do not own. The
root writer refuses a config directory with an ancestor another user can
write without the sticky bit. The project HTTP route checks agent names
with the organization ID_PATTERN and answers 400 naming the key.

The Settings level forms take their own class, so the role-instance
handlers no longer catch them, and keep both drafts in module state with
the revision each began at. The organization writer tests now reach the
file's own uid check and test the assistant protection with an assistant
in the fixture.
This commit was merged in pull request #1913.
This commit is contained in:
jason.woltje committed 2026-11-10 18:25:54 -06:00
1 parent 1e1bbaa6dd
commit a4eed1e219
10 files changed
+226 -54

No files matched your search

+18 -6
View File
@@ -19,9 +19,10 @@
// A write prints its receipt; refusals name keys, never values. // A write prints its receipt; refusals name keys, never values.
import { configDir } from '../../organization/src/organization-config.mjs'; import { configDir } from '../../organization/src/organization-config.mjs';
import { organizationWriter } from '../../organization/src/organization.mjs'; import { OrgError } from '../../organization/src/org-registry.mjs';
import { OrganizationError, organizationWriter } from '../../organization/src/organization.mjs';
import { changeRootAgent, patchRootEntry, projectAgentSummary, readRootAgentsFile, rootAgentSummary } from '../../organization/src/agent-levels-write.mjs'; import { changeRootAgent, patchRootEntry, projectAgentSummary, readRootAgentsFile, rootAgentSummary } from '../../organization/src/agent-levels-write.mjs';
import { rolesDir } from './config.mjs'; import { loadSystem, rolesDir } from './config.mjs';
import { DEV_OWNER, devOwnerInstance } from './dev-local-owner.mjs'; import { DEV_OWNER, devOwnerInstance } from './dev-local-owner.mjs';
import { CliError } from './errors.mjs'; import { CliError } from './errors.mjs';
import { refuseInsideAgent } from './transport.mjs'; import { refuseInsideAgent } from './transport.mjs';
@@ -82,15 +83,26 @@ function vars(parsed, line) {
const revisionOf = (parsed, read) => parsed.single['--revision'] ?? read(); const revisionOf = (parsed, read) => parsed.single['--revision'] ?? read();
function owner(io) { function owner(io) {
refuseInsideAgent(io.env); refuseInsideAgent(io.env);
devOwnerInstance(io.env); // Its refusal is one fixed line naming no path.
let instance;
try { instance = devOwnerInstance(io.env); } catch (error) { throw error instanceof CliError ? error : new CliError(String(error?.message), 2); }
// The instance's system config must exist and validate, marker included, as `mosaic org` checks:
// a missing or broken config refuses (exit 3) before anything is read or written.
loadSystem({ env: io.env, instance });
return { dir: configDir(io.env), roles: rolesDir(io.env) }; return { dir: configDir(io.env), roles: rolesDir(io.env) };
} }
// Only the writers' own coded refusals print their text (it names keys and ids, never a value).
// Anything else, a filesystem error above all, prints its code and a fixed line: its message can
// hold a host path. So does a coded refusal whose text happens to hold an absolute path.
const ABSOLUTE_PATH = /(?:^|[\s('"=:])\/[^\s/]/;
function refusal(error) { function refusal(error) {
if (error instanceof CliError) return error; if (error instanceof CliError) return error;
const code = typeof error?.code === 'string' ? error.code : null; const code = typeof error?.code === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(error.code) ? error.code : null;
const ours = (error instanceof OrgError || error instanceof OrganizationError || error?.name === 'BusinessError') && code !== null;
const text = ours && typeof error.message === 'string' && !ABSOLUTE_PATH.test(error.message) ? error.message : 'the operation failed; the error text is not shown';
// A refusal after the replace says the change landed; the receipt may be missing. // A refusal after the replace says the change landed; the receipt may be missing.
const landed = error?.committed ? ' (the change was written; its receipt may be missing)' : ''; const landed = error?.committed ? ' (the change was written; its receipt may be missing)' : '';
return new CliError(`${code ? `${code}: ` : ''}${error?.message ?? String(error)}${landed}`, 2); return new CliError(`${code ? `${code}: ` : ''}${text}${landed}`, 2);
} }
export async function agentsRootCommand(args, io) { export async function agentsRootCommand(args, io) {
@@ -145,7 +157,7 @@ export async function projectAgentsCommand(args, io) {
if (name !== undefined) throw usage('list takes no name', line); if (name !== undefined) throw usage('list takes no name', line);
only(parsed, ['--org', '--json'], line); only(parsed, ['--org', '--json'], line);
const { document, revision } = writer.read(org); const { document, revision } = writer.read(org);
if (!Object.hasOwn(document.projects ?? {}, project)) throw Object.assign(new Error(`project ${project} is not in organization ${org}`), { code: 'project-not-found' }); if (!Object.hasOwn(document.projects ?? {}, project)) throw new OrgError('project-not-found', `project ${project} is not in organization ${org}`);
const listing = { organization: org, project, revision, agents: projectAgentSummary(document.projects[project].agents ?? {}) }; const listing = { organization: org, project, revision, agents: projectAgentSummary(document.projects[project].agents ?? {}) };
io.stdout.write(parsed.flags.has('--json') ? `${JSON.stringify(listing, null, 2)}\n` : formatProject(listing)); io.stdout.write(parsed.flags.has('--json') ? `${JSON.stringify(listing, null, 2)}\n` : formatProject(listing));
return; return;
+37 -1
View File
@@ -3,7 +3,7 @@
import { test } from 'node:test'; import { test } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { existsSync, mkdtempSync, readFileSync } from 'node:fs'; import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path'; import { join, resolve } from 'node:path';
import { tmpdir } from 'node:os'; import { tmpdir } from 'node:os';
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
@@ -69,6 +69,42 @@ test('agents root list, set, remove: each write prints its receipt, values stay
assert.equal(unknown.status, 4); assert.ok(!unknown.stderr.includes(SECRET)); assert.equal(unknown.status, 4); assert.ok(!unknown.stderr.includes(SECRET));
}); });
test('a filesystem failure prints its code and a fixed line, never a host path', () => {
const { run, configDir, home } = instance();
// A directory where the receipt file goes: opening it fails EISDIR, whose message holds the path.
mkdirSync(join(configDir, 'agents-receipts.jsonl'));
const r = run(['agents', 'root', 'set', 'researcher', '--definition', 'research']);
assert.equal(r.status, 2, r.stderr);
assert.match(r.stderr, /EISDIR: the operation failed; the error text is not shown/);
assert.ok(!r.stderr.includes(home), r.stderr);
assert.equal(existsSync(join(configDir, 'agents.json')), false);
});
test('a missing, malformed or unclaimed instance config refuses before anything is read or written', () => {
const verbs = [['agents', 'root', 'set', 'researcher', '--definition', 'research'], ['agents', 'root', 'list'], ['project', 'agents', 'work', '--org', 'alpha', 'exclude', 'coder']];
const check = (env, dir, why) => {
for (const args of verbs) {
const r = spawnSync(join(repo, 'scripts/mosaic'), args, { cwd: repo, env, encoding: 'utf8' });
assert.equal(r.status, 3, `${why} ${args.join(' ')}: ${r.stderr}`); assert.match(r.stderr, /system config problem/);
}
assert.equal(existsSync(join(dir, 'agents.json')), false, why);
assert.equal(existsSync(join(dir, 'agents-receipts.jsonl')), false, why);
};
// Missing: the instance's config directory exists, its config.json does not.
const home = mkdtempSync(join(tmpdir(), 'a2cfg-'));
const dir = join(home, '.config/mosaic-atwo');
mkdirSync(dir, { recursive: true, mode: 0o700 });
const env = { PATH: process.env.PATH, LANG: 'C.UTF-8', TMPDIR: process.env.TMPDIR ?? tmpdir(), HOME: home, MOSAIC_CONFIG: join(dir, 'config.json') };
check(env, dir, 'missing');
writeFileSync(join(dir, 'config.json'), '{', { mode: 0o600 });
check(env, dir, 'malformed');
// Unclaimed: a bootstrapped instance whose data root marker names another instance.
const booted = instance();
const { dataRoot } = JSON.parse(readFileSync(booted.env.MOSAIC_CONFIG, 'utf8'));
writeFileSync(join(dataRoot, 'instance.json'), JSON.stringify({ instanceVersion: 1, name: 'other' }));
check(booted.env, booted.configDir, 'marker');
});
test('the default instance refuses the agent level verbs', () => { test('the default instance refuses the agent level verbs', () => {
const home = mkdtempSync(join(tmpdir(), 'a2def-')); const home = mkdtempSync(join(tmpdir(), 'a2def-'));
const env = { PATH: process.env.PATH, LANG: 'C.UTF-8', TMPDIR: process.env.TMPDIR ?? tmpdir(), HOME: home }; const env = { PATH: process.env.PATH, LANG: 'C.UTF-8', TMPDIR: process.env.TMPDIR ?? tmpdir(), HOME: home };
@@ -38,15 +38,22 @@ export function requireRootOwner(actor, owner) {
fail('human-required', 'only the signed-in owner writes the root agent file'); fail('human-required', 'only the signed-in owner writes the root agent file');
} }
// Every ancestor a real directory, configDir this uid's and not group or other writable. // Every ancestor a real directory that only root or this uid can change: owned by one of them, and
// group or other writable only with the sticky bit (as /tmp is), so no other user can rename or
// replace configDir between these checks and the path-based lock, temp file and rename. configDir
// itself is this uid's and not group or other writable.
function assertConfigDir(configDir, uid) { function assertConfigDir(configDir, uid) {
if (typeof configDir !== 'string' || resolve(configDir) !== configDir) fail('agents-unsafe', 'config directory must be an absolute normalized path'); if (typeof configDir !== 'string' || resolve(configDir) !== configDir) fail('agents-unsafe', 'config directory must be an absolute normalized path');
let current = parse(configDir).root; let current = parse(configDir).root;
const trusted = st => (st.uid === 0 || st.uid === uid) && (!(st.mode & 0o022) || (st.mode & 0o1000));
try { if (!trusted(lstatSync(current))) fail('agents-unsafe', `a config directory ancestor must belong to root or uid ${uid} and not be writable by others without the sticky bit`); }
catch (error) { if (error instanceof OrgError) throw error; fail('agents-unsafe', 'config directory is missing'); }
for (const part of configDir.slice(current.length).split('/').filter(Boolean)) { for (const part of configDir.slice(current.length).split('/').filter(Boolean)) {
current = join(current, part); current = join(current, part);
let st; let st;
try { st = lstatSync(current); } catch { fail('agents-unsafe', 'config directory is missing'); } try { st = lstatSync(current); } catch { fail('agents-unsafe', 'config directory is missing'); }
if (!st.isDirectory() || st.isSymbolicLink()) fail('agents-unsafe', 'config path contains a symbolic link or non-directory'); if (!st.isDirectory() || st.isSymbolicLink()) fail('agents-unsafe', 'config path contains a symbolic link or non-directory');
if (current !== configDir && !trusted(st)) fail('agents-unsafe', `a config directory ancestor must belong to root or uid ${uid} and not be writable by others without the sticky bit`);
} }
const st = lstatSync(configDir); const st = lstatSync(configDir);
if (st.uid !== uid) fail('agents-unsafe', `config directory must belong to uid ${uid}`); if (st.uid !== uid) fail('agents-unsafe', `config directory must belong to uid ${uid}`);
@@ -55,7 +62,7 @@ function assertConfigDir(configDir, uid) {
// The reader's descriptor checks (loadRootAgents), plus one link: a regular file, no symbolic link, // The reader's descriptor checks (loadRootAgents), plus one link: a regular file, no symbolic link,
// this uid, no group or other write. Missing is an empty root level at ABSENT_REVISION. // this uid, no group or other write. Missing is an empty root level at ABSENT_REVISION.
async function readCurrent(configDir, uid) { async function readCurrent(configDir, uid, statFile = fd => fd.stat()) {
const file = rootAgentsPath(configDir); const file = rootAgentsPath(configDir);
let fd; let fd;
try { fd = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } try { fd = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
@@ -65,7 +72,7 @@ async function readCurrent(configDir, uid) {
} }
let bytes; let bytes;
try { try {
const st = await fd.stat(); const st = await statFile(fd);
if (!st.isFile()) fail('agents-unsafe', `root agent file must be a regular file, not a symbolic link (${ROOT_FILE})`); if (!st.isFile()) fail('agents-unsafe', `root agent file must be a regular file, not a symbolic link (${ROOT_FILE})`);
if (st.uid !== uid) fail('agents-unsafe', `root agent file must belong to uid ${uid} (${ROOT_FILE})`); if (st.uid !== uid) fail('agents-unsafe', `root agent file must belong to uid ${uid} (${ROOT_FILE})`);
if (st.mode & 0o022) fail('agents-unsafe', `root agent file must not be writable by group or other (${ROOT_FILE})`); if (st.mode & 0o022) fail('agents-unsafe', `root agent file must not be writable by group or other (${ROOT_FILE})`);
@@ -80,9 +87,10 @@ async function readCurrent(configDir, uid) {
// The file's document and revision, for a form or a CLI list. A file that is not a root agent // The file's document and revision, for a form or a CLI list. A file that is not a root agent
// document at all refuses; one with a bad entry reads, so the owner can fix or remove that entry. // document at all refuses; one with a bad entry reads, so the owner can fix or remove that entry.
export async function readRootAgentsFile(configDir, { uid = process.geteuid() } = {}) { // statFile is a test seam for the descriptor stat; it grants nothing a caller's uid does not.
export async function readRootAgentsFile(configDir, { uid = process.geteuid(), statFile } = {}) {
assertConfigDir(configDir, uid); assertConfigDir(configDir, uid);
const current = await readCurrent(configDir, uid); const current = await readCurrent(configDir, uid, statFile);
shape(current.document); shape(current.document);
return current; return current;
} }
@@ -172,7 +180,7 @@ async function syncDirectory(dir) {
// Change one root agent. `entry` is the new entry, null to remove it, or a function of the old // Change one root agent. `entry` is the new entry, null to remove it, or a function of the old
// entry (undefined when there is none) returning either. Returns the receipt. An error after the // entry (undefined when there is none) returning either. Returns the receipt. An error after the
// rename carries committed: true, so a caller never retries a write that landed. // rename carries committed: true, so a caller never retries a write that landed.
export async function changeRootAgent(configDir, { revision, name, entry }, { actor, owner, rolesDir, uid = process.geteuid(), beforeReplace, syncDirectory: syncDir = syncDirectory } = {}) { export async function changeRootAgent(configDir, { revision, name, entry }, { actor, owner, rolesDir, uid = process.geteuid(), beforeReplace, statFile, syncDirectory: syncDir = syncDirectory } = {}) {
requireRootOwner(actor, owner); requireRootOwner(actor, owner);
if (typeof name !== 'string' || !ID_PATTERN.test(name)) fail('agents-invalid', 'agent name must be an id: lowercase letters, digits, dot, dash or underscore, at most 64'); if (typeof name !== 'string' || !ID_PATTERN.test(name)) fail('agents-invalid', 'agent name must be an id: lowercase letters, digits, dot, dash or underscore, at most 64');
if (typeof revision !== 'string' || !REVISION.test(revision)) fail('revision-conflict', 'a root agent change needs the revision it was read at'); if (typeof revision !== 'string' || !REVISION.test(revision)) fail('revision-conflict', 'a root agent change needs the revision it was read at');
@@ -188,7 +196,7 @@ export async function changeRootAgent(configDir, { revision, name, entry }, { ac
let temp, receiptFd, committed = false; let temp, receiptFd, committed = false;
try { try {
assertConfigDir(configDir, uid); assertConfigDir(configDir, uid);
const before = await readCurrent(configDir, uid); const before = await readCurrent(configDir, uid, statFile);
if (before.revision !== revision) fail('revision-conflict', 'the root agent file changed since it was read; read it again'); if (before.revision !== revision) fail('revision-conflict', 'the root agent file changed since it was read; read it again');
shape(before.document); shape(before.document);
const old = Object.hasOwn(before.document.agents, name) ? before.document.agents[name] : undefined; const old = Object.hasOwn(before.document.agents, name) ? before.document.agents[name] : undefined;
@@ -219,7 +227,7 @@ export async function changeRootAgent(configDir, { revision, name, entry }, { ac
try { await fd.writeFile(bytes); await fd.sync(); } finally { await fd.close(); } try { await fd.writeFile(bytes); await fd.sync(); } finally { await fd.close(); }
await beforeReplace?.(); await beforeReplace?.();
// A writer that ignores the lock still loses: the bytes must be the ones read. // A writer that ignores the lock still loses: the bytes must be the ones read.
const again = await readCurrent(configDir, uid); const again = await readCurrent(configDir, uid, statFile);
if (again.exists !== before.exists || again.revision !== before.revision) fail('revision-conflict', 'the root agent file changed before the write; read it again'); if (again.exists !== before.exists || again.revision !== before.revision) fail('revision-conflict', 'the root agent file changed before the write; read it again');
// A new file is published with link, which fails rather than replace a file made meanwhile. // A new file is published with link, which fails rather than replace a file made meanwhile.
if (before.exists) await fs.rename(temp, file); if (before.exists) await fs.rename(temp, file);
@@ -4,10 +4,10 @@
import test from "node:test"; import test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from "node:fs"; import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path"; import { dirname, join } from "node:path";
import { loadRootAgents } from "../src/agent-levels.mjs"; import { loadRootAgents } from "../src/agent-levels.mjs";
import { import {
ABSENT_REVISION, ROOT_RECEIPTS, changeRootAgent, patchRootEntry, projectAgentProblem, readRootAgentsFile, rootAgentSummary, ABSENT_REVISION, ROOT_LOCK, ROOT_RECEIPTS, changeRootAgent, patchRootEntry, projectAgentProblem, readRootAgentsFile, rootAgentSummary,
} from "../src/agent-levels-write.mjs"; } from "../src/agent-levels-write.mjs";
import * as oldPath from "../../business/src/agent-levels-write.mjs"; import * as oldPath from "../../business/src/agent-levels-write.mjs";
import { organizationWriter } from "../src/organization.mjs"; import { organizationWriter } from "../src/organization.mjs";
@@ -138,14 +138,35 @@ test("root writer: a symbolic link, a group-writable file and a foreign uid refu
linkSync(file(dir), join(dir, "alias.json")); linkSync(file(dir), join(dir, "alias.json"));
await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, as()), refuses("agents-unsafe", e => /one link/.test(e.message))); await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, as()), refuses("agents-unsafe", e => /one link/.test(e.message)));
unlinkSync(join(dir, "alias.json")); unlinkSync(join(dir, "alias.json"));
// Not this process's uid: the config directory's owner check refuses first, the file's after it. // Not this process's uid: the directory checks refuse first (an ancestor this uid owns is foreign).
await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, { ...as(), uid: process.geteuid() + 1 }), refuses("agents-unsafe", e => /uid/.test(e.message))); await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, { ...as(), uid: process.geteuid() + 1 }), refuses("agents-unsafe", e => /config directory/.test(e.message) && !/root agent file/.test(e.message)));
await assert.rejects(readRootAgentsFile(dir, { uid: process.geteuid() + 1 }), refuses("agents-unsafe", e => /uid/.test(e.message))); await assert.rejects(readRootAgentsFile(dir, { uid: process.geteuid() + 1 }), refuses("agents-unsafe", e => /config directory/.test(e.message) && !/root agent file/.test(e.message)));
assert.equal(bytes(dir), original); assert.equal(bytes(dir), original);
// A file another uid owns, in a directory that is this uid's: the file's own owner check refuses.
// Changing a file's owner needs root, so the descriptor stat reports a foreign uid through the seam.
const foreign = async fd => { const st = await fd.stat(); return Object.assign(Object.create(Object.getPrototypeOf(st)), st, { uid: st.uid + 1 }); };
const receiptsBefore = existsSync(join(dir, ROOT_RECEIPTS)) ? readFileSync(join(dir, ROOT_RECEIPTS), "utf8") : null;
await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, { ...as(), statFile: foreign }), refuses("agents-unsafe", e => /root agent file must belong to uid/.test(e.message)));
await assert.rejects(readRootAgentsFile(dir, { statFile: foreign }), refuses("agents-unsafe", e => /root agent file must belong to uid/.test(e.message)));
assert.equal(bytes(dir), original);
assert.equal(lstatSync(file(dir)).mode & 0o777, 0o600);
assert.equal(existsSync(join(dir, ROOT_RECEIPTS)) ? readFileSync(join(dir, ROOT_RECEIPTS), "utf8") : null, receiptsBefore);
assert.equal(existsSync(join(dir, ROOT_LOCK)), false, "the lock is released");
// A group-writable config directory refuses before any lock or read. // A group-writable config directory refuses before any lock or read.
chmodSync(dir, 0o770); chmodSync(dir, 0o770);
await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, as()), refuses("agents-unsafe", e => /config directory/.test(e.message))); await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, as()), refuses("agents-unsafe", e => /config directory/.test(e.message)));
chmodSync(dir, 0o700); chmodSync(dir, 0o700);
// An ancestor another user can write without the sticky bit refuses: that user could rename the
// config directory between the checks and the write. With the sticky bit, as /tmp has, it can't.
const parent = dirname(dir);
const mode = lstatSync(parent).mode & 0o7777;
chmodSync(parent, 0o777);
try {
await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, as()), refuses("agents-unsafe", e => /ancestor/.test(e.message) && !e.message.includes(dir)));
await assert.rejects(readRootAgentsFile(dir), refuses("agents-unsafe", e => /ancestor/.test(e.message)));
chmodSync(parent, 0o1777);
assert.equal((await readRootAgentsFile(dir)).revision, revision);
} finally { chmodSync(parent, mode); }
assert.equal(bytes(dir), original); assert.equal(bytes(dir), original);
assert.equal(receipts(dir).length, 1); assert.equal(receipts(dir).length, 1);
assert.equal(existsSync(join(dir, "agents.lock")), false); assert.equal(existsSync(join(dir, "agents.lock")), false);
@@ -206,11 +227,9 @@ test("root writer: a held lock refuses agents-locked", async () => {
}); });
// The project-agent verb: the organization file's projects.<p>.agents, one entry per call. // The project-agent verb: the organization file's projects.<p>.agents, one entry per call.
function org(t, mutate = () => {}) { function org(mutate = () => {}) {
const root = tmp(); const root = tmp();
const doc = businessDoc(root); const doc = businessDoc(root);
doc.projects.notes = { kind: "library", root: join(root, "notes"), mapping: undefined };
delete doc.projects.notes;
mutate(doc); mutate(doc);
const dir = join(root, "config"); const dir = join(root, "config");
const orgFile = writeJson(join(dir, "businesses/acme.json"), doc); const orgFile = writeJson(join(dir, "businesses/acme.json"), doc);
@@ -266,13 +285,18 @@ test("project verb: a narrow that widens refuses, and refusals never quote a val
test("project verb: the chief and the assistant refuse", () => { test("project verb: the chief and the assistant refuse", () => {
const { writer, orgFile } = org(doc => { doc.roles.assistant = { definition: "assistant" }; }); const { writer, orgFile } = org(doc => { doc.roles.assistant = { definition: "assistant" }; });
const { revision } = writer.read("acme"); const { document, revision } = writer.read("acme");
assert.equal(document.roles.assistant.definition, "assistant", "the fixture has an organization assistant");
assert.equal(document.roles.chief.definition, "chief-of-staff", "the fixture has a chief");
const before = readFileSync(orgFile, "utf8"); const before = readFileSync(orgFile, "utf8");
for (const [name, entry] of [ const protectedAgent = /a project can't change the organization's (chief-of-staff|assistant)/;
["chief", { exclude: true }], ["chief", { vars: { "limits.network": "none" } }], ["chief", { definition: "reviewer" }], const notProjectAgent = /can't be a project agent/;
["assistant", { exclude: true }], ["helper", { definition: "chief-of-staff" }], ["helper", { definition: "assistant" }], for (const [name, entry, reason] of [
["chief", { exclude: true }, protectedAgent], ["chief", { vars: { "limits.network": "none" } }, protectedAgent], ["chief", { definition: "reviewer" }, protectedAgent],
["assistant", { exclude: true }, protectedAgent], ["assistant", { vars: { "limits.network": "none" } }, protectedAgent], ["assistant", { definition: "reviewer" }, protectedAgent],
["helper", { definition: "chief-of-staff" }, notProjectAgent], ["helper", { definition: "assistant" }, notProjectAgent],
]) { ]) {
assert.throws(() => writer.setProjectAgent("acme", { revision, project: "stack", name, entry }, "jason"), e => e.code === "project-agents-invalid", `${name} ${JSON.stringify(entry)}`); assert.throws(() => writer.setProjectAgent("acme", { revision, project: "stack", name, entry }, "jason"), e => e.code === "project-agents-invalid" && reason.test(e.message), `${name} ${JSON.stringify(entry)}`);
} }
assert.equal(readFileSync(orgFile, "utf8"), before); assert.equal(readFileSync(orgFile, "utf8"), before);
}); });
+8 -2
View File
@@ -21,6 +21,7 @@
// A response or trail entry names agents, keys and revisions, never a var value or a host path. // A response or trail entry names agents, keys and revisions, never a var value or a host path.
import { organizationWriter } from '../../organization/src/organization.mjs'; import { organizationWriter } from '../../organization/src/organization.mjs';
import { changeRootAgent, patchRootEntry, projectAgentSummary, readRootAgentsFile, rootAgentSummary } from '../../organization/src/agent-levels-write.mjs'; import { changeRootAgent, patchRootEntry, projectAgentSummary, readRootAgentsFile, rootAgentSummary } from '../../organization/src/agent-levels-write.mjs';
import { ID_PATTERN } from '../../organization/src/vocabulary.mjs';
import { actor } from './action-trail.mjs'; import { actor } from './action-trail.mjs';
export const ROOT_ROUTE = '/api/agents/root'; export const ROOT_ROUTE = '/api/agents/root';
@@ -28,7 +29,10 @@ export const PROJECT_ROUTE = /^\/api\/orgs\/([^/]+)\/agent-levels\/projects\/([^
// routeTable takes GET and POST only; any other method never reaches these hooks (serve.mjs answers it). // routeTable takes GET and POST only; any other method never reaches these hooks (serve.mjs answers it).
const METHODS = ['GET', 'POST']; const METHODS = ['GET', 'POST'];
const REVISION = /^[a-f0-9]{64}$/; const REVISION = /^[a-f0-9]{64}$/;
const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/; // Agent and project names are the writers' ids (requireId): checked here so a bad one is a 400
// naming the field, not a writer error the Console can't classify.
const NAME = ID_PATTERN;
const NAME_RULE = 'lowercase letters, digits, dot, dash or underscore, at most 64';
const LIMIT = 4096; const LIMIT = 4096;
const ROOT_PATCH = ['definition', 'vars', 'excludeOrgs']; const ROOT_PATCH = ['definition', 'vars', 'excludeOrgs'];
const PROJECT_ENTRY = ['definition', 'vars', 'exclude']; const PROJECT_ENTRY = ['definition', 'vars', 'exclude'];
@@ -86,7 +90,8 @@ async function body(req) {
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return null; } try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return null; }
const keys = ['revision', 'name', 'entry']; const keys = ['revision', 'name', 'entry'];
if (!plain(value) || Object.keys(value).length !== keys.length || !keys.every(k => Object.hasOwn(value, k))) return null; if (!plain(value) || Object.keys(value).length !== keys.length || !keys.every(k => Object.hasOwn(value, k))) return null;
if (typeof value.revision !== 'string' || !REVISION.test(value.revision) || typeof value.name !== 'string' || !NAME.test(value.name)) return null; if (typeof value.revision !== 'string' || !REVISION.test(value.revision) || typeof value.name !== 'string') return null;
if (!NAME.test(value.name)) return 'bad-name';
return value; return value;
} }
const only = (entry, keys) => plain(entry) && Object.keys(entry).length > 0 && Object.keys(entry).every(k => keys.includes(k)); const only = (entry, keys) => plain(entry) && Object.keys(entry).length > 0 && Object.keys(entry).every(k => keys.includes(k));
@@ -107,6 +112,7 @@ export function agentLevelsWriteRoutes({ configDir, rolesDir, trail = null, log
if (!send) { json(res, 403, { error: 'read-only', message: 'this Console was started without writes' }); return null; } if (!send) { json(res, 403, { error: 'read-only', message: 'this Console was started without writes' }); return null; }
const value = await body(req); const value = await body(req);
if (value === 'too-large') { json(res, 413, { error: 'invalid-request', message: `a change is at most ${LIMIT} bytes` }); return null; } if (value === 'too-large') { json(res, 413, { error: 'invalid-request', message: `a change is at most ${LIMIT} bytes` }); return null; }
if (value === 'bad-name') { json(res, 400, { error: 'invalid-request', message: `name must be an id: ${NAME_RULE}` }); return null; }
if (!value) { json(res, 400, { error: 'invalid-request', message: 'this takes revision, name and entry, nothing else' }); return null; } if (!value) { json(res, 400, { error: 'invalid-request', message: 'this takes revision, name and entry, nothing else' }); return null; }
return value; return value;
} }
+42 -15
View File
@@ -247,6 +247,11 @@
const UNKNOWN = 'Outcome unknown. Nothing was retried. The grid below was read again.'; const UNKNOWN = 'Outcome unknown. Nothing was retried. The grid below was read again.';
let root = null, levels = null, project = null, selected = { org: '', project: '' }; let root = null, levels = null, project = null, selected = { org: '', project: '' };
let receipts = { root: '', project: '' }, busy = false, confirming = null; let receipts = { root: '', project: '' }, busy = false, confirming = null;
// What each form holds, kept here so a polling render, a picker change or the other form's save
// repaints it as typed. A draft keeps the revision it began at, so a save sends that and a file
// changed meanwhile refuses rather than being overwritten unseen. The project draft belongs to its
// organization and project. Only the submitted form's own success clears it.
const drafts = { root: null, project: null };
const read = url => fetch(url, { cache: 'no-store', redirect: 'manual' }).then(async r => { const read = url => fetch(url, { cache: 'no-store', redirect: 'manual' }).then(async r => {
if (r.type === 'opaqueredirect') return { signedOut: true }; if (r.type === 'opaqueredirect') return { signedOut: true };
@@ -308,14 +313,22 @@
return `<p role="status" id="agent-levels-${which}-receipt" class="${text.startsWith('Saved') || text.startsWith('Removed') ? 'settings-success' : text ? 'banner err' : ''}">${esc(text)}</p>`; return `<p role="status" id="agent-levels-${which}-receipt" class="${text.startsWith('Saved') || text.startsWith('Removed') ? 'settings-success' : text ? 'banner err' : ''}">${esc(text)}</p>`;
}; };
const projectDraft = () => drafts.project && drafts.project.org === selected.org && drafts.project.project === selected.project ? drafts.project : null;
const shownDraft = which => which === 'root' ? drafts.root : projectDraft();
const field = (which, key) => esc(shownDraft(which)?.values?.[key] ?? '');
const filled = d => !!d && Object.entries(d.values).some(([k, v]) => k !== 'form' && String(v).trim());
function markup() { function markup() {
if (!levels || levels.refused || levels.signedOut) return ''; if (!levels || levels.refused || levels.signedOut) return '';
const off = !writable() || busy ? ' disabled' : ''; const off = !writable() || busy ? ' disabled' : '';
const at = (which, current) => esc(shownDraft(which)?.revision ?? current);
const key = (which, name) => ` data-focus-key="level-${which}-${name}"`;
const chosen = v => (projectDraft()?.values?.form ?? 'define') === v ? ' selected' : '';
const readOnly = writable() ? '' : '<p class="small">This Console was started without writes, so these levels are read only here. <code>mosaic agents root</code> and <code>mosaic project agents</code> change them from a terminal.</p>'; const readOnly = writable() ? '' : '<p class="small">This Console was started without writes, so these levels are read only here. <code>mosaic agents root</code> and <code>mosaic project agents</code> change them from a terminal.</p>';
const rootForm = writable() && root && !root.refused ? `<form id="agent-levels-root-form" class="instance-form" data-revision="${esc(root.revision)}"><h4>Add or change a root agent</h4><div class="filters"><label>Name <input name="name" maxlength="64" required autocomplete="off"${off}></label><label>Definition <input name="definition" maxlength="64" autocomplete="off" placeholder="Unchanged"${off}></label><label>Model <input name="model" maxlength="200" autocomplete="off" placeholder="Unchanged"${off}></label></div><div class="filters"><label>Other variables, one KEY=VALUE per line <textarea name="vars" rows="2"${off}></textarea></label><label>Remove variables, comma separated <input name="unset" autocomplete="off"${off}></label><label>Not in organizations, comma separated, or none <input name="excludeOrgs" autocomplete="off" placeholder="Unchanged"${off}></label></div><div class="settings-actions"><button type="submit"${off}>Save root agent</button></div></form>` : ''; const rootForm = writable() && root && !root.refused ? `<form id="agent-levels-root-form" class="level-form" data-revision="${at('root', root.revision)}"><h4>Add or change a root agent</h4><div class="filters"><label>Name <input name="name" maxlength="64" required autocomplete="off" value="${field('root', 'name')}"${key('root', 'name')}${off}></label><label>Definition <input name="definition" maxlength="64" autocomplete="off" placeholder="Unchanged" value="${field('root', 'definition')}"${key('root', 'definition')}${off}></label><label>Model <input name="model" maxlength="200" autocomplete="off" placeholder="Unchanged" value="${field('root', 'model')}"${key('root', 'model')}${off}></label></div><div class="filters"><label>Other variables, one KEY=VALUE per line <textarea name="vars" rows="2"${key('root', 'vars')}${off}>${field('root', 'vars')}</textarea></label><label>Remove variables, comma separated <input name="unset" autocomplete="off" value="${field('root', 'unset')}"${key('root', 'unset')}${off}></label><label>Not in organizations, comma separated, or none <input name="excludeOrgs" autocomplete="off" placeholder="Unchanged" value="${field('root', 'excludeOrgs')}"${key('root', 'excludeOrgs')}${off}></label></div><div class="settings-actions${filled(drafts.root) ? ' has-draft' : ''}"><button type="submit"${off}>Save root agent</button></div></form>` : '';
const orgs = orgsOf(), projects = orgs.find(o => o.id === selected.org)?.projects ?? []; const orgs = orgsOf(), projects = orgs.find(o => o.id === selected.org)?.projects ?? [];
const pick = `<div class="filters"><label>Organization <select id="agent-levels-org"${busy ? ' disabled' : ''}>${orgs.map(o => `<option value="${esc(o.id)}"${o.id === selected.org ? ' selected' : ''}>${esc(o.id)}</option>`).join('')}</select></label><label>Project <select id="agent-levels-project"${busy ? ' disabled' : ''}>${projects.map(p => `<option value="${esc(p)}"${p === selected.project ? ' selected' : ''}>${esc(p)}</option>`).join('')}</select></label></div>`; const pick = `<div class="filters"><label>Organization <select id="agent-levels-org"${busy ? ' disabled' : ''}>${orgs.map(o => `<option value="${esc(o.id)}"${o.id === selected.org ? ' selected' : ''}>${esc(o.id)}</option>`).join('')}</select></label><label>Project <select id="agent-levels-project"${busy ? ' disabled' : ''}>${projects.map(p => `<option value="${esc(p)}"${p === selected.project ? ' selected' : ''}>${esc(p)}</option>`).join('')}</select></label></div>`;
const projectForm = writable() && project && !project.refused && !project.library ? `<form id="agent-levels-project-form" class="instance-form" data-revision="${esc(project.revision)}"><h4>Add or change a project entry</h4><div class="filters"><label>Agent <input name="name" maxlength="64" required autocomplete="off"${off}></label><label>Entry <select name="form"${off}><option value="define">Define a project agent</option><option value="narrow">Narrow an inherited agent</option><option value="exclude">Exclude an inherited agent</option></select></label><label>Definition, for a defined agent <input name="definition" maxlength="64" autocomplete="off"${off}></label></div><label>Variables, one KEY=VALUE per line. A narrow takes limits.tools, limits.network and limits.authority only. <textarea name="vars" rows="2"${off}></textarea></label><div class="settings-actions"><button type="submit"${off}>Save project entry</button></div></form>` : ''; const projectForm = writable() && project && !project.refused && !project.library ? `<form id="agent-levels-project-form" class="level-form" data-revision="${at('project', project.revision)}"><h4>Add or change a project entry</h4><div class="filters"><label>Agent <input name="name" maxlength="64" required autocomplete="off" value="${field('project', 'name')}"${key('project', 'name')}${off}></label><label>Entry <select name="form"${key('project', 'form')}${off}><option value="define"${chosen('define')}>Define a project agent</option><option value="narrow"${chosen('narrow')}>Narrow an inherited agent</option><option value="exclude"${chosen('exclude')}>Exclude an inherited agent</option></select></label><label>Definition, for a defined agent <input name="definition" maxlength="64" autocomplete="off" value="${field('project', 'definition')}"${key('project', 'definition')}${off}></label></div><label>Variables, one KEY=VALUE per line. A narrow takes limits.tools, limits.network and limits.authority only. <textarea name="vars" rows="2"${key('project', 'vars')}${off}>${field('project', 'vars')}</textarea></label><div class="settings-actions${filled(projectDraft()) ? ' has-draft' : ''}"><button type="submit"${off}>Save project entry</button></div></form>` : '';
return `<div id="agent-levels-edit" data-agent-levels-edit><section class="panel" aria-labelledby="agent-levels-root-title"><h3 id="agent-levels-root-title">Root agents</h3><p>Root agents are in every organization unless a row excludes it. They are read from the instance's root agent file and are not launched yet.</p>${readOnly}${rootGrid()}${receiptLine('root')}${rootForm}</section><section class="panel" aria-labelledby="agent-levels-project-title"><h3 id="agent-levels-project-title">Project agents</h3><p>A project can define its own agents, narrow an inherited agent's limits, or exclude one. Project agents are not launched yet.</p>${orgs.length ? pick : '<p class="muted">No organization to show.</p>'}${orgs.length ? projectGrid() : ''}${receiptLine('project')}${projectForm}</section></div>`; return `<div id="agent-levels-edit" data-agent-levels-edit><section class="panel" aria-labelledby="agent-levels-root-title"><h3 id="agent-levels-root-title">Root agents</h3><p>Root agents are in every organization unless a row excludes it. They are read from the instance's root agent file and are not launched yet.</p>${readOnly}${rootGrid()}${receiptLine('root')}${rootForm}</section><section class="panel" aria-labelledby="agent-levels-project-title"><h3 id="agent-levels-project-title">Project agents</h3><p>A project can define its own agents, narrow an inherited agent's limits, or exclude one. Project agents are not launched yet.</p>${orgs.length ? pick : '<p class="muted">No organization to show.</p>'}${orgs.length ? projectGrid() : ''}${receiptLine('project')}${projectForm}</section></div>`;
} }
const repaint = () => { const box = $('agent-levels-edit'); if (box) box.outerHTML = markup(); }; const repaint = () => { const box = $('agent-levels-edit'); if (box) box.outerHTML = markup(); };
@@ -334,9 +347,8 @@
const refusedText = body => body?.error === 'revision-conflict' ? 'Refused: the file changed since this page read it. The grid below was read again; check it and save again.' const refusedText = body => body?.error === 'revision-conflict' ? 'Refused: the file changed since this page read it. The grid below was read again; check it and save again.'
: typeof body?.message === 'string' ? `Refused (${body.error}): ${body.message}` : UNKNOWN; : typeof body?.message === 'string' ? `Refused (${body.error}): ${body.message}` : UNKNOWN;
async function write(which, url, payload, done, focus) { // fromForm: the submitted form's draft is cleared on success. A row's Remove leaves it alone.
// The busy repaint below replaces the form, so what was typed is taken first. async function write(which, url, payload, done, focus, fromForm = false) {
const typed = draft(which);
busy = true; receipts[which] = ''; repaint(); busy = true; receipts[which] = ''; repaint();
let answer; let answer;
try { answer = await post(url, payload); } catch { answer = null; } try { answer = await post(url, payload); } catch { answer = null; }
@@ -344,16 +356,25 @@
if (answer?.signedOut) { receipts[which] = 'Sign in again, then retry.'; repaint(); return false; } if (answer?.signedOut) { receipts[which] = 'Sign in again, then retry.'; repaint(); return false; }
const ok = answer?.ok && answer.body?.outcome === 'done'; const ok = answer?.ok && answer.body?.outcome === 'done';
receipts[which] = ok ? done(answer.body.receipt) : answer ? refusedText(answer.body) : UNKNOWN; receipts[which] = ok ? done(answer.body.receipt) : answer ? refusedText(answer.body) : UNKNOWN;
const kept = ok ? null : typed; const conflict = answer?.body?.error === 'revision-conflict';
await load(); await load();
if (ok && fromForm) drafts[which] = null;
// After a conflict the grid is read again and the receipt asks for a check: the next save is a
// deliberate one against what is shown now.
if (conflict && fromForm && shownDraft(which)) shownDraft(which).revision = which === 'root' ? root?.revision : project?.revision;
repaint(); repaint();
if (kept) restore(which, kept);
(focus && $(focus))?.focus?.(); (focus && $(focus))?.focus?.();
return ok; return ok;
} }
// A refused form keeps what was typed. // Take what a form holds into its draft, keeping the revision the draft began at.
const draft = which => { const form = $(`agent-levels-${which}-form`); return form ? Object.fromEntries(new FormData(form)) : null; }; function capture(form) {
const restore = (which, values) => { const form = $(`agent-levels-${which}-form`); if (form) for (const [k, v] of Object.entries(values)) if (form.elements[k]) form.elements[k].value = v; }; const which = form.id === 'agent-levels-root-form' ? 'root' : 'project';
const values = Object.fromEntries(new FormData(form));
const old = shownDraft(which);
drafts[which] = { ...(which === 'project' ? { org: selected.org, project: selected.project } : {}), revision: old?.revision ?? form.dataset.revision, values };
form.querySelector('.settings-actions')?.classList.toggle('has-draft', filled(drafts[which]));
return which;
}
async function saveRoot(form) { async function saveRoot(form) {
const f = Object.fromEntries(new FormData(form)); const f = Object.fromEntries(new FormData(form));
@@ -367,9 +388,9 @@
if (String(f.excludeOrgs ?? '').trim()) entry.excludeOrgs = String(f.excludeOrgs).trim() === 'none' ? [] : list(f.excludeOrgs); if (String(f.excludeOrgs ?? '').trim()) entry.excludeOrgs = String(f.excludeOrgs).trim() === 'none' ? [] : list(f.excludeOrgs);
if (!name) throw new Error('A root agent needs a name.'); if (!name) throw new Error('A root agent needs a name.');
if (!Object.keys(entry).length) throw new Error('Nothing to change: give a definition, a variable or the organizations it is not in.'); if (!Object.keys(entry).length) throw new Error('Nothing to change: give a definition, a variable or the organizations it is not in.');
} catch (error) { receipts.root = error.message; const kept = draft('root'); repaint(); restore('root', kept); return; } } catch (error) { receipts.root = error.message; capture(form); repaint(); return; }
await write('root', '/api/agents/root', { revision: form.dataset.revision, name, entry }, await write('root', '/api/agents/root', { revision: form.dataset.revision, name, entry },
r => `Saved ${r.agent} at ${clock()}: ${r.changed.join(', ')}.`, 'agent-levels-root-title'); r => `Saved ${r.agent} at ${clock()}: ${r.changed.join(', ')}.`, 'agent-levels-root-title', true);
} }
async function saveProject(form) { async function saveProject(form) {
@@ -382,9 +403,9 @@
if (f.form === 'exclude') { if (Object.keys(vars).length || String(f.definition ?? '').trim()) throw new Error('An exclude takes no definition and no variables.'); entry = { exclude: true }; } if (f.form === 'exclude') { if (Object.keys(vars).length || String(f.definition ?? '').trim()) throw new Error('An exclude takes no definition and no variables.'); entry = { exclude: true }; }
else if (f.form === 'narrow') { if (String(f.definition ?? '').trim()) throw new Error('A narrow takes no definition.'); if (!Object.keys(vars).length) throw new Error('A narrow needs at least one variable.'); entry = { vars }; } else if (f.form === 'narrow') { if (String(f.definition ?? '').trim()) throw new Error('A narrow takes no definition.'); if (!Object.keys(vars).length) throw new Error('A narrow needs at least one variable.'); entry = { vars }; }
else { if (!String(f.definition ?? '').trim()) throw new Error('A defined agent needs a definition.'); entry = { definition: String(f.definition).trim(), ...(Object.keys(vars).length ? { vars } : {}) }; } else { if (!String(f.definition ?? '').trim()) throw new Error('A defined agent needs a definition.'); entry = { definition: String(f.definition).trim(), ...(Object.keys(vars).length ? { vars } : {}) }; }
} catch (error) { receipts.project = error.message; const kept = draft('project'); repaint(); restore('project', kept); return; } } catch (error) { receipts.project = error.message; capture(form); repaint(); return; }
await write('project', `/api/orgs/${enc(selected.org)}/agent-levels/projects/${enc(selected.project)}`, { revision: form.dataset.revision, name, entry }, await write('project', `/api/orgs/${enc(selected.org)}/agent-levels/projects/${enc(selected.project)}`, { revision: form.dataset.revision, name, entry },
r => `Saved ${r.agent} in ${r.project} at ${clock()}: ${r.form}.`, 'agent-levels-project-title'); r => `Saved ${r.agent} in ${r.project} at ${clock()}: ${r.form}.`, 'agent-levels-project-title', true);
} }
async function remove(which, name) { async function remove(which, name) {
@@ -398,8 +419,13 @@
if (form.id !== 'agent-levels-root-form' && form.id !== 'agent-levels-project-form') return; if (form.id !== 'agent-levels-root-form' && form.id !== 'agent-levels-project-form') return;
e.preventDefault(); e.preventDefault();
if (busy) return; if (busy) return;
capture(form);
(form.id === 'agent-levels-root-form' ? saveRoot : saveProject)(form); (form.id === 'agent-levels-root-form' ? saveRoot : saveProject)(form);
}); });
for (const kind of ['input', 'change']) document.addEventListener(kind, e => {
const form = e.target?.closest?.('.level-form');
if (form && e.target !== form) capture(form);
});
document.addEventListener('click', e => { document.addEventListener('click', e => {
const button = e.target.closest?.('[data-level-remove]'); const button = e.target.closest?.('[data-level-remove]');
if (!button || button.disabled || busy || !writable()) return; if (!button || button.disabled || busy || !writable()) return;
@@ -414,5 +440,6 @@
await load(); repaint(); $(id)?.focus(); await load(); repaint(); $(id)?.focus();
}); });
window.MosaicAgentLevels = Object.freeze({ section, hasDraft: () => [...document.querySelectorAll('#agent-levels-edit form')].some(f => [...f.elements].some(el => (el.tagName === 'TEXTAREA' || el.type === 'text' || el.tagName === 'INPUT') && el.type !== 'hidden' && el.value?.trim())) }); // hasDraft feeds the Settings nav's unsaved-changes dot (bus.js settingsShell and its input listener).
window.MosaicAgentLevels = Object.freeze({ section, hasDraft: () => filled(drafts.root) || filled(drafts.project) });
})(); })();
+3 -1
View File
@@ -1047,6 +1047,8 @@
const unknownInstance='Outcome unknown. Read the role instances again before trying. Draft kept.'; const unknownInstance='Outcome unknown. Read the role instances again before trying. Draft kept.';
// The answer replaces the view the next render draws, so it must have the read's whole shape. // The answer replaces the view the next render draws, so it must have the read's whole shape.
const instanceAnswer=r=>/^[a-f0-9]{64}$/.test(r?.revision??'')&&typeof r.restart==='boolean'&&[r.instances,r.definitions].every(o=>o&&typeof o==='object'&&!Array.isArray(o)); const instanceAnswer=r=>/^[a-f0-9]{64}$/.test(r?.revision??'')&&typeof r.restart==='boolean'&&[r.instances,r.definitions].every(o=>o&&typeof o==='object'&&!Array.isArray(o));
// #1873 A2: the level forms keep their own drafts (agents.js); here they only mark the nav.
for(const kind of ['input','change'])document.addEventListener(kind,e=>{if(e.target?.closest?.('.level-form'))markSettingsDraft('agents',!!window.MosaicAgentLevels?.hasDraft());});
for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('.instance-form');if(form){instanceDrafts[form.dataset.op]=instanceFields(form);markSettingsDraft('agents',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=form.querySelector('[data-instance-discard]');if(discard)discard.hidden=false;}}); for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('.instance-form');if(form){instanceDrafts[form.dataset.op]=instanceFields(form);markSettingsDraft('agents',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=form.querySelector('[data-instance-discard]');if(discard)discard.hidden=false;}});
document.addEventListener('click',e=>{if(e.target.id!=='instances-reload' && e.target.dataset?.instanceDiscard===undefined)return;instanceDrafts={add:null,change:null};instanceView=null;instanceReceipt='';instanceReceipts=Object.create(null);instanceReceiptOp=null;last.delete('instances');render(true);}); document.addEventListener('click',e=>{if(e.target.id!=='instances-reload' && e.target.dataset?.instanceDiscard===undefined)return;instanceDrafts={add:null,change:null};instanceView=null;instanceReceipt='';instanceReceipts=Object.create(null);instanceReceiptOp=null;last.delete('instances');render(true);});
document.addEventListener('submit',async e=>{ document.addEventListener('submit',async e=>{
@@ -1200,7 +1202,7 @@
function settingsShell(page, body, helper='') { function settingsShell(page, body, helper='') {
const pages=isTester ? [['appearance','Appearance'],['business','Business'],['routing','Routing'],['agents','Agents'],['names','Seat names']] : settingsPages; const pages=isTester ? [['appearance','Appearance'],['business','Business'],['routing','Routing'],['agents','Agents'],['names','Seat names']] : settingsPages;
const label=pages.find(([id])=>id===page)?.[1] || 'Appearance'; const label=pages.find(([id])=>id===page)?.[1] || 'Appearance';
const isDirty=id=>(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change)); const isDirty=id=>(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change||window.MosaicAgentLevels?.hasDraft()));
const dot='<span class="settings-dot"><span class="sr-only">unsaved changes</span></span>'; const dot='<span class="settings-dot"><span class="sr-only">unsaved changes</span></span>';
const links=pages.map(([id,name],i)=>`${i===0?'<div class="settings-group">Your browser</div>':i===1?'<div class="settings-group">This instance</div>':''}<a href="#/settings/${id}"${id===page?' aria-current="page"':''}>${name}${isDirty(id)?dot:''}</a>`).join('') + (!isTester ? '<div class="settings-group">Members and invites <span class="muted">not built</span></div>' : ''); const links=pages.map(([id,name],i)=>`${i===0?'<div class="settings-group">Your browser</div>':i===1?'<div class="settings-group">This instance</div>':''}<a href="#/settings/${id}"${id===page?' aria-current="page"':''}>${name}${isDirty(id)?dot:''}</a>`).join('') + (!isTester ? '<div class="settings-group">Members and invites <span class="muted">not built</span></div>' : '');
return `${head('Settings','Your browser and this instance.')}<div class="settings-layout"><div><button type="button" id="settings-disclosure" aria-expanded="false" aria-controls="settings-nav"><small>Section</small><strong>${label}${isDirty(page)?dot:''}</strong><span aria-hidden="true">⌄</span></button><nav id="settings-nav" aria-label="Settings sections">${links}</nav></div><div class="settings-content settings-${page}${readonlyPage(page)?' readonly':''}"><h2 id="settings-page-title" tabindex="-1">${label}</h2><p class="settings-helper">${helper}</p>${readonlyPage(page)?'<p class="settings-readonly">Read only. Saving requires signed-in send mode.</p>':''}${body}</div></div>`; return `${head('Settings','Your browser and this instance.')}<div class="settings-layout"><div><button type="button" id="settings-disclosure" aria-expanded="false" aria-controls="settings-nav"><small>Section</small><strong>${label}${isDirty(page)?dot:''}</strong><span aria-hidden="true">⌄</span></button><nav id="settings-nav" aria-label="Settings sections">${links}</nav></div><div class="settings-content settings-${page}${readonlyPage(page)?' readonly':''}"><h2 id="settings-page-title" tabindex="-1">${label}</h2><p class="settings-helper">${helper}</p>${readonlyPage(page)?'<p class="settings-readonly">Read only. Saving requires signed-in send mode.</p>':''}${body}</div></div>`;
+5 -5
View File
@@ -294,7 +294,7 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed}
#agents-table tbody th,#routes-table tbody th{text-transform:none;font-size:14px;font-weight:600;color:var(--strong)} #agents-table tbody th,#routes-table tbody th{text-transform:none;font-size:14px;font-weight:600;color:var(--strong)}
@media(max-width:759px){.settings-content .routing-panel{border:0;background:transparent;padding:0}.routing-panel .table-wrap{border:0;overflow:visible}.routing-panel #routes-table tr{display:grid;grid-template-columns:1fr 1fr;gap:0 10px;background:var(--surface)}.routing-panel #routes-table th,.routing-panel #routes-table td:first-of-type,.routing-panel #routes-table .fallback-cell:first-of-type{grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4){grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4)::before{content:'Fallback: None'}.routing-panel #routes-table .fallback-open td:nth-of-type(4)::before{content:'Fallback harness'}} @media(max-width:759px){.settings-content .routing-panel{border:0;background:transparent;padding:0}.routing-panel .table-wrap{border:0;overflow:visible}.routing-panel #routes-table tr{display:grid;grid-template-columns:1fr 1fr;gap:0 10px;background:var(--surface)}.routing-panel #routes-table th,.routing-panel #routes-table td:first-of-type,.routing-panel #routes-table .fallback-cell:first-of-type{grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4){grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4)::before{content:'Fallback: None'}.routing-panel #routes-table .fallback-open td:nth-of-type(4)::before{content:'Fallback harness'}}
.settings-content label:has(>input[type=checkbox]){display:inline-flex;align-items:center;gap:8px;min-height:44px;padding:0 8px} .settings-content label:has(>input[type=checkbox]){display:inline-flex;align-items:center;gap:8px;min-height:44px;padding:0 8px}
.settings-content .instance-form textarea,.settings-content .assistant-form textarea{display:block;width:100%} .settings-content :is(.instance-form,.level-form) textarea,.settings-content .assistant-form textarea{display:block;width:100%}
.route-definition{display:none}.settings-spinner{display:inline-block;width:16px;height:16px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;vertical-align:middle;animation:settings-spin .8s linear infinite}@keyframes settings-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.settings-spinner{animation:none}} .route-definition{display:none}.settings-spinner{display:inline-block;width:16px;height:16px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;vertical-align:middle;animation:settings-spin .8s linear infinite}@keyframes settings-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.settings-spinner{animation:none}}
@media(max-width:759px){#routes-table .route-definition{display:inline;float:right;color:var(--muted);font-size:12px;font-weight:400}} @media(max-width:759px){#routes-table .route-definition{display:inline;float:right;color:var(--muted);font-size:12px;font-weight:400}}
/* Settings forms: align controls across rows without changing their write paths. */ /* Settings forms: align controls across rows without changing their write paths. */
@@ -302,15 +302,15 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed}
.settings-limits-table,.settings-model-table{width:100%;table-layout:fixed;border-collapse:collapse} .settings-limits-table,.settings-model-table{width:100%;table-layout:fixed;border-collapse:collapse}
.settings-limits-table col:first-child{width:45%}.settings-limits-table col:nth-child(2){width:144px}.settings-model-table col:first-child{width:25%}.settings-model-table col:nth-child(2),.settings-model-table col:nth-child(3){width:37.5%} .settings-limits-table col:first-child{width:45%}.settings-limits-table col:nth-child(2){width:144px}.settings-model-table col:first-child{width:25%}.settings-model-table col:nth-child(2),.settings-model-table col:nth-child(3){width:37.5%}
.settings-limits-table :is(th,td),.settings-model-table :is(th,td){padding:8px;text-align:left;vertical-align:middle}.settings-limits-table tbody th,.settings-model-table tbody th{text-transform:none;font-size:14px;font-weight:500;color:var(--text)}.settings-limits-table .limit-group th{padding-top:14px;color:var(--muted);font-size:12px;font-weight:600}.settings-model-table input{width:100%} .settings-limits-table :is(th,td),.settings-model-table :is(th,td){padding:8px;text-align:left;vertical-align:middle}.settings-limits-table tbody th,.settings-model-table tbody th{text-transform:none;font-size:14px;font-weight:500;color:var(--text)}.settings-limits-table .limit-group th{padding-top:14px;color:var(--muted);font-size:12px;font-weight:600}.settings-model-table input{width:100%}
.settings-content .instance-form .filters{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto;gap:var(--gap);align-items:end}.settings-content .instance-form .filters>label:not(:has(input[type=checkbox])){display:flex;flex-direction:column;gap:6px}.settings-content .instance-form .filters>label:not(:has(input[type=checkbox])) :is(input,select){width:100%}.settings-content .instance-form .filters>label:has(input[type=checkbox]){display:flex;gap:8px;align-items:center;min-height:44px;white-space:nowrap}.settings-content .instance-form details{margin:var(--gap) 0}.hiring-grid>div{justify-content:flex-start;gap:var(--gap)} .settings-content :is(.instance-form,.level-form) .filters{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto;gap:var(--gap);align-items:end}.settings-content :is(.instance-form,.level-form) .filters>label:not(:has(input[type=checkbox])){display:flex;flex-direction:column;gap:6px}.settings-content :is(.instance-form,.level-form) .filters>label:not(:has(input[type=checkbox])) :is(input,select){width:100%}.settings-content :is(.instance-form,.level-form) .filters>label:has(input[type=checkbox]){display:flex;gap:8px;align-items:center;min-height:44px;white-space:nowrap}.settings-content :is(.instance-form,.level-form) details{margin:var(--gap) 0}.hiring-grid>div{justify-content:flex-start;gap:var(--gap)}
@media(max-width:759px){.settings-content .instance-form .filters{grid-template-columns:1fr}.settings-limits-table,.settings-limits-table tbody,.settings-limits-table tr,.settings-limits-table th,.settings-limits-table td,.settings-model-table,.settings-model-table tbody,.settings-model-table tr,.settings-model-table th,.settings-model-table td{display:block;width:100%}.settings-limits-table colgroup,.settings-model-table colgroup,.settings-limits-table thead,.settings-model-table thead{display:none}.settings-limits-table tbody tr:not(.limit-group){display:grid;grid-template-columns:120px 1fr;gap:0 12px;border-bottom:1px solid var(--line)}.settings-limits-table tbody tr:not(.limit-group)>th{grid-column:1/-1}.settings-limits-table :is(th,td),.settings-model-table :is(th,td){padding:6px 0}.settings-model-table tbody tr{padding:8px 0;border-bottom:1px solid var(--line)}.settings-model-table td:before{display:block;color:var(--muted);font-size:12px}.settings-model-table td:nth-of-type(1):before{content:'Provider'}.settings-model-table td:nth-of-type(2):before{content:'Model'}#routes-table .route-row:not(.fallback-open) td.fallback-cell:nth-of-type(n+5){display:none}} @media(max-width:759px){.settings-content :is(.instance-form,.level-form) .filters{grid-template-columns:1fr}.settings-limits-table,.settings-limits-table tbody,.settings-limits-table tr,.settings-limits-table th,.settings-limits-table td,.settings-model-table,.settings-model-table tbody,.settings-model-table tr,.settings-model-table th,.settings-model-table td{display:block;width:100%}.settings-limits-table colgroup,.settings-model-table colgroup,.settings-limits-table thead,.settings-model-table thead{display:none}.settings-limits-table tbody tr:not(.limit-group){display:grid;grid-template-columns:120px 1fr;gap:0 12px;border-bottom:1px solid var(--line)}.settings-limits-table tbody tr:not(.limit-group)>th{grid-column:1/-1}.settings-limits-table :is(th,td),.settings-model-table :is(th,td){padding:6px 0}.settings-model-table tbody tr{padding:8px 0;border-bottom:1px solid var(--line)}.settings-model-table td:before{display:block;color:var(--muted);font-size:12px}.settings-model-table td:nth-of-type(1):before{content:'Provider'}.settings-model-table td:nth-of-type(2):before{content:'Model'}#routes-table .route-row:not(.fallback-open) td.fallback-cell:nth-of-type(n+5){display:none}}
/* Agent menus must extend beyond the table without being clipped by its scroll region. */ /* Agent menus must extend beyond the table without being clipped by its scroll region. */
.settings-agents .table-wrap{overflow:visible} .settings-agents .table-wrap{overflow:visible}
/* Review fixes: preserve readable actions, labels and targets at every width. */ /* Review fixes: preserve readable actions, labels and targets at every width. */
.settings-content .instance-form .filters>label:not(:has(input[type=checkbox])){align-items:flex-start} .settings-content :is(.instance-form,.level-form) .filters>label:not(:has(input[type=checkbox])){align-items:flex-start}
.settings-content .instance-form .filters>label:has(input[type=checkbox]){grid-column:1/-1;justify-self:start} .settings-content :is(.instance-form,.level-form) .filters>label:has(input[type=checkbox]){grid-column:1/-1;justify-self:start}
.settings-content .settings-actions .banner:not(:empty){order:-1;flex:1 0 100%;margin:0} .settings-content .settings-actions .banner:not(:empty){order:-1;flex:1 0 100%;margin:0}
.agent-mobile-label{display:none} .agent-mobile-label{display:none}
#bus-view .page-head:has(+ .settings-layout) p{font-size:16px} #bus-view .page-head:has(+ .settings-layout) p{font-size:16px}
@@ -2,7 +2,7 @@
// browser on the real routes and writers (a temporary config directory with one organization). // browser on the real routes and writers (a temporary config directory with one organization).
import { test } from 'node:test'; import { test } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os'; import { tmpdir } from 'node:os';
import { join } from 'node:path'; import { join } from 'node:path';
import { businessDoc, rolesCopy, writeJson } from '../../organization/tests/helpers.mjs'; import { businessDoc, rolesCopy, writeJson } from '../../organization/tests/helpers.mjs';
@@ -16,7 +16,9 @@ import { close } from './fixture.mjs';
const SECRET = 'sk-test-NOT-A-SECRET-1234'; const SECRET = 'sk-test-NOT-A-SECRET-1234';
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`); const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
async function open(t, { send = true } = {}) { // orgSend gives the selected organization a send transport, so the role-instance Settings forms
// are writable too and their handlers are live beside the level forms.
async function open(t, { send = true, orgSend = false } = {}) {
const root = mkdtempSync(join(tmpdir(), 'ale-')); const root = mkdtempSync(join(tmpdir(), 'ale-'));
t.after(() => rmSync(root, { recursive: true, force: true })); t.after(() => rmSync(root, { recursive: true, force: true }));
const rolesDir = rolesCopy(root); const rolesDir = rolesCopy(root);
@@ -28,7 +30,7 @@ async function open(t, { send = true } = {}) {
list: async () => [{ id: 'demo', label: 'Demo', busHealthy: true }], list: async () => [{ id: 'demo', label: 'Demo', busHealthy: true }],
members: async () => [{ id: 'demo', doc: doc() }], members: async () => [{ id: 'demo', doc: doc() }],
resolve: async id => id !== 'demo' ? null : { resolve: async id => id !== 'demo' ? null : {
busHealthy: true, busHealthy: true, ...(orgSend ? { send: async () => ({}) } : {}),
reads: { business: async () => ({ business: { id: 'demo', human: 'jason', arbiters: ['chief'], projects: ['stack'], vars: {}, instances: [{ instance: 'chief', vars: {} }] } }), reads: { business: async () => ({ business: { id: 'demo', human: 'jason', arbiters: ['chief'], projects: ['stack'], vars: {}, instances: [{ instance: 'chief', vars: {} }] } }),
settings: async () => ({ business: 'demo', release: 'fixture', notifier: {}, launch: { limits: {} } }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) }, settings: async () => ({ business: 'demo', release: 'fixture', notifier: {}, launch: { limits: {} } }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
bus: { instances: async () => instances, messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => [], tasks: async () => [] }, bus: { instances: async () => instances, messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => [], tasks: async () => [] },
@@ -45,6 +47,9 @@ async function open(t, { send = true } = {}) {
return { b, wait: waitFor(b), file, root }; return { b, wait: waitFor(b), file, root };
} }
const fill = (b, form, values) => b.evaluate(`(() => { const f = document.getElementById(${JSON.stringify(form)}); for (const [k, v] of Object.entries(${JSON.stringify(values)})) { f.elements[k].value = v; } f.requestSubmit(); })()`); const fill = (b, form, values) => b.evaluate(`(() => { const f = document.getElementById(${JSON.stringify(form)}); for (const [k, v] of Object.entries(${JSON.stringify(values)})) { f.elements[k].value = v; } f.requestSubmit(); })()`);
// Typing: each value set, then input and change fired, as a person's edit fires them.
const type = (b, form, values) => b.evaluate(`(() => { const f = document.getElementById(${JSON.stringify(form)}); for (const [k, v] of Object.entries(${JSON.stringify(values)})) { const el = f.elements[k]; el.value = v; el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); } })()`);
const values = (b, form) => b.evaluate(`Object.fromEntries(new FormData(document.getElementById(${JSON.stringify(form)})))`);
const receipt = which => `(document.getElementById("agent-levels-${which}-receipt")?.textContent || "")`; const receipt = which => `(document.getElementById("agent-levels-${which}-receipt")?.textContent || "")`;
test('the root form adds a root agent and the grid repaints from a fresh read; a refusal names the key, keeps the draft and never shows the value', async t => { test('the root form adds a root agent and the grid repaints from a fresh read; a refusal names the key, keeps the draft and never shows the value', async t => {
@@ -111,3 +116,47 @@ test('without --send both levels read but offer no form', async t => {
assert.match(await b.evaluate('document.getElementById("agent-levels-edit").innerText'), /started without writes/); assert.match(await b.evaluate('document.getElementById("agent-levels-edit").innerText'), /started without writes/);
assert.equal(await b.evaluate('!!document.getElementById("agent-levels-root-form") || !!document.getElementById("agent-levels-project-form")'), false); assert.equal(await b.evaluate('!!document.getElementById("agent-levels-root-form") || !!document.getElementById("agent-levels-project-form")'), false);
}); });
test('both drafts survive a refresh render and the other form\'s save; a draft keeps its revision; the role-instance handlers leave the level forms alone', async t => {
const { b, wait, root } = await open(t, { orgSend: true });
await wait('document.getElementById("agent-levels-root-form") && document.getElementById("agent-levels-project-form")');
assert.equal(await b.evaluate('!!document.getElementById("instance-add-form")'), true, 'the role-instance forms are writable in this fixture');
assert.equal(await b.evaluate('document.querySelectorAll("#agent-levels-edit .instance-form").length'), 0);
assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#agent-levels-root-form .filters")).display'), 'grid', 'the level forms keep the Settings form layout');
await type(b, 'agent-levels-root-form', { name: 'drafted', vars: 'limits.network=none' });
await type(b, 'agent-levels-project-form', { name: 'helper', form: 'narrow', vars: 'limits.tools=read' });
assert.equal(await b.evaluate('!!document.querySelector("#settings-nav a[href$=\'settings/agents\'] .settings-dot")'), true, 'the nav marks unsaved changes');
// A full Settings render, as the ten-second poll does: the edit box is a new node, the drafts are in it.
await b.evaluate('document.getElementById("agent-levels-edit").dataset.old = "1"; document.getElementById("refresh").click()');
await wait('document.getElementById("agent-levels-edit") && !document.getElementById("agent-levels-edit").dataset.old');
assert.deepEqual(await values(b, 'agent-levels-root-form'), { name: 'drafted', definition: '', model: '', vars: 'limits.network=none', unset: '', excludeOrgs: '' });
assert.deepEqual(await values(b, 'agent-levels-project-form'), { name: 'helper', form: 'narrow', definition: '', vars: 'limits.tools=read' });
// The root form saves; the project draft stays as typed and the root draft clears.
await type(b, 'agent-levels-root-form', { name: 'researcher', definition: 'research', vars: '' });
await b.evaluate('document.getElementById("agent-levels-root-form").requestSubmit()');
await wait(`${receipt('root')}.startsWith("Saved researcher at ")`);
assert.equal(await b.evaluate('document.getElementById("agent-levels-root-form").elements.name.value'), '');
assert.deepEqual(await values(b, 'agent-levels-project-form'), { name: 'helper', form: 'narrow', definition: '', vars: 'limits.tools=read' });
// A locally refused submit keeps its draft; the role-instance handler takes no part.
await type(b, 'agent-levels-root-form', { name: 'second', vars: 'malformed' });
await b.evaluate('document.getElementById("agent-levels-root-form").requestSubmit()');
await wait(`${receipt('root')} === "Variables line 1 needs KEY=VALUE."`);
await new Promise(r => setTimeout(r, 300));
assert.equal(await b.evaluate('document.getElementById("agent-levels-root-form").elements.name.value'), 'second');
assert.equal(await b.evaluate('document.getElementById("agent-levels-root-form").elements.vars.value'), 'malformed');
assert.equal(await b.evaluate('!!document.querySelector("#instance-add-form .settings-actions.has-draft")'), false, 'the instance form took no draft');
// The file changes under a draft: the draft's save sends the revision it began at and is refused,
// then a second, deliberate save goes through against the file as now read.
await type(b, 'agent-levels-root-form', { name: 'later', definition: 'research', vars: '' });
const began = await b.evaluate('document.getElementById("agent-levels-root-form").dataset.revision');
writeFileSync(join(root, 'agents.json'), JSON.stringify({ agentsVersion: 1, agents: {} }) + '\n', { mode: 0o600 });
await b.evaluate('document.getElementById("agent-levels-edit").dataset.old = "1"; document.getElementById("refresh").click()');
await wait('document.getElementById("agent-levels-edit") && !document.getElementById("agent-levels-edit").dataset.old');
assert.equal(await b.evaluate('document.getElementById("agent-levels-root-form").dataset.revision'), began, 'the draft keeps the revision it began at');
await b.evaluate('document.getElementById("agent-levels-root-form").requestSubmit()');
await wait(`${receipt('root')}.startsWith("Refused: the file changed")`);
assert.equal(await b.evaluate('document.getElementById("agent-levels-root-form").elements.name.value'), 'later');
await b.evaluate('document.getElementById("agent-levels-root-form").requestSubmit()');
await wait(`${receipt('root')}.startsWith("Saved later at ")`);
assert.deepEqual(Object.keys(JSON.parse(readFileSync(join(root, 'agents.json'), 'utf8')).agents), ['later']);
});
@@ -168,6 +168,14 @@ test('project entries: define, narrow, exclude and remove repaint the read; a wi
const [missing, missingBody] = await call(f, '/api/orgs/demo/agent-levels/projects/nope', 'POST', { revision: listed.revision, name: 'scout', entry: { exclude: true } }); const [missing, missingBody] = await call(f, '/api/orgs/demo/agent-levels/projects/nope', 'POST', { revision: listed.revision, name: 'scout', entry: { exclude: true } });
assert.equal(missing, 404); assert.equal(missingBody.error, 'project-not-found'); assert.equal(missing, 404); assert.equal(missingBody.error, 'project-not-found');
assert.equal((await call(f, '/api/orgs/other/agent-levels/projects/stack'))[0], 404); assert.equal((await call(f, '/api/orgs/other/agent-levels/projects/stack'))[0], 404);
// A name the writers can't take is a 400 that names the field, never the value, on both routes.
for (const name of ['BadName', 'a'.repeat(65)]) {
for (const [route, entry] of [[PROJECT, { definition: 'research' }], [ROOT, { definition: 'research' }]]) {
const [s, body, text] = await call(f, route, 'POST', { revision: listed.revision, name, entry });
assert.equal(s, 400, `${route} ${name}: ${text}`); assert.equal(body.error, 'invalid-request'); assert.match(body.message, /^name must be an id/);
assert.ok(!text.includes(name), text);
}
}
assert.equal(readFileSync(f.file, 'utf8'), before); assert.equal(readFileSync(f.file, 'utf8'), before);
for (const name of ['checker', 'coder', 'scout']) assert.equal((await set(name, null))[1].receipt.form, 'remove'); for (const name of ['checker', 'coder', 'scout']) assert.equal((await set(name, null))[1].receipt.form, 'remove');
assert.deepEqual((await call(f, PROJECT))[1].agents, []); assert.deepEqual((await call(f, PROJECT))[1].agents, []);