Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(workflows): stabilize semantic action references

Rahman0e82979ccf20
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index d154af54..494e6ea2 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `workflows` stabilize semantic action references
- `workflows` add semantic session flows
- `workflows` visualize agent sessions
- `ai` add dynamic free provider discovery
diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.md
index 6bd922d7..5749e23a 100644
--- a/docs/generated/MCP-CATALOG.md
+++ b/docs/generated/MCP-CATALOG.md
@@ -4,27 +4,28 @@
## Full MSO catalog
-<!-- mcp-toolset: server=1.14.4 version=2026.09.15.3 tools=109 read=52 write=35 exec=22 -->
+<!-- mcp-toolset: server=1.14.4 version=2026.09.15.3 tools=110 read=53 write=35 exec=22 -->
| Fact | Current source value |
|---|---:|
| MCP server | `1.14.4` |
| Toolset | `2026.09.15.3` |
| Toolset changed at | `2026-09-15T03:35:00+07:00` |
-| Transport tools | **111** |
-| Model/operator tools | **109** |
-| Read | **52** |
+| Transport tools | **112** |
+| Model/operator tools | **110** |
+| Read | **53** |
| Write | **35** |
| Exec | **22** |
| App-only bridges | **2** |
-### Read (52)
+### Read (53)
- `a2a_agent_discover`
- `a2a_agents_list`
- `a2a_task_get`
- `agent_memory_read`
- `agent_memory_search`
+- `agent_session_action_resolve`
- `agent_session_current`
- `agent_session_flow`
- `agent_session_resume`
@@ -143,26 +144,27 @@
## ChatGPT model profile
-<!-- mcp-chatgpt-profile: server=1.14.4 version=2026.09.15.3 tools=109 read=52 write=35 exec=22 app-only=2 total=111 -->
+<!-- mcp-chatgpt-profile: server=1.14.4 version=2026.09.15.3 tools=110 read=53 write=35 exec=22 app-only=2 total=112 -->
The ChatGPT profile automatically projects the complete MSO-owned generic model/operator catalog. OAuth scope is still enforced independently; app-only compatibility bridges stay app-only, and project-owned MCP tool names remain dynamic data behind the generic project bridge.
| Fact | Current source value |
|---|---:|
-| ChatGPT transport tools | **111** |
-| ChatGPT model/operator tools | **109** |
-| Read | **52** |
+| ChatGPT transport tools | **112** |
+| ChatGPT model/operator tools | **110** |
+| Read | **53** |
| Write | **35** |
| Exec | **22** |
| App-only bridges | **2** |
-### ChatGPT read (52)
+### ChatGPT read (53)
- `a2a_agent_discover`
- `a2a_agents_list`
- `a2a_task_get`
- `agent_memory_read`
- `agent_memory_search`
+- `agent_session_action_resolve`
- `agent_session_current`
- `agent_session_flow`
- `agent_session_resume`
diff --git a/frontend/slices/workflows/components/workflow-session-details.tsx b/frontend/slices/workflows/components/workflow-session-details.tsx
index 9e200e58..a848b091 100644
--- a/frontend/slices/workflows/components/workflow-session-details.tsx
+++ b/frontend/slices/workflows/components/workflow-session-details.tsx
@@ -23,11 +23,25 @@ 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>
- <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.path}</span> : null}</div>
+ <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) {
+ return step.groups.map((group) => {
+ const refs = new Set(group.actionRefs);
+ const actions = step.actions.filter((action) => refs.has(action.ref));
+ return <details key={group.ref} data-slot="session-action-group" data-action-group-ref={group.ref} className="rounded-lg border bg-muted/15">
+ <summary className="flex cursor-pointer list-none items-center gap-2 px-2.5 py-2 text-xs marker:hidden">
+ <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>
+ </details>;
+ });
+}
+
export function WorkflowSessionDetails({ view, node, onOpenTerminal, onOpenCode }: { view: SessionGraphView; node: WorkflowGraphNode | null; onOpenTerminal: () => void; onOpenCode: (path: string) => void }) {
const ref = node ? value(node.config, "ref") : undefined;
const step: SessionFlowStep | undefined = ref ? view.steps.find((item) => item.ref === ref) : undefined;
@@ -41,7 +55,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></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></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">Actions</div><span className="text-[10px] text-muted-foreground">{step.actions.length}</span></div><div className="space-y-1.5">{step.actions.map((action) => actionReceipt(action, 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, onOpenTerminal, onOpenCode)}</div></div>
</> : <p className="text-xs text-muted-foreground">Select a semantic step to inspect its actions.</p>}
{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}
</div></ScrollArea>
diff --git a/frontend/slices/workflows/session-graph-ui.test.ts b/frontend/slices/workflows/session-graph-ui.test.ts
index a66ddd90..fbade42f 100644
--- a/frontend/slices/workflows/session-graph-ui.test.ts
+++ b/frontend/slices/workflows/session-graph-ui.test.ts
@@ -28,6 +28,9 @@ describe("Workflow session graph UI contract", () => {
expect(workflowApp).toContain('const openSessionCode = (path: string) => { setDetailsOpen(false);');
expect(sessionDetails).toContain("Open terminal here");
expect(sessionDetails).toContain("Open {action.artifact.label} in Code");
+ expect(sessionDetails).toContain('data-slot="session-action-group"');
+ expect(sessionDetails).toContain("Action groups");
+ expect(sessionDetails).toContain("action.artifact.revisionRef");
expect(sessionDetails).toContain("S3.A4");
expect(workflowCanvas).toContain('showMinimap={!readOnly}');
});
diff --git a/lib/agent/session-create.ts b/lib/agent/session-create.ts
index 35212fe1..ff00fad0 100644
--- a/lib/agent/session-create.ts
+++ b/lib/agent/session-create.ts
@@ -4,6 +4,7 @@ import { listSessionRecords, newAgentSessionId, principalHash, sessionNameLockTa
import { normalizeAgentSessionCwd } from "./session-location";
import { allocateAgentSessionName, requireAgentSessionName } from "./session-name";
import { MAX_HISTORY, compactThresholdTokens, safeTitle, sessionContextTokens } from "./session-policy";
+import { appendSemanticSessionEvent } from "./session-semantic";
import type { AgentSession, AgentSessionEvent, AgentSessionSource, AgentSessionTitleSource } from "./session-types";
export interface CreateOptions {
@@ -31,13 +32,13 @@ async function buildRecord(
if (usedNames.includes(name)) throw new Error(`session name @${name} is already in use`);
const memorySnapshot =
options.memorySnapshot ?? (await snapshotAgentMemory(principal));
- const created: AgentSessionEvent = {
+ const created: AgentSessionEvent = appendSemanticSessionEvent([], {
at: now,
kind: "created",
...(options.resumedFrom
? { detail: `resumed from ${options.resumedFrom}` }
: {}),
- };
+ })[0]!;
const record: AgentSession = {
id: options.id ?? newAgentSessionId(),
principalHash: principalHash(principal),
@@ -63,6 +64,7 @@ async function buildRecord(
: {}),
history: (options.history ?? []).slice(-MAX_HISTORY),
events: [created],
+ eventSeqBase: 0,
estimatedTokens: 0,
lifetimeEstimatedTokens: 0,
compactThresholdTokens: compactThresholdTokens(),
diff --git a/lib/agent/session-files.ts b/lib/agent/session-files.ts
index 4eed9f25..39b552eb 100644
--- a/lib/agent/session-files.ts
+++ b/lib/agent/session-files.ts
@@ -2,6 +2,8 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
import { constants as fsConstants, promises as fs } from "node:fs";
import path from "node:path";
import { compactThresholdTokens, inferredTitleSource, MAX_EVENTS, MAX_HISTORY, safeTitle, sessionContextTokens } from "./session-policy";
+import { eventSequenceBase, retainSessionEvents } from "./session-sequence";
+import { normalizeSessionEventSemantics } from "./session-semantic";
import type { AgentSession } from "./session-types";
import { legacyAgentSessionName, normalizeAgentSessionName } from "./session-name";
@@ -112,13 +114,15 @@ function fileFor(id: string): string {
export function normalizeSession(raw: AgentSession): AgentSession {
const title = safeTitle(raw.title);
const threshold = Number(raw.compactThresholdTokens) || compactThresholdTokens();
+ const retained = retainSessionEvents(Array.isArray(raw.events) ? raw.events : [], eventSequenceBase(raw.eventSeqBase), MAX_EVENTS);
const base = {
...raw,
name: normalizeAgentSessionName((raw as AgentSession & { name?: string }).name) || legacyAgentSessionName(raw.id),
title,
titleSource: inferredTitleSource(title, raw.titleSource),
history: Array.isArray(raw.history) ? raw.history.slice(-MAX_HISTORY) : [],
- events: Array.isArray(raw.events) ? raw.events.slice(-MAX_EVENTS) : [],
+ events: normalizeSessionEventSemantics(retained.events),
+ eventSeqBase: retained.eventSeqBase,
compactThresholdTokens: threshold,
compactionCount: Math.max(0, Number(raw.compactionCount) || 0),
archiveCount: Math.max(0, Number(raw.archiveCount) || 0),
diff --git a/lib/agent/session-flow.test.ts b/lib/agent/session-flow.test.ts
index 490875c1..83c97fdb 100644
--- a/lib/agent/session-flow.test.ts
+++ b/lib/agent/session-flow.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from "vitest";
-import { semanticSessionFlow } from "./session-flow";
+import { resolveSessionFlowAction, semanticSessionFlow } from "./session-flow";
+import { appendSemanticSessionEvent, normalizeSessionEventSemantics } from "./session-semantic";
+import { retainSessionEvents } from "./session-sequence";
import type { AgentSessionEvent } from "./session-types";
const at = (n: number) => new Date(1_780_000_000_000 + n * 1000).toISOString();
@@ -32,4 +34,56 @@ describe("semantic session flow", () => {
expect(action.artifact).toMatchObject({ path: "/srv/project/scripts/release.sh", label: "release.sh", kind: "script" });
expect(action.terminalContext).toBe(true);
});
+
+ it("keeps stable refs when the latest-120 projection moves and resolves actions outside the canvas window", () => {
+ const raw: AgentSessionEvent[] = Array.from({ length: 140 }, (_, index) => ({
+ at: at(index),
+ kind: "tool",
+ tool: index % 3 === 0 ? "fs_read" : index % 3 === 1 ? "fs_write" : "exec_run",
+ state: "completed",
+ detail: index % 3 === 2 ? "bunx vitest run" : `src/file-${index}.ts`,
+ }));
+ const indexed = normalizeSessionEventSemantics(raw);
+ const before = resolveSessionFlowAction(indexed, "E130", "/srv/project", 0)!;
+ const projected = semanticSessionFlow(indexed, 120, "/srv/project", 0);
+ expect(projected.shownEvents).toBeLessThanOrEqual(120);
+ expect(projected.steps.length).toBeLessThanOrEqual(8);
+ let next = indexed;
+ for (let index = 140; index < 180; index += 1) next = appendSemanticSessionEvent(next, { at: at(index), kind: "tool", tool: "fs_read", state: "completed", detail: `src/new-${index}.ts` });
+ const after = resolveSessionFlowAction(next, "E130", "/srv/project", 0)!;
+ expect(after.action.ref).toBe(before.action.ref);
+ expect(after.action.id).toBe(before.action.id);
+ expect(semanticSessionFlow(next, 120, "/srv/project", 0).steps.flatMap((step) => step.actions).some((action) => action.eventRef === "E130")).toBe(false);
+ });
+
+ it("keeps refs stable across MAX_EVENTS rotation using persisted semantic metadata and eventSeqBase", () => {
+ let events = normalizeSessionEventSemantics(Array.from({ length: 400 }, (_, index) => ({
+ at: at(index), kind: "tool" as const, tool: index < 200 ? "fs_read" : "fs_write", state: "completed", detail: `src/${index}.ts`,
+ })));
+ const before = resolveSessionFlowAction(events, "E400", "/srv/project", 0)!;
+ const appended = appendSemanticSessionEvent(events, { at: at(400), kind: "tool", tool: "fs_write", state: "completed", detail: "src/400.ts" });
+ const retained = retainSessionEvents(appended, 0, 400);
+ events = retained.events;
+ const after = resolveSessionFlowAction(events, "E400", "/srv/project", retained.eventSeqBase)!;
+ expect(retained.eventSeqBase).toBe(1);
+ expect(after.action.ref).toBe(before.action.ref);
+ expect(after.action.id).toBe(before.action.id);
+ expect(resolveSessionFlowAction(events, "E401", "/srv/project", retained.eventSeqBase)?.action.ref).toMatch(/^S\d+\.A\d+$/);
+ });
+
+ it("aggregates homogeneous actions without losing exact child receipts or durable artifact identity", () => {
+ const flow = semanticSessionFlow(normalizeSessionEventSemantics([
+ { at: at(0), kind: "tool", tool: "fs_read", detail: "src/a.ts" },
+ { at: at(1), kind: "tool", tool: "fs_read", detail: "src/b.ts" },
+ { at: at(2), kind: "tool", tool: "fs_search", detail: "semanticSessionFlow" },
+ ]), 120, "/srv/project", 0);
+ const step = flow.steps[0]!;
+ expect(step.groups.find((group) => group.key === "read")).toMatchObject({ title: "Read files", count: 2 });
+ expect(step.groups.flatMap((group) => group.actionRefs)).toEqual(expect.arrayContaining(step.actions.map((action) => action.ref)));
+ const artifact = step.actions[0]!.artifact!;
+ expect(artifact.ref).toMatch(/^artifact_[a-f0-9]{20}$/);
+ expect(artifact.relativePath).toBe("src/a.ts");
+ expect(artifact.revisionRef).toBe(step.actions[0]!.ref);
+ });
+
});
diff --git a/lib/agent/session-flow.ts b/lib/agent/session-flow.ts
index 6ee6aa86..be684002 100644
--- a/lib/agent/session-flow.ts
+++ b/lib/agent/session-flow.ts
@@ -1,10 +1,20 @@
+import { createHash } from "node:crypto";
import path from "node:path";
-import { SESSION_GRAPH_EVENT_LIMIT, type SessionFlowAction, type SessionFlowCategory, type SessionFlowStep } from "@/lib/contracts/session-monitor";
+import {
+ SESSION_GRAPH_EVENT_LIMIT,
+ type SessionFlowAction,
+ type SessionFlowActionGroup,
+ type SessionFlowActionResolution,
+ type SessionFlowCategory,
+ type SessionFlowStep,
+} from "@/lib/contracts/session-monitor";
import { redactText } from "@/lib/security/redact-text";
+import { eventSequenceBase } from "./session-sequence";
+import { normalizeSessionEventSemantics } from "./session-semantic";
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 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",
@@ -16,20 +26,6 @@ function text(value: string | undefined, max = 1000): string | undefined {
function safeEvent(row: AgentSessionEvent) {
return { at: row.at, kind: text(row.kind, 40) || "note", tool: text(row.tool, 100), state: text(row.state, 60), detail: text(row.detail, 1000) };
}
-function classify(event: ReturnType<typeof safeEvent>): SessionFlowCategory {
- const tool = (event.tool || "").toLowerCase(), detail = (event.detail || "").toLowerCase(), hay = `${tool} ${detail}`;
- if (["created", "resumed", "compacted"].includes(event.kind)) return "context";
- if (event.kind === "archived" || /workflow_(finish|cancel)/.test(tool)) return "result";
- if (/workflow_start/.test(tool) || /\b(plan|intent|scope|approach)\b/.test(detail) && event.kind === "note") return "plan";
- if (/\b(deploy|dokploy|systemctl|restart|health(?:check)?|production|cloudflare)\b/.test(hay)) return "deploy";
- if (/\bgit\s+(add|commit|merge|cherry-pick|push|rebase|reset|tag)\b/.test(detail) || /\b(pull request|\bpr\b)\b/.test(hay)) return "integrate";
- if (/\b(test|vitest|playwright|lint|typecheck|coverage|audit|verify|verification|check|build)\b/.test(hay)) return "verify";
- if (/\b(fs_write|fs_delete|fs_move|fs_copy|apply_patch|patch|edit|update|create|save|write)\b/.test(tool) || /\b(sed\s+-i|perl\s+-pi|mkdir|rm\s+-|cp\s+|mv\s+|cat\s+>|tee\s+)\b/.test(detail)) return "implement";
- if (/\b(fs_read|fs_list|fs_search|read|search|list|query|inspect|status|find)\b/.test(tool) || /^(git\s+(status|diff|log|show)|rg\b|grep\b|find\b|ls\b|cat\b|sed\s+-n)/.test(detail)) return "inspect";
- if (event.kind === "note") return "context";
- if (event.kind === "workflow") return "plan";
- return "other";
-}
function humanize(value: string): string {
return value.replace(/[_.:-]+/g, " ").replace(/\b\w/g, (char) => char.toUpperCase()).trim();
}
@@ -41,18 +37,29 @@ function actionTitle(event: ReturnType<typeof safeEvent>): string {
}
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";
+ 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): SessionFlowAction["artifact"] | undefined {
+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) || [];
+ 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.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) continue;
- return { path: resolved, label: path.basename(resolved), kind: ["sh","bash","zsh","py","js","ts"].includes(ext) ? "script" : "file", language: languageFor(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;
}
@@ -62,45 +69,125 @@ function actionCode(event: ReturnType<typeof safeEvent>, artifact: SessionFlowAc
if (artifact && event.detail.includes("\n")) return { kind: artifact.kind === "script" ? "script" : "snippet", language: artifact.language || "text", content: event.detail };
return undefined;
}
-function dominantCategory(actions: SessionFlowAction[]): SessionFlowCategory {
- const counts = new Map<SessionFlowCategory, number>();
- for (const action of actions) counts.set(action.category, (counts.get(action.category) || 0) + 1);
- return [...counts.entries()].sort((a,b) => b[1] - a[1])[0]?.[0] || "other";
+function actionGroupDescriptor(action: SessionFlowAction): { key: string; title: string } {
+ const tool = (action.tool || "").toLowerCase();
+ const detail = (action.detail || "").toLowerCase();
+ if (/fs_read|\bcat\b|sed\s+-n/.test(`${tool} ${detail}`)) return { key: "read", title: "Read files" };
+ if (/fs_search|\brg\b|\bgrep\b|\bfind\b|search/.test(`${tool} ${detail}`)) return { key: "search", title: "Search" };
+ if (/git\s+(status|diff|log|show)|\bstatus\b/.test(detail)) return { key: "status", title: "Status & diff" };
+ if (/vitest|playwright|\btest\b/.test(`${tool} ${detail}`)) return { key: "tests", title: "Run tests" };
+ if (/typecheck|lint|coverage|audit/.test(`${tool} ${detail}`)) return { key: "static", title: "Static checks" };
+ if (/\bbuild\b/.test(`${tool} ${detail}`)) return { key: "build", title: "Build" };
+ if (/fs_write|fs_delete|fs_move|fs_copy|apply_patch|\bpatch\b|\bedit\b/.test(`${tool} ${detail}`)) return { key: "changes", title: "File changes" };
+ if (/git\s+(add|commit|merge|cherry-pick|push|rebase|reset|tag)/.test(detail)) return { key: "git", title: "Git integration" };
+ if (/health(?:check)?/.test(`${tool} ${detail}`)) return { key: "health", title: "Health checks" };
+ if (/deploy|dokploy|systemctl|restart|production|cloudflare/.test(`${tool} ${detail}`)) return { key: "deploy", title: "Deployment" };
+ return { key: action.category, title: TITLES[action.category] };
}
-function summarize(actions: SessionFlowAction[]): string {
- const tools = [...new Set(actions.map((action) => action.tool).filter((tool): tool is string => Boolean(tool)))].slice(0, 3).map(humanize);
- return `${actions.length} action${actions.length === 1 ? "" : "s"}${tools.length ? ` · ${tools.join(" · ")}` : ""}`;
+function actionGroups(actions: SessionFlowAction[], stepRef: string): SessionFlowActionGroup[] {
+ const groups = new Map<string, SessionFlowActionGroup>();
+ for (const action of actions) {
+ const descriptor = actionGroupDescriptor(action);
+ let group = groups.get(descriptor.key);
+ if (!group) {
+ group = { ref: `${stepRef}.G${stableId("g", descriptor.key).slice(-6).toUpperCase()}`, key: descriptor.key, title: descriptor.title, actionRefs: [], count: 0 };
+ groups.set(descriptor.key, group);
+ }
+ group.actionRefs.push(action.ref);
+ group.count += 1;
+ }
+ return [...groups.values()];
+}
+function summarize(actions: SessionFlowAction[], groups: SessionFlowActionGroup[]): string {
+ const labels = groups.slice(0, 3).map((group) => group.count > 1 ? `${group.title} ×${group.count}` : group.title);
+ return `${actions.length} action${actions.length === 1 ? "" : "s"}${labels.length ? ` · ${labels.join(" · ")}` : ""}`;
+}
+function semanticTitle(category: SessionFlowCategory, groups: SessionFlowActionGroup[]): string {
+ if (!groups.length) return TITLES[category];
+ const informative = groups.filter((group) => group.key !== category).slice(0, 2).map((group) => group.title);
+ return informative.length ? `${TITLES[category]} · ${informative.join(" + ")}` : TITLES[category];
}
-export function semanticSessionFlow(events: AgentSessionEvent[], requestedLimit = SESSION_GRAPH_EVENT_LIMIT, cwd?: string) {
- const limit = Math.max(1, Math.min(SESSION_GRAPH_EVENT_LIMIT, Math.trunc(requestedLimit) || SESSION_GRAPH_EVENT_LIMIT));
- const totalEvents = events.length, omittedEvents = Math.max(0, totalEvents - limit);
- const actions = events.slice(-limit).map(safeEvent).map((event, index): SessionFlowAction => {
- const artifact = artifactPath(event.detail, cwd), category = classify(event);
- return { ref: "", eventRef: `E${omittedEvents + index + 1}`, title: actionTitle(event), category, at: event.at, kind: event.kind,
- ...(event.tool ? { tool: event.tool } : {}), ...(event.state ? { state: event.state } : {}), ...(event.detail ? { detail: event.detail } : {}),
- terminalContext: Boolean(event.tool && /^(exec(?:_|\.)|terminal|shell)/i.test(event.tool)), ...(artifact ? { artifact } : {}),
- ...(actionCode(event, artifact) ? { code: actionCode(event, artifact) } : {}),
+function buildActions(events: AgentSessionEvent[], cwd?: string, rawBase = 0): SessionFlowAction[] {
+ const normalized = normalizeSessionEventSemantics(events);
+ const base = eventSequenceBase(rawBase);
+ return normalized.map((row, index) => {
+ const event = safeEvent(row);
+ const 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 action: SessionFlowAction = {
+ id: stableId("action", `${eventRef}\0${ref}\0${event.at}\0${event.kind}\0${event.tool || ""}`),
+ ref,
+ eventRef,
+ title: actionTitle(event),
+ category: semantic.category,
+ at: event.at,
+ kind: event.kind,
+ ...(event.tool ? { tool: event.tool } : {}),
+ ...(event.state ? { state: event.state } : {}),
+ ...(event.detail ? { detail: event.detail } : {}),
+ terminalContext: Boolean(event.tool && /^(exec(?:_|\.)|terminal|shell)/i.test(event.tool)),
+ ...(artifact ? { artifact } : {}),
};
+ const code = actionCode(event, artifact);
+ return code ? { ...action, code } : action;
});
- let groups: SessionFlowAction[][] = [];
+}
+function stepFromActions(actions: SessionFlowAction[]): SessionFlowStep {
+ const first = actions[0]!;
+ const ref = first.ref.split(".A", 1)[0]!;
+ const groups = actionGroups(actions, ref);
+ return {
+ id: stableId("step", ref),
+ ref,
+ title: semanticTitle(first.category, groups),
+ category: first.category,
+ summary: summarize(actions, groups),
+ startedAt: first.at,
+ finishedAt: actions.at(-1)!.at,
+ groups,
+ actions,
+ };
+}
+function stepsFromActions(actions: SessionFlowAction[]): SessionFlowStep[] {
+ const groups: SessionFlowAction[][] = [];
for (const action of actions) {
+ const stepRef = action.ref.split(".A", 1)[0];
const last = groups.at(-1);
- if (last && last.at(-1)?.category === action.category) last.push(action); else groups.push([action]);
- }
- while (groups.length > STEP_LIMIT) {
- let smallest = 0;
- for (let i = 1; i < groups.length; i += 1) if (groups[i]!.length < groups[smallest]!.length) smallest = i;
- const target = smallest === 0 ? 1 : smallest === groups.length - 1 ? smallest - 1 : groups[smallest - 1]!.length <= groups[smallest + 1]!.length ? smallest - 1 : smallest + 1;
- const start = Math.min(smallest, target), merged = [...groups[start]!, ...groups[start + 1]!];
- groups.splice(start, 2, merged);
+ if (last && last[0]!.ref.startsWith(`${stepRef}.A`)) last.push(action);
+ else groups.push([action]);
}
- const steps: SessionFlowStep[] = groups.map((group, stepIndex) => {
- const ref = `S${stepIndex + 1}`, category = dominantCategory(group);
- const categories = [...new Set(group.map((action) => action.category))];
- group.forEach((action, actionIndex) => { action.ref = `${ref}.A${actionIndex + 1}`; });
- return { ref, title: categories.length === 1 ? TITLES[category] : categories.slice(0, 2).map((item) => TITLES[item]).join(" & "), category,
- summary: summarize(group), startedAt: group[0]!.at, finishedAt: group.at(-1)!.at, actions: group };
- });
- return { totalEvents, shownEvents: actions.length, omittedEvents, steps };
+ return groups.map(stepFromActions);
+}
+
+export function semanticSessionFlow(events: AgentSessionEvent[], requestedLimit = SESSION_GRAPH_EVENT_LIMIT, cwd?: string, rawBase = 0) {
+ const limit = Math.max(1, Math.min(SESSION_GRAPH_EVENT_LIMIT, Math.trunc(requestedLimit) || SESSION_GRAPH_EVENT_LIMIT));
+ const base = eventSequenceBase(rawBase);
+ const allActions = buildActions(events, cwd, base);
+ const windowActions = allActions.slice(-limit);
+ const windowSteps = stepsFromActions(windowActions);
+ const steps = windowSteps.slice(-STEP_LIMIT);
+ const shownEvents = steps.reduce((sum, step) => sum + step.actions.length, 0);
+ const totalEvents = base + events.length;
+ return { totalEvents, shownEvents, omittedEvents: Math.max(0, totalEvents - shownEvents), steps };
+}
+
+export function resolveSessionFlowAction(events: AgentSessionEvent[], actionRef: string, cwd?: string, rawBase = 0): SessionFlowActionResolution | null {
+ const actions = buildActions(events, cwd, rawBase);
+ const wanted = actionRef.trim();
+ if (!wanted) return null;
+ const upper = wanted.toUpperCase();
+ const index = actions.findIndex((action) => action.ref.toUpperCase() === upper || action.eventRef.toUpperCase() === upper || action.id === wanted);
+ if (index < 0) return null;
+ const action = actions[index]!;
+ const stepRef = action.ref.split(".A", 1)[0]!;
+ const stepActions = actions.filter((row) => row.ref.startsWith(`${stepRef}.A`));
+ return {
+ step: stepFromActions(stepActions),
+ action,
+ ...(actions[index - 1] ? { beforeRef: actions[index - 1]!.ref } : {}),
+ ...(actions[index + 1] ? { afterRef: actions[index + 1]!.ref } : {}),
+ };
}
diff --git a/lib/agent/session-graph.ts b/lib/agent/session-graph.ts
index 79f37e1e..99d54c02 100644
--- a/lib/agent/session-graph.ts
+++ b/lib/agent/session-graph.ts
@@ -5,7 +5,7 @@ import type { AgentSession } from "./session-types";
import { semanticSessionFlow } from "./session-flow";
export function sessionGraph(record: AgentSession, session: SessionCard, requestedLimit = SESSION_GRAPH_EVENT_LIMIT): SessionGraphView {
- const flow = semanticSessionFlow(record.events, requestedLimit, session.cwd);
+ const flow = semanticSessionFlow(record.events, requestedLimit, session.cwd, record.eventSeqBase);
const root: WorkflowGraphNode = {
id: "session-root", name: session.label, type: "session", position: { x: 60, y: 90 },
config: { sessionRoot: true, label: session.label, source: session.source, status: session.status, title: session.title, ...(session.cwd ? { cwd: session.cwd } : {}), stepCount: flow.steps.length },
diff --git a/lib/agent/session-mutations.ts b/lib/agent/session-mutations.ts
index a0dc8cca..955f5b58 100644
--- a/lib/agent/session-mutations.ts
+++ b/lib/agent/session-mutations.ts
@@ -3,6 +3,8 @@ import { redactText } from "@/lib/security/redact-text";
import { listSessionRecords, principalHash, sessionLockTarget, sessionNameLockTarget, writeSessionFile } from "./session-files";
import { requireAgentSessionName } from "./session-name";
import { autoSessionTitle, estimateTokens, MAX_EVENTS, MAX_HISTORY, safeTitle } from "./session-policy";
+import { retainSessionEvents } from "./session-sequence";
+import { appendSemanticSessionEvent } from "./session-semantic";
import { compactIfNeeded, requireOwned } from "./session-record";
import type { AgentSession, AgentSessionEvent, AgentSessionTitleSource } from "./session-types";
@@ -121,7 +123,9 @@ export async function appendAgentSessionEvent(
}
: {}),
};
- record.events = [...record.events, row].slice(-MAX_EVENTS);
+ const retained = retainSessionEvents(appendSemanticSessionEvent(record.events, row), record.eventSeqBase, MAX_EVENTS);
+ record.events = retained.events;
+ record.eventSeqBase = retained.eventSeqBase;
record.updatedAt = at;
record.lifetimeEstimatedTokens += estimateTokens(row);
record = await compactIfNeeded(record, "event-threshold");
diff --git a/lib/agent/session-policy.ts b/lib/agent/session-policy.ts
index 24e7cf68..cc39c2bd 100644
--- a/lib/agent/session-policy.ts
+++ b/lib/agent/session-policy.ts
@@ -1,6 +1,8 @@
import { createHash } from "node:crypto";
import { redactText } from "@/lib/security/redact-text";
import type { AgentSession, AgentSessionEvent, AgentSessionTitleSource } from "./session-types";
+import { retainSessionEvents } from "./session-sequence";
+import { appendSemanticSessionEvent } from "./session-semantic";
export const MAX_HISTORY = 4096;
export const MAX_EVENTS = 400;
@@ -98,11 +100,13 @@ export function compactSessionContext(record: AgentSession, at: string): AgentSe
if (used >= target) break;
}
const event: AgentSessionEvent = { at, kind: "compacted", detail: `context exceeded ${record.compactThresholdTokens} estimated tokens` };
+ const retained = retainSessionEvents(appendSemanticSessionEvent(record.events, event), record.eventSeqBase, MAX_EVENTS);
const next: AgentSession = {
...record,
contextSummary: summaryFrom(record, at),
history: kept.slice(-MAX_HISTORY),
- events: [...record.events.slice(-(MAX_EVENTS - 1)), event],
+ events: retained.events,
+ eventSeqBase: retained.eventSeqBase,
compactionCount: record.compactionCount + 1,
lastCompactedAt: at,
updatedAt: at,
diff --git a/lib/agent/session-record.ts b/lib/agent/session-record.ts
index eaba785d..77caf7b5 100644
--- a/lib/agent/session-record.ts
+++ b/lib/agent/session-record.ts
@@ -2,6 +2,8 @@ import { artifactLocation } from "./artifact-paths";
import { archiveAgentSession, pruneAgentSessionArchives } from "./session-archive";
import { principalHash, readSessionFile } from "./session-files";
import { compactSessionContext, MAX_EVENTS, sessionContextTokens } from "./session-policy";
+import { retainSessionEvents } from "./session-sequence";
+import { appendSemanticSessionEvent } from "./session-semantic";
import type { AgentSession, AgentSessionEvent, AgentSessionSummary } from "./session-types";
import { agentSessionLabel } from "./session-name";
@@ -49,9 +51,11 @@ export async function compactIfNeeded(
kind: "archived",
detail: `${reason}; 30-day retention`,
};
+ const retained = retainSessionEvents(appendSemanticSessionEvent(next.events, archived), next.eventSeqBase, MAX_EVENTS);
next = {
...next,
- events: [...next.events.slice(-(MAX_EVENTS - 1)), archived],
+ events: retained.events,
+ eventSeqBase: retained.eventSeqBase,
archiveCount: record.archiveCount + 1,
lastArchivedAt: now.toISOString(),
};
diff --git a/lib/agent/session-semantic.ts b/lib/agent/session-semantic.ts
new file mode 100644
index 00000000..4437256e
--- /dev/null
+++ b/lib/agent/session-semantic.ts
@@ -0,0 +1,53 @@
+import type { SessionFlowCategory } from "@/lib/contracts/session-monitor";
+import type { AgentSessionEvent, AgentSessionEventSemantic } from "./session-types";
+
+const CATEGORIES = new Set<SessionFlowCategory>([
+ "context", "plan", "inspect", "implement", "verify", "integrate", "deploy", "result", "other",
+]);
+
+export function classifySessionEvent(event: Pick<AgentSessionEvent, "kind" | "tool" | "detail">): SessionFlowCategory {
+ const tool = (event.tool || "").toLowerCase();
+ const detail = (event.detail || "").toLowerCase();
+ const hay = `${tool} ${detail}`;
+ if (["created", "resumed", "compacted"].includes(event.kind)) return "context";
+ if (event.kind === "archived" || /workflow_(finish|cancel)/.test(tool)) return "result";
+ if (/workflow_start/.test(tool) || (/\b(plan|intent|scope|approach)\b/.test(detail) && event.kind === "note")) return "plan";
+ if (/\b(deploy|dokploy|systemctl|restart|health(?:check)?|production|cloudflare)\b/.test(hay)) return "deploy";
+ if (/\bgit\s+(add|commit|merge|cherry-pick|push|rebase|reset|tag)\b/.test(detail) || /\b(pull request|\bpr\b)\b/.test(hay)) return "integrate";
+ if (/\b(test|vitest|playwright|lint|typecheck|coverage|audit|verify|verification|check|build)\b/.test(hay)) return "verify";
+ if (/\b(fs_write|fs_delete|fs_move|fs_copy|apply_patch|patch|edit|update|create|save|write)\b/.test(tool) || /\b(sed\s+-i|perl\s+-pi|mkdir|rm\s+-|cp\s+|mv\s+|cat\s+>|tee\s+)\b/.test(detail)) return "implement";
+ if (/\b(fs_read|fs_list|fs_search|read|search|list|query|inspect|status|find)\b/.test(tool) || /^(git\s+(status|diff|log|show)|rg\b|grep\b|find\b|ls\b|cat\b|sed\s+-n)/.test(detail)) return "inspect";
+ if (event.kind === "note") return "context";
+ if (event.kind === "workflow") return "plan";
+ return "other";
+}
+
+function validSemantic(value: AgentSessionEvent["semantic"]): value is AgentSessionEventSemantic {
+ return Boolean(value && value.version === 1 && Number.isSafeInteger(value.step) && value.step > 0 && Number.isSafeInteger(value.action) && value.action > 0 && CATEGORIES.has(value.category));
+}
+
+function nextSemantic(last: AgentSessionEventSemantic | undefined, category: SessionFlowCategory): AgentSessionEventSemantic {
+ if (last?.category === category) return { version: 1, step: last.step, action: last.action + 1, category };
+ return { version: 1, step: (last?.step || 0) + 1, action: 1, category };
+}
+
+/** Backfill only missing legacy metadata. Persisted semantic refs remain authoritative even if classifiers evolve. */
+export function normalizeSessionEventSemantics(events: AgentSessionEvent[]): AgentSessionEvent[] {
+ let last: AgentSessionEventSemantic | undefined;
+ return events.map((event) => {
+ if (validSemantic(event.semantic)) {
+ last = event.semantic;
+ return event;
+ }
+ const semantic = nextSemantic(last, classifySessionEvent(event));
+ last = semantic;
+ return { ...event, semantic };
+ });
+}
+
+export function appendSemanticSessionEvent(events: AgentSessionEvent[], event: AgentSessionEvent): AgentSessionEvent[] {
+ const normalized = normalizeSessionEventSemantics(events);
+ const last = normalized.at(-1)?.semantic;
+ const semantic = nextSemantic(validSemantic(last) ? last : undefined, classifySessionEvent(event));
+ return [...normalized, { ...event, semantic }];
+}
diff --git a/lib/agent/session-sequence.test.ts b/lib/agent/session-sequence.test.ts
new file mode 100644
index 00000000..02aaaf14
--- /dev/null
+++ b/lib/agent/session-sequence.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { eventSequenceBase, retainSessionEvents } from "./session-sequence";
+import type { AgentSessionEvent } from "./session-types";
+
+const events = (count: number): AgentSessionEvent[] => Array.from({ length: count }, (_, index) => ({ at: String(index), kind: "tool", tool: "fs_read" }));
+
+describe("persisted event sequence", () => {
+ it("normalizes legacy and malformed metadata without inventing lost history", () => {
+ for (const value of [undefined, null, -1, 1.5, NaN, Infinity, "400"]) expect(eventSequenceBase(value)).toBe(0);
+ expect(eventSequenceBase(400)).toBe(400);
+ });
+ it("advances at MAX_EVENTS rotation without shifting retained global event numbers", () => {
+ const original = events(400);
+ const next = retainSessionEvents([...original, { at: "400", kind: "note" }], 0, 400);
+ expect(next.eventSeqBase).toBe(1);
+ expect(next.events[0]).toBe(original[1]);
+ expect(next.eventSeqBase + next.events.indexOf(original[399]!) + 1).toBe(400);
+ expect(retainSessionEvents(next.events, next.eventSeqBase, 400)).toEqual(next);
+ });
+ it("preserves sequence through legacy oversize migration and compaction/archive appends", () => {
+ let record = retainSessionEvents(events(450), undefined, 400);
+ expect(record.eventSeqBase).toBe(50);
+ for (const kind of ["compacted", "archived"] as const) {
+ record = retainSessionEvents([...record.events, { at: kind, kind }], record.eventSeqBase, 400);
+ }
+ expect(record.eventSeqBase).toBe(52);
+ expect(record.events.at(-2)?.kind).toBe("compacted");
+ expect(record.events.at(-1)?.kind).toBe("archived");
+ });
+});
diff --git a/lib/agent/session-sequence.ts b/lib/agent/session-sequence.ts
new file mode 100644
index 00000000..c59bf91e
--- /dev/null
+++ b/lib/agent/session-sequence.ts
@@ -0,0 +1,12 @@
+import type { AgentSessionEvent } from "./session-types";
+
+/** Legacy ledgers start a new known sequence at zero; lost history is not guessed. */
+export function eventSequenceBase(value: unknown): number {
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
+}
+
+/** Keep a suffix of the raw ledger and advance its persisted global offset exactly once. */
+export function retainSessionEvents(events: AgentSessionEvent[], eventSeqBase: unknown, limit: number) {
+ const dropped = Math.max(0, events.length - Math.max(0, Math.trunc(limit)));
+ return { events: events.slice(dropped), eventSeqBase: eventSequenceBase(eventSeqBase) + dropped };
+}
diff --git a/lib/agent/session-types.ts b/lib/agent/session-types.ts
index f106f84c..d6290bcd 100644
--- a/lib/agent/session-types.ts
+++ b/lib/agent/session-types.ts
@@ -1,9 +1,17 @@
import type { artifactLocation } from "./artifact-paths";
import type { AgentMemorySnapshot } from "./memory-store";
+import type { SessionFlowCategory } from "@/lib/contracts/session-monitor";
export type AgentSessionSource = "cli" | "mcp" | "alfa";
export type AgentSessionTitleSource = "default" | "auto" | "manual";
+export interface AgentSessionEventSemantic {
+ version: 1;
+ step: number;
+ action: number;
+ category: SessionFlowCategory;
+}
+
export interface AgentSessionEvent {
at: string;
kind:
@@ -18,6 +26,8 @@ export interface AgentSessionEvent {
state?: string;
workflowId?: string;
detail?: string;
+ /** Durable semantic index metadata. Raw execution fields above remain the source of truth. */
+ semantic?: AgentSessionEventSemantic;
}
export interface AgentSession {
@@ -37,6 +47,8 @@ export interface AgentSession {
contextSummary?: string;
history: unknown[];
events: AgentSessionEvent[];
+ /** Count of events dropped before the first retained event. Legacy sessions normalize to zero. */
+ eventSeqBase?: number;
estimatedTokens: number;
lifetimeEstimatedTokens: number;
compactThresholdTokens: number;
diff --git a/lib/contracts/session-monitor.ts b/lib/contracts/session-monitor.ts
index 396b750c..4a665b86 100644
--- a/lib/contracts/session-monitor.ts
+++ b/lib/contracts/session-monitor.ts
@@ -48,7 +48,18 @@ export interface SessionDetail {
}
export type SessionFlowCategory = "context" | "plan" | "inspect" | "implement" | "verify" | "integrate" | "deploy" | "result" | "other";
+export interface SessionFlowArtifact {
+ ref: string;
+ revisionRef: string;
+ path: string;
+ relativePath: string;
+ label: string;
+ kind: "file" | "script";
+ language?: string;
+}
export interface SessionFlowAction {
+ /** Opaque durable identity scoped to the session. Not rendered as the human reference. */
+ id: string;
ref: string;
eventRef: string;
title: string;
@@ -60,17 +71,33 @@ export interface SessionFlowAction {
detail?: string;
terminalContext?: boolean;
code?: { kind: "command" | "script" | "snippet"; language: string; content: string };
- artifact?: { path: string; label: string; kind: "file" | "script"; language?: string };
+ artifact?: SessionFlowArtifact;
+}
+export interface SessionFlowActionGroup {
+ ref: string;
+ key: string;
+ title: string;
+ actionRefs: string[];
+ count: number;
}
export interface SessionFlowStep {
+ /** Opaque durable identity scoped to the session. */
+ id: string;
ref: string;
title: string;
category: SessionFlowCategory;
summary: string;
startedAt: string;
finishedAt: string;
+ groups: SessionFlowActionGroup[];
actions: SessionFlowAction[];
}
+export interface SessionFlowActionResolution {
+ step: SessionFlowStep;
+ action: SessionFlowAction;
+ beforeRef?: string;
+ afterRef?: string;
+}
export interface SessionGraphView {
session: SessionCard;
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index 7b03c888..57115aa2 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -56,6 +56,7 @@ const MCP_ONLY: Record<string, string> = {
"project.script.run": "RASMIC script replay is an external/terminal orchestration primitive that revalidates bounded read-only steps and may promote candidate metadata; Alfa has no matching workflow/script lifecycle",
"agent.session.current": "external MCP clients need a stable durable MSO session id they can quote from a later ChatGPT conversation; in-shell Alfa already owns its conversation identity",
"agent.session.flow": "semantic flow lookup reads the external durable AgentSession ledger used by MCP/terminal agents; Alfa browser threads intentionally keep a separate conversation identity, while the owner can inspect the same projection in the native Workflows Sessions UI",
+ "agent.session.action.resolve": "stable semantic action resolution belongs to the same external durable AgentSession ledger and preserves owner isolation; Alfa browser threads keep their separate conversation identity",
"agent.sessions.list": "external MCP clients need explicit cross-conversation session discovery; Alfa's in-app thread UI already provides its own conversation list",
"agent.session.resume": "external MCP clients must reconstruct only the safe MSO resume packet across ChatGPT conversations; Alfa can reopen its own persisted in-app thread directly",
"agent.session.rename": "durable MCP/terminal session titles are metadata in the isolated agent-session store; Alfa keeps its separate in-app thread/title lifecycle",
diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.ts
index 00de4e6d..6f59df23 100644
--- a/lib/mcp/tool-contract.ts
+++ b/lib/mcp/tool-contract.ts
@@ -46,7 +46,7 @@ const TITLES: Record<string, string> = {
project_mcp_tools: "List Project MCP Tools", project_mcp_call: "Call Project MCP Tool", project_function_call: "Call Project Function",
read_pipeline: "Run Read Pipeline", fs_list: "List Files", fs_read: "Read File", fs_search: "Search Directories", fs_write: "Write File",
exec_run: "Run Command", exec_job_start: "Start Command Job", exec_job_status: "Command Job Status", exec_job_cancel: "Cancel Command Job",
- agent_session_current: "Current Agent Session", agent_session_flow: "Read Session Flow", agent_session_rename: "Rename Agent Session",
+ agent_session_current: "Current Agent Session", agent_session_flow: "Read Session Flow", agent_session_action_resolve: "Resolve Session Action", agent_session_rename: "Rename Agent Session",
local_agents_list: "List Local Agents", local_agent_inbox: "Receive Local Agent Messages",
organization_chart: "Organization Chart", organization_manage: "Manage Organization",
local_agent_message_send: "Send Local Agent Message", local_agent_reply: "Reply to Local Agent", local_agent_request_wait: "Wait for Local Agent Reply",
@@ -110,7 +110,7 @@ function compactSchema(value: unknown): unknown {
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
if (key === "additionalProperties" && item === true || key === "required" && Array.isArray(item) && item.length === 0) continue;
if (key === "workflow_id" && item && typeof item === "object") out[key] = { type:"string" };
- else if (key === "description" && typeof item === "string") out[key] = compactText(item, 32);
+ else if (key === "description" && typeof item === "string") out[key] = compactText(item, 28);
else out[key] = compactSchema(item);
}
return out;
@@ -124,7 +124,7 @@ export function toolDescriptor(tool: McpTool, profile: McpToolProfile = "full")
return {
name: tool.name,
title: tool.title ?? toolTitle(tool.name),
- description: compact ? compactText(tool.chatgptDescription ?? tool.description, 72) : tool.description,
+ description: compact ? compactText(tool.chatgptDescription ?? tool.description, 64) : tool.description,
inputSchema: compact ? compactSchema(tool.inputSchema) : tool.inputSchema,
...(outputSchema ? { outputSchema: compact ? compactSchema(outputSchema) : outputSchema } : {}),
securitySchemes,
diff --git a/lib/mcp/tools-agent.test.ts b/lib/mcp/tools-agent.test.ts
index 0c45519f..8edc8d86 100644
--- a/lib/mcp/tools-agent.test.ts
+++ b/lib/mcp/tools-agent.test.ts
@@ -5,7 +5,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;
-afterAll(async () => { delete process.env.OS_AGENT_MEMORY_DIR; await fs.rm(root, { recursive: true, force: true }); });
+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 }); });
vi.resetModules();
const { AGENT_TOOLS } = await import("./tools-agent");
@@ -33,3 +34,24 @@ describe("typed MCP agent memory tools", () => {
expect(() => tool("agent_memory_remember").run({ document: "MEMORY.md", key: "x", value: "y", kind: "graph" }, context)).toThrow(/kind must be one of/);
});
});
+
+
+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" });
+ 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 };
+ const flow = await tool("agent_session_flow").run({ session_ref: `@${session.name}` }, context) as { steps: Array<{ actions: Array<{ ref: string; tool?: string }> }> };
+ const actionRef = flow.steps.flatMap((step) => step.actions).find((action) => action.tool === "fs_read")?.ref;
+ expect(actionRef).toMatch(/^S\d+\.A\d+$/);
+ const resolved = await tool("agent_session_action_resolve").run({ session_ref: `@${session.name}`, action_ref: actionRef }, context);
+ const body = JSON.stringify(resolved);
+ expect(body).not.toContain(session.id);
+ expect(body).not.toContain("secret-value");
+ expect(body).toContain("[redacted]");
+ 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.ts
index fc8dd27c..bd73c55c 100644
--- a/lib/mcp/tools-agent.ts
+++ b/lib/mcp/tools-agent.ts
@@ -4,7 +4,7 @@ import { agentSessionSummary, appendAgentSessionEvent, getAgentSession, listAgen
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 { resolveSessionFlowAction, semanticSessionFlow } from "@/lib/agent/session-flow";
function principal(context: { principal?: string }): string {
if (!context.principal) throw new Error("agent session principal is unavailable");
@@ -69,19 +69,35 @@ export const AGENT_TOOLS: McpTool[] = [
}, ["session_ref"]),
run: async (a, context) => {
const owner = principal(context), target = await resolveAgentSessionRef(owner, str(a, "session_ref"));
- const flow = semanticSessionFlow(target.events, Math.max(1, Math.min(120, Number(a.limit) || 120)), target.cwd);
+ const flow = semanticSessionFlow(target.events, Math.max(1, Math.min(120, Number(a.limit) || 120)), target.cwd, target.eventSeqBase);
const session = { label: agentSessionLabel(target.name, target.title, target.cwd), title: target.title, source: target.source, updatedAt: target.updatedAt, ...(target.cwd ? { cwd: target.cwd } : {}) };
- const wanted = optionalString(a, "action_ref")?.toUpperCase();
+ const wanted = optionalString(a, "action_ref");
if (wanted) {
- for (const step of flow.steps) {
- const action = step.actions.find((row) => row.ref.toUpperCase() === wanted || row.eventRef.toUpperCase() === wanted);
- if (action) return { session, step: { ref: step.ref, title: step.title, category: step.category, summary: step.summary }, action };
- }
- throw new Error(`session action not found: ${wanted}`);
+ const resolved = resolveSessionFlowAction(target.events, wanted, target.cwd, target.eventSeqBase);
+ if (!resolved) throw new Error(`session action not found: ${wanted.toUpperCase()}`);
+ return { session, ...resolved };
}
return { session, ...flow };
},
},
+ {
+ name: "agent_session_action_resolve",
+ description: "Resolve one stable human session action reference such as S3.A4 (or E217) to its exact sanitized semantic step/action receipt. The lookup is owner-scoped and never exposes the internal session id.",
+ 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." },
+ 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." },
+ }, ["session_ref", "action_ref"]),
+ run: async (a, context) => {
+ const owner = principal(context), target = await resolveAgentSessionRef(owner, str(a, "session_ref"));
+ const resolved = resolveSessionFlowAction(target.events, str(a, "action_ref"), target.cwd, target.eventSeqBase);
+ 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,
+ };
+ },
+ },
{
name: "agent_session_rename",
description: "Manually rename the current MSO session. Manual names are locked and will not be replaced by automatic workflow-based naming.",
diff --git a/scripts/e2e/mcp-sessions.mjs b/scripts/e2e/mcp-sessions.mjs
index 4b44d5d0..c00e3924 100644
--- a/scripts/e2e/mcp-sessions.mjs
+++ b/scripts/e2e/mcp-sessions.mjs
@@ -74,9 +74,12 @@ 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("Actions", { exact: true }).last()).toBeVisible();
+ await expect(page.getByText("Action groups", { exact: true }).last()).toBeVisible();
expect(await terminalTabs.count()).toBe(terminalCountBefore); // Selecting a node must not launch tools.
const terminalAction = terminalStep.actions.find(action => action.terminalContext);
+ const terminalGroup = terminalStep.groups.find(group => group.actionRefs.includes(terminalAction.ref));
+ expect(terminalGroup).toBeTruthy();
+ await page.locator(`details[data-slot="session-action-group"][data-action-group-ref="${terminalGroup.ref}"] > summary`).click();
await page.locator(`details[data-slot="session-action"][data-action-ref="${terminalAction.ref}"] > summary`).click();
await expect(page.getByRole("button", { name: /Open terminal here/ }).first()).toBeVisible();
expect(await terminalTabs.count()).toBe(terminalCountBefore); // Inspecting an action is still read-only.