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(agent): recover interrupted sessions automatically

Rahman57e306c4ee16
diff --git a/claude-skills/mso-agent-bootstrap/SKILL.md b/claude-skills/mso-agent-bootstrap/SKILL.md
index 93b4282e..1e12bfdb 100644
--- a/claude-skills/mso-agent-bootstrap/SKILL.md
+++ b/claude-skills/mso-agent-bootstrap/SKILL.md
@@ -31,6 +31,11 @@ not missing features.
3. `workflow_start` once for multi-step work; pass exact `workflow_id` thereafter.
Skip this on a read token. Do not call `skills_search` immediately before startup
for the same task.
+ If the user is continuing work from a dead/overlong conversation and did not
+ provide a session id, call `agent_session_resume` with the project when known.
+ It auto-selects the newest relevant unfinished workflow/session and returns a
+ safe continuation recipe. Never ask the user to hunt for an MSO session id
+ unless recovery is genuinely ambiguous or no matching durable state exists.
4. Project MCP: `project_capabilities` → `project_mcp_tools` → `project_mcp_call`.
Never fuse discover and call. Never copy project tool names into the global catalog.
5. Credentials: `integration_query` → private setup/verify → `integration_execute`.
diff --git a/lib/agent/session-query.ts b/lib/agent/session-query.ts
index 2d0e7fae..c045d46b 100644
--- a/lib/agent/session-query.ts
+++ b/lib/agent/session-query.ts
@@ -100,6 +100,44 @@ export async function resolveAgentSessionRef(
);
}
+function normalizedProjectRef(value: string): string {
+ return value.trim().replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
+}
+
+function continuationProjectMatch(record: AgentSession, refs: string[]): boolean {
+ const aliases = new Set<string>();
+ for (const raw of refs) {
+ const normalized = normalizedProjectRef(raw);
+ if (!normalized) continue;
+ aliases.add(normalized);
+ const basename = normalized.split("/").filter(Boolean).at(-1);
+ if (basename) aliases.add(basename);
+ }
+ if (!aliases.size) return true;
+ const cwd = normalizedProjectRef(record.cwd ?? "");
+ const cwdBase = cwd.split("/").filter(Boolean).at(-1) ?? "";
+ if (aliases.has(cwd) || aliases.has(cwdBase)) return true;
+ const haystack = [
+ record.title,
+ ...record.events.slice(-80).map((event) => event.detail ?? ""),
+ ].join("\n").toLowerCase();
+ return [...aliases].some((alias) => alias.length >= 3 && haystack.includes(alias));
+}
+
+/** Resolve a crash-recovery source without making the user find a session id. */
+export async function resolveAgentSessionContinuation(
+ principal: string,
+ options: { excludeSessionId?: string; projectRefs?: string[] } = {},
+): Promise<AgentSession> {
+ const owner = principalHash(principal);
+ const candidates = (await listSessionRecords())
+ .filter((row) => row.principalHash === owner && row.id !== options.excludeSessionId)
+ .filter((row) => continuationProjectMatch(row, options.projectRefs ?? []))
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
+ if (!candidates.length) throw new Error("session_not_found");
+ return candidates[0]!;
+}
+
export async function resolveAgentSessionOwnerRef(
ref: string,
): Promise<AgentSession> {
diff --git a/lib/mcp/instructions.ts b/lib/mcp/instructions.ts
index a1a0b1b5..8a76aea1 100644
--- a/lib/mcp/instructions.ts
+++ b/lib/mcp/instructions.ts
@@ -15,7 +15,7 @@ export type AgentBootstrapStep = {
export const AGENT_BOOTSTRAP_STEPS: readonly AgentBootstrapStep[] = [
{ n: 1, call: "skills_search|skills_read", when: "Learn the map", detail: `Query or read official skill ${AGENT_BOOTSTRAP_SKILL} before expensive mutations.` },
{ n: 2, call: "projects_list", when: "Project unresolved", detail: "Resolve id/path/alias; do not guess across roots." },
- { n: 3, call: "workflow_start", when: "Multi-step work", detail: "Call once; pass exact workflow_id on every later operation." },
+ { n: 3, call: "workflow_start", when: "Multi-step work", detail: "Call once; pass exact workflow_id on every later operation. For continuation after a dead/overlong conversation, first use agent_session_resume with project when known; no session id is required." },
{ n: 4, call: "project_capabilities→project_mcp_tools→project_mcp_call", when: "Project MCP", detail: "Keep discover and call as two tools; never copy project names into the global catalog." },
{ n: 5, call: "integration_query→setup/verify→integration_execute", when: "Credentials", detail: "Never put secrets in chat or tool arguments." },
{ n: 6, call: "read_pipeline|bounded reads", when: "Inspect", detail: "Prefer these before exec_run." },
diff --git a/lib/mcp/tools-agent-recovery.test.ts b/lib/mcp/tools-agent-recovery.test.ts
new file mode 100644
index 00000000..b71bf31e
--- /dev/null
+++ b/lib/mcp/tools-agent-recovery.test.ts
@@ -0,0 +1,133 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-tools-agent-recovery-"));
+process.env.OS_AGENT_MEMORY_DIR = root;
+process.env.OS_AGENT_SESSIONS_DIR = path.join(root, "sessions");
+process.env.OS_SKILL_MEMORY_STORE = path.join(root, "skill-memory.json");
+vi.resetModules();
+
+const { AGENT_TOOLS } = await import("./tools-agent");
+const sessions = await import("@/lib/agent/session-store");
+const workflow = await import("@/lib/workflow");
+
+function tool(name: string) {
+ const found = AGENT_TOOLS.find((row) => row.name === name);
+ if (!found) throw new Error("missing tool " + name);
+ return found;
+}
+
+beforeEach(async () => {
+ await fs.rm(process.env.OS_SKILL_MEMORY_STORE!, { force: true });
+ await fs.rm(process.env.OS_SKILL_MEMORY_STORE! + ".active.json", { force: true });
+ workflow.resetWorkflowStoreCache();
+});
+
+afterAll(async () => {
+ delete process.env.OS_AGENT_MEMORY_DIR;
+ delete process.env.OS_AGENT_SESSIONS_DIR;
+ delete process.env.OS_SKILL_MEMORY_STORE;
+ workflow.resetWorkflowStoreCache();
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+describe("MCP crash-safe session continuation", () => {
+ it("auto-selects the unfinished prior session and returns a fresh-workflow recipe without requiring a session ref", async () => {
+ const principal = "mcp-client:crash-recovery";
+ const prior = await sessions.createAgentSession(principal, "mcp", { title: "MSO recovery implementation" });
+ const active = await workflow.startWorkflow({
+ actor: principal + "#session:" + prior.id,
+ scope: "write",
+ intent: "implement crash-safe continuation",
+ project: "/home/rahman/projects/mso",
+ constraints: "do not reuse dead session workflow ids",
+ });
+ await workflow.recordWorkflowStep(principal + "#session:" + prior.id, active.workflow.id, {
+ id: "step-1",
+ tool: "fs_write",
+ state: "completed",
+ ts: "2026-09-26T08:10:00.000Z",
+ });
+
+ const current = await sessions.createAgentSession(principal, "mcp", { title: "Fresh ChatGPT conversation" });
+ const result = await tool("agent_session_resume").run({}, {
+ principal,
+ sessionId: current.id,
+ scope: "read" as const,
+ }) as {
+ session: { id: string; title: string };
+ continuation: {
+ source: string;
+ workflow: { intent: string; project: string; stepCount: number };
+ workflowStart: { intent: string; project: string; constraints: string };
+ instruction: string;
+ };
+ };
+
+ expect(result.session.id).toBe(prior.id);
+ expect(result.continuation).toMatchObject({
+ source: "unfinished_workflow",
+ workflow: {
+ intent: "implement crash-safe continuation",
+ project: "/home/rahman/projects/mso",
+ stepCount: 1,
+ },
+ workflowStart: {
+ intent: "implement crash-safe continuation",
+ project: "/home/rahman/projects/mso",
+ constraints: "do not reuse dead session workflow ids",
+ },
+ });
+ expect(result.continuation.instruction).toMatch(/Do not reuse the old workflow_id/);
+ expect(JSON.stringify(result.continuation)).not.toContain(active.workflow.id);
+ });
+
+ it("returns safe candidate labels instead of guessing when several unfinished sessions are recoverable", async () => {
+ const principal = "mcp-client:ambiguous-recovery";
+ const first = await sessions.createAgentSession(principal, "mcp", { title: "Batonly UI pass" });
+ const second = await sessions.createAgentSession(principal, "mcp", { title: "BelajarAI staging" });
+ const current = await sessions.createAgentSession(principal, "mcp", { title: "Fresh conversation" });
+
+ const a = await workflow.startWorkflow({
+ actor: principal + "#session:" + first.id,
+ scope: "write",
+ intent: "continue Batonly UI remediation",
+ project: "/home/rahman/projects/baton",
+ });
+ await workflow.recordWorkflowStep(principal + "#session:" + first.id, a.workflow.id, {
+ id: "a", tool: "fs_read", state: "completed", ts: "2026-09-26T08:10:00.000Z",
+ });
+ const b = await workflow.startWorkflow({
+ actor: principal + "#session:" + second.id,
+ scope: "write",
+ intent: "continue BelajarAI staging",
+ project: "/home/rahman/projects/belajar-ai",
+ });
+ await workflow.recordWorkflowStep(principal + "#session:" + second.id, b.workflow.id, {
+ id: "b", tool: "fs_read", state: "completed", ts: "2026-09-26T08:11:00.000Z",
+ });
+
+ const result = await tool("agent_session_resume").run({}, {
+ principal,
+ sessionId: current.id,
+ scope: "read" as const,
+ }) as {
+ selectionRequired: boolean;
+ candidates: Array<{ sessionRef: string; title: string; intent: string; project?: string }>;
+ instruction: string;
+ };
+
+ expect(result.selectionRequired).toBe(true);
+ expect(result.candidates).toHaveLength(2);
+ expect(result.candidates.map((row) => row.title).sort()).toEqual(["Batonly UI pass", "BelajarAI staging"]);
+ expect(result.candidates.map((row) => row.intent)).toEqual(expect.arrayContaining([
+ "continue Batonly UI remediation",
+ "continue BelajarAI staging",
+ ]));
+ expect(result.instruction).toMatch(/Do not ask the user to search MSO for an id/);
+ expect(JSON.stringify(result)).not.toContain(a.workflow.id);
+ expect(JSON.stringify(result)).not.toContain(b.workflow.id);
+ });
+});
diff --git a/lib/mcp/tools-agent-recovery.ts b/lib/mcp/tools-agent-recovery.ts
new file mode 100644
index 00000000..7868e526
--- /dev/null
+++ b/lib/mcp/tools-agent-recovery.ts
@@ -0,0 +1,136 @@
+import { getAgentSession, listAgentSessions, resumeAgentSession } from "@/lib/agent/session-store";
+import type { AgentSession } from "@/lib/agent/session-types";
+import { resolveAgentSessionContinuation, resolveAgentSessionRef } from "@/lib/agent/session-query";
+import { agentSessionLabel } from "@/lib/agent/session-name";
+import { resolveProjectHint } from "@/lib/host/projects-api";
+import { workflowRecoveryCandidates, type WorkflowRecoveryCandidate } from "@/lib/workflow";
+import { type McpTool, S } from "./tool-kit";
+
+function requiredPrincipal(context: { principal?: string }): string {
+ if (!context.principal) throw new Error("agent session principal is unavailable");
+ return context.principal;
+}
+
+function optionalString(a: Record<string, unknown>, key: string): string | undefined {
+ const value = a[key];
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
+}
+
+function continuationPayload(recovery?: WorkflowRecoveryCandidate) {
+ if (!recovery) {
+ return {
+ source: "session" as const,
+ instruction: "Use the resume packet and semantic session flow as evidence. Start a fresh workflow before new mutations.",
+ };
+ }
+ return {
+ source: "unfinished_workflow" as const,
+ workflow: {
+ intent: recovery.intent,
+ ...(recovery.project ? { project: recovery.project } : {}),
+ ...(recovery.constraints ? { constraints: recovery.constraints } : {}),
+ startedAt: recovery.startedAt,
+ lastActivityAt: recovery.lastActivityAt,
+ stepCount: recovery.stepCount,
+ recentSteps: recovery.recentSteps,
+ },
+ workflowStart: {
+ intent: recovery.intent,
+ ...(recovery.project ? { project: recovery.project } : {}),
+ ...(recovery.constraints ? { constraints: recovery.constraints } : {}),
+ },
+ instruction: "This is a crash-recovery checkpoint. Do not reuse the old workflow_id; call workflow_start with workflowStart, validate live state, then continue.",
+ };
+}
+
+export const AGENT_SESSION_RESUME_TOOL: McpTool = {
+ name: "agent_session_resume",
+ description: "Recover prior work without requiring a session id. Pass session_ref for an exact session, or omit it and optionally pass project to auto-select the newest relevant prior session/unfinished workflow. Returns safe recent context plus a fresh-workflow continuation recipe; never ChatGPT hidden transcript.",
+ scope: "read",
+ annotations: { readOnlyHint: true, idempotentHint: true },
+ inputSchema: S({
+ session_ref: { type: "string", description: "Optional human session label (agent-context), @name, title, latest/continue, or legacy exact id. Omit for crash-safe auto recovery." },
+ session_id: { type: "string", description: "Legacy exact MSO session id; prefer session_ref or auto recovery." },
+ project: { type: "string", description: "Optional project id/path/name/alias used to select the newest relevant unfinished workflow/session automatically." },
+ }),
+ run: async (a, context) => {
+ const owner = requiredPrincipal(context);
+ const ref = optionalString(a, "session_ref") || optionalString(a, "session_id");
+ const projectHint = optionalString(a, "project");
+ const resolvedProject = projectHint ? await resolveProjectHint(projectHint).catch(() => null) : null;
+ const projectRefs = [resolvedProject?.path, resolvedProject?.id, resolvedProject?.name, projectHint]
+ .filter((value): value is string => Boolean(value));
+
+ let recovery: WorkflowRecoveryCandidate | undefined;
+ let target: AgentSession;
+ if (ref) {
+ target = await resolveAgentSessionRef(owner, ref);
+ recovery = (await workflowRecoveryCandidates({
+ principal: owner,
+ projectRefs,
+ excludeSessionId: context.sessionId,
+ limit: 20,
+ })).find((row) => row.sourceSessionId === target.id);
+ } else {
+ const unfinished = await workflowRecoveryCandidates({
+ principal: owner,
+ projectRefs,
+ excludeSessionId: context.sessionId,
+ limit: 20,
+ });
+ if (!projectRefs.length && unfinished.length > 1) {
+ const candidates = (await Promise.all(unfinished.slice(0, 8).map(async (row) => {
+ const session = await getAgentSession(owner, row.sourceSessionId);
+ if (!session) return null;
+ return {
+ sessionRef: agentSessionLabel(session.name, session.title, session.cwd),
+ title: session.title,
+ intent: row.intent,
+ ...(row.project ? { project: row.project } : {}),
+ lastActivityAt: row.lastActivityAt,
+ stepCount: row.stepCount,
+ };
+ }))).filter((row): row is NonNullable<typeof row> => Boolean(row));
+ return {
+ selectionRequired: true,
+ candidates,
+ instruction: "Several unfinished workflows are recoverable. Choose the candidate that matches the user's request and call agent_session_resume again with its sessionRef or project. Do not ask the user to search MSO for an id.",
+ };
+ }
+
+ recovery = unfinished[0];
+ if (!recovery && !projectRefs.length) {
+ const priorSessions = (await listAgentSessions(owner, 20))
+ .filter((session) => session.id !== context.sessionId);
+ if (priorSessions.length > 1) {
+ return {
+ selectionRequired: true,
+ candidates: priorSessions.slice(0, 8).map((session) => ({
+ sessionRef: session.label,
+ title: session.title,
+ updatedAt: session.updatedAt,
+ ...(session.cwd ? { project: session.cwd } : {}),
+ })),
+ instruction: "Several durable sessions are recoverable. Choose the candidate that matches the user's request and call agent_session_resume again with its sessionRef. Do not ask the user to search MSO for an id.",
+ };
+ }
+ if (!priorSessions.length) throw new Error("session_not_found");
+ const onlyTarget = await getAgentSession(owner, priorSessions[0]!.id);
+ if (!onlyTarget) throw new Error("session_not_found");
+ target = onlyTarget;
+ } else {
+ const recoveredTarget = recovery
+ ? await getAgentSession(owner, recovery.sourceSessionId)
+ : await resolveAgentSessionContinuation(owner, {
+ excludeSessionId: context.sessionId,
+ projectRefs,
+ });
+ if (!recoveredTarget) throw new Error("session_not_found");
+ target = recoveredTarget;
+ }
+ }
+
+ const packet = await resumeAgentSession(owner, target.id, context.sessionId);
+ return { ...packet, continuation: continuationPayload(recovery) };
+ },
+};
diff --git a/lib/mcp/tools-agent.ts b/lib/mcp/tools-agent.ts
index 96dab701..126430ef 100644
--- a/lib/mcp/tools-agent.ts
+++ b/lib/mcp/tools-agent.ts
@@ -1,12 +1,13 @@
import { createHash } from "node:crypto";
import { forgetAgentMemory, queryAgentMemory, readAgentMemory, rememberAgentMemory, type AgentMemoryDocument, type AgentMemoryKind, type AgentMemorySensitivity } from "@/lib/agent/memory-store";
-import { agentSessionSummary, appendAgentSessionEvent, getAgentSession, listAgentSessions, renameAgentSession, resumeAgentSession } from "@/lib/agent/session-store";
+import { agentSessionSummary, appendAgentSessionEvent, getAgentSession, listAgentSessions, renameAgentSession } from "@/lib/agent/session-store";
import { type McpTool, S, str } from "./tool-kit";
import { resolveAgentSessionRef } from "@/lib/agent/session-query";
import { agentSessionLabel } from "@/lib/agent/session-name";
import { semanticSessionFlow } from "@/lib/agent/session-flow";
import { resolveHistoricalSessionAction } from "@/lib/agent/session-action-history";
import { resolveHistoricalSessionArtifact } from "@/lib/agent/session-artifact-resolver";
+import { AGENT_SESSION_RESUME_TOOL } from "./tools-agent-recovery";
function principal(context: { principal?: string }): string {
if (!context.principal) throw new Error("agent session principal is unavailable");
@@ -48,18 +49,7 @@ export const AGENT_TOOLS: McpTool[] = [
inputSchema: S({ limit: { type: "number", description: "How many sessions to return (1-100, default 20)." } }),
run: (a, context) => listAgentSessions(principal(context), Math.max(1, Math.min(100, Number(a.limit) || 20))),
},
- {
- name: "agent_session_resume",
- description: "Read the safe resume packet for one prior MSO session owned by this client. It returns summary/recent context, never ChatGPT hidden transcript.",
- scope: "read", annotations: { readOnlyHint: true, idempotentHint: true },
- inputSchema: S({ session_ref: { type: "string", description: "Human session label (agent-context), @name, title, or legacy exact id." }, session_id: { type: "string", description: "Legacy exact MSO session id; prefer session_ref." } }),
- run: async (a, context) => {
- const owner = principal(context), ref = optionalString(a, "session_ref") || optionalString(a, "session_id");
- if (!ref) throw new Error("session_ref is required");
- const target = await resolveAgentSessionRef(owner, ref);
- return resumeAgentSession(owner, target.id, context.sessionId);
- },
- },
+ AGENT_SESSION_RESUME_TOOL,
{
name: "agent_session_flow",
description: "Read one session as a compact semantic flow for humans and agents. Returns intent-level steps with human-readable Sx.Ay action references, sanitized execution receipts, commands/code hints, and artifacts without exposing the internal session id. Pass action_ref to jump directly to one action.",
diff --git a/lib/mcp/tools-workflow-start.ts b/lib/mcp/tools-workflow-start.ts
index e3643359..5f6bc989 100644
--- a/lib/mcp/tools-workflow-start.ts
+++ b/lib/mcp/tools-workflow-start.ts
@@ -1,5 +1,4 @@
-import { ownedArtifactSession, prepareSessionArtifacts } from "@/lib/agent/artifact-session";
-import { inspectProject, readProjectKnowledge, resolveProjectHint } from "@/lib/host/projects-api";
+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 { ensureLearnedWorkflowGraph, findMatchingWorkflowGraph } from "@/lib/workflow/graph-store";
import { progressiveVerification } from "@/lib/orchestration/automation";
@@ -15,6 +14,7 @@ import { WORKFLOW_START_OUTPUT, workflowStartProjection } from "./tools-workflow
import { workflowStartAgentMemory } from "./workflow-start-memory";
import { AGENT_BOOTSTRAP_SKILL, workflowOrientation, workflowStartPolicy } from "./instructions";
import { workflowStartCandidateContext } from "./workflow-start-candidates";
+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.",
@@ -40,6 +40,7 @@ export const WORKFLOW_START_TOOL: McpTool = {
const agentMemory = await workflowStartAgentMemory(context, intent);
const projectHint = opt(a, "project");
const project = projectHint ? await resolveProjectHint(projectHint).catch(() => null) : null;
+ if (project?.path && context.principal && context.sessionId) await updateAgentSessionLocation(context.principal, context.sessionId, project.path).catch(() => undefined);
const tools = await visibleTools(context.scope, context.toolProfile);
const intentRoute = routeIntentText(intent);
const routedTools = intentRoute.catalogMatched ? tools.filter((tool) => intentRoute.tools.includes(tool.name) || tool.name === "workflow_start") : tools;
diff --git a/lib/workflow/index.ts b/lib/workflow/index.ts
index 6ee2a433..c9578886 100644
--- a/lib/workflow/index.ts
+++ b/lib/workflow/index.ts
@@ -7,6 +7,8 @@ export { recipeMaturity } from "./maturity";
export { workflowStepProvenance } from "./session-provenance";
export { replayHandlesFromResult } from "./replay";
export { mergeCandidatePools } from "./candidate-pool";
+export { workflowRecoveryCandidates } from "./recovery";
+export type { WorkflowRecoveryCandidate } from "./recovery";
export type {
WorkflowStepState, WorkflowStep, WorkflowStepProvenance, WorkflowReplayHandle, WorkflowCandidatePool, RecipeMaturity, ActiveWorkflow, WorkflowQuality, LearnedRecipe,
FinishWorkflowResult, CancelWorkflowResult, RecipeAccess, ProjectContentionSummary,
diff --git a/lib/workflow/recovery.test.ts b/lib/workflow/recovery.test.ts
new file mode 100644
index 00000000..3053b5a8
--- /dev/null
+++ b/lib/workflow/recovery.test.ts
@@ -0,0 +1,81 @@
+import { afterAll, beforeEach, describe, expect, it } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const file = path.join(os.tmpdir(), "mso-workflow-recovery-" + process.pid + ".json");
+process.env.OS_SKILL_MEMORY_STORE = file;
+
+const workflow = await import("./index");
+
+beforeEach(async () => {
+ await fs.rm(file, { force: true });
+ await fs.rm(file + ".active.json", { force: true });
+ workflow.resetWorkflowStoreCache();
+});
+
+afterAll(async () => {
+ await fs.rm(file, { force: true });
+ await fs.rm(file + ".active.json", { force: true });
+ delete process.env.OS_SKILL_MEMORY_STORE;
+ workflow.resetWorkflowStoreCache();
+});
+
+describe("workflow crash recovery", () => {
+ it("finds unfinished project work across sessions without exposing the old workflow id", async () => {
+ const principal = "mcp-client:recover";
+ const a = principal + "#session:session-a";
+ const b = principal + "#session:session-b";
+ const other = principal + "#session:session-c";
+
+ const first = await workflow.startWorkflow({
+ actor: a,
+ scope: "write",
+ intent: "continue MSO session recovery",
+ project: "/home/rahman/projects/mso",
+ constraints: "preserve session isolation",
+ });
+ await workflow.recordWorkflowStep(a, first.workflow.id, {
+ id: "a-1",
+ tool: "fs_read",
+ state: "completed",
+ ts: "2026-09-26T08:00:00.000Z",
+ });
+
+ const latest = await workflow.startWorkflow({
+ actor: b,
+ scope: "write",
+ intent: "finish MSO crash-safe continuation",
+ project: "/home/rahman/projects/mso",
+ });
+ await workflow.recordWorkflowStep(b, latest.workflow.id, {
+ id: "b-1",
+ tool: "fs_write",
+ state: "completed",
+ ts: "2026-09-26T08:10:00.000Z",
+ });
+
+ await workflow.startWorkflow({
+ actor: other,
+ scope: "write",
+ intent: "unrelated Batonly work",
+ project: "/home/rahman/projects/baton",
+ });
+
+ const rows = await workflow.workflowRecoveryCandidates({
+ principal,
+ projectRefs: ["mso"],
+ excludeSessionId: "session-a",
+ });
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ sourceSessionId: "session-b",
+ intent: "finish MSO crash-safe continuation",
+ project: "/home/rahman/projects/mso",
+ stepCount: 1,
+ });
+ expect(JSON.stringify(rows[0])).not.toContain(latest.workflow.id);
+ expect(JSON.stringify(rows)).not.toContain("unrelated Batonly work");
+ });
+});
diff --git a/lib/workflow/recovery.ts b/lib/workflow/recovery.ts
new file mode 100644
index 00000000..94fdb397
--- /dev/null
+++ b/lib/workflow/recovery.ts
@@ -0,0 +1,80 @@
+import { loadWorkflowStore } from "./storage";
+import type { WorkflowStep } from "./types";
+
+export type WorkflowRecoveryCandidate = {
+ sourceSessionId: string;
+ intent: string;
+ project?: string;
+ constraints?: string;
+ startedAt: string;
+ lastActivityAt: string;
+ stepCount: number;
+ recentSteps: WorkflowStep[];
+};
+
+function normalizedProject(value?: string): string {
+ return String(value ?? "").trim().replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
+}
+
+function projectAliases(values: string[]): Set<string> {
+ const aliases = new Set<string>();
+ for (const value of values) {
+ const normalized = normalizedProject(value);
+ if (!normalized) continue;
+ aliases.add(normalized);
+ const basename = normalized.split("/").filter(Boolean).at(-1);
+ if (basename) aliases.add(basename);
+ }
+ return aliases;
+}
+
+function projectMatches(project: string | undefined, aliases: Set<string>): boolean {
+ if (!aliases.size) return true;
+ const normalized = normalizedProject(project);
+ if (!normalized) return false;
+ const basename = normalized.split("/").filter(Boolean).at(-1) ?? "";
+ return aliases.has(normalized) || aliases.has(basename);
+}
+
+/**
+ * Read-only crash recovery view of unfinished workflows for one stable principal.
+ *
+ * The returned rows deliberately omit the old workflow id/actor. A continuation
+ * must start a fresh workflow in the new session instead of bypassing
+ * conversation-scoped workflow isolation.
+ */
+export async function workflowRecoveryCandidates(input: {
+ principal: string;
+ projectRefs?: string[];
+ excludeSessionId?: string;
+ limit?: number;
+}): Promise<WorkflowRecoveryCandidate[]> {
+ const store = await loadWorkflowStore();
+ const prefix = input.principal + "#session:";
+ const aliases = projectAliases(input.projectRefs ?? []);
+ const rows: WorkflowRecoveryCandidate[] = [];
+
+ for (const [actor, workflows] of Object.entries(store.active)) {
+ if (!actor.startsWith(prefix)) continue;
+ const sourceSessionId = actor.slice(prefix.length);
+ if (!sourceSessionId || sourceSessionId === input.excludeSessionId) continue;
+ for (const workflow of Object.values(workflows)) {
+ if (!projectMatches(workflow.project, aliases)) continue;
+ const recentSteps = workflow.steps.slice(-12);
+ const lastActivityAt = recentSteps.at(-1)?.ts ?? workflow.startedAt;
+ rows.push({
+ sourceSessionId,
+ intent: workflow.intent,
+ ...(workflow.project ? { project: workflow.project } : {}),
+ ...(workflow.constraints ? { constraints: workflow.constraints } : {}),
+ startedAt: workflow.startedAt,
+ lastActivityAt,
+ stepCount: workflow.steps.length,
+ recentSteps,
+ });
+ }
+ }
+
+ rows.sort((a, b) => b.lastActivityAt.localeCompare(a.lastActivityAt));
+ return rows.slice(0, Math.max(1, Math.min(20, input.limit ?? 8)));
+}