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
fix(security): preserve worker grants and bound file reads
Abdurrahman Fakhrula9f50c0112ff
diff --git a/SECURITY.md b/SECURITY.mdindex 7b9f290d..34e9bccc 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -194,8 +194,8 @@ Vendor dashboards require `allow-same-origin` to function. Running that JavaScricockpit origin would give it the owner's browser realm/session. MSO therefore has nosupported same-origin dashboard mode.-The safe default is **no embedded vendor dashboard**. To embed dashboards, set both-`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and `OS_SESSION_COOKIE_DOMAIN` and give each app a+The safe default is **no embedded vendor dashboard**. To embed dashboards, set+`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and give each app aseparate hostname, for example:```text@@ -236,6 +236,11 @@ app identity, state path and symlink collisions before writing, then creates an## In scope+Authenticated raw-file responses allow four concurrent streams per device and sixteen+per process. Each response is capped at 32 MiB; larger files require bounded byte ranges.+Streams close after ten idle seconds or sixty total seconds, and cancellation closes+the pinned descriptor. Saturation returns HTTP 429 before opening the file.+- auth/session/device-approval or role-escalation bypass;- practical login rate-limit defeat;- filesystem-jail or credential-denylist escape;@@ -268,6 +273,6 @@ app identity, state path and symlink collisions before writing, then creates an- rotate provider credentials from Settings → AI or the corresponding environment source;- rotate managed-app credentials if a state snapshot containing them was exposed.-`~/.mso/audit.log` is append-oriented local forensic data and can grow. Use normal host log-retention/rotation and inspect it before sharing because paths and command context can be+`~/.mso/audit.log` is append-oriented local forensic data, rotated at 8 MiB. Inspect it+before sharing because paths and command context can besensitive.diff --git a/app/api/v1/fs/raw/route.test.ts b/app/api/v1/fs/raw/route.test.tsnew file mode 100644index 00000000..2b9cf3c1--- /dev/null+++ b/app/api/v1/fs/raw/route.test.ts@@ -0,0 +1,91 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdtemp, open, rm, writeFile, type FileHandle } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+let actor = "viewer";+const handles: FileHandle[] = [], responses: Response[] = [];+vi.mock("@/lib/agent/server", () => ({ verifyAuth: async () => true }));+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: async () => actor }));+vi.mock("@/lib/host/fs-api", async importOriginal => {+ const original = await importOriginal<typeof import("@/lib/host/fs-api")>();+ return { ...original, statReadable: async (name: string) => {+ const info = await original.statReadable(name); handles.push(info.handle); return info;+ } };+});+import { GET } from "./route";+let root: string, small: string, large: string;+beforeEach(async () => {+ actor = "viewer"; handles.length = 0; responses.length = 0;+ root = await mkdtemp(path.join(os.tmpdir(), "mso-raw-bounds-"));+ vi.stubEnv("OS_FS_READ_ROOTS", root);+ small = path.join(root, "small.txt"); large = path.join(root, "large.mp4");+ await writeFile(small, "abcdef");+ const handle = await open(large, "w"); await handle.truncate(40 * 1024 * 1024); await handle.close();+});+afterEach(async () => {+ for (const response of responses) await response.body?.cancel().catch(() => undefined);+ vi.useRealTimers();+ await vi.waitFor(async () => { for (const handle of handles) await expect(handle.stat()).rejects.toThrow(); });+ vi.unstubAllEnvs(); await rm(root, { recursive: true, force: true });+});+async function get(name = small, range?: string, signal?: AbortSignal) {+ const response = await GET(new Request(`http://localhost/api/v1/fs/raw?path=${encodeURIComponent(name)}`, { headers: range ? { range } : {}, signal }));+ responses.push(response); return response;+}+describe("bounded Viewer raw file responses", () => {+ it("closes empty-file descriptors before returning an empty body", async () => {+ await writeFile(small, "");+ const response = await get();+ expect(response.status).toBe(200); expect(response.headers.get("content-length")).toBe("0");+ await expect(handles[0].stat()).rejects.toThrow();+ await writeFile(small, "later");+ expect(await response.text()).toBe("");+ });+ it("preserves exact small-file bytes and suffix seeking", async () => {+ expect(await (await get()).text()).toBe("abcdef");+ const suffix = await get(small, "bytes=-2");+ expect(suffix.status).toBe(206); expect(suffix.headers.get("content-range")).toBe("bytes 4-5/6");+ expect(await suffix.text()).toBe("ef");+ });+ it("refuses large full responses and clips large ranges without buffering the file", async () => {+ expect((await get(large)).status).toBe(413);+ const response = await get(large, "bytes=0-");+ expect(response.status).toBe(206);+ expect(response.headers.get("content-length")).toBe(String(32 * 1024 * 1024));+ expect(response.headers.get("content-range")).toBe(`bytes 0-${32 * 1024 * 1024 - 1}/${40 * 1024 * 1024}`);+ });+ it.each(["bytes=-0", "bytes=9-10", "bytes=2-1", "bytes=0-1,2-3", "garbage"])("closes invalid ranges: %s", async range => {+ expect((await get(small, range)).status).toBe(416);+ await expect(handles[0].stat()).rejects.toThrow();+ });+ it("rejects excess per-device streams before opening a descriptor and releases cancelled slots", async () => {+ for (let i = 0; i < 4; i++) expect((await get(large, "bytes=0-")).status).toBe(206);+ expect((await get(large, "bytes=0-")).status).toBe(429); expect(handles).toHaveLength(4);+ await responses[0].body!.cancel();+ await vi.waitFor(async () => { await expect(handles[0].stat()).rejects.toThrow(); });+ await vi.waitFor(async () => expect((await get(large, "bytes=0-")).status).toBe(206));+ });+ it("rejects process-wide saturation across devices before opening a descriptor", async () => {+ for (let i = 0; i < 16; i++) { actor = `viewer-${i}`; expect((await get(large, "bytes=0-")).status).toBe(206); }+ actor = "another"; expect((await get(large, "bytes=0-")).status).toBe(429); expect(handles).toHaveLength(16);+ });+ it("closes the descriptor on client abort", async () => {+ const controller = new AbortController(), response = await get(large, "bytes=0-", controller.signal);+ const reader = response.body!.getReader();+ controller.abort(); await expect(reader.read()).rejects.toThrow(/aborted/); reader.releaseLock();+ });+ it("closes idle streams and releases their descriptors", async () => {+ vi.useFakeTimers();+ const response = await get(large, "bytes=0-"), reader = response.body!.getReader();+ await reader.read();+ await vi.advanceTimersByTimeAsync(10_001);+ await expect(reader.read()).rejects.toThrow(/deadline/); reader.releaseLock();+ });+ it("closes a continuously read stream at the total lifetime", async () => {+ vi.useFakeTimers();+ const response = await get(large, "bytes=0-"), reader = response.body!.getReader();+ for (let i = 0; i < 6; i++) { await reader.read(); await vi.advanceTimersByTimeAsync(9_000); }+ await reader.read(); await vi.advanceTimersByTimeAsync(6_001);+ await expect(reader.read()).rejects.toThrow(/deadline/); reader.releaseLock();+ });+});diff --git a/app/api/v1/fs/raw/route.ts b/app/api/v1/fs/raw/route.tsindex f94d4810..00b23f9b 100644--- a/app/api/v1/fs/raw/route.ts+++ b/app/api/v1/fs/raw/route.ts@@ -3,9 +3,13 @@ import { Readable } from "stream";import { verifyAuth } from "@/lib/agent/server";import { apiError } from "@/lib/host/request-api";import { fileStream, statReadable } from "@/lib/host/fs-api";+import { getSessionActor } from "@/lib/auth/require-session";+import { readAdmission, ReadBusyError } from "@/lib/read-admission";export const runtime = "nodejs";export const dynamic = "force-dynamic";+const MAX_RESPONSE_BYTES = 32 * 1024 * 1024;+const admitStream = readAdmission(4, 16);// Raw file bytes for media preview (image/video/audio/pdf). Same-origin so the// session cookie authenticates it directly as an <img>/<video>/<audio> src.@@ -16,11 +20,20 @@ export async function GET(req: Request) {const path = new URL(req.url).searchParams.get("path") ?? "";if (!path) return NextResponse.json({ error: "path required" }, { status: 400 });+ const actor = await getSessionActor();+ if (!actor) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ let release: () => void;+ try { release = admitStream(actor); }+ catch (error) {+ if (error instanceof ReadBusyError) return NextResponse.json({ error: "file_streams_busy" }, { status: 429 });+ throw error;+ }let info: Awaited<ReturnType<typeof statReadable>>;try {info = await statReadable(path);} catch (e) {+ release();return apiError("fs/raw", e, { status: 404, error: "Not found" });}@@ -35,23 +48,35 @@ export async function GET(req: Request) {// scripts when the SVG is loaded as a document; <img>/<image> previews are// unaffected (browsers never script SVG loaded as an image).if (info.mime === "image/svg+xml") base["content-security-policy"] = "sandbox";- const toWeb = (s: ReturnType<typeof fileStream>) =>- Readable.toWeb(s) as unknown as ReadableStream;+ const toWeb = (s: ReturnType<typeof fileStream>) => {+ let idle: ReturnType<typeof setTimeout>;+ const expire = () => s.destroy(new Error("raw file stream deadline exceeded"));+ const resetIdle = () => { clearTimeout(idle); idle = setTimeout(expire, 10_000); idle.unref?.(); };+ const total = setTimeout(expire, 60_000); total.unref?.();+ const abort = () => s.destroy(new Error("raw file request aborted"));+ s.once("close", () => { clearTimeout(idle); clearTimeout(total); req.signal.removeEventListener("abort", abort); release(); });+ s.on("data", resetIdle);+ req.signal.addEventListener("abort", abort, { once: true });+ resetIdle();+ const web = Readable.toWeb(s, { strategy: { highWaterMark: 64 * 1024, size: chunk => chunk.byteLength } }) as ReadableStream;+ if (req.signal.aborted) abort();+ return web;+ };+ const refuse = async (status: number, error: string) => {+ try { await info.handle.close(); } finally { release(); }+ return NextResponse.json({ error }, { status, headers: { "content-range": `bytes */${info.size}`, "accept-ranges": "bytes" } });+ };const range = req.headers.get("range");- const m = range && /bytes=(\d*)-(\d*)/.exec(range);+ const m = range && /^bytes=(\d*)-(\d*)$/.exec(range);+ if (range && (!m || (!m[1] && !m[2]))) return refuse(416, "invalid range");if (m) {- let start = m[1] ? parseInt(m[1], 10) : 0;- let end = m[2] ? parseInt(m[2], 10) : info.size - 1;+ let start = m[1] ? parseInt(m[1], 10) : Math.max(0, info.size - Number(m[2]));+ let end = m[1] && m[2] ? parseInt(m[2], 10) : info.size - 1;if (Number.isNaN(start)) start = 0;if (Number.isNaN(end) || end >= info.size) end = info.size - 1;- if (start > end || start >= info.size) {- await info.handle.close();- return new Response(null, {- status: 416,- headers: { "content-range": `bytes */${info.size}` },- });- }+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start > end || start >= info.size) return refuse(416, "invalid range");+ end = Math.min(end, start + MAX_RESPONSE_BYTES - 1);return new Response(toWeb(fileStream(info.handle, start, end)), {status: 206,headers: {@@ -61,8 +86,13 @@ export async function GET(req: Request) {},});}+ if (info.size > MAX_RESPONSE_BYTES) return refuse(413, "large files require a bounded byte range");+ if (info.size === 0) {+ try { await info.handle.close(); } finally { release(); }+ return new Response(null, { headers: { ...base, "content-length": "0" } });+ }- return new Response(toWeb(fileStream(info.handle)), {+ return new Response(toWeb(fileStream(info.handle, 0, Math.max(0, info.size - 1))), {status: 200,headers: { ...base, "content-length": String(info.size) },});diff --git a/app/mcp/route.test.ts b/app/mcp/route.test.tsindex ce078cee..7fc7eea2 100644--- a/app/mcp/route.test.ts+++ b/app/mcp/route.test.ts@@ -4,7 +4,7 @@ const mocks = vi.hoisted(() => ({validateToken: vi.fn(),touchToken: vi.fn(async () => {}),getClient: vi.fn(),- dispatch: vi.fn(async () => ({ jsonrpc: "2.0", id: 1, result: {} })),+ dispatch: vi.fn(async (): Promise<Record<string, unknown>> => ({ jsonrpc: "2.0", id: 1, result: {} })),clampScope: vi.fn((scope: "read" | "write" | "exec") => scope),rateLimited: vi.fn(() => false),rateLimitedUntrusted: vi.fn(() => false),@@ -68,6 +68,14 @@ function request(body: BodyInit, headers: Record<string, string> = {}) {}describe("/mcp request boundary", () => {+ it("returns HTTP 429 when file resource admission is saturated", async () => {+ mocks.validateToken.mockResolvedValue({ hash: "bounded", scope: "read", label: "read fixture" });+ mocks.dispatch.mockResolvedValueOnce({ jsonrpc: "2.0", id: 1, error: { code: -32002, message: "file reads busy" } });+ const { POST } = await import("./route");+ const response = await POST(request(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "resources/read", params: { uri: "mso-file:///fixture" } })));+ expect(response.status).toBe(429);+ expect((await response.json()).error.message).toBe("file reads busy");+ });beforeEach(() => {mocks.validateToken.mockReset();mocks.touchToken.mockClear();diff --git a/app/mcp/route.ts b/app/mcp/route.tsindex b82be19a..aabc1a4f 100644--- a/app/mcp/route.ts+++ b/app/mcp/route.ts@@ -136,7 +136,8 @@ export async function POST(req: Request) {if (isWait && !await liveAuthorization().then(()=>true,()=>false)) return unauthorized("invalid, revoked or expired MCP token");const result = await dispatch(rpc, effectiveScope, actor, {...agentContext,signal:wait?.signal ?? req.signal});if (isWait && !await liveAuthorization().then(()=>true,()=>false)) return unauthorized("invalid, revoked or expired MCP token");- return Response.json(wire.modern ? modernMcpResult(result, MCP_SERVER_VERSION, rpc.method) : result, { status: wire.modern && (result.error as { code?: number } | undefined)?.code === -32601 ? 404 : 200, headers });+ const code = (result.error as { code?: number } | undefined)?.code;+ return Response.json(wire.modern ? modernMcpResult(result, MCP_SERVER_VERSION, rpc.method) : result, { status: code === RATE_LIMITED ? 429 : wire.modern && code === -32601 ? 404 : 200, headers });} finally {wait?.release();}}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 4ccd5f90..95466cfb 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -271,7 +271,7 @@ default. 9Router can expose `http://<public-ip>:20128` only when the operator exthe only browser-facing surface.Embedded vendor dashboards are optional. A split-origin deployment opts in by setting-`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and `OS_SESSION_COOKIE_DOMAIN`, giving each embedded+`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE`, giving each embeddeddashboard its own hostname while the same MSO process proxies its loopback upstream. Thereis no supported same-origin dashboard mode.diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 51682532..790c6d51 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -12,6 +12,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Fixed**+- `security` preserve worker grants and bound file reads- `mcp` retain scanner limits and document mailbox parity- `security` close credential sinks and revoke pending sessions- `mcp` preserve managed configuration behind credential guardsdiff --git a/docs/MCP.md b/docs/MCP.mdindex 4b0fa5e0..74844bc2 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -609,7 +609,7 @@ Raster files must also fully decode through bounded Sharp validation; magic byte**`fs_export_file`** is the read-side counterpart for one original file up to **10 MiB**. It usesthe same `OS_FS_READ_ROOTS`, realpath and credential denylist as other reads, reads with`O_NOFOLLOW`, computes SHA-256 over the original bytes, then copies those bytes into the existing-private temporary-share store and creates an owner+conversation-session-bound `mso-file:///…` MCP resource. `resources/read` returns that resource as the exact base64 `blob` only to the same authenticated MCP principal and session; it expires after 15 minutes and is read-count bounded. The approved-device browser download remains a separate fallback. Neither path routes through `session_artifacts`, so images and archives are not recompressed or text-decoded. After a public tool/schema change, deploy first, then Scan Tools / Refresh in ChatGPT and test from a new chat. See `CHATGPT-PLUGIN.md` for the end-to-end contract.+private temporary-share store and creates an owner+conversation-session-bound `mso-file:///…` MCP resource. `resources/read` returns that resource as the exact base64 `blob` only to the same authenticated MCP principal and session; it expires after 15 minutes and defaults to five reads. Each read atomically consumes its allowance before loading the file, including failed reads. Admission allows four concurrent reads per principal and eight per process; saturation returns `RATE_LIMITED` with HTTP 429. The approved-device browser download remains a separate fallback. Neither path routes through `session_artifacts`, so images and archives are not recompressed or text-decoded. After a public tool/schema change, deploy first, then Scan Tools / Refresh in ChatGPT and test from a new chat. See `CHATGPT-PLUGIN.md` for the end-to-end contract.`OS_CODEX_BUILTIN_TOOLS` still exists and still takes an allowlisted list, but itsdefault is now EMPTY and `image_generation` is no longer an accepted value — naming itdiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 54c8c9a7..e9f586da 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,15 @@+## 2026-10-10: Close the three Medium findings from the 5a271a38 scan++Project workers now receive the exact initiating authority in both waited and detached execution. The shared runner requires that context, rejects scope escalation and combines parent cancellation with its own timeout. Real credential-store regressions cover child catalog/argument restrictions, token revoke/expiry, deployment changes and detached workers; parent cancellation also reaches model streaming.++Viewer raw-file responses admit four active streams per device and sixteen per process before opening a descriptor. Responses are capped at 32 MiB; larger files require ranges, oversized ranges are clipped and suffix seeking remains available. The Web stream queues at most 64 KiB, closes after ten idle seconds or sixty total seconds, and releases admission on descriptor closure, abort or cancellation.++MCP file resources claim read allowance under the existing cross-process security-store lock before allocating bytes. Failed reads never refund or resurrect claims. Four active reads per principal and eight per process bound allocation; saturation becomes HTTP 429 and the MCP rate-limit error. Ownership, session binding, expiry and integrity checks remain intact. Concurrent and saturation regressions cover exhaustion, cleanup and admission before file loading. Documentation also removes stale shared-cookie guidance and describes the existing audit rotation.++## 2026-10-10: Refresh workflow receipts after fast completion++Required CI exposed a status race: the first disk read captured a running receipt, then completion removed the pending promise while the authority check yielded. Positive-wait status requests now reread the receipt even when no pending promise remains. Wait limits, ownership, original execution authority and final live-authority checks remain intact. A deterministic regression reproduces the stale snapshot and fails before the shared fix; HTTP, MCP, webhook and repeat callers inherit the correction.+## 2026-10-10: Replace desktop streaming with a native repository knowledge viewThe owner found the streamed Obsidian desktop slow and unsuitable for mobile, and requested a KISS implementation built on Organization and Memory. Agent Vault now reads the same separate private Markdown snapshots directly in MSO. Metadata loads first, note bodies load only on selection, and local title/type/source search adds no typing requests. Mobile navigation gives the list and reader their own full pane, with an explicit return action; desktop retains a sidebar. Capture history remains recorded repository evidence rather than live agent/deployment status.diff --git a/lib/agent/delegated-authority.test.ts b/lib/agent/delegated-authority.test.tsindex e95b97cb..402c3c03 100644--- a/lib/agent/delegated-authority.test.ts+++ b/lib/agent/delegated-authority.test.ts@@ -5,14 +5,19 @@ import path from "node:path";import type { CapabilityRuntime } from "@/lib/capabilities/runtime";const stream = vi.hoisted(() => vi.fn());vi.mock("./session-store", () => ({ getAgentSession: async () => ({ id: "parent", cwd: "/fixture" }) }));+vi.mock("@/lib/mcp/tools-project-shared", () => ({ selectedProject: async () => ({ id: "fixture", name: "Fixture", path: "/fixture" }) }));+vi.mock("@/lib/mcp/workflow-workspace-guard", () => ({ requireWorkflowProjectTarget: async () => undefined }));vi.mock("@/lib/ai/selected-model-stream", () => ({ prepareSelectedModel: async () => ({}), streamPreparedSelectedModel: stream }));const root = await mkdtemp(path.join(os.tmpdir(), "mso-worker-grant-"));process.env.OS_MCP_STORE = path.join(root, "mcp.json");+process.env.OS_PROJECT_AGENT_TASKS_DIR = path.join(root, "tasks");const store = await import("@/lib/mcp/store");const state = await import("@/lib/mcp/store-state");const { mcpAuthorizationGrant, authorizeDurableGrant } = await import("@/lib/mcp/durable-grant");const { runSessionSubagent } = await import("./subagent-runner");const { runInboundA2AAgent } = await import("@/lib/a2a/inbound-agent");+const { PROJECT_RUNTIME_TOOLS } = await import("@/lib/mcp/tools-project-runtime");+const { getProjectAgentTask } = await import("./project-agent-task-store");const invoke = vi.fn(async () => ({ content: [{ type: "text" as const, text: "ok" }] }));const capabilities: CapabilityRuntime = { authorize: authorizeDurableGrant, invoke, list: () => [{ name: "project_get", scope: "read", description: "read", inputSchema: { type: "object", properties: {} } },@@ -20,7 +25,7 @@ const capabilities: CapabilityRuntime = { authorize: authorizeDurableGrant, invo] };beforeEach(() => { stream.mockReset(); invoke.mockClear(); vi.stubEnv("OS_MCP_MAX_SCOPE", "exec"); });afterEach(() => vi.unstubAllEnvs());-afterAll(async () => { delete process.env.OS_MCP_STORE; await rm(root, { recursive: true, force: true }); });+afterAll(async () => { delete process.env.OS_MCP_STORE; delete process.env.OS_PROJECT_AGENT_TASKS_DIR; await rm(root, { recursive: true, force: true }); });async function authority() {await store.storeToken("worker", { label: "fixture", clientId: "worker", scope: "exec", allowedTools: ["project_get"], toolArgumentConstraints: { project_get: { project: ["approved"] } } });const token = (await store.validateToken("worker"))!;@@ -29,6 +34,15 @@ async function authority() {const workers = {subagent: async (context: Awaited<ReturnType<typeof authority>>) => runSessionSubagent({ principal: context.principal, parentSessionId: "parent", objective: "inspect", maxScope: "exec", capabilities, authority: context }),local: async (context: Awaited<ReturnType<typeof authority>>) => runInboundA2AAgent({ prompt: "inspect", principal: "a2a:local:target", scope: "exec", taskId: "task", signal: new AbortController().signal, capabilities, executionContext: { authority: context } }),+ ...Object.fromEntries([true, false].map(wait => [`project wait=${wait}`, async (context: Awaited<ReturnType<typeof authority>>) => {+ const output = await PROJECT_RUNTIME_TOOLS.find(tool => tool.name === "project_agent_run")!.run(+ { project: "fixture", message: "inspect", max_scope: "exec", wait }, { ...context, sessionId: "parent" },+ ) as { message_id: string };+ let task = await getProjectAgentTask(context.principal, output.message_id);+ await vi.waitFor(async () => { task = await getProjectAgentTask(context.principal, output.message_id); expect(task?.status).not.toBe("in_progress"); });+ if (task?.status === "failed") throw new Error(task.error);+ return task;+ }])),};describe.each(Object.entries(workers))("%s live initiating authority", (_name, run) => {it("intersects the catalog and preserves the exact grant and argument restrictions", async () => {diff --git a/lib/agent/subagent-runner.test.ts b/lib/agent/subagent-runner.test.tsindex eff378a6..e30add83 100644--- a/lib/agent/subagent-runner.test.ts+++ b/lib/agent/subagent-runner.test.ts@@ -26,6 +26,19 @@ const { runSessionSubagent } = await import("./subagent-runner");describe("same-session subagent runner", () => {beforeEach(() => { stream.mockReset(); dispatch.mockReset(); });+ it("cancels model streaming when the initiating task signal is aborted", async () => {+ const controller = new AbortController();+ stream.mockImplementationOnce(async ({ signal }) => {+ expect(signal.aborted).toBe(false);+ controller.abort(new Error("parent task revoked"));+ expect(signal.aborted).toBe(true);+ throw signal.reason;+ });+ await expect(runSessionSubagent({ principal: "mcp-client:x", parentSessionId: "session-a", objective: "inspect", capabilities,+ authority: { principal: "mcp-client:x", scope: "read", signal: controller.signal },+ })).rejects.toThrow(/revoked/);+ expect(dispatch).not.toHaveBeenCalled();+ });it.each([null, { role: "operator" }])("stops after original Owner authority changes during a model round: %j", async changed => {device.mockResolvedValue({ role: "owner" });stream.mockImplementationOnce(async ({ emit }) => {@@ -45,7 +58,7 @@ describe("same-session subagent runner", () => {opts.emit("tool_use", { id: "tool-1", name: "fs_read", input: {} });}).mockImplementationOnce(async ({ emit }) => emit("delta", "review complete"));dispatch.mockResolvedValue({ content: [{ type: "text", text: "file data" }] });- const result = await runSessionSubagent({ principal: "mcp-client:x", parentSessionId: "session-a", objective: "review auth", capabilities });+ const result = await runSessionSubagent({ principal: "mcp-client:x", parentSessionId: "session-a", objective: "review auth", capabilities, authority: { principal: "mcp-client:x", scope: "read" } });expect(seenTools).toEqual(["fs_read"]);expect(result).toMatchObject({ status: "completed", text: "review complete", rounds: 2, maxScope: "read" });expect(result.toolCalls).toEqual([{ name: "fs_read", ok: true }]);@@ -58,7 +71,7 @@ describe("same-session subagent runner", () => {it("never exposes local-agent or recursive subagent tools even with exec scope", async () => {let names: string[] = [];stream.mockImplementationOnce(async ({ tools, emit }) => { names = tools.map((tool: { name: string }) => tool.name); emit("delta", "done"); });- const result = await runSessionSubagent({ principal: "mcp-client:x", parentSessionId: "session-a", objective: "inspect", maxScope: "exec", capabilities });+ const result = await runSessionSubagent({ principal: "mcp-client:x", parentSessionId: "session-a", objective: "inspect", maxScope: "exec", capabilities, authority: { principal: "mcp-client:x", scope: "exec" } });expect(names).toContain("fs_read");expect(names).toContain("fs_write");expect(names).not.toContain("local_agent_message_send");diff --git a/lib/agent/subagent-runner.ts b/lib/agent/subagent-runner.tsindex 51796c04..a2deb3d7 100644--- a/lib/agent/subagent-runner.ts+++ b/lib/agent/subagent-runner.ts@@ -62,7 +62,7 @@ export async function runSessionSubagent(input: {timeoutMs?: number;explicitContext?: string;capabilities: CapabilityRuntime;- authority?: CapabilityRunContext;+ authority: CapabilityRunContext;}) {const parent = await getAgentSession(input.principal, input.parentSessionId);if (!parent) throw new Error("parent MSO Agent session not found");@@ -71,16 +71,19 @@ export async function runSessionSubagent(input: {if (Buffer.byteLength(objective, "utf8") > 24 * 1024) throw new Error("subagent objective must be 24 KiB or smaller");const name = String(input.name || "worker").trim().replace(/[\r\n\t]+/g, " ").slice(0, 60) || "worker";const maxScope = parseScope(input.maxScope || "read");+ if (!allows(input.authority.scope, maxScope)) throw new Error("subagent scope exceeds initiating authority");const maxTurns = Math.max(1, Math.min(maxTurnsLimit(), Math.trunc(input.maxTurns || DEFAULT_TURNS)));const timeoutMs = Math.max(1_000, Math.min(MAX_TIMEOUT_MS, Math.trunc(input.timeoutMs || DEFAULT_TIMEOUT_MS)));const subagentId = `subagent_${randomUUID()}`;- const authority = { ...input.authority, principal: input.authority?.principal ?? input.principal, scope: maxScope, capabilities: input.capabilities };+ const authority = { ...input.authority, principal: input.authority.principal ?? input.principal, scope: maxScope, capabilities: input.capabilities };const toolDefs = (context: CapabilityRunContext) => input.capabilities.list(context.scope, context).filter((tool) => allows(context.scope, tool.scope) && allowedTool(tool.name) && (!context.allowedTools || context.allowedTools.includes(tool.name)));const prepared = await prepareSelectedModel();const messages: OaMsg[] = [{ role: "user", text: objective }];const toolCalls: Array<{ name: string; ok: boolean }> = [];const controller = new AbortController();const timeout = setTimeout(() => controller.abort(new Error("subagent timeout")), timeoutMs);+ const signal = AbortSignal.any([controller.signal, ...(authority.signal ? [authority.signal] : [])]);+ authority.signal = signal;let finalText = "";try {for (let round = 1; round <= maxTurns; round += 1) {@@ -91,7 +94,7 @@ export async function runSessionSubagent(input: {await streamPreparedSelectedModel({prepared, messages, tools,system: systemPrompt({ name, objective, cwd: parent.cwd, maxScope, explicitContext: input.explicitContext }),- signal: controller.signal,+ signal,emit(event, data) {if (event === "delta") text += String(data ?? "");else if (event === "tool_use") uses.push(data as OaToolUse);diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.tsindex 8522160f..48983ffe 100644--- a/lib/mcp/dispatch.ts+++ b/lib/mcp/dispatch.ts@@ -5,6 +5,7 @@ import { MCP_APP_MIME_TYPE, MCP_UI_EXTENSION, MCP_UI_EXTENSION_CAPABILITY, listUimport { MCP_SKILLS_EXTENSION, getMcpSkill, listMcpSkills, readMcpSkillResource } from "./skills-extension";import { dispatchToolCall } from "./dispatch-tools";import { readMcpFileResource } from "./file-transfer-resource";+import { ReadBusyError } from "@/lib/read-admission";import { toolDescriptor, visibleToolsForProfile, type McpToolProfile } from "./tool-contract";import { MCP_PROTOCOL_LATEST, MCP_PROTOCOLS, negotiateMcpProtocol } from "./protocol";import { mcpInstructions } from "./instructions";@@ -129,7 +130,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string, ag} catch (error) {const message = error instanceof Error ? error.message : String(error);activityFinish(activity, "resources.read", scope, actor, "failed", uri, message);- return rpcFail(id, -32602, message);+ return rpcFail(id, error instanceof ReadBusyError ? RATE_LIMITED : -32602, message);}try {const skillResource = await readMcpSkillResource(uri);diff --git a/lib/mcp/file-transfer-resource.test.ts b/lib/mcp/file-transfer-resource.test.tsindex 58f2f4d6..324584bf 100644--- a/lib/mcp/file-transfer-resource.test.ts+++ b/lib/mcp/file-transfer-resource.test.ts@@ -6,7 +6,7 @@ import { createMcpFileResource, readMcpFileResource } from "./file-transfer-resoconst ROOT = path.join(os.tmpdir(), `mso-mcp-file-resources-${process.pid}`);beforeEach(async () => { await fs.rm(ROOT, { recursive: true, force: true }); vi.useRealTimers(); });-afterEach(async () => { vi.useRealTimers(); await fs.rm(ROOT, { recursive: true, force: true }); });+afterEach(async () => { vi.restoreAllMocks(); vi.useRealTimers(); await fs.rm(ROOT, { recursive: true, force: true }); });describe("principal-bound MCP file resources", () => {it("returns exact bytes only to the creating principal", async () => {@@ -23,6 +23,28 @@ describe("principal-bound MCP file resources", () => {expect((await readMcpFileResource(one.uri, "alice", "session-a"))?.data.toString()).toBe("x");await expect(readMcpFileResource(one.uri, "alice", "session-a")).rejects.toThrow(/unknown or expired/i);});+ it("claims concurrent reads atomically without resurrecting the allowance", async () => {+ const resource = await createMcpFileResource({ data: Buffer.from("bounded"), filename: "x.txt", mimeType: "text/plain", principal: "alice", sessionId: "session-a", maxReads: 5 });+ const burst = await Promise.allSettled(Array.from({ length: 20 }, () => readMcpFileResource(resource.uri, "alice", "session-a")));+ const completed = burst.filter(result => result.status === "fulfilled").length;+ expect(completed).toBeGreaterThan(0);+ expect(completed).toBeLessThanOrEqual(5);+ expect(burst.some(result => result.status === "rejected" && /busy/.test(String(result.reason)))).toBe(true);+ for (let remaining = completed; remaining < 5; remaining++) await readMcpFileResource(resource.uri, "alice", "session-a");+ await expect(readMcpFileResource(resource.uri, "alice", "session-a")).rejects.toThrow(/unknown or expired/);+ expect(await fs.readdir(ROOT)).toEqual([]);+ });+ it("rejects process-wide saturation before reading file bytes and releases completed claims", async () => {+ const resources = await Promise.all(Array.from({ length: 9 }, (_, index) => createMcpFileResource({+ data: Buffer.from("bounded"), filename: "x.txt", mimeType: "text/plain", principal: `reader-${index}`, sessionId: "session-a",+ })));+ const read = vi.spyOn(fs, "readFile");+ const active = resources.slice(0, 8).map((resource, index) => readMcpFileResource(resource.uri, `reader-${index}`, "session-a"));+ await expect(readMcpFileResource(resources[8].uri, "reader-8", "session-a")).rejects.toThrow(/busy/);+ expect(read.mock.calls.some(([name]) => String(name).endsWith(`${resources[8].id}.bin`))).toBe(false);+ await Promise.all(active);+ expect((await readMcpFileResource(resources[8].uri, "reader-8", "session-a"))?.data.toString()).toBe("bounded");+ });it("expires after its TTL", async () => {vi.useFakeTimers();const now = Date.now(); vi.setSystemTime(now);diff --git a/lib/mcp/file-transfer-resource.ts b/lib/mcp/file-transfer-resource.tsindex 5b5a5ce4..81d53476 100644--- a/lib/mcp/file-transfer-resource.ts+++ b/lib/mcp/file-transfer-resource.ts@@ -2,12 +2,15 @@ import { createHash, randomBytes } from "crypto";import { promises as fs } from "fs";import os from "os";import path from "path";+import { withSecurityStoreLock } from "@/lib/security-store-lock";+import { readAdmission } from "@/lib/read-admission";const VERSION = 1 as const;const MAX_BYTES = 10 * 1024 * 1024;const DEFAULT_TTL_MS = 15 * 60_000;const DEFAULT_READS = 5;const ID_RE = /^[a-f0-9]{48}$/;+const admitRead = readAdmission(4, 8);type Entry = {version: typeof VERSION; id: string; file: string; filename: string; mimeType: string;@@ -85,26 +88,32 @@ export async function readMcpFileResource(uri: string, principal?: string, sessiconst id = idFromUri(uri);if (!id) return null;if (!principal || !sessionId) throw new Error("authenticated MCP principal and session required for file resource");- let entry: Entry;- try { entry = await readEntry(id); } catch { throw new Error("unknown or expired file resource"); }- if (entry.ownerHash !== ownerHash(principal, sessionId)) throw new Error("unknown or expired file resource");- if (entry.expiresAt <= Date.now() || entry.readsLeft <= 0) {- await remove(id).catch(() => undefined);- throw new Error("unknown or expired file resource");- }- let data: Buffer;- try { data = await fs.readFile(dataPath(id)); } catch {- await remove(id).catch(() => undefined);- throw new Error("unknown or expired file resource");- }- const actual = createHash("sha256").update(data).digest("hex");- if (data.length !== entry.bytes || actual !== entry.sha256) {- await remove(id).catch(() => undefined);- throw new Error("file resource integrity check failed");- }- entry.readsLeft -= 1;- if (entry.readsLeft <= 0) await remove(id);- else await writeEntry(entry);- const { ownerHash: _owner, file: _file, version: _version, ...safe } = entry;- return { ...safe, uri: uriOf(id), data };+ const release = admitRead(principal);+ try {+ return await withSecurityStoreLock(metaPath(id), async () => {+ let entry: Entry;+ try { entry = await readEntry(id); } catch { throw new Error("unknown or expired file resource"); }+ if (entry.ownerHash !== ownerHash(principal, sessionId)) throw new Error("unknown or expired file resource");+ if (entry.expiresAt <= Date.now() || entry.readsLeft <= 0) {+ await remove(id).catch(() => undefined);+ throw new Error("unknown or expired file resource");+ }+ // Claim before allocating bytes; a failed read consumes the claim and never resurrects it.+ entry.readsLeft -= 1;+ await writeEntry(entry);+ let data: Buffer;+ try { data = await fs.readFile(dataPath(id)); } catch {+ await remove(id).catch(() => undefined);+ throw new Error("unknown or expired file resource");+ }+ const actual = createHash("sha256").update(data).digest("hex");+ if (data.length !== entry.bytes || actual !== entry.sha256) {+ await remove(id).catch(() => undefined);+ throw new Error("file resource integrity check failed");+ }+ if (entry.readsLeft <= 0) await remove(id);+ const { ownerHash: _owner, file: _file, version: _version, ...safe } = entry;+ return { ...safe, uri: uriOf(id), data };+ });+ } finally { release(); }}diff --git a/lib/mcp/tools-project-runtime.ts b/lib/mcp/tools-project-runtime.tsindex 911822e6..c13952da 100644--- a/lib/mcp/tools-project-runtime.ts+++ b/lib/mcp/tools-project-runtime.ts@@ -98,7 +98,7 @@ export const PROJECT_RUNTIME_TOOLS: McpTool[] = [objective: `${mode}\nSelected project: ${project.path}\nUser task: ${message}`, maxScope: requested,maxTurns: typeof a.max_turns === "number" ? a.max_turns : undefined, timeoutMs: typeof a.timeout_ms === "number" ? a.timeout_ms : undefined,explicitContext: `Project id=${project.id}; path=${project.path}. Stay focused on this project.`,- capabilities,+ capabilities, authority: context,});return updateProjectAgentTask(context.principal!, task.id, {status: result.status,diff --git a/lib/read-admission.ts b/lib/read-admission.tsnew file mode 100644index 00000000..26e69db2--- /dev/null+++ b/lib/read-admission.ts@@ -0,0 +1,21 @@+export class ReadBusyError extends Error {+ constructor() { super("file reads busy; retry after active reads finish"); }+}++/** Count active work, not requests per minute; release is safe on competing cleanup paths. */+export function readAdmission(perActor: number, global: number) {+ const actors = new Map<string, number>();+ let active = 0;+ return (actor: string) => {+ const count = actors.get(actor) ?? 0;+ if (count >= perActor || active >= global) throw new ReadBusyError();+ actors.set(actor, count + 1); active++;+ let released = false;+ return () => {+ if (released) return;+ released = true; active--;+ const remaining = (actors.get(actor) ?? 1) - 1;+ if (remaining) actors.set(actor, remaining); else actors.delete(actor);+ };+ };+}diff --git a/lib/workflow/graph-engine.ts b/lib/workflow/graph-engine.tsindex 51d9abd7..d0b510fe 100644--- a/lib/workflow/graph-engine.ts+++ b/lib/workflow/graph-engine.ts@@ -79,6 +79,24 @@ export async function startWorkflowGraph(graph: WorkflowGraph, rawInput: unknownconst owner=workflowGraphOwner(principal),input=inputObject(rawInput),fingerprint=hash(canonical({graphId:graph.id,revision:graph.revision,input})),id=workflowGraphRunId(owner,idempotencyKey,graph.id,triggerNodeId);return lockWorkflowGraphRun(owner,id,async()=>{const legacy=await readWorkflowGraphRun(owner,hash(`${owner}:${idempotencyKey}`).slice(0,32));const existing=await readWorkflowGraphRun(owner,id)??(legacy?.graphId===graph.id&&(legacy.trigger?.nodeId??"")===triggerNodeId?legacy:null);if(existing){await requireWorkflowReceiptAuthority(principal,existing,context.scope);if(existing.fingerprint!==fingerprint)throw new Error("idempotency_key already identifies a different graph/input/revision");return publicWorkflowGraphRun(existing);}const device=principal.startsWith("web:")?await getApprovedDevice(principal.slice(4)):null;if(principal.startsWith("web:")&&(!device||device.role==="viewer"))throw new Error("workflow device is revoked or lacks operator authority");await pruneWorkflowGraphRuns(owner);const run:WorkflowGraphRun={version:1,id,owner,sessionId:context.sessionId!,graphId:graph.id,graphRevision:graph.revision,graphName:graph.name,idempotencyKey,fingerprint,executionScope:context.scope,executionRole:device?.role==="owner"?"owner":device?.role==="operator"?"operator":undefined,state:"running",startedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),pid:process.pid,instance:INSTANCE,nodes:graph.nodes.map((node)=>({id:node.id,name:node.name,type:node.type,state:"queued",logs:[]})),edges:graph.edges.map((edge)=>({id:edge.id,source:edge.source,target:edge.target,...(edge.sourceHandle?{sourceHandle:edge.sourceHandle}:{}),state:edge.disabled?"disabled":"pending"})),trigger:trigger??{type:"manual",nodeId:graph.nodes.find((node)=>node.type==="manual")?.id??graph.nodes.find((node)=>["schedule","webhook","channel_trigger"].includes(node.type))?.id,receivedAt:new Date().toISOString()},ancestry:[...ancestry,graph.id],runtimeInput:structuredClone(input)};await writeWorkflowGraphRun(run);await appendAgentSessionEvent(principal,run.sessionId,{kind:"workflow",tool:"workflow_graph",state:"started",workflowId:graph.id,detail:graph.name}).catch(()=>undefined);const work=execute(run,graph,input,context,resolve).then(()=>maybeRunErrorWorkflow(run,graph,context,resolve,principal)).catch(()=>undefined).finally(()=>{pending.delete(id);cancelled.delete(id);});pending.set(id,work);return publicWorkflowGraphRun(run);});}-export async function workflowGraphRunStatus(principal:string,id:string,waitMs=0,scope:CapabilityRunContext["scope"]="exec"){if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>25_000)throw new Error("wait_ms must be 0-25000");const owner=workflowGraphOwner(principal);let run=await readWorkflowGraphRun(owner,id);if(!run)throw new Error("workflow graph run not found for this principal");await requireWorkflowReceiptAuthority(principal,run,scope);if(run.state==="running"&&pending.has(id)&&waitMs>0){let timer:ReturnType<typeof setTimeout>|undefined;await Promise.race([pending.get(id),new Promise((resolve)=>{timer=setTimeout(resolve,waitMs);})]);clearTimeout(timer);run=await readWorkflowGraphRun(owner,id)??run;}if(run.state==="running"&&run.instance!==INSTANCE){let gone=false;try{process.kill(run.pid,0);}catch(error){gone=(error as NodeJS.ErrnoException).code==="ESRCH";}if(gone){run.state="interrupted";run.updatedAt=run.finishedAt=new Date().toISOString();await writeWorkflowGraphRun(run);}}await requireWorkflowReceiptAuthority(principal,run,scope);return publicWorkflowGraphRun(run);}+export async function workflowGraphRunStatus(principal:string,id:string,waitMs=0,scope:CapabilityRunContext["scope"]="exec"){+ if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>25_000)throw new Error("wait_ms must be 0-25000");+ const owner=workflowGraphOwner(principal);let run=await readWorkflowGraphRun(owner,id);+ if(!run)throw new Error("workflow graph run not found for this principal");+ await requireWorkflowReceiptAuthority(principal,run,scope);+ if(run.state==="running"&&waitMs>0){+ const work=pending.get(id);+ if(work){+ let timer:ReturnType<typeof setTimeout>|undefined;+ await Promise.race([work,new Promise((resolve)=>{timer=setTimeout(resolve,waitMs);})]);+ clearTimeout(timer);+ }+ // Completion can remove pending work while the initial authority check yields.+ run=await readWorkflowGraphRun(owner,id)??run;+ }+ if(run.state==="running"&&run.instance!==INSTANCE){let gone=false;try{process.kill(run.pid,0);}catch(error){gone=(error as NodeJS.ErrnoException).code==="ESRCH";}if(gone){run.state="interrupted";run.updatedAt=run.finishedAt=new Date().toISOString();await writeWorkflowGraphRun(run);}}+ await requireWorkflowReceiptAuthority(principal,run,scope);+ return publicWorkflowGraphRun(run);+}export async function requestWorkflowGraphStop(principal:string,id:string,scope:CapabilityRunContext["scope"]="exec"){const owner=workflowGraphOwner(principal),run=await readWorkflowGraphRun(owner,id);if(!run)throw new Error("workflow graph run not found for this principal");await requireWorkflowReceiptAuthority(principal,run,scope);if(run.state!=="running")return{...publicWorkflowGraphRun(run),stopRequested:false};if(run.instance!==INSTANCE||!pending.has(id))throw new Error("workflow execution is owned by another runtime; refresh its status before retrying stop");cancelled.add(id);return{...publicWorkflowGraphRun(run),stopRequested:true};}diff --git a/lib/workflow/graph-receipt-boundary.test.ts b/lib/workflow/graph-receipt-boundary.test.tsindex 2dafcd12..1b5de877 100644--- a/lib/workflow/graph-receipt-boundary.test.ts+++ b/lib/workflow/graph-receipt-boundary.test.ts@@ -10,16 +10,29 @@ vi.mock("@/lib/auth/device-store", () => ({ getApprovedDevice: async () => roleimport { createWorkflowGraph, workflowGraphOwner } from "./graph-store";import { requestWorkflowGraphStop, startWorkflowGraph, workflowGraphRunStatus } from "./graph-engine";import { listWorkflowGraphRuns, readWorkflowGraphRun, writeWorkflowGraphRun } from "./graph-run-store";+import * as runStore from "./graph-run-store";import { requireWorkflowReceiptAuthority } from "./graph-authority";const principal = "web:11223344556677889900aabbccddeeff";const context = { principal, actor: principal, sessionId: "fixture", scope: "exec" as const };let dir: string;beforeEach(async () => { dir = await mkdtemp(path.join(os.tmpdir(), "mso-receipt-boundary-")); role = "owner"; vi.stubEnv("OS_AGENT_SESSIONS_DIR", dir); vi.stubEnv("OS_MCP_MAX_SCOPE", "exec"); });-afterEach(async () => { vi.unstubAllEnvs(); await rm(dir, { recursive: true, force: true }); });+afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); await rm(dir, { recursive: true, force: true }); });async function graph(name: string) {return createWorkflowGraph(principal, { name, description: "", status: "draft", inputs: {}, metadata: {}, nodes: [{ id: "start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} }, { id: "out", name: "Result", type: "output", position: { x: 100, y: 0 }, config: { value: "fixture-private-output" } }], edges: [{ id: "edge", source: "start", target: "out" }] });}describe("workflow receipt identity and creation authority", () => {+ it("refreshes a running snapshot after its execution has already finished", async () => {+ const started = await startWorkflowGraph(await graph("Fast completion"), {}, "fast-key", context, () => undefined);+ const runtime = globalThis as typeof globalThis & { msoGraphPending?: Map<string, Promise<void>> };+ await runtime.msoGraphPending?.get(started.id);+ const completed = (await readWorkflowGraphRun(workflowGraphOwner(principal), started.id))!;+ expect(completed.state).toBe("completed");+ expect(runtime.msoGraphPending?.has(started.id)).toBe(false);+ // A file read can capture the running receipt just before authority checking yields.+ const read = vi.spyOn(runStore, "readWorkflowGraphRun").mockResolvedValueOnce({ ...completed, state: "running" });+ expect((await workflowGraphRunStatus(principal, started.id, 5000)).state).toBe("completed");+ expect(read).toHaveBeenCalledTimes(2);+ });it("rechecks authority after a waited execution finishes", async () => {let release!: () => void;const pending = new Promise<void>(resolve => { release = resolve; });