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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
merge: reconcile launch hardening and second brain
Rahmanc3f1ad53f09b
diff --cc app/api/v1/workflows/route.tsindex 536d7850,df121ac4..b8a8002f--- a/app/api/v1/workflows/route.ts+++ b/app/api/v1/workflows/route.ts@@@ -21,11 -23,10 +23,10 @@@ import { workflowTemplate, workflowTempimport { suggestWorkflowGraph } from "@/lib/workflow/ai-assist";import { workflowMatchesQuery } from "@/lib/workflow/search";import { resolveProjectHint } from "@/lib/host/projects-api";- import { listAutomationScripts, readAutomationScript } from "@/lib/orchestration/repo-memory-artifacts";- import { listLearnedRecipes, recipeMaturity } from "@/lib/workflow";+ import { listAutomationScripts } from "@/lib/orchestration/repo-memory-artifacts";import { createWorkflowDataTable, deleteWorkflowDataTable, deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "@/lib/workflow/data-table-store";import { optimizeWorkflowGraph } from "@/lib/workflow/graph-optimizer";-import { createJevWorkflowOptimizerEvaluator } from "@/lib/workflow/jev-optimizer";+import { createResolvedJevWorkflowOptimizerEvaluator } from "@/lib/workflow/jev-evaluator";import { resolveJevIntegrationConfig } from "@/lib/workflow/jev-integration";export const runtime="nodejs";export const dynamic="force-dynamic";const headers={"Cache-Control":"no-store, private"};const fail=(error:unknown,status=400)=>NextResponse.json({error:error instanceof Error?error.message.slice(0,500):String(error).slice(0,500)||"workflow request failed"},{status,headers});diff --cc docs/PROGRESS.mdindex 761c4a60,73428ab8..337f0037--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@@ -1,7 -1,3 +1,33 @@@++## 2026-09-26 — Crash-safe continuation and source-isolated agent work++++ChatGPT/MCP continuation no longer depends on the user recovering a dead tab or++manually finding a durable session id. `agent_session_resume` can auto-select the++newest relevant unfinished workflow/session by stable principal and project, return++safe recent context plus a fresh `workflow_start` recipe, and return human session++candidates rather than guessing when multiple unfinished tasks are plausible. Old++workflow ids remain conversation-scoped and are never reused across sessions.++++Source-changing workflows now prepare a task-owned linked Git worktree after++read-only discovery succeeds. Workflow-bound filesystem/project/shell mutations are++restricted to that workspace; a dirty canonical checkout fails closed instead of++being stashed, reset, or overwritten. Clean unused task worktrees may be removed++only by their own workflow close path; changed work is preserved.++++The release reconciliation keeps both JEV session optimization and the new Workflow++learning/second-brain surfaces. JEV archive receipts remain checksum-bound++preservation evidence, but they are not deletion authority: fail-closed session++preservation keeps raw archives until a separate explicit source-release policy++exists. This supersedes the earlier same-day wording that a JEV receipt alone could++authorize aged archive deletion.++++Conflict-focused regression coverage passed 35/35 plus TypeScript and targeted++zero-warning ESLint before the full release gate. Full build/runtime evidence remains++a separate release-stage requirement and is not implied by this entry.+++## 2026-09-26 — JEV session preservation + OpenRouter SSOT++JEV now uses `~typesafe/jev-latest` through OpenRouter’s Decisions API by default. Its credential is read from the same `hostCredentialStore()` used by Settings → AI and Integrations → AI Providers, so MSO no longer needs a separate TypeSafe/JEV token for the normal path. Existing named MCP JEV connections and the `JEV` Integration Variable remain explicit diagnostic compatibility overrides. Workflow Sessions expose **Use JEV**, can copy a bounded `mso.jev-session-optimization.v1` packet for another LLM, and expose **Optimize all before cleanup**. Batch preservation covers both live durable sessions and archived compacted session snapshots. Old archive deletion is hard-gated by an exact SHA-256-bound JEV preservation receipt; unpreserved archives and their action indexes are retained instead of silently aging out.+## 2026-09-26 — Make DOKU credential fields self-explanatoryThe native DOKU setup form now puts the official source beside each credentialdiff --cc frontend/slices/workflows/components/workflow-session-details.tsxindex eb091920,fa9d1224..ece08687--- a/frontend/slices/workflows/components/workflow-session-details.tsx+++ b/frontend/slices/workflows/components/workflow-session-details.tsx@@@ -1,13 -1,14 +1,14 @@@"use client";import { useState } from "react";+ import { WorkflowLearningPanel } from "./workflow-learning-panel";-import { Code2, Copy, ExternalLink, FileCode2, GitCompareArrows, History, Save, TerminalSquare } from "lucide-react";+import { BrainCircuit, Code2, Copy, ExternalLink, FileCode2, GitCompareArrows, History, Save, TerminalSquare } from "lucide-react";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { ScrollArea } from "@/components/ui/scroll-area";import type { SessionFlowAction, SessionFlowStep, SessionGraphView } from "@/lib/contracts/session-monitor";import type { WorkflowGraphNode } from "@/lib/contracts/workflow-graph";- import { getSessionArtifactHistory, optimizeSessionWithJev, type JevSessionOptimization, type SessionArtifactHistoryResponse, type WorkflowLearningRecipeSummary } from "../lib/api";-import { getSessionArtifactHistory, type SessionArtifactHistoryResponse } from "../lib/api";++import { getSessionArtifactHistory, optimizeSessionWithJev, type JevSessionOptimization, type SessionArtifactHistoryResponse } from "../lib/api";function value(config: Record<string, unknown>, key: string): string | undefined {const raw = config[key]; return typeof raw === "string" && raw ? raw : undefined;@@@ -82,26 -83,9 +83,13 @@@ function actionGroups(step: SessionFlow});}- function SelfImprove({ recipes }: { recipes: WorkflowLearningRecipeSummary[] }) {- return <div data-slot="session-self-improve" className="border-t pt-3">- <div className="mb-2 flex items-center gap-1.5 text-[10px] font-semibold uppercase text-muted-foreground"><BrainCircuit className="size-3.5"/>Self-improve</div>- {recipes.length ? <div className="space-y-2">{recipes.slice(0, 4).map((recipe) => <div key={recipe.id} className="rounded-lg border bg-background/35 p-2.5">- <div className="flex flex-wrap items-center gap-1.5"><Badge variant="outline" className="h-5 text-[9px] capitalize">{recipe.stage}</Badge><span className="min-w-0 flex-1 truncate text-xs font-medium">{recipe.intent}</span></div>- <div className="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-[10px] text-muted-foreground"><span>{recipe.attempts} attempts</span><span>{recipe.successRate}% success</span>{recipe.fastestDurationMs != null ? <span>fastest {Math.max(1, Math.round(recipe.fastestDurationMs / 1000))}s</span> : null}</div>- <div className="mt-1.5 flex flex-wrap gap-1">{recipe.sourceSessions.filter((source, index, rows) => rows.findIndex((row) => row.actionRef === source.actionRef) === index).slice(0, 8).map((source) => <code key={`${source.actionRef}-${source.eventRef}`} className="rounded bg-muted px-1.5 py-0.5 text-[9px]">{source.actionRef}</code>)}</div>- <p className="mt-1.5 text-[9px] text-muted-foreground">{recipe.stage === "tested" ? "Tested automation is reusable when current evidence matches." : recipe.stage === "verified" ? "Verified route; current task still requires independent verification." : recipe.stage === "candidate" ? "Repeated route; use as a planning shortcut, not a guarantee." : "Observed route; more successful runs are needed."}{recipe.forge.eligible ? " Skill/tool promotion remains explicit through Tool Forge." : ""}</p>- </div>)}</div> : <p className="rounded-lg border border-dashed p-2.5 text-[10px] text-muted-foreground">No learned recipe is linked to this session yet. A verified <code>workflow_finish</code> can attach future recipe steps to their <code>Sx.Ay</code> receipts.</p>}- </div>;- }-- export function WorkflowSessionDetails({ view, node, onOpenTerminal, onOpenCode, onSaveDraft, savingDraft = false, learning = [] }: { view: SessionGraphView; node: WorkflowGraphNode | null; onOpenTerminal: () => void; onOpenCode: (path: string) => void; onSaveDraft: (stepRef?: string) => void; savingDraft?: boolean; learning?: WorkflowLearningRecipeSummary[] }) {+ export function WorkflowSessionDetails({ view, node, onOpenTerminal, onOpenCode, onSaveDraft, savingDraft = false }: { view: SessionGraphView; node: WorkflowGraphNode | null; onOpenTerminal: () => void; onOpenCode: (path: string) => void; onSaveDraft: (stepRef?: string) => void; savingDraft?: boolean }) {const ref = node ? value(node.config, "ref") : undefined;const step: SessionFlowStep | undefined = ref ? view.steps.find((item) => item.ref === ref) : undefined;- const linked = learning.filter((recipe) => recipe.sourceSessions.some((source) => source.label === view.session.label));+ const [jev, setJev] = useState<JevSessionOptimization | null>(null);+ const [jevBusy, setJevBusy] = useState(false);+ const [jevError, setJevError] = useState("");+ const runJev = async () => { setJevBusy(true); setJevError(""); try { setJev(await optimizeSessionWithJev(view.session.id)); } catch (cause) { setJevError(cause instanceof Error ? cause.message : "JEV unavailable"); } finally { setJevBusy(false); } };return <div className="flex h-full min-h-0 flex-col bg-card/20"><div className="border-b p-3"><div className="break-words text-sm font-semibold">{view.session.label}</div>diff --cc lib/agent/session-archive.tsindex f2553a89,4a18e97f..7a9e0dbd--- a/lib/agent/session-archive.ts+++ b/lib/agent/session-archive.ts@@@ -1,4 -1,5 +1,5 @@@-import { randomUUID } from "node:crypto";+import { createHash, randomUUID } from "node:crypto";+ import { sessionPreservation } from "./session-preservation";import { constants as fsConstants, promises as fs } from "node:fs";import os from "node:os";import path from "node:path";@@@ -130,9 -58,10 +131,10 @@@ export async function pruneAgentSessionconst root = await secureRoot();const cutoff = now - archiveRetentionDays() * 86_400_000;const names = await fs.readdir(root).catch(() => [] as string[]);- let removed = 0, kept = 0;+ let removed = 0, kept = 0, blocked = 0;for (const name of names) {if (!ARCHIVE_FILE.test(name)) continue;- if ((await sessionPreservation(name.split("__")[0])).protected) { kept++; continue; }++ if ((await sessionPreservation(name.split("__")[0])).protected) { blocked++; kept++; continue; }const file = path.join(root, name);let handle: Awaited<ReturnType<typeof fs.open>> | null = null;try {diff --cc lib/agent/session-store.test.tsindex 162a760f,9ee9b73a..fc090591--- a/lib/agent/session-store.test.ts+++ b/lib/agent/session-store.test.ts@@@ -52,19 -50,15 +52,22 @@@ describe("durable agent session contexexpect(archived).toContain("[redacted]");});- it("blocks old archive cleanup until an exact JEV preservation receipt exists", async () => {- it("preserves unreviewed archives beyond the 30-day age window", async () => {++ it("keeps raw archives protected even after an exact JEV preservation receipt", async () => {const [name] = (await fs.readdir(archives)).filter((row) => row.endsWith(".json.gz"));const file = path.join(archives, name);const old = new Date(Date.now() - 31 * 86_400_000);await fs.utimes(file, old, old);+ const blocked = await archive.pruneAgentSessionArchives();+ expect(blocked).toMatchObject({ removed: 0, blocked: 1 });+ await expect(fs.stat(file)).resolves.toBeTruthy();+ const archived = await archive.readAgentSessionArchive(name);+ await archive.writeAgentSessionArchiveJevReceipt(name, archived.sha256, { optimization: { kind: "fixture" } });const result = await archive.pruneAgentSessionArchives();- expect(result).toMatchObject({ removed: 1, blocked: 0 });- await expect(fs.stat(file)).rejects.toMatchObject({ code: "ENOENT" });++ expect(await archive.hasAgentSessionArchiveJevReceipt(name, file)).toBe(true);+ expect(result.removed).toBe(0);++ expect(result.blocked).toBeGreaterThan(0);+ expect(result.kept).toBeGreaterThan(0);+ expect((await fs.stat(file)).isFile()).toBe(true);});it("allows an explicit rename to replace a manual title and refresh modified time", async () => {diff --cc lib/mcp/tools-mutate.tsindex 193a3794,18770ace..fdd7b926--- a/lib/mcp/tools-mutate.ts+++ b/lib/mcp/tools-mutate.ts@@@ -13,10 -14,10 +14,7 @@@ export const MUTATE_TOOLS: McpTool[] =name: "fs_write",limit: { key: "fs.write", max: 120, windowMs: 60_000 },audit: { action: "fs.write" as const, targetArg: "path" },-- description:-- "Create or overwrite a text file on the VPS. Inspect with fs_read first and pass its SHA-256 as expected_sha256 " +-- "to refuse a stale overwrite when another process changed the file. Omitting the hash keeps legacy overwrite behaviour. " +-- "Bounded to OS_FS_WRITE_ROOTS (home + ~/projects by default).",++ description: "Create or overwrite a text file on the VPS. Inspect with fs_read first and pass its SHA-256 as expected_sha256 to refuse a stale overwrite when another process changed the file. Omitting the hash keeps legacy overwrite behaviour. Bounded to OS_FS_WRITE_ROOTS (home + ~/projects by default).",scope: "write",annotations: { idempotentHint: true },actionContract: { phase: "mutate", target: "filesystem-text", sourceOfTruth: "live", discover: ["fs_read"], validators: ["path-policy", "sha256-cas"], verify: ["fs_read"], confirmation: "contextual", concurrency: "hash", presentation: "structured" },@@@ -100,9 -107,9 +104,7 @@@name: "fs_delete",limit: { key: "fs.delete", max: 60, windowMs: 60_000 },audit: { action: "fs.delete" as const, targetArg: "path" },-- description:-- "Delete a file or directory on the VPS. PERMANENT — there is no trash and no undo. " +-- "Confirm with the user before calling this on anything you did not create in this conversation.",++ description: "Delete a file or directory on the VPS. PERMANENT — there is no trash and no undo. Confirm with the user before calling this on anything you did not create in this conversation.",scope: "write",annotations: { destructiveHint: true },inputSchema: S(PATH_P, ["path"]),@@@ -120,10 -127,10 +122,7 @@@return { ok: code === 0, action: "exec.run", detail: `project function exit ${code}` };},},-- description:-- "Execute ONE function explicitly declared by a validated project's .mso/functions.json. " +-- "This is project code execution and therefore requires exec scope. The manifest supplies fixed argv; model/user input is passed only as JSON on stdin and is NEVER interpolated into a shell command. " +-- "Call project_capabilities first for function names and schemas. Projects without an opt-in manifest expose nothing. A function may return a validated bounded direct-image envelope for visual debugging; invalid envelopes remain ordinary text output.",++ description: "Execute ONE function explicitly declared by a validated project's .mso/functions.json. This is project code execution and therefore requires exec scope. The manifest supplies fixed argv; model/user input is passed only as JSON on stdin and is NEVER interpolated into a shell command. Call project_capabilities first for function names and schemas. Projects without an opt-in manifest expose nothing. A function may return a validated bounded direct-image envelope for visual debugging; invalid envelopes remain ordinary text output.",scope: "exec",annotations: { destructiveHint: true, openWorldHint: true },inputSchema: S({@@@ -149,9 -157,9 +149,7 @@@return { ok: !refused, action: refused ? "exec.blocked" : "exec.job.start", detail: refused ? "refused" : "started" };},},-- description:-- "Start one bounded asynchronous shell job for legitimate test/build pipelines that exceed exec_run's 30s request budget. " +-- "The job is client/workflow-bound, capped at 20 minutes and 1 MiB per output stream, limited to four concurrent jobs per client, and uses the same cwd jail and catastrophic-command filter as exec_run. Use exec_job_status to read it and exec_job_cancel to stop it.",++ description: "Start one bounded asynchronous shell job for legitimate test/build pipelines that exceed exec_run's 30s request budget. The job is client/workflow-bound, capped at 20 minutes and 1 MiB per output stream, limited to four concurrent jobs per client, and uses the same cwd jail and catastrophic-command filter as exec_run. Use exec_job_status to read it and exec_job_cancel to stop it.",scope: "exec",annotations: { destructiveHint: true, openWorldHint: true },inputSchema: S({@@@ -201,11 -213,11 +203,7 @@@return { ok: !blocked && code === 0, action: blocked ? "exec.blocked" : "exec.run", detail: `exit ${code}` };},},-- description:-- "Run a shell command on the VPS as the owner and return stdout, stderr and exit code. " +-- "Do not use this as the first call: start multi-step work with workflow_start and prefer bounded reads or read_pipeline. FULL HOST POWER — prefer fs_* and sys_* tools whenever they cover the task; they are bounded and " +-- "this is not. Catastrophic patterns (rm -rf /, fork bombs, disk wipes) are refused by the server. " +-- "Long-running or interactive commands will time out: this is not a terminal session.",++ description: "Run a shell command on the VPS as the owner and return stdout, stderr and exit code. Do not use this as the first call: start multi-step work with workflow_start and prefer bounded reads or read_pipeline. FULL HOST POWER — prefer fs_* and sys_* tools whenever they cover the task; they are bounded and this is not. Catastrophic patterns (rm -rf /, fork bombs, disk wipes) are refused by the server. Long-running or interactive commands will time out: this is not a terminal session.",chatgptDescription: "Last resort shell; prefer reads/read_pipeline first.", scope: "exec",annotations: { destructiveHint: true, openWorldHint: true },result: { maxTextBytes: 48 * 1024, overflowHint: "Command output was compacted; rerun a narrower command (grep/head/tail) for the omitted evidence." },diff --cc lib/mcp/tools-workflow-start.tsindex 5f6bc989,bec7df7b..a080bb6b--- a/lib/mcp/tools-workflow-start.ts+++ b/lib/mcp/tools-workflow-start.ts@@@ -1,5 -1,7 +1,6 @@@- import { ownedArtifactSession, prepareSessionArtifacts } from "@/lib/agent/artifact-session"; import { inspectProject, readProjectKnowledge, resolveProjectHint } from "@/lib/host/projects-api";- import { listLearnedRecipes, markRecipeRecommended, startWorkflow, summarizeProjectContention } from "@/lib/workflow";+ 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 { listLearnedRecipes, markRecipeRecommended, summarizeProjectContention } from "@/lib/workflow";import { ensureLearnedWorkflowGraph, findMatchingWorkflowGraph } from "@/lib/workflow/graph-store";import { progressiveVerification } from "@/lib/orchestration/automation";import { routeIntentText } from "@/lib/orchestration/capability-catalog.mjs";@@@ -14,7 -16,6 +15,8 @@@ import { WORKFLOW_START_OUTPUT, workfloimport { workflowStartAgentMemory } from "./workflow-start-memory";import { AGENT_BOOTSTRAP_SKILL, workflowOrientation, workflowStartPolicy } from "./instructions";import { workflowStartCandidateContext } from "./workflow-start-candidates";++import { prepareWorkflowStartWorkspace, startWorkflowWithWorkspace, workflowWorkspaceResources } from "./workflow-start-workspace";+import { updateAgentSessionLocation } from "@/lib/agent/session-store";export const WORKFLOW_START_TOOL: McpTool = {name: "workflow_start",description: "First call for multi-step work: resolve project context, search trusted skills/recipes/graphs, and return workflow_id. Carry that exact id on later steps. Read official skill mso-agent-bootstrap when learning the MSO map.",@@@ -108,12 -108,21 +110,14 @@@...(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 isolatedWorkspace = await prepareWorkflowStartWorkspace(project?.path, repository?.git.available, classification.isolation);+ 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),++ changedPaths, affectedPaths, reservedResources: workflowWorkspaceResources(reservedResources, isolatedWorkspace),overlappingPaths: contention.overlappingPaths, overlappingResources: contention.overlappingResources,activeProjectWorkflows, conflictingWorkflowCount: contention.conflictingWorkflowCount,memoryHits: agentMemory.length + repoMemory.length + (search.recommendedRecipe ? 1 : 0),@@@ -143,15 -152,21 +147,10 @@@...(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;- }++ const started = await startWorkflowWithWorkspace({++ actor, scope: context.scope, intent, project: project?.path ?? projectHint,++ constraints: opt(a, "constraints"), orchestration, candidatePool,++ }, isolatedWorkspace);if (search.recommendedRecipe) {await markRecipeRecommended(search.recommendedRecipe.id, { actor: recipeOwner, scope: context.scope }).catch(() => undefined);}@@@ -211,7 -227,10 +211,7 @@@"[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}` } : {}),- },++ 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 --cc lib/mcp/workflow-start-workspace.tsindex 00000000,00000000..efca5915new file mode 100644--- /dev/null+++ b/lib/mcp/workflow-start-workspace.ts@@@ -1,0 -1,0 +1,29 @@@++import { discardPreparedProjectWorktree, prepareProjectWorktree, type PreparedProjectWorktree } from "@/lib/host/project-worktree";++import { startWorkflow } from "@/lib/workflow";++import type { TaskClassification } from "@/lib/orchestration/types";++++export async function prepareWorkflowStartWorkspace(++ projectPath: string | undefined,++ gitAvailable: boolean | undefined,++ isolation: TaskClassification["isolation"],++): Promise<PreparedProjectWorktree | undefined> {++ return projectPath && gitAvailable && isolation === "isolated-worktree"++ ? prepareProjectWorktree(projectPath)++ : undefined;++}++++export function workflowWorkspaceResources(resources: string[], workspace?: PreparedProjectWorktree): string[] {++ return [...new Set([...resources, ...(workspace?.created ? [workspace.workspacePath] : [])])].slice(0, 40);++}++++export async function startWorkflowWithWorkspace(++ input: Parameters<typeof startWorkflow>[0],++ workspace?: PreparedProjectWorktree,++) {++ try {++ return await startWorkflow(input);++ } catch (error) {++ if (workspace?.created) await discardPreparedProjectWorktree(workspace).catch(() => false);++ throw error;++ }++}