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.

fix(memory): persist workflow and organization actions

Rahman0785928e0443
diff --git a/.gitleaksignore b/.gitleaksignore
index f9819a16..ac175d7b 100644
--- a/.gitleaksignore
+++ b/.gitleaksignore
@@ -19,3 +19,8 @@ db292708a0ce5554a1a265091a65fb6a19636538:lib/infra/portable/ui.ts:generic-api-ke
# No provider requests; scoped to the original commit, exact file, rule and line.
9d3eb899b80a3d3ace1766a65e3b154fd029d7a3:lib/infra/sc-sync.test.ts:generic-api-key:4
9d3eb899b80a3d3ace1766a65e3b154fd029d7a3:lib/infra/sc-sync.test.ts:generic-api-key:15
+
+# Reviewed earlier SC-sync unit-test fixture revision: deterministic synthetic strings only,
+# all provider calls mocked/in-memory. Exact historical fingerprints, not path/rule suppression.
+2c0723d5df847fa3e4f4e0a2b966cfae052e7c71:lib/infra/sc-sync.test.ts:generic-api-key:4
+2c0723d5df847fa3e4f4e0a2b966cfae052e7c71:lib/infra/sc-sync.test.ts:generic-api-key:15
diff --git a/app/api/v1/agent-sessions/route.ts b/app/api/v1/agent-sessions/route.ts
index 8740fe72..f291ab37 100644
--- a/app/api/v1/agent-sessions/route.ts
+++ b/app/api/v1/agent-sessions/route.ts
@@ -185,7 +185,7 @@ export async function POST(req: NextRequest) {
const context = await getSessionContext();
if (!context?.session.device_id || context.role !== "owner") return NextResponse.json({ error: "owner_role_required" }, { status: 403 });
const definition = sessionWorkflowDraftDefinition(source, body.step_ref);
- const graph = await createWorkflowGraph(`web:${context.session.device_id}`, definition, "create");
+ const graph = await createWorkflowGraph(`web:${context.session.device_id}`, definition, "create", { remember: true });
return NextResponse.json({ graph }, { headers: { "Cache-Control": "private, no-store" } });
}
if (body.action === "prune-archives")
diff --git a/app/api/v1/organization/route.ts b/app/api/v1/organization/route.ts
index 06935ba1..e4070084 100644
--- a/app/api/v1/organization/route.ts
+++ b/app/api/v1/organization/route.ts
@@ -34,7 +34,7 @@ export async function POST(req: NextRequest) {
else if (action === "seat_upsert") chart = await upsertOrganizationSeat(revision, body.seat as Record<string, unknown>);
else if (action === "unit_delete") chart = await deleteOrganizationUnit(revision, String(body.id || ""));
else if (action === "seat_delete") chart = await deleteOrganizationSeat(revision, String(body.id || ""));
- else if (isOrganizationFlowAction(action)) chart = await mutateOrganizationFlow(revision, action, (body.data ?? {}) as Record<string, unknown>);
+ else if (isOrganizationFlowAction(action)) chart = await mutateOrganizationFlow(revision, action, (body.data ?? {}) as Record<string, unknown>, { principal: session.principal });
else if (action === "replace") { if (!roleAtLeast(session.context.role, "owner")) return fail("owner_required", 403); chart = await replaceOrganization(revision, body.chart as never); }
else throw new Error("unknown organization action");
void audit({ action: "agent.organization", actor: session.context.session.device_id, target: action, detail: `organization ${action}` });
diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.ts
index 4a30ef12..836231f7 100644
--- a/app/api/v1/workflows/route.ts
+++ b/app/api/v1/workflows/route.ts
@@ -49,12 +49,12 @@ export async function GET(req:NextRequest){const q=req.nextUrl.searchParams,mini
const graphs=await listWorkflowGraphs(session.principal),query=q.get("q")??"",filters={tag:q.get("tag")||undefined,status:q.get("status")||undefined,project:q.get("project")||undefined,folder:q.get("folder")||undefined,node:q.get("node")||undefined}; return NextResponse.json({graphs:graphs.filter((graph)=>workflowMatchesQuery(graph,query,filters))},{headers});
}catch(error){return fail(error);}}
export async function POST(req:NextRequest){const session=await auth("operator");if(!session)return fail("operator_required",403);try{const body=await readSetupJson(req),action=typeof body.action==="string"?body.action:"";if(rateLimited(`workflow:${action}:${session.context.session.device_id}`,action==="run"?60:30,60_000))return fail("rate_limited",429);
- if(action==="create")return NextResponse.json({graph:await createWorkflowGraph(session.principal,body.graph)},{headers});
- if(action==="update")return NextResponse.json({graph:await updateWorkflowGraph(session.principal,String(body.graph_id??""),String(body.expected_revision??""),body.graph)},{headers});
+ if(action==="create")return NextResponse.json({graph:await createWorkflowGraph(session.principal,body.graph,"create",{remember:true})},{headers});
+ if(action==="update")return NextResponse.json({graph:await updateWorkflowGraph(session.principal,String(body.graph_id??""),String(body.expected_revision??""),body.graph,"update",{remember:true})},{headers});
if(action==="delete")return NextResponse.json(await deleteWorkflowGraph(session.principal,String(body.graph_id??""),String(body.expected_revision??"")),{headers});
- if(action==="clone")return NextResponse.json({graph:await cloneWorkflowGraph(session.principal,String(body.graph_id??""))},{headers});
- if(action==="create_from_template"){const row=workflowTemplate(String(body.template_id??""));if(!row)throw new Error("workflow template not found");return NextResponse.json({graph:await createWorkflowGraph(session.principal,row.definition,"template")},{headers});}
- if(action==="restore_version"){const id=String(body.graph_id??""),snapshot=await readWorkflowGraphVersion(workflowGraphOwner(session.principal),id,String(body.revision??""));if(!snapshot)throw new Error("workflow version not found");return NextResponse.json({graph:await updateWorkflowGraph(session.principal,id,String(body.expected_revision??""),definition(snapshot.graph),"restore")},{headers});}
+ if(action==="clone")return NextResponse.json({graph:await cloneWorkflowGraph(session.principal,String(body.graph_id??""),{remember:true})},{headers});
+ if(action==="create_from_template"){const row=workflowTemplate(String(body.template_id??""));if(!row)throw new Error("workflow template not found");return NextResponse.json({graph:await createWorkflowGraph(session.principal,row.definition,"template",{remember:true})},{headers});}
+ if(action==="restore_version"){const id=String(body.graph_id??""),snapshot=await readWorkflowGraphVersion(workflowGraphOwner(session.principal),id,String(body.revision??""));if(!snapshot)throw new Error("workflow version not found");return NextResponse.json({graph:await updateWorkflowGraph(session.principal,id,String(body.expected_revision??""),definition(snapshot.graph),"restore",{remember:true})},{headers});}
if(action==="variable_set"||action==="variable_delete"){if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);return NextResponse.json(action==="variable_set"?await setWorkflowVariable(session.principal,String(body.key??""),body.value,body.secret===true):await deleteWorkflowVariable(session.principal,String(body.key??"")),{headers});}
if(action==="ai_suggest"){if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);return NextResponse.json({definition:await suggestWorkflowGraph(String(body.prompt??""))},{headers});}
if(action==="run"){const graph=await getWorkflowGraph(session.principal,String(body.graph_id??""));if(!graph)throw new Error("workflow graph not found");const agentSession=await createAgentSession(session.principal,"cli",{title:`Workflow: ${graph.name}`,titleSource:"auto"}),context={principal:session.principal,actor:session.principal,sessionId:agentSession.id,scope:maxScope(),capabilities:msoCapabilityRuntime} as const;return NextResponse.json(await startWorkflowGraph(graph,body.input??{},String(body.idempotency_key??`${Date.now()}`),context,(name)=>TOOLS_BY_NAME.get(name)),{headers});}
diff --git a/docs/COGNITIVE-RUNTIME.md b/docs/COGNITIVE-RUNTIME.md
index 22a0b5a9..381f1253 100644
--- a/docs/COGNITIVE-RUNTIME.md
+++ b/docs/COGNITIVE-RUNTIME.md
@@ -175,6 +175,22 @@ agnostic; no paper implementation is a runtime dependency.
lexical cases, 4/4 stable-core/JIT cases and 3/3 bounded two-hop relationship cases must pass. Graph or
vector storage remains evidence-gated.
+### Memory write triggers
+
+Persistent memory changes only on explicit or verified mutation boundaries, never merely because a value
+was retrieved into context:
+
+- `agent_memory_remember` writes an explicit typed claim for the current principal.
+- `workflow_finish(success=true)` writes the verified workflow's bounded procedural receipt.
+- user-facing Workflow Graph create/save/restore (including **Save session as workflow draft**) writes a
+ bounded `workflow_save` episodic receipt containing only graph identity/status/counts/revision metadata;
+ node configs, variable values and credentials are not copied into memory.
+- user-facing Organization `flow_node_upsert` writes a bounded `organization_node_update` episodic receipt
+ containing unit/node identity, title, kind, status, optional project reference and chart revision; notes
+ and free-form node payloads are not copied into memory.
+- exact-identical ordinary `replace` writes are deterministic NOOPs. Retrieval, `workflow_start`, graph
+ reads, organization reads, and unsuccessful/cancelled workflows do not create memory just by being read.
+
## Deferred capability selection
The external MCP server keeps a stable, complete scope-filtered catalog for standards interoperability.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 6b668f66..52221cce 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,5 +1,8 @@
## 2026-09-19 — Memory v3 closes the learn → retrieve → expose → reuse loop
+- Memory mutation boundaries are now explicit: `agent_memory_remember`, verified `workflow_finish(success=true)`, user-facing Workflow create/save/restore (including session→draft), and Organization `flow_node_upsert`. Workflow/node domain receipts are bounded metadata only; graph configs, node notes, variable values and credentials are excluded.
+- Historical Gitleaks closeout: the two remaining findings were exact older fingerprints of deterministic SC-sync test fixtures. Added only those exact fingerprints to `.gitleaksignore`; a full 820-commit Gitleaks history scan now reports no leaks.
+
- Replaced terminal/A2A first-12k head truncation with a frozen stable-core + query-relevant JIT memory projection. Defaults are 6k core / 8k JIT characters and are configurable without changing the durable typed-memory ledger.
- Added deterministic bilingual/synonym normalization for bounded memory retrieval. The calibration improves from 4/6 to 6/6 lexical cases; the existing local semantic candidate stays 3/6, so vector memory remains blocked rather than adding complexity without recall benefit.
- `workflow_start` compact structured output now carries selected agent/project memory plus the maturity-aware recipe plan, fixing the ChatGPT wrapper path that previously exposed only progress fields.
diff --git a/lib/agent/domain-memory.ts b/lib/agent/domain-memory.ts
new file mode 100644
index 00000000..cbe20224
--- /dev/null
+++ b/lib/agent/domain-memory.ts
@@ -0,0 +1,68 @@
+import { createHash } from "node:crypto";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import type { OrganizationProjectFlow } from "@/lib/contracts/organization-flow";
+import { redactMemoryContext } from "./memory-context.mjs";
+
+function digest(value: string): string {
+ return createHash("sha256").update(value).digest("hex").slice(0, 16);
+}
+function text(value: unknown, max = 160): string {
+ return redactMemoryContext(String(value ?? "")).replace(/[\r\n]+/g, " ").trim().slice(0, max);
+}
+function testMemoryEnabled(): boolean {
+ return process.env.NODE_ENV !== "test" || Boolean(process.env.OS_AGENT_MEMORY_DIR);
+}
+
+export async function rememberWorkflowGraphSave(
+ principal: string,
+ graph: WorkflowGraph,
+ reason: "create" | "update" | "restore" | "import" | "template" | "ai-assisted",
+): Promise<boolean> {
+ if (!principal || !testMemoryEnabled()) return false;
+ const value = [
+ "Event: workflow_save",
+ `Workflow: ${text(graph.name, 180)}`,
+ `Graph ID: ${text(graph.id, 96)}`,
+ `Status: ${text(graph.status, 32)}`,
+ `Reason: ${reason}`,
+ `Nodes: ${graph.nodes.length}`,
+ `Edges: ${graph.edges.length}`,
+ `Revision: ${graph.revision.slice(0, 16)}`,
+ `Updated: ${graph.updatedAt}`,
+ ].join("\n");
+ const { rememberAgentMemory } = await import("./memory-store");
+ await rememberAgentMemory(principal, "MEMORY.md", `workflow-save:${digest(graph.id)}`, value, {
+ kind: "episodic", sensitivity: "private", confidence: 1,
+ provenance: { authority: "observed", channel: "system" },
+ });
+ return true;
+}
+
+export type OrganizationNodeMemory = {
+ unitId: string;
+ node: OrganizationProjectFlow["nodes"][number];
+ chartRevision: string;
+ change: "created" | "updated";
+};
+
+export async function rememberOrganizationNodeUpdate(principal: string, input: OrganizationNodeMemory): Promise<boolean> {
+ if (!principal || !testMemoryEnabled()) return false;
+ const node = input.node;
+ const value = [
+ "Event: organization_node_update",
+ `Unit ID: ${text(input.unitId, 96)}`,
+ `Node ID: ${text(node.id, 96)}`,
+ `Title: ${text(node.title, 180)}`,
+ `Kind: ${text(node.kind, 32)}`,
+ `Status: ${text(node.status, 32)}`,
+ ...(node.projectRef ? [`Project ref: ${text(node.projectRef, 160)}`] : []),
+ `Change: ${input.change}`,
+ `Chart revision: ${input.chartRevision.slice(0, 16)}`,
+ ].join("\n");
+ const { rememberAgentMemory } = await import("./memory-store");
+ await rememberAgentMemory(principal, "MEMORY.md", `organization-node:${digest(`${input.unitId}:${node.id}`)}`, value, {
+ kind: "episodic", sensitivity: "private", confidence: 1,
+ provenance: { authority: "observed", channel: "system" },
+ });
+ return true;
+}
diff --git a/lib/agent/organization-flow.test.ts b/lib/agent/organization-flow.test.ts
index d7f93e2e..84483f88 100644
--- a/lib/agent/organization-flow.test.ts
+++ b/lib/agent/organization-flow.test.ts
@@ -9,8 +9,8 @@ import { emptyOrganizationFlow, ORGANIZATION_FLOW_ACTIONS } from "@/lib/contract
const node = (id: string) => ({ id, title: id, kind: "project", status: "unconfirmed", summary: "", notes: "", position: { x: 0, y: 0 } });
let dir = "";
-beforeEach(async () => { dir = await mkdtemp(path.join(os.tmpdir(), "mso-org-flow-")); process.env.OS_ORGANIZATION_STORE = path.join(dir, "organization.json"); vi.resetModules(); });
-afterEach(async () => { delete process.env.OS_ORGANIZATION_STORE; await rm(dir, { recursive: true, force: true }); vi.resetModules(); });
+beforeEach(async () => { dir = await mkdtemp(path.join(os.tmpdir(), "mso-org-flow-")); process.env.OS_ORGANIZATION_STORE = path.join(dir, "organization.json"); process.env.OS_AGENT_MEMORY_DIR = path.join(dir, "memory"); vi.resetModules(); });
+afterEach(async () => { delete process.env.OS_ORGANIZATION_STORE; delete process.env.OS_AGENT_MEMORY_DIR; await rm(dir, { recursive: true, force: true }); vi.resetModules(); });
async function fixture() {
const api = await import("./organization-store");
@@ -69,8 +69,14 @@ describe("organization project flow persistence", () => {
const write = ORGANIZATION_TOOLS.find((t) => t.name === "organization_manage")!;
expect(read.scope).toBe("read"); expect(write.scope).toBe("write"); expect(write.audit?.action).toBe("agent.organization");
expect(JSON.stringify(write.inputSchema)).toContain("flow_node_upsert");
- const output = await write.run({ action: "flow_node_upsert", expected_revision: chart.revision, data: { unitId: "unit-a", node: node("via-mcp") } }, { principal: "test", scope: "write" } as never) as { chart: typeof chart };
+ const output = await write.run({ action: "flow_node_upsert", expected_revision: chart.revision, data: { unitId: "unit-a", node: { ...node("via-mcp"), notes: "token=must-not-enter-memory" } } }, { principal: "test", scope: "write" } as never) as { chart: typeof chart };
expect(output.chart.units[0].projectFlow?.nodes[0].id).toBe("via-mcp");
+ const memory = await import("./memory-store");
+ const remembered = await memory.queryAgentMemory("test", { query: "organization node via mcp", limit: 10 });
+ expect(remembered.records).toHaveLength(1);
+ expect(remembered.records[0].record.value).toContain("Event: organization_node_update");
+ expect(remembered.records[0].record.value).toContain("Node ID: via-mcp");
+ expect(remembered.records[0].record.value).not.toContain("must-not-enter-memory");
const reread = await read.run({ runtime: false }, { principal: "test" } as never) as { chart: typeof chart };
expect(reread.chart.revision).toBe(output.chart.revision);
expect(ORGANIZATION_FLOW_ACTIONS).toEqual(expect.arrayContaining(["flow_custom_nodes", "flow_nodes_move", "flow_update", "flow_node_upsert", "flow_node_delete", "flow_edge_upsert", "flow_edge_delete", "flow_replace"]));
diff --git a/lib/agent/organization-store.ts b/lib/agent/organization-store.ts
index 7786c88f..5c18cb9a 100644
--- a/lib/agent/organization-store.ts
+++ b/lib/agent/organization-store.ts
@@ -8,6 +8,7 @@ import { expandOwnerStorePath } from "@/lib/owner-store-path.js";
import { withSecurityStoreLock } from "@/lib/security-store-lock";
import type { OrganizationChart, OrganizationSeat, OrganizationUnit } from "@/lib/contracts/organization";
import { parseOrganizationSeat, parseOrganizationUnit, validateOrganizationChart } from "./organization-schema";
+import { rememberOrganizationNodeUpdate, type OrganizationNodeMemory } from "./domain-memory";
export const ORGANIZATION_STORE_PATH = expandOwnerStorePath(process.env.OS_ORGANIZATION_STORE ?? path.join(os.homedir(), ".mso", "private", "organization.json"));
const MAX_BYTES = 2 * 1024 * 1024;
@@ -41,14 +42,34 @@ export async function deleteOrganizationSeat(expectedRevision: string, id: strin
export async function replaceOrganization(expectedRevision: string, raw: { name?: unknown; units?: unknown; seats?: unknown }) { return mutate(expectedRevision, () => { const units = Array.isArray(raw.units) ? raw.units.map((v) => parseOrganizationUnit(v)) : []; const seats = Array.isArray(raw.seats) ? raw.seats.map((v) => parseOrganizationSeat(v)) : []; return materialize(String(raw.name || "Organization"), units, seats); }); }
-export async function mutateOrganizationFlow(expectedRevision: string, action: string, data: Record<string, unknown>) {
+export async function mutateOrganizationFlow(
+ expectedRevision: string,
+ action: string,
+ data: Record<string, unknown>,
+ options: { principal?: string } = {},
+) {
if (!isOrganizationFlowAction(action)) throw new Error("unsupported project flow action");
if (typeof data.unitId !== "string" || !data.unitId) throw new Error("unitId is required for project flow actions");
- return mutate(expectedRevision, (chart) => {
- const unit = chart.units.find((item) => item.id === data.unitId);
+ const unitId = data.unitId;
+ let memory: Omit<OrganizationNodeMemory, "chartRevision"> | undefined;
+ const chart = await mutate(expectedRevision, (current) => {
+ const unit = current.units.find((item) => item.id === unitId);
if (!unit) throw new Error("organization unit not found");
+ const beforeIds = new Set(unit.projectFlow?.nodes.map((node) => node.id) ?? []);
const projectFlow = changeOrganizationFlow(unit.projectFlow, action, data);
+ if (action === "flow_node_upsert") {
+ const raw = data.node && typeof data.node === "object" && !Array.isArray(data.node) ? data.node as Record<string, unknown> : {};
+ const requestedId = typeof raw.id === "string" ? raw.id : undefined;
+ const node = requestedId
+ ? projectFlow.nodes.find((item) => item.id === requestedId)
+ : projectFlow.nodes.find((item) => !beforeIds.has(item.id));
+ if (node) memory = { unitId, node, change: beforeIds.has(node.id) ? "updated" : "created" };
+ }
const next = { ...unit, projectFlow, updatedAt: new Date().toISOString() };
- return materialize(chart.name, chart.units.map((item) => item.id === unit.id ? next : item), chart.seats);
+ return materialize(current.name, current.units.map((item) => item.id === unit.id ? next : item), current.seats);
});
+ if (options.principal && memory) {
+ await rememberOrganizationNodeUpdate(options.principal, { ...memory, chartRevision: chart.revision }).catch(() => false);
+ }
+ return chart;
}
diff --git a/lib/mcp/tools-flows.ts b/lib/mcp/tools-flows.ts
index 5e33c9f4..51ec37bb 100644
--- a/lib/mcp/tools-flows.ts
+++ b/lib/mcp/tools-flows.ts
@@ -77,14 +77,14 @@ export const FLOW_TOOLS: McpTool[] = [
if (action === "variables") return { variables: await listWorkflowVariables(principal) };
if (action === "variable_set") return setWorkflowVariable(principal, String(data.key ?? ""), data.value, data.secret === true);
if (action === "variable_delete") return deleteWorkflowVariable(principal, String(data.key ?? ""));
- if (action === "create_from_template") { const row = workflowTemplate(String(data.template_id ?? "")); if (!row) throw new Error("workflow template not found"); return { graph: await createWorkflowGraph(principal, row.definition, "template") }; }
- if (action === "create") return { graph: await createWorkflowGraph(principal, data.definition ?? data) };
+ if (action === "create_from_template") { const row = workflowTemplate(String(data.template_id ?? "")); if (!row) throw new Error("workflow template not found"); return { graph: await createWorkflowGraph(principal, row.definition, "template", { remember: true }) }; }
+ if (action === "create") return { graph: await createWorkflowGraph(principal, data.definition ?? data, "create", { remember: true }) };
const id = str(a, "id");
if (action === "get") { const graph = await getWorkflowGraph(principal, id); if (!graph) throw new Error("workflow graph not found"); return { graph }; }
if (action === "versions") return { versions: await listWorkflowGraphVersions(workflowGraphOwner(principal), id) };
- if (action === "restore") { const current = await getWorkflowGraph(principal, id), snapshot = await readWorkflowGraphVersion(workflowGraphOwner(principal), id, String(data.version ?? "")); if (!current || !snapshot) throw new Error("workflow graph/version not found"); const { revision: _r, createdAt: _c, updatedAt: _u, version: _v, ...definition } = snapshot.graph; return { graph: await updateWorkflowGraph(principal, id, String(data.revision ?? current.revision), definition, "restore") }; }
- if (action === "clone") return { graph: await cloneWorkflowGraph(principal, id) };
- if (action === "update") return { graph: await updateWorkflowGraph(principal, id, String(data.revision ?? ""), data.definition) };
+ if (action === "restore") { const current = await getWorkflowGraph(principal, id), snapshot = await readWorkflowGraphVersion(workflowGraphOwner(principal), id, String(data.version ?? "")); if (!current || !snapshot) throw new Error("workflow graph/version not found"); const { revision: _r, createdAt: _c, updatedAt: _u, version: _v, ...definition } = snapshot.graph; return { graph: await updateWorkflowGraph(principal, id, String(data.revision ?? current.revision), definition, "restore", { remember: true }) }; }
+ if (action === "clone") return { graph: await cloneWorkflowGraph(principal, id, { remember: true }) };
+ if (action === "update") return { graph: await updateWorkflowGraph(principal, id, String(data.revision ?? ""), data.definition, "update", { remember: true }) };
if (action === "delete") return deleteWorkflowGraph(principal, id, String(data.revision ?? ""));
if (action === "run") {
const graph = await getWorkflowGraph(principal, id); if (!graph) throw new Error("workflow graph not found");
diff --git a/lib/mcp/tools-organization.ts b/lib/mcp/tools-organization.ts
index a10d9657..a3ec2f87 100644
--- a/lib/mcp/tools-organization.ts
+++ b/lib/mcp/tools-organization.ts
@@ -22,13 +22,13 @@ export const ORGANIZATION_TOOLS: McpTool[] = [
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }, audit: { action: "agent.organization", targetArg: "action" }, limit: { key: "organization.write", max: 30, windowMs: 60_000 },
chatgptDescription: "Edit units/seats or internal project flows. flow_* actions require data.unitId and current revision.",
inputSchema: S({ action: { type: "string", enum: ["unit_upsert", "seat_upsert", "unit_delete", "seat_delete", "replace", ...ORGANIZATION_FLOW_ACTIONS] }, expected_revision: { type: "string" }, id: { type: "string" }, data: { type: "object", description: "For flow_* actions: unitId is required; flow_custom_nodes uses customNodes=[{id,name,nodeIds,collapsed}], flow_nodes_move uses positions=[{id,position:{x,y}}]; flow_update uses title/notes; flow_replace uses flow={version:1,title,notes,nodes,edges}; flow_node_upsert uses node={id?,title,kind?,status?,summary?,notes?,position?:{x,y},projectRef?}; flow_edge_upsert uses edge={id?,source,target,label?}; deletes use id. Existing node/edge id permits partial update." } }, ["action", "expected_revision"]),
- run: async (a) => {
+ run: async (a, context) => {
const action = str(a, "action"), revision = str(a, "expected_revision"), data = a.data && typeof a.data === "object" && !Array.isArray(a.data) ? a.data as Record<string, unknown> : {};
if (action === "unit_upsert") return { chart: await upsertOrganizationUnit(revision, data) };
if (action === "seat_upsert") return { chart: await upsertOrganizationSeat(revision, data) };
if (action === "unit_delete") return { chart: await deleteOrganizationUnit(revision, str(a, "id")) };
if (action === "seat_delete") return { chart: await deleteOrganizationSeat(revision, str(a, "id")) };
- if (isOrganizationFlowAction(action)) return { chart: await mutateOrganizationFlow(revision, action, data) };
+ if (isOrganizationFlowAction(action)) return { chart: await mutateOrganizationFlow(revision, action, data, { principal: context.principal }) };
if (action === "replace") return { chart: await replaceOrganization(revision, data as never) };
throw new Error("unsupported organization action");
},
diff --git a/lib/workflow/graph-store.test.ts b/lib/workflow/graph-store.test.ts
index 7e79b54f..31659d1b 100644
--- a/lib/workflow/graph-store.test.ts
+++ b/lib/workflow/graph-store.test.ts
@@ -6,7 +6,9 @@ import type { LearnedRecipe } from "./types";
const dir = await mkdtemp(path.join(os.tmpdir(), "mso-graph-store-"));
process.env.OS_AGENT_SESSIONS_DIR = dir;
+process.env.OS_AGENT_MEMORY_DIR = path.join(dir, "memory");
const store = await import("./graph-store");
+const memory = await import("@/lib/agent/memory-store");
const graph = { name: "Generic build", description: "test", status: "draft" as const, inputs: {}, metadata: { intent: "build project", normalizedIntent: "build project" }, nodes: [
{ id: "start", name: "Start", type: "manual" as const, position: { x: 0, y: 0 }, config: {} },
@@ -14,7 +16,7 @@ const graph = { name: "Generic build", description: "test", status: "draft" as c
], edges: [{ id: "e", source: "start", target: "out" }] };
beforeAll(() => undefined);
-afterAll(async () => { await rm(dir, { recursive: true, force: true }); });
+afterAll(async () => { delete process.env.OS_AGENT_MEMORY_DIR; await rm(dir, { recursive: true, force: true }); });
describe("private workflow graph store", () => {
it("isolates principals and enforces revisions", async () => {
@@ -22,8 +24,13 @@ describe("private workflow graph store", () => {
expect((await store.listWorkflowGraphs("principal-a"))).toHaveLength(1);
expect((await store.listWorkflowGraphs("principal-b"))).toHaveLength(0);
await expect(store.updateWorkflowGraph("principal-a", created.id, "wrong", { ...graph, id: created.id })).rejects.toThrow("revision changed");
- const updated = await store.updateWorkflowGraph("principal-a", created.id, created.revision, { ...graph, id: created.id, name: "Updated" });
+ const updated = await store.updateWorkflowGraph("principal-a", created.id, created.revision, { ...graph, id: created.id, name: "Updated" }, "update", { remember: true });
expect(updated.name).toBe("Updated");
+ const remembered = await memory.queryAgentMemory("principal-a", { query: "workflow save updated", limit: 10 });
+ expect(remembered.records).toHaveLength(1);
+ expect(remembered.records[0].record.value).toContain("Event: workflow_save");
+ expect(remembered.records[0].record.value).toContain("Workflow: Updated");
+ expect(remembered.records[0].record.value).toContain("Nodes: 2");
});
it("deduplicates learned private drafts by fingerprint", async () => {
const recipe: LearnedRecipe = { id: "recipe-private", actor: "principal-learn", scope: "write", intent: "repeat safe route", normalizedIntent: "repeat safe route", project: "project-x", summary: "ok", embeddingVersion: "fixture", embedding: [], bestSteps: [{ id: "s", tool: "sys_stats", state: "completed", ts: new Date().toISOString() }], lastSteps: [], attempts: 1, successes: 1, failures: 0, averageDurationMs: 1, lastDurationMs: 1, averageWallDurationMs: 1, lastWallDurationMs: 1, quality: { stepAttempts: 1, completedSteps: 1, failedSteps: 0, deniedSteps: 0, rateLimitedSteps: 0, invalidArgSteps: 0, retries: 0, rollbackSignals: 0, timedSteps: 0, totalStepDurationMs: 0, averageStepDurationMs: 0 }, lastQuality: { stepAttempts: 1, completedSteps: 1, failedSteps: 0, deniedSteps: 0, rateLimitedSteps: 0, invalidArgSteps: 0, retries: 0, rollbackSignals: 0, timedSteps: 0, totalStepDurationMs: 0, averageStepDurationMs: 0 }, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() };
diff --git a/lib/workflow/graph-store.ts b/lib/workflow/graph-store.ts
index c88e90d2..66f6f4f2 100644
--- a/lib/workflow/graph-store.ts
+++ b/lib/workflow/graph-store.ts
@@ -7,6 +7,7 @@ import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
import { normalizeWorkflowIntent, parseWorkflowGraphDefinition, type WorkflowGraphDefinition } from "./graph-schema";
import { withSecurityStoreLock } from "@/lib/security-store-lock";
import { saveWorkflowGraphVersion, type WorkflowGraphVersionReason } from "./graph-version-store";
+import { rememberWorkflowGraphSave } from "@/lib/agent/domain-memory";
import { readWorkflowJson, writeWorkflowFile } from "./private-file";
@@ -79,20 +80,22 @@ export async function getWorkflowGraph(principal: string, id: string): Promise<W
return (await listWorkflowGraphs(principal)).find((graph) => graph.id === id) ?? null;
}
-export async function createWorkflowGraph(principal: string, raw: unknown, reason: WorkflowGraphVersionReason = "create"): Promise<WorkflowGraph> {
+export async function createWorkflowGraph(principal: string, raw: unknown, reason: WorkflowGraphVersionReason = "create", options: { remember?: boolean } = {}): Promise<WorkflowGraph> {
const owner = workflowGraphOwner(principal), definition = parseWorkflowGraphDefinition(raw);
- return withGraphLock(owner, async () => {
+ const graph = await withGraphLock(owner, async () => {
const store = await readStore(owner, principal);
if (store.graphs.length >= MAX_GRAPHS) throw new Error("private workflow graph limit reached");
const graph = materialize({ ...definition, id: definition.id ?? randomUUID() });
if (store.graphs.some((row) => row.id === graph.id)) throw new Error("workflow graph id already exists");
store.principal = principal; store.graphs.push(graph); await writeStore(store); await saveWorkflowGraphVersion(owner, graph, reason); return graph;
});
+ if (options.remember) await rememberWorkflowGraphSave(principal, graph, reason).catch(() => false);
+ return graph;
}
-export async function updateWorkflowGraph(principal: string, id: string, expectedRevision: string, raw: unknown, reason: WorkflowGraphVersionReason = "update"): Promise<WorkflowGraph> {
+export async function updateWorkflowGraph(principal: string, id: string, expectedRevision: string, raw: unknown, reason: WorkflowGraphVersionReason = "update", options: { remember?: boolean } = {}): Promise<WorkflowGraph> {
const owner = workflowGraphOwner(principal), definition = parseWorkflowGraphDefinition(raw);
- return withGraphLock(owner, async () => {
+ const graph = await withGraphLock(owner, async () => {
const store = await readStore(owner, principal), index = store.graphs.findIndex((graph) => graph.id === id);
if (index < 0) throw new Error("workflow graph not found");
const current = store.graphs[index];
@@ -100,6 +103,8 @@ export async function updateWorkflowGraph(principal: string, id: string, expecte
if (definition.id && definition.id !== id) throw new Error("workflow graph id mismatch");
const graph = materialize({ ...definition, id }, current); store.principal = principal; store.graphs[index] = graph; await writeStore(store); await saveWorkflowGraphVersion(owner, graph, reason); return graph;
});
+ if (options.remember) await rememberWorkflowGraphSave(principal, graph, reason).catch(() => false);
+ return graph;
}
export async function deleteWorkflowGraph(principal: string, id: string, expectedRevision: string): Promise<{ id: string; deleted: true }> {
@@ -112,13 +117,13 @@ export async function deleteWorkflowGraph(principal: string, id: string, expecte
});
}
-export async function cloneWorkflowGraph(principal: string, id: string): Promise<WorkflowGraph> {
+export async function cloneWorkflowGraph(principal: string, id: string, options: { remember?: boolean } = {}): Promise<WorkflowGraph> {
const source = await getWorkflowGraph(principal, id);
if (!source) throw new Error("workflow graph not found");
return createWorkflowGraph(principal, {
name: `${source.name} Copy`, description: source.description, status: "draft", inputs: source.inputs,
nodes: source.nodes, edges: source.edges, metadata: { ...source.metadata, provenance: "clone", fingerprint: undefined },
- });
+ }, "create", options);
}
function tokens(value: string): Set<string> { return new Set(normalizeWorkflowIntent(value).split(" ").filter((word) => word.length > 2)); }