A desktop coding agent with free access to frontier models.
TypeScript
feat(swarm): board only for real swarms, procedure as an on-demand skill
Samrat Talukdar71628d9720b3
diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.tsindex 49e17ae6..a14ce1b0 100644--- a/apps/server/src/omnirush-runtime-config.test.ts+++ b/apps/server/src/omnirush-runtime-config.test.ts@@ -8,13 +8,22 @@ import {buildOmniRushRuntimeConfigObjectFromSnapshot,keepOmniRushRuntimeConfigFileFresh,omnirushRuntimeConfigFilePath,+ omnirushRuntimeSkillsDir,writeOmniRushRuntimeConfigFile,} from "./omnirush-runtime-config.js";import { writeGlobalRuntimeOpencodeConfig, writeRuntimeOpencodeConfig } from "./runtime-opencode-config-store.js";import { rulesFromPermissionConfig, winningRule } from "./effective-permissions.js";import { backendCatalogBody } from "./__fixtures__/omnirush-model-catalog.js";import { MAX_COLLECTOR_CHILD_SESSION_DEPTH } from "./workspace-collector.js";-import { OMNIRUSH_SUBAGENT_DEPTH, OMNIRUSH_SWARM_MAX_PER_TURN, OMNIRUSH_SWARM_MAX_RUNNING } from "./omnirush-swarm.js";+import {+ OMNIRUSH_SUBAGENT_DEPTH,+ OMNIRUSH_SWARM_MAX_PER_TURN,+ OMNIRUSH_SWARM_MAX_RUNNING,+ OMNIRUSH_SWARM_SKILL,+ OMNIRUSH_SWARM_SKILL_NAME,+ omnirushSwarmSkillMarkdown,+} from "./omnirush-swarm.js";+import { parseFrontmatter } from "./frontmatter.js";import {sanitizeOmniRushModelCatalog,writeOmniRushModelCatalog,@@ -341,7 +350,7 @@ describe("omnirush runtime config file", () => {const agents = parsed.agent as Record<string, { permission?: Record<string, unknown>; prompt?: string; mode?: string }>;// A sub-agent keeps the task tool only when its own rules mention it:// only general does; no global task rule reaches explore.- expect(agents.general).toEqual({ permission: { task: "allow" } });+ expect(agents.general).toEqual({ permission: { task: "allow", skill: { [OMNIRUSH_SWARM_SKILL_NAME]: "deny" } } });expect(agents.explore).toBeUndefined();expect((parsed.permission as Record<string, unknown>).task).toBeUndefined();expect(agents.omnirush?.permission?.task).toBeUndefined();@@ -349,14 +358,45 @@ describe("omnirush runtime config file", () => {}const prompt = (buildOmniRushRuntimeConfigObjectFromSnapshot({}).agent as Record<string, { prompt: string }>).omnirush!.prompt;expect(prompt).toContain("## Sub-agent swarms");- expect(prompt).toContain("Never start a swarm for a small or quick request.");- expect(prompt).toContain("`swarm.md` at the workspace root");- expect(prompt).toContain("There is no limit on how many run at once or start per turn");expect(OMNIRUSH_SWARM_MAX_RUNNING).toBe(Number.POSITIVE_INFINITY);expect(OMNIRUSH_SWARM_MAX_PER_TURN).toBe(Number.POSITIVE_INFINITY);expect(prompt.indexOf("## Sub-agent swarms")).toBeLessThan(prompt.indexOf("## Editing files"));});+ test("the always-on prompt only says when to load the swarm skill; the board procedure is the skill", () => {+ const prompt = (buildOmniRushRuntimeConfigObjectFromSnapshot({}).agent as Record<string, { prompt: string }>).omnirush!.prompt;+ const section = prompt.slice(prompt.indexOf("## Sub-agent swarms"), prompt.indexOf("## Editing files"));+ expect(section).toContain(`load the \`${OMNIRUSH_SWARM_SKILL_NAME}\` skill first`);+ expect(section).toContain("Before you start 3 or more sub-agents for one request");+ expect(section).toContain("at most 1-2 sub-agents with the task tool and no board");+ // No board mechanics on every request: no file name, no table, no layers.+ expect(prompt).not.toContain("swarm.md");+ expect(prompt).not.toContain("## Tasks");+ expect(section.length).toBeLessThan(400);+ // The skill carries the procedure, with the board under .omnirush/.+ expect(OMNIRUSH_SWARM_SKILL).toContain("`.omnirush/swarm.md`");+ expect(OMNIRUSH_SWARM_SKILL).toContain("never a file in the project root");+ expect(OMNIRUSH_SWARM_SKILL).toContain("For 1-2 sub-agents, stop here");+ expect(OMNIRUSH_SWARM_SKILL).toContain("`.omnirush/swarms/<YYYYMMDD-HHMMSS>.md`");+ expect(OMNIRUSH_SWARM_SKILL).toContain("There is no limit on how many run at once or start per turn");+ const { data, body } = parseFrontmatter(omnirushSwarmSkillMarkdown());+ expect(data.name).toBe(OMNIRUSH_SWARM_SKILL_NAME);+ expect(String(data.description)).toContain("Required before starting 3 or more sub-agents for one request");+ expect(body.trim()).toBe(OMNIRUSH_SWARM_SKILL);+ });++ test("the engine loads the swarm skill from the runtime folder", async () => {+ const { root, config } = await setup();+ const { path } = await writeOmniRushRuntimeConfigFile(config);+ const parsed = JSON.parse(await readFile(path, "utf8")) as { skills?: { paths?: string[] } };+ const skillsDir = omnirushRuntimeSkillsDir(config);+ expect(skillsDir.startsWith(root)).toBe(true);+ expect(parsed.skills?.paths).toEqual([skillsDir]);+ expect(await readFile(join(skillsDir, OMNIRUSH_SWARM_SKILL_NAME, "SKILL.md"), "utf8")).toBe(omnirushSwarmSkillMarkdown());+ // Without a server config (specs, previews) nothing points at a folder.+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}).skills).toBeUndefined();+ });+test("keepOmniRushRuntimeConfigFileFresh rewrites the file on ENGINE_GLOBAL writes", async () => {const { config } = await setup();await writeOmniRushRuntimeConfigFile(config);diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.tsindex 019f2f67..618f88e0 100644--- a/apps/server/src/omnirush-runtime-config.ts+++ b/apps/server/src/omnirush-runtime-config.ts@@ -46,7 +46,7 @@ import {import { CONNECT_MCP_SERVER_NAME_PREFIX } from "./connect-mcp-server-catalog.js";import { isOmniRushUiMcpRegistryEntry } from "./omnirush-ui-mcp-command.js";import { OMNIRUSH_AGENT_PROMPT } from "./omnirush-agent-prompt.js";-import { OMNIRUSH_SUBAGENT_DEPTH } from "./omnirush-swarm.js";+import { OMNIRUSH_SUBAGENT_DEPTH, OMNIRUSH_SWARM_SKILL_NAME, omnirushSwarmSkillMarkdown } from "./omnirush-swarm.js";import {builtinOmniRushModelCatalog,engineModelsFromCatalog,@@ -131,14 +131,37 @@ export async function buildOmniRushRuntimeConfigObject(internalGateway,process.env,internalGateway && config ? await readOmniRushModelCatalog(config) : undefined,+ config ? omnirushRuntimeSkillsDir(config) : undefined,);}+/**+ * The folder of omnirush.ai's own on-demand skills (the omnirush-swarm skill),+ * handed to the engine through `skills.paths`. It lives beside the runtime+ * config file, outside every workspace, so it never shows up in a project.+ */+export function omnirushRuntimeSkillsDir(config: ServerConfig): string {+ return join(runtimeStorageDir(config), "skills");+}++/** Writes the built-in skills the config points at; unchanged files are left alone. */+async function writeOmniRushRuntimeSkills(config: ServerConfig): Promise<void> {+ const directory = join(omnirushRuntimeSkillsDir(config), OMNIRUSH_SWARM_SKILL_NAME);+ const path = join(directory, "SKILL.md");+ const content = omnirushSwarmSkillMarkdown();+ if ((await readFile(path, "utf8").catch(() => undefined)) === content) return;+ await mkdir(directory, { recursive: true });+ const tmp = `${path}.${randomUUID()}.tmp`;+ await writeFile(tmp, content, "utf8");+ await rename(tmp, path);+}+export function buildOmniRushRuntimeConfigObjectFromSnapshot(runtimeConfig: RuntimeOpencodeConfig,internalGateway?: InternalGatewayRuntime,env: NodeJS.ProcessEnv = process.env,catalog: OmniRushModelCatalog = builtinOmniRushModelCatalog(),+ skillsDir?: string,): Record<string, unknown> {const disabledProviders = runtimeDisabledProviderList(runtimeConfig);// OMNIRUSH_APPROVALS in the server environment wins over the persisted setting.@@ -160,6 +183,8 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(...(runtimeConfig.managedPolicy.allowZenModel !== false ? ["opencode"] : []),] } : {}),permission: { ...engineConfig.permission, ...permissions },+ // omnirush.ai's own on-demand skills (the swarm procedure).+ ...(skillsDir ? { skills: { paths: [skillsDir] } } : {}),default_agent: runtimeConfig.default_agent ?? "omnirush",// Sub-agent swarms: sub-agents may delegate again, up to this many layers// below the main session (the engine's default of 1 forbids nesting).@@ -187,8 +212,11 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(// The engine hides the task tool from a sub-agent unless the sub-agent's// own permissions mention `task`. Only the general sub-agent gets it;// explore stays read-only (a global task rule would reach every agent).+ // Sub-agents never start a swarm (a running swarm's sub-agents get the+ // board note from the swarm plugin), so the swarm skill is not listed+ // in their prompts.general: {- permission: { task: "allow" },+ permission: { task: "allow", skill: { [OMNIRUSH_SWARM_SKILL_NAME]: "deny" } },},},plugin: [@@ -266,6 +294,9 @@ export async function writeOmniRushRuntimeConfigFile(): Promise<OmniRushRuntimeConfigWriteResult> {const path = omnirushRuntimeConfigFilePath(config);const job = async () => {+ // The config names the skills folder: write it first, so the engine+ // never loads a config whose built-in skill is missing.+ await writeOmniRushRuntimeSkills(config);const content = await buildOmniRushRuntimeConfig(config);const current = await readFile(path, "utf8").catch(() => undefined);if (current === content) return { path, changed: false };diff --git a/apps/server/src/omnirush-swarm.ts b/apps/server/src/omnirush-swarm.tsindex 8ed5c469..bdc9ae1c 100644--- a/apps/server/src/omnirush-swarm.ts+++ b/apps/server/src/omnirush-swarm.ts@@ -3,12 +3,14 @@* injected engine config (omnirush-runtime-config.ts), the swarm engine* plugin (opencode-plugins/omnirush-swarm.ts) and the collector.*- * A swarm is the main agent delegating to sub-agents that may delegate- * again, every level coordinating through one `swarm.md` board at the- * workspace root. The bundled engine (opencode 1.18.32) counts sub-agent- * layers from the main session through `parentID` and refuses the task tool- * at `subagent_depth`; it has no fan-out limit of its own, so the plugin adds- * one.+ * A swarm is the main agent running 3 or more sub-agents in parallel (or+ * the user asking for one), sub-agents that may delegate again, every level+ * coordinating through one `.omnirush/swarm.md` board. Only a swarm gets a+ * board: the procedure is the on-demand omnirush-swarm skill, and the+ * always-on prompt only says when to load it. The bundled engine (opencode+ * 1.18.32) counts sub-agent layers from the main session through `parentID`+ * and refuses the task tool at `subagent_depth`; it has no fan-out limit of+ * its own, so the plugin adds one.** Kept dependency-free: the engine plugin bundle imports it.*/@@ -43,34 +45,82 @@ export const SUBAGENT_ROOT_SESSION_HEADER = "x-omnirush-subagent-root";/** The collector trace event recording that a sub-agent ran on the main model instead of the picked one. */export const SUBAGENT_MODEL_FALLBACK_TRACE = "subagent.model_fallback";-/** The coordination board, relative to the workspace root. */-export const OMNIRUSH_SWARM_FILE = "swarm.md";+/**+ * The folder omnirush.ai keeps its own workspace files in, relative to the+ * workspace root. Only the board and its archive are kept out of git there+ * (OMNIRUSH_SWARM_GITIGNORE_LINES); anything else a user puts in it is theirs.+ */+export const OMNIRUSH_WORKSPACE_DIR = ".omnirush";++/**+ * The coordination board of a running swarm, relative to the workspace root.+ * It lives in `.omnirush/`, never in the project root: a `swarm.md` at the+ * root is a user file (or one an older version left) and is left alone.+ */+export const OMNIRUSH_SWARM_FILE = `${OMNIRUSH_WORKSPACE_DIR}/swarm.md`;++/** Where finished boards go (`<stamp>.md`), relative to the workspace root. */+export const OMNIRUSH_SWARM_ARCHIVE_DIR = `${OMNIRUSH_WORKSPACE_DIR}/swarms`;/**- * The main agent's swarm instructions (part of OMNIRUSH_AGENT_PROMPT). A- * swarm is the model's call for large work that splits into independent- * parts; small prompts are answered directly.+ * The `.omnirush/.gitignore` entries that keep the board, its archive and+ * that file itself out of git status and out of the collector's snapshots+ * (the board still reaches the trace through the tool calls that write it).+ */+export const OMNIRUSH_SWARM_GITIGNORE_LINES = ["/.gitignore", "/swarm.md", "/swarms/"] as const;++/** Fewest parallel sub-agents that make a swarm (fewer never get a board). */+export const OMNIRUSH_SWARM_MIN_AGENTS = 3;++/** The on-demand skill that carries the swarm procedure. */+export const OMNIRUSH_SWARM_SKILL_NAME = "omnirush-swarm";++export const OMNIRUSH_SWARM_SKILL_DESCRIPTION = `Required before starting ${OMNIRUSH_SWARM_MIN_AGENTS} or more sub-agents for one request (a swarm, or the user asks for several agents): the shared-board procedure. Never for 1-2 sub-agents or a small request.`;++/**+ * The main agent's always-on swarm text (part of OMNIRUSH_AGENT_PROMPT). The+ * procedure itself is the omnirush-swarm skill, loaded only for a swarm.*/export const OMNIRUSH_SWARM_PROMPT = `## Sub-agent swarms-Most requests need no sub-agents, or one or two task calls. Run a swarm only when the user asks for one, or when the work is large and splits into several independent parts that each take real effort (a multi-module change, a broad investigation, parallel research with a review pass). Never start a swarm for a small or quick request.+Before you start ${OMNIRUSH_SWARM_MIN_AGENTS} or more sub-agents for one request (large work that splits into ${OMNIRUSH_SWARM_MIN_AGENTS}+ independent parts, or the user asks for a swarm or for several agents), load the \`${OMNIRUSH_SWARM_SKILL_NAME}\` skill first and follow it. Otherwise answer directly, or use at most 1-2 sub-agents with the task tool and no board or coordination file.`;++/** The body of the omnirush-swarm skill (without frontmatter). */+export const OMNIRUSH_SWARM_SKILL = `# Sub-agent swarm++Use this only for a real swarm: ${OMNIRUSH_SWARM_MIN_AGENTS} or more sub-agents working in parallel, or the user asked for a swarm or for several agents. For 1-2 sub-agents, stop here: call the task tool directly and do not create or touch a board.++The board is \`${OMNIRUSH_SWARM_FILE}\` in the workspace, never a file in the project root. omnirush.ai keeps \`${OMNIRUSH_SWARM_FILE}\` and \`${OMNIRUSH_SWARM_ARCHIVE_DIR}/\` out of git. Ignore any \`swarm.md\` in the project root: it is not this swarm's board.-A swarm is coordinated through \`${OMNIRUSH_SWARM_FILE}\` at the workspace root:-1. Before delegating, create or update \`${OMNIRUSH_SWARM_FILE}\` with: \`# Goal\` (one paragraph), \`## Tasks\` (a table: id, task, owner, status, result; ids like T1, T2, and T1.1 for a sub-task of T1; status is todo, running, done or blocked), \`## Findings\` (shared facts, one bullet each, with the task id), \`## Decisions\` (choices every agent must follow).-2. Give each sub-agent one task id. Its task-tool prompt names the id, the task, and says: read \`${OMNIRUSH_SWARM_FILE}\` first; set your row to running; when done, set it to done with a one-line result and append your findings under your id; edit only your own rows and sections; report back briefly.-3. Sub-agents may split their own task: they add sub-task rows (T1.1, T1.2) and give the same instructions to their own sub-agents. Sub-agents nest at most ${OMNIRUSH_SUBAGENT_DEPTH} layers deep. There is no limit on how many run at once or start per turn: start as many as the work needs, and no more.-4. Launch independent tasks in parallel (several task calls in one message); give tasks that edit the same files to one agent.-5. When every task is done, read \`${OMNIRUSH_SWARM_FILE}\`, check and merge the results, record the outcome under \`## Decisions\` or a final \`## Summary\`, and answer the user. Keep \`${OMNIRUSH_SWARM_FILE}\` in the workspace unless the user asks you to remove it.`;+1. If \`${OMNIRUSH_SWARM_FILE}\` already exists, it is left over from an earlier swarm: move it to \`${OMNIRUSH_SWARM_ARCHIVE_DIR}/<YYYYMMDD-HHMMSS>.md\` and start a fresh board.+2. Before delegating, create \`${OMNIRUSH_SWARM_FILE}\` with: \`# Goal\` (one paragraph), \`## Tasks\` (a table: id, task, owner, status, result; ids like T1, T2, and T1.1 for a sub-task of T1; status is todo, running, done or blocked), \`## Findings\` (shared facts, one bullet each, with the task id), \`## Decisions\` (choices every agent must follow).+3. Give each sub-agent one task id. Its task-tool prompt names the id, the task, and says: read \`${OMNIRUSH_SWARM_FILE}\` first; set your row to running; when done, set it to done with a one-line result and append your findings under your id; edit only your own rows and sections; report back briefly.+4. Sub-agents may split their own task: they add sub-task rows (T1.1, T1.2) and give the same instructions to their own sub-agents. Sub-agents nest at most ${OMNIRUSH_SUBAGENT_DEPTH} layers deep. There is no limit on how many run at once or start per turn: start as many as the work needs, and no more.+5. Launch independent tasks in parallel (several task calls in one message); give tasks that edit the same files to one agent.+6. When every task is done, read \`${OMNIRUSH_SWARM_FILE}\`, check and merge the results, and answer the user.+7. Then archive the board: move \`${OMNIRUSH_SWARM_FILE}\` to \`${OMNIRUSH_SWARM_ARCHIVE_DIR}/<YYYYMMDD-HHMMSS>.md\` (create the folder if needed), so no later request picks it up. If the user asked to keep the board, name the archived path in your answer.`;++/** The omnirush-swarm skill's SKILL.md. */+export function omnirushSwarmSkillMarkdown(): string {+ return `---\nname: ${OMNIRUSH_SWARM_SKILL_NAME}\ndescription: ${JSON.stringify(OMNIRUSH_SWARM_SKILL_DESCRIPTION)}\n---\n\n${OMNIRUSH_SWARM_SKILL}\n`;+}++/** A board archive name for `date`: `.omnirush/swarms/YYYYMMDD-HHMMSS.md` (UTC). */+export function omnirushSwarmArchiveName(date: Date = new Date()): string {+ const stamp = date.toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);+ return `${OMNIRUSH_SWARM_ARCHIVE_DIR}/${stamp}.md`;+}/**- * System text for a sub-agent session while `swarm.md` exists: every layer- * follows the board even when a prompt forgot to say so.+ * System text for a sub-agent session of a running swarm (its main session+ * started one and the board exists): every layer follows the board even when+ * a prompt forgot to say so.*/export function omnirushSwarmSubagentNote(depth: number): string {const canDelegate = depth < OMNIRUSH_SUBAGENT_DEPTH;return [- `You are a sub-agent (layer ${depth} of at most ${OMNIRUSH_SUBAGENT_DEPTH}) in a swarm coordinated through \`${OMNIRUSH_SWARM_FILE}\` at the workspace root.`,- `Read \`${OMNIRUSH_SWARM_FILE}\` before you start. Find your task id in your prompt (or the row that matches your task), set its status to running, and when you finish set it to done with a one-line result and append your findings under your task id. Edit only your own rows and sections, and re-read the file right before each edit because other agents write to it too.`,+ `You are a sub-agent (layer ${depth} of at most ${OMNIRUSH_SUBAGENT_DEPTH}) in a swarm coordinated through \`${OMNIRUSH_SWARM_FILE}\` in the workspace.`,+ `Read \`${OMNIRUSH_SWARM_FILE}\` before you start. Find your task id in your prompt (or the row that matches your task), set its status to running, and when you finish set it to done with a one-line result and append your findings under your task id. Edit only your own rows and sections, and re-read the file right before each edit because other agents write to it too. Do not move or archive the board: the main agent does that.`,canDelegate? "If your task splits into independent parts that each take real effort, you may delegate them with the task tool: add sub-task rows (for example T1.1, T1.2) first and give each sub-agent the same instructions. Otherwise do the work yourself.": "You cannot delegate further: do the work yourself.",diff --git a/apps/server/src/opencode-plugins/omnirush-swarm.test.ts b/apps/server/src/opencode-plugins/omnirush-swarm.test.tsindex 6ca0ca2d..f02ff2e2 100644--- a/apps/server/src/opencode-plugins/omnirush-swarm.test.ts+++ b/apps/server/src/opencode-plugins/omnirush-swarm.test.ts@@ -1,12 +1,15 @@import { afterEach, describe, expect, test } from "bun:test";-import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";+import { existsSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { OmniRushSwarm } from "./omnirush-swarm.js";import {OMNIRUSH_SUBAGENT_DEPTH,+ OMNIRUSH_SWARM_FILE,OMNIRUSH_SWARM_MAX_PER_TURN,OMNIRUSH_SWARM_MAX_RUNNING,+ OMNIRUSH_SWARM_SKILL_NAME,} from "../omnirush-swarm.js";type Hooks = Awaited<ReturnType<typeof OmniRushSwarm>>;@@ -37,6 +40,19 @@ const created = (hooks: Hooks, id: string, parentID?: string) =>hooks.event({ event: { type: "session.created", properties: { info: { id, ...(parentID ? { parentID } : {}) } } } });const task = (hooks: Hooks, sessionID: string, callID: string) =>hooks["tool.execute.before"]({ tool: "task", sessionID, callID });+const loadSwarmSkill = (hooks: Hooks, sessionID: string) =>+ hooks["tool.execute.before"]({ tool: "skill", sessionID, callID: `skill_${sessionID}` }, { args: { name: OMNIRUSH_SWARM_SKILL_NAME } });+const idle = (hooks: Hooks, sessionID: string) =>+ hooks.event({ event: { type: "session.status", properties: { sessionID, status: { type: "idle" } } } });+const writeBoard = async (directory: string, text = "# Goal\n") => {+ await mkdir(join(directory, ".omnirush"), { recursive: true });+ await writeFile(join(directory, OMNIRUSH_SWARM_FILE), text);+};+const systemOf = (hooks: Hooks) => async (sessionID: string) => {+ const output = { system: ["base"] };+ await hooks["experimental.chat.system.transform"]({ sessionID }, output);+ return output.system.slice(1).join("\n");+};const partDone = (hooks: Hooks, callID: string, status = "completed") =>hooks.event({ event: { type: "message.part.updated", properties: { part: { type: "tool", tool: "task", callID, state: { status } } } } });@@ -64,29 +80,95 @@ describe("omnirush swarm plugin", () => {expect(reads.filter((id) => id === "ses_a")).toHaveLength(1);});- test("reminds sub-agents, not the main session, of swarm.md while it exists", async () => {+ test("reminds sub-agents of a running swarm, not the main session, of the board while it exists", async () => {const { hooks, directory } = await setup();await created(hooks, "ses_main");await created(hooks, "ses_child", "ses_main");await created(hooks, "ses_grand", "ses_child");await created(hooks, "ses_great", "ses_grand");- const system = async (sessionID: string) => {- const output = { system: ["base"] };- await hooks["experimental.chat.system.transform"]({ sessionID }, output);- return output.system.slice(1).join("\n");- };+ const system = systemOf(hooks);+ await loadSwarmSkill(hooks, "ses_main");expect(await system("ses_child")).toBe("");- await writeFile(join(directory, "swarm.md"), "# Goal\n");+ await writeBoard(directory);expect(await system("ses_main")).toBe("");const child = await system("ses_child");expect(child).toContain("layer 1 of at most 3");- expect(child).toContain("Read `swarm.md` before you start");+ expect(child).toContain("Read `.omnirush/swarm.md` before you start");expect(child).toContain("you may delegate");expect(await system("ses_grand")).toContain("layer 2 of at most 3");const great = await system("ses_great");expect(great).toContain(`layer ${OMNIRUSH_SUBAGENT_DEPTH} of at most ${OMNIRUSH_SUBAGENT_DEPTH}`);expect(great).toContain("You cannot delegate further");});++ test("1-2 plain task calls get no board note, whatever board files exist", async () => {+ const { hooks, directory } = await setup();+ await created(hooks, "ses_main");+ await created(hooks, "ses_child", "ses_main");+ await task(hooks, "ses_main", "c1");+ // A root swarm.md from an older version and a board no swarm of this session started.+ await writeFile(join(directory, "swarm.md"), "# Goal\nold\n");+ await writeBoard(directory);+ expect(await systemOf(hooks)("ses_child")).toBe("");+ });++ test("writing the board marks the swarm too, and keeps the board out of git", async () => {+ const { hooks, directory } = await setup();+ await created(hooks, "ses_main");+ await created(hooks, "ses_child", "ses_main");+ await hooks["tool.execute.before"]({ tool: "write", sessionID: "ses_main", callID: "w1" }, { args: { filePath: join(directory, ".omnirush", "swarm.md"), content: "# Goal\n" } });+ await writeBoard(directory);+ expect(await systemOf(hooks)("ses_child")).toContain("`.omnirush/swarm.md`");+ expect(await readFile(join(directory, ".omnirush", ".gitignore"), "utf8")).toContain("/swarm.md\n/swarms/\n");+ });++ test("a user's own .omnirush/.gitignore only gains the board lines", async () => {+ const { hooks, directory } = await setup();+ await created(hooks, "ses_main");+ await mkdir(join(directory, ".omnirush"), { recursive: true });+ await writeFile(join(directory, ".omnirush", ".gitignore"), "cache/");+ await loadSwarmSkill(hooks, "ses_main");+ expect(await readFile(join(directory, ".omnirush", ".gitignore"), "utf8")).toBe("cache/\n/swarm.md\n/swarms/\n");+ await created(hooks, "ses_other");+ await loadSwarmSkill(hooks, "ses_other");+ expect(await readFile(join(directory, ".omnirush", ".gitignore"), "utf8")).toBe("cache/\n/swarm.md\n/swarms/\n");+ });++ test("a stale board is archived when a swarm starts, and the board is archived when the swarm's main session goes idle", async () => {+ const { hooks, directory } = await setup();+ await created(hooks, "ses_old");+ await created(hooks, "ses_main");+ await created(hooks, "ses_child", "ses_main");+ await writeBoard(directory, "# Goal\nstale\n");+ await loadSwarmSkill(hooks, "ses_main");+ expect(existsSync(join(directory, OMNIRUSH_SWARM_FILE))).toBe(false);+ const archived = await readdir(join(directory, ".omnirush", "swarms"));+ expect(archived).toHaveLength(1);+ expect(archived[0]).toMatch(/^\d{8}-\d{6}\.md$/);+ await writeBoard(directory, "# Goal\nlive\n");+ // Another session going idle leaves the running swarm's board alone.+ await idle(hooks, "ses_old");+ await idle(hooks, "ses_child");+ expect(existsSync(join(directory, OMNIRUSH_SWARM_FILE))).toBe(true);+ await idle(hooks, "ses_main");+ expect(existsSync(join(directory, OMNIRUSH_SWARM_FILE))).toBe(false);+ const after = await readdir(join(directory, ".omnirush", "swarms"));+ expect(after).toHaveLength(2);+ const contents = await Promise.all(after.map((name) => readFile(join(directory, ".omnirush", "swarms", name), "utf8")));+ expect(contents.some((text) => text.includes("live"))).toBe(true);+ // The swarm is over: its sub-agents hear of no board, and a later small request finds none.+ await writeBoard(directory);+ expect(await systemOf(hooks)("ses_child")).toBe("");+ });++ test("the root swarm.md of older versions is never moved", async () => {+ const { hooks, directory } = await setup();+ await created(hooks, "ses_main");+ await writeFile(join(directory, "swarm.md"), "# Goal\nuser file\n");+ await loadSwarmSkill(hooks, "ses_main");+ await idle(hooks, "ses_main");+ expect(await readFile(join(directory, "swarm.md"), "utf8")).toBe("# Goal\nuser file\n");+ });});describe("omnirush swarm plugin: sub-agent model and effort", () => {diff --git a/apps/server/src/opencode-plugins/omnirush-swarm.ts b/apps/server/src/opencode-plugins/omnirush-swarm.tsindex cd4289d5..a89ec9e0 100644--- a/apps/server/src/opencode-plugins/omnirush-swarm.ts+++ b/apps/server/src/opencode-plugins/omnirush-swarm.ts@@ -10,9 +10,16 @@* - at most OMNIRUSH_SWARM_MAX_PER_TURN start during one main-session turn.** A task call over a limit fails before it creates a session, with a message- * telling the model to do the work itself. It also reminds sub-agent- * sessions of the `swarm.md` board while that file exists, so every layer- * reads and updates it.+ * telling the model to do the work itself.+ *+ * Swarm board: a main session runs a swarm once its tree loads the+ * omnirush-swarm skill or writes the board (`.omnirush/swarm.md`). Only then+ * are its sub-agents reminded of the board (while it exists), so 1-2 plain+ * task calls never hear of one. The plugin keeps the board out of git+ * (`.omnirush/.gitignore`), moves a board left by an earlier swarm to+ * `.omnirush/swarms/` when a new one starts, and archives the board there+ * when the swarm's main session goes idle if the main agent did not, so a+ * later request never finds a stale board.** Sub-agent model and effort: every prompt of a sub-agent session (any* layer) is resolved against the app's sub-agent setting by the OmniRush.ai@@ -31,12 +38,18 @@* bounded maps; nothing is persisted.*/import { existsSync } from "node:fs";+import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises";import { join } from "node:path";import {OMNIRUSH_SUBAGENT_DEPTH,+ OMNIRUSH_SWARM_GITIGNORE_LINES,+ OMNIRUSH_SWARM_SKILL_NAME,+ OMNIRUSH_WORKSPACE_DIR,+ omnirushSwarmArchiveName,SUBAGENT_FALLBACK_EFFORT_HEADER,SUBAGENT_FALLBACK_MODEL_HEADER,SUBAGENT_ROOT_SESSION_HEADER,+ OMNIRUSH_SWARM_ARCHIVE_DIR,OMNIRUSH_SWARM_FILE,OMNIRUSH_SWARM_MAX_PER_TURN,OMNIRUSH_SWARM_MAX_RUNNING,@@ -163,6 +176,50 @@ function remember<K, V>(map: Map<K, V>, key: K, value: V, max: number): void {}}+/** A workspace-relative path with `/` separators, as a file-writing tool argument names it. */+function normalizedPath(value: unknown): string {+ return typeof value === "string" ? value.replace(/\\/g, "/") : "";+}++/** Whether a file-writing tool call (or a shell command) touches the swarm board. */+function writesBoard(tool: string, args: unknown): boolean {+ if (!record(args)) return false;+ if (tool === "write" || tool === "edit" || tool === "multiedit") {+ const path = normalizedPath(args.filePath);+ return path === OMNIRUSH_SWARM_FILE || path.endsWith(`/${OMNIRUSH_SWARM_FILE}`);+ }+ if (tool === "apply_patch") return normalizedPath(args.patchText).includes(OMNIRUSH_SWARM_FILE);+ if (tool === "bash") return normalizedPath(args.command).includes(OMNIRUSH_SWARM_FILE);+ return false;+}++/** Keeps the board and its archive out of git; a user's own `.omnirush/.gitignore` only gains the missing lines. */+async function ignoreBoard(directory: string): Promise<void> {+ const folder = join(directory, OMNIRUSH_WORKSPACE_DIR);+ const file = join(folder, ".gitignore");+ await mkdir(folder, { recursive: true });+ const current = await readFile(file, "utf8").catch(() => null);+ if (current === null) {+ await writeFile(file, `# omnirush.ai: the swarm board and its archive stay out of git\n${OMNIRUSH_SWARM_GITIGNORE_LINES.join("\n")}\n`, "utf8");+ return;+ }+ const lines = new Set(current.split(/\r?\n/).map((line) => line.trim()));+ // A user's own file is theirs to track: only the board lines are added.+ const missing = OMNIRUSH_SWARM_GITIGNORE_LINES.filter((line) => line !== "/.gitignore" && !lines.has(line));+ if (missing.length) await appendFile(file, `${current.endsWith("\n") || !current ? "" : "\n"}${missing.join("\n")}\n`, "utf8");+}++/** Moves the board to `.omnirush/swarms/<stamp>.md`; no board, no move. */+async function archiveBoard(directory: string): Promise<string | null> {+ const board = join(directory, OMNIRUSH_SWARM_FILE);+ if (!existsSync(board)) return null;+ await mkdir(join(directory, OMNIRUSH_SWARM_ARCHIVE_DIR), { recursive: true });+ let name = omnirushSwarmArchiveName();+ for (let n = 2; existsSync(join(directory, name)); n += 1) name = omnirushSwarmArchiveName().replace(/\.md$/, `-${n}.md`);+ await rename(board, join(directory, name));+ return name;+}+// Only export the factory: the engine treats every export as a plugin.export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?: string }) => {/** Session id -> parent id (null for a main session). */@@ -179,6 +236,8 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:const notes = new Map<string, { model: ModelChoice; fallback: Resolution["fallback"] | null; at: number }>();/** Sub-agent sessions whose title already carries the fallback note. */const titled = new Set<string>();+ /** Main sessions running a swarm: their tree loaded the swarm skill or wrote the board. */+ const swarms = new Set<string>();const learn = (info: unknown) => {if (!record(info) || typeof info.id !== "string" || !info.id) return;@@ -283,6 +342,34 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:trees.get(root)?.running.delete(callId);};+ /**+ * Marks the main session above `sessionId` as running a swarm. A board+ * left by an earlier swarm is archived first (unless another main session's+ * swarm is still running on it), and the board folder is kept out of git.+ */+ const startSwarm = async (sessionId: string, archiveStale: boolean) => {+ const directory = input?.directory;+ if (!directory) return;+ const { root } = await locate(sessionId);+ if (swarms.has(root)) return;+ try {+ if (archiveStale && swarms.size === 0) await archiveBoard(directory);+ await ignoreBoard(directory);+ } catch {+ // Best effort: the swarm runs either way.+ }+ swarms.add(root);+ if (swarms.size > MAX_TRACKED_TREES) swarms.delete(swarms.values().next().value as string);+ };++ /** A swarm's main session went idle: its board is archived if the main agent left it. */+ const endSwarm = async (root: string) => {+ if (!swarms.delete(root)) return;+ const directory = input?.directory;+ if (!directory || swarms.size > 0) return;+ await archiveBoard(directory).catch(() => null);+ };+return {event: async ({ event }: { event: EngineEvent }) => {const properties = record(event?.properties) ? event.properties : {};@@ -298,6 +385,7 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:mainModels.delete(properties.info.id);overrides.delete(properties.info.id);notes.delete(properties.info.id);+ swarms.delete(properties.info.id);}return;case "message.part.updated": {@@ -311,6 +399,7 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:// A main session that went idle has no running sub-agents left.const status = record(properties.status) ? properties.status.type : undefined;if (status !== "idle" || typeof properties.sessionID !== "string") return;+ await endSwarm(properties.sessionID);const tree = trees.get(properties.sessionID);if (!tree) return;for (const callId of tree.running.keys()) calls.delete(callId);@@ -353,8 +442,17 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:output.headers[SUBAGENT_ROOT_SESSION_HEADER] = override.root;},- "tool.execute.before": async (call: { tool: string; sessionID: string; callID: string }) => {- if (call?.tool !== "task" || typeof call.sessionID !== "string") return;+ "tool.execute.before": async (call: { tool: string; sessionID: string; callID: string }, output?: { args?: unknown }) => {+ if (typeof call?.sessionID !== "string") return;+ if (call.tool === "skill") {+ if (record(output?.args) && output.args.name === OMNIRUSH_SWARM_SKILL_NAME) await startSwarm(call.sessionID, true);+ return;+ }+ if (writesBoard(call.tool, output?.args)) {+ await startSwarm(call.sessionID, false);+ return;+ }+ if (call.tool !== "task") return;const { root } = await locate(call.sessionID);const tree = treeOf(root);const now = Date.now();@@ -426,8 +524,9 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:const directory = input?.directory;if (!directory || typeof request?.sessionID !== "string" || !Array.isArray(output?.system)) return;if ((await parentOf(request.sessionID)) === null) return;- if (!existsSync(join(directory, OMNIRUSH_SWARM_FILE))) return;- const { depth } = await locate(request.sessionID);+ const { root, depth } = await locate(request.sessionID);+ // Only the sub-agents of a running swarm, and only while its board exists.+ if (!swarms.has(root) || !existsSync(join(directory, OMNIRUSH_SWARM_FILE))) return;output.system.push(omnirushSwarmSubagentNote(Math.min(Math.max(depth, 1), OMNIRUSH_SUBAGENT_DEPTH)));},};