Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(workflows): isolate source-changing agents

Rahmandfe65d0a08a6
diff --git a/lib/host/project-worktree.test.ts b/lib/host/project-worktree.test.ts
new file mode 100644
index 00000000..db0980fb
--- /dev/null
+++ b/lib/host/project-worktree.test.ts
@@ -0,0 +1,80 @@
+import { execFileSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { discardPreparedProjectWorktree, discardWorkflowWorktreeIfUnchanged, linkedWorkflowWorktreeCanonicalPath, prepareProjectWorktree } from "./project-worktree";
+
+const roots: string[] = [];
+afterEach(() => {
+ vi.unstubAllEnvs();
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+function repoFixture() {
+ const root = mkdtempSync(path.join(os.tmpdir(), "mso-workspace-test-")); roots.push(root);
+ const repo = path.join(root, "project"), worktrees = path.join(root, "worktrees");
+ mkdirSync(repo); writeFileSync(path.join(repo, "README.md"), "fixture\n");
+ const git = (...args: string[]) => execFileSync("git", args, { cwd: repo, encoding: "utf8" }).trim();
+ git("init", "-q", "-b", "main"); git("config", "user.name", "MSO Test"); git("config", "user.email", "[email protected]");
+ git("add", "."); git("commit", "-qm", "initial");
+ vi.stubEnv("MSO_AGENT_WORKTREE_ROOT", worktrees);
+ return { root, repo, worktrees, git };
+}
+
+describe("task-owned project worktrees", () => {
+ it("creates a clean linked worktree at the exact canonical commit", async () => {
+ const { repo } = repoFixture();
+ const base = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repo, encoding: "utf8" }).trim();
+ const result = await prepareProjectWorktree(repo);
+ expect(result).toMatchObject({ canonicalPath: repo, baseCommit: base, created: true });
+ expect(result.workspacePath).not.toBe(repo);
+ expect(result.branch).toMatch(/^agent\/project-[a-f0-9]{12}$/);
+ expect(execFileSync("git", ["rev-parse", "HEAD"], { cwd: result.workspacePath, encoding: "utf8" }).trim()).toBe(base);
+ expect(execFileSync("git", ["status", "--porcelain"], { cwd: result.workspacePath, encoding: "utf8" }).trim()).toBe("");
+ });
+
+ it("fails closed instead of stashing or hiding another owner's dirty canonical work", async () => {
+ const { repo, git } = repoFixture();
+ writeFileSync(path.join(repo, "README.md"), "someone else's work\n");
+ await expect(prepareProjectWorktree(repo)).rejects.toThrow(/uncommitted work/i);
+ expect(git("status", "--porcelain")).toContain("README.md");
+ expect(git("stash", "list")).toBe("");
+ });
+
+ it("reuses an already-linked worktree rather than nesting another worktree", async () => {
+ const { repo } = repoFixture();
+ const first = await prepareProjectWorktree(repo);
+ const second = await prepareProjectWorktree(first.workspacePath);
+ expect(second).toMatchObject({ workspacePath: first.workspacePath, baseCommit: first.baseCommit, created: false });
+ });
+
+ it("maps only an MSO-owned linked worktree back to its canonical checkout", async () => {
+ const { repo } = repoFixture();
+ const workspace = await prepareProjectWorktree(repo);
+ await expect(linkedWorkflowWorktreeCanonicalPath(workspace.workspacePath)).resolves.toBe(repo);
+ await expect(linkedWorkflowWorktreeCanonicalPath(repo)).resolves.toBeNull();
+ });
+
+ it("rolls back only a still-clean fresh worktree and preserves changed work", async () => {
+ const { repo } = repoFixture();
+ const clean = await prepareProjectWorktree(repo);
+ await expect(discardPreparedProjectWorktree(clean)).resolves.toBe(true);
+ await expect(fs.lstat(clean.workspacePath)).rejects.toMatchObject({ code: "ENOENT" });
+
+ const changed = await prepareProjectWorktree(repo);
+ await fs.writeFile(path.join(changed.workspacePath, "README.md"), "unique work\n");
+ await expect(discardPreparedProjectWorktree(changed)).resolves.toBe(false);
+ expect(await fs.readFile(path.join(changed.workspacePath, "README.md"), "utf8")).toBe("unique work\n");
+ });
+
+ it("can clean an unchanged workflow workspace from persisted path/base evidence", async () => {
+ const { repo } = repoFixture();
+ const workspace = await prepareProjectWorktree(repo);
+ await expect(discardWorkflowWorktreeIfUnchanged({
+ canonicalPath: repo, workspacePath: workspace.workspacePath, baseCommit: workspace.baseCommit,
+ })).resolves.toBe(true);
+ await expect(fs.lstat(workspace.workspacePath)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+});
diff --git a/lib/host/project-worktree.ts b/lib/host/project-worktree.ts
new file mode 100644
index 00000000..eb125c12
--- /dev/null
+++ b/lib/host/project-worktree.ts
@@ -0,0 +1,158 @@
+import { execFile } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { promisify } from "node:util";
+import { childEnv } from "./child-env";
+import { HostError } from "./host-error";
+
+const runFile = promisify(execFile);
+const MAX_OUTPUT = 256 * 1024;
+
+async function git(cwd: string, args: string[]): Promise<string> {
+ try {
+ const { stdout } = await runFile("git", args, {
+ cwd,
+ encoding: "utf8",
+ timeout: 15_000,
+ maxBuffer: MAX_OUTPUT,
+ env: childEnv() as NodeJS.ProcessEnv,
+ });
+ return stdout.trim();
+ } catch (error) {
+ const row = error as { stderr?: string; stdout?: string };
+ const detail = String(row.stderr || row.stdout || (error instanceof Error ? error.message : error)).trim().slice(0, 500);
+ throw new HostError(detail ? `Git workspace operation failed: ${detail}` : "Git workspace operation failed");
+ }
+}
+
+function safeSlug(value: string): string {
+ const slug = value.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 42);
+ return slug || "project";
+}
+
+function worktreeRoot(): string {
+ const configured = process.env.MSO_AGENT_WORKTREE_ROOT?.trim();
+ if (configured) return configured.replace(/^~(?=$|\/)/, os.homedir());
+ return path.join(os.homedir(), ".cache", "mso-worktrees");
+}
+
+export type PreparedProjectWorktree = {
+ canonicalPath: string;
+ workspacePath: string;
+ branch: string;
+ baseCommit: string;
+ created: boolean;
+};
+
+/**
+ * Create one task-owned linked worktree from a clean canonical checkout.
+ *
+ * This helper intentionally does NOT integrate, delete, reset or stash anything.
+ * If the canonical tree is dirty it fails closed so one workflow never "helps"
+ * another by hiding or committing its source state.
+ */
+export async function prepareProjectWorktree(projectPath: string): Promise<PreparedProjectWorktree> {
+ const canonicalPath = await fs.realpath(projectPath).catch(() => null);
+ if (!canonicalPath) throw new HostError("Project path does not exist");
+ const top = await git(canonicalPath, ["rev-parse", "--show-toplevel"]);
+ const topReal = await fs.realpath(top).catch(() => top);
+ if (topReal !== canonicalPath) throw new HostError("Source isolation requires the exact Git project root");
+
+ const marker = await fs.lstat(path.join(canonicalPath, ".git")).catch(() => null);
+ if (marker?.isFile()) {
+ const branch = await git(canonicalPath, ["branch", "--show-current"]);
+ const baseCommit = await git(canonicalPath, ["rev-parse", "HEAD"]);
+ return { canonicalPath, workspacePath: canonicalPath, branch, baseCommit, created: false };
+ }
+ if (!marker?.isDirectory() || marker.isSymbolicLink()) throw new HostError("Source isolation requires a normal Git checkout");
+
+ const dirty = await git(canonicalPath, ["status", "--porcelain"]);
+ if (dirty) throw new HostError("Canonical project has uncommitted work; preserve its owner before starting another source-changing workflow");
+ const baseCommit = await git(canonicalPath, ["rev-parse", "HEAD"]);
+ if (!/^[a-f0-9]{40}$/.test(baseCommit)) throw new HostError("Could not prove the canonical Git commit");
+
+ const root = path.resolve(worktreeRoot());
+ await fs.mkdir(root, { recursive: true, mode: 0o700 });
+ const rootReal = await fs.realpath(root);
+ const token = randomUUID().replace(/-/g, "").slice(0, 12);
+ const slug = safeSlug(path.basename(canonicalPath));
+ const workspacePath = path.join(rootReal, `${slug}-${token}`);
+ const branch = `agent/${slug}-${token}`;
+ if (await fs.lstat(workspacePath).catch(() => null)) throw new HostError("Generated agent worktree path already exists");
+
+ await git(canonicalPath, ["worktree", "add", "--no-track", "-b", branch, workspacePath, baseCommit]);
+ const workspaceReal = await fs.realpath(workspacePath).catch(() => null);
+ if (!workspaceReal || workspaceReal !== workspacePath) throw new HostError("Created worktree could not be verified");
+ const [workspaceTop, workspaceHead, workspaceStatus] = await Promise.all([
+ git(workspacePath, ["rev-parse", "--show-toplevel"]),
+ git(workspacePath, ["rev-parse", "HEAD"]),
+ git(workspacePath, ["status", "--porcelain"]),
+ ]);
+ if (await fs.realpath(workspaceTop) !== workspacePath || workspaceHead !== baseCommit || workspaceStatus) {
+ throw new HostError("Created worktree failed identity/cleanliness verification; preserve it for inspection");
+ }
+ return { canonicalPath, workspacePath, branch, baseCommit, created: true };
+}
+
+/** Remove only a freshly-created workspace that still has zero unique bytes/commits.
+ * Used for workflow-start rollback; integration cleanup remains explicit. */
+export async function discardPreparedProjectWorktree(worktree: PreparedProjectWorktree): Promise<boolean> {
+ if (!worktree.created || worktree.workspacePath === worktree.canonicalPath) return false;
+ const workspaceStat = await fs.lstat(worktree.workspacePath).catch(() => null);
+ if (!workspaceStat?.isDirectory() || workspaceStat.isSymbolicLink()) return false;
+ const [head, status, branch] = await Promise.all([
+ git(worktree.workspacePath, ["rev-parse", "HEAD"]),
+ git(worktree.workspacePath, ["status", "--porcelain"]),
+ git(worktree.workspacePath, ["branch", "--show-current"]),
+ ]);
+ if (head !== worktree.baseCommit || status || branch !== worktree.branch) return false;
+ await git(worktree.canonicalPath, ["worktree", "remove", worktree.workspacePath]);
+ await git(worktree.canonicalPath, ["branch", "-D", worktree.branch]);
+ return true;
+}
+
+export async function discardWorkflowWorktreeIfUnchanged(input: { canonicalPath: string; workspacePath: string; baseCommit?: string }): Promise<boolean> {
+ const canonicalPath = await fs.realpath(input.canonicalPath).catch(() => null);
+ const workspacePath = await fs.realpath(input.workspacePath).catch(() => null);
+ if (!canonicalPath || !workspacePath || canonicalPath === workspacePath) return false;
+ const root = await fs.realpath(path.resolve(worktreeRoot())).catch(() => null);
+ if (!root) return false;
+ const rel = path.relative(root, workspacePath);
+ if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel)) return false;
+ const [head, status, branch] = await Promise.all([
+ git(workspacePath, ["rev-parse", "HEAD"]),
+ git(workspacePath, ["status", "--porcelain"]),
+ git(workspacePath, ["branch", "--show-current"]),
+ ]);
+ if (!branch.startsWith("agent/") || status || (input.baseCommit && head !== input.baseCommit)) return false;
+ await git(canonicalPath, ["worktree", "remove", workspacePath]);
+ await git(canonicalPath, ["branch", "-D", branch]);
+ return true;
+}
+
+function insideRoot(root: string, candidate: string): boolean {
+ const rel = path.relative(root, candidate);
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
+}
+
+/** Resolve only MSO-owned linked-worktree paths back to their canonical checkout.
+ * This is the explicit exception that lets project-scoped tools operate on a task
+ * workspace without making arbitrary hidden directories globally resolvable. */
+export async function linkedWorkflowWorktreeCanonicalPath(candidatePath: string): Promise<string | null> {
+ const root = await fs.realpath(path.resolve(worktreeRoot())).catch(() => null);
+ const candidate = await fs.realpath(candidatePath).catch(() => null);
+ if (!root || !candidate || candidate === root || !insideRoot(root, candidate)) return null;
+ const marker = await fs.lstat(path.join(candidate, ".git")).catch(() => null);
+ if (!marker?.isFile() || marker.isSymbolicLink()) return null;
+ const commonRaw = await git(candidate, ["rev-parse", "--git-common-dir"]).catch(() => "");
+ if (!commonRaw) return null;
+ const common = await fs.realpath(path.resolve(candidate, commonRaw)).catch(() => null);
+ if (!common || path.basename(common) !== ".git") return null;
+ const canonical = await fs.realpath(path.dirname(common)).catch(() => null);
+ if (!canonical || canonical === candidate) return null;
+ const canonicalMarker = await fs.lstat(path.join(canonical, ".git")).catch(() => null);
+ if (!canonicalMarker?.isDirectory() || canonicalMarker.isSymbolicLink()) return null;
+ return canonical;
+}
diff --git a/lib/host/projects.ts b/lib/host/projects.ts
index 98c0b0e6..55edb0fe 100644
--- a/lib/host/projects.ts
+++ b/lib/host/projects.ts
@@ -4,6 +4,7 @@ import { boundedGitMeta, fullGitMeta, packageMeta } from "./project-meta";
import { projectCapabilities } from "./project-capabilities";
import { homeDir, isUnderRoot } from "./paths";
import { validateProjectChild, validateProjectDescendant, validateRootHint } from "./project-candidate";
+import { linkedWorkflowWorktreeCanonicalPath } from "./project-worktree";
import { configuredRootPaths, containerById, containerFor, listProjectDirsIn, projectContainers, type ProjectContainer } from "./project-roots";
export type ProjectResolution = {
@@ -88,9 +89,9 @@ export async function resolveProjectHint(hint: string, rootHint?: string): Promi
const pathHint = raw.startsWith("projects/") ? `~/${raw}` : raw;
if (/^(?:~\/|\/|\.\.?\/)/.test(pathHint)) {
- // A path hint gets the SAME component-by-component validation an enumerated entry
- // gets — hidden, symlinked or foreign-uid components are refused at every depth,
- // rather than canonicalized away by a single resolveReadable() call.
+ // Normal projects stay within configured containers. The sole hidden-path
+ // exception is an MSO-owned linked worktree, whose git-common-dir proves the
+ // canonical project before we reuse that project's logical id/root.
const absolute = expandHome(pathHint);
for (const container of containers) {
if (!isUnderRoot(absolute, container.path)) continue;
@@ -98,6 +99,19 @@ export async function resolveProjectHint(hint: string, rootHint?: string): Promi
if (candidate.ok) return resolutionFor(container, candidate.path, raw, "path");
return null; // it belongs to this container and was refused; do not try a wider one
}
+ const canonical = await linkedWorkflowWorktreeCanonicalPath(absolute);
+ if (!canonical) return null;
+ for (const container of containers) {
+ if (!isUnderRoot(canonical, container.path)) continue;
+ const validated = await validateProjectDescendant(container, canonical);
+ if (!validated.ok) return null;
+ const meta = await packageMeta(absolute);
+ const name = path.basename(canonical);
+ return {
+ hint: raw, id: `${container.id}/${name}`, name, path: absolute, rootId: container.id, root: container.path,
+ packageName: meta.name, aliases: projectAliasesFor(name), matchedBy: "path",
+ };
+ }
return null;
}
diff --git a/lib/mcp/tools-mutate.ts b/lib/mcp/tools-mutate.ts
index 193a3794..18770ace 100644
--- a/lib/mcp/tools-mutate.ts
+++ b/lib/mcp/tools-mutate.ts
@@ -4,6 +4,7 @@ import { copy, makeDir, move, remove, writeFileGuarded } from "@/lib/host/fs-api
import { resolveProjectHint, runProjectFunction } from "@/lib/host/projects-api";
import { importOpenAiProvidedFile } from "./openai-file-upload";
import { type McpTool, opt, PATH_P, S, str } from "./tool-kit";
+import { requireWorkflowExecCwd, requireWorkflowMutationPath, requireWorkflowProjectTarget } from "./workflow-workspace-guard";
// The write and exec tiers. Each carries an `audit` descriptor — the dispatcher,
// not the tool, writes the trail, because these call lib/host directly and so
@@ -25,11 +26,15 @@ export const MUTATE_TOOLS: McpTool[] = [
content: { type: "string" },
expected_sha256: { type: "string", description: "Optional SHA-256 returned by fs_read; refuse if the current file no longer matches." },
}, ["path", "content"]),
- run: async (a) => ({ ok: true, ...(await writeFileGuarded({
- path: str(a, "path"),
- content: typeof a.content === "string" ? a.content : "",
- expectedSha256: opt(a, "expected_sha256"),
- })) }),
+ run: async (a, context) => {
+ const target = str(a, "path");
+ await requireWorkflowMutationPath(context, target);
+ return { ok: true, ...(await writeFileGuarded({
+ path: target,
+ content: typeof a.content === "string" ? a.content : "",
+ expectedSha256: opt(a, "expected_sha256"),
+ })) };
+ },
},
{
name: "fs_upload_file",
@@ -60,13 +65,15 @@ export const MUTATE_TOOLS: McpTool[] = [
conflict: { type: "string", enum: ["error", "rename", "replace"], description: "Default error. rename chooses a deterministic content-hash suffix. replace requires expected_sha256." },
expected_sha256: { type: "string", description: "Required only for conflict=replace; SHA-256 from a prior read/export of the current destination." },
}, ["file", "dest"]),
- run: async (a, context) => importOpenAiProvidedFile({
- file: a.file,
- dest: str(a, "dest"),
- filename: opt(a, "filename"),
- conflict: opt(a, "conflict") as "error" | "rename" | "replace" | undefined,
- expectedSha256: opt(a, "expected_sha256"), allowChatGptAzureFamily: context.trustedOpenAiFileParams === true,
- }),
+ run: async (a, context) => {
+ const dest = str(a, "dest");
+ await requireWorkflowMutationPath(context, dest);
+ return importOpenAiProvidedFile({
+ file: a.file, dest, filename: opt(a, "filename"),
+ conflict: opt(a, "conflict") as "error" | "rename" | "replace" | undefined,
+ expectedSha256: opt(a, "expected_sha256"), allowChatGptAzureFamily: context.trustedOpenAiFileParams === true,
+ });
+ },
},
{
name: "fs_mkdir",
@@ -76,7 +83,7 @@ export const MUTATE_TOOLS: McpTool[] = [
scope: "write",
annotations: { idempotentHint: true },
inputSchema: S(PATH_P, ["path"]),
- run: async (a) => { await makeDir(str(a, "path")); return { ok: true, path: a.path }; },
+ run: async (a, context) => { const target = str(a, "path"); await requireWorkflowMutationPath(context, target); await makeDir(target); return { ok: true, path: a.path }; },
},
{
name: "fs_move",
@@ -85,7 +92,7 @@ export const MUTATE_TOOLS: McpTool[] = [
description: "Move or rename a file or directory. Refuses when the source holds credential paths.",
scope: "write",
inputSchema: S({ from: { type: "string" }, to: { type: "string" } }, ["from", "to"]),
- run: async (a) => { await move(str(a, "from"), str(a, "to")); return { ok: true }; },
+ run: async (a, context) => { const from = str(a, "from"), to = str(a, "to"); await requireWorkflowMutationPath(context, from); await requireWorkflowMutationPath(context, to); await move(from, to); return { ok: true }; },
},
{
name: "fs_copy",
@@ -94,7 +101,7 @@ export const MUTATE_TOOLS: McpTool[] = [
description: "Copy a file or directory. The cockpit's own secrets are skipped rather than duplicated.",
scope: "write",
inputSchema: S({ from: { type: "string" }, to: { type: "string" } }, ["from", "to"]),
- run: async (a) => { await copy(str(a, "from"), str(a, "to")); return { ok: true }; },
+ run: async (a, context) => { const from = str(a, "from"), to = str(a, "to"); await requireWorkflowMutationPath(context, to); await copy(from, to); return { ok: true }; },
},
{
name: "fs_delete",
@@ -106,7 +113,7 @@ export const MUTATE_TOOLS: McpTool[] = [
scope: "write",
annotations: { destructiveHint: true },
inputSchema: S(PATH_P, ["path"]),
- run: async (a) => { await remove(str(a, "path")); return { ok: true, path: a.path }; },
+ run: async (a, context) => { const target = str(a, "path"); await requireWorkflowMutationPath(context, target); await remove(target); return { ok: true, path: a.path }; },
},
{
@@ -131,9 +138,10 @@ export const MUTATE_TOOLS: McpTool[] = [
name: { type: "string", description: "Function name returned by project_capabilities." },
input: { type: "object", description: "JSON object passed to the project function on stdin.", additionalProperties: true },
}, ["project", "name", "input"]),
- run: async (a) => {
+ run: async (a, context) => {
const project = await resolveProjectHint(str(a, "project"));
if (!project) throw new Error(`project not found: ${String(a.project)}`);
+ await requireWorkflowProjectTarget(context, project.path);
return (await import("./project-function-content")).projectFunctionContent(await runProjectFunction(project.path, str(a, "name"), a.input));
},
},
@@ -158,10 +166,14 @@ export const MUTATE_TOOLS: McpTool[] = [
command: { type: "string", description: "The shell command line to run asynchronously." },
cwd: { type: "string", description: "Working directory. Defaults to the owner's home." },
}, ["command"]),
- run: async (a, context) => startExecJob({
- artifactEnv: await sessionArtifactEnvironment(context),
- command: str(a, "command"), cwd: opt(a, "cwd"), actor: context.workflowActor ?? context.actor, workflowId: context.workflowId,
- }),
+ run: async (a, context) => {
+ const cwd = opt(a, "cwd");
+ await requireWorkflowExecCwd(context, cwd);
+ return startExecJob({
+ artifactEnv: await sessionArtifactEnvironment(context),
+ command: str(a, "command"), cwd, actor: context.workflowActor ?? context.actor, workflowId: context.workflowId,
+ });
+ },
},
{
name: "exec_job_status",
@@ -213,7 +225,11 @@ export const MUTATE_TOOLS: McpTool[] = [
command: { type: "string", description: "The shell command line to run." },
cwd: { type: "string", description: "Working directory. Defaults to the owner's home." },
}, ["command"]),
- run: async (a, context) => runCommand(str(a, "command"), opt(a, "cwd"), await sessionArtifactEnvironment(context)),
+ run: async (a, context) => {
+ const cwd = opt(a, "cwd");
+ await requireWorkflowExecCwd(context, cwd);
+ return runCommand(str(a, "command"), cwd, await sessionArtifactEnvironment(context));
+ },
},
];
diff --git a/lib/mcp/tools-workflow-lifecycle.ts b/lib/mcp/tools-workflow-lifecycle.ts
index 377e3c1c..64495e64 100644
--- a/lib/mcp/tools-workflow-lifecycle.ts
+++ b/lib/mcp/tools-workflow-lifecycle.ts
@@ -1,4 +1,5 @@
import { inspectProject, resolveProjectHint } from "@/lib/host/projects-api";
+import { discardWorkflowWorktreeIfUnchanged } from "@/lib/host/project-worktree";
import { activeWorkflowForActor, cancelWorkflow, finishWorkflow, workflowStepProvenance } from "@/lib/workflow";
import { getAgentSession } from "@/lib/agent/session-store";
import { agentSessionLabel } from "@/lib/agent/session-name";
@@ -12,6 +13,22 @@ import type { McpTool } from "./tool-kit";
import { opt, S, str } from "./tool-kit";
import { evidenceInput, evidenceSchema, WORKFLOW_PROGRESS_OUTPUT, workflowProgress } from "./tools-learning-shared";
+async function workflowCleanupResult(workflow: { project?: string; orchestration?: { isolation?: "direct" | "optional-worktree" | "isolated-worktree"; workspacePath?: string; baseCommit?: string; affectedPaths?: string[]; reservedResources?: string[] } }) {
+ const guidance = workflowCleanupGuidance(workflow.orchestration);
+ if (!workflow.project || !workflow.orchestration?.workspacePath || workflow.orchestration.isolation !== "isolated-worktree") return guidance;
+ try {
+ const autoRemoved = await discardWorkflowWorktreeIfUnchanged({
+ canonicalPath: workflow.project, workspacePath: workflow.orchestration.workspacePath, baseCommit: workflow.orchestration.baseCommit,
+ });
+ return autoRemoved ? {
+ ...guidance, autoRemoved: true, worktreeCleanupRequired: false,
+ instruction: "Unused clean task worktree was removed automatically after workflow close.",
+ } : { ...guidance, autoRemoved: false };
+ } catch (error) {
+ return { ...guidance, autoRemoved: false, warning: error instanceof Error ? error.message : String(error) };
+ }
+}
+
export const WORKFLOW_LIFECYCLE_TOOLS: McpTool[] = [
{
name: "workflow_status",
@@ -57,7 +74,7 @@ export const WORKFLOW_LIFECYCLE_TOOLS: McpTool[] = [
});
if (workflowActor)
await disarmLocalAgentStandbyWorkflow(workflowActor, cancelled.workflow.id, "workflow cancelled");
- return { ...cancelled, cleanup: workflowCleanupGuidance(cancelled.workflow.orchestration) };
+ return { ...cancelled, cleanup: await workflowCleanupResult(cancelled.workflow) };
},
},
{
@@ -194,7 +211,7 @@ export const WORKFLOW_LIFECYCLE_TOOLS: McpTool[] = [
scriptCandidateCreated: Boolean(scriptPath),
},
repoMemory: { taskMemoryId, scriptPath, warnings: persistenceWarnings },
- cleanup: workflowCleanupGuidance(workflow.orchestration),
+ cleanup: await workflowCleanupResult(workflow),
};
},
},
diff --git a/lib/mcp/tools-workflow-start.ts b/lib/mcp/tools-workflow-start.ts
index e3643359..bec7df7b 100644
--- a/lib/mcp/tools-workflow-start.ts
+++ b/lib/mcp/tools-workflow-start.ts
@@ -1,5 +1,6 @@
import { ownedArtifactSession, prepareSessionArtifacts } from "@/lib/agent/artifact-session";
import { inspectProject, readProjectKnowledge, resolveProjectHint } from "@/lib/host/projects-api";
+import { discardPreparedProjectWorktree, prepareProjectWorktree } from "@/lib/host/project-worktree";
import { listLearnedRecipes, markRecipeRecommended, startWorkflow, summarizeProjectContention } from "@/lib/workflow";
import { ensureLearnedWorkflowGraph, findMatchingWorkflowGraph } from "@/lib/workflow/graph-store";
import { progressiveVerification } from "@/lib/orchestration/automation";
@@ -107,12 +108,21 @@ export const WORKFLOW_START_TOOL: McpTool = {
...(candidateSearch?.matches ?? []).map((match) => `${match.path}:${match.line} ${match.preview}`),
compactSearch.recommendedRecipe?.description ?? "",
].join("\n").length / 4);
+ // Create a source workspace only after read-only discovery/planning succeeds.
+ // A failed catalog/memory lookup must never leave an orphan linked worktree.
+ const isolatedWorkspace = project && repository?.git.available && classification.isolation === "isolated-worktree"
+ ? await prepareProjectWorktree(project.path)
+ : undefined;
+ const workspacePath = isolatedWorkspace?.workspacePath ?? project?.path;
const orchestration: WorkflowOrchestrationSnapshot = {
...classification,
- ...(repository?.git.head?.sha ? { baseCommit: repository.git.head.sha } : {}),
+ ...(isolatedWorkspace?.baseCommit || repository?.git.head?.sha ? { baseCommit: isolatedWorkspace?.baseCommit ?? repository?.git.head?.sha } : {}),
...(repository?.git.branch ? { baseBranch: repository.git.branch } : {}),
- ...(project?.path ? { workspacePath: project.path } : {}),
- changedPaths, affectedPaths, reservedResources,
+ ...(workspacePath ? { workspacePath } : {}),
+ changedPaths, affectedPaths, reservedResources: [...new Set([
+ ...reservedResources,
+ ...(isolatedWorkspace?.created ? [isolatedWorkspace.workspacePath] : []),
+ ])].slice(0, 40),
overlappingPaths: contention.overlappingPaths, overlappingResources: contention.overlappingResources,
activeProjectWorkflows, conflictingWorkflowCount: contention.conflictingWorkflowCount,
memoryHits: agentMemory.length + repoMemory.length + (search.recommendedRecipe ? 1 : 0),
@@ -142,15 +152,21 @@ export const WORKFLOW_START_TOOL: McpTool = {
...(candidateSearch?.cursor ? { cursor: candidateSearch.cursor } : candidatePool?.cursor ? { cursor: candidatePool.cursor } : {}),
} : undefined,
};
- const started = await startWorkflow({
- actor,
- scope: context.scope,
- intent,
- project: project?.path ?? projectHint,
- constraints: opt(a, "constraints"),
- orchestration,
- candidatePool,
- });
+ let started;
+ try {
+ started = await startWorkflow({
+ actor,
+ scope: context.scope,
+ intent,
+ project: project?.path ?? projectHint,
+ constraints: opt(a, "constraints"),
+ orchestration,
+ candidatePool,
+ });
+ } catch (error) {
+ if (isolatedWorkspace?.created) await discardPreparedProjectWorktree(isolatedWorkspace).catch(() => false);
+ throw error;
+ }
if (search.recommendedRecipe) {
await markRecipeRecommended(search.recommendedRecipe.id, { actor: recipeOwner, scope: context.scope }).catch(() => undefined);
}
@@ -203,6 +219,7 @@ export const WORKFLOW_START_TOOL: McpTool = {
...(recipePlan ? [`[Recipe] ${recipePlan.maturity} · ${recipePlan.attempts} attempts · ${recipePlan.successRate}% success · ${recipePlan.steps.length} reusable step(s)`] : []),
...(graphAutomation ? [`[Workflow graph] ${graphAutomation.status} · ${graphAutomation.name} · ${graphAutomation.metadata.provenance ?? "private"}`] : [`[Workflow graph] no matching private graph; successful completion will seed a learned draft`]),
...(reusableScript ? [`[Automation] ${reusableScript.status} script ${reusableScript.id} available`] : []),
+ ...(isolatedWorkspace ? [`[Workspace] ${isolatedWorkspace.created ? "task-owned worktree" : "existing linked worktree"} · ${isolatedWorkspace.workspacePath} · ${isolatedWorkspace.branch || "detached"}`] : []),
...(contention.conflictingWorkflowCount ? [`[Collision] ${contention.conflictingWorkflowCount} workflow(s) overlap declared paths/resources`] : []),
...(candidateSearch ? [`[Candidates] ${candidateSearch.reusedSeed ? "reused recipe pool" : "host index"} · ${candidateSearch.candidates.length} path candidate(s) · ${candidateSearch.matches.length} bounded content hit(s)`] : []),
...(discovery.complete ? [] : [`[Discovery] partial scan — ${[...search.catalog.truncationReasons, ...(candidateSearch?.truncationReasons ?? [])].join(", ")}; do not conclude something is absent`]),
@@ -210,7 +227,10 @@ export const WORKFLOW_START_TOOL: McpTool = {
"[Plan] classify → retrieve minimal memory → isolate if required → execute → progressive verify → learn → workflow_finish",
],
orientation: workflowOrientation(context.scope),
- policy: workflowStartPolicy(classification),
+ policy: {
+ ...workflowStartPolicy(classification),
+ ...(isolatedWorkspace ? { workspace: `Use this exact task workspace for source writes and shell cwd: ${isolatedWorkspace.workspacePath}` } : {}),
+ },
},
search: compactSearch,
instruction: "Use the smallest useful returned memory context and any safe recipe. Follow the risk/isolation policy, verify progressively, then call workflow_finish with evidence.",
diff --git a/lib/mcp/workflow-source-isolation.test.ts b/lib/mcp/workflow-source-isolation.test.ts
new file mode 100644
index 00000000..f17ec7d1
--- /dev/null
+++ b/lib/mcp/workflow-source-isolation.test.ts
@@ -0,0 +1,97 @@
+import { execFileSync } from "node:child_process";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-source-isolation-"));
+const project = path.join(root, "project");
+const worktrees = path.join(root, "worktrees");
+await fs.mkdir(path.join(project, "src"), { recursive: true });
+await fs.writeFile(path.join(project, "package.json"), JSON.stringify({ name: "source-isolation-fixture" }));
+await fs.writeFile(path.join(project, "src/value.ts"), "export const value = 1;\n");
+const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
+git("init", "-q", "-b", "main"); git("config", "user.name", "MSO Test"); git("config", "user.email", "[email protected]");
+git("add", "."); git("commit", "-qm", "initial");
+
+const previous = {
+ read: process.env.OS_FS_READ_ROOTS,
+ write: process.env.OS_FS_WRITE_ROOTS,
+ projectRoots: process.env.OS_PROJECT_ROOTS,
+ memory: process.env.OS_SKILL_MEMORY_STORE,
+ worktrees: process.env.MSO_AGENT_WORKTREE_ROOT,
+};
+
+beforeAll(async () => {
+ process.env.OS_FS_READ_ROOTS = root;
+ process.env.OS_FS_WRITE_ROOTS = root;
+ process.env.OS_PROJECT_ROOTS = root;
+ process.env.OS_SKILL_MEMORY_STORE = path.join(root, "workflow-memory.json");
+ process.env.MSO_AGENT_WORKTREE_ROOT = worktrees;
+ const { resetWorkflowStoreCache } = await import("@/lib/workflow"); resetWorkflowStoreCache();
+});
+
+afterAll(async () => {
+ for (const [key, value] of Object.entries(previous)) {
+ if (value === undefined) delete process.env[key === "read" ? "OS_FS_READ_ROOTS" : key === "write" ? "OS_FS_WRITE_ROOTS" : key === "projectRoots" ? "OS_PROJECT_ROOTS" : key === "memory" ? "OS_SKILL_MEMORY_STORE" : "MSO_AGENT_WORKTREE_ROOT"];
+ else process.env[key === "read" ? "OS_FS_READ_ROOTS" : key === "write" ? "OS_FS_WRITE_ROOTS" : key === "projectRoots" ? "OS_PROJECT_ROOTS" : key === "memory" ? "OS_SKILL_MEMORY_STORE" : "MSO_AGENT_WORKTREE_ROOT"] = value;
+ }
+ const { resetWorkflowStoreCache } = await import("@/lib/workflow"); resetWorkflowStoreCache();
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+describe("workflow_start source isolation", () => {
+ it("creates a task-owned worktree and blocks canonical fs/shell mutation", async () => {
+ const { LEARNING_TOOLS } = await import("./tools-learning");
+ const { MUTATE_TOOLS } = await import("./tools-mutate");
+ const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;
+ const write = MUTATE_TOOLS.find((tool) => tool.name === "fs_write")!;
+ const exec = MUTATE_TOOLS.find((tool) => tool.name === "exec_run")!;
+ const actor = "mcp:source-isolation";
+ const started = await start.run({
+ intent: "fix the source value and verify the repository",
+ project,
+ affected_paths: ["src/value.ts"],
+ }, { actor, scope: "exec" }) as {
+ workflow: { id: string; project?: string; orchestration?: { isolation: string; workspacePath?: string; baseCommit?: string } };
+ bootstrap: { trace: string[]; policy: { workspace?: string } };
+ };
+ const workspace = started.workflow.orchestration?.workspacePath;
+ expect(started.workflow.project).toBe(project);
+ expect(started.workflow.orchestration).toMatchObject({ isolation: "isolated-worktree", baseCommit: git("rev-parse", "HEAD") });
+ expect(workspace).toBeTruthy(); expect(workspace).not.toBe(project); expect(workspace!.startsWith(worktrees + path.sep)).toBe(true);
+ expect(started.bootstrap.trace).toEqual(expect.arrayContaining([expect.stringContaining("[Workspace] task-owned worktree")]));
+ expect(started.bootstrap.policy.workspace).toContain(workspace!);
+
+ const context = { actor, workflowActor: actor, workflowId: started.workflow.id, scope: "exec" as const };
+ await expect(write.run({ path: path.join(project, "src/value.ts"), content: "export const value = 2;\n" }, context)).rejects.toThrow(/source-isolated/i);
+ await expect(exec.run({ command: "git status --short", cwd: project }, context)).rejects.toThrow(/exec cwd/i);
+ await expect(exec.run({ command: "git status --short" }, context)).rejects.toThrow(/exec requires cwd/i);
+
+ await expect(write.run({ path: path.join(workspace!, "src/value.ts"), content: "export const value = 2;\n" }, context)).resolves.toMatchObject({ ok: true });
+ const shell = await exec.run({ command: "git status --short", cwd: workspace }, context) as { code: number; stdout: string };
+ expect(shell.code).toBe(0); expect(shell.stdout).toContain("src/value.ts");
+ expect(await fs.readFile(path.join(project, "src/value.ts"), "utf8")).toBe("export const value = 1;\n");
+ expect(await fs.readFile(path.join(workspace!, "src/value.ts"), "utf8")).toBe("export const value = 2;\n");
+ expect(git("status", "--porcelain")).toBe("");
+ });
+
+ it("auto-removes only an unused clean task worktree when the workflow is cancelled", async () => {
+ const { LEARNING_TOOLS } = await import("./tools-learning");
+ const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;
+ const cancel = LEARNING_TOOLS.find((tool) => tool.name === "workflow_cancel")!;
+ const actor = "mcp:source-isolation-clean";
+ const started = await start.run({
+ intent: "fix one source line then stop if no change is needed", project, affected_paths: ["src/value.ts"],
+ }, { actor, scope: "exec" }) as { workflow: { id: string; orchestration?: { workspacePath?: string } } };
+ const workspace = started.workflow.orchestration?.workspacePath!;
+ expect(workspace).not.toBe(project);
+ const result = await cancel.run({ workflow_id: started.workflow.id, reason: "no source change required" }, {
+ actor, workflowActor: actor, scope: "exec",
+ }) as { cleanup: { autoRemoved?: boolean; worktreeCleanupRequired: boolean } };
+ expect(result.cleanup).toMatchObject({ autoRemoved: true, worktreeCleanupRequired: false });
+ await expect(fs.lstat(workspace)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+});
diff --git a/lib/mcp/workflow-workspace-guard.test.ts b/lib/mcp/workflow-workspace-guard.test.ts
new file mode 100644
index 00000000..7fa41160
--- /dev/null
+++ b/lib/mcp/workflow-workspace-guard.test.ts
@@ -0,0 +1,46 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { resetWorkflowStoreCache, startWorkflow } from "@/lib/workflow";
+import { requireWorkflowExecCwd, requireWorkflowMutationPath } from "./workflow-workspace-guard";
+
+const roots: string[] = [];
+afterEach(async () => {
+ vi.unstubAllEnvs(); resetWorkflowStoreCache();
+ await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));
+});
+
+async function isolatedFixture() {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-workspace-guard-")); roots.push(root);
+ const project = path.join(root, "project"), workspace = path.join(root, "worktree");
+ await fs.mkdir(project); await fs.mkdir(workspace);
+ vi.stubEnv("OS_SKILL_MEMORY_STORE", path.join(root, "workflow.json")); resetWorkflowStoreCache();
+ const started = await startWorkflow({
+ actor: "mcp:test", scope: "exec", intent: "implement source change", project,
+ orchestration: {
+ risk: "medium", complexity: "medium", contention: "none", memoryRelevance: "medium",
+ isolation: "isolated-worktree", verification: "affected", reasons: [], sharedResourceWarnings: [],
+ changedPaths: [], affectedPaths: [], reservedResources: [workspace], overlappingPaths: [], overlappingResources: [],
+ activeProjectWorkflows: 0, conflictingWorkflowCount: 0, memoryHits: 0, contextEstimateTokens: 0,
+ cleanupState: "pending", workspacePath: workspace, createdAt: new Date().toISOString(),
+ },
+ });
+ return { root, project, workspace, context: { actor: "mcp:test", workflowActor: "mcp:test", workflowId: started.workflow.id, scope: "exec" as const } };
+}
+
+describe("workflow source workspace guard", () => {
+ it("allows mutation in the task worktree and rejects canonical/host writes", async () => {
+ const { project, workspace, context } = await isolatedFixture();
+ await expect(requireWorkflowMutationPath(context, path.join(workspace, "src/a.ts"))).resolves.toBeUndefined();
+ await expect(requireWorkflowMutationPath(context, path.join(project, "src/a.ts"))).rejects.toThrow(/source-isolated/i);
+ await expect(requireWorkflowMutationPath(context, path.join(os.homedir(), "outside.txt"))).rejects.toThrow(/source-isolated/i);
+ });
+
+ it("requires shell cwd to be explicit and inside the task worktree", async () => {
+ const { project, workspace, context } = await isolatedFixture();
+ await expect(requireWorkflowExecCwd(context, workspace)).resolves.toBeUndefined();
+ await expect(requireWorkflowExecCwd(context)).rejects.toThrow(/exec requires cwd/i);
+ await expect(requireWorkflowExecCwd(context, project)).rejects.toThrow(/exec cwd/i);
+ });
+});
diff --git a/lib/mcp/workflow-workspace-guard.ts b/lib/mcp/workflow-workspace-guard.ts
new file mode 100644
index 00000000..c3d03d6c
--- /dev/null
+++ b/lib/mcp/workflow-workspace-guard.ts
@@ -0,0 +1,60 @@
+import type { CapabilityRunContext } from "@/lib/capabilities/tool";
+import { activeWorkflowForActor } from "@/lib/workflow";
+import os from "node:os";
+import path from "node:path";
+
+function absolute(value: string): string {
+ if (value === "~") return os.homedir();
+ if (value.startsWith("~/")) return path.join(os.homedir(), value.slice(2));
+ return path.resolve(value);
+}
+
+function inside(root: string, candidate: string): boolean {
+ const rel = path.relative(root, candidate);
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
+}
+
+async function isolatedWorkspace(context: CapabilityRunContext) {
+ const actor = context.workflowActor ?? context.actor;
+ if (!actor || !context.workflowId) return null;
+ const workflow = await activeWorkflowForActor(actor, context.workflowId);
+ if (!workflow?.orchestration || workflow.orchestration.isolation !== "isolated-worktree") return null;
+ const project = workflow.project ? absolute(workflow.project) : null;
+ const workspace = workflow.orchestration.workspacePath ? absolute(workflow.orchestration.workspacePath) : null;
+ if (!project || !workspace) throw new Error("isolated source workflow has no verified workspace; cancel/restart it before mutation");
+ return { project, workspace, workflowId: workflow.id };
+}
+
+/** Mutating filesystem tools are workspace-bound once workflow_start selected
+ * isolated source work. The guard is deliberately stricter than the generic FS
+ * jail: source tasks do not get to write elsewhere on the host just because an
+ * Owner token technically could. */
+export async function requireWorkflowMutationPath(context: CapabilityRunContext, rawPath: string): Promise<void> {
+ const isolated = await isolatedWorkspace(context);
+ if (!isolated || isolated.workspace === isolated.project) return;
+ const target = absolute(rawPath);
+ if (!inside(isolated.workspace, target)) {
+ throw new Error(`workflow ${isolated.workflowId} is source-isolated; mutate only inside ${isolated.workspace}`);
+ }
+}
+
+/** Shell is the widest authority surface. During isolated source work it must
+ * have an explicit cwd inside the task worktree; host/production commands belong
+ * in a separate reviewed workflow. */
+export async function requireWorkflowExecCwd(context: CapabilityRunContext, rawCwd?: string): Promise<void> {
+ const isolated = await isolatedWorkspace(context);
+ if (!isolated || isolated.workspace === isolated.project) return;
+ if (!rawCwd) throw new Error(`workflow ${isolated.workflowId} is source-isolated; exec requires cwd inside ${isolated.workspace}`);
+ const cwd = absolute(rawCwd);
+ if (!inside(isolated.workspace, cwd)) {
+ throw new Error(`workflow ${isolated.workflowId} is source-isolated; exec cwd must stay inside ${isolated.workspace}`);
+ }
+}
+
+export async function requireWorkflowProjectTarget(context: CapabilityRunContext, projectPath: string): Promise<void> {
+ const isolated = await isolatedWorkspace(context);
+ if (!isolated || isolated.workspace === isolated.project) return;
+ if (!inside(isolated.workspace, absolute(projectPath))) {
+ throw new Error(`workflow ${isolated.workflowId} is source-isolated; project execution must target ${isolated.workspace}`);
+ }
+}
diff --git a/lib/orchestration/classifier.test.ts b/lib/orchestration/classifier.test.ts
index 27103898..e52260bc 100644
--- a/lib/orchestration/classifier.test.ts
+++ b/lib/orchestration/classifier.test.ts
@@ -1,20 +1,26 @@
import { describe, expect, it } from "vitest";
-import { classifyTask, gitChangedPaths, sharedResourceWarnings } from "./classifier";
+import { classifyTask, gitChangedPaths, sharedResourceWarnings, sourceChangeLikely } from "./classifier";
describe("RASMIC risk and contention classifier", () => {
- it("keeps trivial docs work direct without a worktree", () => {
+ it("keeps trivial docs work low-risk but isolates the source mutation", () => {
const result = classifyTask({ intent: "fix a typo in docs only", scope: "write" });
expect(result).toMatchObject({
risk: "low",
complexity: "light",
- isolation: "direct",
+ isolation: "isolated-worktree",
verification: "targeted",
});
});
- it("marks contained feature work medium with optional isolation", () => {
+ it("isolates contained feature work even when its risk remains medium", () => {
const result = classifyTask({ intent: "implement one contained feature across a few files", scope: "write" });
- expect(result).toMatchObject({ risk: "medium", isolation: "optional-worktree", verification: "affected" });
+ expect(result).toMatchObject({ risk: "medium", isolation: "isolated-worktree", verification: "affected" });
+ });
+
+ it("does not create source-change pressure for a read-only project audit", () => {
+ expect(sourceChangeLikely("audit the repository and explain the current state")).toBe(false);
+ const result = classifyTask({ intent: "audit the repository and explain the current state", scope: "write" });
+ expect(result.isolation).toBe("direct");
});
it("requires isolated work for high-risk auth/schema/infra work", () => {
diff --git a/lib/orchestration/classifier.ts b/lib/orchestration/classifier.ts
index 09d0b509..31c0bbd6 100644
--- a/lib/orchestration/classifier.ts
+++ b/lib/orchestration/classifier.ts
@@ -36,6 +36,20 @@ const MEMORY_HIGH = [
/\brecipe|script|automation|memory\b/i,
];
+const SOURCE_CHANGE_VERB = /\b(implement|fix|edit|modify|refactor|patch|add|remove|rename|write|rewrite)\b/i;
+const SOURCE_CHANGE_OBJECT = /\b(code|source|files?|repo(?:sitory)?|docs?|documentation|ui|component|tests?|scripts?|config(?:uration)?|package|lockfile|feature)\b/i;
+const SOURCE_CHANGE_WEAK_VERB = /\b(update|change)\b/i;
+
+/** Safety-biased signal for repository/source mutation. It is intentionally
+ * separate from risk: a typo remains low risk but still belongs in a task-owned
+ * worktree so canonical main never becomes shared scratch space. */
+export function sourceChangeLikely(intent: string, constraints = "", affectedPaths: string[] = []): boolean {
+ if (affectedPaths.length > 0) return true;
+ const text = `${intent}\n${constraints}`;
+ if (SOURCE_CHANGE_VERB.test(text)) return true;
+ return SOURCE_CHANGE_WEAK_VERB.test(text) && SOURCE_CHANGE_OBJECT.test(text);
+}
+
const SHARED_RESOURCE_RULES: Array<[RegExp, string]> = [
[/\bpackage\.json\b|\b(?:bun|package|pnpm|yarn)-?lock\b/i, "package manifest/lockfile is shared"],
[/\b(schema|migration|database|db)\b/i, "database/schema is shared"],
@@ -118,7 +132,9 @@ export function classifyTask(input: {
if (MEMORY_HIGH.some((rule) => rule.test(text)) || complexity === "heavy") memoryRelevance = "high";
else if (complexity === "medium") memoryRelevance = "medium";
- const isolation: TaskClassification["isolation"] = risk === "high"
+ const sourceChange = input.scope !== "read" && sourceChangeLikely(input.intent, input.constraints, input.collisionPaths?.length ? input.collisionPaths : []);
+ if (sourceChange) reasons.push("repository/source mutation should use a task-owned worktree");
+ const isolation: TaskClassification["isolation"] = risk === "high" || sourceChange
? "isolated-worktree"
: risk === "medium"
? "optional-worktree"