Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chief setup changes to a bot fewer people can see wait on the card
milind-sonie8925985e88d
diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 39237b267e..7aec06bee8 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -737,7 +737,10 @@ person's MausBot from outside it: no other bot is told of it.other bot on the team, in any department, someone's Chief included, with nothing to set up (`canReach` in`server/peer-roster.ts`). Each bot's roster lists them all, its own department first; a Chief's lists its own teamfirst and everyone else as reachable. Reaching a bot gives no authority over it: supervision, incidents, the inbox,-setup changes and automations follow ownership and departments as above (`hasAuthority`, `canManage`). Only two+setup changes and automations follow ownership and departments as above (`hasAuthority`, `canManage`). A Chief's setup+change (profile, model, skills, team setup or deletion) to a bot that not everyone who can see the Chief can see waits+on the person's card, at Full access too, and `list_team_setup` lists such a bot without its name, title or model+(`setupChangeCovered`). Only twothings narrow reach: archived bots, and the audience rule below (a bot shared with different people; a person's own MausBot is theone exception, above). A turn in someone'sprivate chat may ask any bot, and the work it hands on stays in that person's audience; it never hands work into a roomdiff --git a/server/chief-shared-department-bot.e2e.test.ts b/server/chief-shared-department-bot.e2e.test.tsindex b94159368a..148cc328f2 100644--- a/server/chief-shared-department-bot.e2e.test.ts+++ b/server/chief-shared-department-bot.e2e.test.ts@@ -1,5 +1,6 @@// Real server, fake engine: a Chief of Staff changes the setup of a bot shared with different people when that bot is in-// a department the Chief is in charge of, and still may not for one outside its departments.+// a department the Chief is in charge of, and still may not for one outside its departments. A bot seen by fewer people+// than the Chief is listed without its name and changed only on the person's card.import { spawn, type ChildProcess } from "node:child_process";import { closeSync, openSync } from "node:fs";import { fileURLToPath } from "node:url";@@ -23,14 +24,15 @@ const bot = async (name: string) => (await api("GET", "/api/bots")).body.bots.fibeforeAll(async () => {fixture = await launchVerificationServer();const port = Number(new URL(fixture.info.url).port);- for (const [name, section] of [["Dept Chief", "Work"], ["Editor", "Editing"], ["Payroll", "Private"]]) {+ for (const [name, section] of [["Dept Chief", "Work"], ["Editor", "Editing"], ["Desk", "Editing"], ["Payroll", "Private"]]) {const created = await api("POST", "/api/bots", { name, section });expect(created.status, JSON.stringify(created.body)).toBe(201);}- const chief = await api("PATCH", `/api/bots/${(await bot("Dept Chief")).id}`, { chiefOfStaff: true, managedSections: ["Editing"], acknowledgePeerScope: true });+ const chief = await api("PATCH", `/api/bots/${(await bot("Dept Chief")).id}`, { chiefOfStaff: true, managedSections: ["Editing"], acknowledgePeerScope: true,+ visibility: { people: ["[email protected]", "[email protected]"] } });expect(chief.status, JSON.stringify(chief.body)).toBe(200);- for (const name of ["Editor", "Payroll"]) {- const shared = await api("PATCH", `/api/bots/${(await bot(name)).id}`, { visibility: "admins" });+ for (const [name, visibility] of [["Editor", { people: ["[email protected]"] }], ["Payroll", "admins"]] as const) {+ const shared = await api("PATCH", `/api/bots/${(await bot(name)).id}`, { visibility });expect(shared.status, JSON.stringify(shared.body)).toBe(200);}await waitForExit(fixture.child, { signal: "SIGTERM" });@@ -54,12 +56,13 @@ afterAll(async () => {await fixture?.close();});-it("lets the Chief list and change a shared bot in its department, and not one outside it", async () => {+it("lets the Chief list and change a shared bot in its department, on the card when fewer people see it, and not one outside it", async () => {const chief = await bot("Dept Chief");const editor = await bot("Editor");+ const desk = await bot("Desk");const payroll = await bot("Payroll");- expect(chief).toMatchObject({ chiefOfStaff: true, managedSections: ["Editing"] });- expect([editor.visibility, payroll.visibility]).toEqual(["admins", "admins"]);+ expect(chief).toMatchObject({ chiefOfStaff: true, managedSections: ["Editing"], visibility: { people: ["[email protected]", "[email protected]"] } });+ expect([editor.visibility, desk.visibility ?? "everyone", payroll.visibility]).toEqual([{ people: ["[email protected]"] }, "everyone", "admins"]);const minted = await fetch(fixture.info.url + "/api/testing/internal-capability", {method: "POST", headers: { "content-type": "application/json", "x-openmausbot-test-capability": key },body: JSON.stringify({ botId: chief.id, threadId: chief.threadId, kind: "agents" }),@@ -69,12 +72,22 @@ it("lets the Chief list and change a shared bot in its department, and not one oconst catalog = await api("GET", "/api/internal/team-setup-catalog", undefined, token);expect(catalog.status, JSON.stringify(catalog.body)).toBe(200);- expect((catalog.body.bots as any[]).map((entry) => entry.name).sort()).toEqual(["Dept Chief", "Editor"]);+ expect(catalog.body.bots).toHaveLength(3);+ expect(catalog.body.bots).toEqual(expect.arrayContaining([+ expect.objectContaining({ id: chief.id, name: "Dept Chief" }),+ { id: editor.id, section: "Editing", chiefOfStaff: false, restricted: true },+ expect.objectContaining({ id: desk.id, name: "Desk", section: "Editing" }),+ ]));const change = (target: any) => api("POST", "/api/internal/profile-requests", { fromBotId: chief.id, fromThreadId: chief.threadId,forBotId: target.id, changes: { title: "Proofreader" }, reason: "The person asked." }, token);- const allowed = await change(editor);- expect(allowed.body.state, JSON.stringify(allowed.body)).toBe("applied");+ expect((await change(desk)).body.state).toBe("applied");+ expect((await bot("Desk")).title).toBe("Proofreader");+ const carded = await change(editor);+ expect(carded.body.state, JSON.stringify(carded.body)).toBe("pending");+ expect((await bot("Editor")).title).toBe("");+ const approved = await api("POST", `/api/threads/${chief.threadId}/respond`, { requestId: carded.body.requestId, behavior: "allow" });+ expect(approved.status, JSON.stringify(approved.body)).toBe(200);expect((await bot("Editor")).title).toBe("Proofreader");const refused = await change(payroll);expect(refused.status, JSON.stringify(refused.body)).toBeGreaterThanOrEqual(400);diff --git a/server/host/teammate-skills-host.test.ts b/server/host/teammate-skills-host.test.tsindex d953f7d023..e0406233a4 100644--- a/server/host/teammate-skills-host.test.ts+++ b/server/host/teammate-skills-host.test.ts@@ -189,6 +189,23 @@ describe("a Chief of Staff changing its teammates' skills", () => {expect(t.turns).toEqual([]);});+ it("waits on the card, even at Full access, when a teammate is seen by fewer people than the Chief", () => {+ const t = setup();+ t.bots.coder!.visibility = { people: ["[email protected]"] };+ expect(t.host.stage(t.bots.chief!, "t1", both, "full-access")).toMatchObject({ status: 201, body: { state: "pending" } });+ expect(t.turns).toEqual([]);+ expect(t.card()).toMatchObject({ options: ["Apply", "Deny"] });+ expect(t.approve()).toEqual({ claimed: true, outcome: "allowed-once" });+ expect([t.enabled("writer/research"), t.enabled("coder/lint")]).toEqual([true, false]);+ });++ it("applies at Full access when every teammate is seen by everyone who sees the Chief", () => {+ const t = setup();+ t.bots.chief!.visibility = { people: ["[email protected]"] };+ t.bots.coder!.visibility = { people: ["[email protected]", "[email protected]"] };+ expect(t.host.stage(t.bots.chief!, "t1", both, "full-access")).toMatchObject({ status: 201, body: { state: "applied" } });+ });+it("changes nothing on Deny", () => {const t = setup();t.host.stage(t.bots.chief!, "t1", both, null);diff --git a/server/host/teammate-skills-host.ts b/server/host/teammate-skills-host.tsindex f723216ed8..9e213efd79 100644--- a/server/host/teammate-skills-host.ts+++ b/server/host/teammate-skills-host.ts@@ -13,6 +13,7 @@ import { writeFileAtomic } from "../atomic.ts";import { chiefLevel } from "../chief-level.ts";import { appendDecision } from "../decision-log.ts";import { UNDO_STALE, type DirectApply } from "../direct-apply.ts";+import { setupChangeCovered } from "../peer-roster.ts";import { conversationLanguage, serverLine } from "../server-lines.ts";import { skillContentSha256, skillSwitchStillMatches, skillSwitchTarget, type SwitchableSkill } from "../skill-switch.ts";import type { BotRecord, Message, Store } from "../store.ts";@@ -147,7 +148,8 @@ export function createTeammateSkillsHost(deps: TeammateSkillsHostDeps) {const asked = checked(from, body);if ("status" in asked) return asked;// In a room, always the card: words a teammate posted there must not change bots' skills by themselves.- const applies = store.groupByThread(threadId) ? null : direct;+ const covered = asked.changes.every((change) => setupChangeCovered(from, store.bot(change.botId)));+ const applies = store.groupByThread(threadId) || !covered ? null : direct;const persistence = deps.persistence(from.id, threadId, !applies);if (!persistence.ok) return { status: persistence.status, body: { error: persistence.error } };const requestId = randomUUID();diff --git a/server/index.ts b/server/index.tsindex e8b24b6a66..95e68130c3 100644--- a/server/index.ts+++ b/server/index.ts@@ -128,7 +128,7 @@ import { createSideJobs, helperSelection } from "./side-jobs.ts";import type { CaptureTurn, RoomLine } from "./memory-capture.ts";import { createAboutMe } from "./about-me.ts"; import { createPersonPreference } from "./host/person-preference.ts";import { botMemoryUpdate, ownersOwnAsk } from "./memory-forget.ts";-import { canManage, canManageSetup, canReach, departmentRefusal, hasTeamAuthority, inChargeOfEvery, livePeerRoster, livePeerRosterBlock, peerName, peerRosterPrompt, peerRosterSystemPrompt, withElsewhere, peerStatus, peerStatusWords, reachablePeers, resolveTeammate, roomPeerRosterSystemPrompt, roomRosterLine } from "./peer-roster.ts"; import { createLinkedRoster } from "./host/linked-roster.ts"; import { roomPostRefusal, sharedNamesNote, unreachedMentionLines } from "./same-name-mentions.ts";+import { canManage, canManageSetup, setupChangeCovered, canReach, departmentRefusal, hasTeamAuthority, inChargeOfEvery, livePeerRoster, livePeerRosterBlock, peerName, peerRosterPrompt, peerRosterSystemPrompt, withElsewhere, peerStatus, peerStatusWords, reachablePeers, resolveTeammate, roomPeerRosterSystemPrompt, roomRosterLine } from "./peer-roster.ts"; import { createLinkedRoster } from "./host/linked-roster.ts"; import { roomPostRefusal, sharedNamesNote, unreachedMentionLines } from "./same-name-mentions.ts";import {containerComputerAction,containerComputerFrame,@@ -9056,7 +9056,7 @@ const chiefPeerTargetRule = (noun: string) => (proposerBotId: string, targetBotIif (!proposer || !chiefLevel(proposer)) return "only a section's Chief of Staff can change another bot's " + noun;if (!canManageSetup(proposer, target)) return departmentRefusal(proposer, target) ?? "that bot is not in a department this Chief manages";return null;-};+}; const setupAppliesDirectly = (botId: string, threadId: string, targetBotId: string) => setupChangeCovered(store.bot(botId), store.bot(targetBotId)) ? appliesDirectly(botId, threadId) : null;const burst = createBurstHost({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), tier: () => cloudPlanTier.tier(), maxParallel: () => cfg.burst?.maxParallel, hasRoom: () => engineMemory.laneHasRoom(), store, language: (threadId) => threadLanguage(threadId), startTurn: (botId, text, opts) => startTurn(botId, text, opts), stop: (botId, threadId, cause) => { void interruptDirectThread(botId, threadId, cause).catch(() => {}); }, threadBusy, opened: (threadId, parent) => threadStarters.set(threadId, openerFrom(parent)), origin: (run) => withPerson({ kind: "user", request: quoteInNote(run.task, 400) }, threadPersonKey(run.threadId)), approval: ownThreads.approvalFor, defaultModel: (bot, threadId) => burstDefaultModel({ own: store.taskByThread(bot.id, threadId)?.modelSelection ?? bot.modelSelection, catalog: (id) => registry.get(id)?.models, refused: (id) => quickFallback.refused(id), usable: (selection) => ownThreads.refusal(selection, bot) === null }), modelName, route: (notification) => teamMessages.route(notification, { routine: true }), announce: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); } });const teamMemory = new TeamMemory(join(DATA_DIR, "team-memory.json"));const teamMemoryRequests = createTeamMemoryRequests({ teamMemory, store, sectionKey: sectionContextKey, decide: (row) => appendDecision(DATA_DIR, row) });@@ -9069,13 +9069,13 @@ const { resolveAndSendTrust } = createTrustAnswers({ store, dataDir: DATA_DIR, tconst profileRequests = new ProfileRequestService({store,- autoApply: appliesDirectly,+ autoApply: setupAppliesDirectly,canPersist: proposalPersistence,validateTarget: chiefPeerTargetRule("profile"), browserProfile: { guards: { profiles: () => cfg.browserProfiles ?? [], heldBy: (session) => browserRuntime.heldBy(session), currentBrowserSession: (botId, profile) => currentBrowserSession(botId, profile), turnRunning: (botId) => Boolean(hasDirectDispatch(botId) || activeGroupTurnForBot(botId) || routines?.activeRunForBot(botId)) }, cleanup: { closeForBot: (botId) => browserLive.closeForBot(botId), forgetTemporaryBrowser } },});const modelRequests = new ModelRequestService({store,- autoApply: appliesDirectly,+ autoApply: setupAppliesDirectly,canPersist: proposalPersistence,validateTarget: chiefPeerTargetRule("default model"),validateModel: validateModelProposal,diff --git a/server/peer-roster.test.ts b/server/peer-roster.test.tsindex ef3f0457ab..cfe2ea3c50 100644--- a/server/peer-roster.test.ts+++ b/server/peer-roster.test.ts@@ -18,6 +18,7 @@ import {peerName,peerRosterSystemPrompt,peerStatus,+ setupChangeCovered,reachablePeers,reachRefusal,renderRoster,@@ -170,6 +171,36 @@ describe("a Chief changes the setup of every bot in its departments", () => {});});+describe("a setup change applies without the person's card only when everyone who sees the Chief sees the bot", () => {+ const chief = (visibility?: unknown) => ({ id: "chief", visibility });+ const target = (visibility?: unknown) => ({ id: "target", visibility });+ const ada = { people: ["[email protected]"] };+ const adaAndBo = { people: ["[email protected]", "[email protected]"] };++ it("covers the same audience, a wider one, and any bot for a Chief only admins see", () => {+ expect(setupChangeCovered(chief(), target())).toBe(true);+ expect(setupChangeCovered(chief(ada), target(ada))).toBe(true);+ expect(setupChangeCovered(chief(ada), target(adaAndBo))).toBe(true);+ expect(setupChangeCovered(chief(ada), target("everyone"))).toBe(true);+ expect(setupChangeCovered(chief(ada), target({ people: ["@example.test"] }))).toBe(true);+ expect(setupChangeCovered(chief("admins"), target(ada))).toBe(true);+ });++ it("does not cover a bot seen by fewer people than the Chief", () => {+ expect(setupChangeCovered(chief(), target("admins"))).toBe(false);+ expect(setupChangeCovered(chief(), target(ada))).toBe(false);+ expect(setupChangeCovered(chief(adaAndBo), target(ada))).toBe(false);+ expect(setupChangeCovered(chief(ada), target("admins"))).toBe(false);+ expect(setupChangeCovered(chief(ada), target({ people: ["[email protected]"] }))).toBe(false);+ });++ it("always covers the Chief's own setup, and never a missing bot", () => {+ expect(setupChangeCovered(chief(), { id: "chief", visibility: "admins" })).toBe(true);+ expect(setupChangeCovered(undefined, target())).toBe(false);+ expect(setupChangeCovered(chief(), null)).toBe(false);+ });+});+describe("reach across departments", () => {it("lets any bot reach any department while hidden bots and visibility still apply", () => {expect(canReach(self, fleet[4]!)).toBe(true);diff --git a/server/peer-roster.ts b/server/peer-roster.tsindex 79c8062414..8461f57b23 100644--- a/server/peer-roster.ts+++ b/server/peer-roster.ts@@ -1,5 +1,5 @@import { botOwner } from "../shared/bot-owner.ts";-import { sameAudience } from "./bot-visibility.ts"; import type { DefaultBotFields } from "../shared/default-bot.ts";+import { audienceWithin, sameAudience } from "./bot-visibility.ts"; import type { DefaultBotFields } from "../shared/default-bot.ts";import type { BotActivity } from "./store.ts";export interface RosterMember extends Pick<DefaultBotFields, "defaultBot"> {@@ -88,6 +88,14 @@ export function canManageSetup(from: RosterMember, target: RosterMember): boolea!ownedChief(from) && !ownedChief(target) && hasTeamAuthority(from, target.section);}+/** Security invariant: a setup change `from` makes to `target` applies without the person's card only when everyone who+ * can see `from` can also see `target`; otherwise a person using a Chief could get a bot they cannot see changed unseen. */+export function setupChangeCovered(from: Pick<RosterMember, "id" | "visibility"> | null | undefined,+ target: Pick<RosterMember, "id" | "visibility"> | null | undefined): boolean {+ if (!from || !target) return false;+ return from.id === target.id || audienceWithin(from.visibility, target.visibility);+}+/** Why `from` may not manage `target` when the department rule alone decided; otherwise null. */export function departmentRefusal(from: RosterMember, target: RosterMember): string | null {if (!canReach(from, target) || ownedChief(from) || ownedChief(target) || hasTeamAuthority(from, target.section)) return null;diff --git a/server/routes/internal-chief-team.test.ts b/server/routes/internal-chief-team.test.tsindex 96dcd1127f..e7222e8530 100644--- a/server/routes/internal-chief-team.test.ts+++ b/server/routes/internal-chief-team.test.ts@@ -122,6 +122,35 @@ describe("what a Chief of Staff reads about its team", () => {expect((body.bots as { id: string }[]).map((entry) => entry.id)).toEqual(["chief", "editor"]);});+ it("withholds the name, title and model of a bot some of the Chief's people can't see", async () => {+ const chief = bot("chief", { chiefOfStaff: true, section: "Work", managedSections: ["Editing"], visibility: { people: ["[email protected]", "[email protected]"] } });+ const { get } = await serve(chief, async () => TEAMS, {+ teams: ["", "Work", "Editing"],+ bots: [chief,+ bot("narrow", { section: "Editing", title: "Secret desk", visibility: { people: ["[email protected]"] } }),+ bot("wide", { section: "Editing", title: "Front desk" }),+ bot("admins", { section: "Work", title: "Payroll", visibility: "admins" })],+ });+ const { body } = await get("/api/internal/team-setup-catalog");+ expect(body.bots).toEqual([+ expect.objectContaining({ id: "chief", name: "chief" }),+ { id: "narrow", section: "Editing", chiefOfStaff: false, restricted: true },+ expect.objectContaining({ id: "wide", name: "wide", title: "Front desk", modelSelection: { instanceId: "claude", model: "sonnet" } }),+ { id: "admins", section: "Work", chiefOfStaff: false, restricted: true },+ ]);+ expect(JSON.stringify(body.bots)).not.toMatch(/Secret desk|Payroll/);+ });++ it("withholds nothing from a Chief only admins can see, since they see every bot", async () => {+ const chief = bot("chief", { chiefOfStaff: true, section: "Work", visibility: "admins" });+ const { get } = await serve(chief, async () => TEAMS, {+ teams: ["", "Work"], bots: [chief, bot("ada", { section: "Work", title: "Desk", visibility: { people: ["[email protected]"] } })],+ });+ expect((await get("/api/internal/team-setup-catalog")).body.bots).toEqual([+ expect.objectContaining({ id: "chief" }), expect.objectContaining({ id: "ada", name: "ada", title: "Desk" }),+ ]);+ });+it("leaves every other route to the next handler", async () => {const { get } = await serve(bot("chief", { chiefOfStaff: true }), async () => TEAMS);expect(await get("/api/internal/team-setup-requests")).toEqual({ status: 404, body: { from: "next routes" } });diff --git a/server/routes/internal-chief-team.ts b/server/routes/internal-chief-team.tsindex da857cfdd3..df7f8219a2 100644--- a/server/routes/internal-chief-team.ts+++ b/server/routes/internal-chief-team.ts@@ -1,4 +1,4 @@-import { canManageSetup, hasTeamAuthority, peerAllowed } from "../peer-roster.ts"; import { chiefLevel } from "../chief-level.ts";+import { canManageSetup, hasTeamAuthority, peerAllowed, setupChangeCovered } from "../peer-roster.ts"; import { chiefLevel } from "../chief-level.ts";import type { BotRecord } from "../store.ts";import { libraryTeamRoles } from "../team-library.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -48,10 +48,12 @@ export function createInternalChiefTeamRoutes(deps: {return json(res, 200, {teams: deps.teams().filter((name) => hasTeamAuthority(current, name)),bots: deps.bots().filter((bot) => !bot.hidden && hasTeamAuthority(current, bot.section) && (bot.id === current.id || peerAllowed(current, bot) || canManageSetup(current, bot)))- .map((bot) => ({ id: bot.id, name: bot.name, title: bot.title, section: bot.section ?? "", modelSelection: bot.modelSelection, chiefOfStaff: Boolean(bot.chiefOfStaff) })),+ .map((bot) => setupChangeCovered(current, bot)+ ? { id: bot.id, name: bot.name, title: bot.title, section: bot.section ?? "", modelSelection: bot.modelSelection, chiefOfStaff: Boolean(bot.chiefOfStaff) }+ : { id: bot.id, section: bot.section ?? "", chiefOfStaff: Boolean(bot.chiefOfStaff), restricted: true }),instances: instances.map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, displayName: instance.displayName,state: instance.snapshot.state, models: instance.models, effortLevels: instance.capabilities?.effortLevels ?? [] })),- scope: "Bot model defaults apply to groups and new threads; existing threads retain their models. Requested team setup applies immediately, and the person can undo it. Existing unauthorized teams remain outside this Chief's scope.",+ scope: "Bot model defaults apply to groups and new threads; existing threads retain their models. Requested team setup applies immediately, and the person can undo it. Existing unauthorized teams remain outside this Chief's scope. A restricted bot is seen by fewer people than this Chief, so its name, title and model are not listed, and a change to it always waits for the person's approval.",});};}diff --git a/server/team-setup-requests.test.ts b/server/team-setup-requests.test.tsindex d05587c702..31ae898d00 100644--- a/server/team-setup-requests.test.ts+++ b/server/team-setup-requests.test.ts@@ -452,6 +452,26 @@ describe("team setup that applies on its own", () => {expect(h.apply).toHaveBeenCalledTimes(1);});+ it("waits on the card at Full access when it changes or deletes a bot seen by fewer people than the Chief", async () => {+ const h = harness(); h.autoApply.mockReturnValue("full-access"); h.peer.visibility = { people: ["[email protected]"] };+ const response = await h.submit([{ action: "update", botId: h.peer.id, fields: { title: "Research lead" } }]);+ expect(response).toMatchObject({ applied: false, state: "pending" });+ expect(h.apply).not.toHaveBeenCalled();+ expect(h.messages[0].card?.options).toEqual(["Apply setup", "Cancel"]);+ expect(await h.resolve(response.requestId)).toMatchObject({ duplicate: false, result: { state: "applied" } });+ expect(h.peer.title).toBe("Research lead");+ const deletion = await h.service.submitDeletion({ botId: h.chief.id, threadId: h.chief.threadId, targetBotId: h.peer.id, reason: "User requested deletion" });+ expect(deletion).toMatchObject({ applied: false, state: "pending" });+ expect(h.deleteBot).not.toHaveBeenCalled();+ });++ it("applies at Full access a change to a bot everyone who sees the Chief also sees, and new bots", async () => {+ const h = harness(); h.autoApply.mockReturnValue("full-access");+ h.chief.visibility = { people: ["[email protected]"] }; h.peer.visibility = { people: ["[email protected]", "[email protected]"] };+ const response = await h.submit([specialist("Mira", "Work"), { action: "update", botId: h.peer.id, fields: { title: "Research lead" } }]);+ expect(response).toMatchObject({ applied: true, state: "applied" });+ });+it("deletes through the same guarded lifecycle without publishing a pending confirmation", async () => {const h = harness(); h.autoApply.mockReturnValue("full-access");const response = await h.service.submitDeletion({ botId: h.chief.id, threadId: h.chief.threadId, targetBotId: h.peer.id, reason: "User requested deletion" });diff --git a/server/team-setup-requests.ts b/server/team-setup-requests.tsindex 57844dafe6..4b1c2a2ebb 100644--- a/server/team-setup-requests.ts+++ b/server/team-setup-requests.ts@@ -12,7 +12,7 @@ import type { NewBotApproval } from "./new-bot-defaults.ts";import { harnessCapabilityLines, type DriverCapabilities } from "./harness-capabilities.ts";import { MAX_MCP_SERVERS, mcpServerNameError } from "./mcp-registry.ts";import { redactSecretsInText } from "./redact.ts"; import { chiefLevel } from "./chief-level.ts"; import { defaultBotRefusal } from "./default-bot.ts";-import type { BotRecord, OptionCardData } from "./store.ts"; import { outsideDepartmentReason } from "./peer-roster.ts";+import type { BotRecord, OptionCardData } from "./store.ts"; import { outsideDepartmentReason, setupChangeCovered } from "./peer-roster.ts";import type { TeamSetupFields, TeamSetupOperation, TeamSetupRequest, TeamSetupResult, TeamSetupUndo } from "../shared/team-setup.ts";const section = (value?: string) => value?.trim() || "";@@ -178,7 +178,7 @@ export class TeamSetupRequestService {private validate(request: TeamSetupRequest, confirming: boolean, immediate = false): void {const chief = this.chief(request.botId);if (!this.options.ownsThread(request.botId, request.threadId)) throw new TeamSetupError("The requesting conversation no longer exists", 409);- if (immediate && !this.options.autoApply?.(request.botId, request.threadId)) throw new TeamSetupError("This conversation can no longer apply team setup on its own; ask the owner", 409);+ if (immediate && !this.grant(request)) throw new TeamSetupError("This conversation can no longer apply team setup on its own; ask the owner", 409);if (confirming && !immediate && !this.options.store.messagesFor(request.threadId).some((message) => message.card?.requestId === request.requestId && !message.card.answered && !message.card.dismissed)) throw new TeamSetupError("This setup card is no longer pending", 409);if (confirming && teamSetupRevision(chief, this.requesterScope(request)) !== request.requesterRevision) throw new TeamSetupError("The Chief's settings changed. This setup was cancelled; review a new proposal.", 409);const existingTeams = new Set(this.options.teams().map(section));@@ -295,16 +295,20 @@ export class TeamSetupRequestService {propose(args: SetupArgs) { return this.card(this.prepare(args), args.from); }proposeDeletion(args: DeletionArgs) { return this.card(this.prepareDeletion(args), args.from); }- async submit(args: SetupArgs & SubmitAuthority) {- const grant = this.options.autoApply?.(args.botId, args.threadId) ?? null;- if (grant) return { ...await this.applyImmediately(this.prepare(args), args.from, args.canCommit), appliedBy: grant };- return { ...this.propose(args), applied: false, state: "pending" as const };+ async submit(args: SetupArgs & SubmitAuthority) { return this.submitted(this.prepare(args), args); }+ async submitDeletion(args: DeletionArgs & SubmitAuthority) { return this.submitted(this.prepareDeletion(args), args); }++ private async submitted(request: TeamSetupRequest, args: SubmitAuthority & { from?: RequestFrom }) {+ const grant = this.grant(request);+ if (grant) return { ...await this.applyImmediately(request, args.from, args.canCommit), appliedBy: grant };+ return { ...this.card(request, args.from), applied: false, state: "pending" as const };}- async submitDeletion(args: DeletionArgs & SubmitAuthority) {- const grant = this.options.autoApply?.(args.botId, args.threadId) ?? null;- if (grant) return { ...await this.applyImmediately(this.prepareDeletion(args), args.from, args.canCommit), appliedBy: grant };- return { ...this.proposeDeletion(args), applied: false, state: "pending" as const };+ private grant(request: TeamSetupRequest): DirectApply | null {+ const chief = this.options.store.bot(request.botId);+ const targets = [...request.operations.flatMap((operation) => operation.action === "update" ? [operation.botId] : []), ...(request.deletion ? [request.deletion.botId] : [])];+ if (!targets.every((id) => setupChangeCovered(chief, this.options.store.bot(id)))) return null;+ return this.options.autoApply?.(request.botId, request.threadId) ?? null;}private cardData(request: TeamSetupRequest, immediate = false): OptionCardData {