diff --git a/AGENTS.md b/AGENTS.md index d3e4772..a112547 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -154,9 +154,13 @@ Three hooks wired in index.ts: 4. Fire-and-forget spawn — not blocking, not tmux 5. tool.execute.before for rate limiting — token bucket, in-memory 6. tool.execute.before for sub-agent isolation — full descendant tracking via parent chain -7. Worktree isolation on by default — each teammate gets their own git - worktree via client.worktree.create(). Opt out with worktree: false - for read-only agents. Lead merges branches after cleanup. +7. Writable teammates get their own Git worktrees by default. Read-only + agents and spawns with `worktree: false` use the shared directory. + V1 uses `client.worktree.create()` and skips isolation when the plugin + already runs inside an OpenCode worktree. V2 starts at the lead session's + commit and verifies the child's directory before dispatch. When the lead + has no usable Git commit, V2 uses the shared directory with a warning. + Once V2 attempts allocation, errors fail the spawn. 8. Plan approval is prompt-enforced, not permission-based — the teammate's context message tells it to send a plan and wait for approval. No tool-level gating. diff --git a/src/tools/team-spawn.ts b/src/tools/team-spawn.ts index 736bfe8..af9d9c0 100644 --- a/src/tools/team-spawn.ts +++ b/src/tools/team-spawn.ts @@ -94,7 +94,8 @@ export async function executeTeamSpawn( // never gets a worktree or a shell allow. Fall back to the built-in names. const isReadOnly = (await deps.client.agent?.readOnly(agent).catch(() => undefined)) ?? (agent === "plan" || agent === "explore") - const useWorktree = args.worktree !== false && !isReadOnly && !isWorktreeDirectory(deps.directory) + const isolatedSpawn = args.worktree !== false && !isReadOnly ? deps.client.createIsolatedSession : undefined + const useWorktree = args.worktree !== false && !isReadOnly && (!!isolatedSpawn || !isWorktreeDirectory(deps.directory)) const usePlanApproval = args.plan_approval === true log(`spawn:start name=${args.name} agent=${agent} worktree=${useWorktree}`) @@ -103,7 +104,7 @@ export async function executeTeamSpawn( let worktreeDir: string | null = null let worktreeBranch: string | null = null - if (useWorktree) { + if (useWorktree && !isolatedSpawn) { const resource = getTeamResourceParts(deps.db, teamInfo.teamId) const worktreeName = teamWorktreeName(resource.projectName, resource.teamName, resource.teamId, args.name) try { @@ -170,20 +171,16 @@ export async function executeTeamSpawn( ] as const const permission: PermissionRule[] = [] - if (worktreeDir) { - permission.push( - { permission: "edit", pattern: `${worktreeDir}/**`, action: "allow" }, - // V2 checks files inside the session's location as paths relative to - // it. session.create above binds the location to the worktree (via - // workspaceID, or directory as fallback), so this rule scopes edits - // to the worktree. Files outside the worktree remain gated by - // external_directory. + function worktreePermissions(directory: string): PermissionRule[] { + return [ + { permission: "edit", pattern: `${directory}/**`, action: "allow" }, + // Paths inside the bound worktree can be relative to the session. + // Files outside it are still gated by external_directory. { permission: "edit", pattern: "*", action: "allow" }, - ) - if (!isReadOnly) { - permission.push({ permission: "bash", pattern: "*", action: "allow" }) - } + { permission: "bash", pattern: "*", action: "allow" }, + ] } + if (worktreeDir) permission.push(...worktreePermissions(worktreeDir)) if (isReadOnly) { permission.push( @@ -202,30 +199,52 @@ export async function executeTeamSpawn( // permissions, so explore stays read-only. permission.push({ permission: "execute", pattern: "*", action: "allow" }) - // Create child session — bind to workspace if available (server-enforced CWD isolation). - // Falls back to no workspace binding if workspace.create failed. + // V2 returns an isolated child only after verifying its checkout and location. + // V1 keeps the workspace binding with a directory fallback. let childSessionId: string | undefined + let rollbackIsolated: (() => Promise) | undefined + const isolation = isolatedSpawn ? new AbortController() : undefined + const title = `${args.name} (@${agent} teammate)` try { log(`spawn:session:start name=${args.name}`) - const createResult = await withTimeout( - deps.client.session.create({ - parentID: sessionId, - title: `${args.name} (@${agent} teammate)`, - permission, - ...(workspaceId - ? { workspaceID: workspaceId } - // Workspace binding is preferred; when it is unavailable, bind the - // session to the worktree directory directly. Without a location, - // the teammate's location is the project root, edit paths are - // evaluated relative to it, and the `edit * allow` rule below - // would grant edits to the whole shared tree (PR #46 review). - : worktreeDir ? { directory: worktreeDir } : {}), - }), - getSpawnTimeout(), `session.create for "${args.name}"` - ) - childSessionId = createResult.data?.id + if (isolatedSpawn && isolation) { + const resource = getTeamResourceParts(deps.db, teamInfo.teamId) + const name = teamWorktreeName(resource.projectName, resource.teamName, resource.teamId, args.name) + const result = await withTimeout( + isolatedSpawn({ + parentID: sessionId, + title, + name, + permissions: (directory) => [...worktreePermissions(directory), ...permission], + signal: isolation.signal, + }), + getSpawnTimeout(), `isolated session setup for "${args.name}"`, + ) + if (result) { + childSessionId = result.sessionID + rollbackIsolated = result.rollback + worktreeDir = result.directory + worktreeBranch = result.branch + } + } + // V2 can decline isolation before allocation if the lead has no Git commit. + if (!childSessionId) { + const createResult = await withTimeout( + deps.client.session.create({ + parentID: sessionId, + title, + permission, + ...(workspaceId ? { workspaceID: workspaceId } : worktreeDir ? { directory: worktreeDir } : {}), + }), + getSpawnTimeout(), `session.create for "${args.name}"`, + ) + childSessionId = createResult.data?.id + } log(`spawn:session:done name=${args.name} sessionId=${childSessionId}`) } catch (err) { + // The V2 operation owns cleanup, including a create that settles after + // this timeout. Do not remove the worktree while a session move is in flight. + isolation?.abort(err) log(`spawn:session:failed name=${args.name} err=${err instanceof Error ? err.message : String(err)}`) // Track failure for circuit breaker const errMsg = err instanceof Error ? err.message : String(err) @@ -317,7 +336,7 @@ export async function executeTeamSpawn( context.push(`Other teammates: ${otherMembers.map(m => m.name).join(", ")}`) } - if (worktreeBranch && worktreeDir && !workspaceId) { + if (worktreeBranch && worktreeDir && !workspaceId && !isolatedSpawn) { // Workspace binding failed — fallback to prompt-based CWD instruction context.push( `You are working on branch "${worktreeBranch}" in your own worktree at: ${worktreeDir}`, @@ -455,19 +474,6 @@ export async function executeTeamSpawn( ) } const modelInfo = resolvedModel ? ` (model: ${resolvedModel})` : "" - deps.client.tui.showToast({ - title: "Team", - message: `Teammate "${args.name}" failed to start${modelInfo}: ${errMsg}`, - variant: "error", - duration: 8000, - }).catch(() => { /* TUI may not be available */ }) - notifyLead( - deps.client, - deps.db, - teamInfo.teamId, - `Teammate "${args.name}" failed to start and was removed${modelInfo}. Error: ${errMsg}. You may retry the spawn.`, - ) - // promptAsync can reject after the server accepted the prompt, so the // teammate may have run and committed. Preserve the branch before abort: // session cleanup asynchronously deletes the worktree branch. @@ -479,13 +485,23 @@ export async function executeTeamSpawn( if (preserved) log(`spawn:rollback:branch:preserved src=${worktreeBranch} target=${safeBranch}`) } catch { /* best effort — still abort/clean up */ } } - deps.client.session.abort({ sessionID: childSessionId }).catch(() => { /* best effort */ }) - if (workspaceId) { - deps.client.workspace.remove({ id: workspaceId }).catch(() => { /* best effort */ }) - } - if (worktreeDir) { - deps.client.worktree.remove({ worktreeRemoveInput: { directory: worktreeDir } }).catch(() => { /* best effort */ }) + const interrupt = deps.client.session.abort({ sessionID: childSessionId }).catch(() => { /* best effort */ }) + let recovery = "You may retry the spawn." + if (rollbackIsolated) { + await interrupt + const residuals = await rollbackIsolated() + if (residuals.length) recovery = residuals.join(". ") + } else { + if (workspaceId) { + deps.client.workspace.remove({ id: workspaceId }).catch(() => { /* best effort */ }) + } + if (worktreeDir) { + deps.client.worktree.remove({ worktreeRemoveInput: { directory: worktreeDir } }).catch(() => { /* best effort */ }) + } } + const failure = `Teammate "${args.name}" failed to start${modelInfo}: ${errMsg}. ${recovery}` + notifyLead(deps.client, deps.db, teamInfo.teamId, failure) + deps.client.tui.showToast({ title: "Team", message: failure, variant: "error", duration: 8000 }).catch(() => {}) } catch { /* rollback failed — watchdog will clean up stale member */ } }) diff --git a/src/types.ts b/src/types.ts index 44ba0f5..173f994 100644 --- a/src/types.ts +++ b/src/types.ts @@ -35,6 +35,14 @@ export interface PermissionRule { * Makes mocking trivial in tests. */ export interface PluginClient { + /** V2 provisions and verifies an isolated child, or returns undefined if the lead has no Git commit. */ + createIsolatedSession?(options: { + parentID: string + name: string + title: string + permissions(directory: string): PermissionRule[] + signal: AbortSignal + }): Promise<{ sessionID: string; directory: string; branch: string; rollback(): Promise } | undefined> /** Optional agent introspection (V2). Undefined answers fall back to name checks. */ agent?: { readOnly(agent: string): Promise diff --git a/src/v2-client.ts b/src/v2-client.ts index 6058ca6..a8ad6ed 100644 --- a/src/v2-client.ts +++ b/src/v2-client.ts @@ -1,13 +1,23 @@ -import type { PluginClient } from "./types" -import { log } from "./log" +import { realpath } from "node:fs/promises" +import type { PermissionRule, PluginClient } from "./types" +import { vlog } from "./log" import { runCommand } from "./process" +type SessionInfo = { + id: string + projectID?: string + location?: { directory?: string } +} + /** V2 plugin context subset Ensemble needs (structural, mock-friendly). */ export interface V2Context { /** Plugin location; `project.id` is required by the 2.0.19+ worktree API. */ location?: { directory?: string; project?: { id?: string } } session: { - create(input: Record): Promise<{ id: string }> + create(input: Record): Promise + move?(input: { sessionID: string; directory: string; delivery: "queue" }): Promise + wait?(input: { sessionID: string }): Promise + remove?(input: { sessionID: string }): Promise prompt(input: Record): Promise switchAgent(input: Record): Promise switchModel(input: Record): Promise @@ -55,57 +65,31 @@ export function agentRulesAreReadOnly(rules: unknown): boolean | undefined { return match.effect === "deny" } -/** Prefix marking a workspace id that is really a local directory (see below). */ -const DIR_WORKSPACE_PREFIX = "v2dir:" - -/** Injectable shell lookups (default to git; overridden in tests). */ +/** Optional companion integration. */ export interface V2ClientDeps { - /** Current branch checked out in a directory, or null when unknown. */ - gitBranch?: (directory: string) => Promise - /** Create and check out a branch in a directory. Returns the effective - * branch name, or null when the branch could not be created or checked - * out — never record the requested name without this confirmation. */ - gitCreateBranch?: (directory: string, branch: string) => Promise - /** Worktree directory currently on a branch, or null when none. */ - gitDir?: (branch: string) => Promise /** RPC emitter for companion events (team_view navigation). */ rpcEmitter?: { events: { emit(name: string, data: unknown): Promise } } } -/** Current branch in a directory via git. */ -async function gitBranchDefault(directory: string): Promise { - try { - const result = await runCommand(["git", "branch", "--show-current"], { cwd: directory }) - const branch = result.stdout.trim() - return result.exitCode === 0 && branch ? branch : null - } catch { - return null +async function git(directory: string, ...args: string[]): Promise { + const result = await runCommand(["git", ...args], { cwd: directory }) + if (result.exitCode !== 0) { + throw new Error(`git ${args.join(" ")} in "${directory}" failed: ${result.stderr.trim() || result.exitCode}`) } + return result.stdout.trimEnd() } -/** Create and check out a branch in a directory via git. Returns the - * effective branch name, or null when neither create nor switch worked — - * callers must record the return value, not the requested name, so a - * failed create can never be recorded as a live branch. */ -async function gitCreateBranchDefault(directory: string, branch: string): Promise { - try { - await runCommand(["git", "switch", "-c", branch], { cwd: directory }) - return branch - } catch (err) { - // The branch may already exist (re-spawn after the abort-cleanup race - // documented in AGENTS.md) — switch to it instead of recording a name - // with no ref behind it. Log both attempts; swallowing failures silently - // made team_merge squash a stale branch and silently lose new work - // (PR #46 review). - log(`v2-client:gitCreateBranch:create-failed directory=${directory} branch=${branch} err=${err instanceof Error ? err.message : String(err)} — trying existing branch`) - try { - await runCommand(["git", "switch", branch], { cwd: directory }) - return branch - } catch (err2) { - log(`v2-client:gitCreateBranch:switch-failed directory=${directory} branch=${branch} err=${err2 instanceof Error ? err2.message : String(err2)}`) - return null - } - } +async function gitWorktrees(directory: string): Promise> { + const paths = (await git(directory, "worktree", "list", "--porcelain", "-z")) + .split("\0").filter((field) => field.startsWith("worktree ")).map((field) => field.slice(9)) + // Git emits forward slashes on Windows. Resolve both SDK and Git paths + // the same way, ignoring stale worktree entries whose paths no longer exist. + return Promise.all(paths.map((path) => realpath(path).catch(() => undefined))) +} + +async function sessionIsIn(info: SessionInfo | undefined, directory: string): Promise { + if (!info?.location?.directory) return false + return await realpath(info.location.directory).catch(() => undefined) === directory } /** Concatenate the text parts of a promptAsync payload into one string. */ @@ -118,7 +102,7 @@ function joinParts(parts: Array<{ type: "text"; text: string }>): string { /** * Adapt a V2 plugin context to the shared PluginClient interface so all 14 - * team tools run unchanged on V2 (DRY: one adapter, zero logic forks). + * team tools can use the same client on both hosts. * * Mapping notes (all spike-verified live against v2.0.3 unless marked OQ): * - create: V1 `permission` rules become V2 `{action, resource, effect}`; @@ -132,28 +116,137 @@ function joinParts(parts: Array<{ type: "text"; text: string }>): string { * states here, extend the mapping. * - tui.*: no-op. Toasts and session-select move to the CLI (`./tui`) plugin * in a later phase — the server plugin must not depend on a TUI. - * - worktree.create: V2 reports only the directory, so the branch is read - * back via git (falls back to the requested name). OQ-V2-branch. + * - createIsolatedSession: V2 spawn provisions the worktree from the lead's + * session location and verifies the child's location before returning it. * - worktree.list: V2 entries carry directory only; name is the basename * (recovery filters on the `ensemble-` prefix — a non-matching dir is * skipped, never wrongly deleted). reset has no production callers and * maps to refresh. OQ-V2-wtname. - * - workspace.*: V2 ctx has no workspace domain (workspaces are - * provider-based). create bridges a branch to its worktree directory and - * returns a `v2dir:` id; session.create routes that id to - * location.directory, preserving worktree isolation with zero tool - * changes. list returns [] and remove resolves — the DB workspace_id - * column stays the source of truth and is still nulled by cleanup. + * - Worktree and workspace creation through the shared methods is V1-only. + * V2 workspace list/remove remain no-ops for cleanup of stored workspace IDs. */ export function createV2Client(ctx: V2Context, deps: V2ClientDeps = {}): PluginClient { - const gitBranch = deps.gitBranch ?? gitBranchDefault - const gitCreateBranch = deps.gitCreateBranch ?? gitCreateBranchDefault // 2.0.19+ worktree endpoints require the project; older hosts ignore it. const project = (): Record => { const projectID = ctx.location?.project?.id return projectID ? { projectID } : {} } + function toV2Permissions(permissions?: PermissionRule[]) { + // V1 action names predate the V2 vocabulary: bash is now shell. + return permissions?.map((rule) => ({ + action: rule.permission === "bash" ? "shell" : rule.permission, + resource: rule.pattern, + effect: rule.action, + })) + } + + async function applyLegacyPermissions(id: string, permissions: ReturnType) { + // Before 2.0.19, session rules had to be re-asserted after create. + if (permissions && typeof ctx.permission?.rules === "function") { + await ctx.permission.rules({ sessionID: id, permissions }) + } + } + return { + createIsolatedSession: async ({ parentID, name, title, permissions, signal }) => { + const lead = await ctx.session.get({ sessionID: parentID }) as SessionInfo | undefined + if (!lead?.location?.directory) throw new Error(`Lead session "${parentID}" has no worktree location`) + const from = await realpath(lead.location.directory) + const commit = await runCommand(["git", "rev-parse", "--verify", "--quiet", "HEAD^{commit}"], { cwd: from }) + signal.throwIfAborted() + if (commit.exitCode !== 0) return undefined + const head = commit.stdout.trimEnd() + const existingWorktrees = await gitWorktrees(from) + const worktreeProject = lead.projectID ? { projectID: lead.projectID } : project() + let directory: string | undefined + let createdBranch: string | undefined + let sessionID: string | undefined + let unverifiedWorktree: string | undefined + try { + signal.throwIfAborted() + // Pin the commit, not the source path: a Git-created lead checkout + // need not appear in the host's worktree inventory. + const created = await ctx.worktree.create({ ...worktreeProject, name, branch: head }) + unverifiedWorktree = created.directory + const resolved = await realpath(created.directory) + if (existingWorktrees.includes(resolved) || !(await gitWorktrees(from)).includes(resolved)) { + throw new Error(`OpenCode returned "${resolved}", which is not a new worktree of the lead's repository`) + } + const checkout = await git(resolved, "rev-parse", "--verify", "HEAD") + if (checkout !== head) { + // A detached checkout may be the only reference to this commit. + throw new Error(`Worktree "${resolved}" started at ${checkout}, expected lead commit ${head}`) + } + directory = resolved + unverifiedWorktree = undefined + const hostBranch = await git(directory, "branch", "--show-current") + signal.throwIfAborted() + if (!hostBranch) { + await git(directory, "switch", "-c", name) + createdBranch = name + } + signal.throwIfAborted() + + const rules = toV2Permissions(permissions(directory)) + const child = await ctx.session.create({ parentID, title, permissions: rules, location: { directory } }) + sessionID = child.id + if (!sessionID) throw new Error("OpenCode returned no child session ID") + signal.throwIfAborted() + if (!await sessionIsIn(child, directory)) { + // A linked child can inherit the parent's location on create. + if (!ctx.session.move || !ctx.session.wait) { + throw new Error(`Cannot bind child session "${sessionID}" to "${directory}": session move is unavailable`) + } + signal.throwIfAborted() + await ctx.session.move({ sessionID, directory, delivery: "queue" }) + await ctx.session.wait({ sessionID }) + const moved = await ctx.session.get({ sessionID }) as SessionInfo | undefined + if (!await sessionIsIn(moved, directory)) { + throw new Error(`Child session "${sessionID}" did not move to worktree directory "${directory}"`) + } + } + signal.throwIfAborted() + await applyLegacyPermissions(sessionID, rules) + signal.throwIfAborted() + return { sessionID, directory, branch: hostBranch || name, rollback } + } catch (error) { + const residuals = await rollback() + const message = [String(error), ...residuals].join(". ") + if (signal.aborted || residuals.length) vlog(`Isolated spawn "${name}" failed: ${message}`) + throw new Error(message) + } + + async function rollback(): Promise { + const residuals: string[] = [] + if (unverifiedWorktree) residuals.push(`unverified worktree "${unverifiedWorktree}" was left untouched`) + if (sessionID) { + try { + if (!ctx.session.remove) throw new Error("session.remove is unavailable on this host") + await ctx.session.remove({ sessionID }) + } catch (err) { + residuals.push(`could not remove child session "${sessionID}": ${err}`) + if (directory) residuals.push(`worktree "${directory}" was kept for the remaining child session`) + return residuals + } + } + if (directory) { + try { + if ((await gitWorktrees(from)).includes(directory)) { + // A rejected prompt may already have run, even on a detached HEAD. + const currentHead = await git(directory, "rev-parse", "--verify", "HEAD") + if (currentHead !== head) throw new Error(`keeping checkout with worker commit ${currentHead}`) + await ctx.worktree.remove({ ...worktreeProject, directory, force: false }) + } + if (createdBranch && await git(from, "branch", "--list", createdBranch)) { + await git(from, "branch", "-d", "--", createdBranch) + } + } catch (err) { + residuals.push(`could not finish cleanup of worktree "${directory}": ${err}`) + } + } + return residuals + } + }, agent: { readOnly: async (agent: string) => { if (!ctx.agent) return undefined @@ -169,35 +262,16 @@ export function createV2Client(ctx: V2Context, deps: V2ClientDeps = {}): PluginC create: async (options) => { const input: Record = { title: options.title } if (options.parentID) input["parentID"] = options.parentID - // V1 action names predate the V2 vocabulary: bash is now shell. - const V1_ACTION_MAP: Record = { bash: "shell" } - const permissions = options.permission?.map((rule) => ({ - action: V1_ACTION_MAP[rule.permission] ?? rule.permission, - resource: rule.pattern, - effect: rule.action, - })) + const permissions = toV2Permissions(options.permission) if (permissions) input["permissions"] = permissions if (options.workspaceID ?? options.directory) { - if (options.workspaceID?.startsWith(DIR_WORKSPACE_PREFIX)) { - input["location"] = { - directory: options.workspaceID.slice(DIR_WORKSPACE_PREFIX.length), - } - } else { - input["location"] = { - ...(options.directory ? { directory: options.directory } : {}), - ...(options.workspaceID ? { workspaceID: options.workspaceID } : {}), - } + input["location"] = { + ...(options.directory ? { directory: options.directory } : {}), + ...(options.workspaceID ? { workspaceID: options.workspaceID } : {}), } } const created = await ctx.session.create(input) - if (permissions && typeof ctx.permission?.rules === "function") { - // 2.0.3–2.0.18 merged agent rules after session rules, so create() - // permissions lost to the agent's and had to be re-asserted. From - // 2.0.19 the session ruleset merges last (core permission.ts - // `merge(agent.permissions, session.permissions)` with last-match - // evaluation) and rules() no longer exists, so create() is enough. - await ctx.permission.rules({ sessionID: created.id, permissions }) - } + await applyLegacyPermissions(created.id, permissions) return { data: { id: created.id } } }, promptAsync: async (options) => { @@ -256,20 +330,7 @@ export function createV2Client(ctx: V2Context, deps: V2ClientDeps = {}): PluginC }, }, worktree: { - create: async (options) => { - const name = (options.worktreeCreateInput as { name?: string } | undefined)?.name ?? "ensemble-worktree" - const created = await ctx.worktree.create({ ...project(), name }) - let branch = await gitBranch(created.directory) - if (!branch) { - // 2.0.32+ creates worktrees detached; team_merge needs a named - // branch. Record the effective branch only — never the requested - // name — so a failed create cannot point team_merge at a stale - // same-named branch whose commits would silently shadow new work - // (PR #46 review). - branch = (await gitCreateBranch(created.directory, name)) ?? "" - } - return { data: { name, branch, directory: created.directory } } - }, + create: async () => { throw new Error("V2 worktrees must be created with an isolated session") }, remove: async (options) => { const directory = (options.worktreeRemoveInput as { directory: string }).directory return ctx.worktree.remove({ ...project(), directory, force: false }) @@ -287,30 +348,9 @@ export function createV2Client(ctx: V2Context, deps: V2ClientDeps = {}): PluginC reset: async () => ctx.worktree.refresh(project()), }, workspace: { - create: async (options) => { - const branch = (options as { branch?: string }).branch ?? "" - const directory = await deps.gitDir?.(branch) - if (!directory) throw new Error(`V2 workspace bridge: no worktree found on branch "${branch}"`) - return { - data: { - id: `${DIR_WORKSPACE_PREFIX}${directory}`, - type: "local", - branch, - directory, - projectID: "", - }, - } - }, + create: async () => { throw new Error("V2 does not create workspaces for isolated sessions") }, remove: async () => undefined, - list: async () => ({ - data: [] as Array<{ - id: string - type: string - branch: string | null - directory: string | null - projectID: string - }>, - }), + list: async () => ({ data: [] }), }, - } as PluginClient + } } diff --git a/test/tools/team-spawn.test.ts b/test/tools/team-spawn.test.ts index 76631a7..dd1bf96 100644 --- a/test/tools/team-spawn.test.ts +++ b/test/tools/team-spawn.test.ts @@ -1,11 +1,12 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test" -import { mkdtemp, rm } from "node:fs/promises" +import { mkdtemp, realpath, rm } from "node:fs/promises" import { tmpdir } from "node:os" import path from "node:path" import { setupDeps, insertTeam, insertMember } from "../helpers" -import { executeTeamSpawn } from "../../src/tools/team-spawn" +import { executeTeamSpawn, spawnFailures } from "../../src/tools/team-spawn" import { executeTeamTasksAdd } from "../../src/tools/team-tasks-add" import type { ToolDeps } from "../../src/types" +import { createV2Client } from "../../src/v2-client" async function git(cwd: string, args: string[]): Promise { const proc = Bun.spawn(["git", ...args], { cwd, stdout: "pipe", stderr: "pipe" }) @@ -1077,3 +1078,320 @@ describe("team_spawn — timeout on session.create / worktree.create", () => { expect(result).not.toContain("branch:") }, 10000) }) + +describe("V2 isolated teammate spawn", () => { + let root: string + let leadDir: string + let workerDir: string + let base: string + let leadHead: string + + beforeEach(async () => { + spawnFailures.delete("t1") + root = await realpath(await mkdtemp(path.join(tmpdir(), "ensemble-v2-spawn-"))) + await git(root, ["init", "-b", "main"]) + await git(root, ["-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-m", "default branch"]) + base = (await git(root, ["rev-parse", "HEAD"])).trim() + leadDir = path.join(root, "opencode", "worktree", "lead") + workerDir = path.join(root, "worker") + await git(root, ["worktree", "add", "--detach", leadDir, base]) + await git(leadDir, ["-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-m", "lead change"]) + leadHead = (await git(leadDir, ["rev-parse", "HEAD"])).trim() + }) + + afterEach(async () => { + await rm(root, { recursive: true, force: true }) + }) + + function setupV2(leadDirectory = leadDir) { + const deps = setupDeps() + insertTeam(deps.db, "t1", "my-team", "lead-sess") + const calls: string[] = [] + const dispatched = Promise.withResolvers() + let childDir = leadDirectory + let movedTo: string | undefined + const ctx = { + location: { directory: root, project: { id: "project" } }, + session: { + create: async (input: Record) => { + calls.push("create") + expect(input["parentID"]).toBe("lead-sess") + return { id: "child-sess", location: { directory: childDir } } + }, + get: async (input: Record) => { + if (input["sessionID"] === "lead-sess") return { location: { directory: leadDirectory } } + calls.push("get child") + return { location: { directory: childDir } } + }, + move: async (input: Record) => { + calls.push("move") + movedTo = input["directory"] as string + }, + wait: async () => { + calls.push("wait") + if (movedTo) childDir = movedTo + }, + prompt: async () => { + calls.push(`prompt in ${childDir}`) + dispatched.resolve() + }, + remove: async () => { calls.push("remove session") }, + switchAgent: async () => undefined, + switchModel: async () => undefined, + interrupt: async () => undefined, + active: async () => ({}), + context: async () => [], + synthetic: async () => undefined, + }, + permission: {}, + worktree: { + create: async (input: Record) => { + calls.push("worktree") + // The lead checkout was added by Git, outside the host's inventory. + if (input["from"] === leadDirectory) throw new Error("SourceDirectoryNotFoundError") + await git(root, ["worktree", "add", "--detach", workerDir, String(input["branch"] ?? base)]) + return { directory: workerDir } + }, + remove: async (input: Record) => { + calls.push("remove worktree") + expect(input).toMatchObject({ directory: workerDir, force: false }) + await git(root, ["worktree", "remove", workerDir]) + }, + list: async () => [], + refresh: async () => undefined, + }, + } + return { ctx, calls, dispatched: dispatched.promise, deps: { ...deps, directory: leadDirectory, client: createV2Client(ctx) } } + } + + test.each(["non-Git directory", "repository with unborn HEAD"])("warns and spawns with ordinary permissions from a %s", async (mode) => { + const directory = await realpath(await mkdtemp(path.join(tmpdir(), "ensemble-no-lead-commit-"))) + try { + if (mode === "repository with unborn HEAD") await git(directory, ["init", "-b", "main"]) + const { ctx, calls, dispatched, deps } = setupV2(directory) + const create = ctx.session.create + ctx.session.create = async (input) => { + expect(input).not.toHaveProperty("location") + const rules = input["permissions"] as Array<{ action: string; resource: string; effect: string }> + expect(rules).toContainEqual({ action: "execute", resource: "*", effect: "allow" }) + expect(rules).toContainEqual({ action: "team_message", resource: "*", effect: "allow" }) + expect(rules.map(rule => rule.action)).not.toContain("edit") + expect(rules.map(rule => rule.action)).not.toContain("shell") + return create(input) + } + + const result = await executeTeamSpawn(deps, { name: "builder", prompt: "Implement change" }, "lead-sess") + await dispatched + + expect(result).toMatch(/WARNING: .*share your working directory/) + expect(calls).toEqual(["create", `prompt in ${directory}`]) + expect(deps.db.query("SELECT worktree_dir, worktree_branch, workspace_id FROM team_member WHERE name = ?").get("builder")) + .toEqual({ worktree_dir: null, worktree_branch: null, workspace_id: null }) + } finally { + await rm(directory, { recursive: true, force: true }) + } + }) + + test("can retry the same worker name after session.create rejects", async () => { + const { ctx, calls, dispatched, deps } = setupV2() + const create = ctx.session.create + ctx.session.create = async () => { throw new Error("Session creation rejected") } + const args = { name: "builder", prompt: "Implement change" } + + await expect(executeTeamSpawn(deps, args, "lead-sess")).rejects.toThrow("Session creation rejected") + ctx.session.create = create + const result = await executeTeamSpawn(deps, args, "lead-sess") + await dispatched + + expect(result).toContain("branch: ensemble-") + expect(calls).toEqual(["worktree", "remove worktree", "worktree", "create", "move", "wait", "get child", `prompt in ${workerDir}`]) + }) + + test("leaves a host-selected branch intact on rollback", async () => { + const { ctx, calls, deps } = setupV2() + const branch = "existing-worker-branch" + await git(root, ["branch", branch, leadHead]) + ctx.worktree.create = async () => { + await git(root, ["worktree", "add", workerDir, branch]) + return { directory: workerDir } + } + ctx.session.create = async () => { throw new Error("Session creation rejected") } + + await expect(executeTeamSpawn(deps, { name: "builder", prompt: "Implement change" }, "lead-sess")) + .rejects.toThrow("Session creation rejected") + expect(calls).toEqual(["remove worktree"]) + expect((await git(root, ["rev-parse", `refs/heads/${branch}`])).trim()).toBe(leadHead) + }) + + test("binds a linked child before dispatch and starts its branch at the detached lead's commit", async () => { + const { calls, dispatched, deps } = setupV2() + await executeTeamSpawn(deps, { name: "builder", prompt: "Implement change", model: "test/model" }, "lead-sess") + await dispatched + + expect(calls).toEqual(["worktree", "create", "move", "wait", "get child", `prompt in ${workerDir}`]) + const row = deps.db.query("SELECT worktree_dir, worktree_branch FROM team_member WHERE name = ?").get("builder") + const branch = (await git(workerDir, ["symbolic-ref", "--short", "HEAD"])).trim() + expect(row).toEqual({ worktree_dir: workerDir, worktree_branch: branch }) + expect(branch).toMatch(/^ensemble-/) + expect((await git(workerDir, ["rev-parse", "HEAD", `refs/heads/${branch}`])).trim().split("\n")).toEqual([leadHead, leadHead]) + expect((await git(root, ["rev-parse", "HEAD"])).trim()).toBe(base) + }) + + test("rolls back a child whose move leaves it in the lead checkout before claiming or prompting", async () => { + const { ctx, calls, deps } = setupV2() + ctx.session.wait = async () => { calls.push("wait") } + await executeTeamTasksAdd(deps, { tasks: [{ content: "Implement change", priority: "medium" }] }, "lead-sess") + const task = deps.db.query("SELECT id FROM team_task").get() as { id: string } + + await expect(executeTeamSpawn(deps, { name: "builder", prompt: "Implement change", claim_task: task.id }, "lead-sess")).rejects.toThrow(/location|directory/) + expect(calls).toEqual(["worktree", "create", "move", "wait", "get child", "remove session", "remove worktree"]) + expect(deps.db.query("SELECT name FROM team_member WHERE name = ?").get("builder")).toBeNull() + expect(deps.db.query("SELECT status, assignee FROM team_task WHERE id = ?").get(task.id)).toEqual({ status: "pending", assignee: null }) + expect(deps.registry.isTeamSession("child-sess")).toBe(false) + expect(await git(root, ["branch", "--list", "ensemble-*"])).toBe("") + }) + + test("accepts a child created directly in its worktree without moving it", async () => { + const { ctx, calls, deps } = setupV2() + ctx.session.create = async (input) => { + expect(input["location"]).toEqual({ directory: workerDir }) + return { id: "child-sess", location: { directory: workerDir, workspaceID: "ws_worker" } } + } + await executeTeamSpawn(deps, { name: "builder", prompt: "Implement change" }, "lead-sess") + expect(calls).not.toContain("move") + expect(deps.registry.isTeamSession("child-sess")).toBe(true) + }) + + test("leaves an existing worker branch untouched when git switch exits nonzero", async () => { + const { ctx, calls, deps } = setupV2() + const create = ctx.worktree.create + let name = "" + ctx.worktree.create = async (input) => { + name = String(input["name"]) + await git(root, ["branch", name, base]) + return create(input) + } + await expect(executeTeamSpawn(deps, { name: "builder", prompt: "Implement change" }, "lead-sess")).rejects.toThrow(/already exists/) + expect(calls).toEqual(["worktree", "remove worktree"]) + expect((await git(root, ["rev-parse", `refs/heads/${name}`])).trim()).toBe(base) + }) + + test("preserves a detached commit made by the host startup command", async () => { + const { ctx, calls, deps } = setupV2() + const create = ctx.worktree.create + let actualHead = "" + ctx.worktree.create = async (input) => { + const result = await create(input) + await git(workerDir, ["-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-m", "startup work"]) + actualHead = (await git(workerDir, ["rev-parse", "HEAD"])).trim() + return result + } + + const error = await executeTeamSpawn(deps, { name: "builder", prompt: "Implement change" }, "lead-sess").catch((err: Error) => err) + expect(String(error)).toContain(leadHead) + expect(String(error)).toContain(actualHead) + expect(String(error)).toContain(workerDir) + expect(calls).toEqual(["worktree"]) + expect((await git(workerDir, ["rev-parse", "HEAD"])).trim()).toBe(actualHead) + }) + + test.each(["missing", "failing"])("keeps a moved child's checkout when session.remove is %s", async (mode) => { + const { ctx, calls, deps } = setupV2() + const wait = ctx.session.wait + ctx.session.wait = async () => { + await wait() + throw new Error("Move wait failed") + } + Object.assign(ctx.session, { remove: mode === "missing" ? undefined : async () => { throw new Error("Removal failed") } }) + + const error = await executeTeamSpawn(deps, { name: "builder", prompt: "Implement change" }, "lead-sess").catch((err: Error) => err) + expect(String(error)).toContain("child-sess") + expect(String(error)).toContain(workerDir) + expect(String(error)).toContain(mode === "missing" ? "session.remove is unavailable" : "Removal failed") + expect(calls).toEqual(["worktree", "create", "move", "wait"]) + expect((await git(workerDir, ["rev-parse", "HEAD"])).trim()).toBe(leadHead) + expect(await git(workerDir, ["symbolic-ref", "--short", "HEAD"])).toMatch(/^ensemble-/) + }) + + test("preserves a worker's detached commit if its first prompt rejects after execution", async () => { + const { ctx, deps } = setupV2() + ctx.session.prompt = async () => { + await git(workerDir, ["switch", "--detach"]) + await git(workerDir, ["-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-m", "worker result"]) + throw new Error("Lost prompt response") + } + const notified = Promise.withResolvers() + deps.client.tui.showToast = async () => { notified.resolve() } + await executeTeamSpawn(deps, { name: "builder", prompt: "Implement change", model: "test/model" }, "lead-sess") + await notified.promise + expect(await git(root, ["worktree", "list", "--porcelain"])).toContain(workerDir) + expect((await git(workerDir, ["log", "-1", "--format=%s"])).trim()).toBe("worker result") + }) + + test.each([true, false])("releases a rejected first dispatch only if its child can be removed (%s)", async (canRemove) => { + const { ctx, calls, deps } = setupV2() + ctx.session.switchModel = async () => { throw new Error("Model selection rejected") } + if (!canRemove) Object.assign(ctx.session, { remove: undefined }) + const notified = Promise.withResolvers() + deps.client.tui.showToast = async (options) => { + if (options.variant === "error") notified.resolve() + } + await executeTeamSpawn(deps, { name: "builder", prompt: "Implement change", model: "test/model" }, "lead-sess") + await notified.promise + const msg = deps.db.query("SELECT content FROM team_message WHERE from_name = 'system' AND to_name = 'lead'").get() as { content: string } + expect(msg.content).toContain("Model selection rejected") + expect(calls).not.toContain(`prompt in ${workerDir}`) + if (canRemove) { + expect(calls.slice(-2)).toEqual(["remove session", "remove worktree"]) + expect(await git(root, ["worktree", "list", "--porcelain"])).not.toContain(workerDir) + } else { + expect(msg.content).toContain("child-sess") + expect(msg.content).toContain(workerDir) + expect((await git(workerDir, ["rev-parse", "HEAD"])).trim()).toBe(leadHead) + expect(calls).not.toContain("remove worktree") + } + }) + + test("refuses to use or remove a checkout that existed before worktree creation", async () => { + const { ctx, calls, deps } = setupV2() + await git(root, ["worktree", "add", "--detach", workerDir, leadHead]) + ctx.worktree.create = async () => ({ directory: workerDir }) + await expect(executeTeamSpawn(deps, { name: "builder", prompt: "Implement change" }, "lead-sess")).rejects.toThrow(/not a new worktree/) + expect(calls).toEqual([]) + expect((await git(workerDir, ["rev-parse", "HEAD"])).trim()).toBe(leadHead) + }) + + test("removes a child returned after the spawn times out without moving or prompting it", async () => { + const { ctx, calls, deps } = setupV2() + const started = Promise.withResolvers() + const release = Promise.withResolvers() + const completed = Promise.withResolvers() + const create = ctx.session.create + const provision = deps.client.createIsolatedSession! + ctx.session.create = async (input) => { + started.resolve() + await release.promise + return create(input) + } + deps.client.createIsolatedSession = (input) => provision(input).finally(() => completed.resolve()) + const oldTimeout = process.env.SPAWN_TIMEOUT_MS + process.env.SPAWN_TIMEOUT_MS = "250" + try { + const spawn = executeTeamSpawn(deps, { name: "builder", prompt: "Implement change" }, "lead-sess") + const rejected = expect(spawn).rejects.toThrow(/timed out/) + await Promise.race([started.promise, rejected]) + await rejected + expect(calls).toEqual(["worktree"]) + release.resolve() + await completed.promise + expect(calls).toEqual(["worktree", "create", "remove session", "remove worktree"]) + expect(deps.registry.isTeamSession("child-sess")).toBe(false) + expect(deps.db.query("SELECT name FROM team_member WHERE name = ?").get("builder")).toBeNull() + expect(await git(root, ["branch", "--list", "ensemble-*"])).toBe("") + } finally { + release.resolve() + if (oldTimeout === undefined) delete process.env.SPAWN_TIMEOUT_MS + else process.env.SPAWN_TIMEOUT_MS = oldTimeout + } + }) +}) diff --git a/test/v2-client.test.ts b/test/v2-client.test.ts index 6cf81f6..6608ae2 100644 --- a/test/v2-client.test.ts +++ b/test/v2-client.test.ts @@ -74,11 +74,6 @@ function mockCtx() { return { calls, ctx } } -/** Fake git branch lookup: dir → branch. */ -function mockGit(map: Record) { - return async (directory: string) => map[directory] ?? null -} - describe("v2-client adapter (issue #36, DRY: reuses all tool logic)", () => { test("session.create re-asserts permissions via rules() so agent denies cannot bury them", async () => { const { calls, ctx } = mockCtx() @@ -223,64 +218,6 @@ describe("v2-client adapter (issue #36, DRY: reuses all tool logic)", () => { expect(emitted).toEqual([{ name: "view", data: { sessionID: "ses_child" } }]) }) - test("worktree.create discovers the branch via git (V2 reports directory only)", async () => { - const { calls, ctx } = mockCtx() - const client = createV2Client(ctx as never, { - gitBranch: mockGit({ "/wt/ensemble-proj-team-alice": "ensemble-proj-team-alice" }), - }) - const result = await client.worktree.create({ worktreeCreateInput: { name: "ensemble-proj-team-alice" } }) - expect(calls[0]?.input).toMatchObject({ name: "ensemble-proj-team-alice" }) - expect(result.data).toMatchObject({ - name: "ensemble-proj-team-alice", - branch: "ensemble-proj-team-alice", - directory: "/wt/ensemble-proj-team-alice", - }) - }) - - test("worktree.create names a detached worktree after the requested name", async () => { - const { ctx } = mockCtx() - const created: Array<[string, string]> = [] - const client = createV2Client(ctx as never, { - gitBranch: mockGit({}), - gitCreateBranch: async (directory, branch) => { - created.push([directory, branch]) - return branch - }, - }) - const result = await client.worktree.create({ worktreeCreateInput: { name: "ensemble-x" } }) - expect(result.data?.branch).toBe("ensemble-x") - expect(created).toEqual([["/wt/ensemble-proj-team-alice", "ensemble-x"]]) - }) - - test("worktree.create leaves a worktree that is already on a branch alone", async () => { - const { ctx } = mockCtx() - let createCalls = 0 - const client = createV2Client(ctx as never, { - gitBranch: async () => "existing", - gitCreateBranch: async () => { - createCalls++ - return null - }, - }) - const result = await client.worktree.create({ worktreeCreateInput: { name: "ensemble-x" } }) - expect(result.data?.branch).toBe("existing") - expect(createCalls).toBe(0) - }) - - test("worktree.create records no branch when branch creation fails entirely (PR #46 review)", async () => { - const { ctx } = mockCtx() - const client = createV2Client(ctx as never, { - gitBranch: mockGit({}), - gitCreateBranch: async () => null, - }) - const result = await client.worktree.create({ worktreeCreateInput: { name: "ensemble-x" } }) - // Empty string, not "ensemble-x": recording the requested name when no - // ref exists made team_merge squash a stale same-named branch and - // silently lose the teammate's new work. - expect(result.data?.branch).toBe("") - expect(result.data?.directory).toBe("/wt/ensemble-proj-team-alice") - }) - test("worktree.remove/list/reset map to V2 remove/list/refresh", async () => { const { calls, ctx } = mockCtx() const client = createV2Client(ctx as never) @@ -292,22 +229,6 @@ describe("v2-client adapter (issue #36, DRY: reuses all tool logic)", () => { expect(calls[calls.length - 1]).toMatchObject({ domain: "worktree", method: "refresh" }) }) - test("session.create routes a v2dir workspace id to location.directory", async () => { - const { calls, ctx } = mockCtx() - const client = createV2Client(ctx as never) - await client.session.create({ title: "t", workspaceID: "v2dir:/wt/ensemble-x" }) - expect(calls[0]?.input).toMatchObject({ location: { directory: "/wt/ensemble-x" } }) - }) - - test("workspace.create bridges branch to directory (no workspace domain on V2 ctx)", async () => { - const { ctx } = mockCtx() - const client = createV2Client(ctx as never, { - gitDir: async (_branch: string) => "/wt/ensemble-x", - }) - const result = await client.workspace.create({ branch: "ensemble-x" }) - expect(result.data?.id).toBe("v2dir:/wt/ensemble-x") - }) - test("workspace.list is empty and workspace.remove resolves (DB is the source of truth)", async () => { const { calls, ctx } = mockCtx() const client = createV2Client(ctx as never) @@ -336,16 +257,12 @@ describe("createV2Client — OpenCode 2.0.19+ compatibility (issue #40)", () => test("worktree calls pass the location project id required by 2.0.19+", async () => { const { calls, ctx } = mockCtx() - const client = createV2Client({ ...ctx, location: { directory: "/p", project: { id: "prj_1" } } } as never, { - gitBranch: async () => "b", - }) - await client.worktree.create({ worktreeCreateInput: { name: "ensemble-x" } }) + const client = createV2Client({ ...ctx, location: { directory: "/p", project: { id: "prj_1" } } } as never) await client.worktree.remove({ worktreeRemoveInput: { directory: "/wt/ensemble-x" } }) await client.worktree.list() await client.worktree.reset({ worktreeResetInput: { directory: "/wt/ensemble-x" } }) const worktreeCalls = calls.filter((c) => c.domain === "worktree") - expect(worktreeCalls.map((c) => (c.input as { projectID?: string }).projectID)).toEqual(["prj_1", "prj_1", "prj_1", "prj_1"]) - expect(worktreeCalls[0]?.input).toMatchObject({ projectID: "prj_1", name: "ensemble-x" }) + expect(worktreeCalls.map((c) => (c.input as { projectID?: string }).projectID)).toEqual(["prj_1", "prj_1", "prj_1"]) }) test("agent.readOnly reads the agent's last matching edit rule", async () => {