Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

New-department grant: skip departments rolled back, count grants still queued

milind-sonice4bf080b4ed
diff --git a/scripts/verify-team-backup.ts b/scripts/verify-team-backup.ts
index 6a1c117c21..e7b4671fe8 100644
--- a/scripts/verify-team-backup.ts
+++ b/scripts/verify-team-backup.ts
@@ -4,6 +4,7 @@ import { pathToFileURL } from "node:url";
import { launchVerificationServer, runControlOmb } from "./control-omb.ts";
import { request } from "./mcp-server.ts";
import { parseTeamBackup } from "../shared/team-backup.ts";
+import { inChargeOfEvery } from "../server/peer-roster.ts";
export async function verifyTeamBackup(report: (event: unknown) => void = () => {}) {
const fixture = await launchVerificationServer();
@@ -15,6 +16,11 @@ export async function verifyTeamBackup(report: (event: unknown) => void = () =>
return result;
};
const post = (path: string, body: unknown) => request(path, { method: "POST", body: JSON.stringify(body) }, url);
+ const departments = async (): Promise<string[]> => (await request("/api/sidebar-sections", {}, url)).sections;
+ // The main Chief is in charge of every department, so each department an import adds becomes its too
+ // (server/department-grants.ts). Nothing else about an existing bot changes.
+ const granted = <T extends Parameters<typeof inChargeOfEvery>[0]>(bot: T, before: string[], after: string[]): T => inChargeOfEvery(bot, before)
+ ? { ...bot, managedSections: [...(bot.managedSections ?? []), ...after.filter((name) => !before.includes(name))] } : bot;
try {
const doctor = await command("doctor") as { ok: boolean };
assert.equal(doctor.ok, true);
@@ -29,6 +35,7 @@ export async function verifyTeamBackup(report: (event: unknown) => void = () =>
assert.equal(wait.status, "settled");
const transcript = await command("messages", "--bot", bot.id, "--limit", "10");
const before = await request("/api/bots", {}, url);
+ const departmentsBefore = await departments();
const backup = parseTeamBackup(await post("/api/teams/export", { format: "backup", name: "Fixture backup" }));
report({ command: "export backup", bots: backup.bots.length, conversations: backup.bots.reduce((n, bot) => n + bot.tasks.length, 0) });
const imported = await post("/api/teams/import?mode=add", JSON.parse(JSON.stringify(backup)));
@@ -38,7 +45,9 @@ export async function verifyTeamBackup(report: (event: unknown) => void = () =>
assert.equal(added.section, "Original team 2");
assert.equal(added.soul, soul);
const after = await request("/api/bots", {}, url);
- for (const existing of before.bots) assert.deepEqual(after.bots.find((candidate: { id: string }) => candidate.id === existing.id), existing);
+ const departmentsAfter = await departments();
+ assert.ok(before.bots.some((existing: Parameters<typeof inChargeOfEvery>[0]) => inChargeOfEvery(existing, departmentsBefore)));
+ for (const existing of before.bots) assert.deepEqual(after.bots.find((candidate: { id: string }) => candidate.id === existing.id), granted(existing, departmentsBefore, departmentsAfter));
for (const existing of before.groups) assert.deepEqual(after.groups.find((candidate: { id: string }) => candidate.id === existing.id), existing);
assert.deepEqual(await command("messages", "--bot", bot.id, "--limit", "10"), transcript);
const old = before.bots.find((candidate: { id: string }) => candidate.id === bot.id);
@@ -68,6 +77,7 @@ export async function verifyTeamBackup(report: (event: unknown) => void = () =>
{ format: "repeated Markdown package", path: "/api/teams/import?mode=add", body: packageExport.markdown },
].entries()) {
const existing = await request("/api/bots", {}, url);
+ const existingDepartments = await departments();
const result = await post(example.path, example.body);
const section = `Fixture manifest ${index + 2}`;
assert.ok(result.bots.length > 0);
@@ -75,9 +85,10 @@ export async function verifyTeamBackup(report: (event: unknown) => void = () =>
assert.ok(result.groups.every((candidate: { section?: string }) => candidate.section === section));
if (example.format.includes("project")) assert.equal(result.group.section, section);
const current = await request("/api/bots", {}, url);
+ const currentDepartments = await departments();
assert.equal(current.bots.length, existing.bots.length + result.bots.length);
assert.equal(current.groups.length, existing.groups.length + result.groups.length);
- for (const value of existing.bots) assert.deepEqual(current.bots.find((candidate: { id: string }) => candidate.id === value.id), value);
+ for (const value of existing.bots) assert.deepEqual(current.bots.find((candidate: { id: string }) => candidate.id === value.id), granted(value, existingDepartments, currentDepartments));
for (const value of existing.groups) assert.deepEqual(current.groups.find((candidate: { id: string }) => candidate.id === value.id), value);
assert.deepEqual(await command("messages", "--bot", bot.id, "--limit", "10"), transcript);
report({ command: "import template", format: example.format, section, existingBotsKept: existing.bots.length, existingRoomsKept: existing.groups.length });
diff --git a/server/department-grants.ts b/server/department-grants.ts
index 3bce0cae1a..dd925c6acc 100644
--- a/server/department-grants.ts
+++ b/server/department-grants.ts
@@ -16,19 +16,36 @@ export const departmentGrants = new AsyncLocalStorage<DepartmentGrant[]>();
/** The settings page saves at most this many departments for one Chief (server/routes/bot-patch.ts). */
const MAX_MANAGED = 100;
+/** Grants decided but not yet written, per store: a second department made before they land (a backup import that makes
+ * one department per team it copies) still finds the Chief in charge of every department. */
+const queued = new WeakMap<object, Map<string, string[]>>();
+
/** `added` just joined the departments. Who qualifies is read now, from the bots as they were before the write that
- * made the department (a bot made Chief by that same write does not count); the grant waits until that write is done,
- * since it may still be saving a copy of the bots, and goes only to a Chief that still qualifies then. */
+ * made the department (a bot made Chief by that same write does not count) with the grants still queued; the grant waits
+ * until that write is done, since it may still be saving a copy of the bots, and goes only to a Chief that still
+ * qualifies then. */
export function grantNewDepartments(store: Pick<Store, "sections" | "bots" | "bot" | "patchBot">, added: readonly string[]): void {
const before = store.sections.filter((name) => !added.includes(name));
- const chiefs = store.bots.filter((bot) => inChargeOfEvery(bot, before)).map((bot) => bot.id);
+ const waiting = queued.get(store) ?? new Map<string, string[]>();
+ const chiefs = store.bots.filter((bot) =>
+ inChargeOfEvery({ ...bot, managedSections: [...(bot.managedSections ?? []), ...(waiting.get(bot.id) ?? [])] }, before)).map((bot) => bot.id);
if (!chiefs.length) return;
+ for (const id of chiefs) waiting.set(id, [...(waiting.get(id) ?? []), ...added]);
+ queued.set(store, waiting);
void Promise.resolve().then(() => {
for (const id of chiefs) {
+ const rest = waiting.get(id)?.filter((name) => !added.includes(name)) ?? [];
+ if (rest.length) waiting.set(id, rest); else waiting.delete(id);
+ }
+ if (!waiting.size) queued.delete(store);
+ // A department removed again since (a failed import rolls its new department back) is not granted.
+ const live = added.filter((name) => store.sections.includes(name));
+ const others = before.filter((name) => store.sections.includes(name));
+ for (const id of live.length ? chiefs : []) {
const chief = store.bot(id);
- if (!chief || !inChargeOfEvery(chief, before)) continue;
+ if (!chief || !inChargeOfEvery(chief, others)) continue;
const previous = [...(chief.managedSections ?? [])];
- const managedSections = [...new Set([...previous, ...added])];
+ const managedSections = [...new Set([...previous, ...live])];
if (managedSections.length === previous.length || managedSections.length > MAX_MANAGED) continue;
try {
store.patchBot(chief.id, { managedSections });
diff --git a/server/room-coordination.e2e.test.ts b/server/room-coordination.e2e.test.ts
index 8bada7d714..953b4f19fe 100644
--- a/server/room-coordination.e2e.test.ts
+++ b/server/room-coordination.e2e.test.ts
@@ -213,7 +213,12 @@ it("receipts a retried duplicate of a failed hand-off as failed, not queued behi
f.plan[f.target.id].fail = true;
f.plan[f.sender.id].resumeSteps = [{ arguments: f.plan[f.sender.id].steps[0].arguments, expectError: true }];
await f.start(); expect((await f.wait()).status).toBe("settled");
- expect(f.provider().map((turn: any) => turn.botId)).toEqual([f.sender.id, f.target.id, f.sender.id]);
+ // The main Chief got department A when it was made, so it also hears of the failed run, in a turn of its own.
+ const chief = (await f.api("/api/bots")).bots.find((bot: any) => bot.chiefOfStaff);
+ expect(chief.managedSections).toEqual(["A"]);
+ await expect.poll(() => f.provider().filter((turn: any) => turn.botId === chief.id)
+ .map((turn: any) => /incident report.*Engineer's run in the room \\"Engineering\\" failed/.test(JSON.stringify(turn.prompt))), { timeout: 15_000 }).toEqual([true]);
+ expect(f.provider().map((turn: any) => turn.botId).filter((id: string) => id !== chief.id)).toEqual([f.sender.id, f.target.id, f.sender.id]);
const [assigned, retried] = f.provider().filter((turn: any) => turn.botId === f.sender.id);
expect(assigned.resumed).toBe(false);
const first = JSON.parse(assigned.evidence.find((entry: any) => entry.step).response.result.content[0].text);
diff --git a/server/runtime-roots.e2e.test.ts b/server/runtime-roots.e2e.test.ts
index 3f6edd556d..7417a0f770 100644
--- a/server/runtime-roots.e2e.test.ts
+++ b/server/runtime-roots.e2e.test.ts
@@ -740,7 +740,9 @@ type CardState = { status?: string; stopped?: boolean; resumed?: boolean };
type StallFixture = {
dataDir: string;
clive: { id: string };
- roots(): Array<{ status: string; outcome?: string; executions: number; cards?: string[] }>;
+ roots(): Array<{ status: string; outcome?: string; executions: number; cards?: string[]; assignee: { botId: string } }>;
+ api(method: string, path: string): Promise<{ body: { bots: Array<{ id: string; chiefOfStaff?: boolean; managedSections?: string[] }> } }>;
+ own(record: unknown): string;
messages(threadId: string): Promise<Array<{ id: string; kind: string; tool?: { name: string }; secret?: CardState; connector?: CardState; signIn?: CardState }>>;
turns(botId: string): Array<{ planKey?: string }>;
open(name: string): void;
@@ -759,14 +761,20 @@ const stallOverCards = async (f: StallFixture, job: string, ids: string[]) => {
.toEqual(["error: no activity for 20 minutes — the turn was stopped"]);
const cards = (await f.messages(job)).filter((message) => ids.includes(message.id));
expect(cards.map((message) => (message.secret ?? message.connector ?? message.signIn)?.stopped)).toEqual(ids.map(() => true));
+ // The main Chief got Clive's department when it was made, so it also hears of the stall, in a run of its own.
+ const chief = (await f.api("GET", "/api/bots?messages=0")).body.bots.find((bot) => bot.chiefOfStaff)!;
+ expect(chief.managedSections).toEqual(["Leadership"]);
+ await expect.poll(() => f.roots().filter((row) => row.assignee.botId === chief.id).map((row) => row.status), { timeout: 30_000 }).toEqual(["completed"]);
+ expect(f.turns(chief.id).map((record) => /incident report[\s\S]*Clive's run .* stopped after showing no activity/.test(f.own(record)))).toEqual([true]);
};
const answerStartsNothing = async (f: StallFixture, job: string) => {
f.open("c0");
f.script(f.clive.id, { key: "C-AFTER", match: ["AFTER-ANSWER"], reply: "AFTER-ANSWER-DONE: hello back." });
await f.say(f.clive.id, job, "AFTER-ANSWER: hello after the card was answered.");
- await expect.poll(() => f.roots().map((row) => row.status), { timeout: 30_000 }).toEqual(["failed", "completed"]);
- expect(f.roots().map((row) => [row.outcome, row.executions])).toEqual([["stalled", 1], ["done", 1]]);
+ const roots = () => f.roots().filter((row) => row.assignee.botId === f.clive.id);
+ await expect.poll(() => roots().map((row) => row.status), { timeout: 30_000 }).toEqual(["failed", "completed"]);
+ expect(roots().map((row) => [row.outcome, row.executions])).toEqual([["stalled", 1], ["done", 1]]);
expect(await f.said(job, "AFTER-ANSWER-DONE")).toBe(1);
expect(f.turns(f.clive.id).map((record) => record.planKey)).toEqual(["C-AFTER"]);
};
diff --git a/server/store.test.ts b/server/store.test.ts
index 7974f392b3..6409e63a97 100644
--- a/server/store.test.ts
+++ b/server/store.test.ts
@@ -1285,6 +1285,21 @@ describe("Store", () => {
expect(restored.bot(lead.id)?.managedSections).toEqual(["", "Research"]);
});
+ it("gives the main Chief each department one run makes before the first grant lands, except one removed again", async () => {
+ const store = new Store(selection);
+ const chief = store.createBot({ name: "Chief" });
+ store.setChiefOfStaff(chief.id);
+ store.createBot({ name: "First", section: "First team" });
+ store.createBot({ name: "Second", section: "Second team" });
+ // A failed import rolls its new department back the same way.
+ const member = store.createBot({ name: "Imported", section: "Imported team" });
+ store.deleteBot(member.id);
+ expect(store.changeEmptySection("Imported team", null)).toBeUndefined();
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(store.bot(chief.id)?.managedSections).toEqual(["First team", "Second team"]);
+ expect(new Store(selection).bot(chief.id)?.managedSections).toEqual(["First team", "Second team"]);
+ });
+
it("lands a created specialist in its proposed working folder, keeping the private workspace clean", () => {
const store = new Store(selection);
const chief = store.createBot({ name: "Chief", section: "Ops" });
diff --git a/server/team-package-skills.e2e.test.ts b/server/team-package-skills.e2e.test.ts
index 12d8051ec2..046cafca01 100644
--- a/server/team-package-skills.e2e.test.ts
+++ b/server/team-package-skills.e2e.test.ts
@@ -78,7 +78,10 @@ it("transfers only selected skills disabled, preserves originals, and rolls back
expect(JSON.stringify(messages)).toContain("hello from fake claude");
expect(readFileSync(fixture.fixtureDumpPath, "utf8")).not.toContain("SKILL_FIXTURE_MARKER");
const after = await request("/api/bots", {}, url);
- for (const bot of before.bots) expect(after.bots.find((value: { id: string }) => value.id === bot.id)).toEqual(bot);
+ // The main Chief is in charge of every department, so each imported one became its too; nothing else changed.
+ expect(before.bots.filter((bot: { chiefOfStaff?: boolean }) => bot.chiefOfStaff)).toHaveLength(1);
+ for (const bot of before.bots) expect(after.bots.find((value: { id: string }) => value.id === bot.id))
+ .toEqual(bot.chiefOfStaff ? { ...bot, managedSections: [...(bot.managedSections ?? []), imported.section, copied.section] } : bot);
const backup = await post("/api/teams/export", { format: "backup" });
expect(JSON.stringify(backup)).not.toContain("SKILL_FIXTURE_MARKER");
console.log(JSON.stringify({ ok: true, rollback: true, explicitSelection: true, importedSkillsDisabled: true, messages, logPath: fixture.info.logPath }));