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 internal project flows with callable CRUD
Rahman784fdec54175
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 1cabf0fc..8a67ebb3 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "mso",- "version": "0.2.19",+ "version": "0.2.20","description": "Operate MSO projects, workflows, VPS resources, integrations, deployments, and MCP capabilities through reusable safety-first skills.","author": {"name": "MSO"diff --git a/app/api/v1/organization/route.ts b/app/api/v1/organization/route.tsindex 87d9bcf6..06935ba1 100644--- a/app/api/v1/organization/route.ts+++ b/app/api/v1/organization/route.ts@@ -1,10 +1,11 @@+import { isOrganizationFlowAction } from "@/lib/contracts/organization-flow";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 { deleteOrganizationSeat, deleteOrganizationUnit, mutateOrganizationFlow, getOrganizationChart, replaceOrganization, upsertOrganizationSeat, upsertOrganizationUnit } from "@/lib/agent/organization-store";import { organizationRuntime, resolveOrganizationSeat } from "@/lib/agent/organization-runtime";export const runtime = "nodejs";@@ -25,7 +26,7 @@ export async function GET(req: NextRequest) {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 || "");+ const body = await readSetupJson(req, 2 * 1024 * 1024), 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;@@ -33,6 +34,7 @@ export async function POST(req: NextRequest) {else if (action === "seat_upsert") chart = await upsertOrganizationSeat(revision, body.seat as Record<string, unknown>);else if (action === "unit_delete") chart = await deleteOrganizationUnit(revision, String(body.id || ""));else if (action === "seat_delete") chart = await deleteOrganizationSeat(revision, String(body.id || ""));+ else if (isOrganizationFlowAction(action)) chart = await mutateOrganizationFlow(revision, action, (body.data ?? {}) as Record<string, unknown>);else if (action === "replace") { if (!roleAtLeast(session.context.role, "owner")) return fail("owner_required", 403); chart = await replaceOrganization(revision, body.chart as never); }else throw new Error("unknown organization action");void audit({ action: "agent.organization", actor: session.context.session.device_id, target: action, detail: `organization ${action}` });diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 1cfb3aad..0d0af9e8 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -4,6 +4,12 @@Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;this is the *what*, and it is what Settings → About shows as “What's new”.+## 2026-09-18++**Added**++- `organization` add internal project flows with callable CRUD+## 2026-09-17**Added**diff --git a/docs/ORGANIZATION.md b/docs/ORGANIZATION.mdindex 619cb08b..b1295ec7 100644--- a/docs/ORGANIZATION.md+++ b/docs/ORGANIZATION.md@@ -125,3 +125,47 @@ Every mutation uses the current chart revision. Refresh and reconcile if another- `organization_manage` — revision-checked unit/seat mutation.The MCP tools expose the same store and do not create another organization database.+++## Internal project flow++Every unit may own an optional `projectFlow` in the same private organization store.+The outer organization card remains a two-line summary. Opening a unit defaults to+**Projects**; **Seats** retains the existing reporting/execution-binding view.+Project-flow cards are context nodes, not seats or executable Workflow Graph nodes.++The flow stores a title, multiline notes, nodes and directed labeled connections.+Node kinds are `project`, `activity`, `group`, and `note`; status defaults to+`unconfirmed`, with explicit `planned`, `active`, `blocked`, and `done` alternatives.+`projectRef` is a reference only and grants no authority. Clicking a node opens its+details; editing, dragging positions, connecting and deleting persist through the API.+Search and focus limit the visible context without changing stored data. Long source+notes live inside the unit's Notes editor, not on the overview card.++The existing `organization_chart` read tool returns each unit's `projectFlow`.+The existing `organization_manage` write tool supports the following actions; all+require `expected_revision` and `data.unitId` (the exact owning unit id):++| Action | Additional data |+|---|---|+| `flow_update` | Optional `title`, `notes`; preserves nodes/edges |+| `flow_replace` | Complete `flow: {version:1,title,notes,nodes,edges}` |+| `flow_node_upsert` | `node: {id?,title,kind?,status?,summary?,notes?,position?:{x,y},projectRef?}` |+| `flow_node_delete` | `id`; also removes that node's incident edges |+| `flow_edge_upsert` | `edge: {id?,source,target,label?}` |+| `flow_edge_delete` | `id` |++An existing node/edge id permits a partial update. Missing ids are generated server-side.+Edges must reference nodes in the same unit. Node and edge ids are stable and unique+within their unit; unknown units, dangling edges, invalid positions and stale revisions+fail without writing. Unit edits from older clients preserve an omitted `projectFlow`.+The full-chart `replace` action remains an explicit destructive snapshot replacement.++The HTTP route uses `{action,expected_revision,data}` for flow operations. CLI equivalents+are `mso org flow-node-upsert <revision> <JSON|@file>` and the other hyphenated action names.+UI, CLI and MCP share the same revision-checked mutation handler, not separate databases.+Limits: 200 nodes, 400 edges per unit; 64,000-character flow notes; 12,000-character node+notes; 2 MiB HTTP body and total private store. Over-limit notes are rejected, not clipped.+No flow operation executes a command, fetches a source reference, assigns an agent,+or promotes unconfirmed facts. Existing OAuth scope, device role and audit guards remain.+Public names are unchanged; rescan clients to see the expanded action enum/descriptions.diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 5b152582..861292ac 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,12 @@+## 2026-09-18 — Organization-scoped project flow++- The organization overview previously rendered long context notes directly inside unit cards. Keep overview descriptions clamped and put projects, activities, relationships and long notes inside the selected unit instead.+- Add a generic optional `projectFlow` to the private organization store with bounded schema, stable node/edge ids, same-unit edge validation, atomic revision-checked CRUD and legacy-unit-edit preservation. Public source contains no operator organization data.+- Projects/Seats navigation preserves reporting and execution bindings. Project-flow nodes support details, editing, persistent drag positions, search, focus and explicit connections/deletion; project references do not execute anything.+- Extend the existing organization API/MCP/CLI contract rather than creating a second store or executable workflow. Expand only the organization HTTP body allowance; integration setup retains its original default bound.+- Full verify passed (3,056 tests across 511 files), production build passed, and the isolated browser journey verifies node CRUD, visible directional edges, persistent drags, long notes, real MCP mutation, stale-revision and scope refusal, and desktop/portrait/landscape layouts. The complete release E2E and eager bundle budget also pass. Canvas measurements are preserved separately from server-owned data.++## 2026-09-17 — Lock the native build bootstrap without touching the runtime treeThe complete PR/branch audit found open Scorecard finding #136 in the user-localdiff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.mdindex 088772a6..0cdcf467 100644--- a/docs/generated/MCP-CATALOG.md+++ b/docs/generated/MCP-CATALOG.md@@ -4,13 +4,13 @@## Full MSO catalog-<!-- mcp-toolset: server=1.15.1 version=2026.09.17.2 tools=111 read=54 write=35 exec=22 -->+<!-- mcp-toolset: server=1.15.1 version=2026.09.18.1 tools=111 read=54 write=35 exec=22 -->| Fact | Current source value ||---|---:|| MCP server | `1.15.1` |-| Toolset | `2026.09.17.2` |-| Toolset changed at | `2026-09-17T17:50:58+07:00` |+| Toolset | `2026.09.18.1` |+| Toolset changed at | `2026-09-18T07:18:00+07:00` || Transport tools | **113** || Model/operator tools | **111** || Read | **54** |@@ -145,7 +145,7 @@## ChatGPT model profile-<!-- mcp-chatgpt-profile: server=1.15.1 version=2026.09.17.2 tools=111 read=54 write=35 exec=22 app-only=2 total=113 -->+<!-- mcp-chatgpt-profile: server=1.15.1 version=2026.09.18.1 tools=111 read=54 write=35 exec=22 app-only=2 total=113 -->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.diff --git a/frontend/slices/organization/components/organization-canvas.tsx b/frontend/slices/organization/components/organization-canvas.tsxindex 70acdf7f..2c5f549b 100644--- a/frontend/slices/organization/components/organization-canvas.tsx+++ b/frontend/slices/organization/components/organization-canvas.tsx@@ -22,8 +22,8 @@ const statusClass: Record<OrganizationSeatRuntime["status"], string> = {function UnitCard({ data, selected }: NodeProps<UnitNode>) {return <div className={cn("relative w-[230px] rounded-xl border bg-card p-3 shadow-sm", selected && "ring-2 ring-ring")}><Handle type="target" position={Position.Top} id="input" className="!size-2 !border-0 !bg-muted-foreground/50"/><Handle type="source" position={Position.Bottom} id="output" className="!size-2 !border-0 !bg-muted-foreground/50"/>- <div className="flex items-start gap-2"><Building2 className="mt-0.5 size-4 shrink-0 text-muted-foreground"/><div className="min-w-0 flex-1"><div className="truncate text-sm font-semibold">{data.unit.name}</div><div className="mt-0.5 text-[10px] text-muted-foreground">{data.unit.description || data.unit.kind}</div></div></div>- <div className="mt-2 flex gap-1"><Badge variant="secondary" className="text-[9px]">{data.unit.kind}</Badge><Badge variant="outline" className="text-[9px]">{data.seatCount} seats</Badge></div>+ <div className="flex items-start gap-2"><Building2 className="mt-0.5 size-4 shrink-0 text-muted-foreground"/><div className="min-w-0 flex-1"><div className="truncate text-sm font-semibold">{data.unit.name}</div><div className="mt-0.5 line-clamp-2 break-words text-[10px] text-muted-foreground">{data.unit.description || data.unit.kind}</div></div></div>+ <div className="mt-2 flex gap-1"><Badge variant="secondary" className="text-[9px]">{data.unit.kind}</Badge><Badge variant="outline" className="text-[9px]">{data.seatCount} seats</Badge>{data.unit.projectFlow?.nodes.length ? <Badge variant="outline" className="text-[9px]">{data.unit.projectFlow.nodes.length} nodes</Badge> : null}</div></div>;}function SeatCard({ data, selected }: NodeProps<SeatNode>) {diff --git a/frontend/slices/organization/components/organization-editor.tsx b/frontend/slices/organization/components/organization-editor.tsxindex ecc12d8f..dd0ad27b 100644--- a/frontend/slices/organization/components/organization-editor.tsx+++ b/frontend/slices/organization/components/organization-editor.tsx@@ -6,7 +6,7 @@ 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 Draft = { kind: "unit"; item?: OrganizationUnit } | { kind: "seat"; item?: OrganizationSeat; unitId?: string };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>;@@ -16,7 +16,7 @@ export function OrganizationEditor({ draft, chart, onClose, onSave, onDelete }:}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 [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 ?? (draft?.kind === "seat" ? draft.unitId : undefined) ?? 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>diff --git a/frontend/slices/organization/components/organization-view.tsx b/frontend/slices/organization/components/organization-view.tsxindex 8338982c..02c194ac 100644--- a/frontend/slices/organization/components/organization-view.tsx+++ b/frontend/slices/organization/components/organization-view.tsx@@ -8,12 +8,15 @@ import type { OrganizationSeat, OrganizationUnit } from "@/lib/contracts/organizimport { getOrganization, mutateOrganization, type OrganizationPayload } from "../lib/organization-api";import { OrganizationCanvas } from "./organization-canvas";import { OrganizationEditor } from "./organization-editor";+import { ProjectFlow } from "./project-flow";+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";-type Draft = { kind: "unit"; item?: OrganizationUnit } | { kind: "seat"; item?: OrganizationSeat } | null;+type Draft = { kind: "unit"; item?: OrganizationUnit } | { kind: "seat"; item?: OrganizationSeat; unitId?: string } | null;export function OrganizationView() {const [data, setData] = useState<OrganizationPayload | null>(null);const [selectedUnit, setSelectedUnit] = useState("__all__");+ const [tab, setTab] = useState("projects");const [selectedSeatId, setSelectedSeatId] = useState<string | null>(null);const [draft, setDraft] = useState<Draft>(null);const [error, setError] = useState("");@@ -61,7 +64,7 @@ export function OrganizationView() {if (kind === "unit" && id === selectedUnit) setSelectedUnit("__all__");if (kind === "seat" && id === selectedSeatId) setSelectedSeatId(null);};- const chooseUnit = (id: string) => { setSelectedUnit(id); setSelectedSeatId(null); };+ const chooseUnit = (id: string) => { setSelectedUnit(id); setSelectedSeatId(null); setTab("projects"); };if (!data) return <div className="grid h-full place-items-center p-6 text-sm text-muted-foreground">{error || "Loading organization…"}</div>;@@ -97,13 +100,18 @@ export function OrganizationView() {<p className="mt-0.5 hidden max-w-2xl text-[11px] leading-snug text-muted-foreground @min-[520px]:line-clamp-2">{currentUnit?.description || "Open a unit to inspect its reporting graph. Pan, zoom, fit, and use the minimap like a workflow canvas."}</p></div></div>- <div className="flex shrink-0 gap-1">{currentUnit ? <Button size="sm" variant="outline" className="h-8 px-2" onClick={() => setDraft({ kind: "unit", item: currentUnit })}><Pencil className="size-3 @min-[480px]:mr-1"/><span className="hidden @min-[480px]:inline">Unit</span></Button> : null}{currentUnit ? <Button size="sm" className="h-8 px-2" onClick={() => setDraft({ kind: "seat" })}><Users className="size-3 @min-[480px]:mr-1"/><span className="hidden @min-[480px]:inline">Seat</span></Button> : null}</div>+ <div className="flex shrink-0 gap-1">{currentUnit ? <Button size="sm" variant="outline" className="h-8 px-2" onClick={() => setDraft({ kind: "unit", item: currentUnit })}><Pencil className="size-3 @min-[480px]:mr-1"/><span className="hidden @min-[480px]:inline">Unit</span></Button> : null}{currentUnit ? <Button size="sm" className="h-8 px-2" onClick={() => setDraft({ kind: "seat", unitId: currentUnit.id })}><Users className="size-3 @min-[480px]:mr-1"/><span className="hidden @min-[480px]:inline">Seat</span></Button> : null}</div></div>{error ? <div className="shrink-0 border-b bg-destructive/10 px-4 py-2 text-xs text-destructive">{error}</div> : null}- <div className="relative min-h-0 min-w-0 flex-1 overflow-hidden">+ {currentUnit ? <Tabs key={currentUnit.id} className="flex min-h-0 flex-1 flex-col gap-0">+ <TabsList className="mx-3 my-2 w-fit shrink-0"><TabsTrigger active={tab === "projects"} onClick={() => setTab("projects")}>Projects</TabsTrigger><TabsTrigger active={tab === "seats"} onClick={() => setTab("seats")}>Seats</TabsTrigger></TabsList>+ {tab === "projects" ? <div className="relative min-h-0 flex-1 overflow-hidden"><ProjectFlow unit={currentUnit} onSave={async (action, record) => { const next = await mutateOrganization({ action, expected_revision: data.chart.revision, data: record }); setData(next); }}/></div> : <div className="relative min-h-0 flex-1 overflow-hidden"><OrganizationCanvas chart={data.chart} runtime={data.runtime} unitId={currentUnit?.id ?? ""} selectedSeatId={selectedSeatId} onUnitSelect={chooseUnit} onSeatSelect={(seat) => setSelectedSeatId(seat?.id ?? null)} onSeatOpen={(seat) => setDraft({ kind: "seat", item: seat })}/>{selectedSeat ? <SeatInspector seat={selectedSeat} runtimeLabel={selectedRuntime?.label} runtimeStatus={selectedRuntime?.status} onClose={() => setSelectedSeatId(null)} onEdit={() => setDraft({ kind: "seat", item: selectedSeat })}/> : null}- </div>+ </div>}+ </Tabs> : <div className="relative min-h-0 min-w-0 flex-1 overflow-hidden">+ <OrganizationCanvas chart={data.chart} runtime={data.runtime} unitId="" selectedSeatId={null} onUnitSelect={chooseUnit} onSeatSelect={() => {}} onSeatOpen={() => {}}/>+ </div>}<div className="hidden shrink-0 border-t px-3 py-1.5 text-[10px] leading-snug text-muted-foreground @min-[700px]:block">V select · H pan · Space temporary pan · F fit · wheel/pinch zoom. Seat execution status remains capability-safe and does not grant authority.</div></section><OrganizationEditor draft={draft} chart={data.chart} onClose={() => setDraft(null)} onSave={save} onDelete={remove}/>diff --git a/frontend/slices/organization/components/project-flow-editor.tsx b/frontend/slices/organization/components/project-flow-editor.tsxnew file mode 100644index 00000000..a77efaa3--- /dev/null+++ b/frontend/slices/organization/components/project-flow-editor.tsx@@ -0,0 +1,52 @@+"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 { ORGANIZATION_FLOW_KINDS, ORGANIZATION_FLOW_STATUSES, type OrganizationFlowAction, type OrganizationFlowEdge, type OrganizationFlowNode, type OrganizationProjectFlow } from "@/lib/contracts/organization-flow";++export type FlowDraft = { kind: "node"; node?: OrganizationFlowNode } | { kind: "edge"; edge?: OrganizationFlowEdge } | { kind: "notes" };+type Props = { draft: FlowDraft | null; flow: OrganizationProjectFlow; onClose: () => void; onSave: (action: OrganizationFlowAction, data: Record<string, unknown>) => Promise<void> };+const selectClass = "h-10 w-full rounded-md border bg-background px-2 text-sm";+const Field = ({ label, children }: { label: string; children: React.ReactNode }) => <label className="grid gap-1.5 text-xs"><span className="text-muted-foreground">{label}</span>{children}</label>;+export function ProjectFlowEditor(props: Props) {+ return <ResponsiveDialog open={!!props.draft} onOpenChange={(open) => !open && props.onClose()} size="lg" mobileVariant="drawer-bottom"><EditorBody key={props.draft ? JSON.stringify(props.draft) : "closed"} {...props}/></ResponsiveDialog>;+}+function EditorBody({ draft, flow, onClose, onSave }: Props) {+ const item = draft?.kind === "node" ? draft.node : draft?.kind === "edge" ? draft.edge : undefined;+ const [form, setForm] = useState<Record<string, string>>((): Record<string, string> => draft?.kind === "notes" ? { title: flow.title, notes: flow.notes }+ : draft?.kind === "edge" ? { source: draft.edge?.source ?? flow.nodes[0]?.id ?? "", target: draft.edge?.target ?? flow.nodes[1]?.id ?? "", label: draft.edge?.label ?? "" }+ : { title: draft?.node?.title ?? "", kind: draft?.node?.kind ?? "project", status: draft?.node?.status ?? "unconfirmed", summary: draft?.node?.summary ?? "", notes: draft?.node?.notes ?? "", projectRef: draft?.node?.projectRef ?? "" });+ const [busy, setBusy] = useState(false), [error, setError] = useState(""), [confirmDelete, setConfirmDelete] = useState(false);+ if (!draft) return null;+ const set = (key: string, value: string) => setForm((prev) => ({ ...prev, [key]: value }));+ const run = async (remove = false) => {+ setBusy(true); setError("");+ try {+ if (remove && item) await onSave(draft.kind === "node" ? "flow_node_delete" : "flow_edge_delete", { id: item.id });+ else if (draft.kind === "notes") await onSave("flow_update", form);+ else if (draft.kind === "edge") await onSave("flow_edge_upsert", { edge: { ...item, ...form } });+ else await onSave("flow_node_upsert", { node: { position: { x: (flow.nodes.length % 4) * 300, y: Math.floor(flow.nodes.length / 4) * 200 }, ...item, ...form } });+ onClose();+ } catch (cause) { setError(cause instanceof Error ? cause.message : "Save failed"); }+ finally { setBusy(false); }+ };+ const title = draft.kind === "notes" ? "Flow notes" : `${item ? "Edit" : "New"} ${draft.kind}`;+ return <>+ <ResponsiveDialog.Header><ResponsiveDialog.Title>{title}</ResponsiveDialog.Title><ResponsiveDialog.Description>Saved inside this organization. Context and references only; no automatic execution.</ResponsiveDialog.Description></ResponsiveDialog.Header>+ <ResponsiveDialog.Body><div className="grid gap-4 py-1">+ {draft.kind === "edge" ? <><Field label="From node"><select aria-label="From node" className={selectClass} value={form.source} onChange={(e) => set("source", e.target.value)}>{flow.nodes.map((node) => <option key={node.id} value={node.id}>{node.title}</option>)}</select></Field><Field label="To node"><select aria-label="To node" className={selectClass} value={form.target} onChange={(e) => set("target", e.target.value)}>{flow.nodes.map((node) => <option key={node.id} value={node.id}>{node.title}</option>)}</select></Field><Field label="Relationship"><Input maxLength={160} value={form.label} onChange={(e) => set("label", e.target.value)}/></Field></> : <>+ <Field label={draft.kind === "notes" ? "Flow title" : "Node title"}><Input maxLength={draft.kind === "notes" ? 160 : 120} value={form.title} onChange={(e) => set("title", e.target.value)}/></Field>+ {draft.kind === "node" ? <><div className="grid grid-cols-2 gap-3"><Field label="Node kind"><select aria-label="Node kind" className={selectClass} value={form.kind} onChange={(e) => set("kind", e.target.value)}>{ORGANIZATION_FLOW_KINDS.map((kind) => <option key={kind}>{kind}</option>)}</select></Field><Field label="Status"><select aria-label="Status" className={selectClass} value={form.status} onChange={(e) => set("status", e.target.value)}>{ORGANIZATION_FLOW_STATUSES.map((status) => <option key={status}>{status}</option>)}</select></Field></div><Field label="Summary"><Textarea maxLength={500} value={form.summary} onChange={(e) => set("summary", e.target.value)}/></Field><Field label="Project reference (optional)"><Input maxLength={4096} value={form.projectRef} onChange={(e) => set("projectRef", e.target.value)} placeholder="Canonical project identifier; not an execution command"/></Field></> : null}+ <Field label="Notes"><Textarea className="min-h-52 text-sm" maxLength={draft.kind === "notes" ? 64000 : 12000} value={form.notes} onChange={(e) => set("notes", e.target.value)}/></Field>+ </>}+ {error ? <p role="alert" className="text-sm text-destructive">{error} Your text is kept here; copy it before refreshing after a revision conflict.</p> : null}+ {confirmDelete ? <p role="alert" className="text-sm text-destructive">Delete this {draft.kind}? Deleting a node also removes its connections. This cannot be undone here.</p> : null}+ </div></ResponsiveDialog.Body>+ <ResponsiveDialog.Footer><div className="flex w-full flex-wrap gap-2">+ {item ? <Button variant="destructive" disabled={busy} onClick={() => confirmDelete ? void run(true) : setConfirmDelete(true)}>{confirmDelete ? "Confirm delete" : "Delete"}</Button> : null}+ <div className="flex-1"/><Button variant="outline" disabled={busy} onClick={onClose}>Cancel</Button><Button disabled={busy} onClick={() => void run()}>{busy ? "Saving…" : "Save"}</Button>+ </div></ResponsiveDialog.Footer>+ </>;+}diff --git a/frontend/slices/organization/components/project-flow.tsx b/frontend/slices/organization/components/project-flow.tsxnew file mode 100644index 00000000..26515829--- /dev/null+++ b/frontend/slices/organization/components/project-flow.tsx@@ -0,0 +1,82 @@+"use client";+import { useMemo, useRef, useState } from "react";+import { FileText, FolderKanban, Link2, Pencil, Plus, X } from "lucide-react";+import { Handle, MarkerType, Position, type Edge, type NodeProps, type NodeChange } from "@xyflow/react";+import { GraphCanvas } from "@/components/shared/graph-canvas";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { cn } from "@/lib/utils";+import { emptyOrganizationFlow, type OrganizationFlowAction } from "@/lib/contracts/organization-flow";+import type { OrganizationUnit } from "@/lib/contracts/organization";+import { projectCanvasNodes, updateFlowProjection, type FlowProjection, type ProjectCanvasNode as FlowNode } from "../lib/flow-projection";+import { ProjectFlowEditor, type FlowDraft } from "./project-flow-editor";++function ProjectCard({ data, selected }: NodeProps<FlowNode>) {+ const item = data.item;+ return <div className={cn("w-60 rounded-xl border bg-card p-3 shadow-sm", selected && "ring-2 ring-ring", item.kind === "group" && "border-primary/50", item.kind === "note" && "border-dashed")}>+ <Handle type="target" position={Position.Top} className="!size-3 !bg-muted-foreground"/>+ <div className="flex items-start gap-2"><FolderKanban className="mt-0.5 size-4 shrink-0 text-muted-foreground"/><div className="min-w-0 flex-1"><div className="break-words text-sm font-semibold">{item.title}</div><p className="mt-1 line-clamp-2 break-words text-xs text-muted-foreground">{item.summary || "Open for details"}</p></div></div>+ <div className="mt-2 flex gap-1"><Badge variant="secondary" className="text-[10px]">{item.kind}</Badge><Badge variant="outline" className="text-[10px]">{item.status}</Badge></div>+ <Handle type="source" position={Position.Bottom} className="!size-3 !bg-muted-foreground"/>+ </div>;+}+const nodeTypes = { project: ProjectCard };++type Props = { unit: OrganizationUnit; onSave: (action: OrganizationFlowAction, data: Record<string, unknown>) => Promise<void> };+export function ProjectFlow({ unit, onSave }: Props) {+ const flow = useMemo(() => unit.projectFlow ?? emptyOrganizationFlow(), [unit.projectFlow]);+ const [query, setQuery] = useState(""), [selectedId, setSelectedId] = useState<string | null>(null), [focus, setFocus] = useState(false);+ const [draft, setDraft] = useState<FlowDraft | null>(null), [error, setError] = useState(""), [busy, setBusy] = useState(false);+ const [projection, setProjection] = useState<FlowProjection>({ nodes: [] });+ const pending = useRef(false);+ const selected = flow.nodes.find((node) => node.id === selectedId);+ const visible = useMemo(() => {+ const match = new Set(flow.nodes.filter((node) => focus && selectedId ? node.id === selectedId : `${node.title} ${node.summary} ${node.kind}`.toLowerCase().includes(query.toLowerCase())).map((node) => node.id));+ const ids = new Set(match);+ if (query || (focus && selectedId)) for (const edge of flow.edges) if (match.has(edge.source) || match.has(edge.target)) { ids.add(edge.source); ids.add(edge.target); }+ return ids;+ }, [flow, query, focus, selectedId]);+ const nodes = useMemo<FlowNode[]>(() => projectCanvasNodes(flow.nodes, projection).filter((node) => visible.has(node.id)).map((node) => ({ ...node, selected: node.id === selectedId })), [flow.nodes, projection, selectedId, visible]);+ const edges = useMemo<Edge[]>(() => flow.edges.filter((edge) => visible.has(edge.source) && visible.has(edge.target)).map((edge) => ({ ...edge, type: "smoothstep", markerEnd: { type: MarkerType.ArrowClosed, color: "var(--muted-foreground)" }, style: { stroke: "var(--muted-foreground)" }, labelStyle: { fill: "var(--foreground)", fontSize: 11 }, labelBgStyle: { fill: "var(--background)" } })), [flow.edges, visible]);+ const save = async (action: OrganizationFlowAction, data: Record<string, unknown>) => {+ if (pending.current) throw new Error("A change is still saving. Try again after it completes.");+ pending.current = true; setBusy(true); setError("");+ try { await onSave(action, { ...data, unitId: unit.id }); }+ catch (cause) { const message = cause instanceof Error ? cause.message : "Save failed"; setError(message); throw cause; }+ finally { pending.current = false; setBusy(false); }+ };+ const changes = (updates: NodeChange<FlowNode>[]) => setProjection((prev) => updateFlowProjection(flow.nodes, prev, updates));+ const quickSave = (action: OrganizationFlowAction, data: Record<string, unknown>) => { void save(action, data).catch(() => setProjection({ nodes: [] })); };+ return <div data-slot="organization-project-flow" className="flex h-full min-h-0 flex-col">+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b px-3 py-2">+ <div className="min-w-0 flex-1"><div className="truncate text-sm font-medium">{flow.title}</div><p className="text-[10px] text-muted-foreground">{flow.nodes.length} nodes · {flow.edges.length} connections · {busy ? "Saving…" : "Stored in this organization"}</p></div>+ <Button variant="outline" size="sm" onClick={() => setDraft({ kind: "notes" })}><FileText className="mr-1 size-3.5"/>Notes</Button>+ <Button variant="outline" size="sm" disabled={flow.nodes.length < 2 || busy} onClick={() => setDraft({ kind: "edge" })}><Link2 className="mr-1 size-3.5"/>Connect</Button>+ <Button size="sm" disabled={busy} onClick={() => setDraft({ kind: "node" })}><Plus className="mr-1 size-3.5"/>Node</Button>+ <div className="flex w-full items-center gap-2"><Input aria-label="Search project flow" className="h-8 min-w-0 flex-1" placeholder="Search projects, activities, or notes…" value={query} onChange={(e) => setQuery(e.target.value)}/><Button size="sm" variant={focus ? "secondary" : "outline"} disabled={!selected} onClick={() => setFocus(!focus)}>Focus</Button></div>+ </div>+ {error ? <div role="alert" className="shrink-0 border-b px-3 py-2 text-xs text-destructive">{error} Refresh the organization before retrying a conflicting change.</div> : null}+ <div className="relative min-h-0 flex-1">+ {flow.nodes.length ? <GraphCanvas<FlowNode, Edge>+ ariaLabel="Organization project flow canvas" nodes={nodes} edges={edges} nodeTypes={nodeTypes}+ nodesDraggable={!busy} nodesConnectable={!busy} deleteKeyCode={null} onNodesChange={changes}+ onNodeClick={(_, node) => setSelectedId(node.id)} onNodeDoubleClick={(_, node) => setDraft({ kind: "node", node: node.data.item })}+ onPaneClick={() => { setSelectedId(null); setFocus(false); }}+ onNodeDragStop={(_, node) => quickSave("flow_node_upsert", { node: { id: node.id, position: node.position } })}+ onConnect={(connection) => quickSave("flow_edge_upsert", { edge: { source: connection.source, target: connection.target, label: "" } })}+ onEdgeClick={(_, edge) => setDraft({ kind: "edge", edge: flow.edges.find((item) => item.id === edge.id) })}+ compactFitNodeIds={selected ? [selected.id] : nodes.slice(0, 2).map((node) => node.id)}+ /> : <div className="grid h-full place-items-center p-6"><div className="max-w-sm text-center"><FolderKanban className="mx-auto mb-3 size-7 text-muted-foreground"/><h3 className="font-medium">Project flow inside {unit.name}</h3><p className="mt-2 text-sm text-muted-foreground">Add projects, activities, notes and connections here. The organization overview stays compact.</p><Button className="mt-4" onClick={() => setDraft({ kind: "node" })}>Add first node</Button></div></div>}+ {selected ? <div className="absolute inset-x-2 top-2 z-10 max-h-[calc(100%-1rem)] overflow-y-auto rounded-xl border bg-popover p-3 shadow-lg @min-[700px]:left-auto @min-[700px]:right-3 @min-[700px]:w-80">+ <div className="flex items-start gap-2"><h3 className="min-w-0 flex-1 break-words text-sm font-semibold">{selected.title}</h3><Button size="icon" variant="ghost" className="size-7 shrink-0" aria-label="Close node details" onClick={() => setSelectedId(null)}><X className="size-4"/></Button></div>+ <div className="mt-2 flex gap-1"><Badge variant="secondary">{selected.kind}</Badge><Badge variant="outline">{selected.status}</Badge></div>+ {selected.summary ? <p className="mt-3 whitespace-pre-wrap break-words text-sm">{selected.summary}</p> : null}+ {selected.notes ? <div className="mt-3 whitespace-pre-wrap break-words text-xs leading-relaxed text-muted-foreground">{selected.notes}</div> : null}+ {selected.projectRef ? <p className="mt-3 break-all text-xs">Project reference: {selected.projectRef}</p> : null}+ <Button className="mt-3 w-full" size="sm" onClick={() => setDraft({ kind: "node", node: selected })}><Pencil className="mr-2 size-3"/>Edit node</Button>+ </div> : null}+ </div>+ <ProjectFlowEditor draft={draft} flow={flow} onClose={() => setDraft(null)} onSave={save}/>+ </div>;+}diff --git a/frontend/slices/organization/lib/flow-projection.test.ts b/frontend/slices/organization/lib/flow-projection.test.tsnew file mode 100644index 00000000..d05aef80--- /dev/null+++ b/frontend/slices/organization/lib/flow-projection.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from "vitest";+import type { OrganizationFlowNode } from "@/lib/contracts/organization-flow";+import { projectCanvasNodes, updateFlowProjection, type FlowProjection } from "./flow-projection";++const source = (): OrganizationFlowNode[] => [{ id: "one", title: "Project", kind: "project", status: "unconfirmed", summary: "", notes: "", position: { x: 0, y: 0 } }];++describe("organization flow canvas projection", () => {+ it("retains measured dimensions required for edges, not only drag positions", () => {+ const items = source();+ const state = updateFlowProjection(items, { nodes: [] }, [{ type: "dimensions", id: "one", dimensions: { width: 240, height: 95 } }]);+ expect(projectCanvasNodes(items, state)[0].measured).toEqual({ width: 240, height: 95 });+ const dragged = updateFlowProjection(items, state, [{ type: "position", id: "one", position: { x: 90, y: 40 } }]);+ expect(dragged.nodes[0].position).toEqual({ x: 90, y: 40 });+ expect(dragged.nodes[0].measured).toEqual({ width: 240, height: 95 });+ });++ it("uses refreshed backend positions rather than replaying a stale drag", () => {+ const items = source();+ const state = updateFlowProjection(items, { nodes: [] }, [{ type: "position", id: "one", position: { x: 90, y: 40 } }]);+ const refreshed = source(); refreshed[0].title = "Server edit";+ expect(projectCanvasNodes(refreshed, state)[0]).toMatchObject({ position: { x: 0, y: 0 }, data: { item: { title: "Server edit" } } });+ });++ it("does not copy canvas-only measurements to persisted source data", () => {+ const items = source();+ const state: FlowProjection = updateFlowProjection(items, { nodes: [] }, [{ type: "dimensions", id: "one", dimensions: { width: 240, height: 95 } }]);+ expect(items).toEqual(source());+ expect(projectCanvasNodes([], state)).toEqual([]);+ expect(projectCanvasNodes(source(), state)[0].measured).toEqual({ width: 240, height: 95 });+ });+});diff --git a/frontend/slices/organization/lib/flow-projection.ts b/frontend/slices/organization/lib/flow-projection.tsnew file mode 100644index 00000000..dc8a4801--- /dev/null+++ b/frontend/slices/organization/lib/flow-projection.ts@@ -0,0 +1,20 @@+import { applyNodeChanges, type Node, type NodeChange } from "@xyflow/react";+import type { OrganizationFlowNode } from "@/lib/contracts/organization-flow";++export type ProjectCanvasNode = Node<{ item: OrganizationFlowNode }, "project">;+export type FlowProjection = { source?: OrganizationFlowNode[]; nodes: ProjectCanvasNode[] };++/** API positions are authoritative; measured dimensions belong only to the canvas. */+export function projectCanvasNodes(source: OrganizationFlowNode[], projection: FlowProjection): ProjectCanvasNode[] {+ if (projection.source === source) return projection.nodes;+ const previous = new Map(projection.nodes.map((node) => [node.id, node]));+ return source.map((item) => ({+ id: item.id, type: "project", position: item.position, data: { item },+ measured: previous.get(item.id)?.measured,+ }));+}++/** Retain dimension changes as well as drags, so React Flow can resolve edge handles. */+export function updateFlowProjection(source: OrganizationFlowNode[], previous: FlowProjection, changes: NodeChange<ProjectCanvasNode>[]): FlowProjection {+ return { source, nodes: applyNodeChanges(changes, projectCanvasNodes(source, previous)) };+}diff --git a/lib/agent/organization-flow-mutations.ts b/lib/agent/organization-flow-mutations.tsnew file mode 100644index 00000000..49ac03d3--- /dev/null+++ b/lib/agent/organization-flow-mutations.ts@@ -0,0 +1,43 @@+import { randomUUID } from "node:crypto";+import { emptyOrganizationFlow, type OrganizationFlowAction, type OrganizationProjectFlow } from "@/lib/contracts/organization-flow";+import { flowId, flowRecord, parseFlowEdge, parseFlowNode, parseOrganizationFlow } from "./organization-flow-schema";++/** Pure, unit-local edits. Never resolves a runtime or executes graph content. */+export function changeOrganizationFlow(current: OrganizationProjectFlow | undefined, action: OrganizationFlowAction, data: Record<string, unknown>): OrganizationProjectFlow {+ const flow = structuredClone(current ?? emptyOrganizationFlow());+ switch (action) {+ case "flow_replace": return parseOrganizationFlow(data.flow);+ case "flow_update": return parseOrganizationFlow({ ...flow, ...("title" in data ? { title: data.title } : {}), ...("notes" in data ? { notes: data.notes } : {}) });+ case "flow_node_upsert": {+ const raw = flowRecord(data.node);+ const id = raw.id === undefined ? `node_${randomUUID()}` : flowId(raw.id);+ const node = parseFlowNode({ ...flow.nodes.find((item) => item.id === id), ...raw, id });+ const index = flow.nodes.findIndex((item) => item.id === id);+ if (index < 0) flow.nodes.push(node); else flow.nodes[index] = node;+ break;+ }+ case "flow_node_delete": {+ const id = flowId(data.id);+ if (!flow.nodes.some((node) => node.id === id)) throw new Error("flow node not found in this unit");+ flow.nodes = flow.nodes.filter((node) => node.id !== id);+ flow.edges = flow.edges.filter((edge) => edge.source !== id && edge.target !== id);+ break;+ }+ case "flow_edge_upsert": {+ const raw = flowRecord(data.edge);+ const id = raw.id === undefined ? `edge_${randomUUID()}` : flowId(raw.id);+ const edge = parseFlowEdge({ ...flow.edges.find((item) => item.id === id), ...raw, id });+ const index = flow.edges.findIndex((item) => item.id === id);+ if (index < 0) flow.edges.push(edge); else flow.edges[index] = edge;+ break;+ }+ case "flow_edge_delete": {+ const id = flowId(data.id);+ if (!flow.edges.some((edge) => edge.id === id)) throw new Error("flow edge not found in this unit");+ flow.edges = flow.edges.filter((edge) => edge.id !== id);+ break;+ }+ default: throw new Error("unsupported project flow action");+ }+ return parseOrganizationFlow(flow);+}diff --git a/lib/agent/organization-flow-schema.ts b/lib/agent/organization-flow-schema.tsnew file mode 100644index 00000000..41e2521a--- /dev/null+++ b/lib/agent/organization-flow-schema.ts@@ -0,0 +1,48 @@+import { ORGANIZATION_FLOW_KINDS, ORGANIZATION_FLOW_STATUSES, type OrganizationFlowNode, type OrganizationFlowEdge, type OrganizationProjectFlow } from "@/lib/contracts/organization-flow";++export function flowRecord(value: unknown): Record<string, unknown> {+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("project flow value must be an object");+ return value as Record<string, unknown>;+}+function text(value: unknown, field: string, max: number, required = false): string {+ if (value === undefined) value = "";+ if (typeof value !== "string" || value.length > max) throw new Error(`${field} is invalid or exceeds ${max} characters`);+ if (required && !value.trim()) throw new Error(`${field} is required`);+ return value;+}+export function flowId(value: unknown): string {+ const id = text(value, "flow id", 128, true);+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(id)) throw new Error("flow id is invalid");+ return id;+}+export function parseFlowNode(value: unknown): OrganizationFlowNode {+ const row = flowRecord(value);+ const kind = row.kind ?? "project", status = row.status ?? "unconfirmed";+ if (!(ORGANIZATION_FLOW_KINDS as readonly unknown[]).includes(kind)) throw new Error("flow node kind is invalid");+ if (!(ORGANIZATION_FLOW_STATUSES as readonly unknown[]).includes(status)) throw new Error("flow node status is invalid");+ const position = flowRecord(row.position ?? { x: 0, y: 0 });+ for (const key of ["x", "y"]) if (typeof position[key] !== "number" || !Number.isFinite(position[key]) || Math.abs(position[key] as number) > 100000) throw new Error("flow node position is invalid");+ const projectRef = text(row.projectRef, "projectRef", 4096).trim();+ return {+ id: flowId(row.id), title: text(row.title, "node title", 120, true).trim(),+ kind: kind as OrganizationFlowNode["kind"], status: status as OrganizationFlowNode["status"],+ summary: text(row.summary, "node summary", 500), notes: text(row.notes, "node notes", 12000),+ ...(projectRef ? { projectRef } : {}), position: { x: position.x as number, y: position.y as number },+ };+}+export function parseFlowEdge(value: unknown): OrganizationFlowEdge {+ const row = flowRecord(value);+ const edge = { id: flowId(row.id), source: flowId(row.source), target: flowId(row.target), label: text(row.label, "edge label", 160) };+ if (edge.source === edge.target) throw new Error("flow edge cannot connect a node to itself");+ return edge;+}+export function parseOrganizationFlow(value: unknown): OrganizationProjectFlow {+ const row = flowRecord(value);+ if (row.version !== 1) throw new Error("project flow version is invalid");+ if (!Array.isArray(row.nodes) || row.nodes.length > 200 || !Array.isArray(row.edges) || row.edges.length > 400) throw new Error("project flow requires bounded nodes (200) and edges (400)");+ const nodes = row.nodes.map(parseFlowNode), edges = row.edges.map(parseFlowEdge);+ const ids = new Set(nodes.map((node) => node.id));+ if (ids.size !== nodes.length || new Set(edges.map((edge) => edge.id)).size !== edges.length) throw new Error("project flow ids must be unique");+ if (edges.some((edge) => !ids.has(edge.source) || !ids.has(edge.target))) throw new Error("flow edge endpoint not found in this unit");+ return { version: 1, title: text(row.title, "flow title", 160, true).trim(), notes: text(row.notes, "flow notes", 64000), nodes, edges };+}diff --git a/lib/agent/organization-flow.test.ts b/lib/agent/organization-flow.test.tsnew file mode 100644index 00000000..473c3e63--- /dev/null+++ b/lib/agent/organization-flow.test.ts@@ -0,0 +1,110 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdtemp, readFile, rm, stat } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { changeOrganizationFlow } from "./organization-flow-mutations";+import { parseOrganizationFlow, parseFlowNode } from "./organization-flow-schema";+import { emptyOrganizationFlow, ORGANIZATION_FLOW_ACTIONS } from "@/lib/contracts/organization-flow";++const node = (id: string) => ({ id, title: id, kind: "project", status: "unconfirmed", summary: "", notes: "", position: { x: 0, y: 0 } });+let dir = "";+beforeEach(async () => { dir = await mkdtemp(path.join(os.tmpdir(), "mso-org-flow-")); process.env.OS_ORGANIZATION_STORE = path.join(dir, "organization.json"); vi.resetModules(); });+afterEach(async () => { delete process.env.OS_ORGANIZATION_STORE; await rm(dir, { recursive: true, force: true }); vi.resetModules(); });++async function fixture() {+ const api = await import("./organization-store");+ let chart = await api.getOrganizationChart();+ chart = await api.upsertOrganizationUnit(chart.revision, { id: "unit-a", key: "a", name: "A" });+ chart = await api.upsertOrganizationUnit(chart.revision, { id: "unit-b", key: "b", name: "B" });+ return { api, chart };+}++describe("organization project flow persistence", () => {+ it("stores multiline notes inside a unit and keeps them when a legacy unit editor saves", async () => {+ const { api, chart } = await fixture();+ const next = await api.mutateOrganizationFlow(chart.revision, "flow_update", { unitId: "unit-a", title: "Delivery", notes: "# Source\n\nStill unconfirmed.\n" });+ const saved = await api.upsertOrganizationUnit(next.revision, { id: "unit-a", key: "a", name: "A", description: "Brief summary" });+ expect(saved.units.find((u) => u.id === "unit-a")?.projectFlow?.notes).toBe("# Source\n\nStill unconfirmed.\n");+ expect(saved.units.find((u) => u.id === "unit-b")?.projectFlow).toBeUndefined();+ expect(saved.seats).toEqual(chart.seats);+ expect((await stat(api.ORGANIZATION_STORE_PATH)).mode & 0o077).toBe(0);+ const raw = JSON.parse(await readFile(api.ORGANIZATION_STORE_PATH, "utf8"));+ expect(raw.units.find((u: { id: string }) => u.id === "unit-a").projectFlow.title).toBe("Delivery");+ expect((await api.getOrganizationChart()).units).toEqual(saved.units);+ });+ it("supports node/edge CRUD and position-only patches without dropping notes", async () => {+ const { api, chart } = await fixture();+ let next = await api.mutateOrganizationFlow(chart.revision, "flow_node_upsert", { unitId: "unit-a", node: { ...node("n1"), notes: "Evidence, not a contract" } });+ next = await api.mutateOrganizationFlow(next.revision, "flow_node_upsert", { unitId: "unit-a", node: node("n2") });+ next = await api.mutateOrganizationFlow(next.revision, "flow_edge_upsert", { unitId: "unit-a", edge: { id: "e1", source: "n1", target: "n2", label: "supports" } });+ next = await api.mutateOrganizationFlow(next.revision, "flow_node_upsert", { unitId: "unit-a", node: { id: "n1", position: { x: 240, y: -50 } } });+ expect(next.units[0].projectFlow?.nodes[0]).toMatchObject({ notes: "Evidence, not a contract", position: { x: 240, y: -50 } });+ next = await api.mutateOrganizationFlow(next.revision, "flow_edge_upsert", { unitId: "unit-a", edge: { id: "e1", label: "provisional" } });+ expect(next.units[0].projectFlow?.edges[0].label).toBe("provisional");+ next = await api.mutateOrganizationFlow(next.revision, "flow_edge_delete", { unitId: "unit-a", id: "e1" });+ expect(next.units[0].projectFlow?.edges).toEqual([]);+ next = await api.mutateOrganizationFlow(next.revision, "flow_edge_upsert", { unitId: "unit-a", edge: { source: "n1", target: "n2" } });+ next = await api.mutateOrganizationFlow(next.revision, "flow_node_delete", { unitId: "unit-a", id: "n1" });+ expect(next.units[0].projectFlow?.nodes.map((n) => n.id)).toEqual(["n2"]);+ expect(next.units[0].projectFlow?.edges).toEqual([]);+ });+ it("rejects stale revisions, unknown units/actions, and cross-unit edges without writes", async () => {+ const { api, chart } = await fixture();+ const next = await api.mutateOrganizationFlow(chart.revision, "flow_node_upsert", { unitId: "unit-a", node: node("only-a") });+ await expect(api.mutateOrganizationFlow(chart.revision, "flow_update", { unitId: "unit-a", notes: "stale" })).rejects.toThrow(/revision changed/);+ await expect(api.mutateOrganizationFlow(next.revision, "flow_update", {})).rejects.toThrow(/unitId/);+ await expect(api.mutateOrganizationFlow(next.revision, "flow_update", { unitId: "missing" })).rejects.toThrow(/not found/);+ await expect(api.mutateOrganizationFlow(next.revision, "execute", { unitId: "unit-a" })).rejects.toThrow(/unsupported/);+ await expect(api.mutateOrganizationFlow(next.revision, "flow_edge_upsert", { unitId: "unit-b", edge: { source: "only-a", target: "missing" } })).rejects.toThrow(/endpoint/);+ expect((await api.getOrganizationChart()).revision).toBe(next.revision);+ });+ it("exposes callable flow actions through the existing read/write MCP tools", async () => {+ const { chart } = await fixture();+ const { ORGANIZATION_TOOLS } = await import("@/lib/mcp/tools-organization");+ const read = ORGANIZATION_TOOLS.find((t) => t.name === "organization_chart")!;+ const write = ORGANIZATION_TOOLS.find((t) => t.name === "organization_manage")!;+ expect(read.scope).toBe("read"); expect(write.scope).toBe("write"); expect(write.audit?.action).toBe("agent.organization");+ expect(JSON.stringify(write.inputSchema)).toContain("flow_node_upsert");+ const output = await write.run({ action: "flow_node_upsert", expected_revision: chart.revision, data: { unitId: "unit-a", node: node("via-mcp") } }, { principal: "test", scope: "write" } as never) as { chart: typeof chart };+ expect(output.chart.units[0].projectFlow?.nodes[0].id).toBe("via-mcp");+ const reread = await read.run({ runtime: false }, { principal: "test" } as never) as { chart: typeof chart };+ expect(reread.chart.revision).toBe(output.chart.revision);+ expect(ORGANIZATION_FLOW_ACTIONS).toHaveLength(6);+ });+});++describe("bounded contextual graph schema", () => {+ it("has no executor and defaults new nodes to unconfirmed", () => {+ const flow = changeOrganizationFlow(undefined, "flow_node_upsert", { node: { title: "Draft", run: "never", command: "never" } });+ expect(flow.nodes[0]).toMatchObject({ status: "unconfirmed", kind: "project" });+ expect(flow.nodes[0]).not.toHaveProperty("run"); expect(flow.nodes[0]).not.toHaveProperty("command");+ });+ it("accepts references and exact note text, rejects malformed shapes and overlong data", () => {+ expect(parseFlowNode({ ...node("n"), projectRef: "project-a" }).projectRef).toBe("project-a");+ for (const value of [null, [], "x", 1]) expect(() => parseOrganizationFlow(value)).toThrow();+ expect(() => parseOrganizationFlow({ ...emptyOrganizationFlow(), version: 2 })).toThrow(/version/);+ expect(() => parseOrganizationFlow({ ...emptyOrganizationFlow(), notes: "x".repeat(64001) })).toThrow(/64000/);+ expect(() => parseFlowNode({ ...node("n"), notes: "x".repeat(12001) })).toThrow(/12000/);+ expect(() => parseFlowNode({ ...node("n"), title: " " })).toThrow(/required/);+ expect(() => parseFlowNode({ ...node("n"), id: "../bad" })).toThrow(/invalid/);+ expect(() => parseFlowNode({ ...node("n"), kind: "shell" })).toThrow(/kind/);+ expect(() => parseFlowNode({ ...node("n"), status: "approved-by-ai" })).toThrow(/status/);+ for (const x of [NaN, Infinity, "12", 100001]) expect(() => parseFlowNode({ ...node("n"), position: { x, y: 0 } })).toThrow(/position/);+ });+ it("rejects duplicate, cross-unit, self and over-limit graph objects", () => {+ const flow = { ...emptyOrganizationFlow(), nodes: [node("n")] };+ expect(() => parseOrganizationFlow({ ...flow, nodes: [node("n"), node("n")] })).toThrow(/unique/);+ expect(() => parseOrganizationFlow({ ...flow, edges: [{ id: "e", source: "n", target: "n" }] })).toThrow(/itself/);+ expect(() => parseOrganizationFlow({ ...flow, edges: [{ id: "e", source: "n", target: "other-unit-node" }] })).toThrow(/endpoint/);+ expect(() => parseOrganizationFlow({ ...flow, nodes: Array.from({ length: 201 }, (_, i) => node(`n${i}`)) })).toThrow(/bounded/);+ expect(() => parseOrganizationFlow({ ...flow, edges: Array(401).fill({}) })).toThrow(/bounded/);+ });+ it("preserves the input snapshot and replaces only when explicitly requested", () => {+ const current = { ...emptyOrganizationFlow(), nodes: [parseFlowNode(node("n"))] };+ const updated = changeOrganizationFlow(current, "flow_update", { notes: "updated", nodes: [] });+ expect(updated.nodes).toEqual(current.nodes); expect(current.notes).toBe("");+ expect(changeOrganizationFlow(current, "flow_replace", { flow: emptyOrganizationFlow() }).nodes).toEqual([]);+ expect(() => changeOrganizationFlow(current, "flow_node_delete", { id: "missing" })).toThrow(/not found/);+ expect(() => changeOrganizationFlow(current, "flow_edge_delete", { id: "missing" })).toThrow(/not found/);+ });+});diff --git a/lib/agent/organization-schema.ts b/lib/agent/organization-schema.tsindex b56154fb..f69bfb51 100644--- a/lib/agent/organization-schema.ts+++ b/lib/agent/organization-schema.ts@@ -1,3 +1,4 @@+import { parseOrganizationFlow } from "./organization-flow-schema";import type {OrganizationChart,OrganizationSeat,@@ -36,6 +37,7 @@ export function parseOrganizationUnit(v: unknown, now = new Date().toISOString()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),+ ...(row.projectFlow !== undefined ? { projectFlow: parseOrganizationFlow(row.projectFlow) } : {}),createdAt: text(row.createdAt, 64) || now, updatedAt: text(row.updatedAt, 64) || now };}diff --git a/lib/agent/organization-store.ts b/lib/agent/organization-store.tsindex 7fc9470d..7786c88f 100644--- a/lib/agent/organization-store.ts+++ b/lib/agent/organization-store.ts@@ -1,3 +1,5 @@+import { isOrganizationFlowAction } from "@/lib/contracts/organization-flow";+import { changeOrganizationFlow } from "./organization-flow-mutations";import { createHash, randomUUID } from "node:crypto";import { constants as fsConstants, promises as fs } from "node:fs";import os from "node:os";@@ -32,8 +34,21 @@ async function writeUnlocked(chart: OrganizationChart) { const body = JSON.strinexport 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 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, ...(raw.projectFlow === undefined && previous?.projectFlow ? { projectFlow: previous.projectFlow } : {}) }, 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); }); }+++export async function mutateOrganizationFlow(expectedRevision: string, action: string, data: Record<string, unknown>) {+ if (!isOrganizationFlowAction(action)) throw new Error("unsupported project flow action");+ if (typeof data.unitId !== "string" || !data.unitId) throw new Error("unitId is required for project flow actions");+ return mutate(expectedRevision, (chart) => {+ const unit = chart.units.find((item) => item.id === data.unitId);+ if (!unit) throw new Error("organization unit not found");+ const projectFlow = changeOrganizationFlow(unit.projectFlow, action, data);+ const next = { ...unit, projectFlow, updatedAt: new Date().toISOString() };+ return materialize(chart.name, chart.units.map((item) => item.id === unit.id ? next : item), chart.seats);+ });+}diff --git a/lib/contracts/organization-flow.ts b/lib/contracts/organization-flow.tsnew file mode 100644index 00000000..cc7ebab0--- /dev/null+++ b/lib/contracts/organization-flow.ts@@ -0,0 +1,26 @@+/** Organization context graph, not an executable automation workflow. */+export const ORGANIZATION_FLOW_KINDS = ["project", "activity", "group", "note"] as const;+export const ORGANIZATION_FLOW_STATUSES = ["unconfirmed", "planned", "active", "blocked", "done"] as const;+export const ORGANIZATION_FLOW_ACTIONS = ["flow_update", "flow_replace", "flow_node_upsert", "flow_node_delete", "flow_edge_upsert", "flow_edge_delete"] as const;+export type OrganizationFlowAction = typeof ORGANIZATION_FLOW_ACTIONS[number];+export type OrganizationFlowNode = {+ id: string;+ title: string;+ kind: typeof ORGANIZATION_FLOW_KINDS[number];+ status: typeof ORGANIZATION_FLOW_STATUSES[number];+ summary: string;+ notes: string;+ /** Optional reference only. This never grants execution authority. */+ projectRef?: string;+ position: { x: number; y: number };+};+export type OrganizationFlowEdge = { id: string; source: string; target: string; label: string };+export type OrganizationProjectFlow = {+ version: 1;+ title: string;+ notes: string;+ nodes: OrganizationFlowNode[];+ edges: OrganizationFlowEdge[];+};+export const emptyOrganizationFlow = (): OrganizationProjectFlow => ({ version: 1, title: "Project flow", notes: "", nodes: [], edges: [] });+export const isOrganizationFlowAction = (action: string): action is OrganizationFlowAction => (ORGANIZATION_FLOW_ACTIONS as readonly string[]).includes(action);diff --git a/lib/contracts/organization.ts b/lib/contracts/organization.tsindex d498f0de..03137a4c 100644--- a/lib/contracts/organization.ts+++ b/lib/contracts/organization.ts@@ -1,3 +1,5 @@+import type { OrganizationProjectFlow } from "./organization-flow";+export type OrganizationUnitKind = "holding" | "company" | "division" | "team" | "client" | "other";export type OrganizationStatus = "active" | "inactive";export type OrganizationSeatMode = "permanent" | "on_demand" | "inactive";@@ -17,6 +19,7 @@ export type OrganizationUnit = {status: OrganizationStatus;parentUnitId?: string;description?: string;+ projectFlow?: OrganizationProjectFlow;sortOrder: number;createdAt: string;updatedAt: string;diff --git a/lib/infra/setup-http-limit.test.ts b/lib/infra/setup-http-limit.test.tsnew file mode 100644index 00000000..ffa08b9e--- /dev/null+++ b/lib/infra/setup-http-limit.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from "vitest";+import { readSetupJson } from "./setup-http";++const request = (notes: string) => new Request("http://localhost/test", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ notes }) });+describe("bounded JSON request reader", () => {+ it("retains the strict integration setup default while permitting larger organization notes", async () => {+ const notes = "Source line\n".repeat(2000);+ await expect(readSetupJson(request(notes))).rejects.toThrow("request_too_large");+ await expect(readSetupJson(request(notes), 2 * 1024 * 1024)).resolves.toEqual({ notes });+ });+ it("rejects invalid overrides and still enforces the chosen stream limit", async () => {+ for (const max of [0, -1, NaN, Infinity, 2.5, 2 * 1024 * 1024 + 1]) await expect(readSetupJson(request("x"), max)).rejects.toThrow("invalid_body_limit");+ await expect(readSetupJson(request("x".repeat(50)), 40)).rejects.toThrow("request_too_large");+ });+});diff --git a/lib/infra/setup-http.ts b/lib/infra/setup-http.tsindex 60160de8..9b15e2f5 100644--- a/lib/infra/setup-http.ts+++ b/lib/infra/setup-http.ts@@ -1,7 +1,8 @@import { SetupError, SETUP_MAX_BODY } from "./setup-capability";-export async function readSetupJson(req: Request): Promise<Record<string, unknown>> {+export async function readSetupJson(req: Request, maxBytes = SETUP_MAX_BODY): Promise<Record<string, unknown>> {+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 2 * 1024 * 1024) throw new SetupError("invalid_body_limit", 400);if (req.headers.get("content-type")?.split(";")[0].trim() !== "application/json") throw new SetupError("json_required", 415);- if (Number(req.headers.get("content-length")) > SETUP_MAX_BODY) throw new SetupError("request_too_large", 413);+ if (Number(req.headers.get("content-length")) > maxBytes) throw new SetupError("request_too_large", 413);const reader = req.body?.getReader(); if (!reader) throw new SetupError("invalid_request", 400);let text = "", bytes = 0;const decoder = new TextDecoder();@@ -10,7 +11,7 @@ export async function readSetupJson(req: Request): Promise<Record<string, unknowlet timer: ReturnType<typeof setTimeout> | undefined;const part = await Promise.race([reader.read(), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new SetupError("request_timeout", 408)), 5000); })]).finally(() => clearTimeout(timer));if (part.done) break;- bytes += part.value.byteLength; if (bytes > SETUP_MAX_BODY) throw new SetupError("request_too_large", 413);+ bytes += part.value.byteLength; if (bytes > maxBytes) throw new SetupError("request_too_large", 413);text += decoder.decode(part.value, { stream: true });}text += decoder.decode();diff --git a/lib/mcp/tools-organization.ts b/lib/mcp/tools-organization.tsindex 9f3faf3e..d1d3537b 100644--- a/lib/mcp/tools-organization.ts+++ b/lib/mcp/tools-organization.ts@@ -1,13 +1,14 @@-import { deleteOrganizationSeat, deleteOrganizationUnit, getOrganizationChart, replaceOrganization, upsertOrganizationSeat, upsertOrganizationUnit } from "@/lib/agent/organization-store";+import { ORGANIZATION_FLOW_ACTIONS, isOrganizationFlowAction } from "@/lib/contracts/organization-flow";+import { deleteOrganizationSeat, deleteOrganizationUnit, mutateOrganizationFlow, 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.",+ description: "Read the private MSO organization hierarchy: units, reporting seats, execution bindings and live target status. Each unit may include an internal projectFlow (nodes, edges, notes). These are context maps, not executable workflows.",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.",+ chatgptDescription: "Read organization units, internal projectFlow nodes/edges/notes, seats 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);@@ -17,16 +18,17 @@ export const ORGANIZATION_TOOLS: McpTool[] = [},{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.",+ 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. Internal project flow actions: flow_update (data.unitId,title?,notes?), flow_replace (data.unitId,flow), flow_node_upsert (data.unitId,node), flow_node_delete (data.unitId,id), flow_edge_upsert (data.unitId,edge), flow_edge_delete (data.unitId,id). Node fields: id?,title,kind=project|activity|group|note,status=unconfirmed|planned|active|blocked|done,summary,notes,position={x,y},projectRef?. Edge fields: id?,source,target,label. Node deletion removes its incident edges. No action executes graph content.",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"]),+ chatgptDescription: "Edit units/seats or internal project flows. flow_* actions require data.unitId and current revision.",+ inputSchema: S({ action: { type: "string", enum: ["unit_upsert", "seat_upsert", "unit_delete", "seat_delete", "replace", ...ORGANIZATION_FLOW_ACTIONS] }, expected_revision: { type: "string" }, id: { type: "string" }, data: { type: "object", description: "For flow_* actions: unitId is required; flow_update uses title/notes; flow_replace uses flow={version:1,title,notes,nodes,edges}; flow_node_upsert uses node={id?,title,kind?,status?,summary?,notes?,position?:{x,y},projectRef?}; flow_edge_upsert uses edge={id?,source,target,label?}; deletes use id. Existing node/edge id permits partial update." } }, ["action", "expected_revision"]),run: async (a) => {const action = str(a, "action"), revision = str(a, "expected_revision"), data = a.data && typeof a.data === "object" && !Array.isArray(a.data) ? a.data as Record<string, unknown> : {};if (action === "unit_upsert") return { chart: await upsertOrganizationUnit(revision, data) };if (action === "seat_upsert") return { chart: await upsertOrganizationSeat(revision, data) };if (action === "unit_delete") return { chart: await deleteOrganizationUnit(revision, str(a, "id")) };if (action === "seat_delete") return { chart: await deleteOrganizationSeat(revision, str(a, "id")) };+ if (isOrganizationFlowAction(action)) return { chart: await mutateOrganizationFlow(revision, action, data) };if (action === "replace") return { chart: await replaceOrganization(revision, data as never) };throw new Error("unsupported organization action");},diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.tsindex 5edf16dd..739be7e7 100644--- a/lib/mcp/toolset.ts+++ b/lib/mcp/toolset.ts@@ -4,8 +4,8 @@ import type { McpTool } from "./tool-kit";import { toolDescriptor, type McpToolProfile } from "./tool-contract";export const MCP_SERVER_VERSION = "1.15.1";-export const MCP_TOOLSET_VERSION = "2026.09.17.2";-export const MCP_TOOLSET_CHANGED_AT = "2026-09-17T17:50:58+07:00";+export const MCP_TOOLSET_VERSION = "2026.09.18.1";+export const MCP_TOOLSET_CHANGED_AT = "2026-09-18T07:18:00+07:00";export type McpToolsetInfo = {serverVersion: string;diff --git a/package.json b/package.jsonindex 7d5209d2..3e810aab 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "mso",- "version": "0.2.19",+ "version": "0.2.20","private": true,"engines": {"node": ">=20.9",diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.shindex 22893321..3c827cf8 100755--- a/scripts/cli/commands.sh+++ b/scripts/cli/commands.sh@@ -42,7 +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_org="org flow-update|flow-replace|flow-node-upsert|flow-node-delete|flow-edge-upsert|flow-edge-delete <revision> <JSON with unitId|@file>|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>"diff --git a/scripts/cli/organization.sh b/scripts/cli/organization.shindex bfdef68d..c6b19874 100644--- a/scripts/cli/organization.sh+++ b/scripts/cli/organization.sh@@ -14,6 +14,10 @@ run_org() {show|list)jget "/api/v1/organization";;+ flow-update|flow-replace|flow-node-upsert|flow-node-delete|flow-edge-upsert|flow-edge-delete)+ revision="${1:?revision}"; input="${2:?JSON containing unitId or @file}"; if [ "${input:0:1}" = "@" ]; then input=$(cat -- "${input:1}"); fi+ action="${sub//-/_}"+ jpost "/api/v1/organization" "$(jq -n --arg action "$action" --arg revision "$revision" --argjson data "$input" '{action:$action,expected_revision:$revision,data:$data}')" ;;unit-upsert|seat-upsert|replace)revision="${1:?revision}"; input="${2:?JSON or @file}"; if [ "${input:0:1}" = "@" ]; then input=$(cat -- "${input:1}"); fiaction="${sub//-/_}"; key="${sub%%-*}"diff --git a/scripts/e2e/organization-flow.mjs b/scripts/e2e/organization-flow.mjsnew file mode 100644index 00000000..8b50db9b--- /dev/null+++ b/scripts/e2e/organization-flow.mjs@@ -0,0 +1,122 @@+#!/usr/bin/env node+// Real UI/API/MCP journey with disposable stores; never borrows deployment credentials.+import { chromium, expect } from "@playwright/test";+import { mkdir } from "node:fs/promises";+import path from "node:path";+import { releaseFixture } from "./release-fixture.mjs";++const fixture = await releaseFixture({ live: true });+let browser;+try {+ browser = await chromium.launch({ headless: true });+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });+ await context.addInitScript(device => { localStorage.setItem("mso.device.id", device); localStorage.setItem("mso:onboarding:v1", "done"); }, fixture.device);+ const login = await fetch(fixture.base + "/api/auth/login", { method: "POST", headers: { "content-type": "application/json", origin: fixture.base }, body: JSON.stringify({ password: fixture.password, deviceId: fixture.device, deviceLabel: "Organization flow fixture" }) });+ expect(login.ok).toBe(true);+ const cookie = /(?:^|,\s*)session=([^;]+)/.exec(login.headers.get("set-cookie") ?? "")?.[1];+ if (!cookie) throw new Error("Fixture session missing");+ await context.addCookies([{ name: "session", value: cookie, url: fixture.base, httpOnly: true, sameSite: "Lax" }]);+ const page = await context.newPage(), errors = [];+ page.on("pageerror", (error) => errors.push(error.message));+ await page.goto(fixture.base + "/organization");+ const call = async (body) => page.evaluate(async (body) => {+ const response = await fetch("/api/v1/organization", body ? { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) } : {});+ return { status: response.status, body: await response.json() };+ }, body);+ let chart = (await call()).body.chart;+ for (const id of ["flow-workspace", "other-workspace"]) {+ const result = await call({ action: "unit_upsert", expected_revision: chart.revision, unit: { id, key: id, name: id === "flow-workspace" ? "Flow Workspace" : "Other Workspace", description: "A compact organization summary. ".repeat(20), kind: "company" } });+ expect(result.status).toBe(200); chart = result.body.chart;+ }+ const open = async () => {+ await page.goto(fixture.base + "/organization");+ const card = page.getByRole("application", { name: "Organization units canvas", exact: true }).locator('[data-id="flow-workspace"]');+ await expect(card).toBeVisible();+ expect(await card.evaluate((el) => el.offsetHeight)).toBeLessThan(170);+ await card.click();+ await expect(page.locator('[data-slot="organization-project-flow"]')).toBeVisible();+ };+ await open();+ await page.getByRole("button", { name: "Add first node", exact: true }).click();+ await page.getByLabel("Node title", { exact: true }).fill("First Project");+ await page.getByLabel("Summary", { exact: true }).fill("Evidence stays inside this node.");+ await page.getByLabel("Notes", { exact: true }).fill("Not an employment or revenue commitment.");+ await page.getByRole("button", { name: "Save", exact: true }).click();+ await expect(page.getByRole("heading", { name: "New node", exact: true })).toBeHidden();+ await page.getByRole("button", { name: "Node", exact: true }).click();+ await page.getByLabel("Node title", { exact: true }).fill("Second Project");+ await page.getByRole("button", { name: "Save", exact: true }).click();+ await expect(page.getByRole("heading", { name: "New node", exact: true })).toBeHidden();+ chart = (await call()).body.chart;+ const flow = () => chart.units.find((unit) => unit.id === "flow-workspace").projectFlow;+ const first = flow().nodes[0].id, second = flow().nodes[1].id;+ await page.getByRole("button", { name: "Connect", exact: true }).click();+ await page.getByLabel("From node").selectOption(first);+ await page.getByLabel("To node").selectOption(second);+ await page.getByLabel("Relationship", { exact: true }).fill("supports");+ await page.getByRole("button", { name: "Save", exact: true }).click();+ await expect(page.getByRole("heading", { name: "New edge", exact: true })).toBeHidden();+ const canvas = page.getByRole("application", { name: "Organization project flow canvas", exact: true });+ await expect(canvas.locator(".react-flow__edge")).toHaveCount(1);+ await expect(canvas.locator(".react-flow__edge-path")).toHaveAttribute("marker-end", /url/);+ await canvas.locator(`[data-id="${first}"]`).click();+ await page.getByRole("button", { name: "Edit node", exact: true }).click();+ await page.getByLabel("Node title", { exact: true }).fill("First Project revised");+ await page.getByRole("button", { name: "Save", exact: true }).click();+ await expect(page.getByRole("heading", { name: "Edit node", exact: true })).toBeHidden();+ await page.getByRole("button", { name: "Close node details", exact: true }).click();+ const before = (await call()).body.chart.units.find((u) => u.id === "flow-workspace").projectFlow.nodes[0].position;+ const card = canvas.locator(`[data-id="${first}"]`);+ await expect(card).toBeVisible();+ await page.waitForTimeout(400);+ const box = await card.boundingBox();+ await page.mouse.move(box.x + box.width / 2, box.y + 25);+ await page.mouse.down(); await page.mouse.move(box.x + box.width / 2 + 70, box.y + 85, { steps: 10 }); await page.mouse.up();+ await expect.poll(async () => JSON.stringify((await call()).body.chart.units.find((u) => u.id === "flow-workspace").projectFlow.nodes[0].position)).not.toBe(JSON.stringify(before));+ const notes = "# Source notes\n" + "Unconfirmed source statement.\n".repeat(800);+ await page.getByRole("button", { name: "Notes", exact: true }).click();+ await page.getByLabel("Flow title", { exact: true }).fill("Project Delivery");+ await page.getByLabel("Notes", { exact: true }).fill(notes);+ await page.getByRole("button", { name: "Save", exact: true }).click();+ await expect(page.getByRole("heading", { name: "Flow notes", exact: true })).toBeHidden();+ await open();+ await expect(canvas.locator(`[data-id="${first}"]`)).toContainText("First Project revised");+ await expect(canvas.locator(".react-flow__edge")).toHaveCount(1);+ chart = (await call()).body.chart;+ expect(flow().notes).toBe(notes); expect(flow().edges).toHaveLength(1);+ expect(chart.units.find((u) => u.id === "other-workspace").projectFlow).toBeUndefined();++ await fixture.seedMcp("write");+ const mcp = async (name, args) => {+ const response = await fetch(fixture.base + "/mcp", { method: "POST", headers: { authorization: `Bearer ${fixture.mcpToken}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args, _meta: { "mso/conversationKey": "organization-flow-fixture" } } }) });+ const text = await response.text();+ return JSON.parse(text.startsWith("{") ? text : text.split("\n").filter((line) => line.startsWith("data: ")).at(-1).slice(6));+ };+ const stale = chart.revision;+ const viaMcp = await mcp("organization_manage", { action: "flow_node_upsert", expected_revision: chart.revision, data: { unitId: "flow-workspace", node: { id: first, notes: "Updated via real MCP function calling" } } });+ expect(viaMcp.error).toBeUndefined(); expect(viaMcp.result?.isError).not.toBe(true);+ chart = (await call()).body.chart;+ expect(flow().nodes[0].notes).toBe("Updated via real MCP function calling");+ expect((await call({ action: "flow_update", expected_revision: stale, data: { unitId: "flow-workspace", notes: "must not overwrite" } })).status).toBe(409);+ expect((await call({ action: "flow_edge_upsert", expected_revision: chart.revision, data: { unitId: "other-workspace", edge: { source: first, target: second } } })).status).toBe(400);+ await fixture.setRole("viewer");+ expect((await call({ action: "flow_update", expected_revision: chart.revision, data: { unitId: "flow-workspace", notes: "denied" } })).status).toBe(403);+ await fixture.setRole("owner");+ await fixture.seedMcp("read");+ const denied = await mcp("organization_manage", { action: "flow_update", expected_revision: chart.revision, data: { unitId: "flow-workspace", notes: "denied" } });+ expect(Boolean(denied.error || denied.result?.isError)).toBe(true);+ for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }, { width: 844, height: 390 }]) {+ await page.setViewportSize(viewport); await open();+ const feature = page.locator('[data-slot="organization-feature"]');+ expect(await feature.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true);+ await expect(canvas.locator(`[data-id="${first}"]`)).toBeVisible();+ await expect(canvas.locator(".react-flow__edge")).toHaveCount(1);+ if (process.env.MSO_SCREENSHOT_DIR) { await mkdir(process.env.MSO_SCREENSHOT_DIR, { recursive: true }); await page.screenshot({ path: path.join(process.env.MSO_SCREENSHOT_DIR, `organization-flow-${viewport.width}.png`) }); }+ }+ chart = (await call()).body.chart;+ const deleted = await call({ action: "flow_node_delete", expected_revision: chart.revision, data: { unitId: "flow-workspace", id: first } });+ expect(deleted.status).toBe(200);+ expect(deleted.body.chart.units.find((u) => u.id === "flow-workspace").projectFlow.edges).toEqual([]);+ expect(errors).toEqual([]);+ console.log("PASS: compact overview; internal node create/edit/connect/drag; visible directional edges after reload; multiline notes >16 KiB; reload persistence; real MCP mutation; stale revision/cross-unit/viewer/read-scope refusal; 3 responsive viewports; cascade delete; no browser errors.");+} finally { await browser?.close(); await fixture.close(); }diff --git a/scripts/e2e/organization.mjs b/scripts/e2e/organization.mjsindex fbaf981e..9805fb6a 100644--- a/scripts/e2e/organization.mjs+++ b/scripts/e2e/organization.mjs@@ -67,6 +67,7 @@ export async function organizationJourney(page, fixture) {await page.goto(fixture.base + "/organization");await page.getByRole("button", { name: /E2E Product/ }).click();+ await page.getByRole("button", { name: "Seats", exact: true }).click();const seatCanvas = page.getByRole("application", { name: "Organization seats canvas" });await expect(seatCanvas).toBeVisible();await expect(seatCanvas.locator(".react-flow__node", { hasText: "Chief Executive Officer" })).toBeVisible();diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjsindex 8a7660b1..6643df82 100644--- a/scripts/e2e/release.mjs+++ b/scripts/e2e/release.mjs@@ -11,6 +11,7 @@ import { storeExtensionsJourney } from "./store-extensions.mjs";import { releaseFixture } from "./release-fixture.mjs";execFileSync(process.execPath, ["scripts/e2e/mcp-page.mjs"], { stdio: "inherit" });+execFileSync(process.execPath, ["scripts/e2e/organization-flow.mjs"], { stdio: "inherit" });const fixture = await releaseFixture();let browser;try {