From 9b6bccc996807c15fd25d1439f46d22de9696423 Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:51:31 +0300 Subject: [PATCH 01/17] squad: register agents through the plugin API from squad.json (#85) The roster lives in squad.json (src/squad-store.js); src/squad-agents.js registers its agents with an early and a late agent transform. No agent file is written, pruned or migrated. Legacy generated files are imported once and hidden; a hand-authored agent with a roster id is left alone. Unit tests run against a throwaway config dir (tests/setup-isolation.js). Co-Authored-By: Claude Opus 5.5 --- .opencode/lib/runtime.js | 114 +++--- .opencode/lib/squad.js | 193 +++++++-- src/fs-atomic.js | 2 +- src/model-data.js | 88 +---- src/squad-agents.js | 140 +++++++ src/squad-apply.js | 631 +++++------------------------- src/squad-store.js | 99 +++++ src/workers.js | 137 +------ tests/guard-host.test.js | 18 +- tests/model-data.test.js | 83 +--- tests/plugin-entry.test.js | 109 ++++-- tests/prompt-inject.test.js | 59 +-- tests/regress-squad-files.test.js | 492 ----------------------- tests/runtime-model-data.test.js | 107 +++-- tests/setup-isolation.js | 23 ++ tests/squad-agents.test.js | 147 +++++++ tests/squad-apply.test.js | 434 ++++++-------------- tests/squad-store.test.js | 63 +++ tests/workers.test.js | 177 ++------- vitest.config.js | 2 + 20 files changed, 1152 insertions(+), 1966 deletions(-) create mode 100644 src/squad-agents.js create mode 100644 src/squad-store.js delete mode 100644 tests/regress-squad-files.test.js create mode 100644 tests/setup-isolation.js create mode 100644 tests/squad-agents.test.js create mode 100644 tests/squad-store.test.js diff --git a/.opencode/lib/runtime.js b/.opencode/lib/runtime.js index 438bd27..704a89e 100644 --- a/.opencode/lib/runtime.js +++ b/.opencode/lib/runtime.js @@ -7,15 +7,11 @@ import { fileURLToPath } from "node:url"; import { writeFileAtomic } from "../../src/fs-atomic.js"; import { billingFor, ownerRules } from "../../src/metrics.js"; import { metricsDir, readMetrics, refreshMetrics } from "../../src/metrics-cache.js"; -import { - buildModelData, - modelsChanged, - readModelDataFile, - scanSquadModels, -} from "../../src/model-data.js"; +import { buildModelData, modelsChanged, readModelDataFile } from "../../src/model-data.js"; import { opencodeConfigDir, opencodeDataDir } from "../../src/paths.js"; import { createPromptLoader } from "../../src/prompt-inject.js"; -import { defaultAgentDir, syncDescriptions } from "../../src/squad-apply.js"; +import { defaultAgentDir, readLegacySquad } from "../../src/squad-apply.js"; +import { defaultStoreFile, readStore, writeStore } from "../../src/squad-store.js"; import { describeAgent } from "../../src/workers.js"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -165,16 +161,17 @@ export function loadAuthTypes() { } /** - * Startup auto-regen of the GLOBAL model_data.json: rescan the squad, MERGE - * (preserving every hand-written field, dropping legacy AA perf fields), and - * write ONLY when the models actually changed — so a new grunt/drill lands - * automatically without clobbering edits or churning the file every boot. - * No-op when there is no squad yet (0 models). Only the global agent dir is - * scanned; a project's .opencode/model_data.json is edited by hand only. + * Startup auto-regen of the GLOBAL model_data.json: list the squad's models + * (from squad.json), MERGE (preserving every hand-written field, dropping + * legacy AA perf fields), and write ONLY when the models actually changed — + * so a new grunt/drill lands automatically without clobbering edits or + * churning the file every boot. No-op when there is no squad yet. * - * A file that exists but does not parse is LEFT ALONE: treating it as missing - * once overwrote a hand-edited file with a fresh skeleton, losing every owner - * rule and provider plan in it. Never throws — startup must not break. + * A model_data.json that exists but does not parse is LEFT ALONE: treating it + * as missing once overwrote a hand-edited file with a fresh skeleton, losing + * every owner rule and provider plan in it. So is everything when squad.json + * cannot be read: the merge would drop every model's entry. Never throws — + * startup must not break. * * @returns {{wrote: boolean, problem?: string}} */ @@ -187,24 +184,19 @@ export function ensureGlobalModelDataFresh() { console.warn(`[opencode-squad] model_data.json left untouched — ${problem}`); return { wrote: false, problem }; } - const agentDir = path.join(path.dirname(file), "agent"); - // A squad file whose model cannot be determined (unreadable, or a cut-off - // or broken header) has an unknown model; the merge would drop that - // model's entry and its owner rules with it. One scan feeds both the check - // and the snapshot, so the snapshot is built from what was checked. - const scan = scanSquadModels(agentDir); - if (scan.unreadable.length || scan.undetermined.length) { - const why = [ - ...(scan.unreadable.length ? [`cannot read ${scan.unreadable.join(", ")}`] : []), - ...(scan.undetermined.length ? [`no model in ${scan.undetermined.join(", ")}`] : []), - ]; - const problem = `${agentDir}: ${why.join("; ")}`; + const store = readStore(defaultStoreFile()); + if (store.state === "invalid") { + const problem = `${defaultStoreFile()}: ${store.reason}`; console.warn(`[opencode-squad] model_data.json left untouched — ${problem}`); return { wrote: false, problem }; } + if (store.state === "missing") return { wrote: false }; // no squad + const ids = [ + ...new Set([...Object.keys(store.roster.grunts), ...Object.keys(store.roster.drills)]), + ].sort(); const existing = read.state === "ok" ? read.data : {}; const generated = new Date().toISOString().slice(0, 10); - const snapshot = buildModelData(scan.ids, existing, generated); + const snapshot = buildModelData(ids, existing, generated); if (Object.keys(snapshot.models).length === 0) return { wrote: false }; // no squad if (!modelsChanged(existing, snapshot)) return { wrote: false }; // unchanged writeFileAtomic(file, `${JSON.stringify(snapshot, null, 2)}\n`); @@ -218,26 +210,48 @@ export function ensureGlobalModelDataFresh() { } /** - * describe(role, modelId) for the squad in `agentDir`, from model_data.json. - * The GLOBAL agent dir — shared by every project — reads the global file only: - * with project overrides the shared files would flip with whichever project - * started last. A project's own agent dir also sees that project's file. + * First start after #85: a squad that earlier versions wrote as agent files + * becomes squad.json. Only when squad.json does not exist yet, and only when + * every generated file could be read: an import that dropped an unreadable + * agent would look like a squad the user chose. The files are left in place; + * the plugin hides the agents they define once the roster no longer holds + * them. Never throws. * - * @param {string} agentDir - * @param {string} [directory] project root + * @returns {{imported: number, problems: string[]}} */ -export function squadDescriber(agentDir, directory) { - return describerFrom(loadModelSettings(describerScope(agentDir, directory))); +export function importLegacySquad() { + const store = defaultStoreFile(); + try { + if (readStore(store).state !== "missing") return { imported: 0, problems: [] }; + const legacy = readLegacySquad(defaultAgentDir()); + if (legacy.problems.length) { + for (const p of legacy.problems) { + console.warn(`[opencode-squad] legacy squad not imported — ${p}`); + } + return { imported: 0, problems: legacy.problems }; + } + const count = + Object.keys(legacy.roster.grunts).length + Object.keys(legacy.roster.drills).length; + if (count === 0) return { imported: 0, problems: [] }; + writeStore(store, legacy.roster); + return { imported: count, problems: [] }; + } catch (e) { + const err = /** @type {NodeJS.ErrnoException} */ (e); + const problem = `${store}: ${err?.code ?? err?.name ?? "error"}`; + console.warn(`[opencode-squad] legacy squad import failed — ${problem}`); + return { imported: 0, problems: [problem] }; + } } /** - * The model_data scope that feeds an agent dir's descriptions. + * describe(role, modelId) for the squad, from the GLOBAL model_data.json: the + * squad is global, and with project overrides its descriptions would flip with + * whichever project's instance registered last. * - * @param {string} agentDir - * @param {string} [directory] + * @returns {(role: "grunt"|"drill", modelId: string) => string} */ -export function describerScope(agentDir, directory) { - return path.resolve(agentDir) === path.resolve(defaultAgentDir()) ? null : (directory ?? null); +export function squadDescriber() { + return describerFrom(loadModelSettings(null)); } /** @@ -252,19 +266,3 @@ function describerFrom({ models, providers }) { billing: billingFor(modelId, { note: models[modelId], plans: providers, authTypes }), }); } - -// Startup: rewrite the global squad's descriptions from model_data.json, so an -// edited `info` or plan reaches the orchestrator with a restart instead of a -// re-draft (opencode reloads agent files live). Best-effort, like the regen. -// -// Skipped while the global model_data.json is unreadable: describing from it -// then would rewrite every agent without its owner rules. -export function syncGlobalSquadDescriptions() { - try { - const settings = loadModelSettings(null); - if (settings.problems.length) return []; - return syncDescriptions({ dir: defaultAgentDir(), describe: describerFrom(settings) }); - } catch { - return []; - } -} diff --git a/.opencode/lib/squad.js b/.opencode/lib/squad.js index 80ac606..41bb34b 100644 --- a/.opencode/lib/squad.js +++ b/.opencode/lib/squad.js @@ -57,11 +57,18 @@ import { sessionFacts, } from "../../src/session-status.js"; import { - applySquad, + agentSpecs, + earlyTransform, + isSquadSystem, + lateTransform, +} from "../../src/squad-agents.js"; +import { defaultAgentDir, - formatApplyReport, - readSquad, + formatPatchReport, + planPatch, + readLegacySquad, } from "../../src/squad-apply.js"; +import { defaultStoreFile, readStore, storeSignature, writeStore } from "../../src/squad-store.js"; import { formatVariantLines, isSubagentCaller, @@ -83,10 +90,11 @@ import { SQUAD_SESSION_INPUT, } from "../../src/v2/schemas.js"; import { loadSkills } from "../../src/v2/skills.js"; +import { slugForModel } from "../../src/workers.js"; import { - describerScope, ensureGlobalModelDataFresh, getMetrics, + importLegacySquad, loadAuthTypes, loadModelSettings, loadRolePrompt, @@ -95,9 +103,14 @@ import { SKILLS_DIR, squadDescriber, startMetricsRefresh, - syncGlobalSquadDescriptions, } from "./runtime.js"; +// `directory` scoped the squad to a project's agent files before #85. +const DIRECTORY_GONE = + "Refused: `directory` is no longer supported. The squad is one roster (squad.json in the " + + "OpenCode config dir) registered by the plugin, not agent files in a directory. Call " + + "again without it."; + // squad_metrics({full: true}) returns ~2K tokens per model; cap the bill. const MAX_FULL_MODELS = 6; @@ -127,10 +140,10 @@ export default { id: "squad", /** @param {PluginContext} ctx */ async setup(ctx) { + // A squad older versions wrote as agent files becomes squad.json first, + // so the model_data.json regen below already sees its models. + const legacyImport = importLegacySquad(); ensureGlobalModelDataFresh(); - // After the regen, which may rewrite model_data.json. opencode reloads - // the rewritten agent files on its own (agent.updated). - syncGlobalSquadDescriptions(); startMetricsRefresh(); // { package: "opencode-squad", options: { rate_limit_guard } }. @@ -206,6 +219,85 @@ export default { /** @param {string} sessionID */ const readContext = async (sessionID) => unwrap(await ctx.session.context({ sessionID })) ?? []; + // --- squad agents (#85) --- + // + // Registered from squad.json, never written as files. See + // src/squad-agents.js for why there are two transforms. + + const storeFile = defaultStoreFile(); + let storeSig = storeSignature(storeFile); + /** Agents a hand-authored file holds, and legacy ones hidden; from the late transform. */ + let lateReport = { + foreign: /** @type {string[]} */ ([]), + hidden: /** @type {string[]} */ ([]), + }; + const specsNow = () => { + const store = readStore(storeFile); + if (store.state !== "ok") return null; + return agentSpecs(store.roster, { + describe: squadDescriber(), + prompt: (role) => { + try { + return loadRolePrompt(role); + } catch { + return null; + } + }, + }); + }; + await ctx.agent.transform((editor) => { + try { + earlyTransform(editor, specsNow() ?? []); + } catch { + // A broken roster must not take the host's agent list down with it. + } + }); + /** What squad_dump and squad_patch say about the squad beyond its roster. */ + const squadNotes = () => { + const notes = []; + for (const id of lateReport.foreign) { + notes.push( + `${id}: a hand-authored agent holds this id, so the squad's entry is not registered`, + ); + } + for (const p of legacyImport.problems) { + notes.push(`legacy squad files were not imported: ${p}. Fix or delete it, then restart`); + } + const legacy = readLegacySquad(defaultAgentDir()).files; + if (legacy.length) { + notes.push( + `${legacy.length} agent file(s) from an earlier version remain in ${defaultAgentDir()} ` + + `(${legacy.join(", ")}). squad.json supersedes them and the plugin ignores them; ` + + "the user may delete them.", + ); + } + return notes; + }; + + let lateRegistered = false; + /** @param {boolean} [force] reload even if squad.json looks unchanged */ + const syncSquadAgents = async (force = false) => { + if (!lateRegistered) { + lateRegistered = true; + await ctx.agent.transform((editor) => { + try { + // An unreadable squad.json registers nothing and hides nothing: + // legacy agent files, if any, keep working until it is fixed. + const specs = specsNow(); + if (specs) lateReport = lateTransform(editor, specs); + } catch { + // As above. + } + }); + force = true; + } + const sig = storeSignature(storeFile); + if (!force && sig === storeSig) return; + storeSig = sig; + await ctx.agent.reload(); + agentsPromise = undefined; + }; + // --- skills --- const skills = loadSkills([SKILLS_DIR]); @@ -221,6 +313,13 @@ export default { // --- per-request transforms --- await ctx.session.hook("context", async (event) => { + try { + // Before the bootstrap: its inventory lists the squad. Also picks up + // a squad.json another OpenCode process changed. + await syncSquadAgents(); + } catch { + // The squad stays as last registered. + } try { applySystemPartsTransform(event.system, loadRolePrompt); } catch { @@ -374,21 +473,27 @@ export default { input: SQUAD_DUMP_INPUT, execute: async (input) => { const { directory: asked } = /** @type {{directory?: unknown}} */ (input ?? {}); - const dir = typeof asked === "string" && asked ? asked : defaultAgentDir(); - const { roster, conflicts: readConflicts } = readSquad(dir); - const conflicts = readConflicts; - const count = - Object.keys(roster.grunts ?? {}).length + Object.keys(roster.drills ?? {}).length; - const note = conflicts.length - ? `\n\nnotes:\n${conflicts.map((c) => ` ${c}`).join("\n")}` - : ""; + if (asked !== undefined) return { content: DIRECTORY_GONE }; + const store = readStore(storeFile); + if (store.state === "invalid") { + return { + content: + `The squad roster ${storeFile} cannot be read (${store.reason}). Nothing is ` + + "registered from it and squad_patch refuses until it is fixed: ask the user to " + + "repair or restore the file. It is never overwritten.", + }; + } + const roster = store.state === "ok" ? store.roster : { grunts: {}, drills: {} }; + const count = Object.keys(roster.grunts).length + Object.keys(roster.drills).length; + const notes = squadNotes(); + const note = notes.length ? `\n\nnotes:\n${notes.map((c) => ` ${c}`).join("\n")}` : ""; const variantLines = formatVariantLines(await getVariantMap(), roster); return { content: - `Agent dir: ${dir}\n${JSON.stringify(roster, null, 2)}${note}${variantLines}\n\n` + + `Squad roster: ${storeFile}\n${JSON.stringify(roster, null, 2)}${note}${variantLines}\n\n` + "To change the squad, pass this same document back to squad_patch with your " + "edits applied — keeping every agent you were not asked to touch.", - metadata: { title: `squad: ${count} agent(s)`, dir, agents: count }, + metadata: { title: `squad: ${count} agent(s)`, store: storeFile, agents: count }, }; }, }); @@ -504,7 +609,7 @@ export default { // Untyped until validated: Code Mode can send anything. const raw = /** @type {Record} */ (input ?? {}); const { allow_remove: allowRemove, directory: asked, ...doc } = raw; - const dir = typeof asked === "string" && asked ? asked : defaultAgentDir(); + if (asked !== undefined) return { content: DIRECTORY_GONE }; // Code Mode does not enforce the schema's additionalProperties, and // a roster wrapped as {roster: {...}} used to read as "no agents" — // a 14-agent deletion the guard caught twice in one afternoon. @@ -530,28 +635,58 @@ export default { }; } // Descriptions carry the owner's routing rules from model_data.json; - // writing from an unreadable file would strip them from every agent. - const problems = loadModelSettings(describerScope(dir, directory)).problems; + // registering from an unreadable file would strip them from every agent. + const problems = loadModelSettings(null).problems; if (problems.length) { return { content: "Refused: model_data.json cannot be read, and agent descriptions are built " + - "from it — writing now would drop the owner's routing rules. Nothing was " + + "from it — applying now would drop the owner's routing rules. Nothing was " + `written. Ask the user to fix:\n${problems.map((p) => ` - ${p}`).join("\n")}`, }; } - const result = applySquad({ - roster, - dir, + // Re-read right before writing: another OpenCode process may have + // changed the roster since this one last looked. + const store = readStore(storeFile); + if (store.state === "invalid") { + return { + content: + `Refused: the squad roster ${storeFile} cannot be read (${store.reason}), and ` + + "writing over it could lose the user's squad. Nothing was written. Ask the " + + "user to repair or restore it.", + }; + } + const current = store.state === "ok" ? store.roster : { grunts: {}, drills: {} }; + // A hand-authored agent already holding an id this roster wants. + const agents = unwrap(await ctx.agent.list().catch(() => null)) ?? []; + const byId = new Map( + (Array.isArray(agents) ? agents : []).map((a) => [String(a?.id ?? ""), a]), + ); + const foreign = []; + for (const [key, role] of /** @type {const} */ ([ + ["grunts", "grunt"], + ["drills", "drill"], + ])) { + for (const modelId of Object.keys(roster[key])) { + const id = slugForModel(modelId, role); + const agent = byId.get(id); + if (agent && !isSquadSystem(agent.system)) { + foreign.push({ id, agent: `${role} ${modelId}` }); + } + } + } + const result = planPatch({ + current, + next: roster, allowRemove: allowRemove === true, - describe: squadDescriber(dir, directory), + foreign, }); if (result.ok) { - // The inventory lists the squad; let the next turn see the change. - agentsPromise = undefined; + writeStore(storeFile, roster); + await syncSquadAgents(true); } return { - content: formatApplyReport(result), + content: formatPatchReport(result, { store: storeFile, roster, notes: squadNotes() }), metadata: { ok: result.ok, ...result.diff }, }; }, diff --git a/src/fs-atomic.js b/src/fs-atomic.js index c2bf411..086a302 100644 --- a/src/fs-atomic.js +++ b/src/fs-atomic.js @@ -37,7 +37,7 @@ function resolveTarget(file) { * @param {string} file * @returns {string | null} */ -export function danglingLinkTarget(file) { +function danglingLinkTarget(file) { let link; try { if (!fs.lstatSync(file).isSymbolicLink()) return null; diff --git a/src/model-data.js b/src/model-data.js index b8469e2..2904f70 100644 --- a/src/model-data.js +++ b/src/model-data.js @@ -13,91 +13,6 @@ // empty entry, removed ones are dropped, hand-added fields are preserved. import fs from "node:fs"; -import path from "node:path"; - -import { legacyHeaderFields, readFrontmatter } from "./frontmatter.js"; -import { isGeneratedAgent } from "./workers.js"; - -/** - * Pull the model id out of an agent markdown file's frontmatter, without its - * `#variant` suffix. Only the leading frontmatter block counts: a `model:` - * line in the body (prompt text) is not the agent's model, and a file with no - * block has none. A block that is not valid YAML is read line by line (see - * legacyHeaderFields), as the roster reader does. - * - * @param {string} content - * @returns {string|null} - */ -export function extractModelId(content) { - const fm = readFrontmatter(content); - // A cut-off header is not read line by line: the cut may run through the - // model line itself and yield a wrong id. - const model = - fm.state === "ok" - ? fm.fields.model - : fm.state === "invalid" - ? legacyHeaderFields(fm.header).model - : undefined; - if (typeof model !== "string") return null; - return model.split("#")[0].trim() || null; -} - -/** - * Scan an agent dir for squad files and collect the unique set of - * `provider/model` ids they target (a grunt and a drill of the same model - * collapse to one entry). Hand-authored grunt-/drill- agents count too, and so - * do generated legacy `worker-` files: squad_dump still lists those agents - * (src/squad-apply.js readSquad), so their models are still in the squad. - * - * Two lists name files whose model is unknown, not absent, so a caller that - * would DROP models missing from `ids` must not act on this scan: - * unreadable — the file could not be read at all; - * undetermined — a generated file from which no model could be read (a - * cut-off or broken header): every generated agent has one. - * A hand-authored file without a model owns no model_data entry, so it is - * simply not counted — blocking on it would freeze the refresh for good over - * a file that is not the squad's. - * - * @param {string} dir agent directory (e.g. ~/.config/opencode/agent) - * @returns {{ids: string[], unreadable: string[], undetermined: string[]}} ids sorted and deduped - */ -export function scanSquadModels(dir) { - let files; - try { - files = fs.readdirSync(dir); - } catch { - return { ids: [], unreadable: [], undetermined: [] }; - } - const ids = new Set(); - const unreadable = []; - const undetermined = []; - for (const f of files.sort()) { - const m = /^(grunt|drill|worker)-.*\.md$/.exec(f); - if (!m) continue; - let txt; - try { - txt = fs.readFileSync(path.join(dir, f), "utf8"); - } catch { - unreadable.push(f); - continue; - } - const generated = isGeneratedAgent(txt); - // A hand-authored worker-* agent was never part of the squad. - if (m[1] === "worker" && !generated) continue; - const id = extractModelId(txt); - if (id) ids.add(id); - else if (generated) undetermined.push(f); - } - return { ids: [...ids].sort(), unreadable, undetermined }; -} - -/** - * @param {string} dir agent directory - * @returns {string[]} sorted, deduped model ids (see scanSquadModels) - */ -export function discoverSquadModels(dir) { - return scanSquadModels(dir).ids; -} // Fields earlier versions copied in from Artificial Analysis. They are stale // by construction (AA is no longer a source) and are stripped on the next @@ -138,8 +53,7 @@ export function mergeModelData(modelIds, existing = {}) { /** * Assemble the full model_data.json snapshot object. * - * Takes the ids of a scan the caller has already checked (scanSquadModels): - * scanning again here could see a different directory than the one checked. + * Takes the squad's model ids from the caller (the roster in squad.json). * * @param {string[]} ids model ids of the squad * @param {{models?:Record, _meta?: object, [key: string]: unknown}} [existing] prior model_data.json diff --git a/src/squad-agents.js b/src/squad-agents.js new file mode 100644 index 0000000..a7ad46e --- /dev/null +++ b/src/squad-agents.js @@ -0,0 +1,140 @@ +// Register the squad's agents with OpenCode through the plugin agent API, +// from the roster in squad.json (src/squad-store.js), instead of writing +// agent files (#85). +// +// Two transforms, because of how the host orders them (verified on 2.1.3; +// see #85). Agent transforms run in registration order, and a plugin's +// registered during setup runs BEFORE the built-in config-agent plugin, which +// then (a) appends the user's global permission rules to every agent that +// exists and (b) applies agent files, whose fields override ours. +// +// early (registered in setup): creates each agent, so it exists from the +// first turn and the config plugin gives it the user's global rules. +// late (registered on the first request, then reload): runs after the +// config plugin, on every later reload too. It hides legacy +// generated agents that are no longer in the roster, sets every field +// again (so a same-id legacy file cannot leak steps, color or rules +// into ours) and re-appends the role's rules LAST. With the host's +// last-match permission evaluation that gives the order a file agent +// gets: base, global, own. The host then filters the child's tool +// catalog by them: a drill sees read-only tools only. +// +// A roster id whose agent is hand-authored (its system prompt has no +// squad:prompt fence after the config plugin ran) is left alone and reported: +// the user's agent wins, and squad_patch refuses that id. + +import { findPromptFence, placeholderBody, wrapPrompt } from "./prompt-inject.js"; +import { NOTES_CLOSE, NOTES_OPEN, ROLE_KEYS } from "./roster.js"; +import { roleRules, slugForModel, squadRoleOf } from "./workers.js"; + +/** + * @typedef {{id: string, role: "grunt"|"drill", modelId: string, description: string, + * system: string, model: {id: string, providerID: string, variant?: string}, + * steps?: number, permissions: Array<{action: string, resource: string, effect: string}>}} AgentSpec + */ + +/** + * The agents a roster asks for. A disabled entry stays in the roster (its + * settings survive) but is not registered. + * + * @param {{grunts?: Record, drills?: Record}} roster + * @param {{describe: (role: "grunt"|"drill", modelId: string) => string, + * prompt: (role: "grunt"|"drill") => string | null}} io + * prompt: the role prompt body now; null falls back to the placeholder, + * which the context hook replaces on every request anyway + * @returns {AgentSpec[]} + */ +export function agentSpecs(roster, { describe, prompt }) { + /** @type {AgentSpec[]} */ + const specs = []; + for (const [key, role] of Object.entries(ROLE_KEYS)) { + const map = /** @type {Record | undefined> | undefined} */ ( + roster + )?.[key]; + for (const [modelId, entry] of Object.entries(map ?? {})) { + if (entry?.disable) continue; + const slash = modelId.indexOf("/"); + const variant = typeof entry?.variant === "string" ? entry.variant.trim() : ""; + const notes = typeof entry?.notes === "string" ? entry.notes.trim() : ""; + const body = wrapPrompt(role, prompt(role) ?? placeholderBody(role)); + specs.push({ + id: slugForModel(modelId, role), + role, + modelId, + description: describe(role, modelId), + system: notes ? `${body}\n\n${NOTES_OPEN}\n${notes}\n${NOTES_CLOSE}` : body, + model: { + providerID: modelId.slice(0, slash), + id: modelId.slice(slash + 1), + ...(variant ? { variant } : {}), + }, + ...(typeof entry?.steps === "number" ? { steps: entry.steps } : {}), + permissions: roleRules(role), + }); + } + } + return specs; +} + +/** + * Set every field the squad owns. Fields a legacy file could carry and the + * roster does not (color, steps) are cleared, not inherited. + * + * @param {any} agent the host's mutable agent + * @param {AgentSpec} spec + */ +function shape(agent, spec) { + agent.mode = "subagent"; + agent.hidden = true; + agent.description = spec.description; + agent.system = spec.system; + agent.model = { ...spec.model }; + delete agent.color; + if (spec.steps === undefined) delete agent.steps; + else agent.steps = spec.steps; + if (!Array.isArray(agent.permissions)) agent.permissions = []; + agent.permissions.push(...spec.permissions.map((r) => ({ ...r }))); +} + +/** Whether an agent's system prompt is one this plugin generated. @param {unknown} system */ +export function isSquadSystem(system) { + return typeof system === "string" && findPromptFence(system) !== null; +} + +/** + * @param {{update: (id: string, f: (agent: any) => void) => void}} editor + * @param {AgentSpec[]} specs + */ +export function earlyTransform(editor, specs) { + for (const spec of specs) editor.update(spec.id, (agent) => shape(agent, spec)); +} + +/** + * @param {{list: () => readonly any[], get: (id: string) => any, update: (id: string, f: (agent: any) => void) => void, remove: (id: string) => void}} editor + * @param {AgentSpec[]} specs + * @returns {{foreign: string[], hidden: string[]}} + * foreign: roster ids a hand-authored agent already holds (left alone); + * hidden: legacy generated agents removed because the roster no longer has them + */ +export function lateTransform(editor, specs) { + const wanted = new Map(specs.map((s) => [s.id, s])); + /** @type {string[]} */ + const foreign = []; + /** @type {string[]} */ + const hidden = []; + for (const agent of [...editor.list()]) { + const id = String(agent?.id ?? ""); + if (wanted.has(id) || squadRoleOf(id) === null || !isSquadSystem(agent?.system)) continue; + editor.remove(id); + hidden.push(id); + } + for (const spec of specs) { + const current = editor.get(spec.id); + if (current && !isSquadSystem(current.system)) { + foreign.push(spec.id); + continue; + } + editor.update(spec.id, (agent) => shape(agent, spec)); + } + return { foreign: foreign.sort(), hidden: hidden.sort() }; +} diff --git a/src/squad-apply.js b/src/squad-apply.js index d5f77de..961fee7 100644 --- a/src/squad-apply.js +++ b/src/squad-apply.js @@ -1,568 +1,132 @@ -// Filesystem side of the squad roster: read it off disk, write one back. -// Backs the `squad_dump` / `squad_patch` plugin tools. +// The squad_patch decision and its report, plus the one-time import of a +// squad that older versions wrote as agent files. // -// Kept apart from src/roster.js so that module stays pure and directly -// testable, and apart from the tool definitions so the deletion guard and the -// report have exactly one implementation. +// Since #85 the roster lives in squad.json (src/squad-store.js) and its +// agents are registered through the plugin API (src/squad-agents.js): an +// apply changes one file the plugin owns and never touches an agent file. +// What remains here is the part that was never about files: the deletion +// guard, and a report the orchestrator can act on. import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { danglingLinkTarget, writeFileAtomic } from "./fs-atomic.js"; import { opencodeConfigDir } from "./paths.js"; -import { buildRoster, diffRoster, parseAgentFile, ROLE_KEYS } from "./roster.js"; -import { agentMarkdown, isGeneratedAgent } from "./workers.js"; +import { buildRoster, diffRoster, parseAgentFile } from "./roster.js"; +import { isGeneratedAgent } from "./workers.js"; const GENERATED_FILE_RE = /^(grunt|drill|worker)-.*\.md$/; -/** The global agent dir opencode merges; the default target for the squad. */ +/** The global agent dir, where versions before #85 wrote the squad's files. */ export function defaultAgentDir() { return path.join(opencodeConfigDir(process.env, os.homedir()), "agent"); } /** - * Read the squad that currently exists, from the generated agent files - * themselves — there is deliberately no stored manifest to consult, so there is - * nothing that can desync from what opencode will actually load. + * Read a squad that an earlier version wrote as agent files, for the one-time + * import into squad.json. Read-only: the files stay where they are, and the + * plugin hides the agents they define once the roster no longer holds them + * (src/squad-agents.js lateTransform). * - * Only files carrying our marker count: a hand-authored `grunt-something.md` - * belongs to somebody else and is neither dumped nor pruned. - * - * `filesByAgent` lists EVERY generated file that claims an agent, in directory - * order: a legacy `worker-` file and its `grunt-` successor, or two ids that - * slug to near-identical names, all have to go when that agent is removed. + * Only files carrying our generator marker count. A file whose model cannot be + * read is reported, never silently dropped: an import that lost an agent + * would look like a squad the user chose. * * @param {string} dir - * @returns {{roster: Record>, conflicts: string[], filesByAgent: Map}} + * @returns {{roster: Record>, problems: string[], files: string[]}} */ -export function readSquad(dir) { +export function readLegacySquad(dir) { + const parsed = []; + /** @type {string[]} */ const files = []; - /** @type {Map} */ - const filesByAgent = new Map(); + /** @type {string[]} */ + const problems = []; let names = []; try { names = fs.readdirSync(dir).sort(); } catch { - // No agent dir yet is an empty squad, not an error — also the first-run path. - return { roster: buildRoster([]).roster, conflicts: [], filesByAgent }; + return { roster: buildRoster([]).roster, problems, files }; } - /** @type {string[]} */ - const unreadable = []; for (const name of names) { const m = GENERATED_FILE_RE.exec(name); if (!m) continue; - const read = readText(path.join(dir, name)); - if (read.state === "error") { - unreadable.push(`${name}: cannot read (${read.code})`); - continue; - } - if (read.state === "missing" || !isGenerated(read.text)) continue; - const { modelId, entry } = parseAgentFile(read.text); - if (isDamaged(read.text)) { - unreadable.push( - `${name}: generated file with no readable model (damaged header). It is left as is and blocks the model_data.json refresh: ask the user to repair or delete it`, - ); - continue; - } - // Legacy `worker-` files predate the grunt/drill split; treat them as the - // executor so an old squad still round-trips instead of vanishing. - const role = m[1] === "worker" ? "grunt" : m[1]; - files.push({ role, modelId, entry }); - const agent = `${role} ${modelId}`; - filesByAgent.set(agent, [...(filesByAgent.get(agent) ?? []), name]); - } - const { roster, conflicts } = buildRoster(files); - // squad_dump shows these too, not only the write paths that refuse them. - const shared = sharedDestinations(dir, [...filesByAgent.values()].flat()).map((s) => s.line); - return { roster, conflicts: [...conflicts, ...unreadable, ...shared], filesByAgent }; -} - -/** - * A missing file and one that cannot be read are different answers: only the - * first means there is nothing to protect. - * - * @param {string} file - * @returns {{state: "ok", text: string} | {state: "missing"} | {state: "error", code: string}} - */ -function readText(file) { - try { - return { state: "ok", text: fs.readFileSync(file, "utf8") }; - } catch (e) { - const err = /** @type {NodeJS.ErrnoException} */ (e); - if (err?.code === "ENOENT") return { state: "missing" }; - return { state: "error", code: err?.code ?? err?.name ?? "error" }; - } -} - -const isGenerated = isGeneratedAgent; - -/** The file a path really lands on: through symlinks, or the path itself when new. @param {string} file */ -function physicalPath(file) { - try { - return fs.realpathSync(file); - } catch { - return path.resolve(file); - } -} - -/** - * The directories OpenCode's config-agent loader reads agent Markdown from - * (OpenCode 2.1.3, config/plugin/agent.ts `legacySources`): `deep` ones - * recursively, the others top level only. tests/regress-squad-files.test.js - * compares this with the installed loader, so an OpenCode bump that changes - * them fails there instead of here. - */ -export const AGENT_SOURCES = [ - { name: "agent", deep: true }, - { name: "agents", deep: true }, - { name: "mode", deep: false }, - { name: "modes", deep: false }, -]; - -/** - * Every agent file name OpenCode could load next to `dir`. The pinned - * OpenCode 2.1.3 config-agent loader scans a config dir for - * every .md below `agent/` and `agents/` (subagents, recursive) and the .md - * files directly in `mode/` and `modes/` (primary agents, top level only), following links, and names each by its - * path: a file reached through another root or a linked directory is another - * agent name for the same file. Names are relative to `dir` (a sibling - * root's start with `../agents/`, `../mode/`, ...). - * - * Linked directories are followed as OpenCode follows them, so every alias - * path is listed. A link back into a directory already on the current path - * (a cycle) has no finite listing, and a directory that cannot be read hides - * what is in it: both go to `unlisted`, which callers treat as "uniqueness - * unknown". A missing root is no agents, not a gap. - * - * @param {string} dir - * @returns {{names: string[], unlisted: string[]}} - */ -function listAgentFiles(dir) { - /** @type {string[]} */ - const names = []; - /** @type {string[]} */ - const unlisted = []; - // Only when `dir` is one of the sources is its parent a config dir with - // siblings to check. - const base = path.basename(dir); - const roots = AGENT_SOURCES.some((s) => s.name === base) - ? AGENT_SOURCES.map((s) => ({ abs: path.join(path.dirname(dir), s.name), deep: s.deep })) - : [{ abs: dir, deep: true }]; - /** - * @param {string} abs - * @param {Set} ancestors real paths of the directories above - * @param {boolean} isRoot - * @param {boolean} deep descend into subdirectories (agent roots) or not (mode roots) - */ - const walk = (abs, ancestors, isRoot, deep) => { - /** @type {fs.Dirent[]} */ - let entries; - let real; + let text; try { - real = fs.realpathSync(abs); - entries = fs.readdirSync(abs, { withFileTypes: true }); + text = fs.readFileSync(path.join(dir, name), "utf8"); } catch (e) { const code = /** @type {NodeJS.ErrnoException} */ (e)?.code; - if (isRoot && code === "ENOENT") return; - unlisted.push(`${abs} (${code ?? "error"})`); - return; - } - if (ancestors.has(real)) { - unlisted.push(`${abs} (links back to a directory above it)`); - return; + if (code !== "ENOENT") problems.push(`${name}: cannot read (${code ?? "error"})`); + continue; } - const below = new Set(ancestors).add(real); - for (const ent of entries) { - const child = path.join(abs, ent.name); - let isDir = ent.isDirectory(); - if (ent.isSymbolicLink()) { - try { - isDir = fs.statSync(child).isDirectory(); - } catch { - isDir = false; // dangling: a file name at most - } - } - if (isDir) { - if (deep) walk(child, below, false, true); - } else if (ent.name.endsWith(".md")) - names.push(path.relative(dir, child).split(path.sep).join("/")); + if (!isGeneratedAgent(text)) continue; + const { modelId, entry } = parseAgentFile(text); + if (!modelId) { + problems.push(`${name}: generated file with no readable model (damaged header)`); + continue; } - }; - for (const root of roots) walk(root.abs, new Set(), true, root.deep); - return { names, unlisted }; -} - -/** - * Targets that reach one physical file under another agent file's name: two - * symlinks onto one file, or a link onto a sibling agent. Writing both would - * leave one agent with the other's configuration while both report success. - * An ordinary link onto a file no other loadable agent name reaches is fine. - * - * @param {string} dir - * @param {string[]} targets filenames about to be written - * @returns {Array<{names: string[], line: string}>} one per shared destination - */ -function sharedDestinations(dir, targets) { - /** @type {Map>} physical path -> agent filenames reaching it */ - const reach = new Map(); - /** @param {string} name */ - const add = (name) => { - const real = physicalPath(path.join(dir, name)); - if (!reach.has(real)) reach.set(real, new Set()); - reach.get(real)?.add(name); - }; - const { names, unlisted } = listAgentFiles(dir); - for (const name of new Set([...names, ...targets])) add(name); - const out = []; - // A tree we could not list completely proves nothing about uniqueness: - // every target is held back, and the gap is named. - if (unlisted.length && targets.length) { - out.push({ - names: [...targets].sort(), - line: - `cannot list ${unlisted.join(", ")}, so whether ${[...targets].sort().join(", ")} ` + - "share a file with an agent there is unknown", - }); - } - for (const [real, set] of reach) { - if (set.size < 2 || !targets.some((t) => set.has(t))) continue; - const names = [...set].sort(); - out.push({ - names, - line: `${names.join(", ")} all lead to ${real}; each agent needs its own file`, - }); + // Legacy `worker-` files predate the grunt/drill split: the executor. + parsed.push({ role: m[1] === "worker" ? "grunt" : m[1], modelId, entry }); + files.push(name); } - return out; + const { roster, conflicts } = buildRoster(parsed); + return { roster, problems: [...problems, ...conflicts], files }; } /** - * Ours, but with no model we can read (a truncated or mangled header). One - * predicate for dump and apply, so the file the dump says it leaves in place is - * the file apply refuses to replace: it may hold the user's edits. - * - * @param {string} text - */ -const isDamaged = (text) => isGenerated(text) && !parseAgentFile(text).modelId; - -/** - * @typedef {{role: string, id: string, variant?: string, filename: string, unchanged?: boolean}} WrittenAgent - * @typedef {{ok: true, diff: ReturnType, written: WrittenAgent[], pruned: string[], - * migrated: string[], refreshed: string[], conflicts: string[], dir: string}} ApplyDone - * @typedef {{ok: false, refusal: "remove" | "collision" | "unreadable" | "damaged" | "dangling", problems: string[], - * diff: ReturnType, written: [], pruned: [], conflicts: string[], dir: string}} ApplyRefused + * @typedef {{ok: true, diff: ReturnType}} PatchOk + * @typedef {{ok: false, refusal: "remove" | "foreign", problems: string[], diff: ReturnType}} PatchRefused */ /** - * Write a roster to the agent dir. - * - * Returns `{ok: false, ...}` rather than throwing when the apply is refused — - * the refusal is an ordinary outcome the caller reports, not an exception — - * and every check runs before the first write, so a refused apply leaves the - * squad exactly as it was. Five refusals: - * - * remove — the apply would delete agents and `allowRemove` is not set; - * collision — two roster agents map to one filename (`p/model-1` and - * `p/model.1` both slug to `grunt-p-model-1.md`), or the target - * file exists and is not ours (hand-authored); - * unreadable — a target file exists but cannot be read, so whether it is - * ours cannot be established; - * damaged — a target file is ours but its header has no readable model - * (the one squad_dump reports and leaves as is), so what it - * held and any edits to it would be lost; - * dangling — a target path is a symlink whose target is missing (a dotfiles - * checkout that is not there): writing would replace the link - * with a regular file and detach the path from the repo copy. - * - * Another generated file still claiming a kept agent is handled by name. A - * legacy `worker-` file is migrated: deleted once the agent's `grunt-` file is - * written, so the agent lives in one file and a later removal removes it - * completely. Any other one (a hand copy that kept our marker) is a separate - * agent to OpenCode, so deleting it is a removal like any other: refused - * without `allowRemove`, pruned with it. - * - * On success: a file whose text is already identical is not rewritten (every - * write makes opencode reload), and a file pruned for a removed agent is never - * one just written for a kept agent. + * Decide whether a roster may replace the current one. * - * `describe(role, modelId)` supplies each agent's description (see - * describeAgent); without it the role's generic line is written. + * Two refusals, checked before anything is written: + * foreign — the roster asks for an agent id a hand-authored agent already + * holds; the user's agent wins and is not taken over; + * remove — the apply would delete agents and `allowRemove` is not set. * - * @param {{roster: Record>, dir: string, allowRemove?: boolean, - * describe?: (role: "grunt"|"drill", modelId: string) => string|undefined}} input - * @returns {ApplyDone | ApplyRefused} + * @param {{current: Record, next: Record, allowRemove?: boolean, + * foreign?: Array<{id: string, agent: string}>}} input + * foreign: hand-authored agents holding ids this roster wants + * @returns {PatchOk | PatchRefused} */ -export function applySquad({ roster, dir, allowRemove = false, describe }) { - const { roster: current, conflicts, filesByAgent } = readSquad(dir); - const diff = diffRoster(current, roster); - /** @param {ApplyRefused["refusal"]} refusal @param {string[]} problems @returns {ApplyRefused} */ - const refuse = (refusal, problems) => ({ - ok: false, - refusal, - problems, - diff, - written: [], - pruned: [], - // A shared destination is both a dump note and this refusal: say it once. - conflicts: conflicts.filter((c) => !problems.includes(c)), - dir, - }); - - // The bundled prompts are deliberately NOT read here: an agent file carries a - // fenced placeholder and the plugin injects the current role prompt at - // request time (src/prompt-inject.js), so this writes only frontmatter and - // the roster's own `notes`. - const plan = []; - /** @type {Map} filename -> the agent it is planned for */ - const byFile = new Map(); - const problems = []; - /** @type {string[]} */ - const unreadable = []; - /** @type {string[]} */ - const damaged = []; - /** @type {string[]} */ - const dangling = []; - for (const [key, role] of Object.entries(ROLE_KEYS)) { - for (const [modelId, entry] of Object.entries(roster?.[key] ?? {})) { - const { filename, content } = agentMarkdown(role, modelId, { - ...entry, - description: describe?.(role, modelId), - }); - const agent = `${role} ${modelId}`; - const other = byFile.get(filename); - if (other) { - problems.push(`${other} and ${agent} would both be written to ${filename}`); - continue; - } - byFile.set(filename, agent); - const read = readText(path.join(dir, filename)); - const link = read.state === "missing" ? danglingLinkTarget(path.join(dir, filename)) : null; - if (link !== null) { - dangling.push( - `${path.join(dir, filename)}: symlink to ${link}, which does not exist (${agent} targets it)`, - ); - continue; - } - if (read.state === "error") { - unreadable.push(`${path.join(dir, filename)}: ${read.code} (${agent} targets it)`); - continue; - } - const existing = read.state === "ok" ? read.text : null; - if (existing !== null && !isGenerated(existing)) { - problems.push( - `${filename} exists and was not generated by this plugin (${agent} targets it)`, - ); - continue; - } - if (existing !== null && isDamaged(existing)) { - damaged.push( - `${path.join(dir, filename)}: damaged header, no readable model (${agent} targets it)`, - ); - continue; - } - plan.push({ role, modelId, entry, filename, content, existing }); - } - } - /** @type {string[]} */ - const migrate = []; - /** @type {Array<{file: string, agent: string}>} */ - const duplicates = []; - for (const [agent, files] of filesByAgent) { - if (diff.removed.includes(agent)) continue; - for (const f of files) { - if (byFile.has(f)) continue; - if (f.startsWith("worker-")) migrate.push(f); - else duplicates.push({ file: f, agent }); - } - } - /** Files of removed agents that no kept agent takes over: pruned below. */ - const prune = diff.removed.flatMap((agent) => - (filesByAgent.get(agent) ?? []).filter((f) => !byFile.has(f)), - ); - - // Every path this apply writes, prunes or migrates away. Unlinking a file - // that another loadable name also reaches breaks that agent as surely as - // overwriting it, and allow_remove covers the roster entry, not the other - // agent: so deletions go through the same check as writes, before anything - // changes. - for (const shared of sharedDestinations(dir, [ - ...plan.map((p) => p.filename), - ...prune, - ...duplicates.map((d) => d.file), - ...migrate, - ])) - problems.push(shared.line); - if (unreadable.length) return refuse("unreadable", unreadable); - if (damaged.length) return refuse("damaged", damaged); - if (dangling.length) return refuse("dangling", dangling); - if (problems.length) return refuse("collision", problems); - if ((diff.removed.length > 0 || duplicates.length > 0) && !allowRemove) { - return refuse("remove", [ - ...diff.removed, - ...duplicates.map((d) => `${d.file} (a second file for ${d.agent})`), - ]); - } - - fs.mkdirSync(dir, { recursive: true }); - - /** @type {WrittenAgent[]} */ - const written = []; - // Descriptions follow model_data.json, not the roster, so the roster diff - // cannot see them change; report them separately or an `info` edit - // re-applied reads as "=14 unchanged" while 14 files changed. - const refreshed = []; - for (const { role, modelId, entry, filename, content, existing } of plan) { - const unchanged = existing === content; - if (existing !== null && !unchanged) { - const before = descriptionLine(existing); - const after = descriptionLine(content); - if (before !== after) refreshed.push(`${role} ${modelId}: ${after}`); - } - if (!unchanged) writeFileAtomic(path.join(dir, filename), content); - written.push({ - role, - id: modelId, - variant: entry?.variant, - filename, - ...(unchanged ? { unchanged: true } : {}), - }); - } - - const pruned = []; - for (const f of prune) { - fs.unlinkSync(path.join(dir, f)); - pruned.push(f); - } - for (const { file } of duplicates) { - fs.unlinkSync(path.join(dir, file)); - pruned.push(file); - } - const migrated = []; - for (const f of migrate) { - fs.unlinkSync(path.join(dir, f)); - migrated.push(f); - } - - return { ok: true, diff, written, pruned, migrated, refreshed, conflicts, dir }; -} - -/** - * Bring the existing squad's descriptions in line with model_data.json — run at - * plugin start. opencode reloads agent files on change (an `agent.updated` - * event, seconds later), so an edited `info` or plan reaches the orchestrator - * without anyone re-drafting the squad. - * - * Re-renders each generated file from its own roster entry, so variant, steps - * and notes survive; writes only files whose content actually changes, since - * every write makes opencode reload — and one service process runs this for - * every project it hosts. Files under a legacy name are left for squad_patch, - * which migrates them. - * - * @param {{dir: string, describe: (role: "grunt"|"drill", modelId: string) => string|undefined}} input - * @returns {string[]} filenames rewritten - */ -export function syncDescriptions({ dir, describe }) { - const { roster, filesByAgent } = readSquad(dir); - const planned = []; - for (const [key, role] of Object.entries(ROLE_KEYS)) { - for (const [modelId, entry] of Object.entries(roster[key] ?? {})) { - const { filename, content } = agentMarkdown(role, modelId, { - ...entry, - description: describe(role, modelId), - }); - if (!filesByAgent.get(`${role} ${modelId}`)?.includes(filename)) continue; - planned.push({ filename, content }); - } - } - // The same destination contract as applySquad: paths that reach one file - // are left alone, whoever wrote last would win for both agents. - const shared = sharedDestinations( - dir, - planned.map((p) => p.filename), - ); - const blocked = new Set(shared.flatMap((s) => s.names)); - for (const s of shared) console.warn(`[squad] description refresh skipped: ${s.line}`); - const rewritten = []; - for (const { filename, content } of planned) { - if (blocked.has(filename)) continue; - const file = path.join(dir, filename); - let current; - try { - current = fs.readFileSync(file, "utf8"); - } catch { - continue; - } - if (current === content) continue; - writeFileAtomic(file, content); - rewritten.push(filename); - } - return rewritten; -} - -/** The frontmatter `description:` value as written (quoted or not). */ -/** @param {string} text */ -function descriptionLine(text) { - return /^description: (.*)$/m.exec(text)?.[1] ?? ""; +export function planPatch({ current, next, allowRemove = false, foreign = [] }) { + const diff = diffRoster(current, next); + if (foreign.length) { + return { + ok: false, + refusal: "foreign", + problems: foreign.map((f) => `${f.agent}: agent id ${f.id} is a hand-authored agent`), + diff, + }; + } + if (diff.removed.length && !allowRemove) { + return { ok: false, refusal: "remove", problems: [...diff.removed], diff }; + } + return { ok: true, diff }; } /** - * Human-readable report for an apply — including the variant echo, which is the - * only place a mistyped reasoning level surfaces at all, since opencode drops an - * unknown one silently. + * Human-readable report for squad_patch, including the variant echo, which is + * the only place a mistyped reasoning level surfaces at all, since OpenCode + * drops an unknown one silently. * - * @param {ApplyDone | ApplyRefused} result + * @param {PatchOk | PatchRefused} result + * @param {{store: string, roster: Record>, notes?: string[]}} context * @returns {string} */ -export function formatApplyReport(result) { - const lines = [`Agent dir: ${result.dir}`]; - for (const c of result.conflicts) lines.push(` note ${c}`); +export function formatPatchReport(result, { store, roster, notes = [] }) { + const lines = [`Squad roster: ${store}`]; + for (const n of notes) lines.push(` note ${n}`); - if (!result.ok && result.refusal === "unreadable") { + if (!result.ok && result.refusal === "foreign") { lines.push( "", - "REFUSED: an agent file this roster would replace cannot be read, so it is", - "unknown whether this plugin wrote it:", + "REFUSED: the roster asks for an agent id that a hand-authored agent already holds:", ...result.problems.map((p) => ` - ${p}`), "", - "Nothing was written. The file may be the user's own agent: tell the user and", - "let them fix its permissions or move it. Do not retry until they have.", - ); - return lines.join("\n"); - } - if (!result.ok && result.refusal === "damaged") { - lines.push( - "", - "REFUSED: an agent file this roster would replace has a damaged header, so", - "what it held, and any edits made to it, cannot be carried over:", - ...result.problems.map((p) => ` - ${p}`), - "", - "Nothing was written. Ask the user to repair or delete the file. Do not retry", - "until they have.", - ); - return lines.join("\n"); - } - if (!result.ok && result.refusal === "dangling") { - lines.push( - "", - "REFUSED: an agent file this roster would replace is a symlink whose target", - "does not exist, and writing it would replace the link with a regular file:", - ...result.problems.map((p) => ` - ${p}`), - "", - "Nothing was written and the link is left in place. Ask the user to restore", - "the link's target (e.g. check out their dotfiles) or remove the link. Do not", - "retry until they have.", - ); - return lines.join("\n"); - } - if (!result.ok && result.refusal === "collision") { - lines.push( - "", - "REFUSED: the roster cannot be written without clobbering an agent file:", - ...result.problems.map((p) => ` - ${p}`), - "", - "Nothing was written. Two model ids that differ only in punctuation share a", - "filename — keep one of them. A file that is not ours belongs to the user: ask", - "before touching it.", + "Nothing was written. The existing agent belongs to the user: ask them to rename", + "or remove it, or drop that entry from the roster.", ); return lines.join("\n"); } @@ -579,43 +143,36 @@ export function formatApplyReport(result) { return lines.join("\n"); } - for (const w of result.written) { - lines.push( - ` ${w.unchanged ? "same " : "wrote"} ${w.filename} (${w.id}${w.variant ? `, variant: ${w.variant}` : ""})`, - ); - } - for (const f of result.pruned) lines.push(` pruned ${f}`); - for (const f of result.migrated) lines.push(` migrated away from ${f}`); + const { diff } = result; lines.push( "", - `+${result.diff.added.length} added, -${result.diff.removed.length} removed, ` + - `~${result.diff.changed.length} changed, =${result.diff.unchanged.length} unchanged.`, - ...result.diff.added.map((a) => ` + ${a}`), - ...result.diff.changed.map((c) => ` ~ ${c}`), - ...result.diff.removed.map((r) => ` - ${r}`), + `+${diff.added.length} added, -${diff.removed.length} removed, ` + + `~${diff.changed.length} changed, =${diff.unchanged.length} unchanged.`, + ...diff.added.map((a) => ` + ${a}`), + ...diff.changed.map((c) => ` ~ ${c}`), + ...diff.removed.map((r) => ` - ${r}`), ); - if (result.refreshed?.length) { - lines.push( - "", - `Descriptions refreshed from model_data.json (${result.refreshed.length}):`, - ...result.refreshed.map((r) => ` ~ ${r}`), - ); + const variants = []; + for (const [key, role] of [ + ["grunts", "grunt"], + ["drills", "drill"], + ]) { + for (const [id, entry] of Object.entries(roster[key] ?? {})) { + if (entry?.variant) variants.push(` ${role} ${id} -> ${entry.variant}`); + } } - - const variants = result.written.filter((w) => w.variant); - if (variants.length > 0) { + if (variants.length) { lines.push( "", - "Variants written — opencode IGNORES an unrecognized variant without erroring,", + "Variants set — opencode IGNORES an unrecognized variant without erroring,", "so check each against that model's `reasoning_options` in models.dev:", - ...variants.map((w) => ` ${w.role} ${w.id} -> ${w.variant}`), + ...variants, ); } lines.push( "", - "OpenCode reloads changed agent files automatically; no restart is needed.", - "Role prompt bodies do NOT need this: the plugin refreshes them from the bundled", - "prompts/.md on every request.", + "The plugin re-registered the squad's agents; the change applies to the next dispatch.", + "No agent files are written: the roster above is the whole squad.", ); return lines.join("\n"); } diff --git a/src/squad-store.js b/src/squad-store.js new file mode 100644 index 0000000..91508da --- /dev/null +++ b/src/squad-store.js @@ -0,0 +1,99 @@ +// The squad roster's one home: a JSON file the plugin owns, beside +// model_data.json in the OpenCode config dir. OpenCode never reads it; the +// plugin registers the agents it describes through the agent API +// (src/squad-agents.js), so no agent file is written, pruned or migrated +// (#85, which ended the file-aliasing class of bugs in #16, #51, #52). +// +// A file that exists but does not parse or validate is never overwritten: +// it may hold the user's squad, and a fresh one written over it would lose +// that squad for good. Callers report it and refuse to change the roster. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { writeFileAtomic } from "./fs-atomic.js"; +import { opencodeConfigDir } from "./paths.js"; +import { validateRoster } from "./roster-schema.js"; + +const STORE_VERSION = 1; + +/** The global roster file. */ +export function defaultStoreFile() { + return path.join(opencodeConfigDir(process.env, os.homedir()), "squad.json"); +} + +/** + * @typedef {{grunts: Record>, drills: Record>}} Roster + * @typedef {{state: "missing"} | {state: "ok", roster: Roster} | {state: "invalid", reason: string}} StoreRead + */ + +/** + * @param {string} file + * @returns {StoreRead} + */ +export function readStore(file) { + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch (e) { + const code = /** @type {NodeJS.ErrnoException} */ (e)?.code; + if (code === "ENOENT") return { state: "missing" }; + return { state: "invalid", reason: `cannot read (${code ?? "error"})` }; + } + let doc; + try { + doc = JSON.parse(text); + } catch (e) { + return { state: "invalid", reason: `not valid JSON (${/** @type {Error} */ (e).message})` }; + } + if (!doc || typeof doc !== "object" || Array.isArray(doc)) { + return { state: "invalid", reason: "not a JSON object" }; + } + const { version, ...roster } = doc; + if (version !== STORE_VERSION) { + return { state: "invalid", reason: `unsupported version ${JSON.stringify(version ?? null)}` }; + } + const errors = validateRoster(roster); + if (errors.length) return { state: "invalid", reason: errors.join("; ") }; + return { state: "ok", roster: normalize(roster) }; +} + +/** + * Write the roster, keys sorted so the file diffs cleanly under version + * control. Atomic: a concurrent reader never sees half a squad. + * + * @param {string} file + * @param {{grunts?: Record, drills?: Record}} roster + */ +export function writeStore(file, roster) { + fs.mkdirSync(path.dirname(file), { recursive: true }); + const r = normalize(roster); + writeFileAtomic(file, `${JSON.stringify({ version: STORE_VERSION, ...r }, null, 2)}\n`); +} + +/** + * The file's change signature: other OpenCode processes write it too (the + * desktop service and a CLI share one config dir). + * + * @param {string} file + */ +export function storeSignature(file) { + try { + const st = fs.statSync(file); + return `${st.mtimeMs}:${st.size}`; + } catch { + return "-"; + } +} + +/** + * @param {{grunts?: Record, drills?: Record}} roster + * @returns {Roster} + */ +function normalize(roster) { + /** @param {Record | undefined} map */ + const sorted = (map) => + Object.fromEntries(Object.entries(map ?? {}).sort(([a], [b]) => a.localeCompare(b))); + return { grunts: sorted(roster.grunts), drills: sorted(roster.drills) }; +} diff --git a/src/workers.js b/src/workers.js index 21eeff8..d30dbb6 100644 --- a/src/workers.js +++ b/src/workers.js @@ -1,7 +1,3 @@ -import { parse } from "yaml"; -import { placeholderBody, wrapPrompt } from "./prompt-inject.js"; -import { NOTES_CLOSE, NOTES_OPEN } from "./roster.js"; - // Pure helpers for scaffolding per-model squad subagents — both grunts (workers) // and drills (reviewers) — from one model list. // @@ -10,19 +6,13 @@ import { NOTES_CLOSE, NOTES_OPEN } from "./roster.js"; // materialize one named agent per model per role; each shows up in the inventory // with its model and is dispatched by name. -// Stable prefix that marks our generated files (as a YAML comment) so the -// generator can prune its own previous output without touching hand-authored -// agents. Detection uses this prefix (stable across renames); the full line -// below carries the current skill name for readability. -const GENERATED_MARKER_PREFIX = "generated-by: opencode-squad"; -export const GENERATED_MARKER = `${GENERATED_MARKER_PREFIX} squad-draft`; -// Detection matches files from before the opencode-orchestrate -> squad -// rename too, so regenerating cleanly migrates older generated agents. The two -// markers this plugin has ever written: "opencode-squad" and, before -// the rename, "opencode-orchestrate". Another generator's "opencode-" is not -// ours. +// Versions before #85 wrote each agent as a file marked, on its first +// frontmatter line, with "# generated-by: opencode-squad ..." (or +// "opencode-orchestrate" before the rename). The marker now only identifies +// those files for the one-time import (src/squad-apply.js readLegacySquad); +// another generator's "opencode-" is not ours. const GENERATED_MARKER_DETECT = "generated-by: opencode-(?:squad|orchestrate)(?=[ \\t\\r\\n]|$)"; -// Every version of agentMarkdown has written the marker as the first line of +// Every version that wrote agent files put the marker on the first line of // the frontmatter, so that is the only place it counts: a hand-authored agent // whose prompt quotes the marker is still the user's. No closing fence is // required — a header cut off mid-way is ours, just damaged. An optional BOM @@ -123,6 +113,21 @@ const ROLES = { }, }; +/** + * The permission rules a squad role adds to its agent. The plugin appends + * them after the user's global rules (src/squad-agents.js), so with the host's + * last-match evaluation they decide: a drill stays read-only whatever the + * global config allows. + * + * @param {"grunt"|"drill"} role + * @returns {Array<{action: string, resource: string, effect: string}>} + */ +export function roleRules(role) { + const cfg = ROLES[role]; + if (!cfg) throw new Error(`unknown role: ${role}`); + return cfg.permissions.map((rule) => ({ ...rule })); +} + /** * Turn a `provider/model` id into a stable agent name for a role. * e.g. ("openai/gpt-5.5", "grunt") -> "grunt-openai-gpt-5-5", @@ -154,106 +159,6 @@ export function squadRoleOf(name) { return m ? /** @type {"grunt"|"drill"} */ (m[1]) : null; } -/** - * Render the agent markdown file for one role+model. - * - * `variant` selects the model's reasoning level. opencode builds a model's - * variants from models.dev's `reasoning_options` (glm-5.3 publishes - * `low|high|max`, claude-opus-5 `low|medium|high|xhigh|max`) and lowers the - * chosen one into the provider's own parameter — `reasoning_effort` for - * openai-compatible providers. Without a variant NO reasoning parameter is - * sent, which for an openai-compatible model means its reasoning is bounded by - * nothing but the output cap: measured on glm-5.3, 70% of the token budget went - * to reasoning, with a tail to ~19k reasoning tokens in one turn, and two grunts - * were truncated mid-thought at the 32k cap having emitted 2 and 9 tokens. - * A variant is a HINT ABOUT DEPTH, not a token budget, and it does not stop a - * turn from hitting the cap: on 2026-09-02/03 a glm-5.3 grunt and two - * claude-sonnet-5 grunts were truncated at 32k WITH `variant: high` set. What it - * does change is how often that happens — with the variant, glm-5.3 ran 83 turns - * in a day with none. Treat it as mitigation, not a fix; the fix is the cap. - * - * Nor is Anthropic immune, contrary to what this comment used to claim: sonnet-5 - * burned the whole 32k on reasoning and emitted 0 output tokens. The earlier - * conclusion came from per-message reasoning LENGTHS on another machine and did - * not survive contact with truncation data. - * - * An unknown variant is SILENTLY IGNORED by opencode (`if (!(agent.variant in - * model.variants)) return undefined`), so a typo buys silence, not an error. - * - * `description` is what the orchestrator reads in its subagent inventory when - * choosing who to dispatch. It is PLUGIN-OWNED: built by `describeAgent` from - * the owner's `info` and provider plan in model_data.json, never hand-written - * into the roster — hand-written ones went stale and got invented (see - * describeAgent). Defaults to the role's generic line. - * - * `notes` are extra instructions appended to the role prompt, fenced by markers - * so a dump can read them back — the round trip is what makes the roster - * trustworthy to edit. - * - * The ROLE PROMPT ITSELF is not written here. The file gets a fenced - * placeholder, and the plugin swaps in the current `prompts/.md` on every - * request (src/prompt-inject.js) — so a prompt edit is live without - * regenerating the squad, and the file never carries a second, staler copy of - * a text it does not own. - * - * @param {"grunt"|"drill"} role - * @param {string} modelId e.g. "anthropic/claude-opus-4-7" - * @param {{variant?: string, description?: string, notes?: string, steps?: number, disable?: boolean}} [opts] - * @returns {{slug:string, filename:string, content:string}} - */ -export function agentMarkdown(role, modelId, opts = {}) { - const cfg = ROLES[role]; - if (!cfg) throw new Error(`unknown role: ${role}`); - const slug = slugForModel(modelId, role); - const variant = opts.variant?.trim(); - const description = opts.description?.trim() || cfg.description; - const notes = opts.notes?.trim(); - // Roster `notes` sit OUTSIDE the fence: they belong to this agent, and the - // fence is replaced wholesale on every request. - const fenced = wrapPrompt(role, placeholderBody(role)); - const body = notes ? `${fenced}\n\n${NOTES_OPEN}\n${notes}\n${NOTES_CLOSE}` : fenced; - const content = [ - "---", - `# ${GENERATED_MARKER}`, - // Quoted: owner notes routinely carry ": " or " #", which unquoted YAML - // would turn into a parse error or a silently truncated line. A JSON - // string is valid YAML. - `description: ${JSON.stringify(description)}`, - "mode: subagent", - `model: ${yamlScalar(`${modelId}${variant ? `#${variant}` : ""}`)}`, - // Each emitted only when asked for: an absent key leaves opencode on its - // own default, which is the right behaviour for a model that publishes no - // reasoning options, or an agent nobody has capped. - ...(typeof opts.steps === "number" ? [`steps: ${opts.steps}`] : []), - ...(opts.disable ? ["disabled: true"] : []), - "hidden: true", - "permissions:", - ...cfg.permissions.map((rule) => ` - ${JSON.stringify(rule)}`), - "---", - "", - body, - "", - ].join("\n"); - return { slug, filename: `${slug}.md`, content }; -} - -/** - * A string as a YAML scalar: plain when YAML reads it back unchanged, so the - * files every existing squad already has stay byte-identical; a JSON string - * (valid YAML) otherwise — an id like `p/m: x` or `p/m #x` written plain - * would be a parse error or a silently truncated value. - * - * @param {string} value - */ -function yamlScalar(value) { - try { - if (parse(`v: ${value}`)?.v === value) return value; - } catch { - // Not valid plain: quote it. - } - return JSON.stringify(value); -} - /** * The agent's description, derived from what the user wrote down — never from * benchmarks, which squad_metrics serves live, and never composed by the diff --git a/tests/guard-host.test.js b/tests/guard-host.test.js index 9708695..7729ffc 100644 --- a/tests/guard-host.test.js +++ b/tests/guard-host.test.js @@ -12,11 +12,12 @@ import path from "node:path"; import { afterEach, beforeEach, expect, test, vi } from "vitest"; import { loadModelSettings } from "../.opencode/lib/runtime.js"; import plugin from "../index.js"; +import { defaultStoreFile } from "../src/squad-store.js"; vi.mock("../.opencode/lib/runtime.js", async (importOriginal) => ({ ...(await importOriginal()), ensureGlobalModelDataFresh: () => {}, - syncGlobalSquadDescriptions: () => [], + importLegacySquad: () => ({ imported: 0, problems: [] }), squadDescriber: () => (role, id) => `${role} on ${id}.`, startMetricsRefresh: () => {}, getMetrics: async () => null, @@ -64,7 +65,11 @@ async function host(over = {}) { location: { directory: os.tmpdir() }, options: { rate_limit_guard: { max_silence_seconds: SILENCE_S } }, skill: { transform: async () => {} }, - agent: { list: async () => [] }, + agent: { + list: async () => [], + transform: async () => ({ dispose: async () => {} }), + reload: async () => {}, + }, model: { list: over.modelList ?? (async () => []) }, session: { hook: async (name, callback) => { @@ -230,10 +235,10 @@ test("a failed model catalog lookup is retried by the next call", async () => { const dump = h.tools.get("squad_dump"); const patch = h.tools.get("squad_patch"); // The first lookup fails: variants read as unknown, not as "none". - expect((await dump.execute({ directory })).content).toContain("could not be read"); + expect((await dump.execute({})).content).toContain("could not be read"); // The next one asks again and checks the variant against the catalog. const res = await patch.execute( - { directory, grunts: { "a/b": { variant: "ultra" } } }, + { grunts: { "a/b": { variant: "ultra" } } }, { agent: "build" }, ); expect(res.content).toContain("Roster is invalid"); @@ -241,7 +246,7 @@ test("a failed model catalog lookup is retried by the next call", async () => { expect(fs.readdirSync(directory)).toEqual([]); expect(calls).toBe(2); // A successful catalog is kept. - await dump.execute({ directory }); + await dump.execute({}); expect(calls).toBe(2); } finally { h.dispose(); @@ -261,9 +266,10 @@ test("squad_patch refuses while model_data.json is unreadable, writing nothing", try { const res = await h.tools .get("squad_patch") - .execute({ directory, grunts: { "a/b": {} } }, { agent: "build" }); + .execute({ grunts: { "a/b": {} } }, { agent: "build" }); expect(res.content).toContain("Refused: model_data.json cannot be read"); expect(res.content).toContain("invalid JSON at line 3, column 1"); + expect(fs.existsSync(defaultStoreFile())).toBe(false); expect(fs.readdirSync(directory)).toEqual([]); } finally { h.dispose(); diff --git a/tests/model-data.test.js b/tests/model-data.test.js index aa03992..0da5900 100644 --- a/tests/model-data.test.js +++ b/tests/model-data.test.js @@ -4,8 +4,6 @@ import path from "node:path"; import { afterEach, expect, test } from "vitest"; import { buildModelData, - discoverSquadModels, - extractModelId, LEGACY_PERF_KEYS, mergeModelData, modelsChanged, @@ -23,61 +21,13 @@ function tmpdir() { return dir; } -test("extractModelId reads the frontmatter model line only", () => { - const md = `---\nmode: subagent\nmodel: openai/gpt-5.5\nhidden: true\n---\n\nBody mentions model: anthropic/decoy here.`; - expect(extractModelId(md)).toBe("openai/gpt-5.5"); -}); - -test("extractModelId returns null when absent", () => { - expect(extractModelId("---\nmode: subagent\n---\nbody")).toBeNull(); -}); - -test("extractModelId ignores model: text in the body, with or without a header", () => { - expect(extractModelId("no header\nmodel: x/y\n")).toBeNull(); - expect(extractModelId("---\r\nmode: subagent\r\n---\r\nmodel: x/y\r\n")).toBeNull(); - expect(extractModelId("---\nmode: [broken\n---\nmodel: x/y\n")).toBeNull(); -}); - -test("extractModelId reads CRLF and quoted headers", () => { - expect(extractModelId("---\r\nmodel: p/m#high\r\n---\r\n")).toBe("p/m"); - expect(extractModelId('---\nmodel: "p/m#high"\n---\n')).toBe("p/m"); - expect(extractModelId("---\nmodel: 'p/m'\n---\n")).toBe("p/m"); -}); - -test("extractModelId strips the native V2 variant suffix", () => { - expect(extractModelId("---\nmodel: openai/gpt-5.5#high\n---\n")).toBe("openai/gpt-5.5"); -}); - -test("native drill variants dedupe with grunts and preserve drill-only model data", () => { - const dir = tmpdir(); - try { - fs.writeFileSync(path.join(dir, "grunt-shared.md"), "---\nmodel: openai/gpt-5.5\n---\n"); - fs.writeFileSync(path.join(dir, "drill-shared.md"), "---\nmodel: openai/gpt-5.5#high\n---\n"); - fs.writeFileSync(path.join(dir, "drill-only.md"), "---\nmodel: local/reviewer#high\n---\n"); - expect(discoverSquadModels(dir)).toEqual(["local/reviewer", "openai/gpt-5.5"]); - const snapshot = buildModelData(discoverSquadModels(dir), { - models: { "local/reviewer": { info: "keep this note" } }, - }); - expect(Object.keys(snapshot.models)).toEqual(["local/reviewer", "openai/gpt-5.5"]); - expect(snapshot.models["local/reviewer"].info).toBe("keep this note"); - expect(snapshot.models["openai/gpt-5.5"]).toEqual({ info: "" }); - } finally { - fs.rmSync(dir, { recursive: true, force: true }); - } -}); - -test("discoverSquadModels dedupes grunt+drill of one model and ignores others", () => { - const dir = tmpdir(); - fs.writeFileSync(path.join(dir, "grunt-openai-gpt-5-5.md"), "---\nmodel: openai/gpt-5.5\n---\n"); - fs.writeFileSync(path.join(dir, "drill-openai-gpt-5-5.md"), "---\nmodel: openai/gpt-5.5\n---\n"); - fs.writeFileSync(path.join(dir, "grunt-anthropic-x.md"), "---\nmodel: anthropic/x\n---\n"); - fs.writeFileSync(path.join(dir, "build.md"), "---\nmodel: anthropic/should-ignore\n---\n"); - fs.writeFileSync(path.join(dir, "notes.txt"), "model: nope/nope"); - expect(discoverSquadModels(dir)).toEqual(["anthropic/x", "openai/gpt-5.5"]); -}); - -test("discoverSquadModels returns [] for a missing dir", () => { - expect(discoverSquadModels("/no/such/dir/here")).toEqual([]); +test("drill and grunt of one model share one entry; drill-only notes survive", () => { + const snapshot = buildModelData(["local/reviewer", "openai/gpt-5.5"], { + models: { "local/reviewer": { info: "keep this note" } }, + }); + expect(Object.keys(snapshot.models)).toEqual(["local/reviewer", "openai/gpt-5.5"]); + expect(snapshot.models["local/reviewer"].info).toBe("keep this note"); + expect(snapshot.models["openai/gpt-5.5"]).toEqual({ info: "" }); }); test("mergeModelData keeps hand fields and strips legacy AA perf fields", () => { @@ -108,30 +58,25 @@ test("mergeModelData gives new models empty info and drops removed ones", () => expect("old/removed" in merged).toBe(false); // not in the squad anymore -> dropped }); -test("buildModelData scans a dir and stamps meta", () => { - const dir = tmpdir(); - fs.writeFileSync(path.join(dir, "grunt-openai-gpt-5-5.md"), "---\nmodel: openai/gpt-5.5\n---\n"); - const snap = buildModelData(discoverSquadModels(dir), {}, "2026-06-30"); +test("buildModelData stamps meta", () => { + const snap = buildModelData(["openai/gpt-5.5"], {}, "2026-06-30"); expect(snap._meta.generated).toBe("2026-06-30"); expect(snap._meta.model_count).toBe(1); expect(snap.models["openai/gpt-5.5"]).toEqual({ info: "" }); }); test("modelsChanged detects real model diffs and ignores rebuild churn", () => { - const dir = tmpdir(); - fs.writeFileSync(path.join(dir, "grunt-openai-gpt-5-5.md"), "---\nmodel: openai/gpt-5.5\n---\n"); - const first = buildModelData(discoverSquadModels(dir), {}, "2026-06-30"); + const first = buildModelData(["openai/gpt-5.5"], {}, "2026-06-30"); // rebuild on a later date over the prior output: same models -> no change, // so the startup auto-regen must NOT rewrite just because the date moved. - const second = buildModelData(discoverSquadModels(dir), first, "2026-07-15"); + const second = buildModelData(["openai/gpt-5.5"], first, "2026-07-15"); expect(modelsChanged(first, second)).toBe(false); // a hand-edited info IS a change worth persisting const edited = { models: { ...first.models } }; edited.models["openai/gpt-5.5"] = { ...edited.models["openai/gpt-5.5"], info: "new note" }; expect(modelsChanged(first, edited)).toBe(true); // a new squad member is a change - fs.writeFileSync(path.join(dir, "grunt-anthropic-x.md"), "---\nmodel: anthropic/x\n---\n"); - const third = buildModelData(discoverSquadModels(dir), second, "2026-07-15"); + const third = buildModelData(["anthropic/x", "openai/gpt-5.5"], second, "2026-07-15"); expect(modelsChanged(second, third)).toBe(true); }); @@ -170,10 +115,8 @@ test("readModelDataFile tells an invalid file apart from a missing one, without }); test("buildModelData keeps the hand-written providers section", () => { - const dir = tmpdir(); - fs.writeFileSync(path.join(dir, "grunt-anthropic-x.md"), "---\nmodel: anthropic/x\n---\n"); const snap = buildModelData( - discoverSquadModels(dir), + ["anthropic/x"], { providers: { anthropic: "Max 5x" }, models: {} }, "2026-11-12", ); diff --git a/tests/plugin-entry.test.js b/tests/plugin-entry.test.js index 55cfa14..935912b 100644 --- a/tests/plugin-entry.test.js +++ b/tests/plugin-entry.test.js @@ -1,6 +1,7 @@ // Suite: the package entry (index.js → .opencode/lib/squad.js) as an // OpenCode 2 host sees it. Covers setup registering the squad_* tools, -// squad_patch generating native V2 agent files, and squad_metrics rendering +// squad_patch writing squad.json and registering the agents through the +// host's agent transforms (#85), and squad_metrics rendering // host models + cached metrics, with the startup network refreshes stubbed at // the runtime boundary. Not covered: live hook firing, // rate-limit guard and skill loading — those need a real host or their own @@ -11,6 +12,8 @@ import os from "node:os"; import path from "node:path"; import { afterEach, expect, test, vi } from "vitest"; import plugin from "../index.js"; +import { defaultStoreFile, readStore } from "../src/squad-store.js"; +import { roleRules } from "../src/workers.js"; // Startup refreshes write global model data and schedule network requests; // leave tool registration and the filesystem generator real. @@ -42,8 +45,7 @@ vi.mock("../.opencode/lib/runtime.js", async (importOriginal) => { return { ...(await importOriginal()), ensureGlobalModelDataFresh: () => {}, - // Both would touch the REAL global agent dir / model_data.json. - syncGlobalSquadDescriptions: () => [], + importLegacySquad: () => ({ imported: 0, problems: [] }), squadDescriber: () => (role, id) => `${role} on ${id}. Owner rule: no secrets.`, startMetricsRefresh: () => {}, // A test may swap in its own cache contents. @@ -65,44 +67,85 @@ vi.mock("../.opencode/lib/runtime.js", async (importOriginal) => { * * @param {{directory: string} & Record} host */ -async function setupHost({ directory, ...over }) { +async function setupHost({ directory, agent, ...over }) { const tools = new Map(); + /** Agent transforms in registration order, as the host keeps them. */ + const transforms = []; + /** @type {Map unknown>} */ + const hooks = new Map(); const dispose = await plugin.setup({ location: { directory }, options: { rate_limit_guard: { enabled: false } }, skill: { transform: async () => {} }, - session: { hook: async () => {} }, + session: { + hook: async (name, callback) => { + hooks.set(name, callback); + }, + }, model: { list: async () => [] }, tool: { hook: async () => {}, transform: async (register) => register({ add: (tool) => tools.set(tool.name, tool) }), }, + agent: { + list: async () => registered(), + transform: async (callback) => { + transforms.push(callback); + return { dispose: async () => {} }; + }, + reload: async () => {}, + ...agent, + }, ...over, }); - return { tools, dispose }; + /** The agent list the host would build: every transform over a fresh editor. */ + function registered() { + const map = new Map(); + const editor = { + list: () => [...map.values()], + get: (id) => map.get(id), + remove: (id) => map.delete(id), + default: () => {}, + update: (id, f) => { + const a = map.get(id) ?? { id, permissions: [] }; + f(a); + map.set(id, a); + }, + }; + for (const t of transforms) t(editor); + return [...map.values()]; + } + /** The first request: registers the late transform. */ + const firstRequest = () => hooks.get("context")?.({ agent: "build", system: [] }); + return { tools, dispose, registered, firstRequest }; } const dirs = []; afterEach(() => { for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); + // squad.json lives in the per-run config dir (tests/setup-isolation.js). + fs.rmSync(defaultStoreFile(), { force: true }); }); -test("package exposes only setup and squad_patch generates native agents", async () => { +test("package exposes only setup; squad_patch writes squad.json and registers the agents", async () => { expect(plugin.server).toBeUndefined(); const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); dirs.push(directory); const input = { - directory, grunts: { "a/b": { variant: "high" } }, - drills: { "a/b": { variant: "high" } }, + drills: { "a/b": { variant: "max" } }, }; - const { tools, dispose } = await setupHost({ directory }); + const { tools, dispose, registered, firstRequest } = await setupHost({ directory }); let wrapped; + let report; + let scoped; try { + await firstRequest(); const patch = tools.get("squad_patch"); // A roster wrapped one level too deep must not read as "delete everything". - wrapped = (await patch.execute({ roster: input, directory }, { agent: "build" })).content; - await patch.execute(input, { agent: "build" }); + wrapped = (await patch.execute({ roster: input }, { agent: "build" })).content; + scoped = (await patch.execute({ ...input, directory }, { agent: "build" })).content; + report = (await patch.execute(input, { agent: "build" })).content; } finally { dispose(); } @@ -117,12 +160,24 @@ test("package exposes only setup and squad_patch generates native agents", async ); expect(wrapped).toContain("Refused: pass `grunts` and/or `drills` at the TOP level"); expect(wrapped).toContain("`roster`"); - for (const role of ["grunt", "drill"]) { - const content = fs.readFileSync(path.join(directory, `${role}-a-b.md`), "utf8"); - expect(content).toContain(`description: "${role} on a/b. Owner rule: no secrets."\n`); - expect(content).toContain("permissions:\n"); - expect(content).toContain("model: a/b#high\n"); - expect(content).not.toContain("permission:"); + expect(scoped).toContain("`directory` is no longer supported"); + expect(report).toContain("+2 added"); + expect(readStore(defaultStoreFile())).toEqual({ state: "ok", roster: input }); + // Nothing written next to the project, and no agent file anywhere. + expect(fs.readdirSync(directory)).toEqual([]); + const agents = registered(); + for (const [role, variant] of [ + ["grunt", "high"], + ["drill", "max"], + ]) { + const agent = agents.find((a) => a.id === `${role}-a-b`); + expect(agent).toMatchObject({ + mode: "subagent", + hidden: true, + description: `${role} on a/b. Owner rule: no secrets.`, + model: { providerID: "a", id: "b", variant }, + }); + expect(agent.permissions.slice(-roleRules(role).length)).toEqual(roleRules(role)); } }); @@ -300,8 +355,8 @@ test("squad_patch validates its input with the same schema it advertises", async dirs.push(directory); const { tools, dispose } = await setupHost({ directory }); const patch = tools.get("squad_patch"); - const run = async (input) => - (await patch.execute({ directory, ...input }, { agent: "build" })).content; + const run = async (input) => (await patch.execute(input, { agent: "build" })).content; + const stored = () => readStore(defaultStoreFile()).state; try { // Advertised: the plain JSON Schema subset, no Zod-only keywords. const advertised = JSON.stringify(patch.input); @@ -321,21 +376,25 @@ test("squad_patch validates its input with the same schema it advertises", async expect(bad).toContain('grunts["a/b"].steps must be a positive integer when present'); expect(bad).toContain('grunts["a/b"] has unknown key "colour"'); expect(bad).toContain('grunts["nope"]: "nope" is not a provider/model id'); - expect(fs.readdirSync(directory)).toEqual([]); + expect(stored()).toBe("missing"); } // The call's own switches go through the same schema. const switches = await run({ allow_remove: "true", grunts: { "a/b": {} } }); expect(switches).toContain("allow_remove must be a boolean when present"); - expect(fs.readdirSync(directory)).toEqual([]); + expect(stored()).toBe("missing"); // Wrapped or missing roster: refused before validation, nothing written. expect(await run({ roster: { grunts: { "a/b": {} } } })).toContain("Refused: pass `grunts`"); expect(await run({})).toContain("Refused: pass `grunts`"); - expect(fs.readdirSync(directory)).toEqual([]); + expect(stored()).toBe("missing"); // A valid one-role roster is written. - expect(await run({ grunts: { "a/b": { variant: "high" } } })).toContain("wrote grunt-a-b.md"); - expect(fs.readdirSync(directory)).toEqual(["grunt-a-b.md"]); + expect(await run({ grunts: { "a/b": { variant: "high" } } })).toContain("+1 added"); + expect(readStore(defaultStoreFile())).toEqual({ + state: "ok", + roster: { grunts: { "a/b": { variant: "high" } }, drills: {} }, + }); + expect(fs.readdirSync(directory)).toEqual([]); } finally { dispose(); } diff --git a/tests/prompt-inject.test.js b/tests/prompt-inject.test.js index 55c4335..ae4b3ce 100644 --- a/tests/prompt-inject.test.js +++ b/tests/prompt-inject.test.js @@ -9,8 +9,7 @@ import { promptOpen, wrapPrompt, } from "../src/prompt-inject.js"; -import { parseAgentFile } from "../src/roster.js"; -import { agentMarkdown } from "../src/workers.js"; +import { agentSpecs } from "../src/squad-agents.js"; const sys = (text) => [text]; @@ -123,49 +122,29 @@ describe("createPromptLoader", () => { }); }); -describe("generated agent files carry the fence", () => { - it("fences a placeholder — never a copy of the role prompt — with notes outside it", () => { - const { content } = agentMarkdown("grunt", "anthropic/claude-opus-5", { - notes: "this model over-scaffolds", - }); - const fence = findPromptFence(content); - expect(fence.role).toBe("grunt"); - expect(content.slice(fence.start, fence.end)).toBe( - wrapPrompt("grunt", placeholderBody("grunt")), - ); - expect(content.indexOf("")).toBeGreaterThan(fence.end); - }); +describe("registered squad agents carry the fence", () => { + const io = { describe: () => "d", prompt: () => "BUNDLED BODY" }; - it("the placeholder tells an unhelped agent to stop rather than improvise", () => { - const { content } = agentMarkdown("grunt", "a/b"); - expect(content).toContain("squad prompt missing"); - expect(content).toContain("Do not"); + it("fences the role prompt, with notes outside it", () => { + const [spec] = agentSpecs({ grunts: { "a/b": { notes: "this model over-scaffolds" } } }, io); + const fence = findPromptFence(spec.system); + expect(fence.role).toBe("grunt"); + expect(spec.system.slice(fence.start, fence.end)).toBe(wrapPrompt("grunt", "BUNDLED BODY")); + expect(spec.system.indexOf("")).toBeGreaterThan(fence.end); }); - it("round-trips through parseAgentFile with notes and model intact", () => { - const { content } = agentMarkdown("grunt", "anthropic/claude-opus-5", { - variant: "high", - notes: "this model over-scaffolds", - }); - const { modelId, entry } = parseAgentFile(content); - expect(modelId).toBe("anthropic/claude-opus-5"); - expect(entry).toEqual({ - variant: "high", - notes: "this model over-scaffolds", - }); - // Regenerating from what was read back must reproduce the same file — the - // fence sits before the notes markers, which is exactly where a parser - // reading by index could start eating them. - const again = agentMarkdown("grunt", modelId, entry); - expect(again.content).toBe(content); + it("an unreadable prompt registers the placeholder, which tells the agent to stop", () => { + const [spec] = agentSpecs({ grunts: { "a/b": {} } }, { ...io, prompt: () => null }); + expect(spec.system).toContain(placeholderBody("grunt")); + expect(spec.system).toContain("squad prompt missing"); }); - it("the placeholder is replaced by the real prompt, notes intact", () => { - const { content } = agentMarkdown("drill", "zai-coding-plan/glm-5.3", { notes: "keep me" }); - const system = sys(content); - applySystemPromptTransform(system, () => "REAL ROLE BODY"); - expect(system[0]).toContain("REAL ROLE BODY"); - expect(system[0]).not.toContain("squad prompt missing"); + it("the per-request splice replaces the registered body with the current one, notes intact", () => { + const [spec] = agentSpecs({ drills: { "z/glm": { notes: "keep me" } } }, io); + const system = sys(spec.system); + applySystemPromptTransform(system, () => "EDITED ROLE BODY"); + expect(system[0]).toContain("EDITED ROLE BODY"); + expect(system[0]).not.toContain("BUNDLED BODY"); expect(system[0]).toContain("keep me"); expect(system[0]).toContain(PROMPT_CLOSE); }); diff --git a/tests/regress-squad-files.test.js b/tests/regress-squad-files.test.js deleted file mode 100644 index 7ff5f75..0000000 --- a/tests/regress-squad-files.test.js +++ /dev/null @@ -1,492 +0,0 @@ -// Suite: regressions for unreadable and damaged squad files — #16 (an -// unreadable or damaged apply target), #17 (startup model_data refresh dropping models it -// could not read), #21 (incomplete headers, model ids that are not plain -// YAML), #51 (the generator marker quoted in a hand-authored prompt) and #52 -// (a dangling symlink at an apply target). Run: npx vitest run tests/regress-squad-files.test.js - -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; -import { afterEach, beforeEach, expect, test, vi } from "vitest"; -import { parse } from "yaml"; -import { ensureGlobalModelDataFresh } from "../.opencode/lib/runtime.js"; -import { readFrontmatter } from "../src/frontmatter.js"; -import { parseAgentFile } from "../src/roster.js"; -import { - AGENT_SOURCES, - applySquad, - formatApplyReport, - readSquad, - syncDescriptions, -} from "../src/squad-apply.js"; -import { parseSkillFile } from "../src/v2/skills.js"; -import { agentMarkdown } from "../src/workers.js"; - -const originalXdg = process.env.XDG_CONFIG_HOME; -let root; -let agentDir; -let globalFile; - -beforeEach(() => { - root = fs.mkdtempSync(path.join(os.tmpdir(), "squad-regress-")); - process.env.XDG_CONFIG_HOME = root; - agentDir = path.join(root, "opencode", "agent"); - globalFile = path.join(root, "opencode", "model_data.json"); - fs.mkdirSync(agentDir, { recursive: true }); - vi.spyOn(console, "warn").mockImplementation(() => {}); -}); -afterEach(() => { - vi.restoreAllMocks(); - if (originalXdg === undefined) delete process.env.XDG_CONFIG_HOME; - else process.env.XDG_CONFIG_HOME = originalXdg; - // Undo the permission tests' chmod; symlinks (possibly dangling) are left - // alone and a subdirectory keeps its search bit. - for (const f of fs.readdirSync(agentDir)) { - const p = path.join(agentDir, f); - const st = fs.lstatSync(p); - if (st.isDirectory()) fs.chmodSync(p, 0o700); - else if (st.isFile()) fs.chmodSync(p, 0o600); - } - fs.rmSync(root, { recursive: true, force: true }); -}); - -/** @param {"grunt"|"drill"} role @param {string} modelId */ -function addAgent(role, modelId) { - const { filename, content } = agentMarkdown(role, modelId, {}); - fs.writeFileSync(path.join(agentDir, filename), content); - return { filename, content }; -} - -const isRoot = process.getuid?.() === 0; - -// #21 - -test("a block opened and never closed is incomplete, not absent", () => { - const cut = '---\n# generated-by: opencode-squad squad-draft\ndescription: "x"\nmod'; - const fm = readFrontmatter(cut); - expect(fm.state).toBe("incomplete"); - expect(parseAgentFile(cut).modelId).toBeUndefined(); - // A skill keeps reading the whole text as its body, as before. - expect(parseSkillFile(cut)).toEqual({ fields: {}, body: cut }); - expect(readFrontmatter("---").state).toBe("incomplete"); - expect(readFrontmatter("--- not a delimiter\nmodel: a/b").state).toBe("none"); -}); - -test("a model id that is not a plain YAML scalar is written as a string and round-trips", () => { - const { content } = agentMarkdown("grunt", "p/m: x", { variant: "high" }); - const header = /^---\n([\s\S]*?)\n---\n/.exec(content)?.[1]; - expect(parse(header ?? "").model).toBe("p/m: x#high"); - expect(readFrontmatter(content).state).toBe("ok"); - expect(parseAgentFile(content)).toMatchObject({ modelId: "p/m: x", entry: { variant: "high" } }); -}); - -test("a plain model id stays unquoted, so existing squads are not rewritten", () => { - expect(agentMarkdown("grunt", "a/b", { variant: "high" }).content).toContain("model: a/b#high\n"); -}); - -// #17 — each case keeps one healthy agent, so the "no squad, no write" path -// cannot make it pass. - -const twoModels = () => - JSON.stringify({ models: { "a/b": { info: "rule ab" }, "c/d": { info: "rule cd" } } }); - -test("a generated agent with a cut-off header keeps its model in model_data", () => { - addAgent("grunt", "a/b"); - const { filename, content } = addAgent("grunt", "c/d"); - // Truncated in the middle of the header: the marker survives, the model line does not. - fs.writeFileSync(path.join(agentDir, filename), content.slice(0, content.indexOf("model:") + 4)); - fs.writeFileSync(globalFile, twoModels()); - const before = fs.readFileSync(globalFile, "utf8"); - const r = ensureGlobalModelDataFresh(); - expect(r.wrote).toBe(false); - expect(r.problem).toContain(`no model in ${filename}`); - expect(fs.readFileSync(globalFile, "utf8")).toBe(before); - // squad_dump names the damaged file instead of silently dropping it. - expect(readSquad(agentDir).conflicts.join("\n")).toContain(filename); -}); - -test("a legacy worker- file keeps its model in model_data", () => { - addAgent("grunt", "a/b"); - const { content } = agentMarkdown("grunt", "c/d", {}); - fs.writeFileSync(path.join(agentDir, "worker-c-d.md"), content); - fs.writeFileSync(globalFile, twoModels()); - ensureGlobalModelDataFresh(); - const models = JSON.parse(fs.readFileSync(globalFile, "utf8")).models; - expect(models["c/d"]).toEqual({ info: "rule cd" }); - expect(models["a/b"]).toEqual({ info: "rule ab" }); -}); - -test("a hand-authored worker- file is not part of the squad", () => { - addAgent("grunt", "a/b"); - fs.writeFileSync(path.join(agentDir, "worker-mine.md"), "---\nmodel: x/y\n---\nMINE\n"); - fs.writeFileSync(globalFile, JSON.stringify({ models: { "a/b": { info: "" } } })); - ensureGlobalModelDataFresh(); - expect(Object.keys(JSON.parse(fs.readFileSync(globalFile, "utf8")).models)).toEqual(["a/b"]); -}); - -test("a hand-authored grunt- file without a readable model does not block the refresh", () => { - addAgent("grunt", "a/b"); - // Not valid YAML (": " in a plain scalar) and no model line: the file owns no entry. - fs.writeFileSync( - path.join(agentDir, "grunt-mine.md"), - "---\ndescription: Reviews code: fast\n---\nMINE\n", - ); - fs.writeFileSync(path.join(agentDir, "grunt-rule.md"), "---\nHorizontal rule above, no header\n"); - addAgent("grunt", "c/d"); - fs.writeFileSync(globalFile, JSON.stringify({ models: { "a/b": { info: "rule ab" } } })); - expect(ensureGlobalModelDataFresh()).toEqual({ wrote: true }); - expect(Object.keys(JSON.parse(fs.readFileSync(globalFile, "utf8")).models)).toEqual([ - "a/b", - "c/d", - ]); -}); - -test("a CRLF header that is never closed is incomplete too", () => { - expect(readFrontmatter("---\r\nmodel: a/b\r\n").state).toBe("incomplete"); -}); - -// #16 - -test.skipIf(isRoot)("an unreadable file at a planned destination refuses the whole apply", () => { - const target = path.join(agentDir, "grunt-a-b.md"); - fs.writeFileSync(target, "---\nmodel: a/b\n---\nMY OWN AGENT\n", { mode: 0o600 }); - fs.chmodSync(target, 0o000); - const result = applySquad({ - roster: { grunts: { "a/b": {}, "c/d": {} }, drills: {} }, - dir: agentDir, - }); - expect(result.ok).toBe(false); - expect(result.ok ? null : result.refusal).toBe("unreadable"); - expect(result.ok ? [] : result.problems).toEqual([`${target}: EACCES (grunt a/b targets it)`]); - expect(formatApplyReport(result)).toMatch(/REFUSED: an agent file this roster would replace/); - // Nothing else was written, and the file is as it was. - expect(fs.readdirSync(agentDir)).toEqual(["grunt-a-b.md"]); - // Still unreadable at that path: neither replaced nor re-permissioned. - expect(() => fs.readFileSync(target)).toThrow(/EACCES/); - fs.chmodSync(target, 0o600); - expect(fs.readFileSync(target, "utf8")).toBe("---\nmodel: a/b\n---\nMY OWN AGENT\n"); -}); - -test("a damaged generated file at a planned destination refuses the whole apply", () => { - const { filename, content } = addAgent("grunt", "a/b"); - const target = path.join(agentDir, filename); - // Cut off mid-header (marker kept, model line lost), then edited by hand. - const damaged = `${content.slice(0, content.indexOf("model:") + 4)}\n# my local edit\n`; - fs.writeFileSync(target, damaged); - // squad_dump reports this very file as damaged and left in place. - expect(readSquad(agentDir).conflicts.join("\n")).toContain( - `${filename}: generated file with no readable model`, - ); - const result = applySquad({ - roster: { grunts: { "a/b": {}, "c/d": {} }, drills: {} }, - dir: agentDir, - }); - expect(result.ok).toBe(false); - expect(result.ok ? null : result.refusal).toBe("damaged"); - expect(result.ok ? [] : result.problems).toEqual([ - `${target}: damaged header, no readable model (grunt a/b targets it)`, - ]); - const report = formatApplyReport(result); - expect(report).toMatch(/REFUSED: an agent file this roster would replace has a damaged header/); - expect(report).not.toMatch(/DELETE|allow_remove/); - // Nothing else was written, and the damaged file keeps its bytes. - expect(fs.readdirSync(agentDir)).toEqual([filename]); - expect(fs.readFileSync(target, "utf8")).toBe(damaged); -}); - -// #51 - -// The marker as a markdown heading on its own line in the body: a line-anchored -// check would still claim this file, only the header position must not. -const handAuthoredQuotingMarker = [ - "---", - 'description: "my own grunt"', - "mode: subagent", - "model: a/b", - "---", - "", - "Squad files carry this line, do not copy it:", - "# generated-by: opencode-squad squad-draft", - "", -].join("\n"); - -test("a hand-authored agent quoting the generator marker is not ours to sync", () => { - const target = path.join(agentDir, "grunt-a-b.md"); - fs.writeFileSync(target, handAuthoredQuotingMarker); - expect(readSquad(agentDir).roster).toEqual({ grunts: {}, drills: {} }); - expect(syncDescriptions({ dir: agentDir, describe: () => "new description" })).toEqual([]); - expect(fs.readFileSync(target, "utf8")).toBe(handAuthoredQuotingMarker); -}); - -test("a hand-authored agent quoting the generator marker is a collision for squad_patch", () => { - const target = path.join(agentDir, "grunt-a-b.md"); - fs.writeFileSync(target, handAuthoredQuotingMarker); - const result = applySquad({ roster: { grunts: { "a/b": {} }, drills: {} }, dir: agentDir }); - expect(result.ok ? null : result.refusal).toBe("collision"); - expect(result.ok ? [] : result.problems).toEqual([ - "grunt-a-b.md exists and was not generated by this plugin (grunt a/b targets it)", - ]); - expect(fs.readFileSync(target, "utf8")).toBe(handAuthoredQuotingMarker); -}); - -test("a generated file saved with CRLF line endings is still ours", () => { - const { filename, content } = agentMarkdown("grunt", "a/b", {}); - fs.writeFileSync(path.join(agentDir, filename), content.replaceAll("\n", "\r\n")); - expect(readSquad(agentDir).roster.grunts).toHaveProperty("a/b"); -}); - -test("another generator's opencode-* marker does not make a file ours", () => { - const other = [ - "---", - "# generated-by: opencode-other-tool", - "model: a/b", - "---", - "Their prompt.", - "", - ].join("\n"); - const target = path.join(agentDir, "grunt-a-b.md"); - fs.writeFileSync(target, other); - expect(readSquad(agentDir).roster).toEqual({ grunts: {}, drills: {} }); - expect(syncDescriptions({ dir: agentDir, describe: () => "new description" })).toEqual([]); - const result = applySquad({ roster: { grunts: { "a/b": {} }, drills: {} }, dir: agentDir }); - expect(result.ok ? null : result.refusal).toBe("collision"); - expect(fs.readFileSync(target, "utf8")).toBe(other); -}); - -test("a file with the pre-rename opencode-orchestrate marker is still ours", () => { - const { filename, content } = agentMarkdown("grunt", "a/b", {}); - const legacy = content.replace( - /generated-by: opencode-squad[^\n]*/, - "generated-by: opencode-orchestrate generating-model-workers", - ); - fs.writeFileSync(path.join(agentDir, filename), legacy); - expect(readSquad(agentDir).roster.grunts).toHaveProperty("a/b"); -}); - -// #52 - -test("two agent paths linked to one file refuse the apply and change nothing", () => { - const shared = path.join(root, "dotfiles", "a-b.md"); - fs.mkdirSync(path.dirname(shared), { recursive: true }); - const { content } = agentMarkdown("grunt", "a/b", {}); - fs.writeFileSync(shared, content); - fs.symlinkSync(shared, path.join(agentDir, "grunt-a-b.md")); - fs.symlinkSync(shared, path.join(agentDir, "drill-a-b.md")); - const result = applySquad({ - roster: { grunts: { "a/b": { variant: "low" } }, drills: { "a/b": { variant: "high" } } }, - dir: agentDir, - }); - expect(result.ok ? null : result.refusal).toBe("collision"); - expect(result.ok ? [] : result.problems).toEqual([ - `drill-a-b.md, grunt-a-b.md all lead to ${fs.realpathSync(shared)}; each agent needs its own file`, - ]); - expect(fs.readFileSync(shared, "utf8")).toBe(content); -}); - -test("startup description sync leaves a shared destination intact and names it", () => { - const shared = path.join(root, "dotfiles", "a-b.md"); - fs.mkdirSync(path.dirname(shared), { recursive: true }); - const { content } = agentMarkdown("grunt", "a/b", {}); - fs.writeFileSync(shared, content); - fs.symlinkSync(shared, path.join(agentDir, "grunt-a-b.md")); - fs.symlinkSync(shared, path.join(agentDir, "drill-a-b.md")); - const line = `drill-a-b.md, grunt-a-b.md all lead to ${fs.realpathSync(shared)}; each agent needs its own file`; - expect(syncDescriptions({ dir: agentDir, describe: (role) => `new ${role}` })).toEqual([]); - expect(fs.readFileSync(shared, "utf8")).toBe(content); - expect(console.warn).toHaveBeenCalledWith(`[squad] description refresh skipped: ${line}`); - // squad_dump surfaces it as well. - expect(readSquad(agentDir).conflicts).toContain(line); -}); - -test("a link onto an agent in a subdirectory is a shared destination too", () => { - const nested = path.join(agentDir, "nested", "other-agent.md"); - fs.mkdirSync(path.dirname(nested)); - const { content } = agentMarkdown("grunt", "a/b", {}); - fs.writeFileSync(nested, content); - fs.symlinkSync(nested, path.join(agentDir, "grunt-a-b.md")); - const line = `grunt-a-b.md, nested/other-agent.md all lead to ${fs.realpathSync(nested)}; each agent needs its own file`; - expect(readSquad(agentDir).conflicts).toContain(line); - expect(syncDescriptions({ dir: agentDir, describe: () => "new" })).toEqual([]); - const result = applySquad({ - roster: { grunts: { "a/b": { variant: "low" } }, drills: {} }, - dir: agentDir, - }); - expect(result.ok ? null : result.refusal).toBe("collision"); - expect(fs.readFileSync(nested, "utf8")).toBe(content); -}); - -test.skipIf(isRoot)("an unlistable subdirectory holds every write back and is named", () => { - const shared = path.join(agentDir, "grunt-a-b.md"); - const { content } = agentMarkdown("grunt", "a/b", {}); - fs.writeFileSync(shared, content); - fs.symlinkSync(shared, path.join(agentDir, "drill-a-b.md")); - const locked = path.join(agentDir, "locked"); - fs.mkdirSync(locked); - fs.chmodSync(locked, 0o000); - const line = (targets) => - `cannot list ${locked} (EACCES), so whether ${targets} share a file with an agent there is unknown`; - expect(readSquad(agentDir).conflicts).toContain(line("drill-a-b.md, grunt-a-b.md")); - expect(syncDescriptions({ dir: agentDir, describe: (role) => `new ${role}` })).toEqual([]); - expect(fs.readFileSync(shared, "utf8")).toBe(content); - const result = applySquad({ - roster: { grunts: { "a/b": { variant: "low" } }, drills: {} }, - dir: agentDir, - }); - expect(result.ok ? null : result.refusal).toBe("collision"); - expect(fs.readFileSync(shared, "utf8")).toBe(content); -}); - -test("a symlinked subdirectory is walked like OpenCode walks it", () => { - const elsewhere = path.join(root, "dotfiles", "more"); - fs.mkdirSync(elsewhere, { recursive: true }); - const { content } = agentMarkdown("grunt", "a/b", {}); - fs.writeFileSync(path.join(elsewhere, "other.md"), content); - fs.symlinkSync(elsewhere, path.join(agentDir, "more")); - fs.symlinkSync(path.join(elsewhere, "other.md"), path.join(agentDir, "grunt-a-b.md")); - expect(readSquad(agentDir).conflicts.join("\n")).toMatch( - /grunt-a-b\.md, more\/other\.md all lead to/, - ); -}); - -test("an agents/ directory link onto agent/ makes a second name for every file", () => { - const { filename, content } = addAgent("grunt", "a/b"); - const agents = path.join(path.dirname(agentDir), "agents"); - fs.mkdirSync(agents); - fs.symlinkSync("../agent", path.join(agents, "team")); - const line = `../agents/team/${filename}, ${filename} all lead to ${fs.realpathSync(path.join(agentDir, filename))}; each agent needs its own file`; - expect(readSquad(agentDir).conflicts).toContain(line); - expect(syncDescriptions({ dir: agentDir, describe: () => "new" })).toEqual([]); - const result = applySquad({ - roster: { grunts: { "a/b": { variant: "low" } }, drills: {} }, - dir: agentDir, - }); - expect(result.ok ? null : result.refusal).toBe("collision"); - expect(fs.readFileSync(path.join(agentDir, filename), "utf8")).toBe(content); -}); - -test("a directory link back to the agent root is a gap, not a skipped path", () => { - const { filename, content } = addAgent("grunt", "a/b"); - fs.symlinkSync(".", path.join(agentDir, "self")); - expect(readSquad(agentDir).conflicts.join("\n")).toMatch( - /self \(links back to a directory above it\)/, - ); - expect(syncDescriptions({ dir: agentDir, describe: () => "new" })).toEqual([]); - const result = applySquad({ - roster: { grunts: { "a/b": { variant: "low" } }, drills: {} }, - dir: agentDir, - }); - expect(result.ok ? null : result.refusal).toBe("collision"); - expect(fs.readFileSync(path.join(agentDir, filename), "utf8")).toBe(content); -}); - -test("a primary-agent alias in mode/ shares the file; one in mode/sub/ is never loaded", () => { - const { filename, content } = addAgent("grunt", "a/b"); - const mode = path.join(path.dirname(agentDir), "mode"); - fs.mkdirSync(path.join(mode, "sub"), { recursive: true }); - fs.symlinkSync(path.join(agentDir, filename), path.join(mode, "sub", "deep.md")); - // Not loadable (mode/ is read top level only): no conflict yet. - expect(readSquad(agentDir).conflicts).toEqual([]); - fs.symlinkSync(path.join(agentDir, filename), path.join(mode, "review.md")); - const line = `../mode/review.md, ${filename} all lead to ${fs.realpathSync(path.join(agentDir, filename))}; each agent needs its own file`; - expect(readSquad(agentDir).conflicts).toContain(line); - expect(syncDescriptions({ dir: agentDir, describe: () => "new" })).toEqual([]); - const result = applySquad({ - roster: { grunts: { "a/b": { variant: "low" } }, drills: {} }, - dir: agentDir, - }); - expect(result.ok ? null : result.refusal).toBe("collision"); - expect(fs.readFileSync(path.join(agentDir, filename), "utf8")).toBe(content); -}); - -test("pruning a file another loadable agent links to is refused, allow_remove or not", () => { - const { filename, content } = addAgent("grunt", "a/b"); - const mode = path.join(path.dirname(agentDir), "mode"); - fs.mkdirSync(mode); - fs.symlinkSync(path.join(agentDir, filename), path.join(mode, "review.md")); - const result = applySquad({ - roster: { grunts: {}, drills: {} }, - dir: agentDir, - allowRemove: true, - }); - expect(result.ok ? null : result.refusal).toBe("collision"); - expect(result.ok ? [] : result.problems.join("\n")).toMatch( - /\.\.\/mode\/review\.md, grunt-a-b\.md all lead to/, - ); - expect(fs.readFileSync(path.join(mode, "review.md"), "utf8")).toBe(content); -}); - -test("migrating a legacy worker- file another loadable agent links to is refused", () => { - const { content } = addAgent("grunt", "a/b"); - fs.renameSync(path.join(agentDir, "grunt-a-b.md"), path.join(agentDir, "worker-a-b.md")); - const mode = path.join(path.dirname(agentDir), "mode"); - fs.mkdirSync(mode); - fs.symlinkSync(path.join(agentDir, "worker-a-b.md"), path.join(mode, "review.md")); - const result = applySquad({ roster: readSquad(agentDir).roster, dir: agentDir }); - expect(result.ok ? null : result.refusal).toBe("collision"); - expect(fs.readFileSync(path.join(mode, "review.md"), "utf8")).toBe(content); - expect(fs.existsSync(path.join(agentDir, "grunt-a-b.md"))).toBe(false); -}); - -test("the agent sources match the installed OpenCode loader", () => { - // Read the pinned loader's own list, so an OpenCode bump that adds or - // changes a source fails here. - const dist = path.join( - path.dirname(fileURLToPath(import.meta.url)), - "..", - "node_modules", - "@opencode", - "core", - "dist", - "chunks", - ); - const loader = fs - .readdirSync(dist) - .map((f) => fs.readFileSync(path.join(dist, f), "utf8")) - .find((t) => t.includes("var legacySources")); - expect(loader, "OpenCode config-agent loader not found").toBeDefined(); - const patterns = [...(loader ?? "").matchAll(/pattern: "([^"]+)"/g)].map((m) => m[1]); - const ours = []; - for (const deep of [true, false]) { - const names = AGENT_SOURCES.filter((s) => s.deep === deep).map((s) => s.name); - ours.push(`{${names.join(",")}}/${deep ? "**/" : ""}*.md`); - } - expect(patterns).toEqual(ours); -}); - -test("a symlink to a file nothing else reaches is still written through", () => { - const own = path.join(root, "dotfiles", "grunt-a-b.md"); - fs.mkdirSync(path.dirname(own), { recursive: true }); - fs.writeFileSync(own, agentMarkdown("grunt", "a/b", {}).content); - const link = path.join(agentDir, "grunt-a-b.md"); - fs.symlinkSync(own, link); - const result = applySquad({ - roster: { grunts: { "a/b": { variant: "low" } }, drills: {} }, - dir: agentDir, - }); - expect(result.ok).toBe(true); - expect(fs.lstatSync(link).isSymbolicLink()).toBe(true); - expect(fs.readFileSync(own, "utf8")).toMatch(/low/); -}); - -test("a dangling symlink at a planned destination refuses the apply and keeps the link", () => { - const link = path.join(agentDir, "grunt-a-b.md"); - const missing = path.join(root, "dotfiles", "agent", "grunt-a-b.md"); - fs.symlinkSync(missing, link); - const result = applySquad({ - roster: { grunts: { "a/b": {}, "c/d": {} }, drills: {} }, - dir: agentDir, - }); - expect(result.ok ? null : result.refusal).toBe("dangling"); - expect(result.ok ? [] : result.problems).toEqual([ - `${link}: symlink to ${missing}, which does not exist (grunt a/b targets it)`, - ]); - const report = formatApplyReport(result); - expect(report).toMatch(/REFUSED: an agent file this roster would replace is a symlink/); - expect(report).not.toMatch(/DELETE|allow_remove/); - // Nothing was written, and the link is still the user's link. - expect(fs.readdirSync(agentDir)).toEqual(["grunt-a-b.md"]); - expect(fs.lstatSync(link).isSymbolicLink()).toBe(true); - expect(fs.readlinkSync(link)).toBe(missing); - fs.unlinkSync(link); // afterEach chmods every entry, which a dangling link fails -}); diff --git a/tests/runtime-model-data.test.js b/tests/runtime-model-data.test.js index 43f76c4..bc38fe2 100644 --- a/tests/runtime-model-data.test.js +++ b/tests/runtime-model-data.test.js @@ -1,6 +1,7 @@ -// Suite: .opencode/lib/runtime.js — the model_data.json read layer and the -// startup regen. XDG_CONFIG_HOME points at a temp dir, so the real global -// config is never read or written. +// Suite: .opencode/lib/runtime.js — the model_data.json read layer, the +// startup regen from squad.json, and the one-time import of a squad that +// earlier versions wrote as agent files. XDG_CONFIG_HOME points at a temp +// dir, so the real global config is never read or written. // Run: npx vitest run tests/runtime-model-data.test.js import fs from "node:fs"; @@ -9,21 +10,23 @@ import path from "node:path"; import { afterEach, beforeEach, expect, test, vi } from "vitest"; import { ensureGlobalModelDataFresh, + importLegacySquad, loadModelSettings, - syncGlobalSquadDescriptions, } from "../.opencode/lib/runtime.js"; -import { agentMarkdown } from "../src/workers.js"; +import { readStore, writeStore } from "../src/squad-store.js"; const originalXdg = process.env.XDG_CONFIG_HOME; let root; let configDir; let globalFile; +let storeFile; beforeEach(() => { root = fs.mkdtempSync(path.join(os.tmpdir(), "squad-runtime-")); process.env.XDG_CONFIG_HOME = root; configDir = path.join(root, "opencode"); globalFile = path.join(configDir, "model_data.json"); + storeFile = path.join(configDir, "squad.json"); fs.mkdirSync(path.join(configDir, "agent"), { recursive: true }); vi.spyOn(console, "warn").mockImplementation(() => {}); }); @@ -34,14 +37,24 @@ afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); -/** @param {string} modelId */ -function addGrunt(modelId) { - const { filename, content } = agentMarkdown("grunt", modelId, {}); - fs.writeFileSync(path.join(configDir, "agent", filename), content); -} +/** @param {string[]} ids */ +const squadOf = (...ids) => + writeStore(storeFile, { grunts: Object.fromEntries(ids.map((id) => [id, {}])), drills: {} }); + +/** A squad file as versions before #85 wrote it. */ +const legacyFile = (model, description = '"old"') => + [ + "---", + "# generated-by: opencode-squad squad-draft", + `description: ${description}`, + "mode: subagent", + `model: ${model}`, + "---", + "", + ].join("\n"); test("an invalid global model_data.json is left byte-for-byte intact at startup", () => { - addGrunt("a/b"); + squadOf("a/b"); const broken = '{"models": {"a/b": {"info": "SECRET owner rule"}}, "providers": {"a": "Max"},}'; fs.writeFileSync(globalFile, broken); const r = ensureGlobalModelDataFresh(); @@ -52,11 +65,11 @@ test("an invalid global model_data.json is left byte-for-byte intact at startup" expect(fs.readFileSync(globalFile, "utf8")).toBe(broken); expect(String(console.warn.mock.calls[0][0])).not.toContain("SECRET"); // No temp file left behind either. - expect(fs.readdirSync(configDir).sort()).toEqual(["agent", "model_data.json"]); + expect(fs.readdirSync(configDir).sort()).toEqual(["agent", "model_data.json", "squad.json"]); }); -test("a missing file is generated; a valid one keeps hand-edited fields on refresh", () => { - addGrunt("a/b"); +test("a missing file is generated from squad.json; a valid one keeps hand-edited fields", () => { + squadOf("a/b"); expect(ensureGlobalModelDataFresh()).toEqual({ wrote: true }); const first = JSON.parse(fs.readFileSync(globalFile, "utf8")); expect(Object.keys(first.models)).toEqual(["a/b"]); @@ -64,7 +77,7 @@ test("a missing file is generated; a valid one keeps hand-edited fields on refre first.models["a/b"].info = "no secrets"; first.providers = { a: "Max 5x" }; fs.writeFileSync(globalFile, JSON.stringify(first)); - addGrunt("c/d"); + squadOf("a/b", "c/d"); expect(ensureGlobalModelDataFresh()).toEqual({ wrote: true }); const second = JSON.parse(fs.readFileSync(globalFile, "utf8")); expect(second.models["a/b"].info).toBe("no secrets"); @@ -73,41 +86,59 @@ test("a missing file is generated; a valid one keeps hand-edited fields on refre expect(ensureGlobalModelDataFresh()).toEqual({ wrote: false }); // unchanged -> no write }); -test("a squad file that cannot be read keeps model_data untouched", () => { - addGrunt("a/b"); +test("an unreadable squad.json keeps model_data untouched; none at all is no squad", () => { fs.writeFileSync(globalFile, JSON.stringify({ models: { "a/b": { info: "keep me" } } })); const before = fs.readFileSync(globalFile, "utf8"); - // Unreadable as a file (a directory under that name): its model is unknown. - fs.mkdirSync(path.join(configDir, "agent", "grunt-c-d.md")); + expect(ensureGlobalModelDataFresh()).toEqual({ wrote: false }); + fs.writeFileSync(storeFile, "{broken"); const r = ensureGlobalModelDataFresh(); expect(r.wrote).toBe(false); - expect(r.problem).toContain("grunt-c-d.md"); + expect(r.problem).toContain(storeFile); expect(fs.readFileSync(globalFile, "utf8")).toBe(before); }); -test("a pre-0.4.1 agent with an unquoted description keeps its model entry", () => { - const legacy = [ - "---", - "# generated-by: opencode-squad squad-draft", - "description: Per-model grunt. Owner rule: no secrets.", - "mode: subagent", - "model: a/b#high", - "---", - "", - ].join("\n"); - fs.writeFileSync(path.join(configDir, "agent", "grunt-a-b.md"), legacy); +test("the legacy squad is imported once, files left in place, owner notes kept", () => { + const agentDir = path.join(configDir, "agent"); + // A pre-0.4.1 header: description unquoted, not valid YAML. + fs.writeFileSync( + path.join(agentDir, "grunt-a-b.md"), + legacyFile("a/b#high", "Per-model grunt. Owner rule: no secrets."), + ); + fs.writeFileSync(path.join(agentDir, "drill-c-d.md"), legacyFile("c/d")); + const files = fs.readdirSync(agentDir).sort(); fs.writeFileSync(globalFile, JSON.stringify({ models: { "a/b": { info: "keep me" } } })); + + expect(importLegacySquad()).toEqual({ imported: 2, problems: [] }); + expect(readStore(storeFile)).toEqual({ + state: "ok", + roster: { grunts: { "a/b": { variant: "high" } }, drills: { "c/d": {} } }, + }); + expect(fs.readdirSync(agentDir).sort()).toEqual(files); ensureGlobalModelDataFresh(); expect(JSON.parse(fs.readFileSync(globalFile, "utf8")).models["a/b"].info).toBe("keep me"); + + // Once squad.json exists it is the squad: no second import. + fs.writeFileSync(path.join(agentDir, "grunt-e-f.md"), legacyFile("e/f")); + expect(importLegacySquad()).toEqual({ imported: 0, problems: [] }); + expect(readStore(storeFile).roster?.grunts).not.toHaveProperty("e/f"); +}); + +test("a damaged legacy file blocks the import rather than dropping that agent", () => { + const agentDir = path.join(configDir, "agent"); + fs.writeFileSync(path.join(agentDir, "grunt-a-b.md"), legacyFile("a/b")); + fs.writeFileSync( + path.join(agentDir, "grunt-c-d.md"), + "---\n# generated-by: opencode-squad x\ndesc", + ); + const r = importLegacySquad(); + expect(r.imported).toBe(0); + expect(r.problems).toEqual([expect.stringContaining("grunt-c-d.md")]); + expect(fs.existsSync(storeFile)).toBe(false); }); -test("description sync is skipped while the global file is unreadable", () => { - addGrunt("a/b"); - fs.writeFileSync(globalFile, "{not json"); - const file = path.join(configDir, "agent", "grunt-a-b.md"); - const before = fs.readFileSync(file, "utf8"); - expect(syncGlobalSquadDescriptions()).toEqual([]); - expect(fs.readFileSync(file, "utf8")).toBe(before); +test("no legacy squad, no import: squad.json is not created empty", () => { + expect(importLegacySquad()).toEqual({ imported: 0, problems: [] }); + expect(fs.existsSync(storeFile)).toBe(false); }); test("models and providers come from one read: project over global by key, global-only for null", () => { diff --git a/tests/setup-isolation.js b/tests/setup-isolation.js new file mode 100644 index 0000000..3ce0053 --- /dev/null +++ b/tests/setup-isolation.js @@ -0,0 +1,23 @@ +// Runs before every unit test file: point the OpenCode config and data dirs +// at a throwaway directory, so no test can read or write the real user's +// squad.json, model_data.json or agent dir even when it forgets to set its +// own. A test that needs a specific layout still sets XDG_* itself. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterAll } from "vitest"; + +const root = fs.mkdtempSync(path.join(os.tmpdir(), "squad-unit-")); +for (const [key, dir] of [ + ["XDG_CONFIG_HOME", "config"], + ["XDG_DATA_HOME", "data"], +]) { + const full = path.join(root, dir); + fs.mkdirSync(full, { recursive: true }); + process.env[key] = full; +} + +afterAll(() => { + fs.rmSync(root, { recursive: true, force: true }); +}); diff --git a/tests/squad-agents.test.js b/tests/squad-agents.test.js new file mode 100644 index 0000000..1674a66 --- /dev/null +++ b/tests/squad-agents.test.js @@ -0,0 +1,147 @@ +// Suite: src/squad-agents.js — the agents a roster registers, and the early +// and late agent transforms, against a fake host editor. The real host order +// is covered by tests-integration/squad-agents.test.js. +// Run: npx vitest run tests/squad-agents.test.js + +import { expect, test } from "vitest"; +import { PROMPT_CLOSE, promptOpen } from "../src/prompt-inject.js"; +import { NOTES_CLOSE, NOTES_OPEN } from "../src/roster.js"; +import { agentSpecs, earlyTransform, isSquadSystem, lateTransform } from "../src/squad-agents.js"; +import { roleRules } from "../src/workers.js"; + +const io = { + describe: (role, id) => `${role} on ${id}`, + prompt: (role) => `the ${role} prompt`, +}; + +test("one agent per role entry, with model, variant, steps and description", () => { + const specs = agentSpecs( + { + grunts: { "zai-coding-plan/glm-5.3": { variant: "high", steps: 40 } }, + drills: { "openrouter/anthropic/claude-x": {} }, + }, + io, + ); + expect(specs.map((s) => s.id)).toEqual([ + "grunt-zai-coding-plan-glm-5-3", + "drill-openrouter-anthropic-claude-x", + ]); + expect(specs[0]).toMatchObject({ + role: "grunt", + modelId: "zai-coding-plan/glm-5.3", + description: "grunt on zai-coding-plan/glm-5.3", + model: { providerID: "zai-coding-plan", id: "glm-5.3", variant: "high" }, + steps: 40, + permissions: roleRules("grunt"), + }); + // Only the first slash separates the provider. + expect(specs[1].model).toEqual({ providerID: "openrouter", id: "anthropic/claude-x" }); + expect(specs[1]).not.toHaveProperty("steps"); +}); + +test("the system prompt is the fenced role prompt, with notes outside the fence", () => { + const [spec] = agentSpecs({ grunts: { "a/b": { notes: "keep it short" } } }, io); + expect(spec.system.startsWith(`${promptOpen("grunt")}\nthe grunt prompt\n${PROMPT_CLOSE}`)).toBe( + true, + ); + expect(spec.system.indexOf(PROMPT_CLOSE)).toBeLessThan(spec.system.indexOf(NOTES_OPEN)); + expect(spec.system).toContain(`${NOTES_OPEN}\nkeep it short\n${NOTES_CLOSE}`); + expect(isSquadSystem(spec.system)).toBe(true); +}); + +test("an unreadable role prompt falls back to the placeholder, still fenced", () => { + const [spec] = agentSpecs({ drills: { "a/b": {} } }, { ...io, prompt: () => null }); + expect(isSquadSystem(spec.system)).toBe(true); + expect(spec.system).toContain("squad prompt missing"); +}); + +test("a disabled entry stays in the roster but registers no agent; blank variant is none", () => { + const specs = agentSpecs({ grunts: { "a/b": { disable: true }, "c/d": { variant: " " } } }, io); + expect(specs.map((s) => s.id)).toEqual(["grunt-c-d"]); + expect(specs[0].model).toEqual({ providerID: "c", id: "d" }); +}); + +/** A fake host editor over a Map of agents. */ +function editorOf(agents) { + const map = new Map(agents.map((a) => [a.id, structuredClone(a)])); + return { + map, + list: () => [...map.values()], + get: (id) => map.get(id), + remove: (id) => map.delete(id), + update: (id, f) => { + const agent = map.get(id) ?? { + id, + permissions: [{ action: "*", resource: "*", effect: "allow" }], + }; + f(agent); + map.set(id, agent); + }, + }; +} + +test("early: creates each agent with every squad field and the role rules", () => { + const specs = agentSpecs({ drills: { "a/b": { variant: "max" } } }, io); + const editor = editorOf([]); + earlyTransform(editor, specs); + const agent = editor.get("drill-a-b"); + expect(agent).toMatchObject({ + mode: "subagent", + hidden: true, + description: "drill on a/b", + model: { providerID: "a", id: "b", variant: "max" }, + }); + expect(agent.permissions.slice(1)).toEqual(roleRules("drill")); +}); + +test("late: role rules go last, after whatever the config plugin appended", () => { + const specs = agentSpecs({ drills: { "a/b": {} } }, io); + const editor = editorOf([]); + earlyTransform(editor, specs); + // The config-agent plugin appends the user's global rules after ours. + editor.get("drill-a-b").permissions.push({ action: "*", resource: "*", effect: "allow" }); + lateTransform(editor, specs); + expect(editor.get("drill-a-b").permissions.slice(-roleRules("drill").length)).toEqual( + roleRules("drill"), + ); +}); + +test("late: a same-id legacy generated file is taken over, its own fields cleared", () => { + const specs = agentSpecs({ grunts: { "a/b": {} } }, io); + const legacy = { + id: "grunt-a-b", + system: `${promptOpen("grunt")}\nold\n${PROMPT_CLOSE}`, + description: "old", + color: "#ff0000", + steps: 7, + permissions: [], + }; + const editor = editorOf([legacy]); + const report = lateTransform(editor, specs); + expect(report).toEqual({ foreign: [], hidden: [] }); + const agent = editor.get("grunt-a-b"); + expect(agent.system).toContain("the grunt prompt"); + expect(agent.description).toBe("grunt on a/b"); + expect(agent).not.toHaveProperty("color"); + expect(agent).not.toHaveProperty("steps"); +}); + +test("late: a hand-authored agent with a roster id is left alone and reported", () => { + const specs = agentSpecs({ grunts: { "a/b": {} } }, io); + const mine = { id: "grunt-a-b", system: "My own prompt.", description: "mine", permissions: [] }; + const editor = editorOf([mine]); + expect(lateTransform(editor, specs)).toEqual({ foreign: ["grunt-a-b"], hidden: [] }); + expect(editor.get("grunt-a-b")).toEqual(mine); +}); + +test("late: legacy generated agents the roster dropped are hidden; nothing else is", () => { + const fenced = `${promptOpen("drill")}\nx\n${PROMPT_CLOSE}`; + const editor = editorOf([ + { id: "drill-old-model", system: fenced, permissions: [] }, + { id: "drill-hand-written", system: "mine", permissions: [] }, + { id: "build", system: fenced, permissions: [] }, + ]); + const report = lateTransform(editor, agentSpecs({ grunts: { "a/b": {} } }, io)); + expect(report.hidden).toEqual(["drill-old-model"]); + expect([...editor.map.keys()].sort()).toEqual(["build", "drill-hand-written", "grunt-a-b"]); +}); diff --git a/tests/squad-apply.test.js b/tests/squad-apply.test.js index f937262..e43c830 100644 --- a/tests/squad-apply.test.js +++ b/tests/squad-apply.test.js @@ -1,359 +1,157 @@ +// Suite: src/squad-apply.js — the squad_patch decision and report, and the +// read-only import of a squad that earlier versions wrote as agent files. +// Run: npx vitest run tests/squad-apply.test.js + import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, expect, test } from "vitest"; -import { applySquad, formatApplyReport, readSquad, syncDescriptions } from "../src/squad-apply.js"; +import { formatPatchReport, planPatch, readLegacySquad } from "../src/squad-apply.js"; let dir; - beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), "squad-apply-")); }); afterEach(() => { + for (const f of fs.readdirSync(dir)) { + const p = path.join(dir, f); + if (fs.lstatSync(p).isFile()) fs.chmodSync(p, 0o600); + } fs.rmSync(dir, { recursive: true, force: true }); }); -const apply = (roster, allowRemove = false) => applySquad({ roster, dir, allowRemove }); -const ls = () => fs.readdirSync(dir).sort(); -const read = (f) => fs.readFileSync(path.join(dir, f), "utf8"); - -test("readSquad treats a missing agent dir as an empty squad, not an error", () => { - expect(readSquad(path.join(dir, "nope")).roster).toEqual({ grunts: {}, drills: {} }); -}); - -test("applySquad writes one file per agent and reads back losslessly", () => { - const roster = { - grunts: { - "zai-coding-plan/glm-5.3": { - variant: "high", - notes: "prefer the write tool", - steps: 40, - }, - "openai/gpt-5.6-luna": {}, - }, - drills: { "anthropic/claude-opus-5": { variant: "max" } }, - }; - const result = apply(roster); +const isRoot = process.getuid?.() === 0; + +/** A file as versions before #85 wrote it. */ +const legacyFile = (model, extra = "", marker = "opencode-squad squad-draft") => + [ + "---", + `# generated-by: ${marker}`, + 'description: "old"', + "mode: subagent", + `model: ${model}`, + "hidden: true", + "---", + "", + "", + "placeholder", + "", + extra, + ].join("\n"); + +const current = { grunts: { "a/one": {}, "a/two": { variant: "high" } }, drills: { "a/one": {} } }; + +test("planPatch accepts an edit and reports the diff", () => { + const next = { grunts: { "a/one": {}, "a/two": { variant: "max" } }, drills: { "a/one": {} } }; + const result = planPatch({ current, next }); expect(result.ok).toBe(true); - expect(ls()).toEqual([ - "drill-anthropic-claude-opus-5.md", - "grunt-openai-gpt-5-6-luna.md", - "grunt-zai-coding-plan-glm-5-3.md", - ]); - // The round trip is what makes read-modify-write safe to build on, so every - // field the roster owns has to survive it — notes included. - expect(readSquad(dir).roster).toEqual(roster); + expect(result.diff.changed).toEqual(['grunt a/two: variant "high" -> "max"']); }); -test("one model can be a grunt at one level and a drill at another", () => { - apply({ - grunts: { "a/b": { variant: "high" } }, - drills: { "a/b": { variant: "max" } }, +test("planPatch refuses a deletion unless allow_remove", () => { + const next = { grunts: { "a/one": {} }, drills: {} }; + expect(planPatch({ current, next })).toMatchObject({ + ok: false, + refusal: "remove", + problems: ["drill a/one", "grunt a/two"], }); - expect(read("grunt-a-b.md")).toContain("model: a/b#high\n"); - expect(read("drill-a-b.md")).toContain("model: a/b#max\n"); -}); - -test("legacy grunt and drill files read losslessly and regenerate entirely in native format", () => { - const roster = { - grunts: { "a/b": { variant: "high", steps: 12, notes: "keep me" } }, - drills: { "a/b": { variant: "max", disable: true } }, - }; - for (const [role, variant] of [ - ["grunt", "high"], - ["drill", "max"], - ]) { - fs.writeFileSync( - path.join(dir, `${role}-a-b.md`), - [ - "---", - "# generated-by: opencode-orchestrate workers-draft", - "model: a/b", - `variant: ${variant}`, - ...(role === "drill" ? ["disable: true"] : ["steps: 12"]), - "permission:", - ` edit: ${role === "grunt" ? "allow" : "deny"}`, - ` bash: ${role === "grunt" ? "allow" : "deny"}`, - " task:", - " '*': deny", - "---", - ...(role === "grunt" ? ["", "keep me", ""] : []), - ].join("\n"), - ); - } - expect(readSquad(dir).roster).toEqual(roster); - expect(apply(readSquad(dir).roster)).toMatchObject({ ok: true, pruned: [] }); - for (const role of ["grunt", "drill"]) { - const content = read(`${role}-a-b.md`); - expect(content).toContain(`model: a/b#${role === "grunt" ? "high" : "max"}\n`); - expect(content).toContain("permissions:\n"); - expect(content).not.toMatch(/\n(?:variant|disable|permission):/); - } - expect(read("drill-a-b.md")).toContain("disabled: true\n"); - expect(readSquad(dir).roster).toEqual(roster); + expect(planPatch({ current, next, allowRemove: true }).ok).toBe(true); }); -test("old generated marker still participates in deletion guards and pruning", () => { - fs.writeFileSync( - path.join(dir, "drill-a-old.md"), - "---\n# generated-by: opencode-orchestrate workers-draft\nmodel: a/old\npermission:\n bash: deny\n---\n", - ); - expect(apply({ grunts: {}, drills: {} }).ok).toBe(false); - expect(apply({ grunts: {}, drills: {} }, true)).toMatchObject({ - ok: true, - pruned: ["drill-a-old.md"], +test("planPatch refuses an id a hand-authored agent holds, even with allow_remove", () => { + const result = planPatch({ + current, + next: { ...current, grunts: { ...current.grunts, "b/c": {} } }, + allowRemove: true, + foreign: [{ id: "grunt-b-c", agent: "grunt b/c" }], }); - expect(ls()).toEqual([]); + expect(result).toMatchObject({ ok: false, refusal: "foreign" }); + const report = formatPatchReport(result, { store: "/s.json", roster: current }); + expect(report).toContain("grunt b/c: agent id grunt-b-c is a hand-authored agent"); + expect(report).toMatch(/Nothing was written/); }); -test("a model can be a grunt with no drill at all", () => { - apply({ grunts: { "a/weak": {} }, drills: {} }); - expect(ls()).toEqual(["grunt-a-weak.md"]); +test("the report names every agent a refused apply would delete", () => { + const result = planPatch({ current, next: { grunts: {}, drills: {} } }); + const report = formatPatchReport(result, { store: "/s.json", roster: {} }); + expect(report).toContain("REFUSED: applying this roster would DELETE 3 agent(s)"); + expect(report).toMatch(/retry with allow_remove/); }); -test("applySquad refuses a deletion and writes NOTHING", () => { - apply({ grunts: { "a/one": {}, "a/two": {} }, drills: { "a/one": {} } }); - const before = ls(); - - const result = apply({ grunts: { "a/three": {} }, drills: {} }); - expect(result.ok).toBe(false); - expect(result.diff.removed).toEqual(["drill a/one", "grunt a/one", "grunt a/two"]); - expect(result.written).toEqual([]); - // Total refusal: the agent that WOULD have been added must not appear either. - expect(ls()).toEqual(before); -}); - -test("dropping just a drill is a deletion too, and is gated the same way", () => { - apply({ grunts: { "a/weak": {} }, drills: { "a/weak": {} } }); - const refused = apply({ grunts: { "a/weak": { variant: "high" } }, drills: {} }); - expect(refused.ok).toBe(false); - expect(refused.diff.removed).toEqual(["drill a/weak"]); - // The retune that shared the call must not land either. - expect(read("grunt-a-weak.md")).not.toContain("variant:"); - - const allowed = apply({ grunts: { "a/weak": { variant: "high" } }, drills: {} }, true); - expect(allowed.ok).toBe(true); - expect(allowed.pruned).toEqual(["drill-a-weak.md"]); - expect(ls()).toEqual(["grunt-a-weak.md"]); -}); - -test("adding a drill to an existing grunt needs no permission", () => { - apply({ grunts: { "a/b": {} } }); - expect(apply({ grunts: { "a/b": {} }, drills: { "a/b": {} } }).ok).toBe(true); - expect(ls()).toEqual(["drill-a-b.md", "grunt-a-b.md"]); -}); - -test("a hand-authored agent is invisible: never dumped, never pruned", () => { - fs.writeFileSync(path.join(dir, "grunt-mine.md"), "---\nmodel: a/mine\n---\nMINE\n"); - expect(readSquad(dir).roster.grunts).toEqual({}); - apply({ grunts: { "a/b": {} } }, true); - expect(ls()).toContain("grunt-mine.md"); -}); - -test("applying a roster read from a legacy worker- file leaves the agent in one file", () => { - apply({ grunts: { "a/b": { variant: "high", notes: "keep" } } }); - fs.renameSync(path.join(dir, "grunt-a-b.md"), path.join(dir, "worker-a-b.md")); - const result = apply(readSquad(dir).roster); - expect(result).toMatchObject({ ok: true, pruned: [], migrated: ["worker-a-b.md"] }); - expect(ls()).toEqual(["grunt-a-b.md"]); - expect(readSquad(dir).roster).toEqual({ - grunts: { "a/b": { variant: "high", notes: "keep" } }, - drills: {}, +test("a successful report echoes variants and says no files are written", () => { + const next = { grunts: { "a/one": {}, "a/two": { variant: "high" } }, drills: { "a/one": {} } }; + const report = formatPatchReport(planPatch({ current, next }), { + store: "/cfg/squad.json", + roster: next, + notes: ["a note"], }); - // An authorized removal now removes the agent completely. - expect(apply({ grunts: {}, drills: {} }, true)).toMatchObject({ - ok: true, - pruned: ["grunt-a-b.md"], - }); - expect(ls()).toEqual([]); -}); - -test("removing an agent prunes every file that claims it, legacy name included", () => { - apply({ grunts: { "a/b": {} } }); - fs.copyFileSync(path.join(dir, "grunt-a-b.md"), path.join(dir, "worker-a-b.md")); - const result = apply({ grunts: {}, drills: {} }, true); - expect(result.ok).toBe(true); - expect(result.pruned.sort()).toEqual(["grunt-a-b.md", "worker-a-b.md"]); - expect(ls()).toEqual([]); + expect(report).toContain("Squad roster: /cfg/squad.json"); + expect(report).toContain(" note a note"); + expect(report).toContain("=3 unchanged"); + expect(report).toContain(" grunt a/two -> high"); + expect(report).toMatch(/No agent files are written/); }); -test("two ids that slug to one filename are refused before anything is written", () => { - apply({ grunts: { "a/keep": {} } }); - const before = ls().map((f) => [f, read(f)]); - const result = apply({ grunts: { "a/keep": {}, "p/model-1": {}, "p/model.1": {} } }, true); - expect(result.ok).toBe(false); - expect(result.refusal).toBe("collision"); - expect(result.problems).toEqual([ - "grunt p/model-1 and grunt p/model.1 would both be written to grunt-p-model-1.md", - ]); - expect(ls().map((f) => [f, read(f)])).toEqual(before); - const report = formatApplyReport(result); - expect(report).toContain("REFUSED: the roster cannot be written"); - expect(report).toContain("grunt-p-model-1.md"); -}); - -test("replacing an id with one that shares its filename keeps the new agent on disk", () => { - apply({ grunts: { "p/model.1": { variant: "low" } } }); - const result = apply({ grunts: { "p/model-1": { variant: "high" } } }, true); - expect(result.ok).toBe(true); - expect(result.diff.removed).toEqual(["grunt p/model.1"]); - expect(result.pruned).toEqual([]); - expect(ls()).toEqual(["grunt-p-model-1.md"]); - expect(readSquad(dir).roster.grunts).toEqual({ "p/model-1": { variant: "high" } }); -}); - -test("a hand-authored file at the exact destination is never overwritten", () => { - const mine = "---\nmodel: a/b\ndescription: mine\n---\nMY OWN PROMPT\n"; - fs.writeFileSync(path.join(dir, "grunt-a-b.md"), mine); - for (const allow of [false, true]) { - const result = apply({ grunts: { "a/b": {}, "a/c": {} } }, allow); - expect(result).toMatchObject({ ok: false, refusal: "collision" }); - expect(result.problems).toEqual([ - "grunt-a-b.md exists and was not generated by this plugin (grunt a/b targets it)", - ]); - } - expect(ls()).toEqual(["grunt-a-b.md"]); - expect(read("grunt-a-b.md")).toBe(mine); -}); - -test("a byte-identical agent file is not rewritten", () => { - apply({ grunts: { "a/b": { variant: "high" } } }); - const file = path.join(dir, "grunt-a-b.md"); - const old = new Date("2020-01-01T00:00:00Z"); - fs.utimesSync(file, old, old); - const result = apply({ grunts: { "a/b": { variant: "high" } } }); - expect(result.written).toEqual([ - { role: "grunt", id: "a/b", variant: "high", filename: "grunt-a-b.md", unchanged: true }, - ]); - expect(fs.statSync(file).mtimeMs).toBe(old.getTime()); - expect(formatApplyReport(result)).toContain("same grunt-a-b.md"); -}); - -test("disable is written as frontmatter and survives the round trip", () => { - apply({ grunts: { "a/b": { disable: true } } }); - expect(read("grunt-a-b.md")).toContain("disabled: true"); - expect(readSquad(dir).roster.grunts["a/b"]).toEqual({ disable: true }); -}); - -test("formatApplyReport names every agent a refused apply would have deleted", () => { - apply({ grunts: { "a/one": {} }, drills: { "a/one": {} } }); - const report = formatApplyReport(apply({ grunts: { "a/two": {} } })); - expect(report).toContain("would DELETE 2 agent(s)"); - expect(report).toContain("- drill a/one"); - expect(report).toContain("- grunt a/one"); - expect(report).toContain("Nothing was written"); -}); - -test("formatApplyReport echoes variants per agent, with the typo warning", () => { - const report = formatApplyReport( - apply({ grunts: { "a/b": { variant: "high" } }, drills: { "a/b": { variant: "max" } } }), +test("readLegacySquad imports generated files only, worker- as a grunt", () => { + fs.writeFileSync(path.join(dir, "grunt-a-one.md"), legacyFile("a/one#high")); + fs.writeFileSync( + path.join(dir, "worker-a-two.md"), + legacyFile("a/two", "", "opencode-orchestrate x"), ); - expect(report).toContain("IGNORES an unrecognized variant"); - expect(report).toContain("grunt a/b -> high"); - expect(report).toContain("drill a/b -> max"); -}); - -test("formatApplyReport omits the variant block when nothing set one", () => { - expect(formatApplyReport(apply({ grunts: { "a/b": {} } }))).not.toContain("Variants written"); -}); - -// Descriptions are plugin-owned: squad_patch and the startup sync both take -// them from describe(), and neither leaks them into the dumped roster. -test("applySquad writes describe()'s description; the dump never carries it", () => { - applySquad({ - roster: { grunts: { "z/glm": { variant: "high" } } }, - dir, - describe: (role, id) => `${role} ${id}: Owner rule: no secrets # really`, - }); - expect(read("grunt-z-glm.md")).toContain( - 'description: "grunt z/glm: Owner rule: no secrets # really"\n', + fs.writeFileSync( + path.join(dir, "drill-a-one.md"), + legacyFile("a/one").replace("role=grunt", "role=drill"), ); - expect(readSquad(dir).roster).toEqual({ grunts: { "z/glm": { variant: "high" } }, drills: {} }); -}); - -test("syncDescriptions rewrites only what changed and keeps every roster field", () => { - apply({ - grunts: { "a/b": { variant: "high", steps: 7, notes: "keep me" }, "c/d": {} }, - drills: { "a/b": { variant: "max" } }, - }); - fs.writeFileSync(path.join(dir, "grunt-hand-made.md"), "---\ndescription: mine\n---\n"); - const before = read("grunt-c-d.md"); - const describe = (role, id) => (id === "a/b" ? `${role}: no secrets` : undefined); - - expect(syncDescriptions({ dir, describe }).sort()).toEqual(["drill-a-b.md", "grunt-a-b.md"]); - expect(read("grunt-a-b.md")).toContain('description: "grunt: no secrets"\n'); - expect(read("grunt-a-b.md")).toContain("model: a/b#high\nsteps: 7\n"); - expect(read("grunt-a-b.md")).toContain("keep me"); - expect(read("grunt-c-d.md")).toBe(before); - expect(read("grunt-hand-made.md")).toBe("---\ndescription: mine\n---\n"); - // Idempotent: a second start writes nothing, so opencode reloads nothing. - expect(syncDescriptions({ dir, describe })).toEqual([]); - expect(ls().filter((f) => f.endsWith(".tmp"))).toEqual([]); -}); - -test("syncDescriptions leaves legacy-named files for squad_patch to migrate", () => { + // Hand-authored, another generator's, and the marker only quoted in the body. + fs.writeFileSync(path.join(dir, "grunt-mine.md"), "---\nmodel: m/n\n---\nmine\n"); + fs.writeFileSync(path.join(dir, "grunt-other.md"), legacyFile("o/p", "", "opencode-other-tool")); fs.writeFileSync( - path.join(dir, "worker-a-b.md"), - "---\n# generated-by: opencode-squad squad-draft\ndescription: old\nmodel: a/b\n---\n", + path.join(dir, "grunt-quoted.md"), + "---\nmodel: q/r\n---\n# generated-by: opencode-squad squad-draft\n", ); - expect(syncDescriptions({ dir, describe: () => "new" })).toEqual([]); - expect(syncDescriptions({ dir: path.join(dir, "nope"), describe: () => "x" })).toEqual([]); -}); - -test("formatApplyReport lists descriptions refreshed from model_data.json", () => { - apply({ grunts: { "a/b": {} } }); - const result = applySquad({ - roster: { grunts: { "a/b": {} } }, - dir, - describe: () => "grunt. Owner rule: no secrets.", + const out = readLegacySquad(dir); + expect(out.roster).toEqual({ + grunts: { "a/one": { variant: "high" }, "a/two": {} }, + drills: { "a/one": {} }, }); - expect(result.diff.unchanged).toEqual(["grunt a/b"]); - const report = formatApplyReport(result); - expect(report).toContain("Descriptions refreshed from model_data.json (1):"); - expect(report).toContain('~ grunt a/b: "grunt. Owner rule: no secrets."'); - // Same description again: nothing to report. - expect( - formatApplyReport( - applySquad({ - roster: { grunts: { "a/b": {} } }, - dir, - describe: () => "grunt. Owner rule: no secrets.", - }), - ), - ).not.toContain("refreshed"); + expect(out.files).toEqual(["drill-a-one.md", "grunt-a-one.md", "worker-a-two.md"]); + expect(out.problems).toEqual([]); }); -test("a hand copy of a generated file is a separate agent: removing it needs allow_remove", () => { - apply({ grunts: { "p/m": {} } }); - fs.copyFileSync(path.join(dir, "grunt-p-m.md"), path.join(dir, "grunt-p-m-copy.md")); - const refused = apply({ grunts: { "p/m": {} } }); - expect(refused).toMatchObject({ ok: false, refusal: "remove" }); - expect(refused.problems).toEqual(["grunt-p-m-copy.md (a second file for grunt p/m)"]); - expect(formatApplyReport(refused)).toContain("grunt-p-m-copy.md (a second file for grunt p/m)"); - expect(ls()).toEqual(["grunt-p-m-copy.md", "grunt-p-m.md"]); - - const allowed = apply({ grunts: { "p/m": {} } }, true); - expect(allowed).toMatchObject({ ok: true, pruned: ["grunt-p-m-copy.md"], migrated: [] }); - expect(ls()).toEqual(["grunt-p-m.md"]); +test("readLegacySquad reads CRLF files and keeps notes", () => { + fs.writeFileSync( + path.join(dir, "grunt-a-b.md"), + legacyFile("a/b", "\nshort answers\n").replaceAll( + "\n", + "\r\n", + ), + ); + expect(readLegacySquad(dir).roster.grunts).toEqual({ "a/b": { notes: "short answers" } }); }); -test("a pre-0.4.1 file with an unquoted description is dumped and repaired by the sync", () => { +test("a damaged generated file is a problem, never a silently dropped agent", () => { fs.writeFileSync( path.join(dir, "grunt-a-b.md"), - [ - "---", - "# generated-by: opencode-squad squad-draft", - "description: Per-model grunt. Owner rule: no secrets.", - "mode: subagent", - "model: a/b#high", - "---", - "", - ].join("\n"), + "---\n# generated-by: opencode-squad squad-draft\ndescr", ); - expect(readSquad(dir).roster.grunts).toEqual({ "a/b": { variant: "high" } }); - expect(syncDescriptions({ dir, describe: () => "grunt. Owner rule: no secrets." })).toEqual([ - "grunt-a-b.md", + const out = readLegacySquad(dir); + expect(out.roster.grunts).toEqual({}); + expect(out.problems).toEqual([ + "grunt-a-b.md: generated file with no readable model (damaged header)", ]); - expect(read("grunt-a-b.md")).toContain('description: "grunt. Owner rule: no secrets."\n'); - expect(readSquad(dir).roster.grunts).toEqual({ "a/b": { variant: "high" } }); +}); + +test.skipIf(isRoot)("an unreadable squad file is a problem", () => { + const f = path.join(dir, "grunt-a-b.md"); + fs.writeFileSync(f, legacyFile("a/b")); + fs.chmodSync(f, 0o000); + expect(readLegacySquad(dir).problems).toEqual(["grunt-a-b.md: cannot read (EACCES)"]); +}); + +test("a missing agent dir is an empty legacy squad", () => { + expect(readLegacySquad(path.join(dir, "nope"))).toEqual({ + roster: { grunts: {}, drills: {} }, + problems: [], + files: [], + }); }); diff --git a/tests/squad-store.test.js b/tests/squad-store.test.js new file mode 100644 index 0000000..2271fc4 --- /dev/null +++ b/tests/squad-store.test.js @@ -0,0 +1,63 @@ +// Suite: src/squad-store.js — the roster file the plugin owns (#85). +// Run: npx vitest run tests/squad-store.test.js + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, expect, test } from "vitest"; +import { defaultStoreFile, readStore, storeSignature, writeStore } from "../src/squad-store.js"; + +let dir; +let file; +beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "squad-store-")); + file = path.join(dir, "squad.json"); +}); +afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }); +}); + +test("a missing file is no squad, not an error", () => { + expect(readStore(file)).toEqual({ state: "missing" }); + expect(storeSignature(file)).toBe("-"); +}); + +test("write then read round-trips, keys sorted, with the format version", () => { + writeStore(file, { grunts: { "z/b": { variant: "high" }, "a/b": {} }, drills: {} }); + const text = fs.readFileSync(file, "utf8"); + expect(JSON.parse(text)).toEqual({ + version: 1, + grunts: { "a/b": {}, "z/b": { variant: "high" } }, + drills: {}, + }); + expect(text.indexOf('"a/b"')).toBeLessThan(text.indexOf('"z/b"')); + expect(readStore(file)).toEqual({ + state: "ok", + roster: { grunts: { "a/b": {}, "z/b": { variant: "high" } }, drills: {} }, + }); + expect(storeSignature(file)).not.toBe("-"); +}); + +test.each([ + ["{not json", /not valid JSON/], + ["[]", /not a JSON object/], + [JSON.stringify({ grunts: {} }), /unsupported version null/], + [JSON.stringify({ version: 2, grunts: {} }), /unsupported version 2/], + [JSON.stringify({ version: 1, grunts: { "no-slash": {} } }), /grunts/], + [JSON.stringify({ version: 1, grunts: { "a/b": { description: "x" } } }), /description/], +])("an invalid file is reported, never read as empty: %s", (text, reason) => { + fs.writeFileSync(file, text); + const read = readStore(file); + expect(read.state).toBe("invalid"); + expect(read.state === "invalid" ? read.reason : "").toMatch(reason); +}); + +test("the default file sits in the OpenCode config dir", () => { + const old = process.env.XDG_CONFIG_HOME; + process.env.XDG_CONFIG_HOME = "/xdg/cfg"; + try { + expect(defaultStoreFile()).toBe(path.join("/xdg/cfg", "opencode", "squad.json")); + } finally { + process.env.XDG_CONFIG_HOME = old; + } +}); diff --git a/tests/workers.test.js b/tests/workers.test.js index 07e4c99..610bded 100644 --- a/tests/workers.test.js +++ b/tests/workers.test.js @@ -1,23 +1,16 @@ +// Suite: src/workers.js — agent ids, role permission rules and descriptions. +// Run: npx vitest run tests/workers.test.js + import { expect, test } from "vitest"; -import { readFrontmatter } from "../src/frontmatter.js"; -import { PROMPT_CLOSE, promptOpen } from "../src/prompt-inject.js"; -import { NOTES_CLOSE, NOTES_OPEN, parseAgentFile } from "../src/roster.js"; import { - agentMarkdown, defaultDescriptions, describeAgent, - GENERATED_MARKER, + isGeneratedAgent, + roleRules, slugForModel, squadRoleOf, } from "../src/workers.js"; -/** The frontmatter fields of a generated document; throws unless it parses. */ -function frontmatterOf(content) { - const fm = readFrontmatter(content); - if (fm.state !== "ok") throw new Error(`frontmatter ${fm.state}`); - return fm.fields; -} - test("slug collapses provider/model and punctuation, prefixed by role", () => { expect(slugForModel("openai/gpt-5.5")).toBe("grunt-openai-gpt-5-5"); // default role expect(slugForModel("openai/gpt-5.5", "drill")).toBe("drill-openai-gpt-5-5"); @@ -33,33 +26,16 @@ test("slug is stable and trimmed (no leading/trailing/doubled dashes)", () => { expect(slugForModel(" Foo//Bar..Baz ", "drill")).toBe("drill-foo-bar-baz"); }); -test("grunt markdown: native ordered edit/shell allows and explicit subagent deny", () => { - const body = "You are grunt, a worker subagent."; - const { slug, filename, content } = agentMarkdown("grunt", "anthropic/claude-opus-4-7"); - expect(slug).toBe("grunt-anthropic-claude-opus-4-7"); - expect(filename).toBe("grunt-anthropic-claude-opus-4-7.md"); - expect(content.startsWith("---\n")).toBe(true); - expect(content).toContain("mode: subagent"); - expect(content).toContain("model: anthropic/claude-opus-4-7"); - expect(content).toContain("hidden: true"); - expect(content).toContain( - 'permissions:\n - {"action":"edit","resource":"*","effect":"allow"}\n' + - ' - {"action":"shell","resource":"*","effect":"allow"}\n' + - ' - {"action":"subagent","resource":"*","effect":"deny"}\n---', - ); - expect(content).not.toContain("permission:"); - expect(content).toContain(GENERATED_MARKER); - expect(content).toContain(promptOpen("grunt")); - expect(content.trimEnd().endsWith(PROMPT_CLOSE)).toBe(true); - expect(content).not.toContain(body); +test("grunt rules: edit and shell allowed, subagent denied", () => { + expect(roleRules("grunt")).toEqual([ + { action: "edit", resource: "*", effect: "allow" }, + { action: "shell", resource: "*", effect: "allow" }, + { action: "subagent", resource: "*", effect: "deny" }, + ]); }); -test("V2 drill markdown denies by default, allowing only local reads, web and narrow shell inspection", () => { - const { slug, content } = agentMarkdown("drill", "openai/gpt-5.5"); - expect(slug).toBe("drill-openai-gpt-5-5"); - expect(content).toContain("permissions:\n"); - expect(content).not.toContain("permission:"); - const rules = frontmatterOf(content).permissions; +test("drill rules deny by default, allowing only local reads, web and narrow shell inspection", () => { + const rules = roleRules("drill"); expect(rules).toEqual([ { action: "*", resource: "*", effect: "deny" }, { action: "read", resource: "*", effect: "allow" }, @@ -133,13 +109,10 @@ test("V2 drill markdown denies by default, allowing only local reads, web and na expect( rules.filter((rule) => rule.effect === "allow").map((rule) => rule.resource), ).not.toContain("gh api *"); - expect(content).toContain(promptOpen("drill")); - expect(content.trimEnd().endsWith(PROMPT_CLOSE)).toBe(true); }); -test("V2 write guards and env exceptions come after their broad allows", () => { - const { content } = agentMarkdown("drill", "a/b"); - const rules = frontmatterOf(content).permissions; +test("drill write guards and env exceptions come after their broad allows", () => { + const rules = roleRules("drill"); const index = (action, resource) => rules.findIndex((r) => r.action === action && r.resource === resource); for (const resource of ["*--output*", "sort *-o*", "*>*"]) { @@ -152,116 +125,13 @@ test("V2 write guards and env exceptions come after their broad allows", () => { expect(index("read", "*.env.example")).toBeGreaterThan(index("read", "*.env.*")); }); -test.each(["grunt", "drill"])( - "native %s preserves overrides through a roster round trip", - (role) => { - const { content } = agentMarkdown(role, "openai/gpt-5.5", { - variant: "high", - disable: true, - steps: 12, - notes: "inspect edge cases", - }); - expect(content).toContain("model: openai/gpt-5.5#high\n"); - expect(content).toContain("disabled: true\n"); - expect(content).not.toContain("\nvariant:"); - expect(content).not.toContain("\ndisable:"); - expect(parseAgentFile(content)).toEqual({ - modelId: "openai/gpt-5.5", - entry: { - variant: "high", - disable: true, - steps: 12, - notes: "inspect edge cases", - }, - }); - }, -); - test("unknown role throws", () => { - expect(() => agentMarkdown("captain", "openai/gpt-5.5")).toThrow(); -}); - -test.each(["grunt", "drill"])( - "the generated %s document parses as YAML frontmatter + body", - (role) => { - const { content } = agentMarkdown(role, "openai/gpt-5.5", { - variant: "high", - description: 'routes on: "quotes" # and hashes', - notes: "n", - }); - const fields = frontmatterOf(content); - expect(fields).toMatchObject({ - description: 'routes on: "quotes" # and hashes', - mode: "subagent", - model: "openai/gpt-5.5#high", - hidden: true, - }); - expect(Array.isArray(fields.permissions)).toBe(true); - const { body } = readFrontmatter(content); - expect(body.trimStart().startsWith(promptOpen(role))).toBe(true); - }, -); - -test("agentMarkdown emits variant only when one is given", () => { - const withVariant = agentMarkdown("grunt", "zai-coding-plan/glm-5.3", { - variant: "high", - }).content; - expect(withVariant).toContain("model: zai-coding-plan/glm-5.3#high\n"); - - const without = agentMarkdown("grunt", "anthropic/claude-opus-5").content; - expect(without).not.toContain("variant:"); - expect(without).toContain("model: anthropic/claude-opus-5\nhidden: true\n"); -}); - -test("agentMarkdown ignores a blank variant rather than writing a bare #", () => { - const { content } = agentMarkdown("drill", "openai/gpt-5.5", { variant: " " }); - expect(frontmatterOf(content).model).toBe("openai/gpt-5.5"); + expect(() => roleRules("captain")).toThrow(); }); -test("the variant does not leak into the slug — one agent per model, not per variant", () => { - const a = agentMarkdown("grunt", "zai-coding-plan/glm-5.3", { variant: "high" }); - const b = agentMarkdown("grunt", "zai-coding-plan/glm-5.3"); - expect(a.slug).toBe(b.slug); - expect(a.filename).toBe(b.filename); -}); - -test("agentMarkdown writes the per-agent overrides, and only those that were given", () => { - const { content } = agentMarkdown("grunt", "zai-coding-plan/glm-5.3", { - variant: "high", - description: "cheap long-context coder", - notes: "prefer the write tool over bash heredocs", - steps: 40, - disable: true, - }); - // Quoted, so an owner note carrying ": " or " #" stays valid YAML. - expect(content).toContain('description: "cheap long-context coder"\n'); - expect(content).toContain("model: zai-coding-plan/glm-5.3#high\n"); - expect(content).toContain("steps: 40"); - expect(content).toContain("disabled: true"); - expect(content).toContain(NOTES_OPEN); - expect(content).toContain("prefer the write tool over bash heredocs"); - expect(content).toContain(NOTES_CLOSE); - - const bare = agentMarkdown("grunt", "a/b").content; - expect(bare).not.toContain("variant:"); - expect(bare).not.toContain("steps:"); - expect(bare).not.toContain("disable:"); - expect(bare).not.toContain(NOTES_OPEN); - // Falls back to the role's generic description rather than writing nothing. - expect(bare).toContain(`description: ${JSON.stringify(defaultDescriptions().grunt)}`); -}); - -test("notes are fenced so the body stays separable from the role prompt", () => { - const { content } = agentMarkdown("drill", "a/b", { notes: "extra" }); - const body = content.slice(content.lastIndexOf("---\n") + 4); - expect(body.indexOf(PROMPT_CLOSE)).toBeLessThan(body.indexOf(NOTES_OPEN)); - expect(body.indexOf(NOTES_OPEN)).toBeLessThan(body.indexOf(NOTES_CLOSE)); -}); - -test("a blank override is ignored rather than written as an empty key", () => { - const { content } = agentMarkdown("grunt", "a/b", { variant: " ", notes: " " }); - expect(content).not.toContain("variant:"); - expect(content).not.toContain(NOTES_OPEN); +test("roleRules hands out copies: a caller cannot edit the role's policy", () => { + roleRules("drill")[0].effect = "allow"; + expect(roleRules("drill")[0]).toEqual({ action: "*", resource: "*", effect: "deny" }); }); test("describeAgent carries the owner rule and the plan, nothing invented", () => { @@ -293,3 +163,12 @@ test("squadRoleOf reads the role off a runtime agent id and nothing else", () => expect(squadRoleOf("my-grunt-helper")).toBeNull(); expect(squadRoleOf(undefined)).toBeNull(); }); + +test("isGeneratedAgent: only this plugin's marker, on the first frontmatter line", () => { + expect( + isGeneratedAgent("---\n# generated-by: opencode-squad squad-draft\nmodel: a/b\n---\n"), + ).toBe(true); + expect(isGeneratedAgent("---\r\n# generated-by: opencode-orchestrate x\r\n")).toBe(true); + expect(isGeneratedAgent("---\n# generated-by: opencode-other-tool\n---\n")).toBe(false); + expect(isGeneratedAgent("---\nmodel: a/b\n---\n# generated-by: opencode-squad\n")).toBe(false); +}); diff --git a/vitest.config.js b/vitest.config.js index 89c7349..1aa711d 100644 --- a/vitest.config.js +++ b/vitest.config.js @@ -3,6 +3,8 @@ import { defineConfig } from "vitest/config"; export default defineConfig({ test: { include: ["tests/**/*.test.js"], + // No test may touch the real OpenCode config (squad.json, model_data.json). + setupFiles: ["tests/setup-isolation.js"], coverage: { provider: "v8", // Scoped to src/ on purpose: this is the pure decision-logic layer the From c66ff5971d2ba5906076230f33b690107d61764f Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:57:49 +0300 Subject: [PATCH 02/17] squad: integration test on the real host; docs and skills for squad.json (#85) tests-integration/squad-agents.test.js runs the real plugin on OpenCode 2.1.3 with a global allow-all: drill tools are read-only, rm is refused, a dropped legacy agent is not dispatchable, squad_patch is live on the next dispatch, and a hand-authored agent with a squad id is left alone. The directory argument is gone from the tool schemas. Co-Authored-By: Claude Opus 5.5 --- .opencode/lib/squad.js | 2 +- README.md | 69 ++++---- skills/squad-draft/SKILL.md | 40 ++--- skills/squad-redteam/SKILL.md | 10 +- src/prompt-inject.js | 27 +-- src/roster-schema.js | 5 +- src/roster.js | 12 +- src/squad-tools.js | 12 +- src/v2/schemas.js | 4 +- tests-integration/host.js | 19 ++- tests-integration/squad-agents.test.js | 220 +++++++++++++++++++++++++ tests/squad-tools.test.js | 6 +- 12 files changed, 315 insertions(+), 111 deletions(-) create mode 100644 tests-integration/squad-agents.test.js diff --git a/.opencode/lib/squad.js b/.opencode/lib/squad.js index 41bb34b..0163ad9 100644 --- a/.opencode/lib/squad.js +++ b/.opencode/lib/squad.js @@ -152,7 +152,7 @@ export default { // --- lazy, process-lifetime lookups --- - // opencode reloads agent files live, so the list is re-read after a short + // The agent list changes at runtime (squad_patch, another process), so it is re-read after a short // TTL rather than held for the process lifetime: the startup description // sync and squad_patch both land seconds AFTER a first turn may have // asked, and the desktop service runs for hours. diff --git a/README.md b/README.md index 64264d6..938ea95 100644 --- a/README.md +++ b/README.md @@ -115,33 +115,26 @@ The global file is refreshed at opencode startup: new squad models get an empty --- -## Optional: override subagent models +## Changing subagent models -Use `squad-draft` to add or retune the generated per-model agents. For a project-specific override of an existing generated agent, use its full id under `agents`: - -```json -{ - "plugins": ["@gfn-cis/opencode-squad"], - "agents": { - "grunt-anthropic-claude-sonnet-4-6": { "model": "anthropic/claude-sonnet-4-6#high" } - } -} -``` - -Unspecified fields keep the generated definition. There are no generic fallback grunt/drill agents. +Use `squad-draft` (or `squad_dump` + `squad_patch`) to add or retune the per-model agents. The squad is one roster for every project; an `agents` entry in a project's `opencode.json` no longer overrides a squad agent, because the plugin registers those agents itself and sets every field. There are no generic fallback grunt/drill agents. --- ## Per-model squad (grunts + drills) -OpenCode's `subagent` tool dispatches by agent id rather than model, so model choice requires a named agent per model per role. The `squad-draft` skill discovers available models (`opencode models`), proposes a tiered roster, asks what to change, then — on your OK — writes a hidden **grunt** (executor) and **drill** (read-only reviewer) per selected model into `~/.config/opencode/agent/` (or `$XDG_CONFIG_HOME/opencode/agent`). Existing legacy agent files can be read and regenerated in native format without losing roster settings. +OpenCode's `subagent` tool dispatches by agent id rather than model, so model choice requires a named agent per model per role. The `squad-draft` skill discovers available models (`opencode models`), proposes a tiered roster, asks what to change, then — on your OK — saves the roster to `squad.json` in the OpenCode config dir (`~/.config/opencode/`, or `$XDG_CONFIG_HOME/opencode/`). The plugin registers a hidden **grunt** (executor) and **drill** (read-only reviewer) per selected model through OpenCode's plugin API; no agent file is written. ``` openai/gpt-5.5 → grunt-openai-gpt-5-5 (executor: edit/shell) → drill-openai-gpt-5-5 (reviewer: read-only) ``` -Each generated agent shares the bundled grunt/drill prompt and permissions, differs only in `model`, and is `hidden` (dispatched via `subagent`, not in the `@`-menu). They appear in the orchestrator's inventory **with their models and capability summary**, which makes routing concrete. Re-running syncs the set (prunes generated agents no longer listed; never touches hand-authored agents). OpenCode reloads changed agent files automatically, so no restart is needed. Each file carries a fenced placeholder rather than the role prompt itself; the plugin injects the current `prompts/.md` on every request. Without the plugin loaded the placeholder tells the agent to stop rather than improvise. Frontmatter changes still require re-applying the roster. +Each squad agent shares the bundled grunt/drill prompt and permissions, differs only in `model`, and is `hidden` (dispatched via `subagent`, not in the `@`-menu). They appear in the orchestrator's inventory **with their models and capability summary**, which makes routing concrete. A `squad_patch` applies to the next dispatch, without a restart, and another OpenCode process sharing the config dir picks the change up on its next request. The role prompt comes from `prompts/.md` and is refreshed on every request, so editing it takes effect immediately. Hand-authored agents are never touched. + +**Upgrading from file-based squads (before #85).** On first start the plugin imports the generated `grunt-*`/`drill-*`/`worker-*` files from `~/.config/opencode/agent/` into `squad.json`, once. The files are left in place: the plugin's agents take over their ids, and generated agents the roster no longer has are hidden. `squad_dump` lists the leftovers, and you may delete them. If a generated file cannot be read, nothing is imported and `squad_dump` says which file to fix. + +**Drill permissions.** The plugin appends each role's permission rules after your global `permissions`, so with OpenCode's last-match evaluation a drill stays read-only even when your global config allows everything. The host then hides from a drill every tool its rules deny. There is no bundled fallback agent — if no `grunt-*`/`drill-*` exists yet, the orchestrator tells you to run `squad-draft` instead of inventing a subagent or quietly doing the work itself. @@ -320,8 +313,8 @@ So the roster is data you edit, exposed as two plugin tools: | tool | what it does | | --- | --- | -| `squad_dump` | returns the current roster as JSON, derived from the agent files | -| `squad_patch` | writes a roster back — `grunts` / `drills`, plus `allow_remove` and `directory`; refuses a `description` (generated, see below) and a roster wrapped in an extra key | +| `squad_dump` | returns the current roster from `squad.json` as JSON | +| `squad_patch` | writes a roster back — `grunts` / `drills`, plus `allow_remove`; refuses a `description` (generated, see below), a roster wrapped in an extra key, and the removed `directory` argument | | `squad_metrics` | benchmarks, prices, context and billing for the `models` given; `full: true` for every metric of up to 6 — see [Model metrics](#model-metrics-squad_metrics) | A third tool covers the other half of reuse: @@ -372,7 +365,7 @@ Per-agent fields, and why these and not the rest of opencode's agent schema: | `steps` | cap on agentic iterations before opencode forces a text response | | `disable` | park an agent without deleting it — the soft alternative to a removal | -**Descriptions are generated, not drafted.** An agent's `description` is the line the orchestrator reads when it picks whom to dispatch, so it carries exactly what you own and nothing that goes stale: the role, your `info` for that model as `Owner rule: …`, and the provider's plan (`Billing: subscription (Max 5x).`). The plugin writes it on every `squad_patch` and **rewrites it at every start** from the global `model_data.json` — only files whose text changes, atomically — and opencode reloads changed agent files live. So editing `info` or a plan needs a restart, not a re-draft. A `model_data.json` that does not parse is never overwritten: startup leaves it as it is and logs its path and the parse position, the description rewrite is skipped, `squad_patch` refuses until it is fixed, and `squad_metrics` lists it as ignored. Benchmarks, prices and rankings never go in: hand-written ones went stale within a week, and an orchestrator asked to "refresh descriptions" invented them. +**Descriptions are generated, not drafted.** An agent's `description` is the line the orchestrator reads when it picks whom to dispatch, so it carries exactly what you own and nothing that goes stale: the role, your `info` for that model as `Owner rule: …`, and the provider's plan (`Billing: subscription (Max 5x).`). The plugin builds it from the global `model_data.json` whenever it registers the agents: at start and after every `squad_patch`. So editing `info` or a plan needs a restart, not a re-draft. A `model_data.json` that does not parse is never overwritten: startup leaves it as it is and logs its path and the parse position, `squad_patch` refuses until it is fixed, and `squad_metrics` lists it as ignored. Benchmarks, prices and rankings never go in: hand-written ones went stale within a week, and an orchestrator asked to "refresh descriptions" invented them. Deliberately **not** exposed: `permission` (a drill's read-only contract is a safety property, not a preference), `mode`/`hidden`/`color` (ours), and @@ -386,33 +379,29 @@ that deletes agents. Two properties make the flow safe, and neither is optional: -1. **The roster is derived, never stored.** Every `squad_dump` reads the - generated agent files. A manifest kept beside them would be a second source of - truth, desyncing the first time anyone edited the agent dir by hand. +1. **The roster has one home.** `squad.json` is the whole squad, and only the + plugin writes it. There are no agent files beside it to drift from it. A file + that does not parse is never overwritten: nothing new is registered from it, + `squad_dump` reports it, and `squad_patch` refuses until it is fixed. 2. **Apply refuses to delete.** Read-modify-write only protects while the caller actually modifies; one that rebuilds the roster from memory reintroduces the wipe in a new wrapper. So deletions are refused and named — nothing at all is written, not even the agent that would have been added — until `allow_remove` - says otherwise. The unit is the agent, which is also the unit on disk, so - dropping just a drill is gated exactly like dropping a model. - -**One file, one agent.** OpenCode loads agent Markdown from `agent/` and -`agents/` (recursively) and from `mode/` and `modes/` (top level), through -links, so one file can be loaded under several agent names. Before it writes, -prunes or migrates anything, `squad_patch` checks every path it touches against -all of them: if another loadable name reaches the same file, or a directory -cannot be listed, it refuses and names the paths. The startup description -refresh skips such files and logs them, and `squad_dump` lists them. -`allow_remove` permits dropping a roster entry, not breaking another agent. -Known limitation: a plain `agents -> agent` directory link makes OpenCode load -each file twice under the same id, which would be harmless, but Squad still -refuses it. That errs on the safe side. + says otherwise. The unit is the agent, so dropping just a drill is gated + exactly like dropping a model. + +**No agent files.** Earlier versions wrote each agent as a Markdown file in the +directory OpenCode loads agents from. OpenCode also loads that directory's +siblings and follows links, so one file could be reached under several agent +names, and every write, prune or migration risked changing another agent (#52). +Since #85 the plugin registers the squad through OpenCode's agent API instead, and +none of that can happen. `squad_patch` additionally refuses to run from a `grunt-`/`drill-` agent. A subagent rewriting the squad mid-task is never intended, and the damage outlives the session. -Hand-authored agents are invisible in every mode: never dumped, never pruned. +Hand-authored agents are never dumped, changed or hidden. One that already holds a squad id (`grunt-`) wins: that squad entry is not registered, `squad_dump` notes it, and `squad_patch` refuses the id. --- @@ -568,7 +557,7 @@ Check the OpenCode log for a line referencing `opencode-squad` (plugin id `squad **Orchestrator says there's no squad** -There is no bundled grunt/drill fallback agent — if `~/.config/opencode/agent/` (or a project's `.opencode/agent/`) has no `grunt-*`/`drill-*` files, the bootstrap tells sarge to send you to the `squad-draft` skill instead of delegating. Run it once. +There is no bundled grunt/drill fallback agent — if `squad.json` holds no agents (and there are no `grunt-*`/`drill-*` agents of your own), the bootstrap tells sarge to send you to the `squad-draft` skill instead of delegating. Run it once. **Check which mode it chose** @@ -592,7 +581,11 @@ npm run knip # unused files/exports/dependencies npm run test:integration # the plugin inside the real OpenCode 2 host, offline (Node >= 24) ``` -`tests-integration/` boots the embedded OpenCode 2.1.3 host (`@opencode/sdk`), loads this repository as a plugin from disk, and replaces the model with `TestLLM` from `@opencode/ai/testing`. No credentials and no network: HOME and the XDG dirs point into a temp directory, and every outbound fetch fails. It checks that the plugin loads and puts its bootstrap in the system prompt, that a scripted tool call reaches `squad_session`, and that a subagent whose model stream hangs is interrupted with one guard note to its orchestrator. All `@opencode/*` dev packages are pinned to one exact release, so the host and the plugin types come from the same build. +`tests-integration/` boots the embedded OpenCode 2.1.3 host (`@opencode/sdk`), loads this repository as a plugin from disk, and replaces the model with `TestLLM` from `@opencode/ai/testing`. No credentials and no network: HOME and the XDG dirs point into a temp directory, and every outbound fetch fails. It checks that the plugin loads and puts its bootstrap in the system prompt, that a scripted tool call reaches `squad_session`, and that a subagent whose model stream hangs is interrupted with one guard note to its orchestrator. It also checks the squad agents registered from `squad.json`: +- a drill gets only read-only tools despite a global allow-all, and `rm` is refused; +- a legacy agent dropped from the roster cannot be dispatched; +- a `squad_patch` applies to the next dispatch; +- a hand-authored agent with a squad id keeps its own prompt. All `@opencode/*` dev packages are pinned to one exact release, so the host and the plugin types come from the same build. Coverage is scoped to `src/**` on purpose — that's the decision-logic layer separated from `.opencode/lib/squad.js`'s session/tool hook plumbing. Package-entry tests additionally check registration and native agent generation. diff --git a/skills/squad-draft/SKILL.md b/skills/squad-draft/SKILL.md index c7ded95..98c3130 100644 --- a/skills/squad-draft/SKILL.md +++ b/skills/squad-draft/SKILL.md @@ -11,8 +11,9 @@ let sarge choose a model — for execution OR review — is a named agent per mo a `grunt--` (executor) and a `drill--` (read-only reviewer with allowlisted git/gh/glab inspection and web access). -Requires OpenCode 2. Generated files use native `permissions:`, `model: provider/model#variant` -and `disabled: true`. Existing legacy agent files are read and migrated on re-apply. +Requires OpenCode 2. The roster is saved to `squad.json` in the OpenCode config dir and the +plugin registers the agents itself; no agent file is written. A squad that an older +version wrote as agent files is imported once, at the first start. The squad is edited through two tools, `squad_dump` and `squad_patch`. The roster they speak is one map per role, keyed by model id: @@ -71,9 +72,9 @@ job. (If they hand you an explicit list, honor it.) 3. **Do not write descriptions — they are generated.** The description is what sarge reads at the moment of choice, so it carries only what the USER owns: the model's `info` from `model_data.json` (a binding routing rule, e.g. "no - secrets, no production") and the provider's plan. The plugin builds it on - every `squad_patch` and rewrites it at every start, so an edited `info` or - plan reaches sarge after a restart without a re-draft. Benchmarks, prices, + secrets, no production") and the provider's plan. The plugin builds it + whenever it registers the agents (at start and after every `squad_patch`), + so an edited `info` or plan reaches sarge after a restart without a re-draft. Benchmarks, prices, context and rankings stay out — sarge reads them live from `squad_metrics`; a frozen copy goes stale (a GLM grunt kept advertising "(60/75/84)" long after its source re-scored it at half that). `squad_patch` refuses a @@ -170,16 +171,15 @@ job. (If they hand you an explicit list, honor it.) the user asked for it. - Prefer `disable: true` over deleting an agent the user may want back — it stops being dispatchable but keeps its settings. - - `directory` targets a project's `.opencode/agent` instead of the global - `~/.config/opencode/agent` (or `$XDG_CONFIG_HOME/opencode/agent`). - - Hand-authored agents are invisible to both tools: never dumped, never - pruned. + - There is one squad for every project; `directory` is no longer accepted. + - Hand-authored agents are never dumped or changed. One that already holds a + squad id wins: that entry is not registered, and `squad_patch` refuses it. 7. **Report** the applied diff (`+added / -removed / ~changed / =unchanged`), echo the variants that were written — opencode ignores an unrecognized one without erroring, so this is the only place a typo shows up — and tell the - user that OpenCode reloads changed agent files automatically, so no restart is - needed. Role prompt bodies refresh on every request without re-apply. + user the change applies to the next dispatch, with no restart. Role prompt + bodies refresh on every request without re-apply. ## Notes @@ -197,17 +197,9 @@ job. (If they hand you an explicit list, honor it.) round-trip through `squad_dump`. Use them for per-model quirks, not for policy that belongs in the shared role prompt. - To change behavior for ALL agents of a role, edit the bundled - `prompts/grunt.md` / `prompts/drill.md`. **No re-apply is needed**: the agent - file holds only a fenced placeholder, and the plugin injects the current - prompt on every request (the session `context` hook, see + `prompts/grunt.md` / `prompts/drill.md`. **No re-apply is needed**: the plugin + injects the current prompt on every request (the session `context` hook, see `src/prompt-inject.js`), so an edit is live for the next model call — even - mid-session. The prompt is NOT copied into the file, deliberately: one source - of truth, and nothing on disk that can quietly disagree with what was sent. - Without the plugin an agent has no role prompt at all — the placeholder tells - it to stop and say so, which is the right failure for a grunt holding - `edit`/`shell`. Two limits: an agent generated before the fence existed needs - ONE re-apply to opt in, and everything in the frontmatter — `model`, - `variant`, `steps`, `disable`, permissions, adding or removing a model — still - only changes by re-applying the roster. The `description` is the exception: - the plugin re-derives it from `model_data.json` at every start, and opencode - reloads changed agent files live. + mid-session. `model`, `variant`, `steps`, `disable` and adding or removing a + model change through `squad_patch`; the `description` follows + `model_data.json` at the next start. diff --git a/skills/squad-redteam/SKILL.md b/skills/squad-redteam/SKILL.md index bfaab23..4e65c0d 100644 --- a/skills/squad-redteam/SKILL.md +++ b/skills/squad-redteam/SKILL.md @@ -41,7 +41,7 @@ step 3's `subagent` calls are sent: fall back to "whatever seems to be the current task" — a wrong guess here means every panel member reviews the wrong thing. - The only tools you may use before dispatch are the discovery commands in - step 1 (listing agent files, the `squad_metrics` tool) and the + step 1 (`squad_dump`, the `squad_metrics` tool) and the multi-select question tool. And every dispatched grunt gets told, verbatim, in its task brief (step 3): @@ -62,11 +62,9 @@ first. 1. **Discover the grunts yourself — don't rely on the bootstrap inventory having arrived this turn.** Read the source of truth directly: - ```bash - ls ~/.config/opencode/agent/grunt-*.md .opencode/agent/grunt-*.md 2>/dev/null - ``` - Each file's frontmatter has a `model:` line (`provider/model`). Group the - grunts by the provider segment of the filename (`grunt--...`). + call `squad_dump`. Its `grunts` map is keyed by model id + (`provider/model`); the agent id is `grunt--`. Group the + grunts by provider. 2. Within each provider group, rank by capability. Use the `squad_metrics` result already in your history, or call it once with the grunts' models if it is not: the diff --git a/src/prompt-inject.js b/src/prompt-inject.js index 952b53b..dfd5472 100644 --- a/src/prompt-inject.js +++ b/src/prompt-inject.js @@ -1,19 +1,19 @@ -// Keep a generated agent's role prompt live: swap the body that was frozen -// into its file at generation time for the one bundled with the plugin RIGHT -// NOW, on every request, via the session `context` hook. +// Keep a squad agent's role prompt live: swap the body it was registered with +// for the one bundled with the plugin RIGHT NOW, on every request, via the +// session `context` hook. // -// WHY. A generated agent file exists per model, because the `subagent` tool -// dispatches by agent id and the file is the place a model can be -// pinned. The role prompt used to be INLINED into each of those files, which -// made every file a copy: editing the bundled prompt changed nothing for a -// squad already on disk until someone re-ran squad-draft by hand — a manual -// step nobody remembers, and the copies drifted silently. +// WHY. A squad agent exists per model, because the `subagent` tool dispatches +// by agent id. The plugin registers each with the role prompt it read at +// registration (src/squad-agents.js); an edit to prompts/.md must still +// reach a squad registered hours earlier in a long-lived service, without a +// re-register. Before #85 the agents were files, and the copies in them +// drifted silently until someone re-ran squad-draft. // // The context hook supplies SystemPart[]; the adapter applies this string // splice to the text part that carries a role fence. // -// The role travels INSIDE the text, in the fence markers written by -// `agentMarkdown`. A fence is self-describing, needs no +// The role travels INSIDE the text, in the fence markers the registered +// system prompt carries. A fence is self-describing, needs no // lookup, works for project-scoped agents, and its absence is the correct // no-op for sarge and for hand-authored agents. // @@ -54,7 +54,8 @@ export function wrapPrompt(role, body) { } /** - * What a generated agent file carries INSIDE the fence: not the prompt, a note + * What a squad agent is registered with INSIDE the fence when the bundled role + * prompt cannot be read: not the prompt, a note * saying where the prompt comes from — plus an instruction for the one case * where a model ever reads this text, which is the plugin failing to replace * it. Kept to a few lines because it is dead weight in every healthy request. @@ -82,7 +83,7 @@ export function placeholderBody(role) { /** * Locate the fence in a system prompt. * - * Only the FIRST fence is considered: one agent file carries one role prompt, + * Only the FIRST fence is considered: one agent carries one role prompt, * and a second one would mean something built a payload we do not understand — * in which case doing nothing is the safe reading. * diff --git a/src/roster-schema.js b/src/roster-schema.js index c7a282d..ecba193 100644 --- a/src/roster-schema.js +++ b/src/roster-schema.js @@ -3,7 +3,7 @@ // a tool without the advertised schema being enforced), and the input type // all come from these Zod schemas. Installed-model variant checks and the // deletion guard stay at the application boundary (src/squad-tools.js, -// src/squad-apply.js): they need the host and the disk. +// src/squad-apply.js): they need the host and the stored roster. import { z } from "zod"; @@ -56,7 +56,6 @@ const RosterSchema = z.strictObject({ /** squad_patch's whole input: the roster plus the call's own switches. */ const SquadPatchInputSchema = RosterSchema.extend({ allow_remove: z.boolean().describe(ARG_DESCRIPTIONS["patch.allow_remove"]).optional(), - directory: z.string().describe(ARG_DESCRIPTIONS["patch.directory"]).optional(), }); /** @typedef {z.input} SquadPatchInput */ @@ -109,7 +108,7 @@ export function validateRoster(doc) { /** * validateRoster for squad_patch's whole input: the roster plus `allow_remove` - * and `directory`, against the same schema the tool advertises. + * against the same schema the tool advertises. * * @param {unknown} input * @returns {string[]} empty when valid diff --git a/src/roster.js b/src/roster.js index 59b1196..17f648d 100644 --- a/src/roster.js +++ b/src/roster.js @@ -1,5 +1,5 @@ -// The squad roster as data: read the current squad out of the generated agent -// files, validate an edited roster, and diff the two. +// The squad roster as data: diff two rosters, and read one entry back out of +// an agent file that versions before #85 generated (for the one-time import). // // Why this exists. The generator used to take one declarative list — "here is // the roster, prune everything else". Asked to ADD a model, the caller would @@ -13,16 +13,16 @@ // // Two properties make that safe, and neither is optional: // -// 1. The roster is DERIVED from the agent files on every dump, never stored -// alongside them. A stored manifest would be a second source of truth, and -// it would desync the first time anyone touched the agent dir by hand. +// 1. The roster has ONE home, squad.json (src/squad-store.js), which only the +// plugin writes. Before #85 it was derived from agent files instead, to +// avoid a second source of truth; now there are no agent files at all. // // 2. Apply refuses to delete. Read-modify-write only protects while the // caller actually modifies; one that regenerates the roster from memory // reintroduces the wipe in a new wrapper. The guard, not the format, is // what makes destruction require intent. // -// SHAPE. One map per role, keyed by model id, mirroring the files on disk: +// SHAPE. One map per role, keyed by model id: // // { "grunts": { "zai-coding-plan/glm-5.3": { "variant": "high" } }, // "drills": { "anthropic/claude-opus-5": { "variant": "max" } } } diff --git a/src/squad-tools.js b/src/squad-tools.js index 6e86607..bc0b888 100644 --- a/src/squad-tools.js +++ b/src/squad-tools.js @@ -25,7 +25,7 @@ export const TOOL_DESCRIPTIONS = { "in the `subagent` reply and in its message. Without sessionIDs: the " + "current date and time and your own context size.", squad_dump: - "Read the current squad roster: every generated agent, grouped as `grunts` and " + + "Read the current squad roster: every squad agent, grouped as `grunts` and " + "`drills` and keyed by model id, with its per-agent settings. ALWAYS call this " + "before squad_patch — the roster is a document you edit, not one you retype. " + "Returns JSON.", @@ -43,7 +43,8 @@ export const TOOL_DESCRIPTIONS = { "it is DELETED, so start from squad_dump and edit that. Deleting an agent the user " + "did not ask you to delete is refused, not performed. Agent descriptions are not " + "yours to write: the plugin builds them from model_data.json (the owner's `info` " + - "per model and the provider's plan) on every apply and at startup.", + "per model and the provider's plan) whenever it registers the agents. The change " + + "applies to the next dispatch; no restart.", }; /** Argument descriptions, keyed by argument (agent-entry fields under `agent.*`). */ @@ -66,10 +67,6 @@ export const ARG_DESCRIPTIONS = { "session.sessionIDs": "The subagent sessions to check — every session you are weighing for reuse, in " + "one call. Omit for the current time and your own context.", - "dump.directory": - "Agent directory to read. Defaults to the global ~/.config/opencode/agent " + - "(or $XDG_CONFIG_HOME/opencode/agent). " + - "Pass a project's .opencode/agent to scope the squad to one project.", "metrics.models": "opencode model ids (provider/model) — normally the models of your grunt/drill " + "agents, deduplicated.", @@ -87,9 +84,6 @@ export const ARG_DESCRIPTIONS = { "Permit deleting agents present in the current squad but absent from this " + "roster. Pass true ONLY when the user asked for that deletion — never to " + "get past the refusal.", - "patch.directory": - "Agent directory to write. Defaults to the global ~/.config/opencode/agent " + - "(or $XDG_CONFIG_HOME/opencode/agent).", }; /** diff --git a/src/v2/schemas.js b/src/v2/schemas.js index ac3fc9d..6d33029 100644 --- a/src/v2/schemas.js +++ b/src/v2/schemas.js @@ -29,9 +29,7 @@ export const SQUAD_SESSION_INPUT = { export const SQUAD_DUMP_INPUT = { type: "object", - properties: { - directory: { type: "string", description: ARG_DESCRIPTIONS["dump.directory"] }, - }, + properties: {}, additionalProperties: false, }; diff --git a/tests-integration/host.js b/tests-integration/host.js index 9a504e9..46b59c4 100644 --- a/tests-integration/host.js +++ b/tests-integration/host.js @@ -34,16 +34,22 @@ export const model = SessionRunnerModel.resolved( * Boot a host in a temp project, run `body` against it, tear everything down. * * @template T - * @param {(h: {opencode: any, llm: any, project: string, location: any}) => Effect.Effect} body + * @param {(h: {opencode: any, llm: any, project: string, location: any, resolved: any[]}) => Effect.Effect} body * @param {Record} [configExtra] more opencode.json content + * @param {{prepare?: (project: string) => Promise}} [opts] + * prepare: lay out files before the host starts (the project is also the + * host's config dir, so `/agent/*.md` are loaded agent files) * @returns {Promise} */ -export function withHost(body, configExtra = {}) { +export function withHost(body, configExtra = {}, { prepare } = {}) { + /** Every session the runner resolved a model for, as the host passed it. */ + const resolved = []; const program = Effect.gen(function* () { const project = yield* Effect.acquireRelease( Effect.promise(() => fs.mkdtemp(path.join(os.tmpdir(), "squad-it-project-"))), (dir) => Effect.promise(() => fs.rm(dir, { recursive: true, force: true })), ); + if (prepare) yield* Effect.promise(() => prepare(project)); const llm = yield* TestLLM.Test.pipe(Effect.provide(TestLLM.testLayer())); const opencode = yield* OpenCode.create( { @@ -63,13 +69,18 @@ export function withHost(body, configExtra = {}) { overrides: [ llmClient.replace(Layer.succeed(LLMClient.Service, llm)), SessionRunnerModel.node.replace( - Layer.succeed(SessionRunnerModel.Service, { resolve: () => Effect.succeed(model) }), + Layer.succeed(SessionRunnerModel.Service, { + resolve: (/** @type {any} */ session) => { + resolved.push(session); + return Effect.succeed(model); + }, + }), ), ], }, ); const location = Location.Ref.make({ directory: AbsolutePath.make(project) }); - return yield* body({ opencode, llm, project, location }); + return yield* body({ opencode, llm, project, location, resolved }); }); return Effect.runPromise(Effect.scoped(program)); } diff --git a/tests-integration/squad-agents.test.js b/tests-integration/squad-agents.test.js new file mode 100644 index 0000000..8b16e77 --- /dev/null +++ b/tests-integration/squad-agents.test.js @@ -0,0 +1,220 @@ +// Suite: squad agents registered by the plugin from squad.json, in the real +// OpenCode 2.1.3 host, offline (#85). The roster file is in the run's +// XDG config dir (setup.js); the project is the host's config dir, so +// `/agent/*.md` are agent files the host loads by itself. +// Run: npm run test:integration (Node >= 24) + +import fs from "node:fs/promises"; +import path from "node:path"; +import { Effect } from "effect"; +import { afterEach, expect, test } from "vitest"; +import { promptOpen } from "../src/prompt-inject.js"; +import { model, TestLLM, withHost } from "./host.js"; + +const storeFile = () => path.join(process.env.XDG_CONFIG_HOME ?? "", "opencode", "squad.json"); +afterEach(() => fs.rm(storeFile(), { force: true })); + +/** @param {object} roster */ +async function writeRoster(roster) { + await fs.mkdir(path.dirname(storeFile()), { recursive: true }); + await fs.writeFile(storeFile(), JSON.stringify({ version: 1, ...roster })); +} + +/** An agent file as versions before #85 generated it. */ +const legacy = (role, model, extra = "") => + [ + "---", + "# generated-by: opencode-squad squad-draft", + 'description: "stale description"', + "mode: subagent", + `model: ${model}`, + extra, + "---", + "", + ``, + "stale body", + "", + "", + ].join("\n"); + +const isTitleRequest = (request) => (request.tools ?? []).length === 0; +const toolName = (t) => t.name ?? t.function?.name ?? ""; +const callTool = (id, name, input) => TestLLM.tool(id, name, input); +const code = (id, js) => TestLLM.tool(id, "execute", { code: js }); + +/** The tool part a parent call produced. */ +const toolState = (context, id) => + context.flatMap((m) => m.content ?? []).find((p) => p.type === "tool" && p.id === id)?.state; + +// The user's global rule allows everything: the squad's own rules must still +// decide for its agents. +const GLOBAL_ALLOW = { permissions: [{ action: "*", resource: "*", effect: "allow" }] }; + +test("the squad is registered from squad.json: dispatch, drill policy, legacy agents, live patch", async () => { + await writeRoster({ grunts: { "p/m": { variant: "high" } }, drills: { "p/m": {} } }); + const children = {}; + const out = await withHost( + (h) => + Effect.gen(function* () { + let turn = 0; + yield* h.llm.serve((request) => { + if (isTitleRequest(request)) return TestLLM.text("Title", "title"); + const body = JSON.stringify(request.messages ?? request); + const child = /CHILD-[A-Z-]+/.exec(body)?.[0]; + if (child && !body.includes("PARENT-ASK")) { + children[child] ??= { + tools: (request.tools ?? []).map(toolName), + system: JSON.stringify(request.system ?? null), + }; + if (child === "CHILD-DRILL") { + if (!body.includes("c-rm")) return callTool("c-rm", "shell", { command: "rm -rf x" }); + if (!body.includes("c-gl")) + return callTool("c-gl", "shell", { command: "git log -1" }); + children[child].results = body.slice(body.indexOf("c-rm")); + } + return TestLLM.text(`${child} done`, "answer"); + } + turn++; + if (turn === 1) return code("p-dump", "return await tools.squad_dump({})"); + if (turn === 2) + return callTool("p-drill", "subagent", { + agent: "drill-p-m", + description: "review", + prompt: "CHILD-DRILL", + }); + if (turn === 3) + return callTool("p-ghost", "subagent", { + agent: "drill-old-m", + description: "old", + prompt: "CHILD-GHOST", + }); + if (turn === 4) + return code( + "p-patch", + 'return await tools.squad_patch({grunts: {"p/m": {variant: "high"}, "p/n": {}}, drills: {"p/m": {}}})', + ); + if (turn === 5) + return callTool("p-new", "subagent", { + agent: "grunt-p-n", + description: "new", + prompt: "CHILD-NEW", + }); + return TestLLM.text("parent done", "answer"); + }); + const session = yield* h.opencode.sessions.create({ + location: h.location, + model: model.ref, + }); + yield* h.opencode.sessions.prompt({ sessionID: session.id, text: "PARENT-ASK" }); + yield* h.opencode.sessions + .wait({ sessionID: session.id }) + .pipe(Effect.timeout("60 seconds")); + const context = yield* h.opencode.sessions.context({ sessionID: session.id }); + return { context, resolved: h.resolved }; + }), + GLOBAL_ALLOW, + { + prepare: async (project) => { + await fs.mkdir(path.join(project, "agent")); + // The same id as a roster agent, with fields the squad does not set. + await fs.writeFile( + path.join(project, "agent", "grunt-p-m.md"), + legacy("grunt", "p/m", 'steps: 3\ncolor: "#ff0000"'), + ); + // A legacy agent the roster no longer has. + await fs.writeFile(path.join(project, "agent", "drill-old-m.md"), legacy("drill", "old/m")); + }, + }, + ); + + // squad_dump reads the roster from squad.json. + const dump = JSON.stringify(toolState(out.context, "p-dump")); + expect(dump).toContain(`Squad roster: ${storeFile()}`); + expect(dump).toContain('\\"p/m\\"'); + + // The drill: dispatched with its model, its role prompt, and read-only tools + // only, although the user's global rule allows everything. + const drillRun = out.resolved.find((s) => s.agent === "drill-p-m"); + expect(drillRun?.model).toMatchObject({ providerID: "p", id: "m" }); + const drill = children["CHILD-DRILL"]; + expect(drill.system).toContain(promptOpen("drill").replaceAll('"', '\\"')); + expect(drill.tools).toEqual(expect.arrayContaining(["read", "shell"])); + for (const denied of ["edit", "write", "execute", "subagent"]) + expect(drill.tools).not.toContain(denied); + expect(drill.results).toMatch(/"id":"c-rm".{0,200}permission\.rejected/); + expect(drill.results).not.toMatch(/"id":"c-gl".{0,200}permission\.rejected/); + + // The legacy agent the roster dropped is not dispatchable. + expect(toolState(out.context, "p-ghost")?.status).toBe("error"); + expect(children["CHILD-GHOST"]).toBeUndefined(); + + // squad_patch: written to squad.json, live on the next dispatch. + expect(JSON.stringify(toolState(out.context, "p-patch"))).toContain("+1 added"); + const stored = JSON.parse(await fs.readFile(storeFile(), "utf8")); + expect(Object.keys(stored.grunts)).toEqual(["p/m", "p/n"]); + const newRun = out.resolved.find((s) => s.agent === "grunt-p-n"); + expect(newRun?.model).toMatchObject({ providerID: "p", id: "n" }); + expect(children["CHILD-NEW"]).toBeDefined(); +}, 120_000); + +test("a hand-authored agent holding a roster id keeps its own prompt, and squad_patch refuses that id", async () => { + await writeRoster({ grunts: { "p/q": {} }, drills: {} }); + const children = {}; + const out = await withHost( + (h) => + Effect.gen(function* () { + let turn = 0; + yield* h.llm.serve((request) => { + if (isTitleRequest(request)) return TestLLM.text("Title", "title"); + const body = JSON.stringify(request.messages ?? request); + if (body.includes("CHILD-HAND") && !body.includes("PARENT-ASK")) { + children.hand ??= JSON.stringify(request.system ?? null); + return TestLLM.text("hand done", "answer"); + } + turn++; + if (turn === 1) return code("p-dump", "return await tools.squad_dump({})"); + if (turn === 2) + return callTool("p-hand", "subagent", { + agent: "grunt-p-q", + description: "hand", + prompt: "CHILD-HAND", + }); + if (turn === 3) + return code( + "p-patch", + 'return await tools.squad_patch({grunts: {"p/q": {variant: "high"}}})', + ); + return TestLLM.text("parent done", "answer"); + }); + const session = yield* h.opencode.sessions.create({ + location: h.location, + model: model.ref, + }); + yield* h.opencode.sessions.prompt({ sessionID: session.id, text: "PARENT-ASK" }); + yield* h.opencode.sessions + .wait({ sessionID: session.id }) + .pipe(Effect.timeout("60 seconds")); + return { context: yield* h.opencode.sessions.context({ sessionID: session.id }) }; + }), + GLOBAL_ALLOW, + { + prepare: async (project) => { + await fs.mkdir(path.join(project, "agent")); + await fs.writeFile( + path.join(project, "agent", "grunt-p-q.md"), + "---\ndescription: mine\nmode: subagent\n---\nHAND-WRITTEN PROMPT\n", + ); + }, + }, + ); + expect(JSON.stringify(toolState(out.context, "p-dump"))).toContain( + "grunt-p-q: a hand-authored agent holds this id", + ); + expect(children.hand).toContain("HAND-WRITTEN PROMPT"); + expect(children.hand).not.toContain("squad:prompt"); + const patch = JSON.stringify(toolState(out.context, "p-patch")); + expect(patch).toContain( + "REFUSED: the roster asks for an agent id that a hand-authored agent already holds", + ); + expect(JSON.parse(await fs.readFile(storeFile(), "utf8")).grunts).toEqual({ "p/q": {} }); +}, 120_000); diff --git a/tests/squad-tools.test.js b/tests/squad-tools.test.js index 3226e9d..508c0df 100644 --- a/tests/squad-tools.test.js +++ b/tests/squad-tools.test.js @@ -59,18 +59,16 @@ describe("V2 schemas", () => { expect(SQUAD_SESSION_INPUT.properties.sessionIDs.description).toBe( ARG_DESCRIPTIONS["session.sessionIDs"], ); + // No `directory` since #85: the squad is one roster, not files in a dir. expect(Object.keys(SQUAD_PATCH_INPUT.properties).sort()).toEqual([ "allow_remove", - "directory", "drills", "grunts", ]); expect(SQUAD_PATCH_INPUT.properties.grunts.additionalProperties.properties.steps.type).toBe( "integer", ); - expect(SQUAD_DUMP_INPUT.properties.directory.description).toBe( - ARG_DESCRIPTIONS["dump.directory"], - ); + expect(SQUAD_DUMP_INPUT.properties).toEqual({}); for (const s of [ SQUAD_COMPACT_INPUT, SQUAD_DUMP_INPUT, From 7ebd94d526953f13d2cfb963f81307c10cf7d77c Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:05:05 +0300 Subject: [PATCH 03/17] squad: guard and ownership fixes from review (#85) - Without squad.json, the legacy squad on disk is the current roster: a patch that drops an agent is a deletion, and an unreadable legacy file makes dump say the squad is unknown and patch refuse. - Ours = fenced, or a marker-verified legacy file of the global agent dir (pre-fence files and worker-* included). Only those are hidden when the roster drops them; generated-looking agents from elsewhere are noted. - A hand-authored agent on an unchanged entry no longer blocks a patch. Co-Authored-By: Claude Opus 5.5 --- .opencode/lib/squad.js | 73 ++++++++++++++++++----- src/squad-agents.js | 37 ++++++++---- tests-integration/squad-agents.test.js | 45 ++++++++++---- tests/plugin-entry.test.js | 82 ++++++++++++++++++++++++++ tests/squad-agents.test.js | 42 +++++++++++-- 5 files changed, 236 insertions(+), 43 deletions(-) diff --git a/.opencode/lib/squad.js b/.opencode/lib/squad.js index 0163ad9..a4d4a2d 100644 --- a/.opencode/lib/squad.js +++ b/.opencode/lib/squad.js @@ -27,6 +27,8 @@ * hooks and tools. */ +import path from "node:path"; + import { formatCompactReport } from "../../src/compact.js"; import { estimateContextTokens, indexModelCatalog } from "../../src/context.js"; import { formatInventory, hasSquad } from "../../src/inventory.js"; @@ -226,10 +228,39 @@ export default { const storeFile = defaultStoreFile(); let storeSig = storeSignature(storeFile); - /** Agents a hand-authored file holds, and legacy ones hidden; from the late transform. */ + /** From the late transform: hand-authored holders of roster ids, legacy agents hidden, stray ones left. */ let lateReport = { foreign: /** @type {string[]} */ ([]), hidden: /** @type {string[]} */ ([]), + stray: /** @type {string[]} */ ([]), + }; + // The agents earlier versions generated as files in the global agent dir, + // verified by their marker once, at start: the only way to know a + // pre-fence file or a worker-* is ours (src/squad-agents.js lateTransform). + const legacyIds = new Set( + readLegacySquad(defaultAgentDir()).files.map((f) => f.replace(/\.md$/, "")), + ); + /** + * The roster as it stands. Without squad.json yet (its import was blocked), + * the squad still exists as files: that is the roster an apply diffs + * against, so rebuilding from an empty dump cannot delete it unguarded. + * + * @returns {{state: "ok", roster: any} | {state: "invalid", problems: string[]}} + */ + const currentSquad = () => { + const store = readStore(storeFile); + if (store.state === "ok") return { state: "ok", roster: store.roster }; + if (store.state === "invalid") { + return { state: "invalid", problems: [`${storeFile}: ${store.reason}`] }; + } + const legacy = readLegacySquad(defaultAgentDir()); + if (legacy.problems.length) { + return { + state: "invalid", + problems: legacy.problems.map((p) => path.join(defaultAgentDir(), p)), + }; + } + return { state: "ok", roster: legacy.roster }; }; const specsNow = () => { const store = readStore(storeFile); @@ -260,6 +291,12 @@ export default { `${id}: a hand-authored agent holds this id, so the squad's entry is not registered`, ); } + for (const id of lateReport.stray) { + notes.push( + `${id}: looks generated but is not in the global agent dir, so it is left as is; ` + + "if it is an old squad file of a project, the user may delete it", + ); + } for (const p of legacyImport.problems) { notes.push(`legacy squad files were not imported: ${p}. Fix or delete it, then restart`); } @@ -284,7 +321,7 @@ export default { // An unreadable squad.json registers nothing and hides nothing: // legacy agent files, if any, keep working until it is fixed. const specs = specsNow(); - if (specs) lateReport = lateTransform(editor, specs); + if (specs) lateReport = lateTransform(editor, specs, legacyIds); } catch { // As above. } @@ -474,16 +511,17 @@ export default { execute: async (input) => { const { directory: asked } = /** @type {{directory?: unknown}} */ (input ?? {}); if (asked !== undefined) return { content: DIRECTORY_GONE }; - const store = readStore(storeFile); - if (store.state === "invalid") { + const squad = currentSquad(); + if (squad.state === "invalid") { return { content: - `The squad roster ${storeFile} cannot be read (${store.reason}). Nothing is ` + - "registered from it and squad_patch refuses until it is fixed: ask the user to " + - "repair or restore the file. It is never overwritten.", + "The squad cannot be read, so it is NOT empty: it is unknown. Nothing new is " + + "registered and squad_patch refuses until the user fixes:\n" + + squad.problems.map((p) => ` - ${p}`).join("\n") + + "\nAsk the user to repair or restore these. Do not build a roster from scratch.", }; } - const roster = store.state === "ok" ? store.roster : { grunts: {}, drills: {} }; + const roster = squad.roster; const count = Object.keys(roster.grunts).length + Object.keys(roster.drills).length; const notes = squadNotes(); const note = notes.length ? `\n\nnotes:\n${notes.map((c) => ` ${c}`).join("\n")}` : ""; @@ -647,16 +685,16 @@ export default { } // Re-read right before writing: another OpenCode process may have // changed the roster since this one last looked. - const store = readStore(storeFile); - if (store.state === "invalid") { + const squad = currentSquad(); + if (squad.state === "invalid") { return { content: - `Refused: the squad roster ${storeFile} cannot be read (${store.reason}), and ` + - "writing over it could lose the user's squad. Nothing was written. Ask the " + - "user to repair or restore it.", + "Refused: the current squad cannot be read, and writing a roster now could " + + "lose it. Nothing was written. Ask the user to fix:\n" + + squad.problems.map((p) => ` - ${p}`).join("\n"), }; } - const current = store.state === "ok" ? store.roster : { grunts: {}, drills: {} }; + const current = squad.roster; // A hand-authored agent already holding an id this roster wants. const agents = unwrap(await ctx.agent.list().catch(() => null)) ?? []; const byId = new Map( @@ -667,7 +705,12 @@ export default { ["grunts", "grunt"], ["drills", "drill"], ])) { - for (const modelId of Object.keys(roster[key])) { + for (const [modelId, entry] of Object.entries(roster[key])) { + // An entry kept as it was is not a new claim on the id: a user + // agent that took it over later is reported, not a reason to + // refuse every future patch. + const before = current[key]?.[modelId]; + if (before && JSON.stringify(before) === JSON.stringify(entry)) continue; const id = slugForModel(modelId, role); const agent = byId.get(id); if (agent && !isSquadSystem(agent.system)) { diff --git a/src/squad-agents.js b/src/squad-agents.js index a7ad46e..5f5c06b 100644 --- a/src/squad-agents.js +++ b/src/squad-agents.js @@ -19,9 +19,11 @@ // gets: base, global, own. The host then filters the child's tool // catalog by them: a drill sees read-only tools only. // -// A roster id whose agent is hand-authored (its system prompt has no -// squad:prompt fence after the config plugin ran) is left alone and reported: -// the user's agent wins, and squad_patch refuses that id. +// Which agents are ours: one registered from the roster, or one an earlier +// version generated as a file in the global agent dir (marker-verified at +// start). A roster id an agent of anyone else already holds (no squad:prompt +// fence, not a verified legacy file) is left alone and reported: the user's +// agent wins, and squad_patch refuses that id. import { findPromptFence, placeholderBody, wrapPrompt } from "./prompt-inject.js"; import { NOTES_CLOSE, NOTES_OPEN, ROLE_KEYS } from "./roster.js"; @@ -112,29 +114,42 @@ export function earlyTransform(editor, specs) { /** * @param {{list: () => readonly any[], get: (id: string) => any, update: (id: string, f: (agent: any) => void) => void, remove: (id: string) => void}} editor * @param {AgentSpec[]} specs - * @returns {{foreign: string[], hidden: string[]}} + * @param {Set} [legacy] agent ids of the generated files an earlier + * version wrote to the global agent dir, verified by their marker + * (src/squad-apply.js readLegacySquad). Files from before the role-prompt + * fence, and every `worker-*`, are only recognisable this way: the marker is + * a YAML comment the host never exposes. + * @returns {{foreign: string[], hidden: string[], stray: string[]}} * foreign: roster ids a hand-authored agent already holds (left alone); - * hidden: legacy generated agents removed because the roster no longer has them + * hidden: legacy generated agents removed because the roster no longer has them; + * stray: generated-looking agents from elsewhere (a project's own agent dir), + * left alone because this plugin did not verify them as its own */ -export function lateTransform(editor, specs) { +export function lateTransform(editor, specs, legacy = new Set()) { const wanted = new Map(specs.map((s) => [s.id, s])); /** @type {string[]} */ const foreign = []; /** @type {string[]} */ const hidden = []; + /** @type {string[]} */ + const stray = []; for (const agent of [...editor.list()]) { const id = String(agent?.id ?? ""); - if (wanted.has(id) || squadRoleOf(id) === null || !isSquadSystem(agent?.system)) continue; - editor.remove(id); - hidden.push(id); + if (wanted.has(id)) continue; + if (legacy.has(id)) { + editor.remove(id); + hidden.push(id); + } else if (squadRoleOf(id) !== null && isSquadSystem(agent?.system)) { + stray.push(id); + } } for (const spec of specs) { const current = editor.get(spec.id); - if (current && !isSquadSystem(current.system)) { + if (current && !isSquadSystem(current.system) && !legacy.has(spec.id)) { foreign.push(spec.id); continue; } editor.update(spec.id, (agent) => shape(agent, spec)); } - return { foreign: foreign.sort(), hidden: hidden.sort() }; + return { foreign: foreign.sort(), hidden: hidden.sort(), stray: stray.sort() }; } diff --git a/tests-integration/squad-agents.test.js b/tests-integration/squad-agents.test.js index 8b16e77..e3760c8 100644 --- a/tests-integration/squad-agents.test.js +++ b/tests-integration/squad-agents.test.js @@ -12,7 +12,10 @@ import { promptOpen } from "../src/prompt-inject.js"; import { model, TestLLM, withHost } from "./host.js"; const storeFile = () => path.join(process.env.XDG_CONFIG_HOME ?? "", "opencode", "squad.json"); -afterEach(() => fs.rm(storeFile(), { force: true })); +afterEach(async () => { + await fs.rm(storeFile(), { force: true }); + await fs.rm(path.join(path.dirname(storeFile()), "agent"), { recursive: true, force: true }); +}); /** @param {object} roster */ async function writeRoster(roster) { @@ -89,11 +92,17 @@ test("the squad is registered from squad.json: dispatch, drill policy, legacy ag prompt: "CHILD-GHOST", }); if (turn === 4) + return callTool("p-worker", "subagent", { + agent: "worker-old-w", + description: "old", + prompt: "CHILD-WORKER", + }); + if (turn === 5) return code( "p-patch", 'return await tools.squad_patch({grunts: {"p/m": {variant: "high"}, "p/n": {}}, drills: {"p/m": {}}})', ); - if (turn === 5) + if (turn === 6) return callTool("p-new", "subagent", { agent: "grunt-p-n", description: "new", @@ -115,14 +124,25 @@ test("the squad is registered from squad.json: dispatch, drill policy, legacy ag GLOBAL_ALLOW, { prepare: async (project) => { - await fs.mkdir(path.join(project, "agent")); - // The same id as a roster agent, with fields the squad does not set. - await fs.writeFile( - path.join(project, "agent", "grunt-p-m.md"), - legacy("grunt", "p/m", 'steps: 3\ncolor: "#ff0000"'), - ); - // A legacy agent the roster no longer has. - await fs.writeFile(path.join(project, "agent", "drill-old-m.md"), legacy("drill", "old/m")); + // In a real install the host loads agents from the same global dir the + // plugin verifies legacy files in; here the host's config dir is the + // project, so the files go to both. + const files = { + // The same id as a roster agent, with fields the squad does not set. + "grunt-p-m.md": legacy("grunt", "p/m", 'steps: 3\ncolor: "#ff0000"'), + // A legacy agent the roster no longer has. + "drill-old-m.md": legacy("drill", "old/m"), + // Generated before the role-prompt fence existed: no fence at all. + "worker-old-w.md": legacy("grunt", "old/w").replace(/\n?/g, ""), + }; + for (const dir of [ + path.join(project, "agent"), + path.join(path.dirname(storeFile()), "agent"), + ]) { + await fs.mkdir(dir, { recursive: true }); + for (const [name, text] of Object.entries(files)) + await fs.writeFile(path.join(dir, name), text); + } }, }, ); @@ -144,9 +164,12 @@ test("the squad is registered from squad.json: dispatch, drill policy, legacy ag expect(drill.results).toMatch(/"id":"c-rm".{0,200}permission\.rejected/); expect(drill.results).not.toMatch(/"id":"c-gl".{0,200}permission\.rejected/); - // The legacy agent the roster dropped is not dispatchable. + // Legacy agents the roster dropped are not dispatchable, a pre-fence + // worker- included. expect(toolState(out.context, "p-ghost")?.status).toBe("error"); expect(children["CHILD-GHOST"]).toBeUndefined(); + expect(toolState(out.context, "p-worker")?.status).toBe("error"); + expect(children["CHILD-WORKER"]).toBeUndefined(); // squad_patch: written to squad.json, live on the next dispatch. expect(JSON.stringify(toolState(out.context, "p-patch"))).toContain("+1 added"); diff --git a/tests/plugin-entry.test.js b/tests/plugin-entry.test.js index 935912b..199f837 100644 --- a/tests/plugin-entry.test.js +++ b/tests/plugin-entry.test.js @@ -399,3 +399,85 @@ test("squad_patch validates its input with the same schema it advertises", async dispose(); } }); + +/** A squad file as versions before #85 wrote it, in the global agent dir. */ +function legacyAgent(name, model) { + const dir = path.join(process.env.XDG_CONFIG_HOME, "opencode", "agent"); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(dir, name), + `---\n# generated-by: opencode-squad squad-draft\nmode: subagent\nmodel: ${model}\n---\n`, + ); + return dir; +} + +test("without squad.json, a legacy squad that cannot be read is unknown, not empty", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + const agentDir = legacyAgent("grunt-a-b.md", "a/b"); + dirs.push(agentDir); + fs.writeFileSync( + path.join(agentDir, "grunt-c-d.md"), + "---\n# generated-by: opencode-squad x\ndesc", + ); + const { tools, dispose } = await setupHost({ directory }); + try { + const dump = (await tools.get("squad_dump").execute({}, { agent: "build" })).content; + expect(dump).toContain("The squad cannot be read, so it is NOT empty"); + expect(dump).toContain("grunt-c-d.md"); + const patch = ( + await tools.get("squad_patch").execute({ grunts: { "x/y": {} } }, { agent: "build" }) + ).content; + expect(patch).toContain("Refused: the current squad cannot be read"); + expect(readStore(defaultStoreFile()).state).toBe("missing"); + } finally { + dispose(); + } +}); + +test("without squad.json, the legacy squad is what a patch is diffed against", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + dirs.push(legacyAgent("grunt-a-b.md", "a/b")); + legacyAgent("drill-a-b.md", "a/b"); + const { tools, dispose } = await setupHost({ directory }); + try { + const dump = (await tools.get("squad_dump").execute({}, { agent: "build" })).content; + expect(dump).toContain('"a/b"'); + // Rebuilt from memory without the drill: a deletion, refused. + const patch = ( + await tools.get("squad_patch").execute({ grunts: { "a/b": {} } }, { agent: "build" }) + ).content; + expect(patch).toContain("would DELETE 1 agent(s)"); + expect(patch).toContain("drill a/b"); + expect(readStore(defaultStoreFile()).state).toBe("missing"); + } finally { + dispose(); + } +}); + +test("a hand-authored agent on an unchanged entry is no reason to refuse other changes", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + const { writeStore } = await import("../src/squad-store.js"); + writeStore(defaultStoreFile(), { grunts: { "p/q": {} }, drills: {} }); + const { tools, dispose } = await setupHost({ + directory, + agent: { list: async () => [{ id: "grunt-p-q", system: "My own prompt." }] }, + }); + try { + const patch = tools.get("squad_patch"); + const kept = (await patch.execute({ grunts: { "p/q": {}, "p/r": {} } }, { agent: "build" })) + .content; + expect(kept).toContain("+1 added"); + // Changing that entry is a new claim on the user's id: refused. + const changed = ( + await patch.execute({ grunts: { "p/q": { variant: "high" }, "p/r": {} } }, { agent: "build" }) + ).content; + expect(changed).toContain( + "REFUSED: the roster asks for an agent id that a hand-authored agent", + ); + } finally { + dispose(); + } +}); diff --git a/tests/squad-agents.test.js b/tests/squad-agents.test.js index 1674a66..b4a707f 100644 --- a/tests/squad-agents.test.js +++ b/tests/squad-agents.test.js @@ -118,7 +118,7 @@ test("late: a same-id legacy generated file is taken over, its own fields cleare }; const editor = editorOf([legacy]); const report = lateTransform(editor, specs); - expect(report).toEqual({ foreign: [], hidden: [] }); + expect(report).toEqual({ foreign: [], hidden: [], stray: [] }); const agent = editor.get("grunt-a-b"); expect(agent.system).toContain("the grunt prompt"); expect(agent.description).toBe("grunt on a/b"); @@ -130,18 +130,48 @@ test("late: a hand-authored agent with a roster id is left alone and reported", const specs = agentSpecs({ grunts: { "a/b": {} } }, io); const mine = { id: "grunt-a-b", system: "My own prompt.", description: "mine", permissions: [] }; const editor = editorOf([mine]); - expect(lateTransform(editor, specs)).toEqual({ foreign: ["grunt-a-b"], hidden: [] }); + expect(lateTransform(editor, specs)).toEqual({ foreign: ["grunt-a-b"], hidden: [], stray: [] }); expect(editor.get("grunt-a-b")).toEqual(mine); }); -test("late: legacy generated agents the roster dropped are hidden; nothing else is", () => { +test("late: verified legacy agents the roster dropped are hidden, worker- included; nothing else is", () => { const fenced = `${promptOpen("drill")}\nx\n${PROMPT_CLOSE}`; const editor = editorOf([ { id: "drill-old-model", system: fenced, permissions: [] }, + // Generated before the fence existed: only the marker-verified set knows it. + { id: "worker-old-model", system: "an old inlined prompt", permissions: [] }, { id: "drill-hand-written", system: "mine", permissions: [] }, + // Fenced, but from a project's own agent dir: not verified as ours. + { id: "drill-project-model", system: fenced, permissions: [] }, { id: "build", system: fenced, permissions: [] }, ]); - const report = lateTransform(editor, agentSpecs({ grunts: { "a/b": {} } }, io)); - expect(report.hidden).toEqual(["drill-old-model"]); - expect([...editor.map.keys()].sort()).toEqual(["build", "drill-hand-written", "grunt-a-b"]); + const report = lateTransform( + editor, + agentSpecs({ grunts: { "a/b": {} } }, io), + new Set(["drill-old-model", "worker-old-model"]), + ); + expect(report).toEqual({ + foreign: [], + hidden: ["drill-old-model", "worker-old-model"], + stray: ["drill-project-model"], + }); + expect([...editor.map.keys()].sort()).toEqual([ + "build", + "drill-hand-written", + "drill-project-model", + "grunt-a-b", + ]); +}); + +test("late: a pre-fence legacy file with a roster id is taken over, not foreign", () => { + const editor = editorOf([ + { id: "grunt-a-b", system: "old inlined grunt prompt", permissions: [] }, + ]); + const report = lateTransform( + editor, + agentSpecs({ grunts: { "a/b": {} } }, io), + new Set(["grunt-a-b"]), + ); + expect(report.foreign).toEqual([]); + expect(editor.get("grunt-a-b").system).toContain("the grunt prompt"); }); From de3dd3bd31bfa943c547063bc7ff6a08fc5d918d Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:08:14 +0300 Subject: [PATCH 04/17] test(integration): build the pre-fence legacy file explicitly (CodeQL) Co-Authored-By: Claude Opus 5.5 --- tests-integration/squad-agents.test.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/tests-integration/squad-agents.test.js b/tests-integration/squad-agents.test.js index e3760c8..d8bd773 100644 --- a/tests-integration/squad-agents.test.js +++ b/tests-integration/squad-agents.test.js @@ -40,6 +40,20 @@ const legacy = (role, model, extra = "") => "", ].join("\n"); +/** A file generated before the role-prompt fence existed: the prompt inline. */ +const preFence = (model) => + [ + "---", + "# generated-by: opencode-orchestrate generating-model-workers", + 'description: "stale description"', + "mode: subagent", + `model: ${model}`, + "---", + "", + "You are a worker. (An old inlined prompt.)", + "", + ].join("\n"); + const isTitleRequest = (request) => (request.tools ?? []).length === 0; const toolName = (t) => t.name ?? t.function?.name ?? ""; const callTool = (id, name, input) => TestLLM.tool(id, name, input); @@ -133,7 +147,7 @@ test("the squad is registered from squad.json: dispatch, drill policy, legacy ag // A legacy agent the roster no longer has. "drill-old-m.md": legacy("drill", "old/m"), // Generated before the role-prompt fence existed: no fence at all. - "worker-old-w.md": legacy("grunt", "old/w").replace(/\n?/g, ""), + "worker-old-w.md": preFence("old/w"), }; for (const dir of [ path.join(project, "agent"), From a0a802417c57de14f82ea1647769751695874e34 Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:31:44 +0300 Subject: [PATCH 05/17] squad: build agents only after the config plugin; leave users' agents alone (#87, #88) The early transform now creates one throwaway probe agent (primary, hidden, deny-all) instead of the squad's agents. The late transform reads the user's global rules off it, removes it, and builds each squad agent from a fresh default with the role rules last. Until the late transform runs a squad agent does not exist, so a request for it fails instead of running with a permissive tool catalog. The late transform is registered on plugin.updated, in the prompt hook (before the host selects the agent, child sessions included) and in the context hook. On a squad agent's request the context hook checks that the role rules are still last, moves the late transform back to the end if the config plugin's was re-registered behind it, and drops the tools the role denies from the request's catalog. A legacy file proves ownership of the file, not the id: an agent at a legacy or roster id is taken over or hidden only when it is that file (same prompt and model). Any other agent there is left exactly as the host built it. Co-Authored-By: Claude Opus 5.5 --- .opencode/lib/squad.js | 177 +++++++++++++--- src/squad-agents.js | 277 +++++++++++++++++++------ src/squad-apply.js | 19 +- tests-integration/squad-review.test.js | 153 ++++++++++++++ tests/plugin-entry.test.js | 114 +++++++++- tests/squad-agents.test.js | 232 +++++++++++++++------ tests/squad-apply.test.js | 10 + 7 files changed, 812 insertions(+), 170 deletions(-) create mode 100644 tests-integration/squad-review.test.js diff --git a/.opencode/lib/squad.js b/.opencode/lib/squad.js index a4d4a2d..2ac134d 100644 --- a/.opencode/lib/squad.js +++ b/.opencode/lib/squad.js @@ -60,9 +60,13 @@ import { } from "../../src/session-status.js"; import { agentSpecs, + deniedTools, earlyTransform, + endsWithRoleRules, isSquadSystem, lateTransform, + PROBE_ID, + rosterCollisions, } from "../../src/squad-agents.js"; import { defaultAgentDir, @@ -92,7 +96,7 @@ import { SQUAD_SESSION_INPUT, } from "../../src/v2/schemas.js"; import { loadSkills } from "../../src/v2/skills.js"; -import { slugForModel } from "../../src/workers.js"; +import { roleRules, slugForModel, squadRoleOf } from "../../src/workers.js"; import { ensureGlobalModelDataFresh, getMetrics, @@ -233,13 +237,12 @@ export default { foreign: /** @type {string[]} */ ([]), hidden: /** @type {string[]} */ ([]), stray: /** @type {string[]} */ ([]), + kept: /** @type {string[]} */ ([]), }; // The agents earlier versions generated as files in the global agent dir, // verified by their marker once, at start: the only way to know a // pre-fence file or a worker-* is ours (src/squad-agents.js lateTransform). - const legacyIds = new Set( - readLegacySquad(defaultAgentDir()).files.map((f) => f.replace(/\.md$/, "")), - ); + const legacyAgents = new Map(readLegacySquad(defaultAgentDir()).agents.map((a) => [a.id, a])); /** * The roster as it stands. Without squad.json yet (its import was blocked), * the squad still exists as files: that is the roster an apply diffs @@ -278,9 +281,9 @@ export default { }; await ctx.agent.transform((editor) => { try { - earlyTransform(editor, specsNow() ?? []); + earlyTransform(editor); } catch { - // A broken roster must not take the host's agent list down with it. + // The late transform then finds no probe and adds no global rules. } }); /** What squad_dump and squad_patch say about the squad beyond its roster. */ @@ -291,6 +294,21 @@ export default { `${id}: a hand-authored agent holds this id, so the squad's entry is not registered`, ); } + for (const id of lateReport.kept) { + notes.push( + `${id}: an agent file from an earlier version has this id, but the agent OpenCode ` + + "loaded here is another one (a project's own?), so it is left as is", + ); + } + const store = readStore(storeFile); + if (store.state === "ok") { + for (const c of rosterCollisions(store.roster)) { + notes.push( + `${c.entries.join(" and ")} map to the same agent id ${c.id}, so neither is ` + + "registered; keep one of them", + ); + } + } for (const id of lateReport.stray) { notes.push( `${id}: looks generated but is not in the global agent dir, so it is left as is; ` + @@ -311,28 +329,96 @@ export default { return notes; }; - let lateRegistered = false; - /** @param {boolean} [force] reload even if squad.json looks unchanged */ - const syncSquadAgents = async (force = false) => { - if (!lateRegistered) { - lateRegistered = true; - await ctx.agent.transform((editor) => { - try { - // An unreadable squad.json registers nothing and hides nothing: - // legacy agent files, if any, keep working until it is fixed. - const specs = specsNow(); - if (specs) lateReport = lateTransform(editor, specs, legacyIds); - } catch { - // As above. - } - }); - force = true; + /** @param {any} editor */ + const runLate = (editor) => { + try { + // An unreadable squad.json registers nothing and hides nothing: + // legacy agent files, if any, keep working until it is fixed. + const specs = specsNow(); + if (specs) lateReport = lateTransform(editor, specs, legacyAgents); + else editor.remove(PROBE_ID); + } catch { + // A broken roster must not take the host's agent list down with it. } - const sig = storeSignature(storeFile); - if (!force && sig === storeSig) return; - storeSig = sig; - await ctx.agent.reload(); - agentsPromise = undefined; + }; + /** The late transform's registration; re-registering moves it to the end. */ + let late = /** @type {{dispose?: () => Promise} | null} */ (null); + /** tool name -> the permission action it is checked under (`write` -> `edit`) */ + const toolActions = new Map(); + let toolsRecorded = false; + /** @param {any} editor */ + const recordTools = (editor) => { + if (typeof editor?.list !== "function") return; + toolActions.clear(); + for (const tool of editor.list()) { + if (tool?.name) toolActions.set(tool.name, tool.options?.permission ?? tool.name); + } + }; + /** Live squad agents (ours, not a user's at a squad id) and their roles. */ + const liveSquad = async () => { + const agents = unwrap(await ctx.agent.list().catch(() => null)) ?? []; + return (Array.isArray(agents) ? agents : []).flatMap((a) => { + const role = squadRoleOf(a?.id); + return role && isSquadSystem(a?.system) && !lateReport.foreign.includes(a.id) + ? [{ agent: a, role }] + : []; + }); + }; + let syncing = Promise.resolve(); + /** + * Make sure the late transform is registered after the config plugin's + * and the agents match squad.json. Serialised: hooks of parallel sessions + * call it at once. + * + * @param {{force?: boolean, reposition?: boolean}} [opts] + * force: reload even if squad.json looks unchanged; + * reposition: register the late transform again, at the end + */ + const syncSquadAgents = ({ force = false, reposition = false } = {}) => { + const run = syncing.then(async () => { + if (!late || reposition) { + // Old one out first: two of them would see each other's agents. + await late?.dispose?.(); + late = await ctx.agent.transform(runLate); + force = true; + } + if (!toolsRecorded) { + toolsRecorded = true; + await ctx.tool.transform(recordTools); + } + const sig = storeSignature(storeFile); + if (!force && sig === storeSig) return; + storeSig = sig; + await ctx.agent.reload(); + agentsPromise = undefined; + }); + syncing = run.catch(() => {}); + return run; + }; + /** + * A squad agent's request offers only the tools its rules leave usable. + * The host builds a request's tool catalog before this hook runs, from the + * agent as it was then; if the role's rules were not last (the late + * transform moved behind the config plugin's), it is put back and the + * catalog cut to what the role allows (#87). + * + * @param {{agent?: string, tools?: Record}} event + */ + const enforceRoleTools = async (event) => { + const role = squadRoleOf(event.agent); + if (!role || !event.tools) return; + let live = (await liveSquad()).find((s) => s.agent.id === event.agent); + if (!live) return; + if (!endsWithRoleRules(live.agent, role)) { + await syncSquadAgents({ reposition: true }); + live = (await liveSquad()).find((s) => s.agent.id === event.agent) ?? live; + } + const names = Object.keys(event.tools); + const drop = new Set([ + ...deniedTools(names, live.agent.permissions ?? [], toolActions), + ...deniedTools(names, roleRules(role), toolActions), + ]); + for (const name of drop) delete event.tools[name]; }; // --- skills --- @@ -349,14 +435,31 @@ export default { // --- per-request transforms --- + // Before the host selects the agent for a prompted turn (a subagent's + // child session included): squad agents exist from the late transform + // only, so it must be in place before the first request is built (#87). + await ctx.session.hook("prompt", async () => { + try { + await syncSquadAgents(); + } catch { + // The squad stays as last registered. + } + }); + await ctx.session.hook("context", async (event) => { try { // Before the bootstrap: its inventory lists the squad. Also picks up - // a squad.json another OpenCode process changed. + // a squad.json another OpenCode process changed, and covers a turn + // that resumed without a prompt. await syncSquadAgents(); } catch { // The squad stays as last registered. } + try { + await enforceRoleTools(event); + } catch { + // The host's runtime check still applies the agent's rules. + } try { applySystemPartsTransform(event.system, loadRolePrompt); } catch { @@ -726,7 +829,7 @@ export default { }); if (result.ok) { writeStore(storeFile, roster); - await syncSquadAgents(true); + await syncSquadAgents({ force: true }); } return { content: formatPatchReport(result, { store: storeFile, roster, notes: squadNotes() }), @@ -954,10 +1057,24 @@ export default { stopSilenceWatch(sessionID); }; + // After the host (re)activates plugins: the late transform registered at + // once, so squad agents exist before the first request, and moved back + // to the end if the config plugin's transform was re-registered after it. + const onPluginsUpdated = async () => { + const reposition = + late !== null && (await liveSquad()).some((s) => !endsWithRoleRules(s.agent, s.role)); + await syncSquadAgents({ reposition }); + }; + const events = new AbortController(); - if (guardConfig.enabled) { + if (typeof ctx.event?.subscribe === "function") { void (async () => { for await (const event of ctx.event.subscribe({ signal: events.signal })) { + if (event?.type === "plugin.updated") { + void onPluginsUpdated().catch(() => {}); + continue; + } + if (!guardConfig.enabled) continue; const data = /** @type {Record | undefined} */ (event?.data); const sessionID = data?.sessionID; if (typeof sessionID !== "string") continue; diff --git a/src/squad-agents.js b/src/squad-agents.js index 5f5c06b..5934322 100644 --- a/src/squad-agents.js +++ b/src/squad-agents.js @@ -2,42 +2,79 @@ // from the roster in squad.json (src/squad-store.js), instead of writing // agent files (#85). // -// Two transforms, because of how the host orders them (verified on 2.1.3; -// see #85). Agent transforms run in registration order, and a plugin's +// The ordering the host imposes (verified on 2.1.3; see #85, #87, #88): +// agent transforms run in registration order, and a plugin's transform // registered during setup runs BEFORE the built-in config-agent plugin, which -// then (a) appends the user's global permission rules to every agent that -// exists and (b) applies agent files, whose fields override ours. +// then appends the user's global permission rules to every agent that exists +// and applies agent files and config entries on top. // -// early (registered in setup): creates each agent, so it exists from the -// first turn and the config plugin gives it the user's global rules. -// late (registered on the first request, then reload): runs after the -// config plugin, on every later reload too. It hides legacy -// generated agents that are no longer in the roster, sets every field -// again (so a same-id legacy file cannot leak steps, color or rules -// into ours) and re-appends the role's rules LAST. With the host's -// last-match permission evaluation that gives the order a file agent -// gets: base, global, own. The host then filters the child's tool -// catalog by them: a drill sees read-only tools only. +// early (setup): creates one throwaway probe agent and nothing else. The +// config plugin appends the user's global rules to it, which is the +// only exact way to learn them. No squad id is touched here, so a +// user's agent holding a squad id never sees a squad field (#88). +// late (registered before the first request selects an agent, then +// reload): runs after the config plugin. It reads the global rules +// off the probe and removes it, then builds each squad agent from a +// fresh default: base, global rules, role rules LAST. With the host's +// last-match evaluation the role decides: a drill stays read-only +// under a global allow-all, and the host hides its denied tools. // -// Which agents are ours: one registered from the roster, or one an earlier -// version generated as a file in the global agent dir (marker-verified at -// start). A roster id an agent of anyone else already holds (no squad:prompt -// fence, not a verified legacy file) is left alone and reported: the user's -// agent wins, and squad_patch refuses that id. +// Until the late transform runs, squad agents do not exist: a request for one +// fails as an unknown agent instead of running with the wrong rules (#87). +// +// Which agents are ours: one built from the roster, or one that an earlier +// version generated as a file in the global agent dir, when the live agent at +// that id IS that file (same prompt and model). Any other agent at a squad id +// belongs to the user and is left exactly as the host built it. import { findPromptFence, placeholderBody, wrapPrompt } from "./prompt-inject.js"; import { NOTES_CLOSE, NOTES_OPEN, ROLE_KEYS } from "./roster.js"; import { roleRules, slugForModel, squadRoleOf } from "./workers.js"; +/** The throwaway agent the early transform creates for the late one to read. */ +export const PROBE_ID = "opencode-squad-probe"; +/** Marks where the probe's own rules end and the global ones begin. */ +const PROBE_MARK = Object.freeze({ action: "opencode-squad-probe", resource: "*", effect: "deny" }); + /** + * @typedef {{action: string, resource: string, effect: string}} Rule * @typedef {{id: string, role: "grunt"|"drill", modelId: string, description: string, * system: string, model: {id: string, providerID: string, variant?: string}, - * steps?: number, permissions: Array<{action: string, resource: string, effect: string}>}} AgentSpec + * steps?: number, permissions: Rule[]}} AgentSpec + * @typedef {{system: string, modelId: string}} LegacyAgent + * a generated file from the global agent dir, as the host would load it */ +/** + * Roster entries whose model ids map to the same agent id (`p/m-1` and + * `p/m.1` are both `grunt-p-m-1`). Either one would silently replace the + * other, so neither is registered and squad_patch refuses the roster (#90). + * + * @param {{grunts?: Record, drills?: Record}} roster + * @returns {Array<{id: string, entries: string[]}>} entries as "role model" + */ +export function rosterCollisions(roster) { + /** @type {Map} */ + const byId = new Map(); + for (const [key, role] of Object.entries(ROLE_KEYS)) { + const map = /** @type {Record | undefined} */ ( + /** @type {any} */ (roster)?.[key] + ); + for (const modelId of Object.keys(map ?? {})) { + const id = slugForModel(modelId, role); + byId.set(id, [...(byId.get(id) ?? []), `${role} ${modelId}`]); + } + } + return [...byId] + .filter(([, entries]) => entries.length > 1) + .map(([id, entries]) => ({ id, entries })) + .sort((a, b) => a.id.localeCompare(b.id)); +} + /** * The agents a roster asks for. A disabled entry stays in the roster (its - * settings survive) but is not registered. + * settings survive) but is not registered; nor is an entry whose agent id + * collides with another's (rosterCollisions). * * @param {{grunts?: Record, drills?: Record}} roster * @param {{describe: (role: "grunt"|"drill", modelId: string) => string, @@ -47,6 +84,7 @@ import { roleRules, slugForModel, squadRoleOf } from "./workers.js"; * @returns {AgentSpec[]} */ export function agentSpecs(roster, { describe, prompt }) { + const clashing = new Set(rosterCollisions(roster).map((c) => c.id)); /** @type {AgentSpec[]} */ const specs = []; for (const [key, role] of Object.entries(ROLE_KEYS)) { @@ -55,12 +93,14 @@ export function agentSpecs(roster, { describe, prompt }) { )?.[key]; for (const [modelId, entry] of Object.entries(map ?? {})) { if (entry?.disable) continue; + const id = slugForModel(modelId, role); + if (clashing.has(id)) continue; const slash = modelId.indexOf("/"); const variant = typeof entry?.variant === "string" ? entry.variant.trim() : ""; const notes = typeof entry?.notes === "string" ? entry.notes.trim() : ""; const body = wrapPrompt(role, prompt(role) ?? placeholderBody(role)); specs.push({ - id: slugForModel(modelId, role), + id, role, modelId, description: describe(role, modelId), @@ -78,54 +118,101 @@ export function agentSpecs(roster, { describe, prompt }) { return specs; } +/** Whether an agent's system prompt is one this plugin generated. @param {unknown} system */ +export function isSquadSystem(system) { + return typeof system === "string" && findPromptFence(system) !== null; +} + +/** + * The early transform: the probe, nothing else. A primary agent cannot be + * dispatched by the subagent tool, a hidden one is never selected, and its + * own rules deny everything, so it cannot run in the moment it exists. + * + * @param {{update: (id: string, f: (agent: any) => void) => void}} editor + */ +export function earlyTransform(editor) { + editor.update(PROBE_ID, (agent) => { + agent.mode = "primary"; + agent.hidden = true; + agent.description = "opencode-squad internal probe; removed before any request"; + agent.system = ""; + if (!Array.isArray(agent.permissions)) agent.permissions = []; + agent.permissions.push({ action: "*", resource: "*", effect: "deny" }, { ...PROBE_MARK }); + }); +} + /** - * Set every field the squad owns. Fields a legacy file could carry and the - * roster does not (color, steps) are cleared, not inherited. + * The user's global rules, as the config plugin appended them to the probe. * - * @param {any} agent the host's mutable agent + * @param {any} probe + * @returns {Rule[]} + */ +function globalRules(probe) { + const rules = Array.isArray(probe?.permissions) ? probe.permissions : []; + const mark = rules.findLastIndex( + (/** @type {any} */ r) => + r?.action === PROBE_MARK.action && + r?.resource === PROBE_MARK.resource && + r?.effect === PROBE_MARK.effect, + ); + return mark === -1 ? [] : rules.slice(mark + 1).map((/** @type {Rule} */ r) => ({ ...r })); +} + +/** + * Whether the live agent at an id is exactly the legacy file there: the host + * loads agents from several config dirs, and another one may hold the id + * (#88). Verifying the file proves we own the file, not the id. + * + * @param {any} agent + * @param {LegacyAgent | undefined} file + */ +function isLegacyFile(agent, file) { + if (!file || !agent) return false; + const model = agent.model ? `${agent.model.providerID}/${agent.model.id}` : ""; + const system = String(agent.system ?? "") + .replaceAll("\r\n", "\n") + .trim(); + return system === file.system && model === file.modelId; +} + +/** + * @param {any} agent a fresh default from the host's editor * @param {AgentSpec} spec + * @param {Rule[]} globals */ -function shape(agent, spec) { +function build(agent, spec, globals) { agent.mode = "subagent"; agent.hidden = true; agent.description = spec.description; agent.system = spec.system; agent.model = { ...spec.model }; - delete agent.color; - if (spec.steps === undefined) delete agent.steps; - else agent.steps = spec.steps; + if (spec.steps !== undefined) agent.steps = spec.steps; if (!Array.isArray(agent.permissions)) agent.permissions = []; - agent.permissions.push(...spec.permissions.map((r) => ({ ...r }))); -} - -/** Whether an agent's system prompt is one this plugin generated. @param {unknown} system */ -export function isSquadSystem(system) { - return typeof system === "string" && findPromptFence(system) !== null; -} - -/** - * @param {{update: (id: string, f: (agent: any) => void) => void}} editor - * @param {AgentSpec[]} specs - */ -export function earlyTransform(editor, specs) { - for (const spec of specs) editor.update(spec.id, (agent) => shape(agent, spec)); + agent.permissions.push( + ...globals.map((r) => ({ ...r })), + ...spec.permissions.map((r) => ({ ...r })), + ); } /** * @param {{list: () => readonly any[], get: (id: string) => any, update: (id: string, f: (agent: any) => void) => void, remove: (id: string) => void}} editor * @param {AgentSpec[]} specs - * @param {Set} [legacy] agent ids of the generated files an earlier - * version wrote to the global agent dir, verified by their marker - * (src/squad-apply.js readLegacySquad). Files from before the role-prompt - * fence, and every `worker-*`, are only recognisable this way: the marker is - * a YAML comment the host never exposes. - * @returns {{foreign: string[], hidden: string[], stray: string[]}} - * foreign: roster ids a hand-authored agent already holds (left alone); + * @param {Map} [legacy] the generated files an earlier + * version wrote to the global agent dir, by agent id, verified by their + * marker (src/squad-apply.js readLegacySquad). Files from before the + * role-prompt fence, and every `worker-*`, are only recognisable this way: + * the marker is a YAML comment the host never exposes. + * @returns {{foreign: string[], hidden: string[], stray: string[], kept: string[]}} + * foreign: roster ids another agent already holds (left alone); * hidden: legacy generated agents removed because the roster no longer has them; * stray: generated-looking agents from elsewhere (a project's own agent dir), - * left alone because this plugin did not verify them as its own + * left alone because this plugin did not verify them as its own; + * kept: ids of legacy files the roster dropped, where another agent the + * host loaded holds the id (left alone) */ -export function lateTransform(editor, specs, legacy = new Set()) { +export function lateTransform(editor, specs, legacy = new Map()) { + const globals = globalRules(editor.get(PROBE_ID)); + editor.remove(PROBE_ID); const wanted = new Map(specs.map((s) => [s.id, s])); /** @type {string[]} */ const foreign = []; @@ -133,23 +220,95 @@ export function lateTransform(editor, specs, legacy = new Set()) { const hidden = []; /** @type {string[]} */ const stray = []; + /** @type {string[]} */ + const kept = []; for (const agent of [...editor.list()]) { const id = String(agent?.id ?? ""); if (wanted.has(id)) continue; if (legacy.has(id)) { - editor.remove(id); - hidden.push(id); + if (isLegacyFile(agent, legacy.get(id))) { + editor.remove(id); + hidden.push(id); + } else { + kept.push(id); + } } else if (squadRoleOf(id) !== null && isSquadSystem(agent?.system)) { stray.push(id); } } for (const spec of specs) { const current = editor.get(spec.id); - if (current && !isSquadSystem(current.system) && !legacy.has(spec.id)) { - foreign.push(spec.id); - continue; + if (current) { + if (!isLegacyFile(current, legacy.get(spec.id))) { + foreign.push(spec.id); + continue; + } + // Our own old file: rebuilt from scratch, so none of its fields leak. + editor.remove(spec.id); } - editor.update(spec.id, (agent) => shape(agent, spec)); + editor.update(spec.id, (agent) => build(agent, spec, globals)); } - return { foreign: foreign.sort(), hidden: hidden.sort(), stray: stray.sort() }; + return { + foreign: foreign.sort(), + hidden: hidden.sort(), + stray: stray.sort(), + kept: kept.sort(), + }; +} + +/** + * Whether a live squad agent still ends with its role's rules. Something that + * appends rules after the late transform (the config plugin re-registered + * behind it when the host reloaded plugins) would put the user's global rules + * last again; the plugin then moves its late transform back to the end. + * + * @param {any} agent + * @param {"grunt"|"drill"} role + */ +export function endsWithRoleRules(agent, role) { + const rules = roleRules(role); + const live = Array.isArray(agent?.permissions) ? agent.permissions : []; + if (live.length < rules.length) return false; + const tail = live.slice(-rules.length); + return rules.every( + (r, i) => + tail[i]?.action === r.action && + tail[i]?.resource === r.resource && + tail[i]?.effect === r.effect, + ); +} + +/** + * The host's wildcard match (`*` any run, `?` one char; a trailing ` *` + * also matches the bare command), as OpenCode 2.1.3 evaluates rules. + * + * @param {string} input + * @param {string} pattern + */ +function wildcard(input, pattern) { + let re = pattern + .replaceAll("\\", "/") + .replace(/[.+^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, ".*") + .replace(/\?/g, "."); + if (re.endsWith(" .*")) re = `${re.slice(0, -3)}( .*)?`; + return new RegExp(`^${re}$`, "s").test(input.replaceAll("\\", "/")); +} + +/** + * The tools of one request that the agent's rules leave usable, by the + * host's own test: a tool is gone when the last rule for its permission + * action denies every resource. + * + * @param {string[]} names the request's tool names + * @param {Rule[]} rules the agent's live rules + * @param {Map} [actionOf] tool name -> its permission action + * @returns {string[]} names to drop + */ +export function deniedTools(names, rules, actionOf = new Map()) { + return names.filter((name) => { + const action = actionOf.get(name) ?? name; + const rule = rules.findLast((r) => wildcard(action, r.action)); + return rule?.resource === "*" && rule.effect === "deny"; + }); } diff --git a/src/squad-apply.js b/src/squad-apply.js index 961fee7..63806ea 100644 --- a/src/squad-apply.js +++ b/src/squad-apply.js @@ -10,7 +10,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; - +import { readFrontmatter } from "./frontmatter.js"; import { opencodeConfigDir } from "./paths.js"; import { buildRoster, diffRoster, parseAgentFile } from "./roster.js"; import { isGeneratedAgent } from "./workers.js"; @@ -33,19 +33,25 @@ export function defaultAgentDir() { * would look like a squad the user chose. * * @param {string} dir - * @returns {{roster: Record>, problems: string[], files: string[]}} + * @returns {{roster: Record>, problems: string[], files: string[], + * agents: Array<{id: string, system: string, modelId: string}>}} + * agents: each file as the host would load it (its prompt is the body, + * trimmed), so the plugin can tell whether the live agent at that id is + * this file or another agent the host loaded from elsewhere (#88) */ export function readLegacySquad(dir) { const parsed = []; /** @type {string[]} */ const files = []; + /** @type {Array<{id: string, system: string, modelId: string}>} */ + const agents = []; /** @type {string[]} */ const problems = []; let names = []; try { names = fs.readdirSync(dir).sort(); } catch { - return { roster: buildRoster([]).roster, problems, files }; + return { roster: buildRoster([]).roster, problems, files, agents }; } for (const name of names) { const m = GENERATED_FILE_RE.exec(name); @@ -67,9 +73,14 @@ export function readLegacySquad(dir) { // Legacy `worker-` files predate the grunt/drill split: the executor. parsed.push({ role: m[1] === "worker" ? "grunt" : m[1], modelId, entry }); files.push(name); + agents.push({ + id: name.replace(/\.md$/, ""), + system: readFrontmatter(text).body.replaceAll("\r\n", "\n").trim(), + modelId, + }); } const { roster, conflicts } = buildRoster(parsed); - return { roster, problems: [...problems, ...conflicts], files }; + return { roster, problems: [...problems, ...conflicts], files, agents }; } /** diff --git a/tests-integration/squad-review.test.js b/tests-integration/squad-review.test.js new file mode 100644 index 0000000..bfeebe8 --- /dev/null +++ b/tests-integration/squad-review.test.js @@ -0,0 +1,153 @@ +// Suite: the review findings on #86 (#87, #88) reproduced on the real +// OpenCode 2.1.3 host with TestLLM, each the way the reviewer ran it. +// #87 a drill's very first request, in a session started directly for it, +// offers only the drill's tools and enforces its rules; +// #88 an agent the user wrote keeps its whole effective definition when the +// roster asks for its id, or when a verified legacy file shares its id. +// Run: npm run test:integration (Node >= 24) + +import fs from "node:fs/promises"; +import path from "node:path"; +import { Effect } from "effect"; +import { afterEach, expect, test } from "vitest"; +import { model, TestLLM, withHost } from "./host.js"; + +const configDir = () => path.join(process.env.XDG_CONFIG_HOME ?? "", "opencode"); +const storeFile = () => path.join(configDir(), "squad.json"); +afterEach(async () => { + await fs.rm(storeFile(), { force: true }); + await fs.rm(path.join(configDir(), "agent"), { recursive: true, force: true }); +}); + +/** @param {object} roster */ +async function writeRoster(roster) { + await fs.mkdir(configDir(), { recursive: true }); + await fs.writeFile( + storeFile(), + JSON.stringify({ version: 1, grunts: {}, drills: {}, ...roster }), + ); +} + +const isTitleRequest = (request) => (request.tools ?? []).length === 0; +const toolName = (t) => t.name ?? t.function?.name ?? ""; +const GLOBAL_ALLOW = { permissions: [{ action: "*", resource: "*", effect: "allow" }] }; + +/** One plain turn in a build session, so the host has served a request. */ +const oneTurn = (h) => + Effect.gen(function* () { + const session = yield* h.opencode.sessions.create({ location: h.location, model: model.ref }); + yield* h.opencode.sessions.prompt({ sessionID: session.id, text: "PARENT-ASK" }); + yield* h.opencode.sessions.wait({ sessionID: session.id }).pipe(Effect.timeout("45 seconds")); + }); + +/** The live definition of one agent, or undefined. */ +const liveAgent = (h, id) => + h.opencode.agent + .list({ location: { directory: h.project } }) + .pipe(Effect.map((out) => out.data.find((a) => a.id === id))); + +test("#87: the first request of a session started directly for a drill offers only drill tools", async () => { + await writeRoster({ drills: { "p/m": {} } }); + const requests = []; + const out = await withHost( + (h) => + Effect.gen(function* () { + yield* h.llm.serve((request) => { + if (isTitleRequest(request)) return TestLLM.text("Title", "title"); + const body = JSON.stringify(request.messages ?? request); + requests.push((request.tools ?? []).map(toolName)); + if (!body.includes("c-rm")) return TestLLM.tool("c-rm", "shell", { command: "rm -rf x" }); + return TestLLM.text("done", "answer"); + }); + const session = yield* h.opencode.sessions.create({ + location: h.location, + model: model.ref, + agent: "drill-p-m", + }); + yield* h.opencode.sessions.prompt({ sessionID: session.id, text: "CHILD-DRILL" }); + yield* h.opencode.sessions + .wait({ sessionID: session.id }) + .pipe(Effect.timeout("45 seconds")); + const context = yield* h.opencode.sessions.context({ sessionID: session.id }); + return { context, resolved: h.resolved }; + }), + GLOBAL_ALLOW, + ); + expect(out.resolved.map((s) => s.agent)).toContain("drill-p-m"); + expect(requests.length).toBeGreaterThan(0); + const first = requests[0]; + expect(first).toEqual(expect.arrayContaining(["read", "shell"])); + for (const denied of ["edit", "write", "patch", "execute", "subagent"]) + expect(first).not.toContain(denied); + const rm = out.context + .flatMap((m) => m.content ?? []) + .find((p) => p.type === "tool" && p.id === "c-rm")?.state; + expect(JSON.stringify(rm)).toContain("permission.rejected"); +}, 120_000); + +/** A hand-written agent file: its own prompt, no model, no hidden. */ +const HAND = "---\ndescription: mine\nmode: subagent\n---\nHAND-WRITTEN PROMPT\n"; + +/** The agent's definition as the host builds it with the given roster. */ +async function definitionWith(roster, id, files) { + if (roster) await writeRoster(roster); + else await fs.rm(storeFile(), { force: true }); + return withHost( + (h) => + Effect.gen(function* () { + yield* h.llm.serve((request) => + isTitleRequest(request) ? TestLLM.text("Title", "title") : TestLLM.text("ok", "answer"), + ); + yield* oneTurn(h); + return yield* liveAgent(h, id); + }), + GLOBAL_ALLOW, + { prepare: files }, + ); +} + +test("#88: a hand-authored agent holding a roster id keeps its whole effective definition", async () => { + const files = async (project) => { + await fs.mkdir(path.join(project, "agent"), { recursive: true }); + await fs.writeFile(path.join(project, "agent", "drill-p-foreign.md"), HAND); + }; + const alone = await definitionWith({}, "drill-p-foreign", files); + const claimed = await definitionWith({ drills: { "p/foreign": {} } }, "drill-p-foreign", files); + expect(alone?.system).toContain("HAND-WRITTEN PROMPT"); + expect(claimed).toEqual(alone); +}, 180_000); + +/** An agent file as versions before #85 generated it. */ +const legacy = (role, modelId) => + [ + "---", + "# generated-by: opencode-squad squad-draft", + 'description: "stale description"', + "mode: subagent", + `model: ${modelId}`, + "---", + "", + ``, + "stale body", + "", + "", + ].join("\n"); + +test("#88: a verified legacy file does not hide another agent the host loaded at its id", async () => { + const files = async (project) => { + // Ours, verified by its marker, in the global agent dir... + await fs.mkdir(path.join(configDir(), "agent"), { recursive: true }); + await fs.writeFile(path.join(configDir(), "agent", "drill-old-m.md"), legacy("drill", "old/m")); + // ...while the host loads the user's own agent at the same id. + await fs.mkdir(path.join(project, "agent"), { recursive: true }); + await fs.writeFile(path.join(project, "agent", "drill-old-m.md"), HAND); + }; + const alone = await definitionWith(null, "drill-old-m", async (project) => { + await files(project); + // A store that does not parse: the plugin registers and hides nothing. + await fs.writeFile(storeFile(), "{"); + }); + const live = await definitionWith({}, "drill-old-m", files); + expect(alone?.system).toContain("HAND-WRITTEN PROMPT"); + expect(live).toEqual(alone); +}, 180_000); diff --git a/tests/plugin-entry.test.js b/tests/plugin-entry.test.js index 199f837..d18d8be 100644 --- a/tests/plugin-entry.test.js +++ b/tests/plugin-entry.test.js @@ -67,10 +67,16 @@ vi.mock("../.opencode/lib/runtime.js", async (importOriginal) => { * * @param {{directory: string} & Record} host */ -async function setupHost({ directory, agent, ...over }) { +async function setupHost({ directory, agent, globals = [], ...over }) { const tools = new Map(); /** Agent transforms in registration order, as the host keeps them. */ const transforms = []; + /** @param {(editor: any) => void} run */ + const register = (run) => { + const entry = { run }; + transforms.push(entry); + return { dispose: async () => transforms.splice(transforms.indexOf(entry), 1) }; + }; /** @type {Map unknown>} */ const hooks = new Map(); const dispose = await plugin.setup({ @@ -85,19 +91,33 @@ async function setupHost({ directory, agent, ...over }) { model: { list: async () => [] }, tool: { hook: async () => {}, - transform: async (register) => register({ add: (tool) => tools.set(tool.name, tool) }), + transform: async (callback) => + callback({ + add: (tool) => tools.set(tool.name, tool), + // The host's built-in tools, as a tool transform lists them. + list: () => [ + { name: "read" }, + { name: "shell" }, + { name: "edit", options: { permission: "edit" } }, + { name: "write", options: { permission: "edit" } }, + ], + }), }, agent: { list: async () => registered(), - transform: async (callback) => { - transforms.push(callback); - return { dispose: async () => {} }; - }, + transform: async (callback) => register(callback), reload: async () => {}, ...agent, }, ...over, }); + // The config-agent plugin registers after every package plugin's setup: the + // user's global rules go to every agent that exists by then. + /** @param {any} editor */ + const configRun = (editor) => { + for (const a of editor.list()) a.permissions.push(...globals.map((r) => ({ ...r }))); + }; + let config = register(configRun); /** The agent list the host would build: every transform over a fresh editor. */ function registered() { const map = new Map(); @@ -112,12 +132,20 @@ async function setupHost({ directory, agent, ...over }) { map.set(id, a); }, }; - for (const t of transforms) t(editor); + for (const t of transforms) t.run(editor); return [...map.values()]; } /** The first request: registers the late transform. */ - const firstRequest = () => hooks.get("context")?.({ agent: "build", system: [] }); - return { tools, dispose, registered, firstRequest }; + const firstRequest = async () => { + await hooks.get("prompt")?.({ sessionID: "s" }); + await hooks.get("context")?.({ agent: "build", system: [] }); + }; + /** The host re-activated plugins: the config plugin's transform is re-registered last. */ + const reorderConfig = async () => { + await config.dispose(); + config = register(configRun); + }; + return { tools, dispose, registered, firstRequest, hooks, reorderConfig }; } const dirs = []; @@ -400,6 +428,74 @@ test("squad_patch validates its input with the same schema it advertises", async } }); +const ALLOW_ALL = { action: "*", resource: "*", effect: "allow" }; +const drillTools = () => ({ read: {}, shell: {}, edit: {}, write: {}, execute: {} }); + +test("no squad agent exists before the late transform; the prompt hook puts it in place (#87)", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + const { writeStore } = await import("../src/squad-store.js"); + writeStore(defaultStoreFile(), { grunts: {}, drills: { "a/b": {} } }); + const { registered, hooks, dispose } = await setupHost({ directory, globals: [ALLOW_ALL] }); + try { + // Only the probe: a request for the drill fails as an unknown agent. + expect(registered().map((a) => a.id)).toEqual(["opencode-squad-probe"]); + await hooks.get("prompt")({ sessionID: "s" }); + const drill = registered().find((a) => a.id === "drill-a-b"); + expect(registered().map((a) => a.id)).toEqual(["drill-a-b"]); + expect(drill.permissions).toEqual([ALLOW_ALL, ...roleRules("drill")]); + const event = { agent: "drill-a-b", system: [], tools: drillTools() }; + await hooks.get("context")(event); + expect(Object.keys(event.tools)).toEqual(["read", "shell"]); + } finally { + dispose(); + } +}); + +test("the config plugin re-registered behind the late transform is caught on the next request", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + const { writeStore } = await import("../src/squad-store.js"); + writeStore(defaultStoreFile(), { grunts: {}, drills: { "a/b": {} } }); + const { registered, hooks, reorderConfig, dispose } = await setupHost({ + directory, + globals: [ALLOW_ALL], + }); + const drill = () => registered().find((a) => a.id === "drill-a-b"); + try { + await hooks.get("prompt")({ sessionID: "s" }); + // The host reloaded plugins from one before the config plugin onward. + await reorderConfig(); + expect(drill().permissions.at(-1)).toEqual(ALLOW_ALL); + // The catalog was built from that agent; the hook cuts it to the role's + // tools and moves the late transform back to the end. + const event = { agent: "drill-a-b", system: [], tools: drillTools() }; + await hooks.get("context")(event); + expect(Object.keys(event.tools)).toEqual(["read", "shell"]); + expect(drill().permissions.slice(-roleRules("drill").length)).toEqual(roleRules("drill")); + } finally { + dispose(); + } +}); + +test("a user's agent at a squad id is not policed by the squad's rules", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + const { writeStore } = await import("../src/squad-store.js"); + writeStore(defaultStoreFile(), { grunts: {}, drills: { "a/b": {} } }); + const { hooks, dispose } = await setupHost({ + directory, + agent: { list: async () => [{ id: "drill-a-b", system: "mine", permissions: [ALLOW_ALL] }] }, + }); + try { + const event = { agent: "drill-a-b", system: [], tools: drillTools() }; + await hooks.get("context")(event); + expect(Object.keys(event.tools)).toEqual(Object.keys(drillTools())); + } finally { + dispose(); + } +}); + /** A squad file as versions before #85 wrote it, in the global agent dir. */ function legacyAgent(name, model) { const dir = path.join(process.env.XDG_CONFIG_HOME, "opencode", "agent"); diff --git a/tests/squad-agents.test.js b/tests/squad-agents.test.js index b4a707f..78721b2 100644 --- a/tests/squad-agents.test.js +++ b/tests/squad-agents.test.js @@ -1,12 +1,22 @@ -// Suite: src/squad-agents.js — the agents a roster registers, and the early -// and late agent transforms, against a fake host editor. The real host order -// is covered by tests-integration/squad-agents.test.js. +// Suite: src/squad-agents.js — the agents a roster registers, id collisions, +// the early (probe) and late agent transforms against a fake host editor, and +// the per-request tool check. The real host order is covered by +// tests-integration/squad-agents.test.js and squad-review.test.js. // Run: npx vitest run tests/squad-agents.test.js import { expect, test } from "vitest"; import { PROMPT_CLOSE, promptOpen } from "../src/prompt-inject.js"; import { NOTES_CLOSE, NOTES_OPEN } from "../src/roster.js"; -import { agentSpecs, earlyTransform, isSquadSystem, lateTransform } from "../src/squad-agents.js"; +import { + agentSpecs, + deniedTools, + earlyTransform, + endsWithRoleRules, + isSquadSystem, + lateTransform, + PROBE_ID, + rosterCollisions, +} from "../src/squad-agents.js"; import { roleRules } from "../src/workers.js"; const io = { @@ -61,7 +71,26 @@ test("a disabled entry stays in the roster but registers no agent; blank variant expect(specs[0].model).toEqual({ providerID: "c", id: "d" }); }); -/** A fake host editor over a Map of agents. */ +test("model ids that map to one agent id collide: neither is registered (#90)", () => { + const roster = { + grunts: { "p/m-1": {}, "p/m.1": { variant: "high" }, "q/r": {} }, + drills: { "p/m-1": {} }, + }; + expect(rosterCollisions(roster)).toEqual([ + { id: "grunt-p-m-1", entries: ["grunt p/m-1", "grunt p/m.1"] }, + ]); + expect(agentSpecs(roster, io).map((s) => s.id)).toEqual(["grunt-q-r", "drill-p-m-1"]); + // A disabled entry still holds its id: enabling it later would collide. + expect(rosterCollisions({ grunts: { "p/m-1": {}, "p/m.1": { disable: true } } })).toHaveLength(1); +}); + +const GLOBAL = { action: "*", resource: "*", effect: "allow" }; + +/** + * A fake host editor over a Map of agents. `hostOrder` runs the transforms + * the way the host does: ours early, the config-agent plugin (global rules to + * every agent, then file agents on top), ours late. + */ function editorOf(agents) { const map = new Map(agents.map((a) => [a.id, structuredClone(a)])); return { @@ -70,90 +99,134 @@ function editorOf(agents) { get: (id) => map.get(id), remove: (id) => map.delete(id), update: (id, f) => { - const agent = map.get(id) ?? { - id, - permissions: [{ action: "*", resource: "*", effect: "allow" }], - }; + const agent = map.get(id) ?? { id, permissions: [] }; f(agent); map.set(id, agent); }, }; } -test("early: creates each agent with every squad field and the role rules", () => { - const specs = agentSpecs({ drills: { "a/b": { variant: "max" } } }, io); +/** @param {{files?: any[], specs: any[], legacy?: Map, globals?: any[]}} run */ +function hostOrder({ files = [], specs, legacy, globals = [GLOBAL] }) { const editor = editorOf([]); - earlyTransform(editor, specs); - const agent = editor.get("drill-a-b"); - expect(agent).toMatchObject({ + earlyTransform(editor); + for (const a of editor.list()) a.permissions.push(...globals.map((r) => ({ ...r }))); + for (const file of files) { + editor.update(file.id, (a) => { + Object.assign(a, structuredClone({ ...file, permissions: undefined })); + a.permissions = [...(a.permissions ?? []), ...globals, ...(file.permissions ?? [])]; + }); + } + const report = lateTransform(editor, specs, legacy); + return { editor, report }; +} + +test("early: only the probe, which cannot be dispatched or selected", () => { + const editor = editorOf([]); + earlyTransform(editor); + expect(editor.list().map((a) => a.id)).toEqual([PROBE_ID]); + const probe = editor.get(PROBE_ID); + // The subagent tool refuses a primary agent; a hidden one is never selected. + expect(probe).toMatchObject({ mode: "primary", hidden: true, system: "" }); + expect(probe.permissions[0]).toEqual({ action: "*", resource: "*", effect: "deny" }); +}); + +test("late: built from a fresh default — global rules, then role rules last; probe removed", () => { + const specs = agentSpecs({ drills: { "a/b": { variant: "max" } } }, io); + const { editor } = hostOrder({ specs }); + expect(editor.get(PROBE_ID)).toBeUndefined(); + expect(editor.get("drill-a-b")).toEqual({ + id: "drill-a-b", mode: "subagent", hidden: true, description: "drill on a/b", + system: specs[0].system, model: { providerID: "a", id: "b", variant: "max" }, + permissions: [GLOBAL, ...roleRules("drill")], }); - expect(agent.permissions.slice(1)).toEqual(roleRules("drill")); + expect(endsWithRoleRules(editor.get("drill-a-b"), "drill")).toBe(true); }); -test("late: role rules go last, after whatever the config plugin appended", () => { - const specs = agentSpecs({ drills: { "a/b": {} } }, io); +test("late: without the probe there are no global rules to copy, and nothing breaks", () => { const editor = editorOf([]); - earlyTransform(editor, specs); - // The config-agent plugin appends the user's global rules after ours. - editor.get("drill-a-b").permissions.push({ action: "*", resource: "*", effect: "allow" }); - lateTransform(editor, specs); - expect(editor.get("drill-a-b").permissions.slice(-roleRules("drill").length)).toEqual( - roleRules("drill"), - ); + lateTransform(editor, agentSpecs({ grunts: { "a/b": {} } }, io)); + expect(editor.get("grunt-a-b").permissions).toEqual(roleRules("grunt")); }); -test("late: a same-id legacy generated file is taken over, its own fields cleared", () => { - const specs = agentSpecs({ grunts: { "a/b": {} } }, io); - const legacy = { - id: "grunt-a-b", - system: `${promptOpen("grunt")}\nold\n${PROMPT_CLOSE}`, - description: "old", - color: "#ff0000", - steps: 7, - permissions: [], +/** A legacy generated file as the host loads it, and as readLegacySquad saw it. */ +const legacyFile = (id, modelId, system) => { + const [providerID, ...rest] = modelId.split("/"); + return { + live: { + id, + system, + description: "stale", + color: "#ff0000", + steps: 7, + model: { providerID, id: rest.join("/") }, + permissions: [{ action: "edit", resource: "*", effect: "allow" }], + }, + seen: [id, { id, system, modelId }], }; - const editor = editorOf([legacy]); - const report = lateTransform(editor, specs); - expect(report).toEqual({ foreign: [], hidden: [], stray: [] }); - const agent = editor.get("grunt-a-b"); - expect(agent.system).toContain("the grunt prompt"); - expect(agent.description).toBe("grunt on a/b"); +}; + +test("late: a same-id legacy file is rebuilt from scratch, none of its fields kept", () => { + const specs = agentSpecs({ drills: { "a/b": {} } }, io); + const old = legacyFile("drill-a-b", "a/b", "an old inlined prompt"); + const { editor, report } = hostOrder({ specs, files: [old.live], legacy: new Map([old.seen]) }); + expect(report).toEqual({ foreign: [], hidden: [], stray: [], kept: [] }); + const agent = editor.get("drill-a-b"); expect(agent).not.toHaveProperty("color"); expect(agent).not.toHaveProperty("steps"); + expect(agent.permissions).toEqual([GLOBAL, ...roleRules("drill")]); }); -test("late: a hand-authored agent with a roster id is left alone and reported", () => { - const specs = agentSpecs({ grunts: { "a/b": {} } }, io); - const mine = { id: "grunt-a-b", system: "My own prompt.", description: "mine", permissions: [] }; - const editor = editorOf([mine]); - expect(lateTransform(editor, specs)).toEqual({ foreign: ["grunt-a-b"], hidden: [], stray: [] }); - expect(editor.get("grunt-a-b")).toEqual(mine); +test("late: a hand-authored agent with a roster id is left exactly as the host built it (#88)", () => { + const specs = agentSpecs({ drills: { "p/foreign": {} } }, io); + const mine = { id: "drill-p-foreign", system: "My own prompt.", description: "mine" }; + const alone = hostOrder({ specs: [], files: [mine] }).editor.get("drill-p-foreign"); + const { editor, report } = hostOrder({ specs, files: [mine] }); + expect(report.foreign).toEqual(["drill-p-foreign"]); + expect(editor.get("drill-p-foreign")).toEqual(alone); +}); + +test("late: a verified legacy id held by another agent is neither hidden nor taken over (#88)", () => { + const old = legacyFile("drill-old-m", "old/m", "stale body"); + const mine = { id: "drill-old-m", system: "My own prompt.", model: old.live.model }; + const dropped = hostOrder({ specs: [], files: [mine], legacy: new Map([old.seen]) }); + expect(dropped.report.kept).toEqual(["drill-old-m"]); + expect(dropped.editor.get("drill-old-m").system).toBe("My own prompt."); + const claimed = hostOrder({ + specs: agentSpecs({ drills: { "old/m": {} } }, io), + files: [mine], + legacy: new Map([old.seen]), + }); + expect(claimed.report.foreign).toEqual(["drill-old-m"]); + expect(claimed.editor.get("drill-old-m").system).toBe("My own prompt."); }); test("late: verified legacy agents the roster dropped are hidden, worker- included; nothing else is", () => { const fenced = `${promptOpen("drill")}\nx\n${PROMPT_CLOSE}`; - const editor = editorOf([ - { id: "drill-old-model", system: fenced, permissions: [] }, - // Generated before the fence existed: only the marker-verified set knows it. - { id: "worker-old-model", system: "an old inlined prompt", permissions: [] }, - { id: "drill-hand-written", system: "mine", permissions: [] }, - // Fenced, but from a project's own agent dir: not verified as ours. - { id: "drill-project-model", system: fenced, permissions: [] }, - { id: "build", system: fenced, permissions: [] }, - ]); - const report = lateTransform( - editor, - agentSpecs({ grunts: { "a/b": {} } }, io), - new Set(["drill-old-model", "worker-old-model"]), - ); + const drill = legacyFile("drill-old-model", "o/d", fenced); + // Generated before the fence existed: only the marker-verified set knows it. + const worker = legacyFile("worker-old-model", "o/w", "an old inlined prompt"); + const { editor, report } = hostOrder({ + specs: agentSpecs({ grunts: { "a/b": {} } }, io), + files: [ + drill.live, + worker.live, + { id: "drill-hand-written", system: "mine" }, + // Fenced, but from a project's own agent dir: not verified as ours. + { id: "drill-project-model", system: fenced }, + { id: "build", system: fenced }, + ], + legacy: new Map([drill.seen, worker.seen]), + }); expect(report).toEqual({ foreign: [], hidden: ["drill-old-model", "worker-old-model"], stray: ["drill-project-model"], + kept: [], }); expect([...editor.map.keys()].sort()).toEqual([ "build", @@ -163,15 +236,38 @@ test("late: verified legacy agents the roster dropped are hidden, worker- includ ]); }); -test("late: a pre-fence legacy file with a roster id is taken over, not foreign", () => { - const editor = editorOf([ - { id: "grunt-a-b", system: "old inlined grunt prompt", permissions: [] }, +test("a legacy file matches the live agent across CRLF and surrounding blank lines", () => { + const old = legacyFile("grunt-a-b", "a/b", "line one\nline two"); + const { report } = hostOrder({ + specs: agentSpecs({ grunts: { "a/b": {} } }, io), + files: [{ ...old.live, system: "\nline one\r\nline two\n" }], + legacy: new Map([old.seen]), + }); + expect(report.foreign).toEqual([]); +}); + +test("endsWithRoleRules: global rules appended after the role's are caught", () => { + const agent = { permissions: [...roleRules("drill")] }; + expect(endsWithRoleRules(agent, "drill")).toBe(true); + agent.permissions.push(GLOBAL); + expect(endsWithRoleRules(agent, "drill")).toBe(false); + expect(endsWithRoleRules({}, "grunt")).toBe(false); +}); + +test("deniedTools: the host's whole-tool test, under the tool's permission action", () => { + const names = ["read", "shell", "edit", "write", "execute", "webfetch"]; + const actions = new Map([["write", "edit"]]); + expect(deniedTools(names, [GLOBAL, ...roleRules("drill")], actions)).toEqual([ + "edit", + "write", + "execute", ]); - const report = lateTransform( - editor, - agentSpecs({ grunts: { "a/b": {} } }, io), - new Set(["grunt-a-b"]), + // A pattern on the resource is not a whole-tool deny: shell stays for git. + expect(deniedTools(["shell"], [{ action: "shell", resource: "rm *", effect: "deny" }])).toEqual( + [], ); - expect(report.foreign).toEqual([]); - expect(editor.get("grunt-a-b").system).toContain("the grunt prompt"); + expect(deniedTools(["question"], [{ action: "q*", resource: "*", effect: "deny" }])).toEqual([ + "question", + ]); + expect(deniedTools(names, [GLOBAL, ...roleRules("grunt")], actions)).toEqual([]); }); diff --git a/tests/squad-apply.test.js b/tests/squad-apply.test.js index e43c830..d5d35ac 100644 --- a/tests/squad-apply.test.js +++ b/tests/squad-apply.test.js @@ -116,6 +116,15 @@ test("readLegacySquad imports generated files only, worker- as a grunt", () => { }); expect(out.files).toEqual(["drill-a-one.md", "grunt-a-one.md", "worker-a-two.md"]); expect(out.problems).toEqual([]); + // Each as the host would load it: the body is the prompt, the model without + // its variant, for telling this file from another agent at the id (#88). + expect(out.agents.map((a) => [a.id, a.modelId])).toEqual([ + ["drill-a-one", "a/one"], + ["grunt-a-one", "a/one"], + ["worker-a-two", "a/two"], + ]); + const body = fs.readFileSync(path.join(dir, "grunt-a-one.md"), "utf8").split(/^---$/m)[2].trim(); + expect(out.agents[1].system).toBe(body); }); test("readLegacySquad reads CRLF files and keeps notes", () => { @@ -153,5 +162,6 @@ test("a missing agent dir is an empty legacy squad", () => { roster: { grunts: {}, drills: {} }, problems: [], files: [], + agents: [], }); }); From 76b1347f301437c59d43179ca3250bca0d994cd8 Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:33:01 +0300 Subject: [PATCH 06/17] squad: refuse model ids that map to one agent id (#90) `p/m-1` and `p/m.1` both become `grunt-p-m-1`. squad_patch now refuses such a roster before writing; a stored roster registers neither entry and squad_dump names both; the legacy import refuses files that would collide. The file writer had this check (#52) and #86 dropped it with the writer. Co-Authored-By: Claude Opus 5.5 --- .opencode/lib/runtime.js | 10 ++++++++++ .opencode/lib/squad.js | 13 ++++++++++++ tests/plugin-entry.test.js | 34 ++++++++++++++++++++++++++++++++ tests/runtime-model-data.test.js | 10 ++++++++++ 4 files changed, 67 insertions(+) diff --git a/.opencode/lib/runtime.js b/.opencode/lib/runtime.js index 704a89e..d866a22 100644 --- a/.opencode/lib/runtime.js +++ b/.opencode/lib/runtime.js @@ -10,6 +10,7 @@ import { metricsDir, readMetrics, refreshMetrics } from "../../src/metrics-cache import { buildModelData, modelsChanged, readModelDataFile } from "../../src/model-data.js"; import { opencodeConfigDir, opencodeDataDir } from "../../src/paths.js"; import { createPromptLoader } from "../../src/prompt-inject.js"; +import { rosterCollisions } from "../../src/squad-agents.js"; import { defaultAgentDir, readLegacySquad } from "../../src/squad-apply.js"; import { defaultStoreFile, readStore, writeStore } from "../../src/squad-store.js"; import { describeAgent } from "../../src/workers.js"; @@ -230,6 +231,15 @@ export function importLegacySquad() { } return { imported: 0, problems: legacy.problems }; } + // Two files whose models map to one agent id: importing both would + // register only one of them (#90). + const clashes = rosterCollisions(legacy.roster).map( + (c) => `${c.entries.join(" and ")} map to the same agent id ${c.id}; delete one of the files`, + ); + if (clashes.length) { + for (const p of clashes) console.warn(`[opencode-squad] legacy squad not imported — ${p}`); + return { imported: 0, problems: clashes }; + } const count = Object.keys(legacy.roster.grunts).length + Object.keys(legacy.roster.drills).length; if (count === 0) return { imported: 0, problems: [] }; diff --git a/.opencode/lib/squad.js b/.opencode/lib/squad.js index 2ac134d..8d97d4c 100644 --- a/.opencode/lib/squad.js +++ b/.opencode/lib/squad.js @@ -769,6 +769,19 @@ export default { } const valid = /** @type {SquadPatchInput} */ (raw); const roster = { grunts: valid.grunts ?? {}, drills: valid.drills ?? {} }; + // Two model ids with one agent id would leave one entry unregistered + // while the report counts both (#90). + const collisions = rosterCollisions(roster); + if (collisions.length) { + return { + content: `Roster is invalid:\n${collisions + .map( + (c) => + ` - ${c.entries.join(" and ")} map to the same agent id ${c.id}; keep one of them`, + ) + .join("\n")}`, + }; + } const variantErrors = validateVariants(roster, await getVariantMap()); if (variantErrors.length) { return { diff --git a/tests/plugin-entry.test.js b/tests/plugin-entry.test.js index d18d8be..7e73f74 100644 --- a/tests/plugin-entry.test.js +++ b/tests/plugin-entry.test.js @@ -428,6 +428,40 @@ test("squad_patch validates its input with the same schema it advertises", async } }); +test("squad_patch refuses model ids that would register one agent (#90)", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + const { tools, dispose } = await setupHost({ directory }); + try { + const out = ( + await tools + .get("squad_patch") + .execute({ grunts: { "p/m-1": {}, "p/m.1": {} } }, { agent: "build" }) + ).content; + expect(out).toContain("Roster is invalid"); + expect(out).toContain("grunt p/m-1 and grunt p/m.1 map to the same agent id grunt-p-m-1"); + expect(readStore(defaultStoreFile()).state).toBe("missing"); + } finally { + dispose(); + } +}); + +test("a stored roster with colliding ids registers neither and says so in the dump (#90)", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + const { writeStore } = await import("../src/squad-store.js"); + writeStore(defaultStoreFile(), { grunts: { "p/m-1": {}, "p/m.1": {}, "q/r": {} }, drills: {} }); + const { tools, registered, firstRequest, dispose } = await setupHost({ directory }); + try { + await firstRequest(); + expect(registered().map((a) => a.id)).toEqual(["grunt-q-r"]); + const dump = (await tools.get("squad_dump").execute({}, { agent: "build" })).content; + expect(dump).toContain("grunt p/m-1 and grunt p/m.1 map to the same agent id grunt-p-m-1"); + } finally { + dispose(); + } +}); + const ALLOW_ALL = { action: "*", resource: "*", effect: "allow" }; const drillTools = () => ({ read: {}, shell: {}, edit: {}, write: {}, execute: {} }); diff --git a/tests/runtime-model-data.test.js b/tests/runtime-model-data.test.js index bc38fe2..a966f73 100644 --- a/tests/runtime-model-data.test.js +++ b/tests/runtime-model-data.test.js @@ -136,6 +136,16 @@ test("a damaged legacy file blocks the import rather than dropping that agent", expect(fs.existsSync(storeFile)).toBe(false); }); +test("legacy files whose models map to one agent id block the import (#90)", () => { + const agentDir = path.join(configDir, "agent"); + fs.writeFileSync(path.join(agentDir, "grunt-p-m-1.md"), legacyFile("p/m-1")); + fs.writeFileSync(path.join(agentDir, "grunt-p-m-1-copy.md"), legacyFile("p/m.1")); + const r = importLegacySquad(); + expect(r.imported).toBe(0); + expect(r.problems).toEqual([expect.stringContaining("grunt-p-m-1")]); + expect(fs.existsSync(storeFile)).toBe(false); +}); + test("no legacy squad, no import: squad.json is not created empty", () => { expect(importLegacySquad()).toEqual({ imported: 0, problems: [] }); expect(fs.existsSync(storeFile)).toBe(false); From a44e65d9d4f36e266a79b3b42b696a6d823a162d Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:38:44 +0300 Subject: [PATCH 07/17] squad: a patch must name the revision it was built on (#89) squad_dump prints a `revision` (a hash of squad.json's bytes, read in the same read as the roster) and squad_patch requires it back. A patch whose base is no longer current is refused, so two edits of one dump cannot silently undo each other and the deletion guard always compares against the roster actually replaced. The handler finishes every await (variants, the host's agent list) before it reads the roster; read, check, plan and write then run synchronously under an exclusive squad.json.lock, which keeps other OpenCode processes sharing the config dir out. A held lock is refused with "retry", one older than 30 s is taken over. The legacy import takes the same lock. Co-Authored-By: Claude Opus 5.5 --- .opencode/lib/runtime.js | 50 +++++----- .opencode/lib/squad.js | 130 +++++++++++++++++-------- src/roster-schema.js | 1 + src/squad-store.js | 81 ++++++++++++++- src/squad-tools.js | 8 +- tests-integration/squad-agents.test.js | 7 +- tests/guard-host.test.js | 4 +- tests/plugin-entry.test.js | 130 ++++++++++++++++++++++--- tests/runtime-model-data.test.js | 2 +- tests/squad-store.test.js | 42 +++++++- tests/squad-tools.test.js | 3 + 11 files changed, 368 insertions(+), 90 deletions(-) diff --git a/.opencode/lib/runtime.js b/.opencode/lib/runtime.js index d866a22..2acbda7 100644 --- a/.opencode/lib/runtime.js +++ b/.opencode/lib/runtime.js @@ -12,7 +12,7 @@ import { opencodeConfigDir, opencodeDataDir } from "../../src/paths.js"; import { createPromptLoader } from "../../src/prompt-inject.js"; import { rosterCollisions } from "../../src/squad-agents.js"; import { defaultAgentDir, readLegacySquad } from "../../src/squad-apply.js"; -import { defaultStoreFile, readStore, writeStore } from "../../src/squad-store.js"; +import { defaultStoreFile, readStore, withStoreLock, writeStore } from "../../src/squad-store.js"; import { describeAgent } from "../../src/workers.js"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -223,28 +223,34 @@ export function ensureGlobalModelDataFresh() { export function importLegacySquad() { const store = defaultStoreFile(); try { - if (readStore(store).state !== "missing") return { imported: 0, problems: [] }; - const legacy = readLegacySquad(defaultAgentDir()); - if (legacy.problems.length) { - for (const p of legacy.problems) { - console.warn(`[opencode-squad] legacy squad not imported — ${p}`); + // Under the roster's lock: another process may be importing or patching. + const locked = withStoreLock(store, () => { + if (readStore(store).state !== "missing") return { imported: 0, problems: [] }; + const legacy = readLegacySquad(defaultAgentDir()); + if (legacy.problems.length) { + for (const p of legacy.problems) { + console.warn(`[opencode-squad] legacy squad not imported — ${p}`); + } + return { imported: 0, problems: legacy.problems }; } - return { imported: 0, problems: legacy.problems }; - } - // Two files whose models map to one agent id: importing both would - // register only one of them (#90). - const clashes = rosterCollisions(legacy.roster).map( - (c) => `${c.entries.join(" and ")} map to the same agent id ${c.id}; delete one of the files`, - ); - if (clashes.length) { - for (const p of clashes) console.warn(`[opencode-squad] legacy squad not imported — ${p}`); - return { imported: 0, problems: clashes }; - } - const count = - Object.keys(legacy.roster.grunts).length + Object.keys(legacy.roster.drills).length; - if (count === 0) return { imported: 0, problems: [] }; - writeStore(store, legacy.roster); - return { imported: count, problems: [] }; + // Two files whose models map to one agent id: importing both would + // register only one of them (#90). + const clashes = rosterCollisions(legacy.roster).map( + (c) => + `${c.entries.join(" and ")} map to the same agent id ${c.id}; delete one of the files`, + ); + if (clashes.length) { + for (const p of clashes) console.warn(`[opencode-squad] legacy squad not imported — ${p}`); + return { imported: 0, problems: clashes }; + } + const count = + Object.keys(legacy.roster.grunts).length + Object.keys(legacy.roster.drills).length; + if (count === 0) return { imported: 0, problems: [] }; + writeStore(store, legacy.roster); + return { imported: count, problems: [] }; + }); + // Busy: the process holding the lock imports, or the next start does. + return locked.busy ? { imported: 0, problems: [] } : locked.value; } catch (e) { const err = /** @type {NodeJS.ErrnoException} */ (e); const problem = `${store}: ${err?.code ?? err?.name ?? "error"}`; diff --git a/.opencode/lib/squad.js b/.opencode/lib/squad.js index 8d97d4c..6204903 100644 --- a/.opencode/lib/squad.js +++ b/.opencode/lib/squad.js @@ -74,7 +74,14 @@ import { planPatch, readLegacySquad, } from "../../src/squad-apply.js"; -import { defaultStoreFile, readStore, storeSignature, writeStore } from "../../src/squad-store.js"; +import { + defaultStoreFile, + NO_STORE_REVISION, + readStore, + storeSignature, + withStoreLock, + writeStore, +} from "../../src/squad-store.js"; import { formatVariantLines, isSubagentCaller, @@ -248,11 +255,14 @@ export default { * the squad still exists as files: that is the roster an apply diffs * against, so rebuilding from an empty dump cannot delete it unguarded. * - * @returns {{state: "ok", roster: any} | {state: "invalid", problems: string[]}} + * @returns {{state: "ok", roster: any, revision: string} | {state: "invalid", problems: string[]}} + * revision: of the bytes the roster was read from; NO_STORE_REVISION + * while there is no squad.json */ const currentSquad = () => { const store = readStore(storeFile); - if (store.state === "ok") return { state: "ok", roster: store.roster }; + if (store.state === "ok") + return { state: "ok", roster: store.roster, revision: store.revision }; if (store.state === "invalid") { return { state: "invalid", problems: [`${storeFile}: ${store.reason}`] }; } @@ -263,7 +273,7 @@ export default { problems: legacy.problems.map((p) => path.join(defaultAgentDir(), p)), }; } - return { state: "ok", roster: legacy.roster }; + return { state: "ok", roster: legacy.roster, revision: NO_STORE_REVISION }; }; const specsNow = () => { const store = readStore(storeFile); @@ -625,15 +635,18 @@ export default { }; } const roster = squad.roster; + const { revision } = squad; const count = Object.keys(roster.grunts).length + Object.keys(roster.drills).length; const notes = squadNotes(); const note = notes.length ? `\n\nnotes:\n${notes.map((c) => ` ${c}`).join("\n")}` : ""; const variantLines = formatVariantLines(await getVariantMap(), roster); return { content: - `Squad roster: ${storeFile}\n${JSON.stringify(roster, null, 2)}${note}${variantLines}\n\n` + + `Squad roster: ${storeFile}\n${JSON.stringify({ revision, ...roster }, null, 2)}` + + `${note}${variantLines}\n\n` + "To change the squad, pass this same document back to squad_patch with your " + - "edits applied — keeping every agent you were not asked to touch.", + "edits applied — its revision included, and every agent you were not asked to " + + "touch kept.", metadata: { title: `squad: ${count} agent(s)`, store: storeFile, agents: count }, }; }, @@ -763,6 +776,16 @@ export default { ". Nothing was written.", }; } + // Without the base it was built on, a patch cannot tell an edit from + // a revert of someone else's change (#89). + if (typeof raw.revision !== "string") { + return { + content: + "Refused: pass the `revision` from squad_dump along with the roster you edited " + + "from it. Nothing was written. Call squad_dump, apply your edit to what it " + + "prints, and send that document back whole.", + }; + } const errors = validatePatchInput(raw); if (errors.length) { return { content: `Roster is invalid:\n${errors.map((e) => ` - ${e}`).join("\n")}` }; @@ -799,51 +822,72 @@ export default { `written. Ask the user to fix:\n${problems.map((p) => ` - ${p}`).join("\n")}`, }; } - // Re-read right before writing: another OpenCode process may have - // changed the roster since this one last looked. - const squad = currentSquad(); - if (squad.state === "invalid") { - return { - content: - "Refused: the current squad cannot be read, and writing a roster now could " + - "lose it. Nothing was written. Ask the user to fix:\n" + - squad.problems.map((p) => ` - ${p}`).join("\n"), - }; - } - const current = squad.roster; - // A hand-authored agent already holding an id this roster wants. + // Every await happens above this line. From here to the write the + // handler is synchronous, so no other patch of this process runs in + // between, and the lock keeps other OpenCode processes out (#89). const agents = unwrap(await ctx.agent.list().catch(() => null)) ?? []; const byId = new Map( (Array.isArray(agents) ? agents : []).map((a) => [String(a?.id ?? ""), a]), ); - const foreign = []; - for (const [key, role] of /** @type {const} */ ([ - ["grunts", "grunt"], - ["drills", "drill"], - ])) { - for (const [modelId, entry] of Object.entries(roster[key])) { - // An entry kept as it was is not a new claim on the id: a user - // agent that took it over later is reported, not a reason to - // refuse every future patch. - const before = current[key]?.[modelId]; - if (before && JSON.stringify(before) === JSON.stringify(entry)) continue; - const id = slugForModel(modelId, role); - const agent = byId.get(id); - if (agent && !isSquadSystem(agent.system)) { - foreign.push({ id, agent: `${role} ${modelId}` }); + const locked = withStoreLock(storeFile, () => { + const squad = currentSquad(); + if (squad.state === "invalid") { + return { + refused: + "Refused: the current squad cannot be read, and writing a roster now could " + + "lose it. Nothing was written. Ask the user to fix:\n" + + squad.problems.map((p) => ` - ${p}`).join("\n"), + }; + } + const now = squad.revision; + if (now !== valid.revision) { + return { + refused: + "REFUSED: squad.json changed since that squad_dump (revision " + + `${valid.revision}, now ${now}): another session or OpenCode process ` + + "patched it. Nothing was written. Call squad_dump again, apply your edit to " + + "what it prints now, and patch with its revision.", + }; + } + const current = squad.roster; + // A hand-authored agent already holding an id this roster wants. + const foreign = []; + for (const [key, role] of /** @type {const} */ ([ + ["grunts", "grunt"], + ["drills", "drill"], + ])) { + for (const [modelId, entry] of Object.entries(roster[key])) { + // An entry kept as it was is not a new claim on the id: a user + // agent that took it over later is reported, not a reason to + // refuse every future patch. + const before = current[key]?.[modelId]; + if (before && JSON.stringify(before) === JSON.stringify(entry)) continue; + const id = slugForModel(modelId, role); + const agent = byId.get(id); + if (agent && !isSquadSystem(agent.system)) { + foreign.push({ id, agent: `${role} ${modelId}` }); + } } } - } - const result = planPatch({ - current, - next: roster, - allowRemove: allowRemove === true, - foreign, + const result = planPatch({ + current, + next: roster, + allowRemove: allowRemove === true, + foreign, + }); + if (result.ok) writeStore(storeFile, roster); + return { result }; }); - if (result.ok) { - writeStore(storeFile, roster); - await syncSquadAgents({ force: true }); + if (locked.busy) { + return { + content: + "Refused: another OpenCode process is writing squad.json right now. Nothing " + + "was written. Call squad_dump again and retry with its revision.", + }; } + if ("refused" in locked.value) return { content: locked.value.refused }; + const { result } = locked.value; + if (result.ok) await syncSquadAgents({ force: true }); return { content: formatPatchReport(result, { store: storeFile, roster, notes: squadNotes() }), metadata: { ok: result.ok, ...result.diff }, diff --git a/src/roster-schema.js b/src/roster-schema.js index ecba193..78dcdd6 100644 --- a/src/roster-schema.js +++ b/src/roster-schema.js @@ -55,6 +55,7 @@ const RosterSchema = z.strictObject({ /** squad_patch's whole input: the roster plus the call's own switches. */ const SquadPatchInputSchema = RosterSchema.extend({ + revision: z.string().describe(ARG_DESCRIPTIONS["patch.revision"]), allow_remove: z.boolean().describe(ARG_DESCRIPTIONS["patch.allow_remove"]).optional(), }); diff --git a/src/squad-store.js b/src/squad-store.js index 91508da..2beb142 100644 --- a/src/squad-store.js +++ b/src/squad-store.js @@ -8,6 +8,7 @@ // it may hold the user's squad, and a fresh one written over it would lose // that squad for good. Callers report it and refuse to change the roster. +import crypto from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -25,7 +26,8 @@ export function defaultStoreFile() { /** * @typedef {{grunts: Record>, drills: Record>}} Roster - * @typedef {{state: "missing"} | {state: "ok", roster: Roster} | {state: "invalid", reason: string}} StoreRead + * @typedef {{state: "missing"} | {state: "ok", roster: Roster, revision: string} | {state: "invalid", reason: string}} StoreRead + * revision: of the bytes this roster was read from (storeRevision) */ /** @@ -33,14 +35,15 @@ export function defaultStoreFile() { * @returns {StoreRead} */ export function readStore(file) { - let text; + let bytes; try { - text = fs.readFileSync(file, "utf8"); + bytes = fs.readFileSync(file); } catch (e) { const code = /** @type {NodeJS.ErrnoException} */ (e)?.code; if (code === "ENOENT") return { state: "missing" }; return { state: "invalid", reason: `cannot read (${code ?? "error"})` }; } + const text = bytes.toString("utf8"); let doc; try { doc = JSON.parse(text); @@ -56,7 +59,7 @@ export function readStore(file) { } const errors = validateRoster(roster); if (errors.length) return { state: "invalid", reason: errors.join("; ") }; - return { state: "ok", roster: normalize(roster) }; + return { state: "ok", roster: normalize(roster), revision: revisionOf(bytes) }; } /** @@ -72,6 +75,76 @@ export function writeStore(file, roster) { writeFileAtomic(file, `${JSON.stringify({ version: STORE_VERSION, ...r }, null, 2)}\n`); } +/** The revision of a roster that has no squad.json yet. */ +export const NO_STORE_REVISION = "none"; + +/** + * The file's content revision: squad_dump prints it and squad_patch must + * pass it back, so a patch built on a roster that changed since is refused + * instead of silently reverting that change (#89). A hash of the bytes, not + * mtime and size: an edit within one timestamp tick or of equal length still + * counts. + * + * @param {string} file + * @returns {string | null} null when the file exists but cannot be read + */ +export function storeRevision(file) { + try { + return revisionOf(fs.readFileSync(file)); + } catch (e) { + return /** @type {NodeJS.ErrnoException} */ (e)?.code === "ENOENT" ? NO_STORE_REVISION : null; + } +} + +/** @param {Buffer} bytes */ +function revisionOf(bytes) { + return crypto.createHash("sha256").update(bytes).digest("hex").slice(0, 16); +} + +/** A lock older than this was left by a process that died holding it. */ +const LOCK_STALE_MS = 30_000; + +/** + * Run `fn` holding `.lock`, created exclusively: another OpenCode + * process sharing the config dir (the desktop service and a CLI do) cannot + * read-check-write the roster at the same time. `fn` must be synchronous; + * with no await inside, no other patch of this process interleaves either. + * Busy is reported, not waited out: the caller retries with a fresh dump. + * + * @template T + * @param {string} file + * @param {() => T} fn + * @returns {{busy: true} | {busy: false, value: T}} + */ +export function withStoreLock(file, fn) { + const lock = `${file}.lock`; + fs.mkdirSync(path.dirname(file), { recursive: true }); + let fd; + for (let attempt = 0; attempt < 2 && fd === undefined; attempt++) { + try { + fd = fs.openSync(lock, "wx"); + } catch (e) { + if (/** @type {NodeJS.ErrnoException} */ (e)?.code !== "EEXIST") throw e; + let age = 0; + try { + age = Date.now() - fs.statSync(lock).mtimeMs; + } catch { + // Released meanwhile: try again. + } + if (age <= LOCK_STALE_MS) return { busy: true }; + fs.rmSync(lock, { force: true }); + } + } + if (fd === undefined) return { busy: true }; + try { + fs.writeSync(fd, String(process.pid)); + return { busy: false, value: fn() }; + } finally { + fs.closeSync(fd); + fs.rmSync(lock, { force: true }); + } +} + /** * The file's change signature: other OpenCode processes write it too (the * desktop service and a CLI share one config dir). diff --git a/src/squad-tools.js b/src/squad-tools.js index bc0b888..c7229ab 100644 --- a/src/squad-tools.js +++ b/src/squad-tools.js @@ -28,7 +28,7 @@ export const TOOL_DESCRIPTIONS = { "Read the current squad roster: every squad agent, grouped as `grunts` and " + "`drills` and keyed by model id, with its per-agent settings. ALWAYS call this " + "before squad_patch — the roster is a document you edit, not one you retype. " + - "Returns JSON.", + "Returns JSON with a `revision`; pass the edited document back WITH it.", squad_metrics: "Benchmark scores, list prices, context windows and billing for the models you " + "name — pass the `model:` of every grunt/drill in your inventory. Call it ONCE " + @@ -40,7 +40,7 @@ export const TOOL_DESCRIPTIONS = { squad_patch: "Write the squad roster: one agent per entry under `grunts` / `drills`, keyed by " + "model id. This is the COMPLETE intended squad, not a delta — an agent absent from " + - "it is DELETED, so start from squad_dump and edit that. Deleting an agent the user " + + "it is DELETED, so start from squad_dump and edit that, keeping its `revision`. Deleting an agent the user " + "did not ask you to delete is refused, not performed. Agent descriptions are not " + "yours to write: the plugin builds them from model_data.json (the owner's `info` " + "per model and the provider's plan) whenever it registers the agents. The change " + @@ -80,6 +80,10 @@ export const ARG_DESCRIPTIONS = { "rubber-stamps the work or invents faults, and both are worse than no review " + "because they launder a bad change as an approved one. Cheap and small " + "models belong in `grunts` alone.", + "patch.revision": + "The `revision` squad_dump printed with the roster you edited. Required: if the " + + "roster changed since (another session or process patched it), the patch is " + + "refused and nothing is written, instead of silently undoing that change.", "patch.allow_remove": "Permit deleting agents present in the current squad but absent from this " + "roster. Pass true ONLY when the user asked for that deletion — never to " + diff --git a/tests-integration/squad-agents.test.js b/tests-integration/squad-agents.test.js index d8bd773..2e0270c 100644 --- a/tests-integration/squad-agents.test.js +++ b/tests-integration/squad-agents.test.js @@ -9,6 +9,7 @@ import path from "node:path"; import { Effect } from "effect"; import { afterEach, expect, test } from "vitest"; import { promptOpen } from "../src/prompt-inject.js"; +import { storeRevision } from "../src/squad-store.js"; import { model, TestLLM, withHost } from "./host.js"; const storeFile = () => path.join(process.env.XDG_CONFIG_HOME ?? "", "opencode", "squad.json"); @@ -69,6 +70,7 @@ const GLOBAL_ALLOW = { permissions: [{ action: "*", resource: "*", effect: "allo test("the squad is registered from squad.json: dispatch, drill policy, legacy agents, live patch", async () => { await writeRoster({ grunts: { "p/m": { variant: "high" } }, drills: { "p/m": {} } }); + const revision = storeRevision(storeFile()); const children = {}; const out = await withHost( (h) => @@ -114,7 +116,7 @@ test("the squad is registered from squad.json: dispatch, drill policy, legacy ag if (turn === 5) return code( "p-patch", - 'return await tools.squad_patch({grunts: {"p/m": {variant: "high"}, "p/n": {}}, drills: {"p/m": {}}})', + `return await tools.squad_patch({revision: "${revision}", grunts: {"p/m": {variant: "high"}, "p/n": {}}, drills: {"p/m": {}}})`, ); if (turn === 6) return callTool("p-new", "subagent", { @@ -196,6 +198,7 @@ test("the squad is registered from squad.json: dispatch, drill policy, legacy ag test("a hand-authored agent holding a roster id keeps its own prompt, and squad_patch refuses that id", async () => { await writeRoster({ grunts: { "p/q": {} }, drills: {} }); + const revision = storeRevision(storeFile()); const children = {}; const out = await withHost( (h) => @@ -219,7 +222,7 @@ test("a hand-authored agent holding a roster id keeps its own prompt, and squad_ if (turn === 3) return code( "p-patch", - 'return await tools.squad_patch({grunts: {"p/q": {variant: "high"}}})', + `return await tools.squad_patch({revision: "${revision}", grunts: {"p/q": {variant: "high"}}})`, ); return TestLLM.text("parent done", "answer"); }); diff --git a/tests/guard-host.test.js b/tests/guard-host.test.js index 7729ffc..7f62d09 100644 --- a/tests/guard-host.test.js +++ b/tests/guard-host.test.js @@ -238,7 +238,7 @@ test("a failed model catalog lookup is retried by the next call", async () => { expect((await dump.execute({})).content).toContain("could not be read"); // The next one asks again and checks the variant against the catalog. const res = await patch.execute( - { grunts: { "a/b": { variant: "ultra" } } }, + { revision: "none", grunts: { "a/b": { variant: "ultra" } } }, { agent: "build" }, ); expect(res.content).toContain("Roster is invalid"); @@ -266,7 +266,7 @@ test("squad_patch refuses while model_data.json is unreadable, writing nothing", try { const res = await h.tools .get("squad_patch") - .execute({ grunts: { "a/b": {} } }, { agent: "build" }); + .execute({ revision: "none", grunts: { "a/b": {} } }, { agent: "build" }); expect(res.content).toContain("Refused: model_data.json cannot be read"); expect(res.content).toContain("invalid JSON at line 3, column 1"); expect(fs.existsSync(defaultStoreFile())).toBe(false); diff --git a/tests/plugin-entry.test.js b/tests/plugin-entry.test.js index 7e73f74..83741e1 100644 --- a/tests/plugin-entry.test.js +++ b/tests/plugin-entry.test.js @@ -12,7 +12,7 @@ import os from "node:os"; import path from "node:path"; import { afterEach, expect, test, vi } from "vitest"; import plugin from "../index.js"; -import { defaultStoreFile, readStore } from "../src/squad-store.js"; +import { defaultStoreFile, readStore, storeRevision } from "../src/squad-store.js"; import { roleRules } from "../src/workers.js"; // Startup refreshes write global model data and schedule network requests; @@ -171,9 +171,10 @@ test("package exposes only setup; squad_patch writes squad.json and registers th await firstRequest(); const patch = tools.get("squad_patch"); // A roster wrapped one level too deep must not read as "delete everything". - wrapped = (await patch.execute({ roster: input }, { agent: "build" })).content; - scoped = (await patch.execute({ ...input, directory }, { agent: "build" })).content; - report = (await patch.execute(input, { agent: "build" })).content; + const revision = storeRevision(defaultStoreFile()); + wrapped = (await patch.execute({ revision, roster: input }, { agent: "build" })).content; + scoped = (await patch.execute({ revision, ...input, directory }, { agent: "build" })).content; + report = (await patch.execute({ revision, ...input }, { agent: "build" })).content; } finally { dispose(); } @@ -190,7 +191,7 @@ test("package exposes only setup; squad_patch writes squad.json and registers th expect(wrapped).toContain("`roster`"); expect(scoped).toContain("`directory` is no longer supported"); expect(report).toContain("+2 added"); - expect(readStore(defaultStoreFile())).toEqual({ state: "ok", roster: input }); + expect(readStore(defaultStoreFile())).toMatchObject({ state: "ok", roster: input }); // Nothing written next to the project, and no agent file anywhere. expect(fs.readdirSync(directory)).toEqual([]); const agents = registered(); @@ -383,7 +384,13 @@ test("squad_patch validates its input with the same schema it advertises", async dirs.push(directory); const { tools, dispose } = await setupHost({ directory }); const patch = tools.get("squad_patch"); - const run = async (input) => (await patch.execute(input, { agent: "build" })).content; + const run = async (input) => + ( + await patch.execute( + { revision: storeRevision(defaultStoreFile()), ...input }, + { agent: "build" }, + ) + ).content; const stored = () => readStore(defaultStoreFile()).state; try { // Advertised: the plain JSON Schema subset, no Zod-only keywords. @@ -418,7 +425,7 @@ test("squad_patch validates its input with the same schema it advertises", async // A valid one-role roster is written. expect(await run({ grunts: { "a/b": { variant: "high" } } })).toContain("+1 added"); - expect(readStore(defaultStoreFile())).toEqual({ + expect(readStore(defaultStoreFile())).toMatchObject({ state: "ok", roster: { grunts: { "a/b": { variant: "high" } }, drills: {} }, }); @@ -436,7 +443,7 @@ test("squad_patch refuses model ids that would register one agent (#90)", async const out = ( await tools .get("squad_patch") - .execute({ grunts: { "p/m-1": {}, "p/m.1": {} } }, { agent: "build" }) + .execute({ revision: "none", grunts: { "p/m-1": {}, "p/m.1": {} } }, { agent: "build" }) ).content; expect(out).toContain("Roster is invalid"); expect(out).toContain("grunt p/m-1 and grunt p/m.1 map to the same agent id grunt-p-m-1"); @@ -462,6 +469,91 @@ test("a stored roster with colliding ids registers neither and says so in the du } }); +test("a patch from a stale dump is refused; the change it would revert survives (#89)", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + const { writeStore } = await import("../src/squad-store.js"); + writeStore(defaultStoreFile(), { grunts: { "p/a": {} }, drills: {} }); + const { tools, dispose } = await setupHost({ directory }); + const patch = (input) => tools.get("squad_patch").execute(input, { agent: "build" }); + try { + const dump = (await tools.get("squad_dump").execute({}, { agent: "build" })).content; + const doc = JSON.parse(dump.slice(dump.indexOf("{"), dump.indexOf("\n}") + 2)); + expect(doc.revision).toBe(storeRevision(defaultStoreFile())); + // Two edits of the same dump: notes on p/a, then a new p/b. + const notes = await patch({ ...doc, grunts: { "p/a": { notes: "terse" } } }); + expect(notes.content).toContain("~1 changed"); + const stale = await patch({ ...doc, grunts: { "p/a": {}, "p/b": {} } }); + expect(stale.content).toContain("REFUSED: squad.json changed since that squad_dump"); + expect(readStore(defaultStoreFile()).roster.grunts).toEqual({ "p/a": { notes: "terse" } }); + // Without a revision there is no base to check against. + const { revision: _r, ...bare } = doc; + expect((await patch(bare)).content).toContain("pass the `revision` from squad_dump"); + } finally { + dispose(); + } +}); + +test("two patches in flight from one dump: one applies, the other is refused (#89)", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + // Both handlers pause at the host's agent list, after reading their input. + let release; + const gate = new Promise((resolve) => { + release = resolve; + }); + const { tools, dispose } = await setupHost({ + directory, + agent: { + list: async () => { + await gate; + return []; + }, + }, + }); + const patch = (input) => tools.get("squad_patch").execute(input, { agent: "build" }); + try { + const revision = storeRevision(defaultStoreFile()); + const a = patch({ revision, grunts: { "p/a": {} } }); + const b = patch({ revision, grunts: { "p/b": {} } }); + release(); + const out = [(await a).content, (await b).content]; + expect(out.filter((c) => c.includes("+1 added"))).toHaveLength(1); + expect(out.filter((c) => c.includes("REFUSED: squad.json changed"))).toHaveLength(1); + expect(Object.keys(readStore(defaultStoreFile()).roster.grunts)).toHaveLength(1); + } finally { + dispose(); + } +}); + +test("squad.json locked by another process: the patch writes nothing and says so (#89)", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + const { tools, dispose } = await setupHost({ directory }); + const lock = `${defaultStoreFile()}.lock`; + fs.mkdirSync(path.dirname(lock), { recursive: true }); + fs.writeFileSync(lock, "4242"); + const patch = () => + tools.get("squad_patch").execute( + { revision: storeRevision(defaultStoreFile()), grunts: { "p/a": {} } }, + { + agent: "build", + }, + ); + try { + expect((await patch()).content).toContain("another OpenCode process is writing squad.json"); + expect(readStore(defaultStoreFile()).state).toBe("missing"); + // A lock left by a process that died long ago is taken over. + const old = new Date(Date.now() - 120_000); + fs.utimesSync(lock, old, old); + expect((await patch()).content).toContain("+1 added"); + expect(fs.existsSync(lock)).toBe(false); + } finally { + dispose(); + fs.rmSync(lock, { force: true }); + } +}); + const ALLOW_ALL = { action: "*", resource: "*", effect: "allow" }; const drillTools = () => ({ read: {}, shell: {}, edit: {}, write: {}, execute: {} }); @@ -556,7 +648,9 @@ test("without squad.json, a legacy squad that cannot be read is unknown, not emp expect(dump).toContain("The squad cannot be read, so it is NOT empty"); expect(dump).toContain("grunt-c-d.md"); const patch = ( - await tools.get("squad_patch").execute({ grunts: { "x/y": {} } }, { agent: "build" }) + await tools + .get("squad_patch") + .execute({ revision: "none", grunts: { "x/y": {} } }, { agent: "build" }) ).content; expect(patch).toContain("Refused: the current squad cannot be read"); expect(readStore(defaultStoreFile()).state).toBe("missing"); @@ -576,7 +670,9 @@ test("without squad.json, the legacy squad is what a patch is diffed against", a expect(dump).toContain('"a/b"'); // Rebuilt from memory without the drill: a deletion, refused. const patch = ( - await tools.get("squad_patch").execute({ grunts: { "a/b": {} } }, { agent: "build" }) + await tools + .get("squad_patch") + .execute({ revision: "none", grunts: { "a/b": {} } }, { agent: "build" }) ).content; expect(patch).toContain("would DELETE 1 agent(s)"); expect(patch).toContain("drill a/b"); @@ -597,12 +693,20 @@ test("a hand-authored agent on an unchanged entry is no reason to refuse other c }); try { const patch = tools.get("squad_patch"); - const kept = (await patch.execute({ grunts: { "p/q": {}, "p/r": {} } }, { agent: "build" })) - .content; + const revision = () => storeRevision(defaultStoreFile()); + const kept = ( + await patch.execute( + { revision: revision(), grunts: { "p/q": {}, "p/r": {} } }, + { agent: "build" }, + ) + ).content; expect(kept).toContain("+1 added"); // Changing that entry is a new claim on the user's id: refused. const changed = ( - await patch.execute({ grunts: { "p/q": { variant: "high" }, "p/r": {} } }, { agent: "build" }) + await patch.execute( + { revision: revision(), grunts: { "p/q": { variant: "high" }, "p/r": {} } }, + { agent: "build" }, + ) ).content; expect(changed).toContain( "REFUSED: the roster asks for an agent id that a hand-authored agent", diff --git a/tests/runtime-model-data.test.js b/tests/runtime-model-data.test.js index a966f73..ee2770d 100644 --- a/tests/runtime-model-data.test.js +++ b/tests/runtime-model-data.test.js @@ -109,7 +109,7 @@ test("the legacy squad is imported once, files left in place, owner notes kept", fs.writeFileSync(globalFile, JSON.stringify({ models: { "a/b": { info: "keep me" } } })); expect(importLegacySquad()).toEqual({ imported: 2, problems: [] }); - expect(readStore(storeFile)).toEqual({ + expect(readStore(storeFile)).toMatchObject({ state: "ok", roster: { grunts: { "a/b": { variant: "high" } }, drills: { "c/d": {} } }, }); diff --git a/tests/squad-store.test.js b/tests/squad-store.test.js index 2271fc4..2ec3d05 100644 --- a/tests/squad-store.test.js +++ b/tests/squad-store.test.js @@ -5,7 +5,15 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, expect, test } from "vitest"; -import { defaultStoreFile, readStore, storeSignature, writeStore } from "../src/squad-store.js"; +import { + defaultStoreFile, + NO_STORE_REVISION, + readStore, + storeRevision, + storeSignature, + withStoreLock, + writeStore, +} from "../src/squad-store.js"; let dir; let file; @@ -34,10 +42,42 @@ test("write then read round-trips, keys sorted, with the format version", () => expect(readStore(file)).toEqual({ state: "ok", roster: { grunts: { "a/b": {}, "z/b": { variant: "high" } }, drills: {} }, + revision: storeRevision(file), }); expect(storeSignature(file)).not.toBe("-"); }); +test("the revision is of the bytes: any edit changes it, none means no file (#89)", () => { + expect(storeRevision(file)).toBe(NO_STORE_REVISION); + writeStore(file, { grunts: { "a/b": { notes: "x" } }, drills: {} }); + const first = storeRevision(file); + expect(first).toMatch(/^[0-9a-f]{16}$/); + // Same length, same second: mtime and size would not see it. + fs.writeFileSync(file, fs.readFileSync(file, "utf8").replace('"x"', '"y"')); + expect(storeRevision(file)).not.toBe(first); + fs.chmodSync(file, 0o000); + expect(storeRevision(file)).toBeNull(); + fs.chmodSync(file, 0o600); +}); + +test("withStoreLock: exclusive, released after, busy while held, stale taken over", () => { + const lock = `${file}.lock`; + expect(withStoreLock(file, () => fs.existsSync(lock))).toEqual({ busy: false, value: true }); + expect(fs.existsSync(lock)).toBe(false); + // Released even when the body throws. + expect(() => + withStoreLock(file, () => { + throw new Error("boom"); + }), + ).toThrow("boom"); + expect(fs.existsSync(lock)).toBe(false); + fs.writeFileSync(lock, "1"); + expect(withStoreLock(file, () => 1)).toEqual({ busy: true }); + const old = new Date(Date.now() - 60_000); + fs.utimesSync(lock, old, old); + expect(withStoreLock(file, () => 2)).toEqual({ busy: false, value: 2 }); +}); + test.each([ ["{not json", /not valid JSON/], ["[]", /not a JSON object/], diff --git a/tests/squad-tools.test.js b/tests/squad-tools.test.js index 508c0df..da89a92 100644 --- a/tests/squad-tools.test.js +++ b/tests/squad-tools.test.js @@ -64,7 +64,10 @@ describe("V2 schemas", () => { "allow_remove", "drills", "grunts", + "revision", ]); + // The base the edit was built on is not optional (#89). + expect(SQUAD_PATCH_INPUT.required).toEqual(["revision"]); expect(SQUAD_PATCH_INPUT.properties.grunts.additionalProperties.properties.steps.type).toBe( "integer", ); From e15caf8826755b3300798962c0276909517ecfe3 Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:42:11 +0300 Subject: [PATCH 08/17] squad: an unreadable model_data.json keeps or flags the owner rules (#91) One contract for startup, reloads and squad_patch. The plugin keeps the settings it last read without a problem for the life of the instance; with none read yet, each squad agent's description says the owner's rules are unknown and to ask the user before giving it secrets. squad_dump and the patch report name the file. squad_patch no longer refuses over it: the roster write never carried the rules, and refusing there while registration went ahead was the inconsistency the ticket describes. Co-Authored-By: Claude Opus 5.5 --- .opencode/lib/runtime.js | 36 ++++++++++++++++++++++++-- .opencode/lib/squad.js | 28 +++++++++++--------- tests-integration/squad-review.test.js | 28 ++++++++++++++++++++ tests/guard-host.test.js | 25 +++++++++--------- tests/plugin-entry.test.js | 6 ++++- tests/runtime-model-data.test.js | 25 ++++++++++++++++++ 6 files changed, 121 insertions(+), 27 deletions(-) diff --git a/.opencode/lib/runtime.js b/.opencode/lib/runtime.js index 2acbda7..212a499 100644 --- a/.opencode/lib/runtime.js +++ b/.opencode/lib/runtime.js @@ -259,15 +259,47 @@ export function importLegacySquad() { } } +/** Said in a squad agent's description when the owner's rules cannot be read. */ +export const OWNER_RULES_UNKNOWN = + "Owner rules UNKNOWN: model_data.json could not be read, so any routing rule the " + + "owner set for this model is missing here. Ask the user before giving it secrets or " + + "anything they may restrict."; + /** * describe(role, modelId) for the squad, from the GLOBAL model_data.json: the * squad is global, and with project overrides its descriptions would flip with * whichever project's instance registered last. * - * @returns {(role: "grunt"|"drill", modelId: string) => string} + * The owner's rules in there are binding routing rules ("no secrets"), and a + * description is the line the orchestrator routes by, so a file that cannot + * be read must not turn them into a plain description (#91). One contract for + * startup, every reload and squad_patch alike: + * - the settings last read without a problem stay in force, for the life of + * the plugin instance (`stale`); + * - with none read yet, each description says the owner's rules are unknown; + * - either way `problems` names the file, for squad_dump and squad_patch. + * + * @returns {() => {describe: (role: "grunt"|"drill", modelId: string) => string, + * problems: string[], stale: boolean}} */ export function squadDescriber() { - return describerFrom(loadModelSettings(null)); + /** @type {ModelSettings | null} */ + let lastGood = null; + return () => { + const settings = loadModelSettings(null); + if (!settings.problems.length) { + lastGood = settings; + return { describe: describerFrom(settings), problems: [], stale: false }; + } + if (lastGood) { + return { describe: describerFrom(lastGood), problems: settings.problems, stale: true }; + } + return { + describe: (role) => `${describeAgent(role)} ${OWNER_RULES_UNKNOWN}`, + problems: settings.problems, + stale: false, + }; + }; } /** diff --git a/.opencode/lib/squad.js b/.opencode/lib/squad.js index 6204903..02165d0 100644 --- a/.opencode/lib/squad.js +++ b/.opencode/lib/squad.js @@ -275,11 +275,13 @@ export default { } return { state: "ok", roster: legacy.roster, revision: NO_STORE_REVISION }; }; + // The owner's rules for descriptions, with the last good read kept (#91). + const readDescriptions = squadDescriber(); const specsNow = () => { const store = readStore(storeFile); if (store.state !== "ok") return null; return agentSpecs(store.roster, { - describe: squadDescriber(), + describe: readDescriptions().describe, prompt: (role) => { try { return loadRolePrompt(role); @@ -325,6 +327,16 @@ export default { "if it is an old squad file of a project, the user may delete it", ); } + const described = readDescriptions(); + if (described.problems.length) { + notes.push( + `model_data.json cannot be read (${described.problems.join("; ")}): ` + + (described.stale + ? "agent descriptions keep the owner rules read earlier in this session" + : "agent descriptions carry no owner rules and say so") + + ". Ask the user to fix the file.", + ); + } for (const p of legacyImport.problems) { notes.push(`legacy squad files were not imported: ${p}. Fix or delete it, then restart`); } @@ -811,17 +823,9 @@ export default { content: `Roster is invalid:\n${variantErrors.map((e) => ` - ${e}`).join("\n")}`, }; } - // Descriptions carry the owner's routing rules from model_data.json; - // registering from an unreadable file would strip them from every agent. - const problems = loadModelSettings(null).problems; - if (problems.length) { - return { - content: - "Refused: model_data.json cannot be read, and agent descriptions are built " + - "from it — applying now would drop the owner's routing rules. Nothing was " + - `written. Ask the user to fix:\n${problems.map((p) => ` - ${p}`).join("\n")}`, - }; - } + // An unreadable model_data.json does not block the roster: the + // descriptions keep the owner's rules last read, or say they are + // unknown, and the report's notes name the file (#91). // Every await happens above this line. From here to the write the // handler is synchronous, so no other patch of this process runs in // between, and the lock keeps other OpenCode processes out (#89). diff --git a/tests-integration/squad-review.test.js b/tests-integration/squad-review.test.js index bfeebe8..a948ab9 100644 --- a/tests-integration/squad-review.test.js +++ b/tests-integration/squad-review.test.js @@ -4,6 +4,8 @@ // offers only the drill's tools and enforces its rules; // #88 an agent the user wrote keeps its whole effective definition when the // roster asks for its id, or when a verified legacy file shares its id. +// #91 an unreadable model_data.json never registers a squad agent whose +// description silently lacks the owner's rules. // Run: npm run test:integration (Node >= 24) import fs from "node:fs/promises"; @@ -151,3 +153,29 @@ test("#88: a verified legacy file does not hide another agent the host loaded at expect(alone?.system).toContain("HAND-WRITTEN PROMPT"); expect(live).toEqual(alone); }, 180_000); + +test("#91: with model_data.json unreadable, the live description says the owner rules are unknown", async () => { + await writeRoster({ grunts: { "p/m": {} } }); + // The owner's rule is in there, but the file does not parse. + await fs.writeFile( + path.join(configDir(), "model_data.json"), + '{"models": {"p/m": {"info": "no secrets"}},', + ); + try { + const live = await withHost( + (h) => + Effect.gen(function* () { + yield* h.llm.serve((request) => + isTitleRequest(request) ? TestLLM.text("Title", "title") : TestLLM.text("ok", "answer"), + ); + yield* oneTurn(h); + return yield* liveAgent(h, "grunt-p-m"); + }), + GLOBAL_ALLOW, + ); + expect(live?.description).toContain("Owner rules UNKNOWN"); + expect(live?.description).toContain("model_data.json could not be read"); + } finally { + await fs.rm(path.join(configDir(), "model_data.json"), { force: true }); + } +}, 120_000); diff --git a/tests/guard-host.test.js b/tests/guard-host.test.js index 7f62d09..0abab04 100644 --- a/tests/guard-host.test.js +++ b/tests/guard-host.test.js @@ -10,15 +10,17 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, expect, test, vi } from "vitest"; -import { loadModelSettings } from "../.opencode/lib/runtime.js"; import plugin from "../index.js"; -import { defaultStoreFile } from "../src/squad-store.js"; vi.mock("../.opencode/lib/runtime.js", async (importOriginal) => ({ ...(await importOriginal()), ensureGlobalModelDataFresh: () => {}, importLegacySquad: () => ({ imported: 0, problems: [] }), - squadDescriber: () => (role, id) => `${role} on ${id}.`, + squadDescriber: () => () => ({ + describe: (role, id) => `${role} on ${id}.`, + problems: globalThis.__modelDataProblems ?? [], + stale: false, + }), startMetricsRefresh: () => {}, getMetrics: async () => null, loadModelSettings: vi.fn(() => ({ models: {}, providers: {}, found: false, problems: [] })), @@ -254,24 +256,23 @@ test("a failed model catalog lookup is retried by the next call", async () => { } }); -test("squad_patch refuses while model_data.json is unreadable, writing nothing", async () => { +test("an unreadable model_data.json does not block squad_patch; the report names it (#91)", async () => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-unreadable-")); const h = await host(); - vi.mocked(loadModelSettings).mockReturnValueOnce({ - models: {}, - providers: {}, - found: false, - problems: ["/cfg/opencode/model_data.json: invalid JSON at line 3, column 1"], - }); + globalThis.__modelDataProblems = [ + "/cfg/opencode/model_data.json: invalid JSON at line 3, column 1", + ]; try { const res = await h.tools .get("squad_patch") .execute({ revision: "none", grunts: { "a/b": {} } }, { agent: "build" }); - expect(res.content).toContain("Refused: model_data.json cannot be read"); + expect(res.content).toContain("+1 added"); + expect(res.content).toContain("model_data.json cannot be read"); expect(res.content).toContain("invalid JSON at line 3, column 1"); - expect(fs.existsSync(defaultStoreFile())).toBe(false); + expect(res.content).toContain("agent descriptions carry no owner rules and say so"); expect(fs.readdirSync(directory)).toEqual([]); } finally { + delete globalThis.__modelDataProblems; h.dispose(); fs.rmSync(directory, { recursive: true, force: true }); } diff --git a/tests/plugin-entry.test.js b/tests/plugin-entry.test.js index 83741e1..4a9577d 100644 --- a/tests/plugin-entry.test.js +++ b/tests/plugin-entry.test.js @@ -46,7 +46,11 @@ vi.mock("../.opencode/lib/runtime.js", async (importOriginal) => { ...(await importOriginal()), ensureGlobalModelDataFresh: () => {}, importLegacySquad: () => ({ imported: 0, problems: [] }), - squadDescriber: () => (role, id) => `${role} on ${id}. Owner rule: no secrets.`, + squadDescriber: () => () => ({ + describe: (role, id) => `${role} on ${id}. Owner rule: no secrets.`, + problems: [], + stale: false, + }), startMetricsRefresh: () => {}, // A test may swap in its own cache contents. getMetrics: async () => globalThis.__squadMetricsData ?? data, diff --git a/tests/runtime-model-data.test.js b/tests/runtime-model-data.test.js index ee2770d..5ae3366 100644 --- a/tests/runtime-model-data.test.js +++ b/tests/runtime-model-data.test.js @@ -12,6 +12,8 @@ import { ensureGlobalModelDataFresh, importLegacySquad, loadModelSettings, + OWNER_RULES_UNKNOWN, + squadDescriber, } from "../.opencode/lib/runtime.js"; import { readStore, writeStore } from "../src/squad-store.js"; @@ -146,6 +148,29 @@ test("legacy files whose models map to one agent id block the import (#90)", () expect(fs.existsSync(storeFile)).toBe(false); }); +test("an unreadable model_data.json never yields a description without its rules (#91)", () => { + const read = squadDescriber(); + // Broken from the start: no rules known, and the description says so. + fs.writeFileSync(globalFile, '{"models": {"a/b": {"info": "no secrets"}},'); + let now = read(); + expect(now.problems).toEqual([expect.stringContaining(globalFile)]); + expect(now.stale).toBe(false); + expect(now.describe("grunt", "a/b")).toContain(OWNER_RULES_UNKNOWN); + expect(now.describe("grunt", "a/b")).not.toContain("no secrets"); + // Readable: the owner's rule, no problems. + fs.writeFileSync(globalFile, JSON.stringify({ models: { "a/b": { info: "no secrets" } } })); + now = read(); + expect(now.problems).toEqual([]); + expect(now.describe("grunt", "a/b")).toContain("Owner rule: no secrets."); + // Broken again: the rules last read stay in force, and the problem is named. + fs.writeFileSync(globalFile, "{"); + now = read(); + expect(now.stale).toBe(true); + expect(now.problems).toEqual([expect.stringContaining(globalFile)]); + expect(now.describe("grunt", "a/b")).toContain("Owner rule: no secrets."); + expect(now.describe("grunt", "a/b")).not.toContain(OWNER_RULES_UNKNOWN); +}); + test("no legacy squad, no import: squad.json is not created empty", () => { expect(importLegacySquad()).toEqual({ imported: 0, problems: [] }); expect(fs.existsSync(storeFile)).toBe(false); From 6a59ddbbb5165f476b0e0c5a744d575105e3b5bc Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:43:20 +0300 Subject: [PATCH 09/17] docs: revision, agent ownership and model_data contract (#87-#91) README and squad-draft: squad_dump prints a revision that squad_patch needs back, a stale one is refused; colliding model ids are refused; an agent of the user's at a squad id keeps its whole definition; a legacy file is taken over only when it is the agent OpenCode loaded; squad agents exist only once OpenCode's config is applied; what an unreadable model_data.json does to descriptions. Co-Authored-By: Claude Opus 5.5 --- README.md | 26 ++++++++++++++++---------- skills/squad-draft/SKILL.md | 23 +++++++++++++++++++---- 2 files changed, 35 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 938ea95..80c8736 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ The global file is refreshed at opencode startup: new squad models get an empty ## Changing subagent models -Use `squad-draft` (or `squad_dump` + `squad_patch`) to add or retune the per-model agents. The squad is one roster for every project; an `agents` entry in a project's `opencode.json` no longer overrides a squad agent, because the plugin registers those agents itself and sets every field. There are no generic fallback grunt/drill agents. +Use `squad-draft` (or `squad_dump` + `squad_patch`) to add or retune the per-model agents. The squad is one roster for every project. An `agents` entry in an `opencode.json`, or an agent file, at a squad agent's id is your own agent from then on: it wins, exactly as you wrote it, and that squad entry is not registered. There are no generic fallback grunt/drill agents. --- @@ -132,9 +132,9 @@ openai/gpt-5.5 → grunt-openai-gpt-5-5 (executor: edit/shell) Each squad agent shares the bundled grunt/drill prompt and permissions, differs only in `model`, and is `hidden` (dispatched via `subagent`, not in the `@`-menu). They appear in the orchestrator's inventory **with their models and capability summary**, which makes routing concrete. A `squad_patch` applies to the next dispatch, without a restart, and another OpenCode process sharing the config dir picks the change up on its next request. The role prompt comes from `prompts/.md` and is refreshed on every request, so editing it takes effect immediately. Hand-authored agents are never touched. -**Upgrading from file-based squads (before #85).** On first start the plugin imports the generated `grunt-*`/`drill-*`/`worker-*` files from `~/.config/opencode/agent/` into `squad.json`, once. The files are left in place: the plugin's agents take over their ids, and generated agents the roster no longer has are hidden. `squad_dump` lists the leftovers, and you may delete them. If a generated file cannot be read, nothing is imported and `squad_dump` says which file to fix. +**Upgrading from file-based squads (before #85).** On first start the plugin imports the generated `grunt-*`/`drill-*`/`worker-*` files from `~/.config/opencode/agent/` into `squad.json`, once. The files are left in place: where the agent OpenCode loaded at an id is that very file (same prompt and model), the plugin's agent takes the id over, and generated agents the roster no longer has are hidden. If another agent holds the id, say a project's own file, it is left alone and `squad_dump` says so. `squad_dump` lists the leftovers, and you may delete them. If a generated file cannot be read, nothing is imported and `squad_dump` says which file to fix. -**Drill permissions.** The plugin appends each role's permission rules after your global `permissions`, so with OpenCode's last-match evaluation a drill stays read-only even when your global config allows everything. The host then hides from a drill every tool its rules deny. +**Drill permissions.** Each squad agent gets your global `permissions` first and its role's rules last, so with OpenCode's last-match evaluation a drill stays read-only even when your global config allows everything, and the host hides from it every tool its rules deny. To get that order the plugin builds the squad's agents after OpenCode's own config has been applied; until then they do not exist, so an early request for one fails instead of running with the wrong rules. Each request a squad agent makes is checked once more: if the role's rules are no longer last, they are put back and the request's tools are cut to what the role allows. There is no bundled fallback agent — if no `grunt-*`/`drill-*` exists yet, the orchestrator tells you to run `squad-draft` instead of inventing a subagent or quietly doing the work itself. @@ -314,7 +314,7 @@ So the roster is data you edit, exposed as two plugin tools: | tool | what it does | | --- | --- | | `squad_dump` | returns the current roster from `squad.json` as JSON | -| `squad_patch` | writes a roster back — `grunts` / `drills`, plus `allow_remove`; refuses a `description` (generated, see below), a roster wrapped in an extra key, and the removed `directory` argument | +| `squad_patch` | writes a roster back — `grunts` / `drills`, the `revision` the dump printed, plus `allow_remove`; refuses a stale `revision`, a `description` (generated, see below), model ids that map to one agent id, a roster wrapped in an extra key, and the removed `directory` argument | | `squad_metrics` | benchmarks, prices, context and billing for the `models` given; `full: true` for every metric of up to 6 — see [Model metrics](#model-metrics-squad_metrics) | A third tool covers the other half of reuse: @@ -365,7 +365,7 @@ Per-agent fields, and why these and not the rest of opencode's agent schema: | `steps` | cap on agentic iterations before opencode forces a text response | | `disable` | park an agent without deleting it — the soft alternative to a removal | -**Descriptions are generated, not drafted.** An agent's `description` is the line the orchestrator reads when it picks whom to dispatch, so it carries exactly what you own and nothing that goes stale: the role, your `info` for that model as `Owner rule: …`, and the provider's plan (`Billing: subscription (Max 5x).`). The plugin builds it from the global `model_data.json` whenever it registers the agents: at start and after every `squad_patch`. So editing `info` or a plan needs a restart, not a re-draft. A `model_data.json` that does not parse is never overwritten: startup leaves it as it is and logs its path and the parse position, `squad_patch` refuses until it is fixed, and `squad_metrics` lists it as ignored. Benchmarks, prices and rankings never go in: hand-written ones went stale within a week, and an orchestrator asked to "refresh descriptions" invented them. +**Descriptions are generated, not drafted.** An agent's `description` is the line the orchestrator reads when it picks whom to dispatch, so it carries exactly what you own and nothing that goes stale: the role, your `info` for that model as `Owner rule: …`, and the provider's plan (`Billing: subscription (Max 5x).`). The plugin builds it from the global `model_data.json` whenever it registers the agents: at start and after every `squad_patch`. So editing `info` or a plan needs a restart, not a re-draft. A `model_data.json` that does not parse is never overwritten: startup leaves it as it is and logs its path and the parse position, and `squad_metrics` lists it as ignored. Its owner rules are never silently dropped from a description: the plugin keeps the ones it last read for as long as it runs, and with none read yet each squad agent's description says the owner's rules are unknown. `squad_dump` and the `squad_patch` report name the file until it is fixed. Benchmarks, prices and rankings never go in: hand-written ones went stale within a week, and an orchestrator asked to "refresh descriptions" invented them. Deliberately **not** exposed: `permission` (a drill's read-only contract is a safety property, not a preference), `mode`/`hidden`/`color` (ours), and @@ -377,13 +377,18 @@ path that wiped a squad; keeping it as a second entry point would have meant a second copy of the deletion guard, and the copy that drifted would be the one that deletes agents. -Two properties make the flow safe, and neither is optional: +Three properties make the flow safe, and none is optional: 1. **The roster has one home.** `squad.json` is the whole squad, and only the plugin writes it. There are no agent files beside it to drift from it. A file that does not parse is never overwritten: nothing new is registered from it, `squad_dump` reports it, and `squad_patch` refuses until it is fixed. -2. **Apply refuses to delete.** Read-modify-write only protects while the caller +2. **A patch names the roster it edited.** `squad_dump` prints a `revision`, a + hash of `squad.json`, and `squad_patch` requires it back. If the roster + changed since (another session or OpenCode process patched it), the patch is + refused and nothing is written, so two edits of one dump cannot undo each + other. The check and the write run under an exclusive `squad.json.lock`. +3. **Apply refuses to delete.** Read-modify-write only protects while the caller actually modifies; one that rebuilds the roster from memory reintroduces the wipe in a new wrapper. So deletions are refused and named — nothing at all is written, not even the agent that would have been added — until `allow_remove` @@ -401,7 +406,7 @@ none of that can happen. subagent rewriting the squad mid-task is never intended, and the damage outlives the session. -Hand-authored agents are never dumped, changed or hidden. One that already holds a squad id (`grunt-`) wins: that squad entry is not registered, `squad_dump` notes it, and `squad_patch` refuses the id. +Hand-authored agents are never dumped, changed or hidden. One that already holds a squad id (`grunt-`) wins with its whole definition, as OpenCode built it without the squad: that squad entry is not registered, `squad_dump` notes it, and `squad_patch` refuses to add or change that entry. --- @@ -582,10 +587,11 @@ npm run test:integration # the plugin inside the real OpenCode 2 host, offline ``` `tests-integration/` boots the embedded OpenCode 2.1.3 host (`@opencode/sdk`), loads this repository as a plugin from disk, and replaces the model with `TestLLM` from `@opencode/ai/testing`. No credentials and no network: HOME and the XDG dirs point into a temp directory, and every outbound fetch fails. It checks that the plugin loads and puts its bootstrap in the system prompt, that a scripted tool call reaches `squad_session`, and that a subagent whose model stream hangs is interrupted with one guard note to its orchestrator. It also checks the squad agents registered from `squad.json`: -- a drill gets only read-only tools despite a global allow-all, and `rm` is refused; +- a drill gets only read-only tools despite a global allow-all, and `rm` is refused, from the first request of a session started directly for it; - a legacy agent dropped from the roster cannot be dispatched; - a `squad_patch` applies to the next dispatch; -- a hand-authored agent with a squad id keeps its own prompt. All `@opencode/*` dev packages are pinned to one exact release, so the host and the plugin types come from the same build. +- a hand-authored agent with a squad id, or at the id of a legacy squad file, keeps its whole definition; +- with `model_data.json` unreadable, a squad agent's description says the owner's rules are unknown. All `@opencode/*` dev packages are pinned to one exact release, so the host and the plugin types come from the same build. Coverage is scoped to `src/**` on purpose — that's the decision-logic layer separated from `.opencode/lib/squad.js`'s session/tool hook plumbing. Package-entry tests additionally check registration and native agent generation. diff --git a/skills/squad-draft/SKILL.md b/skills/squad-draft/SKILL.md index 98c3130..018a4ad 100644 --- a/skills/squad-draft/SKILL.md +++ b/skills/squad-draft/SKILL.md @@ -19,11 +19,15 @@ The squad is edited through two tools, `squad_dump` and `squad_patch`. The roster they speak is one map per role, keyed by model id: ```json -{ "grunts": { "zai-coding-plan/glm-5.3": { "variant": "high" }, +{ "revision": "3f9c0a1b2c4d5e6f", + "grunts": { "zai-coding-plan/glm-5.3": { "variant": "high" }, "openai/gpt-5.6-luna": {} }, "drills": { "anthropic/claude-opus-5": { "variant": "max" } } } ``` +`revision` identifies the roster you were shown; keep it when you send the +document back. + An agent exists if it appears in a role map, and `{}` is a valid entry meaning "this model, role defaults". Per-agent fields: `variant`, `notes`, `steps`, `disable` — all optional, all described in the tool schema. There is no @@ -78,7 +82,9 @@ job. (If they hand you an explicit list, honor it.) context and rankings stay out — sarge reads them live from `squad_metrics`; a frozen copy goes stale (a GLM grunt kept advertising "(60/75/84)" long after its source re-scored it at half that). `squad_patch` refuses a - `description`. + `description`. If `model_data.json` cannot be read, the dump and the patch + report say so; tell the user, because descriptions then keep older rules or + say the rules are unknown. **If the user states a routing rule**, write it into `~/.config/opencode/model_data.json` yourself — their words, one line, keep @@ -161,7 +167,15 @@ job. (If they hand you an explicit list, honor it.) their edits. Do not apply before they confirm. 6. **Apply with `squad_patch`**, passing the COMPLETE intended squad — the - document you got from `squad_dump` with your edits folded in. + document you got from `squad_dump` with your edits folded in, its + `revision` included. + + - **A stale revision is refused.** If another session or OpenCode process + patched the squad since your dump, nothing is written. Call `squad_dump` + again, fold the same edits into what it prints now, and patch with its + revision; never copy the old revision onto a new dump. + - Two model ids that map to one agent id (`p/m-1` and `p/m.1`) are refused: + keep one of them. - **Deletions are refused by default.** Any agent present now and absent from your roster is a deletion, including dropping a drill from a model that @@ -173,7 +187,8 @@ job. (If they hand you an explicit list, honor it.) stops being dispatchable but keeps its settings. - There is one squad for every project; `directory` is no longer accepted. - Hand-authored agents are never dumped or changed. One that already holds a - squad id wins: that entry is not registered, and `squad_patch` refuses it. + squad id wins: that entry is not registered, and `squad_patch` refuses to + add or change it. 7. **Report** the applied diff (`+added / -removed / ~changed / =unchanged`), echo the variants that were written — opencode ignores an unrecognized one From 6916781cc98746a3e88b7916f6d07227308dd260 Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:48:30 +0300 Subject: [PATCH 10/17] squad: police and claim only the agents the late transform built The per-request check picked squad agents by their prompt fence, so a stray fenced file of a project's own, or a legacy agent left live while squad.json is unreadable, had its tools cut and set off a re-registration on every request. It now covers only the ids the late transform built. squad_patch's ownership test matches registration: an agent at an added or changed id is the user's unless the plugin built it or it is our own legacy file. A fenced file of someone else's no longer passes as ours, which reported "+1 added" for an entry that was then not registered. A failed re-registration no longer leaves a disposed handle behind. Co-Authored-By: Claude Opus 5.5 --- .opencode/lib/squad.js | 30 +++++++++++---- src/squad-agents.js | 10 ++++- tests/plugin-entry.test.js | 76 +++++++++++++++++++++++++++++++++++--- tests/squad-agents.test.js | 3 +- 4 files changed, 102 insertions(+), 17 deletions(-) diff --git a/.opencode/lib/squad.js b/.opencode/lib/squad.js index 02165d0..bb6b0b1 100644 --- a/.opencode/lib/squad.js +++ b/.opencode/lib/squad.js @@ -63,7 +63,7 @@ import { deniedTools, earlyTransform, endsWithRoleRules, - isSquadSystem, + isLegacyFile, lateTransform, PROBE_ID, rosterCollisions, @@ -241,6 +241,7 @@ export default { let storeSig = storeSignature(storeFile); /** From the late transform: hand-authored holders of roster ids, legacy agents hidden, stray ones left. */ let lateReport = { + built: /** @type {string[]} */ ([]), foreign: /** @type {string[]} */ ([]), hidden: /** @type {string[]} */ ([]), stray: /** @type {string[]} */ ([]), @@ -358,7 +359,10 @@ export default { // legacy agent files, if any, keep working until it is fixed. const specs = specsNow(); if (specs) lateReport = lateTransform(editor, specs, legacyAgents); - else editor.remove(PROBE_ID); + else { + editor.remove(PROBE_ID); + lateReport = { ...lateReport, built: [] }; + } } catch { // A broken roster must not take the host's agent list down with it. } @@ -376,14 +380,16 @@ export default { if (tool?.name) toolActions.set(tool.name, tool.options?.permission ?? tool.name); } }; - /** Live squad agents (ours, not a user's at a squad id) and their roles. */ + /** + * Live agents the late transform built, and their roles: nothing else is + * policed, not a user's agent, a stray fenced file or a legacy agent left + * live while squad.json is unreadable. + */ const liveSquad = async () => { const agents = unwrap(await ctx.agent.list().catch(() => null)) ?? []; return (Array.isArray(agents) ? agents : []).flatMap((a) => { const role = squadRoleOf(a?.id); - return role && isSquadSystem(a?.system) && !lateReport.foreign.includes(a.id) - ? [{ agent: a, role }] - : []; + return role && lateReport.built.includes(a.id) ? [{ agent: a, role }] : []; }); }; let syncing = Promise.resolve(); @@ -400,7 +406,9 @@ export default { const run = syncing.then(async () => { if (!late || reposition) { // Old one out first: two of them would see each other's agents. - await late?.dispose?.(); + const previous = late; + late = null; + await previous?.dispose?.(); late = await ctx.agent.transform(runLate); force = true; } @@ -868,7 +876,13 @@ export default { if (before && JSON.stringify(before) === JSON.stringify(entry)) continue; const id = slugForModel(modelId, role); const agent = byId.get(id); - if (agent && !isSquadSystem(agent.system)) { + // Ours only if the late transform built it or it is our own + // legacy file: the same test the registration applies. + if ( + agent && + !lateReport.built.includes(id) && + !isLegacyFile(agent, legacyAgents.get(id)) + ) { foreign.push({ id, agent: `${role} ${modelId}` }); } } diff --git a/src/squad-agents.js b/src/squad-agents.js index 5934322..203b886 100644 --- a/src/squad-agents.js +++ b/src/squad-agents.js @@ -166,7 +166,7 @@ function globalRules(probe) { * @param {any} agent * @param {LegacyAgent | undefined} file */ -function isLegacyFile(agent, file) { +export function isLegacyFile(agent, file) { if (!file || !agent) return false; const model = agent.model ? `${agent.model.providerID}/${agent.model.id}` : ""; const system = String(agent.system ?? "") @@ -202,7 +202,9 @@ function build(agent, spec, globals) { * marker (src/squad-apply.js readLegacySquad). Files from before the * role-prompt fence, and every `worker-*`, are only recognisable this way: * the marker is a YAML comment the host never exposes. - * @returns {{foreign: string[], hidden: string[], stray: string[], kept: string[]}} + * @returns {{built: string[], foreign: string[], hidden: string[], stray: string[], kept: string[]}} + * built: the squad agents this transform created: the only ones the + * plugin polices per request; * foreign: roster ids another agent already holds (left alone); * hidden: legacy generated agents removed because the roster no longer has them; * stray: generated-looking agents from elsewhere (a project's own agent dir), @@ -222,6 +224,8 @@ export function lateTransform(editor, specs, legacy = new Map()) { const stray = []; /** @type {string[]} */ const kept = []; + /** @type {string[]} */ + const built = []; for (const agent of [...editor.list()]) { const id = String(agent?.id ?? ""); if (wanted.has(id)) continue; @@ -247,8 +251,10 @@ export function lateTransform(editor, specs, legacy = new Map()) { editor.remove(spec.id); } editor.update(spec.id, (agent) => build(agent, spec, globals)); + built.push(spec.id); } return { + built: built.sort(), foreign: foreign.sort(), hidden: hidden.sort(), stray: stray.sort(), diff --git a/tests/plugin-entry.test.js b/tests/plugin-entry.test.js index 4a9577d..1ae4076 100644 --- a/tests/plugin-entry.test.js +++ b/tests/plugin-entry.test.js @@ -71,8 +71,10 @@ vi.mock("../.opencode/lib/runtime.js", async (importOriginal) => { * * @param {{directory: string} & Record} host */ -async function setupHost({ directory, agent, globals = [], ...over }) { +async function setupHost({ directory, agent, globals = [], files = [], ...over }) { const tools = new Map(); + /** How often the plugin asked the host to rebuild its agent list. */ + const counts = { reloads: 0, agentTransforms: 0 }; /** Agent transforms in registration order, as the host keeps them. */ const transforms = []; /** @param {(editor: any) => void} run */ @@ -109,8 +111,13 @@ async function setupHost({ directory, agent, globals = [], ...over }) { }, agent: { list: async () => registered(), - transform: async (callback) => register(callback), - reload: async () => {}, + transform: async (callback) => { + counts.agentTransforms++; + return register(callback); + }, + reload: async () => { + counts.reloads++; + }, ...agent, }, ...over, @@ -120,6 +127,16 @@ async function setupHost({ directory, agent, globals = [], ...over }) { /** @param {any} editor */ const configRun = (editor) => { for (const a of editor.list()) a.permissions.push(...globals.map((r) => ({ ...r }))); + // Agent files: their fields on top; a new agent gets the global rules too. + for (const file of files) { + const exists = editor.get(file.id) !== undefined; + const { permissions = [], ...fields } = file; + editor.update(file.id, (a) => { + if (!exists) a.permissions.push(...globals.map((r) => ({ ...r }))); + Object.assign(a, structuredClone(fields)); + a.permissions.push(...permissions); + }); + } }; let config = register(configRun); /** The agent list the host would build: every transform over a fresh editor. */ @@ -149,7 +166,7 @@ async function setupHost({ directory, agent, globals = [], ...over }) { await config.dispose(); config = register(configRun); }; - return { tools, dispose, registered, firstRequest, hooks, reorderConfig }; + return { tools, dispose, registered, firstRequest, hooks, reorderConfig, counts }; } const dirs = []; @@ -608,6 +625,52 @@ test("the config plugin re-registered behind the late transform is caught on the } }); +test("a fenced agent the plugin did not build is neither policed nor re-registered for", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + const { writeStore } = await import("../src/squad-store.js"); + writeStore(defaultStoreFile(), { grunts: {}, drills: { "a/b": {} } }); + // An old squad file of a project's own, at an id the roster does not have. + const fenced = "\nold\n"; + const { hooks, counts, dispose } = await setupHost({ + directory, + globals: [ALLOW_ALL], + files: [{ id: "drill-x-y", system: fenced }], + }); + try { + await hooks.get("prompt")({ sessionID: "s" }); + const before = { ...counts }; + const event = { agent: "drill-x-y", system: [], tools: drillTools() }; + await hooks.get("context")(event); + expect(Object.keys(event.tools)).toEqual(Object.keys(drillTools())); + expect(counts).toEqual(before); + } finally { + dispose(); + } +}); + +test("squad_patch refuses an id a fenced file of someone else's holds, as registration would (#88)", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); + dirs.push(directory); + const fenced = "\nold\n"; + const { tools, firstRequest, registered, dispose } = await setupHost({ + directory, + files: [{ id: "grunt-p-q", system: fenced }], + }); + try { + await firstRequest(); + const out = ( + await tools + .get("squad_patch") + .execute({ revision: "none", grunts: { "p/q": {} } }, { agent: "build" }) + ).content; + expect(out).toContain("REFUSED: the roster asks for an agent id that a hand-authored agent"); + expect(registered().find((a) => a.id === "grunt-p-q").system).toBe(fenced); + } finally { + dispose(); + } +}); + test("a user's agent at a squad id is not policed by the squad's rules", async () => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "squad-host-")); dirs.push(directory); @@ -691,11 +754,12 @@ test("a hand-authored agent on an unchanged entry is no reason to refuse other c dirs.push(directory); const { writeStore } = await import("../src/squad-store.js"); writeStore(defaultStoreFile(), { grunts: { "p/q": {} }, drills: {} }); - const { tools, dispose } = await setupHost({ + const { tools, dispose, firstRequest } = await setupHost({ directory, - agent: { list: async () => [{ id: "grunt-p-q", system: "My own prompt." }] }, + files: [{ id: "grunt-p-q", system: "My own prompt." }], }); try { + await firstRequest(); const patch = tools.get("squad_patch"); const revision = () => storeRevision(defaultStoreFile()); const kept = ( diff --git a/tests/squad-agents.test.js b/tests/squad-agents.test.js index 78721b2..025235b 100644 --- a/tests/squad-agents.test.js +++ b/tests/squad-agents.test.js @@ -174,7 +174,7 @@ test("late: a same-id legacy file is rebuilt from scratch, none of its fields ke const specs = agentSpecs({ drills: { "a/b": {} } }, io); const old = legacyFile("drill-a-b", "a/b", "an old inlined prompt"); const { editor, report } = hostOrder({ specs, files: [old.live], legacy: new Map([old.seen]) }); - expect(report).toEqual({ foreign: [], hidden: [], stray: [], kept: [] }); + expect(report).toEqual({ built: ["drill-a-b"], foreign: [], hidden: [], stray: [], kept: [] }); const agent = editor.get("drill-a-b"); expect(agent).not.toHaveProperty("color"); expect(agent).not.toHaveProperty("steps"); @@ -223,6 +223,7 @@ test("late: verified legacy agents the roster dropped are hidden, worker- includ legacy: new Map([drill.seen, worker.seen]), }); expect(report).toEqual({ + built: ["grunt-a-b"], foreign: [], hidden: ["drill-old-model", "worker-old-model"], stray: ["drill-project-model"], From 2931ca7bc0c2d70632a71142a8145fd55bca6c17 Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:50:39 +0300 Subject: [PATCH 11/17] test(squad-store): create the stand-in lock exclusively (CodeQL) An existsSync check followed by a write to the same path is a js/file-system-race finding even in a test. An exclusive create both checks that the lock was released and plays the other holder. Co-Authored-By: Claude Opus 5.5 --- tests/squad-store.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/squad-store.test.js b/tests/squad-store.test.js index 2ec3d05..7196a51 100644 --- a/tests/squad-store.test.js +++ b/tests/squad-store.test.js @@ -70,8 +70,8 @@ test("withStoreLock: exclusive, released after, busy while held, stale taken ove throw new Error("boom"); }), ).toThrow("boom"); - expect(fs.existsSync(lock)).toBe(false); - fs.writeFileSync(lock, "1"); + // Released: an exclusive create succeeds, and stands in for another holder. + fs.closeSync(fs.openSync(lock, "wx")); expect(withStoreLock(file, () => 1)).toEqual({ busy: true }); const old = new Date(Date.now() - 60_000); fs.utimesSync(lock, old, old); From ad356b6e268fceb79260db49f7576606540b2f44 Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:52:58 +0300 Subject: [PATCH 12/17] test(squad-store): no existence check before the stand-in lock (CodeQL) Co-Authored-By: Claude Opus 5.5 --- tests/squad-store.test.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/squad-store.test.js b/tests/squad-store.test.js index 7196a51..55f604a 100644 --- a/tests/squad-store.test.js +++ b/tests/squad-store.test.js @@ -62,15 +62,18 @@ test("the revision is of the bytes: any edit changes it, none means no file (#89 test("withStoreLock: exclusive, released after, busy while held, stale taken over", () => { const lock = `${file}.lock`; - expect(withStoreLock(file, () => fs.existsSync(lock))).toEqual({ busy: false, value: true }); - expect(fs.existsSync(lock)).toBe(false); - // Released even when the body throws. + // Held while the body runs: the lock names this process. + expect(withStoreLock(file, () => fs.readFileSync(lock, "utf8"))).toEqual({ + busy: false, + value: String(process.pid), + }); expect(() => withStoreLock(file, () => { throw new Error("boom"); }), ).toThrow("boom"); - // Released: an exclusive create succeeds, and stands in for another holder. + // Released both times, even after a throw: an exclusive create succeeds, + // and stands in for another process holding it. fs.closeSync(fs.openSync(lock, "wx")); expect(withStoreLock(file, () => 1)).toEqual({ busy: true }); const old = new Date(Date.now() - 60_000); From 996f13ac176ff55f7210dd0db9c08227b39d175c Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:18:08 +0300 Subject: [PATCH 13/17] squad: reload when squad.json's content changes, not its size or mtime (#92) The reload decision compared mtime:size, while patches identify a roster by the hash of its bytes. An equally long roster with the old timestamp left a running process on the previous roster until some later write. The context hook now compares the content revision; storeSignature is gone. Co-Authored-By: Claude Opus 5.5 --- .opencode/lib/squad.js | 8 ++++--- src/squad-store.js | 15 ------------- tests-integration/squad-review.test.js | 31 ++++++++++++++++++++++++++ tests/squad-store.test.js | 4 +--- 4 files changed, 37 insertions(+), 21 deletions(-) diff --git a/.opencode/lib/squad.js b/.opencode/lib/squad.js index bb6b0b1..3143bd8 100644 --- a/.opencode/lib/squad.js +++ b/.opencode/lib/squad.js @@ -78,7 +78,7 @@ import { defaultStoreFile, NO_STORE_REVISION, readStore, - storeSignature, + storeRevision, withStoreLock, writeStore, } from "../../src/squad-store.js"; @@ -238,7 +238,9 @@ export default { // src/squad-agents.js for why there are two transforms. const storeFile = defaultStoreFile(); - let storeSig = storeSignature(storeFile); + // What the agents were last built from: squad.json's content revision. + // Size and mtime can match for different contents (#92). + let storeSig = storeRevision(storeFile); /** From the late transform: hand-authored holders of roster ids, legacy agents hidden, stray ones left. */ let lateReport = { built: /** @type {string[]} */ ([]), @@ -416,7 +418,7 @@ export default { toolsRecorded = true; await ctx.tool.transform(recordTools); } - const sig = storeSignature(storeFile); + const sig = storeRevision(storeFile); if (!force && sig === storeSig) return; storeSig = sig; await ctx.agent.reload(); diff --git a/src/squad-store.js b/src/squad-store.js index 2beb142..70b94e3 100644 --- a/src/squad-store.js +++ b/src/squad-store.js @@ -145,21 +145,6 @@ export function withStoreLock(file, fn) { } } -/** - * The file's change signature: other OpenCode processes write it too (the - * desktop service and a CLI share one config dir). - * - * @param {string} file - */ -export function storeSignature(file) { - try { - const st = fs.statSync(file); - return `${st.mtimeMs}:${st.size}`; - } catch { - return "-"; - } -} - /** * @param {{grunts?: Record, drills?: Record}} roster * @returns {Roster} diff --git a/tests-integration/squad-review.test.js b/tests-integration/squad-review.test.js index a948ab9..34e3181 100644 --- a/tests-integration/squad-review.test.js +++ b/tests-integration/squad-review.test.js @@ -4,6 +4,8 @@ // offers only the drill's tools and enforces its rules; // #88 an agent the user wrote keeps its whole effective definition when the // roster asks for its id, or when a verified legacy file shares its id. +// #92 a roster replaced with equal size and mtime still takes effect on +// the next request; // #91 an unreadable model_data.json never registers a squad agent whose // description silently lacks the owner's rules. // Run: npm run test:integration (Node >= 24) @@ -179,3 +181,32 @@ test("#91: with model_data.json unreadable, the live description says the owner await fs.rm(path.join(configDir(), "model_data.json"), { force: true }); } }, 120_000); + +test("#92: an equal-size roster with the old mtime still takes effect on the next request", async () => { + await writeRoster({ grunts: { "p/m": { variant: "low" } } }); + // A whole second, so it can be put back exactly. + const stamp = new Date("2026-01-01T00:00:00Z"); + await fs.utimes(storeFile(), stamp, stamp); + const live = await withHost( + (h) => + Effect.gen(function* () { + yield* h.llm.serve((request) => + isTitleRequest(request) ? TestLLM.text("Title", "title") : TestLLM.text("ok", "answer"), + ); + yield* oneTurn(h); + const before = (yield* liveAgent(h, "grunt-p-m"))?.model?.variant; + // Another process swaps in an equally long roster, and the + // timestamp ends up where it was. + yield* Effect.promise(async () => { + const text = (await fs.readFile(storeFile(), "utf8")).replace('"low"', '"max"'); + await fs.writeFile(`${storeFile()}.tmp`, text); + await fs.rename(`${storeFile()}.tmp`, storeFile()); + await fs.utimes(storeFile(), stamp, stamp); + }); + yield* oneTurn(h); + return { before, after: (yield* liveAgent(h, "grunt-p-m"))?.model?.variant }; + }), + GLOBAL_ALLOW, + ); + expect(live).toEqual({ before: "low", after: "max" }); +}, 120_000); diff --git a/tests/squad-store.test.js b/tests/squad-store.test.js index 55f604a..c2e4499 100644 --- a/tests/squad-store.test.js +++ b/tests/squad-store.test.js @@ -10,7 +10,6 @@ import { NO_STORE_REVISION, readStore, storeRevision, - storeSignature, withStoreLock, writeStore, } from "../src/squad-store.js"; @@ -27,7 +26,7 @@ afterEach(() => { test("a missing file is no squad, not an error", () => { expect(readStore(file)).toEqual({ state: "missing" }); - expect(storeSignature(file)).toBe("-"); + expect(storeRevision(file)).toBe(NO_STORE_REVISION); }); test("write then read round-trips, keys sorted, with the format version", () => { @@ -44,7 +43,6 @@ test("write then read round-trips, keys sorted, with the format version", () => roster: { grunts: { "a/b": {}, "z/b": { variant: "high" } }, drills: {} }, revision: storeRevision(file), }); - expect(storeSignature(file)).not.toBe("-"); }); test("the revision is of the bytes: any edit changes it, none means no file (#89)", () => { From 353988af5e0a0eda10aabad60ee69ac3f53ffc8b Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:19:44 +0300 Subject: [PATCH 14/17] squad: never take over squad.json.lock; release only our own (#89) Stale-lock recovery removed the lock by path, so a process that saw an abandoned lock could delete the fresh one another process had just taken, and both writers committed. A lock someone else holds is now never removed, however old: the patch is refused, and a lock older than 30 s is named with its holder for the user to delete. Release removes the lock only if it still carries this call's token. Co-Authored-By: Claude Opus 5.5 --- .opencode/lib/squad.js | 13 ++++++- README.md | 4 +- src/squad-store.js | 76 +++++++++++++++++++++++++++----------- tests/plugin-entry.test.js | 32 +++++++++------- tests/squad-store.test.js | 45 ++++++++++++++++------ 5 files changed, 121 insertions(+), 49 deletions(-) diff --git a/.opencode/lib/squad.js b/.opencode/lib/squad.js index 3143bd8..620aacd 100644 --- a/.opencode/lib/squad.js +++ b/.opencode/lib/squad.js @@ -76,6 +76,7 @@ import { } from "../../src/squad-apply.js"; import { defaultStoreFile, + LOCK_OLD_MS, NO_STORE_REVISION, readStore, storeRevision, @@ -899,10 +900,20 @@ export default { return { result }; }); if (locked.busy) { + const holder = locked.holder; + const old = + holder && holder.ageMs > LOCK_OLD_MS + ? ` ${storeFile}.lock has been held for ${Math.round(holder.ageMs / 1000)} s` + + (holder.pid + ? ` by process ${holder.pid}${holder.host ? ` on ${holder.host}` : ""}` + : "") + + ": if no OpenCode process is changing the squad, it was left by one that " + + "crashed, and it is safe to delete. Tell the user; do not delete it yourself." + : ""; return { content: "Refused: another OpenCode process is writing squad.json right now. Nothing " + - "was written. Call squad_dump again and retry with its revision.", + `was written. Call squad_dump again and retry with its revision.${old}`, }; } if ("refused" in locked.value) return { content: locked.value.refused }; diff --git a/README.md b/README.md index 80c8736..d1b7abf 100644 --- a/README.md +++ b/README.md @@ -387,7 +387,9 @@ Three properties make the flow safe, and none is optional: hash of `squad.json`, and `squad_patch` requires it back. If the roster changed since (another session or OpenCode process patched it), the patch is refused and nothing is written, so two edits of one dump cannot undo each - other. The check and the write run under an exclusive `squad.json.lock`. + other. The check and the write run under an exclusive `squad.json.lock`. A + lock held by another process is never taken over: the patch is refused, and a + lock left behind by a crashed process is named so you can delete it. 3. **Apply refuses to delete.** Read-modify-write only protects while the caller actually modifies; one that rebuilds the roster from memory reintroduces the wipe in a new wrapper. So deletions are refused and named — nothing at all is diff --git a/src/squad-store.js b/src/squad-store.js index 70b94e3..7150549 100644 --- a/src/squad-store.js +++ b/src/squad-store.js @@ -101,48 +101,80 @@ function revisionOf(bytes) { return crypto.createHash("sha256").update(bytes).digest("hex").slice(0, 16); } -/** A lock older than this was left by a process that died holding it. */ -const LOCK_STALE_MS = 30_000; +/** A lock held longer than this is worth telling the user about. */ +export const LOCK_OLD_MS = 30_000; /** * Run `fn` holding `.lock`, created exclusively: another OpenCode * process sharing the config dir (the desktop service and a CLI do) cannot * read-check-write the roster at the same time. `fn` must be synchronous; * with no await inside, no other patch of this process interleaves either. - * Busy is reported, not waited out: the caller retries with a fresh dump. + * + * A lock someone else holds is never taken over, however old: removing it by + * path could remove a fresh lock another process has just created, and two + * writers would then both commit (#89). Busy is reported with the holder, and + * the caller declines; a lock left by a crash is for the user to delete. On + * release only the lock this call created is removed. * * @template T * @param {string} file * @param {() => T} fn - * @returns {{busy: true} | {busy: false, value: T}} + * @returns {{busy: true, holder: LockHolder | null} | {busy: false, value: T}} */ export function withStoreLock(file, fn) { const lock = `${file}.lock`; fs.mkdirSync(path.dirname(file), { recursive: true }); + const token = crypto.randomUUID(); let fd; - for (let attempt = 0; attempt < 2 && fd === undefined; attempt++) { - try { - fd = fs.openSync(lock, "wx"); - } catch (e) { - if (/** @type {NodeJS.ErrnoException} */ (e)?.code !== "EEXIST") throw e; - let age = 0; - try { - age = Date.now() - fs.statSync(lock).mtimeMs; - } catch { - // Released meanwhile: try again. - } - if (age <= LOCK_STALE_MS) return { busy: true }; - fs.rmSync(lock, { force: true }); - } + try { + fd = fs.openSync(lock, "wx"); + } catch (e) { + if (/** @type {NodeJS.ErrnoException} */ (e)?.code !== "EEXIST") throw e; + return { busy: true, holder: lockHolder(lock) }; } - if (fd === undefined) return { busy: true }; try { - fs.writeSync(fd, String(process.pid)); + fs.writeSync(fd, JSON.stringify({ pid: process.pid, host: os.hostname(), token })); + fs.closeSync(fd); + fd = undefined; return { busy: false, value: fn() }; } finally { - fs.closeSync(fd); - fs.rmSync(lock, { force: true }); + if (fd !== undefined) fs.closeSync(fd); + try { + if (JSON.parse(fs.readFileSync(lock, "utf8"))?.token === token) fs.rmSync(lock); + } catch { + // Gone already, or not ours: leave it. + } + } +} + +/** + * @typedef {{pid: number | null, host: string | null, ageMs: number}} LockHolder + */ + +/** + * Who holds a lock, as far as its file says. + * + * @param {string} lock + * @returns {LockHolder | null} null when it vanished meanwhile + */ +function lockHolder(lock) { + let ageMs; + try { + ageMs = Date.now() - fs.statSync(lock).mtimeMs; + } catch { + return null; + } + let owner = {}; + try { + owner = JSON.parse(fs.readFileSync(lock, "utf8")) ?? {}; + } catch { + // Being written, or not ours to read: age alone. } + return { + pid: typeof owner.pid === "number" ? owner.pid : null, + host: typeof owner.host === "string" ? owner.host : null, + ageMs, + }; } /** diff --git a/tests/plugin-entry.test.js b/tests/plugin-entry.test.js index 1ae4076..7775fca 100644 --- a/tests/plugin-entry.test.js +++ b/tests/plugin-entry.test.js @@ -553,22 +553,28 @@ test("squad.json locked by another process: the patch writes nothing and says so const { tools, dispose } = await setupHost({ directory }); const lock = `${defaultStoreFile()}.lock`; fs.mkdirSync(path.dirname(lock), { recursive: true }); - fs.writeFileSync(lock, "4242"); - const patch = () => - tools.get("squad_patch").execute( - { revision: storeRevision(defaultStoreFile()), grunts: { "p/a": {} } }, - { - agent: "build", - }, - ); + const text = JSON.stringify({ pid: 4242, host: "h", token: "t" }); + fs.writeFileSync(lock, text); + const patch = async () => + ( + await tools.get("squad_patch").execute( + { revision: storeRevision(defaultStoreFile()), grunts: { "p/a": {} } }, + { + agent: "build", + }, + ) + ).content; try { - expect((await patch()).content).toContain("another OpenCode process is writing squad.json"); - expect(readStore(defaultStoreFile()).state).toBe("missing"); - // A lock left by a process that died long ago is taken over. + expect(await patch()).toContain("another OpenCode process is writing squad.json"); + // Old: still not taken over, but the user is told which file to delete. const old = new Date(Date.now() - 120_000); fs.utimesSync(lock, old, old); - expect((await patch()).content).toContain("+1 added"); - expect(fs.existsSync(lock)).toBe(false); + const stale = await patch(); + expect(stale).toContain(`${lock} has been held for`); + expect(stale).toContain("process 4242"); + expect(stale).toContain("safe to delete"); + expect(fs.readFileSync(lock, "utf8")).toBe(text); + expect(readStore(defaultStoreFile()).state).toBe("missing"); } finally { dispose(); fs.rmSync(lock, { force: true }); diff --git a/tests/squad-store.test.js b/tests/squad-store.test.js index c2e4499..9893cf5 100644 --- a/tests/squad-store.test.js +++ b/tests/squad-store.test.js @@ -58,25 +58,46 @@ test("the revision is of the bytes: any edit changes it, none means no file (#89 fs.chmodSync(file, 0o600); }); -test("withStoreLock: exclusive, released after, busy while held, stale taken over", () => { +test("withStoreLock: exclusive while held, released after, even after a throw", () => { const lock = `${file}.lock`; - // Held while the body runs: the lock names this process. - expect(withStoreLock(file, () => fs.readFileSync(lock, "utf8"))).toEqual({ - busy: false, - value: String(process.pid), - }); + // Held while the body runs, by this process. + const held = withStoreLock(file, () => JSON.parse(fs.readFileSync(lock, "utf8"))); + expect(held).toMatchObject({ busy: false, value: { pid: process.pid } }); expect(() => withStoreLock(file, () => { throw new Error("boom"); }), ).toThrow("boom"); - // Released both times, even after a throw: an exclusive create succeeds, - // and stands in for another process holding it. + // Released both times: an exclusive create succeeds. fs.closeSync(fs.openSync(lock, "wx")); - expect(withStoreLock(file, () => 1)).toEqual({ busy: true }); - const old = new Date(Date.now() - 60_000); - fs.utimesSync(lock, old, old); - expect(withStoreLock(file, () => 2)).toEqual({ busy: false, value: 2 }); +}); + +test("a lock is never taken over, however old or whoever held it (#89)", () => { + const lock = `${file}.lock`; + const old = new Date(Date.now() - 600_000); + // A process that is gone, and one that is alive (this one) but slow. + for (const pid of [2 ** 22 + 12345, process.pid]) { + const text = JSON.stringify({ pid, host: "h", token: "theirs" }); + fs.writeFileSync(lock, text); + fs.utimesSync(lock, old, old); + const out = withStoreLock(file, () => "entered"); + expect(out).toMatchObject({ busy: true, holder: { pid } }); + expect(out.holder.ageMs).toBeGreaterThan(500_000); + expect(fs.readFileSync(lock, "utf8")).toBe(text); + } + fs.rmSync(lock); +}); + +test("release removes only the lock this call created (#89)", () => { + const lock = `${file}.lock`; + const other = JSON.stringify({ pid: 1, host: "h", token: "someone else" }); + withStoreLock(file, () => { + // Someone deleted ours and took the path meanwhile. + fs.rmSync(lock); + fs.writeFileSync(lock, other); + }); + expect(fs.readFileSync(lock, "utf8")).toBe(other); + fs.rmSync(lock); }); test.each([ From 188f824904e75752111dc0930e498dfdfb8836ac Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:25:39 +0300 Subject: [PATCH 15/17] squad: a legacy file owns an id only if the live agent is that file, field for field (#88) Model and prompt equality could not tell the generated file from a project agent that copied them and changed its description or variant, so an empty roster hid the user's agent. The live agent must now equal what the host builds from the file alone: the host's fresh-agent defaults (seen by the early transform), the file's fields, and the rules (as a multiset: later transforms such as the browser plugin's append after the file's own). Only the last generator's format is modelled; any other file is never treated as the live agent and the dump says to delete it. The probe's id is now random per plugin instance, so a user's agent named opencode-squad-probe is no longer merged into it and removed. Co-Authored-By: Claude Opus 5.5 --- .opencode/lib/squad.js | 23 +++++-- README.md | 2 +- src/squad-agents.js | 89 ++++++++++++++++++++------ src/squad-apply.js | 86 ++++++++++++++++++++++--- tests-integration/squad-review.test.js | 49 +++++++++++++- tests/plugin-entry.test.js | 4 +- tests/squad-agents.test.js | 87 ++++++++++++++++++++----- tests/squad-apply.test.js | 48 +++++++++++--- 8 files changed, 322 insertions(+), 66 deletions(-) diff --git a/.opencode/lib/squad.js b/.opencode/lib/squad.js index 620aacd..f73cfd8 100644 --- a/.opencode/lib/squad.js +++ b/.opencode/lib/squad.js @@ -65,7 +65,7 @@ import { endsWithRoleRules, isLegacyFile, lateTransform, - PROBE_ID, + newProbeId, rosterCollisions, } from "../../src/squad-agents.js"; import { @@ -244,6 +244,7 @@ export default { let storeSig = storeRevision(storeFile); /** From the late transform: hand-authored holders of roster ids, legacy agents hidden, stray ones left. */ let lateReport = { + globals: /** @type {Array<{action: string, resource: string, effect: string}>} */ ([]), built: /** @type {string[]} */ ([]), foreign: /** @type {string[]} */ ([]), hidden: /** @type {string[]} */ ([]), @@ -295,9 +296,14 @@ export default { }, }); }; + // This instance's probe: its own id, and what the early transform saw. + const probe = { + id: newProbeId(), + seen: /** @type {{defaults?: Record}} */ ({}), + }; await ctx.agent.transform((editor) => { try { - earlyTransform(editor); + earlyTransform(editor, probe.id, probe.seen); } catch { // The late transform then finds no probe and adds no global rules. } @@ -313,7 +319,9 @@ export default { for (const id of lateReport.kept) { notes.push( `${id}: an agent file from an earlier version has this id, but the agent OpenCode ` + - "loaded here is another one (a project's own?), so it is left as is", + "loaded here is not exactly that file (another agent, a project's own perhaps, or a " + + "file in a format this version cannot verify), so it is left as is. If it is the " + + "old squad file, the user may delete it", ); } const store = readStore(storeFile); @@ -361,9 +369,9 @@ export default { // An unreadable squad.json registers nothing and hides nothing: // legacy agent files, if any, keep working until it is fixed. const specs = specsNow(); - if (specs) lateReport = lateTransform(editor, specs, legacyAgents); + if (specs) lateReport = lateTransform(editor, specs, legacyAgents, probe); else { - editor.remove(PROBE_ID); + editor.remove(probe.id); lateReport = { ...lateReport, built: [] }; } } catch { @@ -884,7 +892,10 @@ export default { if ( agent && !lateReport.built.includes(id) && - !isLegacyFile(agent, legacyAgents.get(id)) + !isLegacyFile(agent, legacyAgents.get(id), { + defaults: probe.seen.defaults, + globals: lateReport.globals, + }) ) { foreign.push({ id, agent: `${role} ${modelId}` }); } diff --git a/README.md b/README.md index d1b7abf..8d1e3ea 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,7 @@ openai/gpt-5.5 → grunt-openai-gpt-5-5 (executor: edit/shell) Each squad agent shares the bundled grunt/drill prompt and permissions, differs only in `model`, and is `hidden` (dispatched via `subagent`, not in the `@`-menu). They appear in the orchestrator's inventory **with their models and capability summary**, which makes routing concrete. A `squad_patch` applies to the next dispatch, without a restart, and another OpenCode process sharing the config dir picks the change up on its next request. The role prompt comes from `prompts/.md` and is refreshed on every request, so editing it takes effect immediately. Hand-authored agents are never touched. -**Upgrading from file-based squads (before #85).** On first start the plugin imports the generated `grunt-*`/`drill-*`/`worker-*` files from `~/.config/opencode/agent/` into `squad.json`, once. The files are left in place: where the agent OpenCode loaded at an id is that very file (same prompt and model), the plugin's agent takes the id over, and generated agents the roster no longer has are hidden. If another agent holds the id, say a project's own file, it is left alone and `squad_dump` says so. `squad_dump` lists the leftovers, and you may delete them. If a generated file cannot be read, nothing is imported and `squad_dump` says which file to fix. +**Upgrading from file-based squads (before #85).** On first start the plugin imports the generated `grunt-*`/`drill-*`/`worker-*` files from `~/.config/opencode/agent/` into `squad.json`, once. The files are left in place: where the agent OpenCode loaded at an id is exactly that file, every field equal to what the file alone gives, the plugin's agent takes the id over, and generated agents the roster no longer has are hidden. If another agent holds the id, say a project's own file, or the file is in an older format this version cannot reproduce exactly, it is left alone and `squad_dump` says so; delete such an old file to let the squad take the id. `squad_dump` lists the leftovers, and you may delete them. If a generated file cannot be read, nothing is imported and `squad_dump` says which file to fix. **Drill permissions.** Each squad agent gets your global `permissions` first and its role's rules last, so with OpenCode's last-match evaluation a drill stays read-only even when your global config allows everything, and the host hides from it every tool its rules deny. To get that order the plugin builds the squad's agents after OpenCode's own config has been applied; until then they do not exist, so an early request for one fails instead of running with the wrong rules. Each request a squad agent makes is checked once more: if the role's rules are no longer last, they are put back and the request's tools are cut to what the role allows. diff --git a/src/squad-agents.js b/src/squad-agents.js index 203b886..a4db052 100644 --- a/src/squad-agents.js +++ b/src/squad-agents.js @@ -27,12 +27,19 @@ // that id IS that file (same prompt and model). Any other agent at a squad id // belongs to the user and is left exactly as the host built it. +import crypto from "node:crypto"; + import { findPromptFence, placeholderBody, wrapPrompt } from "./prompt-inject.js"; import { NOTES_CLOSE, NOTES_OPEN, ROLE_KEYS } from "./roster.js"; import { roleRules, slugForModel, squadRoleOf } from "./workers.js"; -/** The throwaway agent the early transform creates for the late one to read. */ -export const PROBE_ID = "opencode-squad-probe"; +/** + * The throwaway agent the early transform creates for the late one to read: + * a fresh id per plugin instance, so no agent of the user's can hold it. + */ +export function newProbeId() { + return `opencode-squad-probe-${crypto.randomUUID().slice(0, 12)}`; +} /** Marks where the probe's own rules end and the global ones begin. */ const PROBE_MARK = Object.freeze({ action: "opencode-squad-probe", resource: "*", effect: "deny" }); @@ -41,8 +48,10 @@ const PROBE_MARK = Object.freeze({ action: "opencode-squad-probe", resource: "*" * @typedef {{id: string, role: "grunt"|"drill", modelId: string, description: string, * system: string, model: {id: string, providerID: string, variant?: string}, * steps?: number, permissions: Rule[]}} AgentSpec - * @typedef {{system: string, modelId: string}} LegacyAgent - * a generated file from the global agent dir, as the host would load it + * @typedef {{definition: import("./squad-apply.js").LegacyDefinition | null}} LegacyAgent + * a generated file from the global agent dir, as the host builds it alone + * @typedef {{defaults?: Record}} ProbeSeen + * defaults: a fresh agent as the host creates one, seen by the early transform */ /** @@ -129,9 +138,12 @@ export function isSquadSystem(system) { * own rules deny everything, so it cannot run in the moment it exists. * * @param {{update: (id: string, f: (agent: any) => void) => void}} editor + * @param {string} probeId + * @param {ProbeSeen} [seen] receives the host's fresh-agent defaults */ -export function earlyTransform(editor) { - editor.update(PROBE_ID, (agent) => { +export function earlyTransform(editor, probeId, seen = {}) { + editor.update(probeId, (agent) => { + seen.defaults = JSON.parse(JSON.stringify(agent)); agent.mode = "primary"; agent.hidden = true; agent.description = "opencode-squad internal probe; removed before any request"; @@ -158,21 +170,51 @@ function globalRules(probe) { return mark === -1 ? [] : rules.slice(mark + 1).map((/** @type {Rule} */ r) => ({ ...r })); } +/** JSON with object keys sorted, for comparing definitions. @param {unknown} v */ +function canonical(v) { + return JSON.stringify(v, (_k, x) => + x && typeof x === "object" && !Array.isArray(x) + ? Object.fromEntries( + Object.keys(x) + .sort() + .map((k) => [k, x[k]]), + ) + : x, + ); +} + /** - * Whether the live agent at an id is exactly the legacy file there: the host + * Whether the live agent at an id IS the legacy file there: equal, field for + * field, to what the host builds from that file alone (fresh defaults, the + * file's fields, then the global rules and the file's own rules). The host * loads agents from several config dirs, and another one may hold the id - * (#88). Verifying the file proves we own the file, not the id. + * with any field changed (#88); verifying the file proves we own the file, + * not the id. Without the host's defaults or a reproducible file, never. * * @param {any} agent * @param {LegacyAgent | undefined} file + * @param {{defaults?: Record, globals: Rule[]}} host */ -export function isLegacyFile(agent, file) { - if (!file || !agent) return false; - const model = agent.model ? `${agent.model.providerID}/${agent.model.id}` : ""; - const system = String(agent.system ?? "") - .replaceAll("\r\n", "\n") - .trim(); - return system === file.system && model === file.modelId; +export function isLegacyFile(agent, file, { defaults, globals }) { + const def = file?.definition; + if (!def || !agent || !defaults) return false; + const { id: _i, name: _n, ...base } = /** @type {Record} */ (defaults); + const expected = { + ...base, + ...def.fields, + permissions: [.../** @type {any[]} */ (base.permissions ?? []), ...globals, ...def.permissions], + }; + const { id: _a, name: _b, ...live } = agent; + // Rules as a multiset: transforms after the config plugin (the browser + // plugin's deny, on 2.1.3) append to every agent, so on a file agent they + // land after the file's own rules, and on the probe before. A user's file + // cannot reorder rules without changing them. + /** @param {any} a */ + const rules = (a) => (Array.isArray(a.permissions) ? a.permissions : []).map(canonical).sort(); + return ( + canonical({ ...live, permissions: rules(live) }) === + canonical({ ...expected, permissions: rules(expected) }) + ); } /** @@ -202,7 +244,10 @@ function build(agent, spec, globals) { * marker (src/squad-apply.js readLegacySquad). Files from before the * role-prompt fence, and every `worker-*`, are only recognisable this way: * the marker is a YAML comment the host never exposes. - * @returns {{built: string[], foreign: string[], hidden: string[], stray: string[], kept: string[]}} + * @param {{id: string, seen: ProbeSeen}} [probe] this instance's probe and + * what the early transform saw + * @returns {{globals: Rule[], built: string[], foreign: string[], hidden: string[], stray: string[], kept: string[]}} + * globals: the user's global rules, read off the probe; * built: the squad agents this transform created: the only ones the * plugin polices per request; * foreign: roster ids another agent already holds (left alone); @@ -212,9 +257,10 @@ function build(agent, spec, globals) { * kept: ids of legacy files the roster dropped, where another agent the * host loaded holds the id (left alone) */ -export function lateTransform(editor, specs, legacy = new Map()) { - const globals = globalRules(editor.get(PROBE_ID)); - editor.remove(PROBE_ID); +export function lateTransform(editor, specs, legacy = new Map(), probe = { id: "", seen: {} }) { + const globals = globalRules(editor.get(probe.id)); + editor.remove(probe.id); + const host = { defaults: probe.seen.defaults, globals }; const wanted = new Map(specs.map((s) => [s.id, s])); /** @type {string[]} */ const foreign = []; @@ -230,7 +276,7 @@ export function lateTransform(editor, specs, legacy = new Map()) { const id = String(agent?.id ?? ""); if (wanted.has(id)) continue; if (legacy.has(id)) { - if (isLegacyFile(agent, legacy.get(id))) { + if (isLegacyFile(agent, legacy.get(id), host)) { editor.remove(id); hidden.push(id); } else { @@ -243,7 +289,7 @@ export function lateTransform(editor, specs, legacy = new Map()) { for (const spec of specs) { const current = editor.get(spec.id); if (current) { - if (!isLegacyFile(current, legacy.get(spec.id))) { + if (!isLegacyFile(current, legacy.get(spec.id), host)) { foreign.push(spec.id); continue; } @@ -254,6 +300,7 @@ export function lateTransform(editor, specs, legacy = new Map()) { built.push(spec.id); } return { + globals, built: built.sort(), foreign: foreign.sort(), hidden: hidden.sort(), diff --git a/src/squad-apply.js b/src/squad-apply.js index 63806ea..b2ebadc 100644 --- a/src/squad-apply.js +++ b/src/squad-apply.js @@ -34,16 +34,16 @@ export function defaultAgentDir() { * * @param {string} dir * @returns {{roster: Record>, problems: string[], files: string[], - * agents: Array<{id: string, system: string, modelId: string}>}} - * agents: each file as the host would load it (its prompt is the body, - * trimmed), so the plugin can tell whether the live agent at that id is - * this file or another agent the host loaded from elsewhere (#88) + * agents: Array<{id: string, definition: LegacyDefinition | null}>}} + * agents: each file's agent as the host builds it from that file alone, or + * null for a shape that cannot be reproduced exactly; the plugin compares it + * to the live agent to tell this file from another agent at the id (#88) */ export function readLegacySquad(dir) { const parsed = []; /** @type {string[]} */ const files = []; - /** @type {Array<{id: string, system: string, modelId: string}>} */ + /** @type {Array<{id: string, definition: LegacyDefinition | null}>} */ const agents = []; /** @type {string[]} */ const problems = []; @@ -73,16 +73,82 @@ export function readLegacySquad(dir) { // Legacy `worker-` files predate the grunt/drill split: the executor. parsed.push({ role: m[1] === "worker" ? "grunt" : m[1], modelId, entry }); files.push(name); - agents.push({ - id: name.replace(/\.md$/, ""), - system: readFrontmatter(text).body.replaceAll("\r\n", "\n").trim(), - modelId, - }); + agents.push({ id: name.replace(/\.md$/, ""), definition: legacyDefinition(text) }); } const { roster, conflicts } = buildRoster(parsed); return { roster, problems: [...problems, ...conflicts], files, agents }; } +/** + * @typedef {{fields: Record, permissions: Array>}} LegacyDefinition + * fields: the agent fields the file sets, as OpenCode 2.1.3's config-agent + * plugin applies them; permissions: the file's own rules + */ + +/** Frontmatter keys of the last generated format, and nothing else. */ +const LEGACY_KEYS = new Set([ + "description", + "mode", + "model", + "variant", + "steps", + "hidden", + "permissions", +]); + +/** + * What the host builds from a generated file alone, for the format the last + * file-writing version produced (and older files using only its keys). + * Anything else (a `permission`/`tools` map, a key this does not model, a + * disabled agent) cannot be reproduced exactly: null, and the plugin then + * never treats the live agent at that id as this file. + * + * @param {string} text + * @returns {LegacyDefinition | null} + */ +function legacyDefinition(text) { + const fm = readFrontmatter(text); + if (fm.state !== "ok") return null; + const f = fm.fields; + if (Object.keys(f).some((k) => !LEGACY_KEYS.has(k))) return null; + if (typeof f.model !== "string" || !f.model.trim()) return null; + // `model: p/m#v`, or `variant:` folded into it, as the host's decode does. + let ref = f.model.trim(); + if (!ref.includes("#") && typeof f.variant === "string" && /^[^#]+$/.test(f.variant)) { + ref = `${ref}#${f.variant}`; + } else if (f.variant !== undefined && !ref.includes("#")) return null; + const [path0, variant] = ref.split("#"); + const slash = path0.indexOf("/"); + if (slash <= 0) return null; + /** @type {Record} */ + const fields = { + system: fm.body.trim(), + model: { + id: path0.slice(slash + 1), + providerID: path0.slice(0, slash), + ...(variant ? { variant } : {}), + }, + }; + for (const key of ["description", "mode", "hidden", "steps"]) { + if (f[key] !== undefined) fields[key] = f[key]; + } + const permissions = f.permissions ?? []; + if (!Array.isArray(permissions)) return null; + if ( + permissions.some( + (r) => + !r || + typeof r !== "object" || + Object.keys(r).sort().join() !== "action,effect,resource" || + String(r.resource).startsWith("~") || + String(r.resource).startsWith("$HOME"), + ) + ) { + return null; + } + return { fields, permissions: permissions.map((r) => ({ ...r })) }; +} + /** * @typedef {{ok: true, diff: ReturnType}} PatchOk * @typedef {{ok: false, refusal: "remove" | "foreign", problems: string[], diff: ReturnType}} PatchRefused diff --git a/tests-integration/squad-review.test.js b/tests-integration/squad-review.test.js index 34e3181..2a1089b 100644 --- a/tests-integration/squad-review.test.js +++ b/tests-integration/squad-review.test.js @@ -121,7 +121,7 @@ test("#88: a hand-authored agent holding a roster id keeps its whole effective d expect(claimed).toEqual(alone); }, 180_000); -/** An agent file as versions before #85 generated it. */ +/** An agent file exactly as the last file-writing version (0.5) generated it. */ const legacy = (role, modelId) => [ "---", @@ -129,6 +129,9 @@ const legacy = (role, modelId) => 'description: "stale description"', "mode: subagent", `model: ${modelId}`, + "hidden: true", + "permissions:", + ' - {"action":"edit","resource":"*","effect":"deny"}', "---", "", ``, @@ -210,3 +213,47 @@ test("#92: an equal-size roster with the old mtime still takes effect on the nex ); expect(live).toEqual({ before: "low", after: "max" }); }, 120_000); + +test("#88: a project agent with the legacy file's model and prompt but its own fields is left alone", async () => { + const mine = legacy("drill", "old/m#high").replace('"stale description"', '"mine"'); + const files = async (project) => { + await fs.mkdir(path.join(configDir(), "agent"), { recursive: true }); + await fs.writeFile(path.join(configDir(), "agent", "drill-old-m.md"), legacy("drill", "old/m")); + await fs.mkdir(path.join(project, "agent"), { recursive: true }); + await fs.writeFile(path.join(project, "agent", "drill-old-m.md"), mine); + }; + const alone = await definitionWith(null, "drill-old-m", async (project) => { + await files(project); + await fs.writeFile(storeFile(), "{"); + }); + expect(alone).toMatchObject({ description: "mine", model: { variant: "high" } }); + expect(await definitionWith({}, "drill-old-m", files)).toEqual(alone); +}, 180_000); + +test("#88: the plugin still recognises its own legacy file: hidden with an empty roster", async () => { + const files = async (project) => { + for (const dir of [path.join(configDir(), "agent"), path.join(project, "agent")]) { + await fs.mkdir(dir, { recursive: true }); + await fs.writeFile(path.join(dir, "drill-old-m.md"), legacy("drill", "old/m#high")); + } + }; + const alone = await definitionWith(null, "drill-old-m", async (project) => { + await files(project); + await fs.writeFile(storeFile(), "{"); + }); + expect(alone?.model).toMatchObject({ providerID: "old", id: "m", variant: "high" }); + expect(await definitionWith({}, "drill-old-m", files)).toBeUndefined(); +}, 180_000); + +test("#88: a hand-authored agent named like the plugin's probe is left intact", async () => { + const files = async (project) => { + await fs.mkdir(path.join(project, "agent"), { recursive: true }); + await fs.writeFile(path.join(project, "agent", "opencode-squad-probe.md"), HAND); + }; + const alone = await definitionWith(null, "opencode-squad-probe", async (project) => { + await files(project); + await fs.writeFile(storeFile(), "{"); + }); + expect(alone?.system).toContain("HAND-WRITTEN PROMPT"); + expect(await definitionWith({}, "opencode-squad-probe", files)).toEqual(alone); +}, 180_000); diff --git a/tests/plugin-entry.test.js b/tests/plugin-entry.test.js index 7775fca..fb0d468 100644 --- a/tests/plugin-entry.test.js +++ b/tests/plugin-entry.test.js @@ -592,7 +592,9 @@ test("no squad agent exists before the late transform; the prompt hook puts it i const { registered, hooks, dispose } = await setupHost({ directory, globals: [ALLOW_ALL] }); try { // Only the probe: a request for the drill fails as an unknown agent. - expect(registered().map((a) => a.id)).toEqual(["opencode-squad-probe"]); + expect(registered().map((a) => a.id)).toEqual([ + expect.stringMatching(/^opencode-squad-probe-/), + ]); await hooks.get("prompt")({ sessionID: "s" }); const drill = registered().find((a) => a.id === "drill-a-b"); expect(registered().map((a) => a.id)).toEqual(["drill-a-b"]); diff --git a/tests/squad-agents.test.js b/tests/squad-agents.test.js index 025235b..7e6c49b 100644 --- a/tests/squad-agents.test.js +++ b/tests/squad-agents.test.js @@ -14,7 +14,7 @@ import { endsWithRoleRules, isSquadSystem, lateTransform, - PROBE_ID, + newProbeId, rosterCollisions, } from "../src/squad-agents.js"; import { roleRules } from "../src/workers.js"; @@ -106,10 +106,15 @@ function editorOf(agents) { }; } +const PROBE = "opencode-squad-probe-test"; +/** A fresh agent as the fake host creates one. */ +const DEFAULTS = { permissions: [] }; + /** @param {{files?: any[], specs: any[], legacy?: Map, globals?: any[]}} run */ function hostOrder({ files = [], specs, legacy, globals = [GLOBAL] }) { const editor = editorOf([]); - earlyTransform(editor); + const probe = { id: PROBE, seen: {} }; + earlyTransform(editor, probe.id, probe.seen); for (const a of editor.list()) a.permissions.push(...globals.map((r) => ({ ...r }))); for (const file of files) { editor.update(file.id, (a) => { @@ -117,15 +122,17 @@ function hostOrder({ files = [], specs, legacy, globals = [GLOBAL] }) { a.permissions = [...(a.permissions ?? []), ...globals, ...(file.permissions ?? [])]; }); } - const report = lateTransform(editor, specs, legacy); + const report = lateTransform(editor, specs, legacy, probe); return { editor, report }; } -test("early: only the probe, which cannot be dispatched or selected", () => { +test("early: only the probe, which cannot be dispatched or selected; host defaults seen", () => { const editor = editorOf([]); - earlyTransform(editor); - expect(editor.list().map((a) => a.id)).toEqual([PROBE_ID]); - const probe = editor.get(PROBE_ID); + const seen = {}; + earlyTransform(editor, PROBE, seen); + expect(seen.defaults).toEqual({ id: PROBE, ...DEFAULTS }); + expect(editor.list().map((a) => a.id)).toEqual([PROBE]); + const probe = editor.get(PROBE); // The subagent tool refuses a primary agent; a hidden one is never selected. expect(probe).toMatchObject({ mode: "primary", hidden: true, system: "" }); expect(probe.permissions[0]).toEqual({ action: "*", resource: "*", effect: "deny" }); @@ -134,7 +141,7 @@ test("early: only the probe, which cannot be dispatched or selected", () => { test("late: built from a fresh default — global rules, then role rules last; probe removed", () => { const specs = agentSpecs({ drills: { "a/b": { variant: "max" } } }, io); const { editor } = hostOrder({ specs }); - expect(editor.get(PROBE_ID)).toBeUndefined(); + expect(editor.get(PROBE)).toBeUndefined(); expect(editor.get("drill-a-b")).toEqual({ id: "drill-a-b", mode: "subagent", @@ -166,7 +173,21 @@ const legacyFile = (id, modelId, system) => { model: { providerID, id: rest.join("/") }, permissions: [{ action: "edit", resource: "*", effect: "allow" }], }, - seen: [id, { id, system, modelId }], + seen: [ + id, + { + definition: { + fields: { + system, + description: "stale", + color: "#ff0000", + steps: 7, + model: { providerID, id: rest.join("/") }, + }, + permissions: [{ action: "edit", resource: "*", effect: "allow" }], + }, + }, + ], }; }; @@ -174,7 +195,14 @@ test("late: a same-id legacy file is rebuilt from scratch, none of its fields ke const specs = agentSpecs({ drills: { "a/b": {} } }, io); const old = legacyFile("drill-a-b", "a/b", "an old inlined prompt"); const { editor, report } = hostOrder({ specs, files: [old.live], legacy: new Map([old.seen]) }); - expect(report).toEqual({ built: ["drill-a-b"], foreign: [], hidden: [], stray: [], kept: [] }); + expect(report).toEqual({ + globals: [GLOBAL], + built: ["drill-a-b"], + foreign: [], + hidden: [], + stray: [], + kept: [], + }); const agent = editor.get("drill-a-b"); expect(agent).not.toHaveProperty("color"); expect(agent).not.toHaveProperty("steps"); @@ -223,6 +251,7 @@ test("late: verified legacy agents the roster dropped are hidden, worker- includ legacy: new Map([drill.seen, worker.seen]), }); expect(report).toEqual({ + globals: [GLOBAL], built: ["grunt-a-b"], foreign: [], hidden: ["drill-old-model", "worker-old-model"], @@ -237,14 +266,38 @@ test("late: verified legacy agents the roster dropped are hidden, worker- includ ]); }); -test("a legacy file matches the live agent across CRLF and surrounding blank lines", () => { - const old = legacyFile("grunt-a-b", "a/b", "line one\nline two"); - const { report } = hostOrder({ - specs: agentSpecs({ grunts: { "a/b": {} } }, io), - files: [{ ...old.live, system: "\nline one\r\nline two\n" }], - legacy: new Map([old.seen]), +test("a legacy id whose live agent differs from the file in any field is not ours (#88)", () => { + const old = legacyFile("drill-old-m", "old/m", "stale body"); + const variants = [ + { description: "mine" }, + { model: { ...old.live.model, variant: "high" } }, + { temperature: 0.2 }, + { permissions: [{ action: "bash", resource: "*", effect: "allow" }] }, + ]; + for (const change of variants) { + const { editor, report } = hostOrder({ + specs: [], + files: [{ ...old.live, ...change }], + legacy: new Map([old.seen]), + }); + expect(report.kept).toEqual(["drill-old-m"]); + expect(editor.get("drill-old-m")).toBeDefined(); + } + // Exactly the file: hidden. + const same = hostOrder({ specs: [], files: [old.live], legacy: new Map([old.seen]) }); + expect(same.report.hidden).toEqual(["drill-old-m"]); + // A file this version cannot reproduce is never treated as the live agent. + const unknown = hostOrder({ + specs: [], + files: [old.live], + legacy: new Map([["drill-old-m", { definition: null }]]), }); - expect(report.foreign).toEqual([]); + expect(unknown.report.kept).toEqual(["drill-old-m"]); +}); + +test("each instance has its own probe id", () => { + expect(newProbeId()).toMatch(/^opencode-squad-probe-[0-9a-f-]{12}$/); + expect(newProbeId()).not.toBe(newProbeId()); }); test("endsWithRoleRules: global rules appended after the role's are caught", () => { diff --git a/tests/squad-apply.test.js b/tests/squad-apply.test.js index d5d35ac..c9532aa 100644 --- a/tests/squad-apply.test.js +++ b/tests/squad-apply.test.js @@ -116,15 +116,45 @@ test("readLegacySquad imports generated files only, worker- as a grunt", () => { }); expect(out.files).toEqual(["drill-a-one.md", "grunt-a-one.md", "worker-a-two.md"]); expect(out.problems).toEqual([]); - // Each as the host would load it: the body is the prompt, the model without - // its variant, for telling this file from another agent at the id (#88). - expect(out.agents.map((a) => [a.id, a.modelId])).toEqual([ - ["drill-a-one", "a/one"], - ["grunt-a-one", "a/one"], - ["worker-a-two", "a/two"], - ]); - const body = fs.readFileSync(path.join(dir, "grunt-a-one.md"), "utf8").split(/^---$/m)[2].trim(); - expect(out.agents[1].system).toBe(body); + // Each as the host builds it from the file alone, for telling this file + // from another agent at the id (#88). + expect(out.agents.map((a) => a.id)).toEqual(["drill-a-one", "grunt-a-one", "worker-a-two"]); + expect(out.agents[1].definition?.fields.model).toEqual({ + providerID: "a", + id: "one", + variant: "high", + }); +}); + +test("legacy definitions: the last generator's format exactly, anything else unverifiable", () => { + const write = (name, text) => fs.writeFileSync(path.join(dir, name), text); + const head = "---\n# generated-by: opencode-squad squad-draft\n"; + write( + "drill-a-b.md", + `${head}description: "d"\nmode: subagent\nmodel: a/b\nvariant: max\nsteps: 4\nhidden: true\n` + + 'permissions:\n - {"action":"edit","resource":"*","effect":"deny"}\n---\n\nbody\n', + ); + write("drill-c-d.md", `${head}model: c/d\npermission:\n edit: deny\n---\nbody\n`); + write("drill-e-f.md", `${head}model: e/f\ntemperature: 0.1\n---\nbody\n`); + write( + "drill-g-h.md", + `${head}model: g/h\npermissions:\n - {"action":"read","resource":"~/x","effect":"deny"}\n---\nb\n`, + ); + const defs = Object.fromEntries(readLegacySquad(dir).agents.map((a) => [a.id, a.definition])); + expect(defs["drill-a-b"]).toEqual({ + fields: { + system: "body", + description: "d", + mode: "subagent", + hidden: true, + steps: 4, + model: { providerID: "a", id: "b", variant: "max" }, + }, + permissions: [{ action: "edit", resource: "*", effect: "deny" }], + }); + expect(defs["drill-c-d"]).toBeNull(); + expect(defs["drill-e-f"]).toBeNull(); + expect(defs["drill-g-h"]).toBeNull(); }); test("readLegacySquad reads CRLF files and keeps notes", () => { From fdd1bb9f851f3c20af7b5347c8838e6aa31fbf8b Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:29:29 +0300 Subject: [PATCH 16/17] squad-store: lock ownership by descriptor; fix the holder's types (CodeQL, tsc) Release no longer reads the lock back by path: the descriptor it was created with still being linked means it is still ours at the path. The holder is read through one descriptor, so its age and owner are of the same file. Co-Authored-By: Claude Opus 5.5 --- src/squad-store.js | 48 +++++++++++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/src/squad-store.js b/src/squad-store.js index 7150549..2972952 100644 --- a/src/squad-store.js +++ b/src/squad-store.js @@ -124,7 +124,6 @@ export const LOCK_OLD_MS = 30_000; export function withStoreLock(file, fn) { const lock = `${file}.lock`; fs.mkdirSync(path.dirname(file), { recursive: true }); - const token = crypto.randomUUID(); let fd; try { fd = fs.openSync(lock, "wx"); @@ -133,17 +132,15 @@ export function withStoreLock(file, fn) { return { busy: true, holder: lockHolder(lock) }; } try { - fs.writeSync(fd, JSON.stringify({ pid: process.pid, host: os.hostname(), token })); - fs.closeSync(fd); - fd = undefined; + fs.writeSync(fd, JSON.stringify({ pid: process.pid, host: os.hostname() })); return { busy: false, value: fn() }; } finally { - if (fd !== undefined) fs.closeSync(fd); - try { - if (JSON.parse(fs.readFileSync(lock, "utf8"))?.token === token) fs.rmSync(lock); - } catch { - // Gone already, or not ours: leave it. - } + // Ours is the file this descriptor holds. Still linked means still at the + // lock path (nobody renames it); unlinked means someone removed ours, and + // whatever is at the path now is not ours to remove. + const linked = fs.fstatSync(fd).nlink > 0; + fs.closeSync(fd); + if (linked) fs.rmSync(lock, { force: true }); } } @@ -152,29 +149,36 @@ export function withStoreLock(file, fn) { */ /** - * Who holds a lock, as far as its file says. + * Who holds a lock, as far as its file says: read through one descriptor, so + * the age and the owner are of the same file. * * @param {string} lock * @returns {LockHolder | null} null when it vanished meanwhile */ function lockHolder(lock) { - let ageMs; + let fd; try { - ageMs = Date.now() - fs.statSync(lock).mtimeMs; + fd = fs.openSync(lock, "r"); } catch { return null; } - let owner = {}; try { - owner = JSON.parse(fs.readFileSync(lock, "utf8")) ?? {}; - } catch { - // Being written, or not ours to read: age alone. + const ageMs = Date.now() - fs.fstatSync(fd).mtimeMs; + /** @type {{pid?: unknown, host?: unknown}} */ + let owner = {}; + try { + owner = JSON.parse(fs.readFileSync(fd, "utf8")) ?? {}; + } catch { + // Being written: age alone. + } + return { + pid: typeof owner.pid === "number" ? owner.pid : null, + host: typeof owner.host === "string" ? owner.host : null, + ageMs, + }; + } finally { + fs.closeSync(fd); } - return { - pid: typeof owner.pid === "number" ? owner.pid : null, - host: typeof owner.host === "string" ? owner.host : null, - ageMs, - }; } /** From 79740ebbaa9af17114652d7ce6975592b5faad0f Mon Sep 17 00:00:00 2001 From: Alex MKX <25821291+AlexMKX@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:28:45 +0300 Subject: [PATCH 17/17] chore: release 0.6.0 Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 47bacce..a999036 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@gfn-cis/opencode-squad", - "version": "0.5.0", + "version": "0.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@gfn-cis/opencode-squad", - "version": "0.5.0", + "version": "0.6.0", "license": "MIT", "dependencies": { "yaml": "^2.9.1", diff --git a/package.json b/package.json index 51e49ac..661c1b4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@gfn-cis/opencode-squad", - "version": "0.5.0", + "version": "0.6.0", "description": "OpenCode 2 plugin that turns the build agent into a PDCA orchestrator (sarge) over grunt/drill subagents", "type": "module", "main": "index.js",