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
feat(workflows): add exact session artifact history
Rahman57733dbcb4a7
diff --git a/app/api/v1/agent-sessions/monitor.test.ts b/app/api/v1/agent-sessions/monitor.test.tsindex 22c15be0..b452cf4d 100644--- a/app/api/v1/agent-sessions/monitor.test.ts+++ b/app/api/v1/agent-sessions/monitor.test.ts@@ -1,8 +1,10 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";-const mocks = vi.hoisted(() => ({ context: vi.fn(), page: vi.fn(), detail: vi.fn(), graph: vi.fn() }));+const mocks = vi.hoisted(() => ({ context: vi.fn(), page: vi.fn(), detail: vi.fn(), graph: vi.fn(), resolveOwner: vi.fn(), artifact: vi.fn() }));vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: mocks.context }));vi.mock("@/lib/agent/session-monitor", () => ({ ownerSessionPage: mocks.page, ownerSessionDetail: mocks.detail, ownerSessionGraph: mocks.graph }));+vi.mock("@/lib/agent/session-query", () => ({ ownerSessionSummaries: vi.fn(), resolveAgentSessionOwnerRef: mocks.resolveOwner, resumeAgentSessionForOwner: vi.fn() }));+vi.mock("@/lib/agent/session-artifact-resolver", () => ({ resolveHistoricalSessionArtifactForOwner: mocks.artifact }));import { GET } from "./route";beforeEach(() => { vi.clearAllMocks(); mocks.context.mockResolvedValue({ role: "owner", session: { device_id: "owner" } }); });describe("session monitor route", () => {@@ -24,6 +26,20 @@ describe("session monitor route", () => {expect(mocks.graph).toHaveBeenCalledWith("20260901_100000_aabbccdd", 120);expect(response.headers.get("cache-control")).toBe("private, no-store");});+ it("serves owner-scoped artifact history without exposing resolver failures", async () => {+ mocks.resolveOwner.mockResolvedValue({ id: "internal", principalHash: "a".repeat(64) });+ mocks.artifact.mockResolvedValue({ artifact: { ref: "artifact_a", relativePath: "src/a.ts" }, history: { capture: { state: "captured", exactAtCapture: true }, historical: { available: true, exact: true }, diff: { available: true, changed: true } } });+ const response = await GET(new NextRequest("http://localhost/api/v1/agent-sessions?view=artifact&id=20260901_100000_aabbccdd&action_ref=S3.A4"));+ expect(response.status).toBe(200);+ expect(mocks.resolveOwner).toHaveBeenCalledWith("20260901_100000_aabbccdd");+ expect(mocks.artifact).toHaveBeenCalledWith(expect.objectContaining({ id: "internal" }), "S3.A4");+ expect(response.headers.get("cache-control")).toBe("private, no-store");+ mocks.artifact.mockRejectedValue(new Error("/private/path token=hidden"));+ const failed = await GET(new NextRequest("http://localhost/api/v1/agent-sessions?view=artifact&id=x&action_ref=S3.A4"));+ expect(failed.status).toBe(503);+ expect(JSON.stringify(await failed.json())).not.toMatch(/private|hidden/);+ });+it("returns 404 for a missing exact session and does not expose store error details", async () => {mocks.detail.mockResolvedValue(null);expect((await GET(new NextRequest("http://localhost/api/v1/agent-sessions?view=monitor&id=missing"))).status).toBe(404);diff --git a/app/api/v1/agent-sessions/route.ts b/app/api/v1/agent-sessions/route.tsindex 090d88a2..8740fe72 100644--- a/app/api/v1/agent-sessions/route.ts+++ b/app/api/v1/agent-sessions/route.ts@@ -12,6 +12,7 @@ import {} from "@/lib/agent/session-store";import { pruneAgentSessionArchives } from "@/lib/agent/session-archive";import { sessionWorkflowDraftDefinition } from "@/lib/agent/session-workflow-draft";+import { resolveHistoricalSessionArtifactForOwner } from "@/lib/agent/session-artifact-resolver";import { createWorkflowGraph } from "@/lib/workflow/graph-store";import {ownerSessionSummaries,@@ -48,6 +49,20 @@ export async function GET(req: NextRequest) {if (!principal)return NextResponse.json({ error: "owner_role_required" }, { status: 403 });const view = req.nextUrl.searchParams.get("view");+ if (view === "artifact") {+ try {+ const ref = String(req.nextUrl.searchParams.get("id") || req.nextUrl.searchParams.get("ref") || "").trim();+ const actionRef = String(req.nextUrl.searchParams.get("action_ref") || "").trim();+ if (!ref || !actionRef) return NextResponse.json({ error: "session_and_action_reference_required" }, { status: 400 });+ const source = await resolveAgentSessionOwnerRef(ref);+ const result = await resolveHistoricalSessionArtifactForOwner(source, actionRef);+ if (!result?.artifact) return NextResponse.json({ error: "artifact_revision_not_found" }, { status: 404, headers: { "Cache-Control": "private, no-store" } });+ return NextResponse.json(result, { headers: { "Cache-Control": "private, no-store" } });+ } catch (cause) {+ const missing = cause instanceof Error && cause.message === "session_not_found";+ return NextResponse.json({ error: missing ? "session_not_found" : "artifact_revision_unavailable" }, { status: missing ? 404 : 503, headers: { "Cache-Control": "private, no-store" } });+ }+ }if (view === "monitor" || view === "graph") {try {const id = req.nextUrl.searchParams.get("id");diff --git a/app/api/v1/term/close/route.ts b/app/api/v1/term/close/route.tsindex 67e840a0..1a5bab7b 100644--- a/app/api/v1/term/close/route.ts+++ b/app/api/v1/term/close/route.ts@@ -15,13 +15,14 @@ export async function POST(req: Request) {if (!(await verifyAuth(req)))return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const actor = await getSessionActor();+ if (!actor) return NextResponse.json({ error: "unauthorized" }, { status: 401 });const body = await readJson(req);const id = requireString(body, "id");if (id === null) return invalidRequest("id");try {- const killed = closePty(id);+ const killed = closePty(id, actor);if (killed) {- const actor = await getSessionActor();audit({ action: "term.close", actor, target: `pty ${id.slice(0, 8)}`, ok: true });}return NextResponse.json({ ok: true });diff --git a/app/api/v1/term/input/route.ts b/app/api/v1/term/input/route.tsindex a99eb79d..60526df8 100644--- a/app/api/v1/term/input/route.ts+++ b/app/api/v1/term/input/route.ts@@ -1,5 +1,6 @@import { NextResponse } from "next/server";import { verifyAuth } from "@/lib/agent/server";+import { getSessionActor } from "@/lib/auth/require-session";import { apiError, invalidRequest, readJson, requireString } from "@/lib/host/request-api";import { writePty } from "@/lib/host/terminal-api";@@ -14,13 +15,15 @@ export async function POST(req: Request) {if (!(await verifyAuth(req)))return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const actor = await getSessionActor();+ if (!actor) return NextResponse.json({ error: "unauthorized" }, { status: 401 });const body = await readJson(req);const id = requireString(body, "id");if (id === null) return invalidRequest("id");const data = requireString(body, "data", { allowEmpty: true });if (data === null) return invalidRequest("data");try {- writePty(id, data);+ writePty(id, actor, data);return NextResponse.json({ ok: true });} catch (e) {return apiError("term/input", e);diff --git a/app/api/v1/term/open/route.ts b/app/api/v1/term/open/route.tsindex 5073abea..268eaade 100644--- a/app/api/v1/term/open/route.ts+++ b/app/api/v1/term/open/route.ts@@ -34,7 +34,8 @@ export async function POST(req: Request) {const cwd = optionalString(body, "cwd");if (cwd === null) return invalidRequest("cwd");try {- const { id, cwd: dir } = await openPty({ cols, rows, cwd });+ if (!actor) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const { id, cwd: dir } = await openPty({ cols, rows, cwd, owner: actor });audit({action: "term.open",actor,diff --git a/app/api/v1/term/resize/route.ts b/app/api/v1/term/resize/route.tsindex 83417d9a..f2237103 100644--- a/app/api/v1/term/resize/route.ts+++ b/app/api/v1/term/resize/route.ts@@ -1,5 +1,6 @@import { NextResponse } from "next/server";import { verifyAuth } from "@/lib/agent/server";+import { getSessionActor } from "@/lib/auth/require-session";import { apiError, invalidRequest, readJson, requireInt, requireString } from "@/lib/host/request-api";import { resizePty } from "@/lib/host/terminal-api";@@ -11,6 +12,8 @@ export async function POST(req: Request) {if (!(await verifyAuth(req)))return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const actor = await getSessionActor();+ if (!actor) return NextResponse.json({ error: "unauthorized" }, { status: 401 });const body = await readJson(req);const id = requireString(body, "id");if (id === null) return invalidRequest("id");@@ -19,7 +22,7 @@ export async function POST(req: Request) {const rows = requireInt(body, "rows", 2, 500);if (rows === null) return invalidRequest("rows");try {- resizePty(id, cols, rows);+ resizePty(id, actor, cols, rows);return NextResponse.json({ ok: true });} catch (e) {return apiError("term/resize", e);diff --git a/app/api/v1/term/stream/route.ts b/app/api/v1/term/stream/route.tsindex 20795c39..1bf1feab 100644--- a/app/api/v1/term/stream/route.ts+++ b/app/api/v1/term/stream/route.ts@@ -1,5 +1,6 @@import { NextResponse } from "next/server";import { verifyAuth } from "@/lib/agent/server";+import { getSessionActor } from "@/lib/auth/require-session";import { attachPty, hasPty } from "@/lib/host/terminal-api";export const runtime = "nodejs";@@ -17,8 +18,10 @@ export async function GET(req: Request) {if (!(await verifyAuth(req)))return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const actor = await getSessionActor();+ if (!actor) return NextResponse.json({ error: "unauthorized" }, { status: 401 });const id = new URL(req.url).searchParams.get("id") ?? "";- if (!id || !hasPty(id))+ if (!id || !hasPty(id, actor))return NextResponse.json({ error: "Unknown terminal session" }, { status: 400 });const last = req.headers.get("last-event-id");const from = last ? parseInt(last, 10) || 0 : 0;@@ -53,7 +56,7 @@ export async function GET(req: Request) {}};try {- detach = attachPty(id, from, {+ detach = attachPty(id, actor, from, {onData: (chunk, off) =>send(`id: ${off}\nevent: data\ndata: ${Buffer.from(chunk, "utf8").toString("base64")}\n\n`),onExit: (code) => {diff --git a/frontend/slices/workflows/components/workflow-session-details.tsx b/frontend/slices/workflows/components/workflow-session-details.tsxindex 9e8da2c3..331e5ad2 100644--- a/frontend/slices/workflows/components/workflow-session-details.tsx+++ b/frontend/slices/workflows/components/workflow-session-details.tsx@@ -1,17 +1,55 @@"use client";-import { BrainCircuit, Code2, Copy, ExternalLink, FileCode2, Save, TerminalSquare } from "lucide-react";+import { useState } from "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 type { WorkflowLearningRecipeSummary } from "../lib/api";+import { getSessionArtifactHistory, type SessionArtifactHistoryResponse, type WorkflowLearningRecipeSummary } from "../lib/api";function value(config: Record<string, unknown>, key: string): string | undefined {const raw = config[key]; return typeof raw === "string" && raw ? raw : undefined;}-function actionReceipt(action: SessionFlowAction, onOpenTerminal: () => void, onOpenCode: (path: string) => void) {+function ArtifactRevisionInspector({ sessionId, action }: { sessionId: string; action: SessionFlowAction }) {+ const [result, setResult] = useState<SessionArtifactHistoryResponse | null>(null);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ if (!action.artifact) return null;+ const inspect = async () => {+ setLoading(true); setError(null);+ try { setResult(await getSessionArtifactHistory(sessionId, action.ref)); }+ catch (cause) { setError(cause instanceof Error ? cause.message : "artifact history unavailable"); }+ finally { setLoading(false); }+ };+ const history = result?.history;+ return <div data-slot="session-artifact-history" className="space-y-2">+ <Button type="button" size="sm" variant="outline" className="h-7 text-[10px]" disabled={loading} onClick={() => void inspect()}>+ <History className="size-3.5"/>{loading ? "Checking revision…" : result ? "Refresh revision" : "Inspect revision"}+ </Button>+ {error ? <p className="text-[10px] text-destructive">{error}</p> : null}+ {history ? <div className="space-y-1.5 rounded-md border bg-muted/20 p-2 text-[10px]">+ <div className="flex flex-wrap items-center gap-1.5">+ <Badge variant="outline" className="h-5 px-1.5 text-[9px]">{history.capture.state === "legacy" ? "legacy · no proof" : history.capture.exactAtCapture ? "exact capture" : "capture proof"}</Badge>+ {history.capture.sha256 ? <code className="text-[9px] text-muted-foreground">sha256 {history.capture.sha256.slice(0, 12)}</code> : null}+ {history.capture.gitHead ? <code className="text-[9px] text-muted-foreground">git {history.capture.gitHead.slice(0, 12)}</code> : null}+ </div>+ <p className="text-muted-foreground">{history.capture.state === "legacy" ? "This older action predates artifact capture proof, so MSO will not guess a historical snapshot." : history.historical.available ? "Historical identity is proven. Source previews below are redacted before display." : "Capture metadata exists, but an exact historical body is no longer provable."}</p>+ {history.current.available ? <p className="text-muted-foreground">Current file · {history.current.matchesCapture ? "matches captured revision" : "changed since capture"} · {history.current.bytes ?? 0} bytes</p> : <p className="text-muted-foreground">Current file is unavailable.</p>}+ {history.historical.available ? <details data-slot="session-artifact-snapshot" className="rounded border bg-background/40">+ <summary className="cursor-pointer px-2 py-1.5 font-medium">Historical snapshot · exact · {history.historical.source}</summary>+ <div className="border-t p-2">{history.historical.truncated ? <p className="text-muted-foreground">Exact hash/size retained; preview omitted because the snapshot exceeds the preview limit.</p> : <pre className="max-h-56 overflow-auto whitespace-pre p-2 font-mono text-[10px] leading-4"><code>{history.historical.content ?? ""}</code></pre>}</div>+ </details> : null}+ {history.diff.available ? <details data-slot="session-artifact-diff" className="rounded border bg-background/40">+ <summary className="flex cursor-pointer items-center gap-1.5 px-2 py-1.5 font-medium"><GitCompareArrows className="size-3"/>Historical ↔ current · {history.diff.changed ? "changed" : "no changes"}</summary>+ <div className="border-t p-2"><pre className="max-h-64 overflow-auto whitespace-pre p-2 font-mono text-[10px] leading-4"><code>{history.diff.unifiedDiff || "No changes."}</code></pre></div>+ </details> : null}+ </div> : null}+ </div>;+}++function actionReceipt(action: SessionFlowAction, sessionId: string, onOpenTerminal: () => void, onOpenCode: (path: string) => void) {return <details key={action.ref} data-slot="session-action" data-action-ref={action.ref} className="group rounded-lg border bg-background/35"><summary data-slot="session-action-summary" aria-label={`Inspect action ${action.ref}: ${action.title}`} className="flex cursor-pointer list-none items-start gap-2 p-2.5 text-xs marker:hidden"><code className="shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] font-semibold">{action.ref}</code>@@ -24,12 +62,13 @@ function actionReceipt(action: SessionFlowAction, onOpenTerminal: () => void, on{action.terminalContext ? <Button type="button" size="sm" variant="outline" className="h-7 text-[10px]" onClick={onOpenTerminal}><TerminalSquare className="size-3.5"/>Open terminal here<ExternalLink className="size-3"/></Button> : null}{action.artifact ? <Button type="button" size="sm" variant="outline" className="h-7 text-[10px]" onClick={() => onOpenCode(action.artifact!.path)}><FileCode2 className="size-3.5"/>Open {action.artifact.label} in Code<ExternalLink className="size-3"/></Button> : null}</div>+ {action.artifact ? <ArtifactRevisionInspector sessionId={sessionId} action={action}/> : null}<div className="flex flex-wrap gap-x-3 gap-y-1 text-[9px] text-muted-foreground"><span>{new Date(action.at).toLocaleString()}</span><span>{action.eventRef}</span>{action.artifact ? <span className="break-all">{action.artifact.relativePath} · revision {action.artifact.revisionRef}</span> : null}</div></div></details>;}-function actionGroups(step: SessionFlowStep, onOpenTerminal: () => void, onOpenCode: (path: string) => void) {+function actionGroups(step: SessionFlowStep, sessionId: string, onOpenTerminal: () => void, onOpenCode: (path: string) => void) {return step.groups.map((group) => {const refs = new Set(group.actionRefs);const actions = step.actions.filter((action) => refs.has(action.ref));@@ -38,7 +77,7 @@ function actionGroups(step: SessionFlowStep, onOpenTerminal: () => void, onOpenC<span className="min-w-0 flex-1 truncate font-medium">{group.title}</span><Badge variant="outline" className="h-5 shrink-0 px-1.5 text-[9px]">{group.count}</Badge></summary>- <div className="space-y-1.5 border-t p-2">{actions.map((action) => actionReceipt(action, onOpenTerminal, onOpenCode))}</div>+ <div className="space-y-1.5 border-t p-2">{actions.map((action) => actionReceipt(action, sessionId, onOpenTerminal, onOpenCode))}</div></details>;});}@@ -69,7 +108,7 @@ export function WorkflowSessionDetails({ view, node, onOpenTerminal, onOpenCode,<ScrollArea className="min-h-0 flex-1"><div className="space-y-3 p-3">{!node || node.id === "session-root" ? <><div><div className="text-[10px] uppercase text-muted-foreground">Flow</div><div className="mt-1 text-sm font-semibold">{view.session.title}</div><Button data-slot="save-session-workflow-draft" type="button" size="sm" variant="outline" className="mt-2 h-7 text-[10px]" disabled={savingDraft} onClick={() => onSaveDraft()}><Save className="size-3.5"/>Save session as workflow draft</Button></div><div className="space-y-1.5">{view.steps.map((item) => <div key={item.ref} className="rounded-lg border bg-background/35 p-2"><div className="flex items-center gap-2"><code className="rounded bg-muted px-1.5 py-0.5 text-[10px] font-semibold">{item.ref}</code><span className="text-xs font-medium">{item.title}</span><span className="ml-auto text-[10px] text-muted-foreground">{item.actions.length} actions</span></div><p className="mt-1 text-[10px] text-muted-foreground">{item.summary}</p></div>)}</div></> : step ? <><div><div className="flex items-center gap-2"><code className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] font-semibold">{step.ref}</code><Badge variant="outline" className="text-[9px] capitalize">{step.category}</Badge></div><div className="mt-2 break-words text-sm font-semibold">{step.title}</div><p className="mt-1 text-xs text-muted-foreground">{step.summary}</p><Button data-slot="save-step-workflow-draft" type="button" size="sm" variant="outline" className="mt-2 h-7 text-[10px]" disabled={savingDraft} onClick={() => onSaveDraft(step.ref)}><Save className="size-3.5"/>Save {step.ref} as workflow draft</Button></div>- <div className="border-t pt-3"><div className="mb-2 flex items-center justify-between"><div className="text-[10px] font-semibold uppercase text-muted-foreground">Action groups</div><span className="text-[10px] text-muted-foreground">{step.groups.length} groups · {step.actions.length} actions</span></div><div className="space-y-1.5">{actionGroups(step, onOpenTerminal, onOpenCode)}</div></div>+ <div className="border-t pt-3"><div className="mb-2 flex items-center justify-between"><div className="text-[10px] font-semibold uppercase text-muted-foreground">Action groups</div><span className="text-[10px] text-muted-foreground">{step.groups.length} groups · {step.actions.length} actions</span></div><div className="space-y-1.5">{actionGroups(step, view.session.id, onOpenTerminal, onOpenCode)}</div></div></> : <p className="text-xs text-muted-foreground">Select a semantic step to inspect its actions.</p>}<SelfImprove recipes={linked}/>{view.session.cwd ? <div className="border-t pt-3"><div className="text-[10px] uppercase text-muted-foreground">Session context</div><p className="mt-1 break-all font-mono text-[10px] text-muted-foreground">{view.session.cwd}</p></div> : null}diff --git a/frontend/slices/workflows/lib/api.ts b/frontend/slices/workflows/lib/api.tsindex daa5bc6a..5cf23aa6 100644--- a/frontend/slices/workflows/lib/api.ts+++ b/frontend/slices/workflows/lib/api.ts@@ -27,6 +27,15 @@ export async function resolveNode(graphId:string,nodeId:string){return json<{proexport async function listWorkflowSessions(page=1,query=""){const q=new URLSearchParams({view:"monitor",includeOffline:"1",page:String(page)});if(query.trim())q.set("q",query.trim());return json<SessionPage>(`/api/v1/agent-sessions?${q}`);}export async function getSessionGraph(id:string){return json<SessionGraphView>(`/api/v1/agent-sessions?view=graph&id=${encodeURIComponent(id)}&limit=120`);}+export type SessionArtifactHistoryView = {+ capture:{state:"legacy"|"captured";exactAtCapture:boolean;sha256?:string;bytes?:number;gitHead?:string;gitBlob?:string};+ current:{available:boolean;path?:string;sha256?:string;bytes?:number;matchesCapture?:boolean};+ historical:{available:boolean;exact?:true;source?:"git-blob"|"current-match";sha256?:string;bytes?:number;blobOid?:string;content?:string;previewRedacted?:boolean;truncated?:boolean;reason?:string};+ diff:{available:boolean;changed?:boolean;unifiedDiff?:string;previewRedacted?:boolean;reason?:string};+};+export type SessionArtifactHistoryResponse = {artifact:{ref:string;revisionRef:string;path:string;relativePath:string;label:string;kind:"file"|"script";language?:string};history:SessionArtifactHistoryView};+export async function getSessionArtifactHistory(id:string,actionRef:string){const q=new URLSearchParams({view:"artifact",id,action_ref:actionRef});return json<SessionArtifactHistoryResponse>(`/api/v1/agent-sessions?${q}`);}+export type WorkflowDirectory = {tools:Array<{name:string;description:string;scope:string;inputSchema:Record<string,unknown>}>;workflows:Array<{id:string;name:string;status:string;nodeCount:number;updatedAt:string}>;sessions:Array<{id:string;label?:string;title:string;name:string;updatedAt:string;cwd?:string;source:string}>};export async function listWorkflowDirectory(query=""){return cachedWorkflowResource(`directory:${query}`,15000,()=>json<WorkflowDirectory>(`/api/v1/workflows?directory=1&q=${encodeURIComponent(query)}`));}diff --git a/frontend/slices/workflows/session-graph-ui.test.ts b/frontend/slices/workflows/session-graph-ui.test.tsindex 8f875d17..5e17a4e7 100644--- a/frontend/slices/workflows/session-graph-ui.test.ts+++ b/frontend/slices/workflows/session-graph-ui.test.ts@@ -31,6 +31,11 @@ describe("Workflow session graph UI contract", () => {expect(sessionDetails).toContain('data-slot="session-action-group"');expect(sessionDetails).toContain("Action groups");expect(sessionDetails).toContain("action.artifact.revisionRef");+ expect(sessionDetails).toContain('data-slot="session-artifact-history"');+ expect(sessionDetails).toContain('data-slot="session-artifact-snapshot"');+ expect(sessionDetails).toContain('data-slot="session-artifact-diff"');+ expect(sessionDetails).toContain("Inspect revision");+ expect(sessionDetails).toContain("MSO will not guess a historical snapshot");expect(sessionDetails).toContain("S3.A4");expect(sessionDetails).toContain('data-slot="save-session-workflow-draft"');expect(sessionDetails).toContain('data-slot="save-step-workflow-draft"');diff --git a/lib/agent/session-action-history.test.ts b/lib/agent/session-action-history.test.tsindex bb78395f..a822b447 100644--- a/lib/agent/session-action-history.test.ts+++ b/lib/agent/session-action-history.test.ts@@ -18,6 +18,7 @@ describe("archive-backed session action lookup", () => {const principal = "mcp-client:owner", now = Date.now();const all = normalizeSessionEventSemantics(Array.from({ length: 401 }, (_, index) => ({at: new Date(now + index).toISOString(), kind: "tool" as const, tool: index === 0 ? "fs_read" : "fs_write", state: "completed", detail: index === 0 ? "src/old.ts token=secret-value" : `src/${index}.ts`,+ ...(index === 0 ? { artifactRevision: { version: 1 as const, cwd: "/srv/project", relativePath: "src/old.ts", worktreeSha256: "a".repeat(64), bytes: 12, cleanAtCapture: false } } : {}),})));const original = resolveSessionFlowAction(all, "E1", "/srv/project", 0)!;const session: AgentSession = {@@ -30,6 +31,8 @@ describe("archive-backed session action lookup", () => {const resolved = await history.resolveHistoricalSessionAction(principal, session, ref);expect(resolved?.action.eventRef).toBe("E1");expect(JSON.stringify(resolved)).not.toContain("secret-value");+ const record = await history.resolveHistoricalSessionActionRecord(principal, session, ref);+ expect(record?.event.artifactRevision).toMatchObject({ relativePath: "src/old.ts", bytes: 12 });}await expect(history.resolveHistoricalSessionAction("mcp-client:other", session, "E1")).rejects.toThrow("session not found");});diff --git a/lib/agent/session-action-history.ts b/lib/agent/session-action-history.tsindex bc8c05e2..1f442649 100644--- a/lib/agent/session-action-history.ts+++ b/lib/agent/session-action-history.ts@@ -6,6 +6,7 @@ import { withSecurityStoreLock } from "@/lib/security-store-lock";import { redactText } from "@/lib/security/redact-text";import { agentSessionArchiveRoot, archiveRetentionDays } from "./session-archive";import { resolveSessionFlowAction } from "./session-flow";+import { validSessionArtifactRevision } from "./session-artifact-history";import type { AgentSession, AgentSessionEvent } from "./session-types";const MAX_BYTES = 4 * 1024 * 1024;@@ -30,7 +31,8 @@ function validEvent(value: unknown): value is AgentSessionEvent {["tool", "state", "workflowId", "detail"].every((key) => row[key as keyof AgentSessionEvent] === undefined || (typeof row[key as keyof AgentSessionEvent] === "string" && String(row[key as keyof AgentSessionEvent]).length <= 16000)) &&(row.semantic === undefined || (row.semantic.version === 1 && Number.isSafeInteger(row.semantic.step) && row.semantic.step > 0 &&Number.isSafeInteger(row.semantic.action) && row.semantic.action > 0 &&- ["context", "plan", "inspect", "implement", "verify", "integrate", "deploy", "result", "other"].includes(row.semantic.category)));+ ["context", "plan", "inspect", "implement", "verify", "integrate", "deploy", "result", "other"].includes(row.semantic.category))) &&+ (row.artifactRevision === undefined || validSessionArtifactRevision(row.artifactRevision));}function events(value: unknown): value is AgentSessionEvent[] {return Array.isArray(value) && value.length <= 10000 && value.every(validEvent);@@ -43,6 +45,7 @@ function safeEvent(event: AgentSessionEvent): AgentSessionEvent {...(event.workflowId ? { workflowId: event.workflowId.slice(0, 80) } : {}),...(event.detail ? { detail: redactText(event.detail, 500) } : {}),...(event.semantic ? { semantic: event.semantic } : {}),+ ...(event.artifactRevision && validSessionArtifactRevision(event.artifactRevision) ? { artifactRevision: event.artifactRevision } : {}),};}function actionIndexPath(sessionId: string): string {@@ -98,24 +101,37 @@ export async function archiveDroppedSessionEvents(session: Pick<AgentSession, "i});}-async function resolveActionIndex(session: AgentSession, actionRef: string) {+export type HistoricalSessionActionRecord = {+ resolution: NonNullable<ReturnType<typeof resolveSessionFlowAction>>;+ event: AgentSessionEvent;+ sequence: number;+};++function resolveEventRecord(events: AgentSessionEvent[], actionRef: string, cwd: string | undefined, rawBase: number): HistoricalSessionActionRecord | null {+ const resolution = resolveSessionFlowAction(events, actionRef, cwd, rawBase);+ if (!resolution) return null;+ const sequence = Number(resolution.action.eventRef.slice(1));+ if (!Number.isSafeInteger(sequence) || sequence <= rawBase) return null;+ const event = events[sequence - rawBase - 1];+ return event ? { resolution, event, sequence } : null;+}++async function resolveActionIndex(session: AgentSession, actionRef: string): Promise<HistoricalSessionActionRecord | null> {const index = await readActionIndex(actionIndexPath(session.id)).catch(() => null);if (!index || index.sessionId !== session.id || index.principalHash !== session.principalHash) return null;const cutoff = Date.now() - archiveRetentionDays() * 86_400_000;for (const row of index.records) {if (Date.parse(row.event.at) < cutoff) continue;- const resolved = resolveSessionFlowAction([row.event], actionRef, session.cwd ?? index.cwd, row.sequence - 1);- if (resolved) return resolved;+ const resolution = resolveSessionFlowAction([row.event], actionRef, session.cwd ?? index.cwd, row.sequence - 1);+ if (resolution) return { resolution, event: row.event, sequence: row.sequence };}return null;}-/** Caller supplies an authenticated principal and its exact loaded session, never an arbitrary archive path. */-export async function resolveHistoricalSessionAction(principal: string, session: AgentSession, actionRef: string) {- const owner = createHash("sha256").update(principal).digest("hex");+async function resolveHistoricalSessionActionRecordOwned(session: AgentSession, actionRef: string, owner: string): Promise<HistoricalSessionActionRecord | null> {if (session.principalHash !== owner) throw new Error("session not found");if (!/^(?:S\d+\.A\d+|E\d+|action_[a-f0-9]{20})$/i.test(actionRef.trim())) return null;- const current = resolveSessionFlowAction(session.events, actionRef, session.cwd, session.eventSeqBase);+ const current = resolveEventRecord(session.events, actionRef, session.cwd, session.eventSeqBase ?? 0);if (current) return current;const indexed = await resolveActionIndex(session, actionRef);if (indexed) return indexed;@@ -148,14 +164,29 @@ export async function resolveHistoricalSessionAction(principal: string, session:if (payload?.schemaVersion !== 1 || typeof payload.archivedAt !== "string" || !Number.isFinite(Date.parse(payload.archivedAt)) || Date.parse(payload.archivedAt) < cutoff || archived?.id !== session.id || archived?.principalHash !== owner || !events(archived.events)) continue;const base = archived.eventSeqBase ?? 0;if (!Number.isSafeInteger(base) || base < 0) continue;- const resolved = resolveSessionFlowAction(archived.events, actionRef, session.cwd, base);- if (resolved) return resolved;+ const record = resolveEventRecord(archived.events, actionRef, session.cwd, base);+ if (record) return record;} catch { /* malformed/expired/unsafe archives do not block other matches */ }finally { await handle?.close().catch(() => undefined); }}return null;}+/** MCP/client path: caller supplies an authenticated principal and its exact loaded session. */+export async function resolveHistoricalSessionActionRecord(principal: string, session: AgentSession, actionRef: string): Promise<HistoricalSessionActionRecord | null> {+ const owner = createHash("sha256").update(principal).digest("hex");+ return resolveHistoricalSessionActionRecordOwned(session, actionRef, owner);+}++/** Web owner-console path. Caller MUST already enforce the application owner role. */+export async function resolveHistoricalSessionActionRecordForOwner(session: AgentSession, actionRef: string): Promise<HistoricalSessionActionRecord | null> {+ return resolveHistoricalSessionActionRecordOwned(session, actionRef, session.principalHash);+}++export async function resolveHistoricalSessionAction(principal: string, session: AgentSession, actionRef: string) {+ return (await resolveHistoricalSessionActionRecord(principal, session, actionRef))?.resolution ?? null;+}+export async function pruneSessionActionIndexes(now = Date.now()): Promise<number> {const root = await secureArchiveRoot(), cutoff = now - archiveRetentionDays() * 86_400_000;const names = await fs.readdir(root).catch(() => [] as string[]); let removed = 0;diff --git a/lib/agent/session-artifact-history.test.ts b/lib/agent/session-artifact-history.test.tsnew file mode 100644index 00000000..6ee11b82--- /dev/null+++ b/lib/agent/session-artifact-history.test.ts@@ -0,0 +1,73 @@+import { afterEach, describe, expect, it } from "vitest";+import { execFileSync } from "node:child_process";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { captureSessionArtifactRevision, resolveArtifactRevisionView } from "./session-artifact-history";++const roots: string[] = [];+afterEach(async () => {+ delete process.env.OS_FS_WRITE_ROOTS;+ while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });+});++function git(cwd: string, ...args: string[]) {+ return execFileSync("git", args, { cwd, encoding: "utf8" }).trim();+}++async function fixture() {+ const root = await mkdtemp(path.join(os.tmpdir(), "mso-artifact-history-"));+ roots.push(root); process.env.OS_FS_WRITE_ROOTS = root;+ git(root, "init", "-b", "main");+ git(root, "config", "user.email", "[email protected]"); git(root, "config", "user.name", "MSO Test");+ await writeFile(path.join(root, "app.ts"), "export const value = 1;\n", "utf8");+ git(root, "add", "app.ts"); git(root, "commit", "-m", "initial");+ return root;+}++describe("session artifact revision proof", () => {+ it("resolves an exact committed snapshot and a current diff without storing source in the revision metadata", async () => {+ const root = await fixture();+ const revision = await captureSessionArtifactRevision({ kind: "tool", tool: "fs_write", detail: "app.ts" }, root);+ expect(revision).toMatchObject({ version: 1, relativePath: "app.ts", cleanAtCapture: true });+ expect(JSON.stringify(revision)).not.toContain("export const value");+ await writeFile(path.join(root, "app.ts"), "export const value = 2;\n", "utf8");+ const view = await resolveArtifactRevisionView(revision);+ expect(view.capture.exactAtCapture).toBe(true);+ expect(view.historical).toMatchObject({ available: true, exact: true, source: "git-blob", previewRedacted: true });+ if (view.historical.available && "content" in view.historical) expect(view.historical.content).toContain("value = 1");+ expect(view.current).toMatchObject({ available: true, matchesCapture: false });+ expect(view.diff).toMatchObject({ available: true, changed: true, previewRedacted: true });+ if (view.diff.available) {+ expect(view.diff.unifiedDiff).toContain("-export const value = 1;");+ expect(view.diff.unifiedDiff).toContain("+export const value = 2;");+ expect(view.diff.unifiedDiff).not.toContain(root);+ }+ });++ it("fails safe for an uncommitted captured revision after the working file changes", async () => {+ const root = await fixture();+ await writeFile(path.join(root, "app.ts"), "export const value = 2;\n", "utf8");+ const revision = await captureSessionArtifactRevision({ kind: "tool", tool: "fs_write", detail: "app.ts" }, root);+ expect(revision?.cleanAtCapture).toBe(false);+ await writeFile(path.join(root, "app.ts"), "export const value = 3;\n", "utf8");+ const view = await resolveArtifactRevisionView(revision);+ expect(view.historical).toMatchObject({ available: false, reason: "exact_snapshot_unavailable" });+ expect(view.diff).toMatchObject({ available: false, reason: "exact_snapshot_unavailable" });+ });++ it("can prove a dirty capture exactly while the file still matches its captured hash", async () => {+ const root = await fixture();+ await writeFile(path.join(root, "app.ts"), "export const value = 9;\n", "utf8");+ const revision = await captureSessionArtifactRevision({ kind: "tool", tool: "fs_write", detail: "app.ts" }, root);+ const view = await resolveArtifactRevisionView(revision);+ expect(view.historical).toMatchObject({ available: true, exact: true, source: "current-match" });+ expect(view.diff).toMatchObject({ available: true, changed: false });+ });++ it("keeps read-only/legacy events metadata-free rather than pretending a snapshot exists", async () => {+ const root = await fixture();+ expect(await captureSessionArtifactRevision({ kind: "tool", tool: "fs_read", detail: "app.ts" }, root)).toBeUndefined();+ expect(await resolveArtifactRevisionView(undefined)).toMatchObject({ capture: { state: "legacy" }, historical: { available: false, reason: "no_capture_proof" } });+ });+});diff --git a/lib/agent/session-artifact-history.ts b/lib/agent/session-artifact-history.tsnew file mode 100644index 00000000..082b2c7b--- /dev/null+++ b/lib/agent/session-artifact-history.ts@@ -0,0 +1,193 @@+import { spawn } from "node:child_process";+import { createHash, randomUUID } from "node:crypto";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { childEnv } from "@/lib/host/child-env";+import { resolveCwd } from "@/lib/host/exec";+import { redactText } from "@/lib/security/redact-text";+import { resolveSessionArtifactCandidate } from "./session-artifact-path";+import type { AgentSessionArtifactRevision, AgentSessionEvent } from "./session-types";++const OID = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i;+const SHA256 = /^[a-f0-9]{64}$/i;+const MAX_FILE_BYTES = 4 * 1024 * 1024;+const MAX_SNAPSHOT_TEXT = 128 * 1024;+const MAX_DIFF_BYTES = 256 * 1024;+const GIT_TIMEOUT_MS = 5_000;++type GitResult = { code: number; stdout: Buffer; stderr: Buffer };++async function git(cwd: string, args: string[], maxBytes = MAX_DIFF_BYTES): Promise<GitResult> {+ return new Promise((resolve, reject) => {+ const child = spawn("git", args, { cwd, env: childEnv() as NodeJS.ProcessEnv, shell: false, stdio: ["ignore", "pipe", "pipe"] });+ const stdout: Buffer[] = [], stderr: Buffer[] = [];+ let bytes = 0, settled = false;+ const timer = setTimeout(() => finish(new Error(`git timed out after ${GIT_TIMEOUT_MS}ms`)), GIT_TIMEOUT_MS);+ const finish = (error?: Error, result?: GitResult) => {+ if (settled) return;+ settled = true; clearTimeout(timer);+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM");+ error ? reject(error) : resolve(result!);+ };+ const take = (target: Buffer[], chunk: Buffer) => {+ bytes += chunk.byteLength;+ if (bytes > maxBytes) return finish(new Error(`git output exceeded ${maxBytes} bytes`));+ target.push(Buffer.from(chunk));+ };+ child.stdout.on("data", (chunk: Buffer) => take(stdout, chunk));+ child.stderr.on("data", (chunk: Buffer) => take(stderr, chunk));+ child.on("error", (error) => finish(new Error(`git failed to start: ${error.message}`)));+ child.on("close", (code) => finish(undefined, { code: code ?? 1, stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr) }));+ });+}++async function regularFileInfo(file: string): Promise<{ bytes: Buffer; sha256: string; size: number } | null> {+ try {+ const stat = await fs.lstat(file);+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size < 0 || stat.size > MAX_FILE_BYTES) return null;+ const bytes = await fs.readFile(file);+ if (bytes.length !== stat.size || bytes.length > MAX_FILE_BYTES) return null;+ return { bytes, sha256: createHash("sha256").update(bytes).digest("hex"), size: bytes.length };+ } catch { return null; }+}++function safeRel(value: string): boolean {+ return Boolean(value && !path.isAbsolute(value) && value !== ".." && !value.startsWith("../") && !value.includes("\0"));+}++function parseLsTree(buffer: Buffer, wanted: string): string | undefined {+ const body = buffer.toString("utf8");+ for (const row of body.split("\0")) {+ if (!row) continue;+ const tab = row.indexOf("\t");+ if (tab < 0) continue;+ const meta = row.slice(0, tab).split(" "), file = row.slice(tab + 1);+ if (file === wanted && meta[1] === "blob" && OID.test(meta[2] || "")) return meta[2]!.toLowerCase();+ }+ return undefined;+}++function toolWorthCapturing(event: Pick<AgentSessionEvent, "kind" | "tool">): boolean {+ if (event.kind !== "tool") return false;+ const tool = (event.tool || "").toLowerCase();+ return /(?:^|_)(?:write|delete|move|copy|patch|edit)(?:$|_)/.test(tool) || /^(?:exec(?:_|\.)|terminal|shell|project_script_run)/.test(tool);+}++/** Capture proof metadata only. No source body is persisted into the session record. */+export async function captureSessionArtifactRevision(event: Pick<AgentSessionEvent, "kind" | "tool" | "detail">, cwd?: string): Promise<AgentSessionArtifactRevision | undefined> {+ if (!cwd || !toolWorthCapturing(event)) return undefined;+ const dir = await resolveCwd(cwd).catch(() => null);+ if (!dir) return undefined;+ const candidate = resolveSessionArtifactCandidate(event.detail, dir);+ if (!candidate) return undefined;+ const current = await regularFileInfo(candidate.path);+ const base: AgentSessionArtifactRevision = {+ version: 1, cwd: dir, relativePath: candidate.relativePath,+ ...(current ? { worktreeSha256: current.sha256, bytes: current.size } : {}),+ };+ try {+ const rootResult = await git(dir, ["rev-parse", "--show-toplevel", "HEAD"], 16 * 1024);+ if (rootResult.code !== 0) return base;+ const [rootRaw = "", headRaw = ""] = rootResult.stdout.toString("utf8").trim().split("\n");+ const repoRoot = await resolveCwd(rootRaw).catch(() => null);+ const head = headRaw.trim().toLowerCase();+ if (!repoRoot || !OID.test(head)) return base;+ const repoRel = path.relative(repoRoot, candidate.path).replaceAll(path.sep, "/");+ if (!safeRel(repoRel)) return base;+ const tree = await git(repoRoot, ["ls-tree", "-z", "HEAD", "--", repoRel], 32 * 1024);+ const headBlob = tree.code === 0 ? parseLsTree(tree.stdout, repoRel) : undefined;+ let cleanAtCapture = false, worktreeBlob: string | undefined;+ const diff = await git(repoRoot, ["diff", "--quiet", "HEAD", "--", repoRel], 8 * 1024).catch(() => null);+ cleanAtCapture = Boolean(current && headBlob && diff?.code === 0);+ if (current) {+ const hashed = await git(repoRoot, ["hash-object", "--no-filters", "--", candidate.path], 8 * 1024).catch(() => null);+ const oid = hashed?.stdout.toString("utf8").trim().toLowerCase();+ if (hashed?.code === 0 && oid && OID.test(oid)) worktreeBlob = oid;+ }+ return {+ ...base, repoRoot, repoRelativePath: repoRel, gitHead: head,+ ...(headBlob ? { headBlob } : {}), ...(worktreeBlob ? { worktreeBlob } : {}), cleanAtCapture,+ };+ } catch { return base; }+}++export function validSessionArtifactRevision(value: unknown): value is AgentSessionArtifactRevision {+ if (!value || typeof value !== "object") return false;+ const row = value as AgentSessionArtifactRevision;+ if (row.version !== 1 || typeof row.cwd !== "string" || row.cwd.length > 4096 || typeof row.relativePath !== "string" || row.relativePath.length > 4096 || !safeRel(row.relativePath)) return false;+ if (row.repoRoot !== undefined && (typeof row.repoRoot !== "string" || row.repoRoot.length > 4096)) return false;+ if (row.repoRelativePath !== undefined && (typeof row.repoRelativePath !== "string" || row.repoRelativePath.length > 4096 || !safeRel(row.repoRelativePath))) return false;+ for (const oid of [row.gitHead, row.headBlob, row.worktreeBlob]) if (oid !== undefined && (typeof oid !== "string" || !OID.test(oid))) return false;+ if (row.worktreeSha256 !== undefined && (typeof row.worktreeSha256 !== "string" || !SHA256.test(row.worktreeSha256))) return false;+ if (row.bytes !== undefined && (!Number.isSafeInteger(row.bytes) || row.bytes < 0 || row.bytes > MAX_FILE_BYTES)) return false;+ if (row.cleanAtCapture !== undefined && typeof row.cleanAtCapture !== "boolean") return false;+ return true;+}++type ExactSnapshot = { bytes: Buffer; source: "git-blob" | "current-match"; blobOid?: string };++async function exactSnapshot(revision: AgentSessionArtifactRevision, current: Awaited<ReturnType<typeof regularFileInfo>>): Promise<ExactSnapshot | null> {+ if (current && revision.worktreeSha256 && current.sha256 === revision.worktreeSha256) return { bytes: current.bytes, source: "current-match" };+ const repoRoot = revision.repoRoot ? await resolveCwd(revision.repoRoot).catch(() => null) : null;+ if (!repoRoot) return null;+ const candidates = [revision.cleanAtCapture ? revision.headBlob : undefined, revision.worktreeBlob].filter((oid, index, rows): oid is string => Boolean(oid && rows.indexOf(oid) === index));+ for (const oid of candidates) {+ if (!OID.test(oid)) continue;+ const kind = await git(repoRoot, ["cat-file", "-t", oid], 1024).catch(() => null);+ if (kind?.code !== 0 || kind.stdout.toString("utf8").trim() !== "blob") continue;+ const blob = await git(repoRoot, ["cat-file", "blob", oid], MAX_FILE_BYTES + 1024).catch(() => null);+ if (!blob || blob.code !== 0 || blob.stdout.length > MAX_FILE_BYTES) continue;+ if (revision.worktreeSha256 && createHash("sha256").update(blob.stdout).digest("hex") !== revision.worktreeSha256) continue;+ return { bytes: blob.stdout, source: "git-blob", blobOid: oid };+ }+ return null;+}++async function unifiedDiff(relativePath: string, historical: Buffer, currentPath: string): Promise<{ text: string; changed: boolean } | null> {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-artifact-diff-"));+ await fs.chmod(root, 0o700).catch(() => undefined);+ const oldFile = path.join(root, `${randomUUID()}.old`);+ try {+ await fs.writeFile(oldFile, historical, { mode: 0o600, flag: "wx" });+ const result = await git(root, ["diff", "--no-index", "--no-ext-diff", "--unified=3", "--", oldFile, currentPath], MAX_DIFF_BYTES).catch(() => null);+ if (!result || (result.code !== 0 && result.code !== 1)) return null;+ let text = result.stdout.toString("utf8");+ text = text.replaceAll(oldFile, `a/${relativePath}`).replaceAll(currentPath, `b/${relativePath}`);+ return { text, changed: result.code === 1 };+ } finally { await fs.rm(root, { recursive: true, force: true }).catch(() => undefined); }+}++export async function resolveArtifactRevisionView(revision: AgentSessionArtifactRevision | undefined) {+ if (!revision || !validSessionArtifactRevision(revision)) return {+ capture: { state: "legacy" as const, exactAtCapture: false },+ current: { available: false as const },+ historical: { available: false as const, reason: "no_capture_proof" },+ diff: { available: false as const, reason: "no_capture_proof" },+ };+ const captureCwd = await resolveCwd(revision.cwd).catch(() => null);+ if (!captureCwd) return {+ capture: { state: "captured" as const, exactAtCapture: Boolean(revision.cleanAtCapture && revision.headBlob), sha256: revision.worktreeSha256, bytes: revision.bytes, gitHead: revision.gitHead, gitBlob: revision.cleanAtCapture ? revision.headBlob : undefined },+ current: { available: false as const }, historical: { available: false as const, reason: "capture_root_unavailable" }, diff: { available: false as const, reason: "capture_root_unavailable" },+ };+ const currentPath = path.resolve(captureCwd, revision.relativePath);+ const relCheck = path.relative(captureCwd, currentPath);+ if (!relCheck || relCheck === ".." || relCheck.startsWith(`..${path.sep}`) || path.isAbsolute(relCheck)) throw new Error("artifact revision escaped capture root");+ const current = await regularFileInfo(currentPath);+ const historical = await exactSnapshot(revision, current);+ const snapshotSha = historical ? createHash("sha256").update(historical.bytes).digest("hex") : undefined;+ const diff = historical && current ? await unifiedDiff(revision.relativePath, historical.bytes, currentPath) : null;+ return {+ capture: {+ state: "captured" as const, exactAtCapture: Boolean(revision.cleanAtCapture && revision.headBlob), sha256: revision.worktreeSha256, bytes: revision.bytes,+ ...(revision.gitHead ? { gitHead: revision.gitHead } : {}), ...(revision.cleanAtCapture && revision.headBlob ? { gitBlob: revision.headBlob } : {}),+ },+ current: current ? { available: true as const, path: currentPath, sha256: current.sha256, bytes: current.size, matchesCapture: Boolean(revision.worktreeSha256 && current.sha256 === revision.worktreeSha256) } : { available: false as const },+ historical: historical ? {+ available: true as const, exact: true as const, source: historical.source, sha256: snapshotSha!, bytes: historical.bytes.length,+ ...(historical.blobOid ? { blobOid: historical.blobOid } : {}),+ ...(historical.bytes.length <= MAX_SNAPSHOT_TEXT ? { content: redactText(historical.bytes.toString("utf8")), previewRedacted: true, truncated: false } : { previewRedacted: true, truncated: true }),+ } : { available: false as const, reason: "exact_snapshot_unavailable" },+ diff: diff ? { available: true as const, changed: diff.changed, unifiedDiff: redactText(diff.text), previewRedacted: true } : { available: false as const, reason: historical ? "current_file_unavailable" : "exact_snapshot_unavailable" },+ };+}diff --git a/lib/agent/session-artifact-path.ts b/lib/agent/session-artifact-path.tsnew file mode 100644index 00000000..374e86cf--- /dev/null+++ b/lib/agent/session-artifact-path.ts@@ -0,0 +1,36 @@+import path from "node:path";++const CODE_EXTENSIONS = new Set(["ts", "tsx", "js", "jsx", "mjs", "cjs", "svelte", "py", "sh", "bash", "zsh", "md", "json", "yaml", "yml", "css", "scss", "html", "sql", "toml"]);++export type SessionArtifactCandidate = {+ path: string;+ relativePath: string;+ label: string;+ kind: "file" | "script";+ language: string;+};++export function artifactLanguage(filePath: string): string {+ const ext = filePath.split(".").pop()?.toLowerCase() || "";+ return ({ ts: "typescript", tsx: "tsx", js: "javascript", jsx: "jsx", mjs: "javascript", cjs: "javascript", svelte: "svelte", py: "python", sh: "bash", bash: "bash", zsh: "zsh", md: "markdown", json: "json", yaml: "yaml", yml: "yaml", css: "css", scss: "scss", html: "html", sql: "sql", toml: "toml" } as Record<string, string>)[ext] || "text";+}++export function resolveSessionArtifactCandidate(detail: string | undefined, cwd: string | undefined): SessionArtifactCandidate | undefined {+ if (!detail || !cwd) return undefined;+ const candidates = detail.match(/(?:\/|\.?\.?\/)?[[email protected]]+(?:\/[[email protected]]+)*\.[A-Za-z0-9]+/g) || [];+ for (const raw of candidates) {+ const ext = raw.split(".").pop()?.toLowerCase() || "";+ if (!CODE_EXTENSIONS.has(ext) || raw.includes("..")) continue;+ const resolved = path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(cwd, raw.replace(/^\.\//, ""));+ const rel = path.relative(path.resolve(cwd), resolved);+ if (!rel || rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) continue;+ return {+ path: resolved,+ relativePath: rel.replaceAll(path.sep, "/"),+ label: path.basename(resolved),+ kind: ["sh", "bash", "zsh", "py", "js", "ts"].includes(ext) ? "script" : "file",+ language: artifactLanguage(resolved),+ };+ }+ return undefined;+}diff --git a/lib/agent/session-artifact-resolver.ts b/lib/agent/session-artifact-resolver.tsnew file mode 100644index 00000000..633b4597--- /dev/null+++ b/lib/agent/session-artifact-resolver.ts@@ -0,0 +1,24 @@+import type { AgentSession } from "./session-types";+import { resolveHistoricalSessionActionRecord, resolveHistoricalSessionActionRecordForOwner } from "./session-action-history";+import { resolveArtifactRevisionView } from "./session-artifact-history";++export async function resolveHistoricalSessionArtifact(principal: string, session: AgentSession, actionRef: string) {+ const record = await resolveHistoricalSessionActionRecord(principal, session, actionRef);+ if (!record) return null;+ const artifact = record.resolution.action.artifact;+ if (!artifact) return { resolution: record.resolution, artifact: null, history: null };+ return {+ resolution: record.resolution,+ artifact,+ history: await resolveArtifactRevisionView(record.event.artifactRevision),+ };+}++/** Owner-console variant. The API route must verify owner role before calling this. */+export async function resolveHistoricalSessionArtifactForOwner(session: AgentSession, actionRef: string) {+ const record = await resolveHistoricalSessionActionRecordForOwner(session, actionRef);+ if (!record) return null;+ const artifact = record.resolution.action.artifact;+ if (!artifact) return { resolution: record.resolution, artifact: null, history: null };+ return { resolution: record.resolution, artifact, history: await resolveArtifactRevisionView(record.event.artifactRevision) };+}diff --git a/lib/agent/session-flow.ts b/lib/agent/session-flow.tsindex 778b1e20..465dd9fc 100644--- a/lib/agent/session-flow.ts+++ b/lib/agent/session-flow.ts@@ -1,5 +1,4 @@import { createHash } from "node:crypto";-import path from "node:path";import {SESSION_GRAPH_EVENT_LIMIT,type SessionFlowAction,@@ -11,10 +10,11 @@ import {import { redactText } from "@/lib/security/redact-text";import { eventSequenceBase } from "./session-sequence";import { normalizeSessionEventSemantics } from "./session-semantic";+import { resolveSessionArtifactCandidate } from "./session-artifact-path";+import { validSessionArtifactRevision } from "./session-artifact-history";import type { AgentSessionEvent } from "./session-types";const STEP_LIMIT = 8;-const CODE_EXTENSIONS = new Set(["ts", "tsx", "js", "jsx", "mjs", "cjs", "svelte", "py", "sh", "bash", "zsh", "md", "json", "yaml", "yml", "css", "scss", "html", "sql", "toml"]);const TITLES: Record<SessionFlowCategory, string> = {context: "Context", plan: "Plan", inspect: "Inspect", implement: "Implement",verify: "Verify", integrate: "Integrate", deploy: "Deploy", result: "Result", other: "Actions",@@ -35,33 +35,27 @@ function actionTitle(event: ReturnType<typeof safeEvent>): string {if (event.tool && /^fs_(read|write|delete|move|copy)/i.test(event.tool) && detail) return `${humanize(event.tool)} · ${detail}`.slice(0, 110);return humanize(event.tool || event.kind || "Action").slice(0, 110);}-function languageFor(filePath: string): string {- const ext = filePath.split(".").pop()?.toLowerCase() || "";- return ({ ts: "typescript", tsx: "tsx", js: "javascript", jsx: "jsx", mjs: "javascript", cjs: "javascript", svelte: "svelte", py: "python", sh: "bash", bash: "bash", zsh: "zsh", md: "markdown", json: "json", yaml: "yaml", yml: "yaml", css: "css", scss: "scss", html: "html", sql: "sql", toml: "toml" } as Record<string, string>)[ext] || "text";-}function stableId(prefix: string, value: string): string {return `${prefix}_${createHash("sha256").update(value).digest("hex").slice(0, 20)}`;}-function artifactPath(detail: string | undefined, cwd: string | undefined, revisionRef: string): SessionFlowAction["artifact"] | undefined {- if (!detail || !cwd) return undefined;- const candidates = detail.match(/(?:\/|\.?\.?\/)?[[email protected]]+(?:\/[[email protected]]+)*\.[A-Za-z0-9]+/g) || [];- for (const raw of candidates) {- const ext = raw.split(".").pop()?.toLowerCase() || "";- if (!CODE_EXTENSIONS.has(ext) || raw.includes("..")) continue;- const resolved = path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(cwd, raw.replace(/^\.\//, ""));- const rel = path.relative(path.resolve(cwd), resolved);- if (!rel || rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) continue;- return {- ref: stableId("artifact", rel.replaceAll(path.sep, "/")),- revisionRef,- path: resolved,- relativePath: rel.replaceAll(path.sep, "/"),- label: path.basename(resolved),- kind: ["sh", "bash", "zsh", "py", "js", "ts"].includes(ext) ? "script" : "file",- language: languageFor(resolved),- };- }- return undefined;+function artifactPath(row: AgentSessionEvent, detail: string | undefined, cwd: string | undefined, revisionRef: string): SessionFlowAction["artifact"] | undefined {+ const revision = validSessionArtifactRevision(row.artifactRevision) ? row.artifactRevision : undefined;+ const captureCwd = revision ? revision.cwd : cwd;+ const candidate = resolveSessionArtifactCandidate(detail, captureCwd);+ if (!candidate) return undefined;+ const capture = revision ? {+ state: "captured" as const,+ exactAtCapture: Boolean(revision.cleanAtCapture && revision.headBlob),+ ...(revision.worktreeSha256 ? { sha256: revision.worktreeSha256 } : {}),+ ...(revision.bytes !== undefined ? { bytes: revision.bytes } : {}),+ ...(revision.gitHead ? { gitHead: revision.gitHead } : {}),+ ...(revision.cleanAtCapture && revision.headBlob ? { gitBlob: revision.headBlob } : {}),+ } : { state: "legacy" as const, exactAtCapture: false };+ return {+ ref: stableId("artifact", candidate.relativePath), revisionRef,+ path: candidate.path, relativePath: candidate.relativePath, label: candidate.label,+ kind: candidate.kind, language: candidate.language, capture,+ };}function actionCode(event: ReturnType<typeof safeEvent>, artifact: SessionFlowAction["artifact"]): SessionFlowAction["code"] | undefined {if (!event.detail) return undefined;@@ -116,7 +110,7 @@ export function sessionFlowActions(events: AgentSessionEvent[], cwd?: string, raconst semantic = row.semantic!;const ref = `S${semantic.step}.A${semantic.action}`;const eventRef = `E${base + index + 1}`;- const artifact = artifactPath(event.detail, cwd, ref);+ const artifact = artifactPath(row, event.detail, cwd, ref);const action: SessionFlowAction = {id: stableId("action", `${eventRef}\0${ref}\0${event.at}\0${event.kind}\0${event.tool || ""}`),ref,diff --git a/lib/agent/session-mutations.ts b/lib/agent/session-mutations.tsindex dd36b390..73c0bc79 100644--- a/lib/agent/session-mutations.ts+++ b/lib/agent/session-mutations.ts@@ -6,6 +6,7 @@ import { autoSessionTitle, estimateTokens, MAX_EVENTS, MAX_HISTORY, safeTitle }import { retainSessionEvents } from "./session-sequence";import { appendSemanticSessionEvent } from "./session-semantic";import { archiveDroppedSessionEvents } from "./session-action-history";+import { captureSessionArtifactRevision } from "./session-artifact-history";import { compactIfNeeded, requireOwned } from "./session-record";import type { AgentSession, AgentSessionEvent, AgentSessionTitleSource } from "./session-types";@@ -124,6 +125,8 @@ export async function appendAgentSessionEvent(}: {}),};+ const artifactRevision = await captureSessionArtifactRevision(row, record.cwd);+ if (artifactRevision) row.artifactRevision = artifactRevision;const expanded = appendSemanticSessionEvent(record.events, row);const retained = retainSessionEvents(expanded, record.eventSeqBase, MAX_EVENTS);const droppedCount = expanded.length - retained.events.length;diff --git a/lib/agent/session-types.ts b/lib/agent/session-types.tsindex d6290bcd..e3eeebe5 100644--- a/lib/agent/session-types.ts+++ b/lib/agent/session-types.ts@@ -12,6 +12,23 @@ export interface AgentSessionEventSemantic {category: SessionFlowCategory;}+export interface AgentSessionArtifactRevision {+ version: 1;+ /** Capture-time cwd. Backend metadata used to resolve the project safely later. */+ cwd: string;+ /** Path relative to the capture-time cwd. */+ relativePath: string;+ repoRoot?: string;+ repoRelativePath?: string;+ gitHead?: string;+ headBlob?: string;+ worktreeBlob?: string;+ worktreeSha256?: string;+ bytes?: number;+ /** True only when the working file matched HEAD at capture time. */+ cleanAtCapture?: boolean;+}+export interface AgentSessionEvent {at: string;kind:@@ -28,6 +45,8 @@ export interface AgentSessionEvent {detail?: string;/** Durable semantic index metadata. Raw execution fields above remain the source of truth. */semantic?: AgentSessionEventSemantic;+ /** Compact proof metadata for future exact artifact history. Never stores the source body. */+ artifactRevision?: AgentSessionArtifactRevision;}export interface AgentSession {diff --git a/lib/contracts/session-monitor.ts b/lib/contracts/session-monitor.tsindex 4a665b86..196c70fa 100644--- a/lib/contracts/session-monitor.ts+++ b/lib/contracts/session-monitor.ts@@ -56,6 +56,14 @@ export interface SessionFlowArtifact {label: string;kind: "file" | "script";language?: string;+ capture?: {+ state: "legacy" | "captured";+ exactAtCapture: boolean;+ sha256?: string;+ bytes?: number;+ gitHead?: string;+ gitBlob?: string;+ };}export interface SessionFlowAction {/** Opaque durable identity scoped to the session. Not rendered as the human reference. */diff --git a/lib/host/pty-limits.test.ts b/lib/host/pty-limits.test.tsindex 2e92e990..2f78deeb 100644--- a/lib/host/pty-limits.test.ts+++ b/lib/host/pty-limits.test.ts@@ -19,6 +19,7 @@ type FakePty = {_exitCbs: ((e: { exitCode: number }) => void)[];};+const OWNER = "owner-a";const fakePtys: FakePty[] = [];vi.mock("node-pty", () => ({@@ -69,13 +70,8 @@ function resetSessions() {fakePtys.length = 0;}-beforeEach(() => {- resetSessions();-});--afterEach(() => {- resetSessions();-});+beforeEach(() => resetSessions());+afterEach(() => resetSessions());async function importPty() {// Fresh import so the mock is wired up; the module is cached but the mock@@ -83,38 +79,46 @@ async function importPty() {return await import("./pty");}-describe("PTY session cap", () => {+describe("PTY session limits and ownership", () => {+ it("does not let another authenticated device use a live terminal id", async () => {+ const { openPty, hasPty, attachPty, writePty, resizePty, closePty } = await importPty();+ const { id } = await openPty({ cols: 80, rows: 24, owner: OWNER });+ expect(hasPty(id, "owner-b")).toBe(false);+ expect(() => attachPty(id, "owner-b", 0, { onData: () => {}, onExit: () => {} })).toThrow(/Unknown terminal session/);+ expect(() => writePty(id, "owner-b", "echo nope\n")).toThrow(/Unknown terminal session/); expect(() => resizePty(id, "owner-b", 100, 30)).toThrow(/Unknown terminal session/);+ expect(closePty(id, "owner-b")).toBe(false); expect(closePty(id, OWNER)).toBe(true);+ });it("allows up to 8 concurrent sessions, rejects the 9th", async () => {const { openPty } = await importPty();const ids: string[] = [];for (let i = 0; i < 8; i++) {- const { id } = await openPty({ cols: 80, rows: 24 });+ const { id } = await openPty({ cols: 80, rows: 24, owner: OWNER });ids.push(id);}expect(ids).toHaveLength(8);- await expect(openPty({ cols: 80, rows: 24 })).rejects.toThrow(/Too many terminal sessions/);+ await expect(openPty({ cols: 80, rows: 24, owner: OWNER })).rejects.toThrow(/Too many terminal sessions/);});it("releases the slot when a session is closed → next open succeeds", async () => {const { openPty, closePty, attachPty } = await importPty();const ids: string[] = [];for (let i = 0; i < 8; i++) {- const { id } = await openPty({ cols: 80, rows: 24 });+ const { id } = await openPty({ cols: 80, rows: 24, owner: OWNER });ids.push(id);}// Capacity is full.- await expect(openPty({ cols: 80, rows: 24 })).rejects.toThrow(/Too many/);+ await expect(openPty({ cols: 80, rows: 24, owner: OWNER })).rejects.toThrow(/Too many/);// Close one — node-pty's exit fires via queueMicrotask, so attach to learn// when the session went dead.let exited = false;- attachPty(ids[0], 0, { onData: () => {}, onExit: () => (exited = true) });- expect(closePty(ids[0])).toBe(true);+ attachPty(ids[0], OWNER, 0, { onData: () => {}, onExit: () => (exited = true) });+ expect(closePty(ids[0], OWNER)).toBe(true);await new Promise((r) => setTimeout(r, 5));expect(exited).toBe(true);// Cap counts only LIVE (non-dead) sessions → slot freed.- const { id: id9 } = await openPty({ cols: 80, rows: 24 });+ const { id: id9 } = await openPty({ cols: 80, rows: 24, owner: OWNER });expect(id9).toBeTruthy();});@@ -124,13 +128,13 @@ describe("PTY session cap", () => {try {const { openPty, attachPty } = await importPty();const ids: string[] = [];- for (let i = 0; i < 8; i++) ids.push((await openPty({ cols: 80, rows: 24 })).id);+ for (let i = 0; i < 8; i++) ids.push((await openPty({ cols: 80, rows: 24, owner: OWNER })).id);// Seven active streams are protected. Leave only the eighth detached.- for (const id of ids.slice(0, 7)) attachPty(id, 0, { onData: () => {}, onExit: () => {} });+ for (const id of ids.slice(0, 7)) attachPty(id, OWNER, 0, { onData: () => {}, onExit: () => {} });await vi.advanceTimersByTimeAsync(11_000);- const { id: replacement } = await openPty({ cols: 80, rows: 24 });+ const { id: replacement } = await openPty({ cols: 80, rows: 24, owner: OWNER });expect(replacement).toBeTruthy();expect(fakePtys[7]!.killed).toBe(true);expect(fakePtys.slice(0, 7).every((pty) => !pty.killed)).toBe(true);@@ -145,11 +149,11 @@ describe("PTY session cap", () => {try {const { openPty, attachPty } = await importPty();const ids: string[] = [];- for (let i = 0; i < 8; i++) ids.push((await openPty({ cols: 80, rows: 24 })).id);- for (const id of ids) attachPty(id, 0, { onData: () => {}, onExit: () => {} });+ for (let i = 0; i < 8; i++) ids.push((await openPty({ cols: 80, rows: 24, owner: OWNER })).id);+ for (const id of ids) attachPty(id, OWNER, 0, { onData: () => {}, onExit: () => {} });await vi.advanceTimersByTimeAsync(60_000);- await expect(openPty({ cols: 80, rows: 24 })).rejects.toThrow(/Too many terminal sessions/);+ await expect(openPty({ cols: 80, rows: 24, owner: OWNER })).rejects.toThrow(/Too many terminal sessions/);expect(fakePtys.every((pty) => !pty.killed)).toBe(true);} finally {vi.useRealTimers();@@ -158,10 +162,10 @@ describe("PTY session cap", () => {it("closePty is idempotent + returns false on a dead session", async () => {const { openPty, closePty } = await importPty();- const { id } = await openPty({ cols: 80, rows: 24 });- expect(closePty(id)).toBe(true);+ const { id } = await openPty({ cols: 80, rows: 24, owner: OWNER });+ expect(closePty(id, OWNER)).toBe(true);await new Promise((r) => setTimeout(r, 5));- expect(closePty(id)).toBe(false);+ expect(closePty(id, OWNER)).toBe(false);});});@@ -171,10 +175,10 @@ describe("PTY idle reaper", () => {vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));try {const { openPty, attachPty } = await importPty();- const { id } = await openPty({ cols: 80, rows: 24 });+ const { id } = await openPty({ cols: 80, rows: 24, owner: OWNER });// Attach + detach so listeners.size === 0 → idle clock starts now.- const detach = attachPty(id, 0, { onData: () => {}, onExit: () => {} });+ const detach = attachPty(id, OWNER, 0, { onData: () => {}, onExit: () => {} });detach();// The reaper ticks once a minute. Push past the 30-min idle threshold.@@ -183,7 +187,7 @@ describe("PTY idle reaper", () => {// Session was killed → fake pty's onExit (queueMicrotask) marks it dead.// A fresh attach on a dead session replays exit immediately.let replayExit: number | null = null;- attachPty(id, 0, { onData: () => {}, onExit: (c) => (replayExit = c) });+ attachPty(id, OWNER, 0, { onData: () => {}, onExit: (c) => (replayExit = c) });expect(replayExit).toBe(0);} finally {vi.useRealTimers();@@ -194,16 +198,16 @@ describe("PTY idle reaper", () => {vi.useFakeTimers();try {const { openPty, attachPty, closePty } = await importPty();- const { id } = await openPty({ cols: 80, rows: 24 });+ const { id } = await openPty({ cols: 80, rows: 24, owner: OWNER });let exit: number | null = null;- attachPty(id, 0, { onData: () => {}, onExit: (c) => (exit = c) });+ attachPty(id, OWNER, 0, { onData: () => {}, onExit: (c) => (exit = c) });// Push past the idle window — but the listener pins it.vi.advanceTimersByTime(60 * 60_000);expect(exit).toBeNull();// Manual close still works.- expect(closePty(id)).toBe(true);+ expect(closePty(id, OWNER)).toBe(true);await vi.advanceTimersByTimeAsync(0);expect(exit).toBe(0);} finally {diff --git a/lib/host/pty.test.ts b/lib/host/pty.test.tsindex 8dd48c7f..af63e80e 100644--- a/lib/host/pty.test.ts+++ b/lib/host/pty.test.ts@@ -11,35 +11,37 @@ async function until(cond: () => boolean, ms: number): Promise<void> {await new Promise((r) => setTimeout(r, 25));}+const OWNER = "owner-a";+describe("pty session manager", () => {it("opens a shell, runs echo, replays buffer, and dies on close", async () => {- const { id, cwd } = await openPty({ cols: 80, rows: 24 });+ const { id, cwd } = await openPty({ cols: 80, rows: 24, owner: OWNER });expect(cwd.length).toBeGreaterThan(0);- expect(hasPty(id)).toBe(true);+ expect(hasPty(id, OWNER)).toBe(true);let out = "";let exit: number | null = null;- const detach = attachPty(id, 0, {+ const detach = attachPty(id, OWNER, 0, {onData: (chunk) => (out += chunk),onExit: (code) => (exit = code),});// $((20+22)) proves the SHELL ran it (the keystroke echo alone still// contains the literal "$((20+22))", never the expanded 42).- writePty(id, "echo pty-e2e-$((20+22))\n");+ writePty(id, OWNER, "echo pty-e2e-$((20+22))\n");await until(() => out.includes("pty-e2e-42"), 8000);expect(out).toContain("pty-e2e-42");// A second attach from offset 0 must replay the same buffered output.let replay = "";- const detach2 = attachPty(id, 0, { onData: (c) => (replay += c), onExit: () => {} });+ const detach2 = attachPty(id, OWNER, 0, { onData: (c) => (replay += c), onExit: () => {} });expect(replay).toContain("pty-e2e-42");detach2();- expect(closePty(id)).toBe(true);+ expect(closePty(id, OWNER)).toBe(true);await until(() => exit !== null, 8000);expect(exit).not.toBeNull();- expect(closePty(id)).toBe(false); // idempotent after death+ expect(closePty(id, OWNER)).toBe(false); // idempotent after deathdetach();}, 20_000);});diff --git a/lib/host/pty.ts b/lib/host/pty.tsindex 2d6d2c82..d5b0c6e5 100644--- a/lib/host/pty.ts+++ b/lib/host/pty.ts@@ -11,7 +11,7 @@// (high-volume, and the owner has a full shell by design).import { spawn } from "node-pty";import type { IPty } from "node-pty";-import { randomBytes } from "crypto";+import { createHash, randomBytes } from "crypto";import { HostError } from "./host-error";import { resolveCwd } from "./exec";import { childEnv } from "./child-env";@@ -36,6 +36,7 @@ export type PtyListener = {type Session = {id: string;+ ownerHash: string;pty: IPty;/** Replay ring: recent output chunks with absolute start offsets. */chunks: { off: number; data: string }[];@@ -70,9 +71,14 @@ function ensureReaper(): void {g.__osPtyReaper.unref?.();}-function get(id: string): Session {+function ownerHash(owner: string): string {+ if (!owner || owner.length > 512) throw new HostError("Unknown terminal session");+ return createHash("sha256").update(owner).digest("hex");+}++function get(id: string, owner: string): Session {const s = sessions.get(id);- if (!s) throw new HostError("Unknown terminal session");+ if (!s || s.ownerHash !== ownerHash(owner)) throw new HostError("Unknown terminal session");return s;}@@ -102,6 +108,7 @@ export async function openPty(opts: {cols: number;rows: number;cwd?: string;+ owner: string;}): Promise<{ id: string; cwd: string }> {let live = 0;for (const s of sessions.values()) if (!s.dead) live++;@@ -123,6 +130,7 @@ export async function openPty(opts: {});const s: Session = {id: randomBytes(16).toString("hex"),+ ownerHash: ownerHash(opts.owner),pty,chunks: [],buffered: 0,@@ -154,15 +162,16 @@ export async function openPty(opts: {}/** True when the session id exists (live or recently exited). */-export function hasPty(id: string): boolean {- return sessions.has(id);+export function hasPty(id: string, owner: string): boolean {+ const session = sessions.get(id);+ return Boolean(session && session.ownerHash === ownerHash(owner));}// Attach a stream: replay buffered output past `fromOffset` synchronously,// then live events. A dead session replays + fires onExit immediately.// Returns the detach fn (idle-reap clock starts when the last client leaves).-export function attachPty(id: string, fromOffset: number, l: PtyListener): () => void {- const s = get(id);+export function attachPty(id: string, owner: string, fromOffset: number, l: PtyListener): () => void {+ const s = get(id, owner);const from = Math.max(0, Math.min(fromOffset, s.offset));for (const c of s.chunks) {const end = c.off + c.data.length;@@ -180,14 +189,14 @@ export function attachPty(id: string, fromOffset: number, l: PtyListener): () =>};}-export function writePty(id: string, data: string): void {- const s = get(id);+export function writePty(id: string, owner: string, data: string): void {+ const s = get(id, owner);if (s.dead) throw new HostError("Terminal session has exited");s.pty.write(data);}-export function resizePty(id: string, cols: number, rows: number): void {- const s = get(id);+export function resizePty(id: string, owner: string, cols: number, rows: number): void {+ const s = get(id, owner);if (s.dead) throw new HostError("Terminal session has exited");s.pty.resize(clampDim(cols), clampDim(rows));}@@ -195,9 +204,9 @@ export function resizePty(id: string, cols: number, rows: number): void {// Idempotent close: the client fires close-on-unmount even after the shell// already exited. Returns whether a live shell was actually killed (audit// only logs a real kill).-export function closePty(id: string): boolean {+export function closePty(id: string, owner: string): boolean {const s = sessions.get(id);- if (!s || s.dead) return false;+ if (!s || s.ownerHash !== ownerHash(owner) || s.dead) return false;s.pty.kill();return true;}diff --git a/lib/mcp/tools-agent.test.ts b/lib/mcp/tools-agent.test.tsindex 8edc8d86..b521e782 100644--- a/lib/mcp/tools-agent.test.ts+++ b/lib/mcp/tools-agent.test.ts@@ -6,7 +6,8 @@ import path from "node:path";const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-tools-agent-p1-"));process.env.OS_AGENT_MEMORY_DIR = root;process.env.OS_AGENT_SESSIONS_DIR = path.join(root, "sessions");-afterAll(async () => { delete process.env.OS_AGENT_MEMORY_DIR; delete process.env.OS_AGENT_SESSIONS_DIR; await fs.rm(root, { recursive: true, force: true }); });+process.env.OS_FS_WRITE_ROOTS = root;+afterAll(async () => { delete process.env.OS_AGENT_MEMORY_DIR; delete process.env.OS_AGENT_SESSIONS_DIR; delete process.env.OS_FS_WRITE_ROOTS; await fs.rm(root, { recursive: true, force: true }); });vi.resetModules();const { AGENT_TOOLS } = await import("./tools-agent");@@ -40,7 +41,10 @@ describe("semantic session resolver tools", () => {it("resolves stable human refs owner-safely without exposing internal session ids or secrets", async () => {const store = await import("@/lib/agent/session-store");const principal = "mcp-client:flow-owner";- const session = await store.createAgentSession(principal, "mcp", { title: "Semantic resolver", cwd: "/tmp/project" });+ const project = path.join(root, "project");+ await fs.mkdir(path.join(project, "src"), { recursive: true });+ await fs.writeFile(path.join(project, "src", "app.ts"), "export const password=secret-value;\n", "utf8");+ const session = await store.createAgentSession(principal, "mcp", { title: "Semantic resolver", cwd: project });await store.appendAgentSessionEvent(principal, session.id, { kind: "tool", tool: "fs_read", state: "completed", detail: "src/app.ts token=secret-value" });await store.appendAgentSessionEvent(principal, session.id, { kind: "tool", tool: "fs_write", state: "completed", detail: "src/app.ts" });const context = { principal, sessionId: session.id, scope: "exec" as const };@@ -52,6 +56,12 @@ describe("semantic session resolver tools", () => {expect(body).not.toContain(session.id);expect(body).not.toContain("secret-value");expect(body).toContain("[redacted]");+ const writeRef = flow.steps.flatMap((step) => step.actions).find((action) => action.tool === "fs_write")?.ref;+ const historical = await tool("agent_session_action_resolve").run({ session_ref: `@${session.name}`, action_ref: writeRef, artifact_view: "snapshot" }, context);+ const historicalBody = JSON.stringify(historical);+ expect(historicalBody).toContain("artifactHistory");+ expect(historicalBody).toContain("previewRedacted");+ expect(historicalBody).not.toContain("password=secret-value");await expect(tool("agent_session_action_resolve").run({ session_ref: `@${session.name}`, action_ref: actionRef }, { ...context, principal: "mcp-client:other" })).rejects.toThrow(/not found|session/i);});});diff --git a/lib/mcp/tools-agent.ts b/lib/mcp/tools-agent.tsindex 0e82d3d7..96dab701 100644--- a/lib/mcp/tools-agent.ts+++ b/lib/mcp/tools-agent.ts@@ -6,6 +6,7 @@ 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";function principal(context: { principal?: string }): string {if (!context.principal) throw new Error("agent session principal is unavailable");@@ -88,15 +89,26 @@ export const AGENT_TOOLS: McpTool[] = [inputSchema: S({session_ref: { type: "string", description: "Human session label (agent-context), @name, title, or legacy exact id." },action_ref: { type: "string", description: "Stable semantic action reference such as S3.A4, event reference such as E217, or an opaque action id returned by the semantic flow." },+ artifact_view: { type: "string", enum: ["metadata", "snapshot", "diff"], description: "Optional exact artifact history view. Snapshot/diff are returned only when capture proof is trustworthy." },}, ["session_ref", "action_ref"]),run: async (a, context) => {const owner = principal(context), target = await resolveAgentSessionRef(owner, str(a, "session_ref"));- const resolved = await resolveHistoricalSessionAction(owner, target, str(a, "action_ref"));- if (!resolved) throw new Error(`session action not found: ${str(a, "action_ref").toUpperCase()}`);- return {- session: { label: agentSessionLabel(target.name, target.title, target.cwd), title: target.title, source: target.source, updatedAt: target.updatedAt, ...(target.cwd ? { cwd: target.cwd } : {}) },- ...resolved,- };+ const actionRef = str(a, "action_ref"), artifactView = enumValue(a, "artifact_view", ["metadata", "snapshot", "diff"] as const);+ const session = { label: agentSessionLabel(target.name, target.title, target.cwd), title: target.title, source: target.source, updatedAt: target.updatedAt, ...(target.cwd ? { cwd: target.cwd } : {}) };+ if (artifactView) {+ const artifact = await resolveHistoricalSessionArtifact(owner, target, actionRef);+ if (!artifact) throw new Error(`session action not found: ${actionRef.toUpperCase()}`);+ if (!artifact.artifact || !artifact.history) return { session, ...artifact.resolution, artifactHistory: null };+ const history = structuredClone(artifact.history) as any;+ if (artifactView === "metadata") {+ if (history.historical) delete history.historical.content;+ if (history.diff) delete history.diff.unifiedDiff;+ } else if (artifactView === "snapshot" && history.diff) delete history.diff.unifiedDiff;+ return { session, ...artifact.resolution, artifactHistory: history };+ }+ const resolved = await resolveHistoricalSessionAction(owner, target, actionRef);+ if (!resolved) throw new Error(`session action not found: ${actionRef.toUpperCase()}`);+ return { session, ...resolved };},},{diff --git a/scripts/e2e/mcp-sessions.mjs b/scripts/e2e/mcp-sessions.mjsindex 1fa3da17..cff5c397 100644--- a/scripts/e2e/mcp-sessions.mjs+++ b/scripts/e2e/mcp-sessions.mjs@@ -66,6 +66,33 @@ export async function mcpSessionsJourney(page, fixture) {const selectedGraphResponse = await page.request.get(fixture.base + `/api/v1/agent-sessions?view=graph&id=${encodeURIComponent(selectedMonitor.sessions[0].id)}`);const selectedGraph = await selectedGraphResponse.json();expect(selectedGraph.graph.nodes.length).toBeLessThanOrEqual(9);+ const artifactStep = selectedGraph.steps.find(step => step.actions.some(action => action.artifact));+ const artifactAction = artifactStep?.actions.find(action => action.artifact);+ expect(artifactStep).toBeTruthy(); expect(artifactAction).toBeTruthy();+ const artifactApi = await page.request.get(fixture.base + `/api/v1/agent-sessions?view=artifact&id=${encodeURIComponent(selectedMonitor.sessions[0].id)}&action_ref=${encodeURIComponent(artifactAction.ref)}`);+ expect(artifactApi.status()).toBe(200);+ const artifactPayload = await artifactApi.json();+ expect(artifactPayload.history.capture.exactAtCapture).toBe(true);+ expect(artifactPayload.history.historical).toMatchObject({ available: true, exact: true, source: "git-blob", previewRedacted: true });+ expect(artifactPayload.history.diff).toMatchObject({ available: true, changed: true, previewRedacted: true });+ expect(JSON.stringify(artifactPayload)).not.toMatch(/FIXTURE_SECRET_MUST_NOT_LEAK|principalHash/);+ const artifactStepNode = page.locator(".react-flow__node").filter({ hasText: artifactStep.ref + " ·" }).first();+ await artifactStepNode.click();+ await expect(page.getByText("Action groups", { exact: true }).last()).toBeVisible();+ const artifactGroup = artifactStep.groups.find(group => group.actionRefs.includes(artifactAction.ref));+ expect(artifactGroup).toBeTruthy();+ await page.locator(`details[data-slot="session-action-group"][data-action-group-ref="${artifactGroup.ref}"] > summary`).click();+ await page.locator(`details[data-slot="session-action"][data-action-ref="${artifactAction.ref}"] > summary`).click();+ await page.getByRole("button", { name: "Inspect revision", exact: true }).click();+ await expect(page.getByText("exact capture", { exact: true })).toBeVisible();+ await expect(page.locator('[data-slot="session-artifact-snapshot"]')).toBeVisible();+ await expect(page.locator('[data-slot="session-artifact-diff"]')).toBeVisible();+ expect(await page.locator('[data-slot="session-artifact-history"]').innerText()).not.toMatch(/FIXTURE_SECRET_MUST_NOT_LEAK/);+ const openDetailsOverlay = page.locator('[data-slot="sheet-overlay"][data-state="open"]');+ if (await openDetailsOverlay.count()) {+ await page.keyboard.press("Escape");+ await expect(openDetailsOverlay).toHaveCount(0);+ }const terminalStep = selectedGraph.steps.find(step => step.actions.some(action => action.terminalContext));expect(terminalStep).toBeTruthy();const terminalStepNode = page.locator(".react-flow__node").filter({ hasText: terminalStep.ref + " ·" }).first();@@ -74,7 +101,11 @@ export async function mcpSessionsJourney(page, fixture) {await expect(terminalStepNode).toBeVisible();expect(await page.locator('[data-slot="workflows-feature"]').innerText()).not.toMatch(/\b\d{8}_\d{6}_[a-f0-9]{8}\b/);await terminalStepNode.click();- await expect(page.getByText("Action groups", { exact: true }).last()).toBeVisible();+ const terminalActionGroups = page.getByText("Action groups", { exact: true }).last();+ if (!await terminalActionGroups.isVisible().catch(() => false)) {+ await page.getByRole("button", { name: "Session details", exact: true }).click();+ }+ await expect(terminalActionGroups).toBeVisible();await expect(page.getByRole("button", { name: `Save ${terminalStep.ref} as workflow draft`, exact: true })).toBeVisible();await expect(page.getByText("Self-improve", { exact: true }).last()).toBeVisible();expect(await terminalTabs.count()).toBe(terminalCountBefore); // Selecting a node must not launch tools.diff --git a/scripts/e2e/session-fixture.mjs b/scripts/e2e/session-fixture.mjsindex b008c290..c95b26bd 100644--- a/scripts/e2e/session-fixture.mjs+++ b/scripts/e2e/session-fixture.mjs@@ -1,9 +1,21 @@import { mkdir, writeFile } from "node:fs/promises";+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";import path from "node:path";export async function seedSessionMonitor(env, count = 9) {const root = env.OS_AGENT_SESSIONS_DIR;if (!root || !env.OS_LOCAL_AGENT_PRESENCE_STORE) throw new Error("Synthetic session stores required");await mkdir(root, { recursive: true, mode: 0o700 });+ const project = path.join(path.dirname(root), "session-project");+ await mkdir(path.join(project, "src"), { recursive: true, mode: 0o700 });+ const original = "export const value = 1;\n", current = "export const value = 2;\n", artifactFile = path.join(project, "src", "fixture.ts");+ await writeFile(artifactFile, original, { mode: 0o600 });+ const git = (...args) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();+ git("init", "-b", "main"); git("config", "user.email", "[email protected]"); git("config", "user.name", "MSO Release Fixture");+ git("add", "src/fixture.ts"); git("commit", "-m", "fixture artifact");+ const gitHead = git("rev-parse", "HEAD"), headBlob = git("rev-parse", "HEAD:src/fixture.ts"), worktreeSha256 = createHash("sha256").update(original).digest("hex");+ const artifactRevision = { version: 1, cwd: project, relativePath: "src/fixture.ts", repoRoot: project, repoRelativePath: "src/fixture.ts", gitHead, headBlob, worktreeBlob: headBlob, worktreeSha256, bytes: Buffer.byteLength(original), cleanAtCapture: true };+ await writeFile(artifactFile, current, { mode: 0o600 });const now = Date.now(), entries = [];for (let i = 0; i < count; i++) {const id = "20260909_120000_" + i.toString(16).padStart(8, "0"), at = new Date(now - i * 1000).toISOString();@@ -11,9 +23,11 @@ export async function seedSessionMonitor(env, count = 9) {const row = { id, principalHash, source: i % 2 ? "mcp" : "cli", name: "fixture-" + i,title: "Session fixture " + i, titleSource: "manual", createdAt: at, updatedAt: at,memorySnapshot: {}, history: ["PRIVATE_TRANSCRIPT_MUST_NOT_LEAK"], contextSummary: "PRIVATE_CONTEXT_MUST_NOT_LEAK",+ cwd: project,events: Array.from({ length: 25 }, (_, n) => ({ at: new Date(now - (24 - n) * 100).toISOString(),- kind: "tool", tool: "exec_run", state: n === 0 ? "failed" : "completed",- detail: "Verify fixture " + n + " token=FIXTURE_SECRET_MUST_NOT_LEAK", workflowId: "workflow-fixture" })),+ kind: "tool", tool: n === 0 ? "fs_write" : "exec_run", state: n === 0 ? "completed" : "completed",+ detail: n === 0 ? "src/fixture.ts token=FIXTURE_SECRET_MUST_NOT_LEAK" : "Verify fixture " + n + " token=FIXTURE_SECRET_MUST_NOT_LEAK", workflowId: "workflow-fixture",+ ...(n === 0 ? { artifactRevision } : {}) })),estimatedTokens: 0, lifetimeEstimatedTokens: 0, compactThresholdTokens: 700000, compactionCount: 0, archiveCount: 0 };await writeFile(path.join(root, id + ".json"), JSON.stringify(row), { mode: 0o600 });entries.push({ sessionId: id, principalHash, alias: "agent-" + String.fromCharCode(97 + i), instanceId: "fixture",