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(organization): add agent org chart and routing
Rahmanbeabb8001c4b
diff --git a/.env.example b/.env.exampleindex 16c166c7..135e9c68 100644--- a/.env.example+++ b/.env.example@@ -229,6 +229,7 @@ OS_SESSION_SECRET=# Native Local Agents use private defaults; overrides are normally unnecessary.# OS_LOCAL_AGENT_PRESENCE_STORE=~/.mso/private/local-agent-presence.json # live receive leases/aliases (0600)# OS_LOCAL_AGENT_MESSAGE_STORE=~/.mso/private/local-agent-messages.json # durable explicit local messages/tasks (0600)+# OS_ORGANIZATION_STORE=~/.mso/private/organization.json # owner-private org units/seats/reporting/agent bindings (0600)# OS_LOCAL_AGENT_LEASE_MS=60000 # receiver lease; CLI heartbeat is lighter than this expiry# OS_TOOL_FORGE_DIR=~/.mso/tool-forge # private inert Tool Forge candidate/evaluation records# OS_TOOL_FORGE_NODE_IMAGE=mso-forge-sandbox:node22-v1 # labelled cached Docker image used only for executable Forge fixturesdiff --git a/app/api/v1/organization/route.ts b/app/api/v1/organization/route.tsnew file mode 100644index 00000000..87d9bcf6--- /dev/null+++ b/app/api/v1/organization/route.ts@@ -0,0 +1,41 @@+import { NextRequest, NextResponse } from "next/server";+import { getSessionContext } from "@/lib/auth/require-session";+import { roleAtLeast } from "@/lib/auth/roles";+import { audit } from "@/lib/host/audit-api";+import { rateLimited } from "@/lib/host/limits-api";+import { readSetupJson } from "@/lib/infra/setup-http";+import { deleteOrganizationSeat, deleteOrganizationUnit, getOrganizationChart, replaceOrganization, upsertOrganizationSeat, upsertOrganizationUnit } from "@/lib/agent/organization-store";+import { organizationRuntime, resolveOrganizationSeat } from "@/lib/agent/organization-runtime";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";+const headers = { "Cache-Control": "private, no-store" };+const fail = (error: unknown, status = 400) => NextResponse.json({ error: error instanceof Error ? error.message.slice(0, 500) : String(error).slice(0, 500) }, { status, headers });+async function auth(minimum: "viewer" | "operator" | "owner" = "viewer") { const context = await getSessionContext(); if (!context?.session.device_id || !roleAtLeast(context.role, minimum)) return null; return { context, principal: `web:${context.session.device_id}` }; }++export async function GET(req: NextRequest) {+ const session = await auth("viewer"); if (!session) return fail("unauthorized", 401);+ try {+ const chart = await getOrganizationChart(), seatRef = req.nextUrl.searchParams.get("seat");+ if (seatRef) return NextResponse.json({ chart: { name: chart.name, revision: chart.revision }, seat: await resolveOrganizationSeat(seatRef), runtime: await organizationRuntime(session.principal) }, { headers });+ return NextResponse.json({ chart, runtime: req.nextUrl.searchParams.get("runtime") === "0" ? [] : await organizationRuntime(session.principal) }, { 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 = String(body.action || "");+ if (rateLimited(`organization:${action}:${session.context.session.device_id}`, 40, 60_000)) return fail("rate_limited", 429);+ const revision = String(body.expected_revision || ""); if (!revision) throw new Error("expected_revision is required");+ let chart;+ if (action === "unit_upsert") chart = await upsertOrganizationUnit(revision, body.unit as Record<string, unknown>);+ 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 (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}` });+ return NextResponse.json({ chart, runtime: await organizationRuntime(session.principal) }, { headers });+ } catch (error) { const message = error instanceof Error ? error.message : ""; return fail(error, /revision changed/.test(message) ? 409 : 400); }+}diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.tsindex 79ae9308..f2b5d1dc 100644--- a/app/api/v1/workflows/route.ts+++ b/app/api/v1/workflows/route.ts@@ -6,6 +6,7 @@ import { readSetupJson } from "@/lib/infra/setup-http";import { rateLimited } from "@/lib/host/limits-api";import { maxScope } from "@/lib/mcp/scope";import { TOOLS_BY_NAME } from "@/lib/mcp/tools";+import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";import { cloneWorkflowGraph, createWorkflowGraph, deleteWorkflowGraph, getWorkflowGraph, listWorkflowGraphs, updateWorkflowGraph, workflowGraphOwner } from "@/lib/workflow/graph-store";import { startWorkflowGraph, workflowGraphRunStatus } from "@/lib/workflow/graph-engine";import { listWorkflowGraphRuns } from "@/lib/workflow/graph-run-store";@@ -39,5 +40,5 @@ export async function POST(req:NextRequest){const session=await auth("operator")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==="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()} as const;return NextResponse.json(await startWorkflowGraph(graph,body.input??{},String(body.idempotency_key??`${Date.now()}`),context,(name)=>TOOLS_BY_NAME.get(name)),{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});}throw new Error("unknown workflow action");}catch(error){return fail(error);}}diff --git a/app/api/v1/workflows/webhook/[...hook]/route.ts b/app/api/v1/workflows/webhook/[...hook]/route.tsindex cf76aba8..96111ca3 100644--- a/app/api/v1/workflows/webhook/[...hook]/route.ts+++ b/app/api/v1/workflows/webhook/[...hook]/route.ts@@ -3,6 +3,7 @@ import { NextRequest, NextResponse } from "next/server";import { rateLimited } from "@/lib/host/limits-api";import { createAgentSession } from "@/lib/agent/session-store";import { maxScope } from "@/lib/mcp/scope";+import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";import { findActiveWebhookSource } from "@/lib/workflow/graph-triggers";import { startWorkflowGraph, workflowGraphRunStatus } from "@/lib/workflow/graph-engine";import { workflowVariableValues } from "@/lib/workflow/variables";@@ -10,5 +11,5 @@ export const runtime="nodejs";export const dynamic="force-dynamic";function same(a:string,b:string){const x=Buffer.from(a),y=Buffer.from(b);return x.length===y.length&&timingSafeEqual(x,y);}async function payload(req:NextRequest){const length=Number(req.headers.get("content-length")||0);if(length>64*1024)throw new Error("webhook body too large");let body:unknown=null;if(!["GET","HEAD"].includes(req.method)){const text=await req.text();if(Buffer.byteLength(text)>64*1024)throw new Error("webhook body too large");try{body=text?JSON.parse(text):null;}catch{body=text;}}return{method:req.method,query:Object.fromEntries(req.nextUrl.searchParams),httpHeaders:{"content-type":req.headers.get("content-type")||undefined,"user-agent":req.headers.get("user-agent")||undefined,"x-request-id":req.headers.get("x-request-id")||undefined},body};}async function handle(req:NextRequest,ctx:{params:Promise<{hook:string[]}>}){try{const {hook}=await ctx.params;if(hook.length!==2)return NextResponse.json({error:"webhook_not_found"},{status:404});const source=await findActiveWebhookSource(hook[0]!,hook[1]!);if(!source)return NextResponse.json({error:"webhook_not_found"},{status:404});const methods=Array.isArray(source.node.config.methods)?source.node.config.methods.map(String):["POST"];if(!methods.includes(req.method))return NextResponse.json({error:"method_not_allowed"},{status:405,headers:{Allow:methods.join(", ")}});if(rateLimited(`workflow-webhook:${source.graph.id}:${source.node.id}`,120,60_000))return NextResponse.json({error:"rate_limited"},{status:429});const authVar=typeof source.node.config.authVariable==="string"?source.node.config.authVariable:"";if(authVar){const vars=await workflowVariableValues(source.principal),expected=vars[authVar];if(typeof expected!=="string")return NextResponse.json({error:"webhook_auth_not_configured"},{status:503});const raw=req.headers.get("authorization")?.replace(/^Bearer\s+/i,"")??req.headers.get("x-webhook-token")??"";if(!same(raw,expected))return NextResponse.json({error:"unauthorized"},{status:401});}- const input=await payload(req),session=await createAgentSession(source.principal,"cli",{title:`Webhook: ${source.graph.name}`,titleSource:"auto"}),{TOOLS_BY_NAME}=await import("@/lib/mcp/tools"),key=(req.headers.get("idempotency-key")||`webhook-${crypto.randomUUID()}`).slice(0,128),context={principal:source.principal,actor:source.principal,sessionId:session.id,scope:maxScope()} as const;const started=await startWorkflowGraph(source.graph,input,key,context,(name)=>TOOLS_BY_NAME.get(name),source.principal,{type:"webhook",nodeId:source.node.id,receivedAt:new Date().toISOString()});if(source.node.config.responseMode!=="lastNode")return NextResponse.json({runId:started.id,state:started.state},{status:202});const done=await workflowGraphRunStatus(source.principal,started.id,25_000),output=[...done.nodes].reverse().find((node)=>node.type==="output"&&node.output!==undefined)?.output;return NextResponse.json({runId:done.id,state:done.state,output},{status:done.state==="failed"?500:200});}catch(error){return NextResponse.json({error:error instanceof Error?error.message.slice(0,300):"webhook_failed"},{status:400});}}+ const input=await payload(req),session=await createAgentSession(source.principal,"cli",{title:`Webhook: ${source.graph.name}`,titleSource:"auto"}),{TOOLS_BY_NAME}=await import("@/lib/mcp/tools"),key=(req.headers.get("idempotency-key")||`webhook-${crypto.randomUUID()}`).slice(0,128),context={principal:source.principal,actor:source.principal,sessionId:session.id,scope:maxScope(),capabilities:msoCapabilityRuntime} as const;const started=await startWorkflowGraph(source.graph,input,key,context,(name)=>TOOLS_BY_NAME.get(name),source.principal,{type:"webhook",nodeId:source.node.id,receivedAt:new Date().toISOString()});if(source.node.config.responseMode!=="lastNode")return NextResponse.json({runId:started.id,state:started.state},{status:202});const done=await workflowGraphRunStatus(source.principal,started.id,25_000),output=[...done.nodes].reverse().find((node)=>node.type==="output"&&node.output!==undefined)?.output;return NextResponse.json({runId:done.id,state:done.state,output},{status:done.state==="failed"?500:200});}catch(error){return NextResponse.json({error:error instanceof Error?error.message.slice(0,300):"webhook_failed"},{status:400});}}export const GET=handle;export const POST=handle;export const PUT=handle;export const PATCH=handle;export const DELETE=handle;diff --git a/bin/mso b/bin/msoindex ffb63218..542bcf4e 100755--- a/bin/mso+++ b/bin/mso@@ -69,6 +69,7 @@# threads * Conversation history: list | show | rm# agent-sessions * Durable MSO Agent sessions: list | show | create# agents * Native local session agents: list | send | inbox+# org * Organization chart: units, seats, reporting lines, targets# a2a * Agent-to-Agent v1: list | discover | add | rm | send | task | cancel | handoff# memory * Assistant memories: list | add | rm# config * Advanced raw AI config compatibility surfacediff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 48c18b7a..9ad66a41 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -291,4 +291,8 @@ Each MSO connector/server scope owns its own Page app catalog. Core MSO Page cod## Server-native workflow graph+## Organization and agent routing++MSO Organization is a first-class owner-private domain beside Workflow Graph, Local Agents, A2A, Project Agents, and Integrations. It stores stable units/seats/reporting lines and execution-target references; it does not store credentials, transcripts, or workflow topology. An active seat may be `unbound`, and a seat may reference an existing `project-agent`, `local-agent`, or `a2a` executor. Workflow Agent nodes can hold `orgSeatId` and resolve that pointer at run time, so organizational identity remains stable when the underlying executor changes. All existing capability/audit/approval boundaries still apply. See [`ORGANIZATION.md`](./ORGANIZATION.md).+MSO has a Workflow Graph v2 layer above the existing automation/lifecycle/RASMIC primitives. It is the automation-topology SSOT and provides server-side schedule/webhook triggers, bounded branching/loops/subflows, retry/error paths, versioned definitions, private variables and persisted execution history. Canonical project paths resolve dynamically and credentials remain in integration authorities rather than portable graph definitions. Graph definitions/versions/runs/variables are isolated by authenticated principal, while tools/scripts/subflows retain normal capability scope, audit, connection and project guards. See [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md).diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 4e23effc..2d1f4703 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**+- `organization` add agent org chart and routing- `workflows` complete server-native automation parity- `workflows` add server-native workflow graphdiff --git a/docs/CLI.md b/docs/CLI.mdindex 2367c898..26bb4f49 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -109,6 +109,7 @@ Commands:threads * Conversation history: list | show | rmagent-sessions * Durable MSO Agent sessions: list | show | createagents * Native local session agents: list | send | inbox+ org * Organization chart: units, seats, reporting lines, targetsa2a * Agent-to-Agent v1: list | discover | add | rm | send | task | cancel | handoffmemory * Assistant memories: list | add | rmconfig * Advanced raw AI config compatibility surfacediff --git a/docs/MCP.md b/docs/MCP.mdindex 9a4b0f70..2d8f0b46 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -200,6 +200,8 @@ RASMIC adds three stable generic MCP tools without coupling MSO to another repos### Local Agent collaboration+Organization is a separate private operating-structure domain. `organization_chart` reads units, seats, reporting lines, execution bindings, and live target status; `organization_manage` applies revision-checked mutations. Seats only reference existing Project Agent, Local Agent, or A2A targets and never copy credentials or hidden session context. Workflow graphs may reference a seat by `orgSeatId`, but the Organization registry remains the SSOT. See [Organization](./ORGANIZATION.md).+Local same-owner session collaboration is intentionally separate from public A2A. `local_agents_list` reports each durable session's short public `name`, lease status, and live receiver observability (`consumerConnected` / `consumerCount`). `local_agent_message_send` + `local_agent_reply` provide durable correlated mailbox semantics. `local_agent_inbox(wait_ms=...)` can hold one foreground MCP call for at most 20 seconds and returns early when a peer message arrives; the implementation registers the same in-process receiver used by terminal Local Agents, closes the read/subscribe race with a second durable-mailbox read, and unsubscribes on return/timeout. The default `wait_ms=0` preserves immediate reads. `local_agent_request_wait` remains the bounded wait for one exact correlated outbound request, while `local_agent_request` remains an explicit exec-gated fresh worker from another durable session context and never claims to wake/control its original terminal/ChatGPT process. Human `@name` mentions resolve active public names only.### Agent-to-Agent (A2A) peersdiff --git a/docs/ORGANIZATION.md b/docs/ORGANIZATION.mdnew file mode 100644index 00000000..0240a279--- /dev/null+++ b/docs/ORGANIZATION.md@@ -0,0 +1,127 @@+# Organization — agent roles, reporting lines, and execution routing++MSO Organization is the private owner-level source of truth for **who exists in the operating structure, what seat they occupy, who they report to, and which existing agent runtime may execute work for that seat**.++It is intentionally **not a Workflow feature**. Workflow owns automation topology and execution. Organization owns operating structure and routing context. A Workflow Agent node may reference an Organization seat, but the workflow does not copy or own that seat.++## Domain split++| Domain | Owns | Does not own |+|---|---|---|+| Organization | units, seats, titles, roles, reporting lines, seat mode/state, execution target references | automation graphs, credentials, agent transcripts |+| Workflow Graph | triggers, nodes, edges, retries, execution history, versions | organization hierarchy |+| Local Agents | same-owner durable session identity and messaging/execution | organizational title/reporting truth |+| A2A | registered remote peer metadata and remote task transport | organizational title/reporting truth |+| Project Agent | bounded execution inside one canonical project | organization hierarchy |+| Integrations | credentials and provider connections | seat metadata |+| Alfa Agent persona | browser-local conversational persona | organizational authority or execution permissions |++An Org seat never grants capability. Existing scope, approval, project, A2A, Local Agent, and Integrations guards remain authoritative.++## Model++### Unit++A unit is a stable organization/context boundary:++- `holding`+- `company`+- `division`+- `team`+- `client`+- `other`++Units can nest with `parentUnitId`. The store rejects missing parents and cycles.++### Seat++A seat is an organizational position. It belongs to one unit and may report to another seat, including a seat in a different unit. This enables a complete holding-company reporting tree while still allowing unit-filtered views.++Seat state:++- `active` — the position exists and is active.+- `vacant` — the position exists but is intentionally unfilled.+- `inactive` — the position is retained but disabled.++Seat mode:++- `permanent` — persistent context/role owner.+- `on_demand` — valid role invoked only when work needs it.+- `inactive` — disabled execution seat.++Runtime status is separate from seat state. An active seat with no executor is `unbound`, not `vacant`.++## Execution targets++A seat may point to one existing execution authority:++- `none` — organization/context only.+- `project-agent` — a canonical MSO project agent target.+- `local-agent` — a durable same-owner Local Agent/session reference.+- `a2a` — a registered remote A2A peer reference.++The Org store persists only references. It never stores provider keys, A2A credentials, integration secrets, hidden conversation context, or project credentials.++## Workflow integration++The Workflows Agent node supports `config.orgSeatId`.++When present, MSO resolves the seat at execution time:++1. validate the seat is active;+2. read its current target reference;+3. route through the existing target authority;+4. preserve the original workflow scope/audit/runtime guards.++Target mapping:++- `project-agent` → `project_agent_run`+- `local-agent` → `local_agent_request`+- `a2a` → `a2a_handoff`++Because resolution happens at run time, changing a seat's executor does not require editing every workflow that points to the seat.++## Storage and safety++Default store: `~/.mso/private/organization.json` (override with `OS_ORGANIZATION_STORE`).++The store is owner-private and shared across this owner's MSO surfaces so Web, CLI, MCP, schedules, and webhooks see the same organization. It uses:++- directory mode `0700`;+- file mode `0600`;+- no-follow reads and owner checks;+- atomic writes;+- optimistic `revision` checks;+- bounded unit/seat/text counts;+- unit and reporting-cycle prevention;+- child/direct-report delete guards.++This is a private runtime store. MSO source ships **no operator-specific organization data**.++## UI++Open **Alfa → Organization**.++The default `All organization` view renders the complete reporting hierarchy across units. Selecting a unit filters the view while keeping the same SSOT. Seat cards show role, unit, seat mode, execution binding, and current runtime state.++Editing uses the shell-responsive dialog/drawer primitive so desktop and mobile use the same contract.++## CLI++```text+mso org show+mso org unit-upsert <revision> <JSON|@file>+mso org seat-upsert <revision> <JSON|@file>+mso org unit-delete <revision> <id>+mso org seat-delete <revision> <id>+mso org replace <revision> <JSON|@file>+```++Every mutation uses the current chart revision. Refresh and reconcile if another surface changed it first.++## MCP++- `organization_chart` — read chart, optional seat lookup, and live target status.+- `organization_manage` — revision-checked unit/seat mutation.++The MCP tools expose the same store and do not create another organization database.diff --git a/docs/README.md b/docs/README.mdindex 9c30b067..f4ac74b6 100644--- a/docs/README.md+++ b/docs/README.md@@ -36,6 +36,7 @@ evidence and review freshness. The repository quality gate runs both automatical| [`PROJECT-MCP-CONNECTIONS.md`](./PROJECT-MCP-CONNECTIONS.md) | Named private connections, endpoint binding and identity for modular project MCPs || [`AUTOMATION-FLOWS.md`](./AUTOMATION-FLOWS.md) | Versioned project API/MCP flows, CLI, sessions, Add MCP, assets and limits || [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md) | Private server-native Workflow Graph v2 with n8n-core triggers/flow control, versions/history, variables, integrations, visual execution and automatic learning |+| [`ORGANIZATION.md`](./ORGANIZATION.md) | Owner-private organization units, seats, reporting lines, live agent bindings, and workflow routing references || [`MCP-HOW-TO.md`](./MCP-HOW-TO.md) | Bahasa Indonesia onboarding: client connection, prompts, workflow, project MCP and troubleshooting || [`MCP.md`](./MCP.md) | MCP/OAuth internals and full external-tool security model || [`A2A.md`](./A2A.md) | A2A v1 peer discovery, delegation/task lifecycle, CLI/MCP surface and trust boundary |diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.mdindex 699b796e..f9e45c77 100644--- a/docs/WORKFLOW-GRAPH.md+++ b/docs/WORKFLOW-GRAPH.md@@ -176,3 +176,7 @@ The linear `flow_catalog`, `flow_manage`, `flow_run` and `flow_status` tools rem## Scope of n8n parityMSO targets **core self-hosted workflow parity**, not n8n's SaaS business surface. MSO intentionally uses its own server-native project, filesystem, Skill, agent and integration nodes instead of reproducing n8n's marketplace or cloud billing/team-administration products. Free cyclic graph topology is also intentionally replaced by bounded loop/subflow constructs for safer unattended server execution.++## Organization seat routing++Organization is not owned by Workflow Graph. An `agent` node may set `orgSeatId`; at execution time MSO resolves that seat from the private Organization registry and routes to its current Project Agent, Local Agent, or A2A target. This indirection lets a workflow say “send to the CTO seat” without duplicating which concrete agent currently fills that seat. Direct project-bound Agent nodes remain backward compatible. See [`ORGANIZATION.md`](./ORGANIZATION.md).diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.mdindex 7eccb157..7ba7d4a9 100644--- a/docs/generated/MCP-CATALOG.md+++ b/docs/generated/MCP-CATALOG.md@@ -4,21 +4,21 @@## Full MSO catalog-<!-- mcp-toolset: server=1.14.4 version=2026.09.15.3 tools=106 read=50 write=34 exec=22 -->+<!-- mcp-toolset: server=1.14.4 version=2026.09.15.3 tools=108 read=51 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 | **108** |-| Model/operator tools | **106** |-| Read | **50** |-| Write | **34** |+| Transport tools | **110** |+| Model/operator tools | **108** |+| Read | **51** |+| Write | **35** || Exec | **22** || App-only bridges | **2** |-### Read (50)+### Read (51)- `a2a_agent_discover`- `a2a_agents_list`@@ -50,6 +50,7 @@- `local_agent_request_wait`- `local_agents_list`- `mso_surface_apps_list`+- `organization_chart`- `project_agent_status`- `project_capabilities`- `project_changes_list`@@ -71,7 +72,7 @@- `tool_forge_candidates`- `vps_status`-### Write (34)+### Write (35)- `a2a_agent_register`- `a2a_agent_remove`@@ -96,6 +97,7 @@- `integration_setup_open`- `local_agent_message_send`- `local_agent_reply`+- `organization_manage`- `project_asset_attach`- `project_knowledge_set`- `project_mcp_manage`@@ -140,20 +142,20 @@## ChatGPT model profile-<!-- mcp-chatgpt-profile: server=1.14.4 version=2026.09.15.3 tools=106 read=50 write=34 exec=22 app-only=2 total=108 -->+<!-- mcp-chatgpt-profile: server=1.14.4 version=2026.09.15.3 tools=108 read=51 write=35 exec=22 app-only=2 total=110 -->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 | **108** |-| ChatGPT model/operator tools | **106** |-| Read | **50** |-| Write | **34** |+| ChatGPT transport tools | **110** |+| ChatGPT model/operator tools | **108** |+| Read | **51** |+| Write | **35** || Exec | **22** || App-only bridges | **2** |-### ChatGPT read (50)+### ChatGPT read (51)- `a2a_agent_discover`- `a2a_agents_list`@@ -185,6 +187,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/- `local_agent_request_wait`- `local_agents_list`- `mso_surface_apps_list`+- `organization_chart`- `project_agent_status`- `project_capabilities`- `project_changes_list`@@ -206,7 +209,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/- `tool_forge_candidates`- `vps_status`-### ChatGPT write (34)+### ChatGPT write (35)- `a2a_agent_register`- `a2a_agent_remove`@@ -231,6 +234,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/- `integration_setup_open`- `local_agent_message_send`- `local_agent_reply`+- `organization_manage`- `project_asset_attach`- `project_knowledge_set`- `project_mcp_manage`diff --git a/frontend/slices/assistant/CONTRACT.md b/frontend/slices/assistant/CONTRACT.mdindex aec64a59..d9b256eb 100644--- a/frontend/slices/assistant/CONTRACT.md+++ b/frontend/slices/assistant/CONTRACT.md@@ -9,7 +9,7 @@ unrelated things both called "skill".----> **Where this lives, and how to not lose it.** Agents, Skills and Automations are+> **Where this lives, and how to not lose it.** Alfa personas, Playbooks and browser Automations are> per-browser localStorage (`alfa.*`), so clearing site data destroys them and there> is no server copy. **Settings → Backup** exports every mso-owned key as one JSON> file and imports it back. The `alfa.` prefix is matched by rule, so a new@@ -96,6 +96,10 @@ and a regular non-symlink `SKILL.md`; the generic HOME agent roots stay untrusteEvery response carries a scan report, so a truncated catalog is never presented ascomplete. See [`docs/MCP.md`](../../../docs/MCP.md) and [`skills/README.md`](../../../skills/README.md).+## Organization (not an Alfa persona)++The **Organization** tab is a server-side owner-private operating-structure view, not another browser Agent persona store. Its SSOT is `~/.mso/private/organization.json` via `lib/agent/organization-store.ts`. Units and seats define stable hierarchy/reporting context; a seat can point at an existing Project Agent, Local Agent/session, or A2A peer. Those references grant no extra tools or credentials. Workflows may resolve `orgSeatId` at execution time. See [`docs/ORGANIZATION.md`](../../../docs/ORGANIZATION.md).+## Agent**A persona.** Currently that, and only that.diff --git a/frontend/slices/assistant/app.tsx b/frontend/slices/assistant/app.tsxindex 41cfd4d0..ac778e29 100644--- a/frontend/slices/assistant/app.tsx+++ b/frontend/slices/assistant/app.tsx@@ -17,6 +17,7 @@ import { ThreadList } from "./components/thread-list";import { LibraryGrid } from "./components/library-grid";import { SkillForm } from "./components/skill-form";import { McpActivityView } from "./components/mcp-activity-view";+import { OrganizationView } from "./components/organization-view";import { AlfaCockpitBar } from "./components/alfa-cockpit-bar";import { assistantRouteFromPayload, type AssistantTab } from "./lib/navigation";@@ -30,6 +31,7 @@ type FormState =const TABS: [Tab, string][] = [["chat", "Chat"],["agents", "Agents"],+ ["organization", "Organization"],["skills", "Playbooks"],["automations", "Automations"],["mcp", "Activity"],@@ -151,6 +153,8 @@ export default function Assistant({ payload }: AppProps) {onNew={() => setForm({ kind: "agent" })}onEdit={(it) => setForm({ kind: "agent", item: it as Agent })}/>+ ) : tab === "organization" ? (+ <OrganizationView />) : tab === "skills" ? (<LibraryGridkind="skill"diff --git a/frontend/slices/assistant/components/organization-editor.tsx b/frontend/slices/assistant/components/organization-editor.tsxnew file mode 100644index 00000000..ecc12d8f--- /dev/null+++ b/frontend/slices/assistant/components/organization-editor.tsx@@ -0,0 +1,26 @@+"use client";+import { useState } from "react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";+import { ResponsiveDialog } from "@/features/appshell";+import type { OrganizationChart, OrganizationSeat, OrganizationTarget, OrganizationUnit } from "@/lib/contracts/organization";++type Draft = { kind: "unit"; item?: OrganizationUnit } | { kind: "seat"; item?: OrganizationSeat };+type Props = { draft: Draft | null; chart: OrganizationChart; onClose: () => void; onSave: (action: string, data: Record<string, unknown>) => Promise<void>; onDelete: (kind: "unit" | "seat", id: string) => Promise<void> };+const selectClass = "h-9 w-full rounded-md border bg-background px-2 text-sm";+const Field = ({ label, children }: { label: string; children: React.ReactNode }) => <label className="space-y-1 text-xs"><span className="text-muted-foreground">{label}</span>{children}</label>;+export function OrganizationEditor({ draft, chart, onClose, onSave, onDelete }: Props) {+ const key = draft ? `${draft.kind}:${draft.item?.id ?? "new"}` : "closed";+ return <ResponsiveDialog open={!!draft} onOpenChange={(open) => !open && onClose()} size="md" mobileVariant="drawer-bottom"><EditorBody key={key} draft={draft} chart={chart} onClose={onClose} onSave={onSave} onDelete={onDelete}/></ResponsiveDialog>;+}+function EditorBody({ draft, chart, onClose, onSave, onDelete }: Props) {+ const unit = draft?.kind === "unit" ? draft.item : undefined, seat = draft?.kind === "seat" ? draft.item : undefined;+ const [form, setForm] = useState<Record<string, unknown>>(() => draft?.kind === "unit" ? { id: unit?.id, key: unit?.key ?? "", name: unit?.name ?? "", kind: unit?.kind ?? "company", status: unit?.status ?? "active", parentUnitId: unit?.parentUnitId ?? "", description: unit?.description ?? "", sortOrder: unit?.sortOrder ?? 0 } : { id: seat?.id, unitId: seat?.unitId ?? chart.units[0]?.id ?? "", name: seat?.name ?? "", title: seat?.title ?? "", role: seat?.role ?? "agent", state: seat?.state ?? "active", seatMode: seat?.seatMode ?? "permanent", reportsToSeatId: seat?.reportsToSeatId ?? "", description: seat?.description ?? "", responsibilities: seat?.responsibilities.join("\n") ?? "", targetKind: seat?.target.kind ?? "none", targetRef: seat?.target.kind === "project-agent" ? seat.target.project : seat?.target.kind === "local-agent" || seat?.target.kind === "a2a" ? seat.target.ref : "", sortOrder: seat?.sortOrder ?? 0 });+ const [busy, setBusy] = useState(false), [error, setError] = useState(""); if (!draft) return null; const set = (k: string, v: unknown) => setForm((prev) => ({ ...prev, [k]: v }));+ const save = async () => { setBusy(true); setError(""); try { if (draft.kind === "unit") { const data = { ...form, parentUnitId: form.parentUnitId || undefined }; await onSave("unit_upsert", data); } else { const kind = String(form.targetKind || "none"), target: OrganizationTarget = kind === "project-agent" ? { kind, project: String(form.targetRef || "") } : kind === "local-agent" || kind === "a2a" ? { kind, ref: String(form.targetRef || "") } : { kind: "none" }; const data: Record<string, unknown> = { ...form, reportsToSeatId: form.reportsToSeatId || undefined, responsibilities: String(form.responsibilities || "").split("\n").map((x) => x.trim()).filter(Boolean), target }; delete data.targetKind; delete data.targetRef; await onSave("seat_upsert", data); } onClose(); } catch (e) { setError(e instanceof Error ? e.message : "Save failed"); } finally { setBusy(false); } };+ return <><ResponsiveDialog.Header><ResponsiveDialog.Title>{draft.item ? "Edit" : "New"} {draft.kind === "unit" ? "unit" : "seat"}</ResponsiveDialog.Title><ResponsiveDialog.Description>{draft.kind === "unit" ? "Organization boundary and hierarchy." : "Role, reporting line, and execution binding."}</ResponsiveDialog.Description></ResponsiveDialog.Header>+ <ResponsiveDialog.Body><div className="grid gap-3 py-1">{draft.kind === "unit" ? <><Field label="Name"><Input value={String(form.name ?? "")} onChange={(e) => set("name", e.target.value)}/></Field><Field label="Key"><Input value={String(form.key ?? "")} onChange={(e) => set("key", e.target.value.toLowerCase().replace(/[^a-z0-9._-]+/g,"-"))}/></Field><Field label="Kind"><select className={selectClass} value={String(form.kind)} onChange={(e) => set("kind", e.target.value)}>{["holding","company","division","team","client","other"].map((x)=><option key={x}>{x}</option>)}</select></Field><Field label="Parent unit"><select className={selectClass} value={String(form.parentUnitId ?? "")} onChange={(e)=>set("parentUnitId",e.target.value)}><option value="">Root</option>{chart.units.filter((u)=>u.id!==unit?.id).map((u)=><option key={u.id} value={u.id}>{u.name}</option>)}</select></Field></> : <><Field label="Unit"><select className={selectClass} value={String(form.unitId)} onChange={(e)=>set("unitId",e.target.value)}>{chart.units.map((u)=><option key={u.id} value={u.id}>{u.name}</option>)}</select></Field><div className="grid gap-3 sm:grid-cols-2"><Field label="Seat name"><Input value={String(form.name)} onChange={(e)=>set("name",e.target.value)}/></Field><Field label="Title"><Input value={String(form.title)} onChange={(e)=>set("title",e.target.value)}/></Field></div><div className="grid gap-3 sm:grid-cols-2"><Field label="Role"><Input value={String(form.role)} onChange={(e)=>set("role",e.target.value)}/></Field><Field label="Reports to"><select className={selectClass} value={String(form.reportsToSeatId ?? "")} onChange={(e)=>set("reportsToSeatId",e.target.value)}><option value="">Root seat</option>{chart.seats.filter((s)=>s.id!==seat?.id).map((s)=><option key={s.id} value={s.id}>{s.title} · {s.name}</option>)}</select></Field></div><div className="grid gap-3 sm:grid-cols-2"><Field label="Seat mode"><select className={selectClass} value={String(form.seatMode)} onChange={(e)=>set("seatMode",e.target.value)}>{["permanent","on_demand","inactive"].map((x)=><option key={x}>{x}</option>)}</select></Field><Field label="State"><select className={selectClass} value={String(form.state)} onChange={(e)=>set("state",e.target.value)}>{["active","vacant","inactive"].map((x)=><option key={x}>{x}</option>)}</select></Field></div><div className="grid gap-3 sm:grid-cols-2"><Field label="Execution target"><select className={selectClass} value={String(form.targetKind)} onChange={(e)=>set("targetKind",e.target.value)}>{["none","project-agent","local-agent","a2a"].map((x)=><option key={x}>{x}</option>)}</select></Field>{form.targetKind!=="none"?<Field label={form.targetKind==="project-agent"?"Project":"Target ref"}><Input value={String(form.targetRef)} onChange={(e)=>set("targetRef",e.target.value)}/></Field>:null}</div><Field label="Responsibilities (one per line)"><Textarea value={String(form.responsibilities)} onChange={(e)=>set("responsibilities",e.target.value)} className="min-h-24"/></Field></>}+ <Field label="Description"><Textarea value={String(form.description ?? "")} onChange={(e)=>set("description",e.target.value)}/></Field>{error?<p className="text-xs text-destructive">{error}</p>:null}</div></ResponsiveDialog.Body>+ <ResponsiveDialog.Footer><div className="flex w-full gap-2">{draft.item?<Button variant="destructive" onClick={()=>void onDelete(draft.kind,draft.item!.id)} disabled={busy}>Delete</Button>:null}<div className="flex-1"/><Button variant="outline" onClick={onClose}>Cancel</Button><Button onClick={()=>void save()} disabled={busy}>{busy?"Saving…":"Save"}</Button></div></ResponsiveDialog.Footer></>;+}diff --git a/frontend/slices/assistant/components/organization-tree.tsx b/frontend/slices/assistant/components/organization-tree.tsxnew file mode 100644index 00000000..1943853b--- /dev/null+++ b/frontend/slices/assistant/components/organization-tree.tsx@@ -0,0 +1,27 @@+"use client";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import type { OrganizationChart, OrganizationSeat, OrganizationSeatRuntime } from "@/lib/contracts/organization";++type Props = { chart: OrganizationChart; runtime: OrganizationSeatRuntime[]; unitId: string; onEdit: (seat: OrganizationSeat) => void };+const statusClass: Record<OrganizationSeatRuntime["status"], string> = { ready: "bg-emerald-500", busy: "bg-amber-500", offline: "bg-muted-foreground", unresolved: "bg-destructive", unbound: "bg-sky-500", vacant: "bg-border" };+export function OrganizationTree({ chart, runtime, unitId, onEdit }: Props) {+ const seats = chart.seats.filter((seat) => !unitId || seat.unitId === unitId).sort((a, b) => a.sortOrder - b.sortOrder || a.title.localeCompare(b.title));+ const ids = new Set(seats.map((seat) => seat.id)), roots = seats.filter((seat) => !seat.reportsToSeatId || !ids.has(seat.reportsToSeatId));+ const byParent = new Map<string, OrganizationSeat[]>(); for (const seat of seats) if (seat.reportsToSeatId && ids.has(seat.reportsToSeatId)) byParent.set(seat.reportsToSeatId, [...(byParent.get(seat.reportsToSeatId) ?? []), seat]);+ const runtimeById = new Map(runtime.map((row) => [row.seatId, row])), unitById = new Map(chart.units.map((row) => [row.id, row]));+ if (!seats.length) return <div className="grid min-h-64 place-items-center rounded-xl border border-dashed text-sm text-muted-foreground">No seats in this unit yet.</div>;+ return <div className="min-w-max p-4"><div className="flex items-start justify-center gap-8">{roots.map((seat) => <Branch key={seat.id} seat={seat} childrenByParent={byParent} runtimeById={runtimeById} unitById={unitById} onEdit={onEdit} />)}</div></div>;+}+function Branch({ seat, childrenByParent, runtimeById, unitById, onEdit }: { seat: OrganizationSeat; childrenByParent: Map<string, OrganizationSeat[]>; runtimeById: Map<string, OrganizationSeatRuntime>; unitById: Map<string, { name: string }>; onEdit: (seat: OrganizationSeat) => void }) {+ const children = (childrenByParent.get(seat.id) ?? []).sort((a, b) => a.sortOrder - b.sortOrder || a.title.localeCompare(b.title)), state = runtimeById.get(seat.id);+ return <div className="flex min-w-[220px] flex-col items-center">+ <Button variant="ghost" className="h-auto w-[220px] whitespace-normal rounded-xl border bg-card p-0 text-left shadow-sm hover:bg-accent" onClick={() => onEdit(seat)}>+ <div className="w-full p-3"><div className="flex items-start gap-2"><span className={cn("mt-1 size-2.5 shrink-0 rounded-full", statusClass[state?.status ?? "vacant"])} /><div className="min-w-0 flex-1"><div className="font-semibold leading-tight">{seat.title}</div><div className="mt-0.5 text-[11px] text-muted-foreground">{seat.name}</div></div></div>+ <div className="mt-2 flex flex-wrap gap-1"><Badge variant="secondary" className="text-[9px]">{seat.role}</Badge><Badge variant="outline" className="text-[9px]">{unitById.get(seat.unitId)?.name ?? seat.unitId}</Badge><Badge variant="outline" className="text-[9px]">{seat.seatMode}</Badge>{seat.target.kind !== "none" ? <Badge variant="outline" className="max-w-[180px] truncate text-[9px]">{state?.label ?? seat.target.kind}</Badge> : null}</div>+ </div>+ </Button>+ {children.length ? <><div className="h-5 w-px bg-border"/><div className="relative flex items-start gap-4 pt-5 before:absolute before:left-[calc(50%-((100%-220px)/2))] before:right-[calc(50%-((100%-220px)/2))] before:top-0 before:h-px before:bg-border">{children.map((child) => <div key={child.id} className="relative before:absolute before:left-1/2 before:top-[-20px] before:h-5 before:w-px before:bg-border"><Branch seat={child} childrenByParent={childrenByParent} runtimeById={runtimeById} unitById={unitById} onEdit={onEdit}/></div>)}</div></> : null}+ </div>;+}diff --git a/frontend/slices/assistant/components/organization-view.tsx b/frontend/slices/assistant/components/organization-view.tsxnew file mode 100644index 00000000..081c6c20--- /dev/null+++ b/frontend/slices/assistant/components/organization-view.tsx@@ -0,0 +1,34 @@+"use client";+import { useCallback, useEffect, useState } from "react";+import { Building2, Plus, RefreshCw, Users } from "lucide-react";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { ScrollArea } from "@/components/ui/scroll-area";+import type { OrganizationSeat, OrganizationUnit } from "@/lib/contracts/organization";+import { getOrganization, mutateOrganization, type OrganizationPayload } from "../lib/organization-api";+import { OrganizationEditor } from "./organization-editor";+import { OrganizationTree } from "./organization-tree";++type Draft = { kind: "unit"; item?: OrganizationUnit } | { kind: "seat"; item?: OrganizationSeat } | null;+export function OrganizationView() {+ const [data, setData] = useState<OrganizationPayload | null>(null), [selected, setSelected] = useState("__all__"), [draft, setDraft] = useState<Draft>(null), [error, setError] = useState("");+ const load = useCallback(async () => { try { const next = await getOrganization(); setData(next); setSelected((current) => current === "__all__" || next.chart.units.some((u)=>u.id===current) ? current : "__all__"); setError(""); } catch (e) { setError(e instanceof Error ? e.message : "Organization unavailable"); } }, []);+ useEffect(() => {+ let alive = true;+ void getOrganization().then((next) => {+ if (!alive) return;+ setData(next); setSelected((current) => current === "__all__" || next.chart.units.some((u) => u.id === current) ? current : "__all__"); setError("");+ }).catch((e: unknown) => { if (alive) setError(e instanceof Error ? e.message : "Organization unavailable"); });+ return () => { alive = false; };+ }, []);+ const current = data?.chart.units.find((u) => u.id === selected);+ const mutate = async (action: string, record: Record<string, unknown>) => { if (!data) return; const key = action.startsWith("unit_") ? "unit" : "seat", next = await mutateOrganization({ action, expected_revision: data.chart.revision, [key]: record }); setData(next); };+ const remove = async (kind: "unit"|"seat", id: string) => { if (!data) return; const next = await mutateOrganization({ action: `${kind}_delete`, expected_revision: data.chart.revision, id }); setData(next); setDraft(null); if (kind === "unit" && id === selected) setSelected("__all__"); };+ if (!data) return <div className="grid h-full place-items-center p-6 text-sm text-muted-foreground">{error || "Loading organization…"}</div>;+ return <div className="grid h-full min-h-0 grid-cols-1 overflow-hidden lg:grid-cols-[240px_minmax(0,1fr)]">+ <aside className="flex min-h-0 flex-col border-b bg-card/20 lg:border-b-0 lg:border-r"><div className="flex items-center gap-2 p-3"><div><div className="font-semibold">Organization</div><div className="text-[11px] text-muted-foreground">{data.chart.units.length} units · {data.chart.seats.length} seats</div></div><Button size="icon" variant="ghost" className="ml-auto" onClick={()=>void load()}><RefreshCw className="size-3.5"/></Button><Button size="icon" onClick={()=>setDraft({kind:"unit"})}><Plus className="size-3.5"/></Button></div><ScrollArea className="max-h-40 flex-1 lg:max-h-none"><div className="space-y-1 p-2"><button className={`flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-sm ${selected==="__all__"?"bg-accent font-medium":"hover:bg-accent/60"}`} onClick={()=>setSelected("__all__")}><Users className="size-4 shrink-0"/><span className="min-w-0 flex-1 truncate">All organization</span><Badge variant="outline" className="text-[9px]">{data.chart.seats.length}</Badge></button>{data.chart.units.slice().sort((a,b)=>a.sortOrder-b.sortOrder||a.name.localeCompare(b.name)).map((unit)=><button key={unit.id} className={`flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-sm ${unit.id===selected?"bg-accent font-medium":"hover:bg-accent/60"}`} onClick={()=>setSelected(unit.id)}><Building2 className="size-4 shrink-0"/><span className="min-w-0 flex-1 truncate">{unit.name}</span><Badge variant="outline" className="text-[9px]">{data.chart.seats.filter((s)=>s.unitId===unit.id).length}</Badge></button>)}</div></ScrollArea></aside>+ <section className="flex min-h-0 min-w-0 flex-col"><div className="flex flex-wrap items-center gap-2 border-b px-4 py-3"><div className="min-w-0"><div className="flex items-center gap-2"><h2 className="truncate font-semibold">{current?.name ?? data.chart.name}</h2>{current?<Badge variant="secondary">{current.kind}</Badge>:null}</div><p className="text-xs text-muted-foreground">{current?.description || (selected==="__all__"?"Complete reporting hierarchy across every organization unit.":"Choose or create an organization unit.")}</p></div><div className="ml-auto flex gap-2">{current?<Button size="sm" variant="outline" onClick={()=>setDraft({kind:"unit",item:current})}>Edit unit</Button>:null}{current?<Button size="sm" onClick={()=>setDraft({kind:"seat"})}><Users className="mr-1 size-3.5"/>Add seat</Button>:null}</div></div>+ {error?<div className="border-b bg-destructive/10 px-4 py-2 text-xs text-destructive">{error}</div>:null}<ScrollArea className="flex-1"><div className="min-h-full min-w-full overflow-auto">{selected==="__all__"||current?<OrganizationTree chart={data.chart} runtime={data.runtime} unitId={current?.id??""} onEdit={(seat)=>setDraft({kind:"seat",item:seat})}/>:<div className="grid min-h-64 place-items-center text-sm text-muted-foreground">Create the first organization unit.</div>}</div></ScrollArea><div className="border-t px-4 py-2 text-[10px] text-muted-foreground">Seat status resolves existing project agents, durable local sessions, or registered A2A peers. Org metadata grants no extra capability.</div>+ </section><OrganizationEditor draft={draft} chart={data.chart} onClose={()=>setDraft(null)} onSave={mutate} onDelete={remove}/>+ </div>;+}diff --git a/frontend/slices/assistant/lib/navigation.test.ts b/frontend/slices/assistant/lib/navigation.test.tsindex df3a5f46..036cdcff 100644--- a/frontend/slices/assistant/lib/navigation.test.ts+++ b/frontend/slices/assistant/lib/navigation.test.ts@@ -1,13 +1,9 @@import { describe, expect, it } from "vitest";-import { assistantTabFromPayload } from "./navigation";+import { assistantRouteFromPayload } from "./navigation";-describe("assistant deep-link payload", () => {- it("opens the MCP activity tab for /assistant/mcp", () => {- expect(assistantTabFromPayload({ path: "/mcp" })).toBe("mcp");- });-- it("fails back to chat for absent or unknown paths", () => {- expect(assistantTabFromPayload(undefined)).toBe("chat");- expect(assistantTabFromPayload({ path: "/unknown" })).toBe("chat");+describe("assistant navigation", () => {+ it("deep-links Organization as a first-class Alfa tab", () => {+ expect(assistantRouteFromPayload({ path: "/organization" })).toEqual({ key: "/organization", tab: "organization" });+ expect(assistantRouteFromPayload({ path: "/organization/holding" }).tab).toBe("organization");});});diff --git a/frontend/slices/assistant/lib/navigation.ts b/frontend/slices/assistant/lib/navigation.tsindex 909a242a..9b0c4337 100644--- a/frontend/slices/assistant/lib/navigation.ts+++ b/frontend/slices/assistant/lib/navigation.ts@@ -1,6 +1,6 @@-export type AssistantTab = "chat" | "agents" | "skills" | "automations" | "mcp";+export type AssistantTab = "chat" | "agents" | "organization" | "skills" | "automations" | "mcp";-const TABS = new Set<AssistantTab>(["chat", "agents", "skills", "automations", "mcp"]);+const TABS = new Set<AssistantTab>(["chat", "agents", "organization", "skills", "automations", "mcp"]);export function assistantRouteFromPayload(payload: unknown): { key: string; tab: AssistantTab } {if (!payload || typeof payload !== "object") return { key: "", tab: "chat" };diff --git a/frontend/slices/assistant/lib/organization-api.ts b/frontend/slices/assistant/lib/organization-api.tsnew file mode 100644index 00000000..c455a8a4--- /dev/null+++ b/frontend/slices/assistant/lib/organization-api.ts@@ -0,0 +1,5 @@+import type { OrganizationChart, OrganizationSeatRuntime } from "@/lib/contracts/organization";+export type OrganizationPayload = { chart: OrganizationChart; runtime: OrganizationSeatRuntime[] };+async function json<T>(input: RequestInfo, init?: RequestInit): Promise<T> { const response = await fetch(input, { ...init, cache: "no-store", headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) } }); const body = await response.json().catch(() => ({})); if (!response.ok) throw new Error(typeof body.error === "string" ? body.error : `request failed (${response.status})`); return body as T; }+export const getOrganization = () => json<OrganizationPayload>("/api/v1/organization");+export const mutateOrganization = (body: Record<string, unknown>) => json<OrganizationPayload>("/api/v1/organization", { method: "POST", body: JSON.stringify(body) });diff --git a/frontend/slices/workflows/components/workflow-agent-seat-field.tsx b/frontend/slices/workflows/components/workflow-agent-seat-field.tsxnew file mode 100644index 00000000..f8fa357f--- /dev/null+++ b/frontend/slices/workflows/components/workflow-agent-seat-field.tsx@@ -0,0 +1,9 @@+"use client";+import { useEffect, useState } from "react";+import type { OrganizationChart } from "@/lib/contracts/organization";+const selectClass = "h-9 w-full rounded-md border bg-background px-2";+export function WorkflowAgentSeatField({ value, onChange }: { value: string; onChange: (value: string) => void }) {+ const [chart, setChart] = useState<OrganizationChart | null>(null);+ useEffect(() => { let alive = true; void fetch("/api/v1/organization?runtime=0", { cache: "no-store" }).then((r) => r.ok ? r.json() : Promise.reject()).then((body) => { if (alive) setChart(body.chart as OrganizationChart); }).catch(() => undefined); return () => { alive = false; }; }, []);+ return <label className="block space-y-1"><span className="text-muted-foreground">Organization seat</span><select className={selectClass} value={value} onChange={(e) => onChange(e.target.value)}><option value="">Direct project agent</option>{chart?.seats.slice().sort((a,b)=>a.title.localeCompare(b.title)).map((seat)=><option key={seat.id} value={seat.id}>{seat.title} · {seat.name}</option>)}</select><span className="block text-[10px] text-muted-foreground">When selected, execution target follows the Org Chart seat binding.</span></label>;+}diff --git a/frontend/slices/workflows/components/workflow-inspector.tsx b/frontend/slices/workflows/components/workflow-inspector.tsxindex 0bfa2894..3f800129 100644--- a/frontend/slices/workflows/components/workflow-inspector.tsx+++ b/frontend/slices/workflows/components/workflow-inspector.tsx@@ -9,6 +9,7 @@ import { Textarea } from "@/components/ui/textarea";import { Switch } from "@/components/ui/switch";import { openWindow } from "@/features/appshell";import { resolveNode } from "../lib/api";+import { WorkflowAgentSeatField } from "./workflow-agent-seat-field";const selectClass="h-9 w-full rounded-md border bg-background px-2";function Field({label,children}:{label:string;children:React.ReactNode}){return <label className="block space-y-1"><span className="text-muted-foreground">{label}</span>{children}</label>;}function number(value:unknown,fallback:number){const n=Number(value);return Number.isFinite(n)?n:fallback;}@@ -28,7 +29,8 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph<Field label="Type"><select className={selectClass} value={node.type} onChange={(e)=>patch({type:e.target.value as WorkflowGraphNodeType})}>{WORKFLOW_GRAPH_NODE_TYPES.map((type)=><option key={type} value={type}>{type}</option>)}</select></Field>{node.type==="schedule"&&<><Field label="Schedule mode"><select className={selectClass} value={String(node.config.mode??"interval")} onChange={(e)=>setConfig("mode",e.target.value)}><option value="interval">Interval</option><option value="cron">Cron</option></select></Field>{node.config.mode==="cron"?<Field label="Cron (5 fields)"><Input value={String(node.config.cron??"0 * * * *")} onChange={(e)=>setConfig("cron",e.target.value)}/></Field>:<Field label="Every minutes"><Input type="number" min={1} max={10080} value={number(node.config.everyMinutes,60)} onChange={(e)=>setConfig("everyMinutes",Number(e.target.value))}/></Field>}<Field label="Timezone override"><Input value={String(node.config.timezone??"")} placeholder={graph.metadata.timezone??"UTC"} onChange={(e)=>setConfig("timezone",e.target.value)}/></Field></>}{node.type==="webhook"&&<><Field label="Methods"><Input value={Array.isArray(node.config.methods)?node.config.methods.join(", "):"POST"} onChange={(e)=>setConfig("methods",e.target.value.split(",").map((v)=>v.trim().toUpperCase()).filter(Boolean))}/></Field><Field label="Response"><select className={selectClass} value={String(node.config.responseMode??"onReceived")} onChange={(e)=>setConfig("responseMode",e.target.value)}><option value="onReceived">202 immediately</option><option value="lastNode">Wait for output</option></select></Field><Field label="Auth variable"><Input value={String(node.config.authVariable??"")} placeholder="WEBHOOK_TOKEN (optional)" onChange={(e)=>e.target.value?setConfig("authVariable",e.target.value.toUpperCase()):removeConfig("authVariable")}/></Field><div className="rounded border p-2"><div className="break-all font-mono text-[10px]">/api/v1/workflows/webhook/{graph.id}/{node.id}</div><Button className="mt-2" size="sm" variant="outline" onClick={copyWebhook}><Copy className="mr-1 size-3"/>Copy URL</Button></div></>}- {(node.type==="project"||node.type==="folder"||node.type==="knowledge"||node.type==="agent"||node.type==="script"||node.type==="project_function"||node.type==="project_mcp"||node.type==="subflow")&&<Field label="Project"><Input value={String(node.config.project??graph.metadata.project??"")} placeholder="Canonical project id/name" onChange={(e)=>setConfig("project",e.target.value)}/></Field>}+ {node.type==="agent"&&<WorkflowAgentSeatField value={String(node.config.orgSeatId??"")} onChange={(value)=>value?setConfig("orgSeatId",value):removeConfig("orgSeatId")}/>}+ {(node.type==="project"||node.type==="folder"||node.type==="knowledge"||(node.type==="agent"&&!node.config.orgSeatId)||node.type==="script"||node.type==="project_function"||node.type==="project_mcp"||node.type==="subflow")&&<Field label="Project"><Input value={String(node.config.project??graph.metadata.project??"")} placeholder="Canonical project id/name" onChange={(e)=>setConfig("project",e.target.value)}/></Field>}{node.type==="folder"&&<Field label="Relative path"><Input value={String(node.config.path??".")} onChange={(e)=>setConfig("path",e.target.value)}/></Field>}{node.type==="tool"&&<Field label="MSO tool"><Input value={String(node.config.tool??"")} placeholder="project_get" onChange={(e)=>setConfig("tool",e.target.value)}/></Field>}{node.type==="integration"&&<>{["user","provider","connection","operation"].map((key)=><Field key={key} label={key[0]!.toUpperCase()+key.slice(1)}><Input value={String(node.config[key]??"")} onChange={(e)=>setConfig(key,e.target.value)}/></Field>)}</>}diff --git a/instrumentation.ts b/instrumentation.tsindex 1728a2a4..f7971bfd 100644--- a/instrumentation.ts+++ b/instrumentation.ts@@ -16,8 +16,8 @@ export async function register() {import("./lib/agent/session-archive").then(({ pruneAgentSessionArchives }) => pruneAgentSessionArchives()).catch(() => undefined),- Promise.all([import("./lib/workflow/graph-triggers"), import("./lib/mcp/tools")])- .then(([{ startWorkflowScheduler }, { TOOLS_BY_NAME }]) => startWorkflowScheduler((name) => TOOLS_BY_NAME.get(name)))+ Promise.all([import("./lib/workflow/graph-triggers"), import("./lib/mcp/tools"), import("./lib/mcp/capability-runtime")])+ .then(([{ startWorkflowScheduler }, { TOOLS_BY_NAME }, { msoCapabilityRuntime }]) => startWorkflowScheduler((name) => TOOLS_BY_NAME.get(name), msoCapabilityRuntime)).catch(() => undefined),]);// systemd liveness: when the unit sets WatchdogSec, systemd exposesdiff --git a/lib/agent/organization-runtime.ts b/lib/agent/organization-runtime.tsnew file mode 100644index 00000000..2e6403b9--- /dev/null+++ b/lib/agent/organization-runtime.ts@@ -0,0 +1,22 @@+import type { OrganizationSeat, OrganizationSeatRuntime } from "@/lib/contracts/organization";+import { listA2AAgents } from "@/lib/a2a";+import { listLocalAgents } from "./local-agent-directory";+import { getOrganizationChart } from "./organization-store";++export function organizationLocalAgentPrincipal(principal: string): string { return principal.startsWith("web:") ? `cli:${principal.slice(4)}` : principal; }++export async function resolveOrganizationSeat(ref: string): Promise<OrganizationSeat> {+ const chart = await getOrganizationChart(), q = String(ref || "").trim().toLowerCase(); if (!q) throw new Error("organization seat reference is required");+ const rows = chart.seats.filter((seat) => [seat.id, seat.name, seat.title, seat.role].some((v) => v.toLowerCase() === q));+ if (!rows.length) throw new Error(`organization seat not found: ${ref}`); if (rows.length > 1) throw new Error(`organization seat is ambiguous: ${rows.map((r) => r.id).join(", ")}`); return rows[0];+}+export async function organizationRuntime(principal?: string): Promise<OrganizationSeatRuntime[]> {+ const chart = await getOrganizationChart(); const localPrincipal = principal ? organizationLocalAgentPrincipal(principal) : undefined; const [locals, a2a] = await Promise.all([localPrincipal ? listLocalAgents(localPrincipal, { includeOffline: true }).catch(() => []) : Promise.resolve([]), listA2AAgents().catch(() => [])]);+ return chart.seats.map((seat) => { const target = seat.target; if (seat.state === "vacant") return { seatId: seat.id, targetKind: target.kind, status: "vacant" };+ if (target.kind === "none") return { seatId: seat.id, targetKind: target.kind, status: "unbound", detail: "no execution target" };+ if (seat.state === "inactive" || seat.seatMode === "inactive") return { seatId: seat.id, targetKind: target.kind, status: "offline", detail: "inactive seat" };+ if (target.kind === "project-agent") return { seatId: seat.id, targetKind: target.kind, status: "ready", label: target.project };+ if (target.kind === "local-agent") { const q = target.ref.toLowerCase(), row = locals.find((x) => [x.id, x.alias, x.name, x.label].some((v) => v.toLowerCase() === q)); return row ? { seatId: seat.id, targetKind: target.kind, status: row.status === "busy" ? "busy" : ["offline", "ended"].includes(row.status) ? "offline" : "ready", label: row.label, detail: row.status } : { seatId: seat.id, targetKind: target.kind, status: "unresolved", label: target.ref }; }+ const q = target.ref.toLowerCase(), row = a2a.find((x) => [x.id, x.alias, x.card.name].some((v) => v.toLowerCase() === q)); return row ? { seatId: seat.id, targetKind: target.kind, status: "ready", label: row.alias } : { seatId: seat.id, targetKind: target.kind, status: "unresolved", label: target.ref };+ });+}diff --git a/lib/agent/organization-schema.ts b/lib/agent/organization-schema.tsnew file mode 100644index 00000000..b56154fb--- /dev/null+++ b/lib/agent/organization-schema.ts@@ -0,0 +1,70 @@+import type {+ OrganizationChart,+ OrganizationSeat,+ OrganizationSeatMode,+ OrganizationSeatState,+ OrganizationTarget,+ OrganizationUnit,+ OrganizationUnitKind,+} from "@/lib/contracts/organization";++const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;+const KEY = /^[a-z0-9][a-z0-9._-]{0,63}$/;+const UNIT_KINDS = new Set<OrganizationUnitKind>(["holding", "company", "division", "team", "client", "other"]);+const SEAT_MODES = new Set<OrganizationSeatMode>(["permanent", "on_demand", "inactive"]);+const SEAT_STATES = new Set<OrganizationSeatState>(["active", "vacant", "inactive"]);+const text = (v: unknown, max = 160) => String(v ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim().slice(0, max);+const required = (v: unknown, field: string, max = 160) => { const out = text(v, max); if (!out) throw new Error(`${field} is required`); return out; };+const id = (v: unknown, field: string) => { const out = required(v, field, 128); if (!ID.test(out)) throw new Error(`${field} is invalid`); return out; };+const order = (v: unknown) => Number.isFinite(Number(v)) ? Math.max(-10000, Math.min(10000, Math.trunc(Number(v)))) : 0;++function target(v: unknown): OrganizationTarget {+ if (!v || typeof v !== "object" || Array.isArray(v)) return { kind: "none" };+ const row = v as Record<string, unknown>, kind = String(row.kind || "none");+ if (kind === "none") return { kind: "none" };+ if (kind === "project-agent") return { kind, project: required(row.project, "target.project", 4096) };+ if (kind === "local-agent" || kind === "a2a") return { kind, ref: required(row.ref, "target.ref", 4096) };+ throw new Error("organization target kind is invalid");+}++export function parseOrganizationUnit(v: unknown, now = new Date().toISOString()): OrganizationUnit {+ if (!v || typeof v !== "object" || Array.isArray(v)) throw new Error("organization unit must be an object");+ const row = v as Partial<OrganizationUnit>, kind = String(row.kind || "other") as OrganizationUnitKind;+ if (!UNIT_KINDS.has(kind)) throw new Error("organization unit kind is invalid");+ const key = required(row.key, "unit.key", 64).toLowerCase(); if (!KEY.test(key)) throw new Error("unit.key is invalid");+ const parentUnitId = row.parentUnitId ? id(row.parentUnitId, "unit.parentUnitId") : undefined;+ return { id: id(row.id, "unit.id"), key, name: required(row.name, "unit.name", 120), kind,+ status: row.status === "inactive" ? "inactive" : "active", ...(parentUnitId ? { parentUnitId } : {}),+ ...(text(row.description, 1000) ? { description: text(row.description, 1000) } : {}), sortOrder: order(row.sortOrder),+ createdAt: text(row.createdAt, 64) || now, updatedAt: text(row.updatedAt, 64) || now };+}++export function parseOrganizationSeat(v: unknown, now = new Date().toISOString()): OrganizationSeat {+ if (!v || typeof v !== "object" || Array.isArray(v)) throw new Error("organization seat must be an object");+ const row = v as Partial<OrganizationSeat>, seatMode = String(row.seatMode || "permanent") as OrganizationSeatMode,+ state = String(row.state || "active") as OrganizationSeatState;+ if (!SEAT_MODES.has(seatMode) || !SEAT_STATES.has(state)) throw new Error("organization seat state/mode is invalid");+ const reportsToSeatId = row.reportsToSeatId ? id(row.reportsToSeatId, "seat.reportsToSeatId") : undefined;+ const responsibilities = Array.isArray(row.responsibilities) ? row.responsibilities.map((x) => text(x, 240)).filter(Boolean).slice(0, 32) : [];+ return { id: id(row.id, "seat.id"), unitId: id(row.unitId, "seat.unitId"), name: required(row.name, "seat.name", 120),+ title: required(row.title, "seat.title", 160), role: required(row.role, "seat.role", 80), state, seatMode,+ ...(reportsToSeatId ? { reportsToSeatId } : {}), ...(text(row.description, 1000) ? { description: text(row.description, 1000) } : {}),+ responsibilities, target: target(row.target), sortOrder: order(row.sortOrder), createdAt: text(row.createdAt, 64) || now, updatedAt: text(row.updatedAt, 64) || now };+}++function assertNoCycles(ids: string[], parent: (id: string) => string | undefined, label: string) {+ const known = new Set(ids);+ for (const start of ids) { const seen = new Set<string>(); let current: string | undefined = start;+ while (current) { if (seen.has(current)) throw new Error(`${label} cycle detected`); seen.add(current); const next = parent(current); if (next && !known.has(next)) throw new Error(`${label} parent not found`); current = next; } }+}++export function validateOrganizationChart(chart: Omit<OrganizationChart, "revision">): void {+ if (chart.units.length > 256 || chart.seats.length > 1024) throw new Error("organization chart limit reached");+ const unitIds = chart.units.map((u) => u.id), seatIds = chart.seats.map((s) => s.id);+ if (new Set(unitIds).size !== unitIds.length || new Set(seatIds).size !== seatIds.length) throw new Error("organization ids must be unique");+ const keys = chart.units.map((u) => u.key); if (new Set(keys).size !== keys.length) throw new Error("organization unit keys must be unique");+ const unitById = new Map(chart.units.map((u) => [u.id, u])); const seatById = new Map(chart.seats.map((s) => [s.id, s]));+ for (const seat of chart.seats) { if (!unitById.has(seat.unitId)) throw new Error(`seat unit not found: ${seat.name}`); if (seat.reportsToSeatId === seat.id) throw new Error("seat cannot report to itself"); }+ assertNoCycles(unitIds, (x) => unitById.get(x)?.parentUnitId, "organization unit");+ assertNoCycles(seatIds, (x) => seatById.get(x)?.reportsToSeatId, "organization reporting");+}diff --git a/lib/agent/organization-store.test.ts b/lib/agent/organization-store.test.tsnew file mode 100644index 00000000..a5f56f00--- /dev/null+++ b/lib/agent/organization-store.test.ts@@ -0,0 +1,35 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdtemp, rm, stat } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++let dir = "";+beforeEach(async () => { dir = await mkdtemp(path.join(os.tmpdir(), "mso-org-")); 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(); });++async function store() { return import("./organization-store"); }++describe("organization store", () => {+ it("persists units/seats privately with revision checks and reporting guards", async () => {+ const api = await store();+ let chart = await api.getOrganizationChart();+ expect(chart.units).toEqual([]); expect(chart.seats).toEqual([]);+ chart = await api.upsertOrganizationUnit(chart.revision, { id: "unit_root", key: "root", name: "Root", kind: "holding", status: "active", sortOrder: 0 });+ chart = await api.upsertOrganizationSeat(chart.revision, { id: "seat_ceo", unitId: "unit_root", name: "CEO", title: "Chief Executive Officer", role: "ceo", state: "active", seatMode: "permanent", target: { kind: "none" }, responsibilities: [] });+ chart = await api.upsertOrganizationSeat(chart.revision, { id: "seat_cto", unitId: "unit_root", name: "CTO", title: "Chief Technology Officer", role: "cto", state: "active", seatMode: "on_demand", reportsToSeatId: "seat_ceo", target: { kind: "project-agent", project: "mso" }, responsibilities: ["Technology"] });+ await expect(api.upsertOrganizationSeat(chart.revision, { ...chart.seats.find((s) => s.id === "seat_ceo"), reportsToSeatId: "seat_cto" })).rejects.toThrow(/cycle/i);+ await expect(api.deleteOrganizationSeat(chart.revision, "seat_ceo")).rejects.toThrow(/direct reports/i);+ await expect(api.upsertOrganizationUnit("stale", { id: "unit_other", key: "other", name: "Other", kind: "team" })).rejects.toThrow(/revision changed/i);+ expect((await stat(api.ORGANIZATION_STORE_PATH)).mode & 0o077).toBe(0);+ });++ it("keeps active seats without an executor distinct from vacant seats", async () => {+ const api = await store(); let chart = await api.getOrganizationChart();+ chart = await api.upsertOrganizationUnit(chart.revision, { id: "unit_a", key: "a", name: "A", kind: "company" });+ chart = await api.upsertOrganizationSeat(chart.revision, { id: "seat_active", unitId: "unit_a", name: "Active", title: "CEO", role: "ceo", state: "active", seatMode: "permanent", target: { kind: "none" } });+ chart = await api.upsertOrganizationSeat(chart.revision, { id: "seat_vacant", unitId: "unit_a", name: "Vacant", title: "CFO", role: "cfo", state: "vacant", seatMode: "permanent", target: { kind: "none" } });+ const runtime = await (await import("./organization-runtime")).organizationRuntime();+ expect(runtime.find((x) => x.seatId === "seat_active")?.status).toBe("unbound");+ expect(runtime.find((x) => x.seatId === "seat_vacant")?.status).toBe("vacant");+ });+});diff --git a/lib/agent/organization-store.ts b/lib/agent/organization-store.tsnew file mode 100644index 00000000..7fc9470d--- /dev/null+++ b/lib/agent/organization-store.ts@@ -0,0 +1,39 @@+import { createHash, randomUUID } from "node:crypto";+import { constants as fsConstants, promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+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";++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;+const hash = (v: unknown) => createHash("sha256").update(JSON.stringify(v)).digest("hex");+function base(): OrganizationChart { const updatedAt = new Date(0).toISOString(); const row = { version: 1 as const, name: "Organization", updatedAt, units: [], seats: [] }; return { ...row, revision: hash(row) }; }+function materialize(name: string, units: OrganizationUnit[], seats: OrganizationSeat[]): OrganizationChart {+ const row = { version: 1 as const, name: String(name || "Organization").trim().slice(0, 120) || "Organization", updatedAt: new Date().toISOString(), units, seats };+ validateOrganizationChart(row); return { ...row, revision: hash(row) };+}+async function readUnlocked(): Promise<OrganizationChart> {+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;+ try { handle = await fs.open(ORGANIZATION_STORE_PATH, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW); const stat = await handle.stat();+ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_BYTES || (stat.mode & 0o077) !== 0) throw new Error("organization store is unsafe");+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("organization store owner mismatch");+ const raw = JSON.parse(await handle.readFile("utf8")) as Partial<OrganizationChart>; if (raw.version !== 1 || !Array.isArray(raw.units) || !Array.isArray(raw.seats)) throw new Error("organization store shape is invalid");+ const units = raw.units.map((v) => parseOrganizationUnit(v)); const seats = raw.seats.map((v) => parseOrganizationSeat(v)); const chart = materialize(String(raw.name || "Organization"), units, seats);+ return { ...chart, updatedAt: String(raw.updatedAt || chart.updatedAt), revision: typeof raw.revision === "string" ? raw.revision : chart.revision };+ } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return base(); throw error; }+ finally { await handle?.close().catch(() => undefined); }+}+async function writeUnlocked(chart: OrganizationChart) { const body = JSON.stringify(chart, null, 2) + "\n"; if (Buffer.byteLength(body) > MAX_BYTES) throw new Error("organization store exceeds 2 MiB");+ const dir = path.dirname(ORGANIZATION_STORE_PATH); await fs.mkdir(dir, { recursive: true, mode: 0o700 }); await fs.chmod(dir, 0o700).catch(() => undefined);+ const temp = `${ORGANIZATION_STORE_PATH}.${randomUUID()}.tmp`; await fs.writeFile(temp, body, { flag: "wx", mode: 0o600 }); try { await fs.rename(temp, ORGANIZATION_STORE_PATH); await fs.chmod(ORGANIZATION_STORE_PATH, 0o600); } finally { await fs.unlink(temp).catch(() => undefined); } }+export async function getOrganizationChart() { return structuredClone(await readUnlocked()); }+async function mutate(expectedRevision: string, fn: (chart: OrganizationChart) => OrganizationChart) { return withSecurityStoreLock(ORGANIZATION_STORE_PATH, async () => { const current = await readUnlocked(); if (current.revision !== expectedRevision) throw new Error("organization revision changed; refresh before editing"); const next = fn(current); await writeUnlocked(next); return structuredClone(next); }); }+const touch = (row: Record<string, unknown>, previous?: { createdAt?: string }) => ({ ...row, createdAt: previous?.createdAt || row.createdAt || new Date().toISOString(), updatedAt: new Date().toISOString() });+export async function upsertOrganizationUnit(expectedRevision: string, raw: Record<string, unknown>) { return mutate(expectedRevision, (chart) => { const id = typeof raw.id === "string" && raw.id ? raw.id : `unit_${randomUUID()}`; const previous = chart.units.find((u) => u.id === id); const unit = parseOrganizationUnit(touch({ ...raw, id }, previous)); const units = [...chart.units.filter((u) => u.id !== id), unit]; return materialize(chart.name, units, chart.seats); }); }+export async function upsertOrganizationSeat(expectedRevision: string, raw: Record<string, unknown>) { return mutate(expectedRevision, (chart) => { const id = typeof raw.id === "string" && raw.id ? raw.id : `seat_${randomUUID()}`; const previous = chart.seats.find((s) => s.id === id); const seat = parseOrganizationSeat(touch({ ...raw, id }, previous)); const seats = [...chart.seats.filter((s) => s.id !== id), seat]; return materialize(chart.name, chart.units, seats); }); }+export async function deleteOrganizationUnit(expectedRevision: string, id: string) { return mutate(expectedRevision, (chart) => { if (chart.units.some((u) => u.parentUnitId === id) || chart.seats.some((s) => s.unitId === id)) throw new Error("organization unit still has children or seats"); return materialize(chart.name, chart.units.filter((u) => u.id !== id), chart.seats); }); }+export async function deleteOrganizationSeat(expectedRevision: string, id: string) { return mutate(expectedRevision, (chart) => { if (chart.seats.some((s) => s.reportsToSeatId === id)) throw new Error("organization seat still has direct reports"); return materialize(chart.name, chart.units, chart.seats.filter((s) => s.id !== id)); }); }+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); }); }diff --git a/lib/contracts/audit.ts b/lib/contracts/audit.tsindex 21afa577..2796967e 100644--- a/lib/contracts/audit.ts+++ b/lib/contracts/audit.ts@@ -24,6 +24,7 @@ export type AuditAction =| "workflow.cancel"| "workflow.finish"| "agent.session"+ | "agent.organization"| "agent.message"| "agent.subagent"| "agent.memory"diff --git a/lib/contracts/organization.ts b/lib/contracts/organization.tsnew file mode 100644index 00000000..d498f0de--- /dev/null+++ b/lib/contracts/organization.ts@@ -0,0 +1,57 @@+export type OrganizationUnitKind = "holding" | "company" | "division" | "team" | "client" | "other";+export type OrganizationStatus = "active" | "inactive";+export type OrganizationSeatMode = "permanent" | "on_demand" | "inactive";+export type OrganizationSeatState = "active" | "vacant" | "inactive";++export type OrganizationTarget =+ | { kind: "none" }+ | { kind: "project-agent"; project: string }+ | { kind: "local-agent"; ref: string }+ | { kind: "a2a"; ref: string };++export type OrganizationUnit = {+ id: string;+ key: string;+ name: string;+ kind: OrganizationUnitKind;+ status: OrganizationStatus;+ parentUnitId?: string;+ description?: string;+ sortOrder: number;+ createdAt: string;+ updatedAt: string;+};++export type OrganizationSeat = {+ id: string;+ unitId: string;+ name: string;+ title: string;+ role: string;+ state: OrganizationSeatState;+ seatMode: OrganizationSeatMode;+ reportsToSeatId?: string;+ description?: string;+ responsibilities: string[];+ target: OrganizationTarget;+ sortOrder: number;+ createdAt: string;+ updatedAt: string;+};++export type OrganizationChart = {+ version: 1;+ name: string;+ revision: string;+ updatedAt: string;+ units: OrganizationUnit[];+ seats: OrganizationSeat[];+};++export type OrganizationSeatRuntime = {+ seatId: string;+ targetKind: OrganizationTarget["kind"];+ status: "ready" | "busy" | "offline" | "unresolved" | "unbound" | "vacant";+ label?: string;+ detail?: string;+};diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.tsindex 537b5181..b1172b6f 100644--- a/lib/mcp/tool-contract.ts+++ b/lib/mcp/tool-contract.ts@@ -48,6 +48,7 @@ const TITLES: Record<string, string> = {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_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",a2a_agent_discover: "Discover A2A Agent", a2a_agents_list: "List A2A Agents", a2a_message_send: "Send A2A Message",cloudflare_dns_upsert: "Upsert Cloudflare DNS", hostinger_dns_upsert: "Upsert Hostinger DNS",diff --git a/lib/mcp/tools-block.ts b/lib/mcp/tools-block.tsindex 544272c7..7f906ed5 100644--- a/lib/mcp/tools-block.ts+++ b/lib/mcp/tools-block.ts@@ -60,16 +60,13 @@ const ACTION_SCHEMA = {} as const;export const BLOCK_OUTPUT_SCHEMA = {+ // Output is normalized by normalizeBlock() below. Keep the advertised result+ // envelope intentionally compact: duplicating every input constraint here adds+ // several KiB to tools/list without adding a runtime safety boundary.type: "object",properties: {- kind: { type: "string", enum: ["validation", "crud", "action"] },- title: { type: "string" },- description: { type: "string" },- status: { type: "string", enum: ["neutral", "pending", "success", "warning", "error"] },- fields: { type: "array", items: FIELD_SCHEMA },- checks: { type: "array", items: CHECK_SCHEMA },- outputs: { type: "array", items: OUTPUT_SCHEMA },- actions: { type: "array", items: ACTION_SCHEMA },+ kind: { type: "string" }, title: { type: "string" }, description: { type: "string" }, status: { type: "string" },+ fields: { type: "array" }, checks: { type: "array" }, outputs: { type: "array" }, actions: { type: "array" },},required: ["kind", "title", "status", "fields", "checks", "outputs", "actions"],additionalProperties: false,diff --git a/lib/mcp/tools-organization.test.ts b/lib/mcp/tools-organization.test.tsnew file mode 100644index 00000000..33e8718c--- /dev/null+++ b/lib/mcp/tools-organization.test.ts@@ -0,0 +1,13 @@+import { describe, expect, it } from "vitest";+import { ORGANIZATION_TOOLS } from "./tools-organization";++describe("organization MCP surface", () => {+ const tools = new Map(ORGANIZATION_TOOLS.map((tool) => [tool.name, tool]));+ it("keeps chart reads separate from revision-checked mutations", () => {+ expect(tools.get("organization_chart")?.scope).toBe("read");+ expect(tools.get("organization_chart")?.annotations?.readOnlyHint).toBe(true);+ expect(tools.get("organization_manage")?.scope).toBe("write");+ expect(tools.get("organization_manage")?.inputSchema.required).toEqual(expect.arrayContaining(["action", "expected_revision"]));+ expect(JSON.stringify(tools.get("organization_manage")?.inputSchema)).not.toMatch(/password|token|credential/i);+ });+});diff --git a/lib/mcp/tools-organization.ts b/lib/mcp/tools-organization.tsnew file mode 100644index 00000000..9f3faf3e--- /dev/null+++ b/lib/mcp/tools-organization.ts@@ -0,0 +1,34 @@+import { deleteOrganizationSeat, deleteOrganizationUnit, getOrganizationChart, replaceOrganization, upsertOrganizationSeat, upsertOrganizationUnit } from "@/lib/agent/organization-store";+import { organizationRuntime, resolveOrganizationSeat } from "@/lib/agent/organization-runtime";+import { type McpTool, S, str } from "./tool-kit";++export const ORGANIZATION_TOOLS: McpTool[] = [+ {+ name: "organization_chart", title: "Organization Chart", scope: "read",+ description: "Read the private MSO organization hierarchy: units, reporting seats, execution bindings and live target status. This is organization/context metadata, not a workflow definition and never contains credentials.",+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }, limit: { key: "organization.read", max: 60, windowMs: 60_000 },+ chatgptDescription: "Read private organization units, seats, reporting lines and target status.",+ inputSchema: S({ seat: { type: "string" }, runtime: { type: "boolean" } }),+ run: async (a, context) => {+ const chart = await getOrganizationChart(), runtime = a.runtime === false ? [] : await organizationRuntime(context.principal);+ if (typeof a.seat === "string" && a.seat.trim()) return { chart: { name: chart.name, revision: chart.revision }, seat: await resolveOrganizationSeat(a.seat), runtime };+ return { chart, runtime };+ },+ },+ {+ name: "organization_manage", title: "Manage Organization", scope: "write",+ description: "Create/update/delete organization units and seats with optimistic revision checks. Seat targets reference existing project agents, local sessions, or A2A peers; no credentials or hidden context are copied.",+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }, audit: { action: "agent.organization", targetArg: "action" }, limit: { key: "organization.write", max: 30, windowMs: 60_000 },+ chatgptDescription: "Mutate organization units/seats using the current revision.",+ inputSchema: S({ action: { type: "string" }, expected_revision: { type: "string" }, id: { type: "string" }, data: { type: "object" } }, ["action", "expected_revision"]),+ run: async (a) => {+ 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 (action === "replace") return { chart: await replaceOrganization(revision, data as never) };+ throw new Error("unsupported organization action");+ },+ },+];diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.tsindex 8a0cbc5a..f08c9a3b 100644--- a/lib/mcp/tools.ts+++ b/lib/mcp/tools.ts@@ -13,6 +13,7 @@ import { INTEGRATION_TOOLS } from "./tools-integrations";import { LEARNING_TOOLS } from "./tools-learning";import { LOCAL_AGENT_TOOLS } from "./tools-local-agents";import { OPERATOR_DASHBOARD_TOOLS } from "./tools-operator-dashboard";+import { ORGANIZATION_TOOLS } from "./tools-organization";import { POWER_TOOLS } from "./tools-power";import { PROJECT_EXPERIENCE_TOOLS } from "./tools-project-experience";import { PROJECT_MCP_TOOLS } from "./tools-project-mcp";@@ -25,4 +26,4 @@ import { BLOCK_TOOLS, SURFACE_TOOLS } from "./tools-ui";import type { McpTool } from "./tool-kit";import { MUTATE_TOOLS } from "./tools-mutate";-export const TOOLS: McpTool[] = [...FLOW_TOOLS, ...AGENT_OPEN_TOOLS, ...PROJECT_ASSET_TOOLS, ...PROJECT_MCP_MANAGE_TOOLS, ...SESSION_ARTIFACT_TOOLS, ...READ_TOOLS, ...FILE_TRANSFER_READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...BLOCK_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...INTEGRATION_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));+export const TOOLS: McpTool[] = [...FLOW_TOOLS, ...AGENT_OPEN_TOOLS, ...PROJECT_ASSET_TOOLS, ...PROJECT_MCP_MANAGE_TOOLS, ...SESSION_ARTIFACT_TOOLS, ...READ_TOOLS, ...FILE_TRANSFER_READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...ORGANIZATION_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...BLOCK_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...INTEGRATION_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));diff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.tsindex 29ff3e34..b68223cd 100644--- a/lib/workflow/graph-runtime.ts+++ b/lib/workflow/graph-runtime.ts@@ -10,6 +10,7 @@ import { graphObject } from "./graph-schema";import { bindLoopItem, bindWorkflowValue } from "./graph-bindings";import { executeFlowNode, workflowItems, type FlowNodeResult } from "./graph-flow-nodes";import { workflowVariableValues } from "./variables";+import { organizationLocalAgentPrincipal, resolveOrganizationSeat } from "@/lib/agent/organization-runtime";type Resolver = (name: string) => CapabilityTool | undefined;type NodeExecutionResult = FlowNodeResult;@@ -84,7 +85,19 @@ async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graphif (node.type === "project_function") { if (!project || typeof config.name !== "string") throw new Error("project_function node requires project and name"); return { output: await callTool("project_function_call", { project, name: config.name, input: graphObject(config.input) ? config.input : {}, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Project function ${config.name} completed.` }; }if (node.type === "project_mcp") { if (!project || typeof config.server !== "string" || typeof config.tool !== "string") throw new Error("project_mcp node requires project/server/tool"); return { output: await callTool("project_mcp_call", { project, server: config.server, tool: config.tool, arguments: graphObject(config.arguments) ? config.arguments : {}, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Project MCP ${config.server}.${config.tool} completed.` }; }if (node.type === "script") { if (!project || typeof config.script_id !== "string") throw new Error("script node requires project and script_id"); return { output: await callTool("project_script_run", { project, script_id: config.script_id, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Script ${config.script_id} completed.` }; }- if (node.type === "agent") { if (!project || typeof config.message !== "string") throw new Error("agent node requires project and message"); const args: Record<string, unknown> = { project, message: config.message, wait: config.wait !== false, plan_mode: Boolean(config.plan_mode), max_scope: ["read", "write", "exec"].includes(String(config.max_scope)) ? config.max_scope : "write" }; if (context.workflowId) args.workflow_id = context.workflowId; return { output: await callTool("project_agent_run", args, context, resolve), log: "Project agent action completed." }; }+ if (node.type === "agent") {+ if (typeof config.message !== "string" || !config.message.trim()) throw new Error("agent node requires message");+ if (typeof config.orgSeatId === "string" && config.orgSeatId) {+ const seat = await resolveOrganizationSeat(config.orgSeatId), target = seat.target;+ if (seat.state !== "active" || seat.seatMode === "inactive") throw new Error(`organization seat ${seat.title} is not active`);+ if (target.kind === "project-agent") { const args: Record<string, unknown> = { project: target.project, message: config.message, wait: config.wait !== false, plan_mode: Boolean(config.plan_mode), max_scope: ["read", "write", "exec"].includes(String(config.max_scope)) ? config.max_scope : "write" }; if (context.workflowId) args.workflow_id = context.workflowId; return { output: await callTool("project_agent_run", args, context, resolve), log: `Organization seat ${seat.title} routed to project agent.` }; }+ if (target.kind === "local-agent") return { output: await callTool("local_agent_request", { target: target.ref, objective: config.message, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, { ...context, principal: organizationLocalAgentPrincipal(principal) }, resolve), log: `Organization seat ${seat.title} routed to local agent.` };+ if (target.kind === "a2a") return { output: await callTool("a2a_handoff", { target: target.ref, objective: config.message, return_immediately: config.wait === false, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Organization seat ${seat.title} routed to A2A agent.` };+ throw new Error(`organization seat ${seat.title} has no execution target`);+ }+ if (!project) throw new Error("agent node requires project or organization seat");+ const args: Record<string, unknown> = { project, message: config.message, wait: config.wait !== false, plan_mode: Boolean(config.plan_mode), max_scope: ["read", "write", "exec"].includes(String(config.max_scope)) ? config.max_scope : "write" }; if (context.workflowId) args.workflow_id = context.workflowId; return { output: await callTool("project_agent_run", args, context, resolve), log: "Project agent action completed." };+ }if (node.type === "subflow") {if (typeof config.workflowId === "string" && config.workflowId) {const principal = context.principal ?? context.actor; if (!principal) throw new Error("workflow subflow requires principal");diff --git a/lib/workflow/graph-triggers.ts b/lib/workflow/graph-triggers.tsindex 780070b1..c57efb9a 100644--- a/lib/workflow/graph-triggers.ts+++ b/lib/workflow/graph-triggers.ts@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";import { createAgentSession } from "@/lib/agent/session-store";import type { WorkflowGraphNode } from "@/lib/contracts/workflow-graph";import type { CapabilityTool } from "@/lib/capabilities/tool";+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";import { listWorkflowGraphTriggerSources } from "./graph-store";import { scheduleBucket } from "./schedule";import { startWorkflowGraph, workflowGraphRunId } from "./graph-engine";@@ -10,12 +11,12 @@ import { readWorkflowGraphRun } from "./graph-run-store";const g=globalThis as typeof globalThis&{__msoWorkflowScheduler?:ReturnType<typeof setInterval>;__msoWorkflowSchedulerBusy?:boolean};function key(parts:string[]){return `trigger:${createHash("sha256").update(parts.join(":" )).digest("hex").slice(0,48)}`;}type Resolver=(name:string)=>CapabilityTool|undefined;-async function runScheduled(principal:string,owner:string,graph:Awaited<ReturnType<typeof listWorkflowGraphTriggerSources>>[number]["graph"],node:WorkflowGraphNode,bucket:string,resolve:Resolver){+async function runScheduled(principal:string,owner:string,graph:Awaited<ReturnType<typeof listWorkflowGraphTriggerSources>>[number]["graph"],node:WorkflowGraphNode,bucket:string,resolve:Resolver,capabilities?:CapabilityRuntime){const idempotency=key([graph.id,node.id,bucket]);if(await readWorkflowGraphRun(owner,workflowGraphRunId(owner,idempotency)))return;const session=await createAgentSession(principal,"cli",{title:`Schedule: ${graph.name}`,titleSource:"auto"});- const context={principal,actor:principal,sessionId:session.id,scope:"exec" as const};+ const context={principal,actor:principal,sessionId:session.id,scope:"exec" as const,...(capabilities?{capabilities}:{})};await startWorkflowGraph(graph,{trigger:{type:"schedule",nodeId:node.id,bucket,at:new Date().toISOString()}},idempotency,context,resolve,principal,{type:"schedule",nodeId:node.id,receivedAt:new Date().toISOString()});}-export async function tickWorkflowScheduler(resolve:Resolver,now=new Date()){if(g.__msoWorkflowSchedulerBusy)return;g.__msoWorkflowSchedulerBusy=true;try{const sources=await listWorkflowGraphTriggerSources();let started=0;for(const source of sources){for(const node of source.graph.nodes.filter((row)=>row.type==="schedule"&&!row.disabled)){if(started>=50)return;let bucket:string|null=null;try{bucket=scheduleBucket(node,now,source.graph.metadata.timezone||"UTC");}catch{continue;}if(!bucket)continue;await runScheduled(source.principal,source.owner,source.graph,node,bucket,resolve).catch(()=>undefined);started+=1;}}}finally{g.__msoWorkflowSchedulerBusy=false;}}-export function startWorkflowScheduler(resolve:Resolver){if(process.env.NODE_ENV==="test"||g.__msoWorkflowScheduler)return;void tickWorkflowScheduler(resolve);g.__msoWorkflowScheduler=setInterval(()=>void tickWorkflowScheduler(resolve),15_000);g.__msoWorkflowScheduler.unref();}+export async function tickWorkflowScheduler(resolve:Resolver,now=new Date(),capabilities?:CapabilityRuntime){if(g.__msoWorkflowSchedulerBusy)return;g.__msoWorkflowSchedulerBusy=true;try{const sources=await listWorkflowGraphTriggerSources();let started=0;for(const source of sources){for(const node of source.graph.nodes.filter((row)=>row.type==="schedule"&&!row.disabled)){if(started>=50)return;let bucket:string|null=null;try{bucket=scheduleBucket(node,now,source.graph.metadata.timezone||"UTC");}catch{continue;}if(!bucket)continue;await runScheduled(source.principal,source.owner,source.graph,node,bucket,resolve,capabilities).catch(()=>undefined);started+=1;}}}finally{g.__msoWorkflowSchedulerBusy=false;}}+export function startWorkflowScheduler(resolve:Resolver,capabilities?:CapabilityRuntime){if(process.env.NODE_ENV==="test"||g.__msoWorkflowScheduler)return;void tickWorkflowScheduler(resolve,new Date(),capabilities);g.__msoWorkflowScheduler=setInterval(()=>void tickWorkflowScheduler(resolve,new Date(),capabilities),15_000);g.__msoWorkflowScheduler.unref();}export async function findActiveWebhookSource(graphId:string,nodeId:string){for(const source of await listWorkflowGraphTriggerSources()){if(source.graph.id!==graphId)continue;const node=source.graph.nodes.find((row)=>row.id===nodeId&&row.type==="webhook"&&!row.disabled);if(node)return{...source,node};}return null;}diff --git a/lib/workflow/node-catalog.ts b/lib/workflow/node-catalog.tsindex bb993089..c427249d 100644--- a/lib/workflow/node-catalog.ts+++ b/lib/workflow/node-catalog.ts@@ -15,7 +15,7 @@ export const WORKFLOW_NODE_CATALOG:WorkflowNodeCatalogItem[]=[{type:"project_mcp",title:"Project MCP",category:"Actions",description:"Call a project-owned MCP tool.",defaults:{}},{type:"integration",title:"Integration",category:"Actions",description:"Execute through an existing MSO integration connection; credentials stay outside the graph.",defaults:{}},{type:"script",title:"Script",category:"Actions",description:"Run a learned RASMIC script.",defaults:{}},- {type:"agent",title:"Agent",category:"AI",description:"Run a focused project agent action.",defaults:{wait:true,max_scope:"write"}},+ {type:"agent",title:"Agent",category:"AI",description:"Run an organization seat or focused project agent action.",defaults:{wait:true,max_scope:"write"}},{type:"subflow",title:"Subflow",category:"Flow",description:"Run an existing project flow.",defaults:{}},{type:"project",title:"Project",category:"Context",description:"Resolve canonical project identity/path at runtime.",defaults:{}},{type:"folder",title:"Folder",category:"Context",description:"Resolve a real folder inside a canonical project.",defaults:{path:"."}},diff --git a/lib/workflow/organization-agent-routing.test.ts b/lib/workflow/organization-agent-routing.test.tsnew file mode 100644index 00000000..649af5cd--- /dev/null+++ b/lib/workflow/organization-agent-routing.test.ts@@ -0,0 +1,52 @@+import { afterAll, describe, expect, it, vi } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import type { CapabilityTool } from "@/lib/capabilities/tool";++vi.mock("@/lib/capabilities/execute", () => ({ executeCapabilityCall: async ({ tool, args, context }: { tool: CapabilityTool; args: Record<string, unknown>; context: never }) => {+ try { return { kind: "success", result: await tool.run(args, context) }; } catch (error) { return { kind: "error", message: error instanceof Error ? error.message : String(error) }; }+} }));+const dir = await mkdtemp(path.join(os.tmpdir(), "mso-org-routing-"));+process.env.OS_AGENT_SESSIONS_DIR = path.join(dir, "sessions");+process.env.OS_ORGANIZATION_STORE = path.join(dir, "organization.json");+const org = await import("@/lib/agent/organization-store");+const graphs = await import("./graph-store");+const engine = await import("./graph-engine");+afterAll(async () => { delete process.env.OS_ORGANIZATION_STORE; await rm(dir, { recursive: true, force: true }); });++describe("workflow organization seat routing", () => {+ it("routes an Agent node through the seat's project-agent binding", async () => {+ let chart = await org.getOrganizationChart();+ chart = await org.upsertOrganizationUnit(chart.revision, { id: "unit_product", key: "product", name: "Product", kind: "division" });+ chart = await org.upsertOrganizationSeat(chart.revision, { id: "seat_cto", unitId: "unit_product", name: "CTO", title: "CTO", role: "cto", state: "active", seatMode: "on_demand", target: { kind: "project-agent", project: "project-from-org" } });+ const graph = await graphs.createWorkflowGraph("org-route-owner", { name: "Org route", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [+ { id: "start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },+ { id: "agent", name: "CTO", type: "agent", position: { x: 120, y: 0 }, config: { orgSeatId: "seat_cto", message: "Ship it", wait: true } },+ { id: "out", name: "Out", type: "output", position: { x: 240, y: 0 }, config: { value: { ok: true } } },+ ], edges: [{ id: "a", source: "start", target: "agent" }, { id: "b", source: "agent", target: "out" }] });+ let received: Record<string, unknown> | null = null;+ const tool: CapabilityTool = { name: "project_agent_run", description: "fixture", scope: "exec", inputSchema: { type: "object", properties: {} }, run: async (args) => { received = args; return { ok: true }; } };+ const context = { principal: "org-route-owner", actor: "org-route-owner", sessionId: "session", scope: "exec" as const };+ const started = await engine.startWorkflowGraph(graph, {}, "org-seat-once", context, (name) => name === tool.name ? tool : undefined);+ const done = await engine.workflowGraphRunStatus("org-route-owner", started.id, 5000);+ expect(done.state).toBe("completed");+ expect(received).toMatchObject({ project: "project-from-org", message: "Ship it", wait: true });+ expect(done.nodes.find((node) => node.id === "agent")?.logs.join(" ")).toContain("Organization seat CTO routed to project agent");+ });+ it("bridges a Web workflow principal to the same device's native Local Agent namespace", async () => {+ let chart = await org.getOrganizationChart();+ chart = await org.upsertOrganizationSeat(chart.revision, { id: "seat_local", unitId: "unit_product", name: "Operator", title: "Operator", role: "operator", state: "active", seatMode: "on_demand", target: { kind: "local-agent", ref: "milo" } });+ const graph = await graphs.createWorkflowGraph("web:device-1", { name: "Local route", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [+ { id: "start-local", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },+ { id: "agent-local", name: "Operator", type: "agent", position: { x: 120, y: 0 }, config: { orgSeatId: "seat_local", message: "Inspect" } },+ ], edges: [{ id: "local-e", source: "start-local", target: "agent-local" }] });+ let seenPrincipal = "";+ const tool: CapabilityTool = { name: "local_agent_request", description: "fixture", scope: "exec", inputSchema: { type: "object", properties: {} }, run: async (_args, ctx) => { seenPrincipal = ctx.principal ?? ""; return { ok: true }; } };+ const context = { principal: "web:device-1", actor: "web:device-1", sessionId: "session", scope: "exec" as const };+ const started = await engine.startWorkflowGraph(graph, {}, "org-local-once", context, (name) => name === tool.name ? tool : undefined);+ const done = await engine.workflowGraphRunStatus("web:device-1", started.id, 5000);+ expect(done.state).toBe("completed"); expect(seenPrincipal).toBe("cli:device-1");+ });++});diff --git a/scripts/cli/commands-state.sh b/scripts/cli/commands-state.shindex f1a0b1d3..9ad55738 100755--- a/scripts/cli/commands-state.sh+++ b/scripts/cli/commands-state.sh@@ -53,6 +53,7 @@ case "$cmd" injget "/api/v1/local-agents?inbox=1&session=$(enc "$session_id")$([ "$include" = "--all" ] && printf '&includeRead=1')" ;;*) die "usage: mso $U_agents" ;;esac ;;+ org) source "$ROOT/scripts/cli/organization.sh"; run_org "$@" ;;a2a)sub="${1:-list}"; shift || truecase "$sub" indiff --git a/scripts/cli/commands.sh b/scripts/cli/commands.shindex cf806920..fcac1160 100755--- a/scripts/cli/commands.sh+++ b/scripts/cli/commands.sh@@ -42,6 +42,7 @@ U_cockpit="cockpit [project] | cockpit show [project] | cockpit search <query…U_threads="threads list|show <id>|save <json>|rm <id>"U_agent_sessions="agent-sessions list [limit]|show <id>|create [title]"U_agents="agents list [current-session-id]|send <source-session-id> <target> <message> [message|task]|inbox <session-id> [--all]"+U_org="org show|unit-upsert <revision> <JSON|@file>|seat-upsert <revision> <JSON|@file>|unit-delete <revision> <id>|seat-delete <revision> <id>|replace <revision> <JSON|@file>"U_a2a="a2a list|state|sessions|spawn <source-session> <objective> [title]|inbox <session>|discover <url>|add <url> [alias]|rm <target>|send <target> <message> [--wait]|stream <target> <message>|task <target> <taskId> [history]|cancel <target> <taskId>|handoff <target> <objective> [context] [--wait]|local sessions|local handoff <session> <objective>|local spawn <sourceSession> <objective> [title]|local inbox <session>|auth list [target]|auth add <target> [label] [bearer|api-key|oauth2]|auth use <target> <credentialId|none>|auth rm <credentialId>|inbound list|inbound create [label] [read|write|exec]|inbound rm <tokenId>"U_memory="memory list|add <text>|rm <id>"U_config="config show|set <json>|key <provider>|style <off|caveman|ponytail>|rm <provider>"@@ -94,7 +95,7 @@ mso_cli_main() {mso_cmd_host "$cmd" "$@" ;;agent|chat|model|setup|onboard|provider|providers|integrations|flow|workflow|gateway|web|camoufox|apps|mapp|term)mso_cmd_runtime "$cmd" "$@" ;;- ai|cockpit|threads|agent-sessions|agents|a2a|memory|config|prefs|models|skills|changelog|stock)+ ai|cockpit|threads|agent-sessions|agents|org|a2a|memory|config|prefs|models|skills|changelog|stock)mso_cmd_state "$cmd" "$@" ;;devices|device|approve|revoke|oauth|mcp|audit|whoami|login|logout|service|build|deploy|update|reset|uninstall|crud|api|completion)mso_cmd_admin "$cmd" "$@" ;;diff --git a/scripts/cli/organization.sh b/scripts/cli/organization.shnew file mode 100644index 00000000..1cf36156--- /dev/null+++ b/scripts/cli/organization.sh@@ -0,0 +1,19 @@+#!/usr/bin/env bash+# Owner-private Organization CLI. Same API as Alfa → Organization and MCP.+run_org() {+ local sub="${1:-show}" revision input action key body id+ shift || true+ case "$sub" in+ show|list) jget "/api/v1/organization" ;;+ unit-upsert|seat-upsert|replace)+ revision="${1:?revision}"; input="${2:?JSON or @file}"; case "$input" in @*) input=$(cat -- "${input#@}") ;; esac+ action="${sub//-/_}"; key="${sub%%-*}"+ if [ "$sub" = replace ]; then body=$(jq -n --arg action "$action" --arg revision "$revision" --argjson chart "$input" '{action:$action,expected_revision:$revision,chart:$chart}')+ else body=$(jq -n --arg action "$action" --arg revision "$revision" --arg key "$key" --argjson data "$input" '{action:$action,expected_revision:$revision} + {($key):$data}'); fi+ jpost "/api/v1/organization" "$body" ;;+ unit-delete|seat-delete)+ revision="${1:?revision}"; id="${2:?id}"; action="${sub//-/_}"+ jpost "/api/v1/organization" "$(jq -n --arg action "$action" --arg revision "$revision" --arg id "$id" '{action:$action,expected_revision:$revision,id:$id}')" ;;+ *) die "usage: mso $U_org" ;;+ esac+}diff --git a/scripts/e2e/organization.mjs b/scripts/e2e/organization.mjsnew file mode 100644index 00000000..dad704e7--- /dev/null+++ b/scripts/e2e/organization.mjs@@ -0,0 +1,62 @@+import { expect } from "@playwright/test";++async function call(page, route, body) {+ return page.evaluate(async ([route, body]) => {+ const init = body ? { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) } : {};+ const response = await fetch(route, init);+ return { status: response.status, body: await response.json() };+ }, [route, body]);+}++export async function organizationJourney(page, fixture) {+ let response = await call(page, "/api/v1/organization");+ expect(response.status).toBe(200);+ let revision = response.body.chart.revision;++ response = await call(page, "/api/v1/organization", {+ action: "unit_upsert", expected_revision: revision,+ unit: { id: "e2e-holding", key: "e2e-holding", name: "E2E Holding", kind: "holding", status: "active", sortOrder: 0 },+ });+ expect(response.status).toBe(200); revision = response.body.chart.revision;+ response = await call(page, "/api/v1/organization", {+ action: "unit_upsert", expected_revision: revision,+ unit: { id: "e2e-product", key: "e2e-product", name: "E2E Product", kind: "division", status: "active", parentUnitId: "e2e-holding", sortOrder: 1 },+ });+ expect(response.status).toBe(200); revision = response.body.chart.revision;+ response = await call(page, "/api/v1/organization", {+ action: "seat_upsert", expected_revision: revision,+ seat: { id: "e2e-ceo", unitId: "e2e-holding", name: "E2E CEO", title: "Chief Executive Officer", role: "ceo", state: "active", seatMode: "permanent", target: { kind: "none" }, responsibilities: ["Direction"] },+ });+ expect(response.status).toBe(200); revision = response.body.chart.revision;+ response = await call(page, "/api/v1/organization", {+ action: "seat_upsert", expected_revision: revision,+ seat: { id: "e2e-cto", unitId: "e2e-product", name: "E2E CTO", title: "Chief Technology Officer", role: "cto", state: "active", seatMode: "on_demand", reportsToSeatId: "e2e-ceo", target: { kind: "none" }, responsibilities: ["Technology"] },+ });+ expect(response.status).toBe(200);++ await page.goto(fixture.base + "/assistant/organization");+ await expect(page.getByRole("button", { name: "Organization", exact: true })).toBeVisible();+ await expect(page.getByText("All organization", { exact: true })).toBeVisible();+ await expect(page.getByText("Chief Executive Officer", { exact: true })).toBeVisible();+ await expect(page.getByText("Chief Technology Officer", { exact: true })).toBeVisible();+ await expect(page.getByText("E2E Holding", { exact: true }).first()).toBeVisible();+ await expect(page.getByText("E2E Product", { exact: true }).first()).toBeVisible();+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);++ await page.getByRole("button", { name: /Chief Technology Officer/ }).click();+ await expect(page.getByRole("heading", { name: "Edit seat" })).toBeVisible();+ await page.getByLabel("Execution target").selectOption("project-agent");+ await page.getByRole("textbox", { name: "Project", exact: true }).fill("fixture-project");+ await page.getByRole("button", { name: "Save", exact: true }).click();+ await expect(page.getByText("fixture-project", { exact: true })).toBeVisible();++ response = await call(page, "/api/v1/organization");+ expect(response.status).toBe(200); revision = response.body.chart.revision;+ expect(response.body.chart.seats.find(seat => seat.id === "e2e-cto")?.target).toEqual({ kind: "project-agent", project: "fixture-project" });+ for (const [action, id] of [["seat_delete", "e2e-cto"], ["seat_delete", "e2e-ceo"], ["unit_delete", "e2e-product"], ["unit_delete", "e2e-holding"]]) {+ response = await call(page, "/api/v1/organization", { action, expected_revision: revision, id });+ expect(response.status).toBe(200); revision = response.body.chart.revision;+ }+ expect((await call(page, "/api/v1/organization")).body.chart.units).toHaveLength(0);+ console.log("PASS Organization hierarchy, cross-unit reporting, responsive chart, seat edit/routing and cleanup");+}diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjsindex aebe930a..6a15ac91 100644--- a/scripts/e2e/release.mjs+++ b/scripts/e2e/release.mjs@@ -5,6 +5,7 @@ import { chromium, expect } from "@playwright/test";import AxeBuilder from "@axe-core/playwright";import { mcpOwnerJourneys, mcpPublicJourney, settingsAccessibilityJourney } from "./mcp-settings.mjs";import { automationJourney } from "./automation.mjs";+import { organizationJourney } from "./organization.mjs";import { releaseFixture } from "./release-fixture.mjs";execFileSync(process.execPath, ["scripts/e2e/mcp-page.mjs"], { stdio: "inherit" });@@ -116,6 +117,7 @@ try {expect((await call("/api/v1/fs/list?path=" + encodeURIComponent(fixture.dir))).status).toBe(200);await mcpOwnerJourneys(page, fixture);await automationJourney(page, fixture);+ await organizationJourney(page, fixture);await fixture.setRole("viewer");expect((await call("/api/v1/agent-sessions?view=monitor")).status).toBe(403);expect((await call("/api/v1/integrations")).status).toBe(403);diff --git a/scripts/mso-org-cli-contract.test.ts b/scripts/mso-org-cli-contract.test.tsnew file mode 100644index 00000000..df446ad0--- /dev/null+++ b/scripts/mso-org-cli-contract.test.ts@@ -0,0 +1,13 @@+import { readFile } from "node:fs/promises";+import { describe, expect, it } from "vitest";++describe("organization CLI contract", () => {+ it("routes org through the canonical organization API with revision checks", async () => {+ const state = await readFile("scripts/cli/commands-state.sh", "utf8"), org = await readFile("scripts/cli/organization.sh", "utf8"), commands = await readFile("scripts/cli/commands.sh", "utf8"), bin = await readFile("bin/mso", "utf8");+ expect(state).toContain('org)');+ expect(org).toContain('/api/v1/organization');+ expect(org).toContain('expected_revision');+ expect(commands).toContain('U_org=');+ expect(bin).toContain('org *');+ });+});