Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat: integrate verified MSO shell and tenant changes

Abdurrahman Fakhrul8282037cbde2
diff --git a/.env.example b/.env.example
index 863abeab..9650ec5f 100644
--- a/.env.example
+++ b/.env.example
@@ -18,6 +18,13 @@ OS_SESSION_SECRET=
# is ONLY for split-origin managed apps — see that section below; do not set one
# without the other.
+# Experimental source-only tenancy seam. Default legacy leaves current behavior unchanged.
+# tenant-preview denies unimplemented capabilities and has no live registry/storage adapter.
+# Do not enable on a production/shared-user deployment; it is not multiuser readiness.
+# OS_TENANCY_MODE=legacy
+# Existing canonical private tenant store; no default, auto-initialization or enrollment.
+# OS_TENANCY_STORAGE_ROOT=
+
# --- Filesystem bounds (optional) ---
# Colon-separated roots. "~" = home, "/" = whole filesystem.
# READ defaults to home + ~/projects; set "/" to browse the whole box read-only.
diff --git a/.gitignore b/.gitignore
index c5d77bc7..61ebc750 100644
--- a/.gitignore
+++ b/.gitignore
@@ -49,3 +49,6 @@ __pycache__/
# Local integration-transfer artifacts (never commit personal exports)
*.integration-bundle.json
*.integration-bundle.enc.json
+
+# Isolated fake HOME for tenancy regression tests; never stage generated state.
+.tenant-test-home/
diff --git a/app/globals.css b/app/globals.css
index 0090ce03..75c8ecb2 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -371,6 +371,20 @@ body {
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
}
+/* iOS 27 home-screen widget placeholders. The kit paints these purple so the
+ size (small, medium, large, extra large) reads before a real widget does.
+ Scoped to the iOS shell so the macOS widget stack stays on its own cards. */
+[data-shell="ios"] [data-slot="ios-widget-placeholder"] {
+ background: #6e56cf;
+}
+
+/* Two-tone focus stays visible across light and dark wallpaper regions. */
+.ios-lock-focus:focus-visible {
+ outline: 2px solid Canvas;
+ outline-offset: 2px;
+ box-shadow: 0 0 0 4px CanvasText;
+}
+
/* iOS Settings grouped-list body. The shell-settings primitives render the SAME
markup in every shell; the iOS type scale + borderless-card-on-grouped-page
look lives here (scoped) so the portable slice stays brand/shell-free.
diff --git a/app/mcp/route.test.ts b/app/mcp/route.test.ts
index 209f45da..ad95d8e2 100644
--- a/app/mcp/route.test.ts
+++ b/app/mcp/route.test.ts
@@ -45,6 +45,7 @@ vi.mock("@/lib/host/limits-api", () => ({
vi.mock("@/lib/mcp/capability-runtime", () => ({
msoCapabilityRuntime: { list: () => [], invoke: vi.fn(async () => ({ content: [] })) },
}));
+vi.mock("@/lib/agent/local-agent-standby", () => ({ ensureLocalAgentStandbyRuntime: vi.fn(async () => {}) }));
vi.mock("@/lib/mcp/tools", () => ({ TOOLS: [] }));
vi.mock("@/lib/mcp/toolset", () => ({ toolsetInfo: () => ({}) }));
vi.mock("@/lib/mcp/client-profile", () => ({
diff --git a/app/mcp/route.ts b/app/mcp/route.ts
index cb6c2b0e..9865a553 100644
--- a/app/mcp/route.ts
+++ b/app/mcp/route.ts
@@ -1,3 +1,7 @@
+import { TENANT_MEMORY_TOOLS } from "@/lib/tenancy/memory-tools";
+import { tenantPreviewEnabled } from "@/lib/tenancy/mode";
+import { resolveMcpTenant, tenantRuntimeConfigurationPresent } from "@/lib/tenancy/runtime";
+import { dispatchTenantRpc } from "@/lib/mcp/tenant-dispatch";
import { dispatch, isNotification, rpcError, UNAUTHORIZED, RATE_LIMITED, type RpcRequest } from "@/lib/mcp/dispatch";
import { getClient, validateToken, touchToken } from "@/lib/mcp/store";
import { clampScope, mcpEnabled } from "@/lib/mcp/scope";
@@ -81,6 +85,19 @@ export async function POST(req: Request) {
const principal = token.clientId ? `mcp-client:${token.clientId}` : `mcp-token:${token.hash}`;
const expectedResource = `${origin}/mcp`;
if (token.resource && token.resource !== expectedResource) return unauthorized("token was minted for a different MCP resource");
+ let tenantContext;
+ try { tenantContext = await resolveMcpTenant(token); }
+ catch { return unauthorized("tenant access is unavailable"); }
+ if (tenantContext) {
+ const result = await dispatchTenantRpc(rpc, effectiveScope, `mcp:${token.hash.slice(0, 16)}`, {
+ tenantContext, toolProfile: token.profile ?? "full",
+ allowedTools: token.allowedTools, toolArgumentConstraints: token.toolArgumentConstraints,
+ });
+ if (isNotification(body)) return new Response(null, { status: 202, headers: responseHeaders(req) });
+ 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: responseHeaders(req, { "Cache-Control": "no-store" }) });
+ }
const client = token.clientId ? await getClient(token.clientId).catch(() => null) : null;
const toolProfile = token.profile ?? client?.profile ?? detectMcpToolProfile({ clientId: token.clientId, name: client?.name, redirectUris: client?.redirectUris });
const trustedOpenAiFileParams = isTrustedOpenAiFileParamsClient({ clientId: token.clientId, redirectUris: client?.redirectUris });
@@ -118,6 +135,12 @@ export async function GET(req: Request) {
return new Response(null, { status: 405, headers: responseHeaders(req, { Allow: "POST", "Cache-Control": "no-store" }) });
}
if (req.headers.get("MCP-Protocol-Version") === "2026-07-28") return new Response(null, { status: 405, headers: responseHeaders(req, { Allow: "POST", "Cache-Control": "no-store" }) });
+ try {
+ if (tenantPreviewEnabled()) return Response.json({ name: "mso MCP tenant preview",
+ transport: "streamable-http", supportedTenantTools: [...TENANT_MEMORY_TOOLS],
+ storageRootConfigured: tenantRuntimeConfigurationPresent(), productionTenantIsolationReady: false },
+ { headers: responseHeaders(req, { "Cache-Control": "no-store" }) });
+ } catch { return Response.json({ error: "invalid tenancy mode" }, { status: 503, headers: responseHeaders(req) }); }
const full = toolsetInfo(TOOLS, undefined, "full");
const chatgptTools = visibleToolsForProfile(TOOLS, "exec", "chatgpt");
return Response.json({
diff --git a/app/mcp/tenant-persistent-route.test.ts b/app/mcp/tenant-persistent-route.test.ts
new file mode 100644
index 00000000..b4ae06a3
--- /dev/null
+++ b/app/mcp/tenant-persistent-route.test.ts
@@ -0,0 +1,108 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import { alice, bindingA, fixture } from "@/lib/tenancy/persistence-test-fixtures";
+vi.mock("server-only", () => ({}));
+const auth = vi.hoisted(() => ({ records: new Map<string, Record<string, unknown>>(), touch: vi.fn(), client: vi.fn() }));
+type McpStore = typeof import("@/lib/mcp/store");
+vi.mock("@/lib/mcp/store", async importOriginal => {
+ const actual = await importOriginal<McpStore>();
+ return {
+ ...actual,
+ validateToken: async (bearer: string) => auth.records.get(bearer) ?? null,
+ touchToken: auth.touch, getClient: auth.client,
+ };
+});
+let f: Awaited<ReturnType<typeof fixture>>, post: typeof import("./route").POST;
+let ownerRuns: Array<() => void> = [];
+const cleanup: Array<() => Promise<void>> = [];
+function request(name: string, args = {}, token = "fixture-A") {
+ return new Request("https://tenant.fixture.invalid/mcp", { method: "POST", headers: {
+ authorization: "Bearer " + token, "content-type": "application/json", "Mso-Session-Id": "other-session",
+ }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call",
+ params: { name, arguments: args, _meta: { tenantId: "tenant-b", user: "bob", path: "/foreign" } } }) });
+}
+const call = async (name: string, args = {}, token = "fixture-A") => {
+ const response = await post(request(name, args, token));
+ return { status: response.status, body: await response.json() };
+};
+beforeEach(async () => {
+ vi.resetModules(); vi.clearAllMocks(); ownerRuns = [];
+ f = await fixture(); auth.records.clear();
+ for (const [raw, identity, hash] of [["fixture-A", alice, "a"], ["fixture-B", { ...alice, subject: "bob" }, "b"]] as const) {
+ const b = (await f.store.registry.resolve(identity))!;
+ auth.records.set(raw, { hash: hash.repeat(64), label: "synthetic", clientId: "shared-client", scope: "write",
+ resource: "https://tenant.fixture.invalid/mcp", profile: "full", expiresAt: identity.expiresAt,
+ tenantBinding: { version: 1, issuer: identity.issuer, subject: identity.subject,
+ tenantId: b.tenantId, principalId: b.principalId, mappingRevision: b.mappingRevision } });
+ }
+ vi.stubEnv("OS_MCP_ENABLED", "1"); vi.stubEnv("NEXT_PUBLIC_OS_DEMO", "0");
+ vi.stubEnv("OS_MCP_MAX_SCOPE", "exec"); vi.stubEnv("OS_PUBLIC_ORIGIN", "https://tenant.fixture.invalid");
+ vi.stubEnv("OS_TENANCY_MODE", "tenant-preview"); vi.stubEnv("OS_TENANCY_STORAGE_ROOT", f.root);
+ post = (await import("./route")).POST;
+ const { TOOLS_BY_NAME } = await import("@/lib/mcp/tools");
+ ownerRuns = ["agent_memory_read", "agent_memory_search", "agent_memory_remember", "agent_memory_forget"]
+ .map(name => { const spy = vi.spyOn(TOOLS_BY_NAME.get(name)!, "run");
+ return () => { expect(spy).not.toHaveBeenCalled(); spy.mockRestore(); }; });
+});
+afterEach(async () => {
+ for (const check of ownerRuns) check();
+ expect(auth.touch).not.toHaveBeenCalled(); expect(auth.client).not.toHaveBeenCalled();
+ vi.unstubAllEnvs(); await f.cleanup(); for (const fn of cleanup.splice(0)) await fn();
+});
+it("runs actual POST, composition, dispatcher and kernel against two durable namespaces", async () => {
+ const write = (value: string, token: string) => call("agent_memory_remember", { document: "MEMORY.md", key: "private-key", value }, token);
+ for (const result of await Promise.all([write("private-A", "fixture-A"), write("private-B", "fixture-B")])) {
+ expect(result.status).toBe(200); expect(result.body.error).toBeUndefined(); expect(result.body.result.isError).not.toBe(true);
+ }
+ const a = JSON.stringify((await call("agent_memory_read")).body);
+ const b = JSON.stringify((await call("agent_memory_read", {}, "fixture-B")).body);
+ expect(a).toContain("private-A"); expect(a).not.toContain("private-B");
+ expect(b).toContain("private-B"); expect(b).not.toContain("private-A");
+ const state = JSON.parse(await fs.readFile(f.root + "/state.json", "utf8"));
+ expect(state.audit).toHaveLength(4);
+ for (const value of ["private-key", "private-A", "private-B", "fixture-A", "fixture-B"]) expect(JSON.stringify(state.audit)).not.toContain(value);
+ expect(JSON.stringify((await call("agent_memory_search", { query: "private-key" })).body)).toContain("private-A");
+ expect((await call("agent_memory_forget", { document: "MEMORY.md", key: "private-key" })).body.error).toBeUndefined();
+ expect(JSON.stringify((await call("agent_memory_read")).body)).not.toContain("private-A");
+});
+it.each([{ tenantId: "tenant-b" }, { user: "bob" }, { path: "/foreign" }, { document: "CLAIMS.v1" }])("rejects argument selectors %j without mutation", async extra => {
+ const result = await call("agent_memory_remember", { document: "MEMORY.md", key: "safe", value: "safe", ...extra });
+ expect(result.body.error?.code).toBe(-32602);
+ expect(await f.store.administration.status()).toEqual({ revision: 2, auditEntries: 2 });
+});
+it("enforces read scope, token allowlists and argument constraints before writes", async () => {
+ const token = auth.records.get("fixture-A")!;
+ for (const policy of [{ scope: "read" }, { scope: "write", allowedTools: ["agent_memory_read"] },
+ { scope: "write", allowedTools: ["agent_memory_remember"], toolArgumentConstraints: { agent_memory_remember: { document: ["USER.md"] } } }]) {
+ Object.assign(token, policy);
+ const result = await call("agent_memory_remember", { document: "MEMORY.md", key: "safe", value: "safe" });
+ expect(result.body.error || result.body.result?.isError).toBeTruthy();
+ }
+ expect(await f.store.administration.status()).toEqual({ revision: 2, auditEntries: 2 });
+});
+it("denies stale credentials after durable revoke and re-enable", async () => {
+ await call("agent_memory_read");
+ await f.store.administration.setBinding(alice, { ...bindingA, enabled: false }, 2);
+ expect((await call("agent_memory_read")).status).toBe(401);
+ await f.store.administration.setBinding(alice, bindingA, 3);
+ expect((await call("agent_memory_read")).status).toBe(401);
+});
+it("denies permission drift without exposing the configured path", async () => {
+ await call("agent_memory_read");
+ await fs.chmod(f.root + "/state.json", 0o644);
+ const denied = await call("agent_memory_read");
+ expect(denied.status).toBe(401); expect(JSON.stringify(denied.body)).not.toContain(f.root);
+});
+it("refuses unsupported host/app tools before legacy execution", async () => {
+ for (const name of ["exec_run", "fs_read", "browser_status", "apps_power", "integration_execute"]) {
+ expect((await call(name)).body.error).toBeDefined();
+ }
+ expect(await f.store.administration.status()).toEqual({ revision: 2, auditEntries: 2 });
+});
+it("denies a changed server root without creating replacement storage", async () => {
+ await call("agent_memory_read");
+ const other = f.root + "-other"; await fs.mkdir(other, { mode: 0o700 }); cleanup.push(() => fs.rm(other, { recursive: true, force: true }));
+ vi.stubEnv("OS_TENANCY_STORAGE_ROOT", other);
+ expect((await call("agent_memory_read")).status).toBe(401);
+ expect(await fs.readdir(other)).toEqual([]);
+});
diff --git a/app/mcp/tenant-route.test.ts b/app/mcp/tenant-route.test.ts
new file mode 100644
index 00000000..9fd5de92
--- /dev/null
+++ b/app/mcp/tenant-route.test.ts
@@ -0,0 +1,113 @@
+import { beforeEach, afterEach, expect, it, vi } from "vitest";
+import { tenantFixture } from "@/lib/tenancy/test-fixtures";
+
+const mocks = vi.hoisted(() => ({
+ validate: vi.fn(), touch: vi.fn(async () => {}), client: vi.fn(),
+ originAllowed: vi.fn(() => true), resolveTenant: vi.fn(), tenantDispatch: vi.fn<(...args: unknown[]) => Promise<Record<string, unknown>>>(async () => ({ jsonrpc: "2.0", id: 1, result: {} })),
+ legacyDispatch: vi.fn(async () => ({ jsonrpc: "2.0", id: 1, result: {} })),
+ session: vi.fn(async () => ({ conversationBound: false })), standby: vi.fn(async () => {}),
+}));
+vi.mock("@/lib/mcp/store", () => ({ validateToken: mocks.validate, touchToken: mocks.touch, getClient: mocks.client }));
+vi.mock("@/lib/tenancy/runtime", () => ({ resolveMcpTenant: mocks.resolveTenant, tenantRuntimeConfigurationPresent: () => false }));
+vi.mock("@/lib/mcp/tenant-dispatch", () => ({ dispatchTenantRpc: mocks.tenantDispatch }));
+vi.mock("@/lib/mcp/dispatch", () => ({
+ dispatch: mocks.legacyDispatch, isNotification: (body: { id?: unknown }) => body.id === undefined,
+ rpcError: (id: unknown, code: number, message: string) => ({ jsonrpc: "2.0", id, error: { code, message } }),
+ UNAUTHORIZED: -32001, RATE_LIMITED: -32002,
+}));
+vi.mock("@/lib/mcp/scope", () => ({ mcpEnabled: () => true, clampScope: (scope: string) => scope }));
+vi.mock("@/lib/mcp/origin", () => ({
+ publicOrigin: () => "https://mso.example.test", clientIp: () => "127.0.0.1",
+ mcpCorsHeaders: () => ({}), mcpRequestOriginAllowed: mocks.originAllowed,
+}));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: () => false, rateLimitedUntrusted: () => false }));
+vi.mock("@/lib/mcp/tools", () => ({ TOOLS: [] }));
+vi.mock("@/lib/mcp/capability-runtime", () => ({ msoCapabilityRuntime: {} }));
+vi.mock("@/lib/mcp/session-context", () => ({ resolveMcpSession: mocks.session, mcpSessionHeaders: () => ({}) }));
+vi.mock("@/lib/agent/local-agent-standby", () => ({ ensureLocalAgentStandbyRuntime: mocks.standby }));
+
+import { POST, GET } from "./route";
+function request(args = {}, extra: Record<string, unknown> = {}) {
+ return new Request("https://mso.example.test/mcp", {
+ method: "POST", headers: { authorization: "Bearer synthetic", "content-type": "application/json",
+ "Mcp-Session-Id": "foreign-session", "Mso-Session-Id": "foreign-session" },
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call",
+ params: { name: "agent_memory_read", arguments: args, _meta: { "mso/sessionId": "foreign-session" } }, ...extra }),
+ });
+}
+function noOwnerState() {
+ for (const spy of [mocks.touch, mocks.client, mocks.legacyDispatch, mocks.session, mocks.standby]) expect(spy).not.toHaveBeenCalled();
+}
+beforeEach(() => {
+ vi.clearAllMocks(); mocks.originAllowed.mockReturnValue(true); vi.stubEnv("OS_TENANCY_MODE", "tenant-preview");
+ mocks.validate.mockResolvedValue({ hash: "a".repeat(64), scope: "read", clientId: "shared-client",
+ label: "synthetic", tenantBinding: { version: 1, issuer: "mso-local", subject: "alice", tenantId: "tenant-a", principalId: "principal-a", mappingRevision: 1 }, expiresAt: 5000 });
+ const f = tenantFixture();
+ mocks.resolveTenant.mockImplementation(token => f.authority.authenticate(f.identity(token.tenantBinding.subject), token.tenantBinding));
+});
+afterEach(() => vi.unstubAllEnvs());
+
+it("binds tenant context only after bearer validation and skips all owner state", async () => {
+ const response = await POST(request({}));
+ expect(response.status).toBe(200);
+ expect(mocks.resolveTenant).toHaveBeenCalledWith(expect.objectContaining({ tenantBinding: expect.objectContaining({ subject: "alice", mappingRevision: 1 }), clientId: "shared-client" }));
+ expect(mocks.tenantDispatch).toHaveBeenCalledWith(expect.any(Object), "read", expect.stringMatching(/^mcp:/),
+ expect.objectContaining({ tenantContext: { kind: "tenant-preview" } }));
+ expect(mocks.tenantDispatch.mock.calls[0][3]).not.toHaveProperty("sessionId");
+ noOwnerState();
+});
+it("does not let body/metadata or session headers become authenticated subject", async () => {
+ await POST(request({ tenantSubject: "bob", tenantId: "tenant-b", user: "bob" }));
+ expect(mocks.resolveTenant.mock.calls[0][0].tenantBinding.subject).toBe("alice");
+ noOwnerState();
+});
+it("rejects invalid bearer before resolving a tenant", async () => {
+ mocks.validate.mockResolvedValue(null);
+ expect((await POST(request())).status).toBe(401);
+ expect(mocks.resolveTenant).not.toHaveBeenCalled(); expect(mocks.tenantDispatch).not.toHaveBeenCalled();
+ noOwnerState();
+});
+it("rejects wrong resource binding before tenant resolution", async () => {
+ mocks.validate.mockResolvedValue({ hash: "a".repeat(64), scope: "read", resource: "https://other.example/mcp" });
+ expect((await POST(request())).status).toBe(401);
+ expect(mocks.resolveTenant).not.toHaveBeenCalled(); noOwnerState();
+});
+it("resolver failure is fail-closed and sanitized", async () => {
+ mocks.resolveTenant.mockRejectedValue(new Error("private registry detail"));
+ const response = await POST(request());
+ expect(response.status).toBe(401);
+ expect(await response.text()).not.toContain("private registry detail");
+ expect(mocks.tenantDispatch).not.toHaveBeenCalled(); noOwnerState();
+});
+it("legacy mode keeps the existing dispatcher when no tenant identity is bound", async () => {
+ vi.stubEnv("OS_TENANCY_MODE", "legacy"); mocks.resolveTenant.mockResolvedValue(undefined);
+ mocks.client.mockResolvedValue(null);
+ expect((await POST(request())).status).toBe(200);
+ expect(mocks.legacyDispatch).toHaveBeenCalledOnce(); expect(mocks.tenantDispatch).not.toHaveBeenCalled();
+});
+it("preview diagnostics do not advertise host tools as tenant-safe", async () => {
+ const response = await GET(new Request("https://mso.example.test/mcp"));
+ expect(await response.json()).toMatchObject({ supportedTenantTools: ["agent_memory_read", "agent_memory_search", "agent_memory_remember", "agent_memory_forget"], productionTenantIsolationReady: false });
+ noOwnerState();
+});
+
+it("preview GET retains origin and streaming guards", async () => {
+ mocks.originAllowed.mockReturnValue(false);
+ expect((await GET(new Request("https://mso.example.test/mcp"))).status).toBe(403);
+ mocks.originAllowed.mockReturnValue(true);
+ for (const headers of [new Headers({ accept: "text/event-stream" }), new Headers({ "MCP-Protocol-Version": "2026-07-28" })]) {
+ expect((await GET(new Request("https://mso.example.test/mcp", { headers }))).status).toBe(405);
+ }
+ noOwnerState();
+});
+it("modern tenant method-not-found keeps HTTP404 semantics", async () => {
+ mocks.tenantDispatch.mockResolvedValueOnce({ jsonrpc: "2.0", id: 1, error: { code: -32601, message: "unavailable" } });
+ const body = { jsonrpc: "2.0", id: 1, method: "unsupported", params: { _meta: {
+ "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {},
+ } } };
+ const req = new Request("https://mso.example.test/mcp", { method: "POST", headers: {
+ authorization: "Bearer synthetic", "content-type": "application/json", "MCP-Protocol-Version": "2026-07-28",
+ "Mcp-Method": "unsupported",
+ }, body: JSON.stringify(body) });
+ expect((await POST(req)).status).toBe(404); noOwnerState();
+});
diff --git a/app/oauth/token/route.test.ts b/app/oauth/token/route.test.ts
index aa1d4a41..e7981322 100644
--- a/app/oauth/token/route.test.ts
+++ b/app/oauth/token/route.test.ts
@@ -1,3 +1,4 @@
+import { TenantDenied } from "@/lib/tenancy/authority";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ consumeCode: vi.fn(), storeGrant: vi.fn(), rotate: vi.fn(), random: vi.fn(), verify: vi.fn(() => true), limited: vi.fn(() => false) }));
vi.mock("@/lib/mcp/store", () => ({ consumeCode: mocks.consumeCode, storeOAuthGrant: mocks.storeGrant, rotateOAuthGrant: mocks.rotate, OAUTH_ACCESS_TOKEN_TTL_MS: 3_600_000 }));
@@ -9,7 +10,7 @@ const { POST } = await import("./route");
const post = (body: Record<string, string>) => new Request("https://mso.example.test/oauth/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body) });
describe("OAuth token endpoint", () => {
- beforeEach(() => { vi.clearAllMocks(); mocks.random.mockImplementation((prefix: string) => `${prefix}${mocks.random.mock.calls.length}`); mocks.verify.mockReturnValue(true); });
+ beforeEach(() => { vi.clearAllMocks(); mocks.random.mockImplementation((prefix: string) => `${prefix}${mocks.random.mock.calls.length}`); mocks.verify.mockReturnValue(true); mocks.storeGrant.mockReset(); });
it("exchanges an authorization code into resource-bound access + refresh credentials", async () => {
mocks.consumeCode.mockResolvedValue({ clientId: "chatgpt", redirectUri: "https://chatgpt.com/cb", codeChallenge: "challenge", scope: "exec", resource: "https://mso.example.test/mcp", profile: "chatgpt", offlineAccess: true });
@@ -29,3 +30,26 @@ describe("OAuth token endpoint", () => {
expect(bad.status).toBe(400); expect(await bad.json()).toMatchObject({ error: "invalid_target" });
});
});
+
+describe("tenant credential exchange projection", () => {
+ const binding = { version: 1, issuer: "fixture", subject: "alice", tenantId: "tenant-a", principalId: "person-a", mappingRevision: 3 };
+ const request = () => post({ grant_type: "authorization_code", code: "fixture-code", code_verifier: "v".repeat(43),
+ client_id: "fixture-client", redirect_uri: "https://fixture.invalid/cb", tenantSubject: "attacker", tenantBinding: "forged" });
+ beforeEach(() => {
+ vi.clearAllMocks(); mocks.storeGrant.mockReset(); mocks.verify.mockReturnValue(true);
+ mocks.random.mockImplementation((prefix: string) => prefix + "synthetic");
+ mocks.consumeCode.mockResolvedValue({ clientId: "fixture-client", redirectUri: "https://fixture.invalid/cb",
+ codeChallenge: "fake", scope: "read", tenantBinding: binding });
+ });
+ it("copies only the server-owned code binding and ignores request selectors", async () => {
+ expect((await POST(request())).status).toBe(200);
+ expect(mocks.storeGrant).toHaveBeenCalledWith(expect.objectContaining({ tenantBinding: binding }));
+ expect(mocks.storeGrant.mock.calls[0][0]).not.toHaveProperty("tenantSubject");
+ });
+ it("returns a sanitized denial when binding changes before grant storage", async () => {
+ mocks.storeGrant.mockRejectedValue(new TenantDenied("private registry state"));
+ const response = await POST(request());
+ expect(response.status).toBe(400);
+ expect(await response.json()).toEqual({ error: "invalid_grant" });
+ });
+});
diff --git a/app/oauth/token/route.ts b/app/oauth/token/route.ts
index 13fb3deb..c5669e42 100644
--- a/app/oauth/token/route.ts
+++ b/app/oauth/token/route.ts
@@ -1,3 +1,4 @@
+import { TenantDenied } from "@/lib/tenancy/authority";
import { consumeCode, OAUTH_ACCESS_TOKEN_TTL_MS, rotateOAuthGrant, storeOAuthGrant } from "@/lib/mcp/store";
import { verifyPkce, randomToken } from "@/lib/mcp/pkce";
import { mcpEnabled, oauthScopeString } from "@/lib/mcp/scope";
@@ -39,6 +40,7 @@ export async function POST(req: Request) {
if (!verifyPkce(p.code_verifier, rec.codeChallenge, "S256")) return json({ error: "invalid_grant" }, 400);
const access = randomToken("mso_mcp_"), refresh = randomToken("mso_refresh_"), grantId = randomToken("grant_", 16);
- await storeOAuthGrant({ accessToken: access, refreshToken: refresh, label: `oauth · ${rec.clientId.slice(0, 14)}`, clientId: rec.clientId, scope: rec.scope, resource, profile: rec.profile, offlineAccess: rec.offlineAccess, grantId });
+ try { await storeOAuthGrant({ accessToken: access, refreshToken: refresh, label: `oauth · ${rec.clientId.slice(0, 14)}`, clientId: rec.clientId, scope: rec.scope, resource, profile: rec.profile, offlineAccess: rec.offlineAccess, grantId, tenantBinding: rec.tenantBinding }); }
+ catch (error) { if (error instanceof TenantDenied) return json({ error: "invalid_grant" }, 400); throw error; }
return json({ access_token: access, token_type: "Bearer", refresh_token: refresh, expires_in: Math.floor(OAUTH_ACCESS_TOKEN_TTL_MS / 1000), scope: oauthScopeString(rec.scope, rec.offlineAccess === true) });
}
diff --git a/bun.lock b/bun.lock
index ee25256e..08ada635 100644
--- a/bun.lock
+++ b/bun.lock
@@ -45,6 +45,7 @@
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitest/coverage-v8": "5.0.2",
+ "brace-expansion": "5.0.12",
"eslint": "^9.39.4",
"eslint-config-next": "^16.3.8",
"fast-check": "^4.10.2",
@@ -60,8 +61,13 @@
"trustedDependencies": [
"node-pty",
],
+ "patchedDependencies": {
+ },
"overrides": {
"js-yaml": "^4.3.2",
+ "micromatch": "npm:[email protected]",
"nanoid": "^3.3.18",
"postcss": "^8.5.10",
"sharp": "^0.35.4",
@@ -569,13 +575,11 @@
"axobject-query": ["[email protected]", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="],
- "balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
+ "balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-r7WnVImvVCeFpf2DOXfy41aPWzeNg3H/A2X4dKmy1QL0MSyyk/e7z8ihJ3N6Nn2PsdhkVlqnEfnUE4a05P2aTA=="],
- "brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw=="],
-
- "braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
+ "brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="],
"browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.10.44", "caniuse-lite": "^1.0.30001806", "electron-to-chromium": "^1.5.393", "node-releases": "^2.0.51", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw=="],
@@ -735,14 +739,12 @@
"fast-sha256": ["[email protected]", "", {}, "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ=="],
- "fastq": ["[email protected]", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="],
+ "fastq": ["[email protected]", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw=="],
"fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"file-entry-cache": ["[email protected]", "", { "dependencies": { "flat-cache": "^4.0.0" } }, "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ=="],
- "fill-range": ["[email protected]", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
-
"find-up": ["[email protected]", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="],
"flat-cache": ["[email protected]", "", { "dependencies": { "flatted": "^3.2.9", "keyv": "^4.5.4" } }, "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw=="],
@@ -851,8 +853,6 @@
"is-negative-zero": ["[email protected]", "", {}, "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw=="],
- "is-number": ["[email protected]", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="],
-
"is-number-object": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "has-tostringtag": "^1.0.2" } }, "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw=="],
"is-regex": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g=="],
@@ -957,7 +957,7 @@
"merge2": ["[email protected]", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="],
- "micromatch": ["[email protected]", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
+ "micromatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
"minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
@@ -1161,8 +1161,6 @@
"tinyrainbow": ["[email protected]", "", {}, "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw=="],
- "to-regex-range": ["[email protected]", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
-
"ts-algebra": ["[email protected]", "", {}, "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw=="],
"ts-api-utils": ["[email protected]", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA=="],
@@ -1265,8 +1263,6 @@
"@tailwindcss/oxide-wasm32-wasi/tslib": ["[email protected]", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
- "@tailwindcss/postcss/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.17", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ=="],
-
"@typescript-eslint/eslint-plugin/ignore": ["[email protected]", "", {}, "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw=="],
"@typescript-eslint/typescript-estree/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
@@ -1293,7 +1289,7 @@
"loose-envify/js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
- "micromatch/picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
+ "minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw=="],
"protobufjs/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="],
@@ -1305,13 +1301,11 @@
"vite/picomatch": ["[email protected]", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="],
- "vite/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.17", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ=="],
-
"@next/eslint-plugin-next/@eslint-community/eslint-utils/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
"@tailwindcss/node/magic-string/@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
- "@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="],
+ "minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
"vite/lightningcss/lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="],
@@ -1334,7 +1328,5 @@
"vite/lightningcss/lightningcss-win32-arm64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="],
"vite/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="],
-
- "@typescript-eslint/typescript-estree/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
}
}
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 9db08b34..4c321bd2 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -4,6 +4,39 @@
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 → Account → About shows as “What's new”.
+## 2026-10-05
+
+**Added**
+
+- `shell` import reviewed macOS chrome and security candidate
+- `tenancy` compose scoped durable memory runtime
+- `tenancy` pin credential generations across OAuth lifecycle
+- `tenancy` add atomic durable registry and memory adapter
+- `tenancy` add disabled identity and scoped read seam
+
+**Fixed**
+
+- `ci` retain executable verification entrypoint
+- `managed-apps` refresh install state on return
+
+**Tests**
+
+- `shell` wait for settled desktop geometry before switching
+- `tenancy` keep persistent route mock fully parseable
+- `ci` cover both shell journeys in build isolation fixture
+- `tenancy` verify claim corruption and document rollout gates
+
+**Chores**
+
+- `deps-dev` bump simple-icons
+- `lint` ignore linked worktrees
+
+**CI**
+
+- preserve strict auditing before the native dependency check
+- verify both shell candidates in isolated builds
+- gate combined macOS and iOS release journeys
+
## 2026-10-04
**Added**
@@ -12,9 +45,18 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Fixed**
+- `shell` retain focus contrast with screen light enabled
+- `shell` preserve focus contrast within CSS budget
+- `shell` reuse accessible focus token within CSS budget
+- `shell` make iOS lock privacy-safe and keyboard accessible
- `appearance` version immutable default wallpaper URLs
+- `shell` match complete lock weather locale subtags
- `appearance` refine default 27 desktop wallpapers
- `security` clear unfixed dependency and Semgrep audit gates
+- `shell` use Semibold for the iOS lock time
+- `shell` shrink iOS widgets and paint glass fills
+- `shell` tighten the lock date and lighten the time
+- `shell` build the iOS lock screen on the shell wallpaper
**Chores**
@@ -22,6 +64,19 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
- `deps` bump the production-minor-patch group with 5 updates
- `deps-dev` bump the test-toolchain group with 2 updates
+## 2026-10-03
+
+**Added**
+
+- `shell` restyle iPhone and iPad tab bars as iOS 27 glass capsules
+
+**Fixed**
+
+- `shell` correct lock date tracking and cover the home
+- `shell` match iOS Large type styles and touch sizes
+- `shell` place each widget size on its own home screen
+- `shell` match the iOS 27 home screen frames
+
## 2026-10-02
**Fixed**
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 017221c6..7ef6e580 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -208,6 +208,28 @@ NOT add it to `trustedDependencies` to "restore" anything.
For deeper Files/Settings and Preview acceptance, run `bash scripts/verify-build.sh --extended`. It reuses the isolated production build and synthetic credentials; legacy browser scripts no longer read deployment secrets. Media samples skip only when ffmpeg or a system PDF is unavailable.
+## Next ESLint glob dependency
+
+Next ESLint keeps fast-glob 3.3.1 and its filesystem traversal unchanged. Its only
+micromatch consumer uses scan/makeRe (forwarders to picomatch) and brace expansion.
+The exact npm alias to picomatch 2.3.2 retains the original matcher. A versioned Bun
+patch replaces only brace expansion with brace-expansion 5.0.12, removing braces.
+Both replacements are MIT-licensed maintained npm packages. All lint rules and
+security scans remain enabled without advisory exceptions. A matching patch for
+brace-expansion's CommonJS and ESM entrypoints turns every count, encoded-length,
+depth and rewrite limit into an error, preventing silent partial lint discovery.
+
+Expansion fails closed above 4096 input characters, 32 nested brace levels or
+1000 expanded results. Escape handling and deduplication remain covered by tests.
+The output-length budget is bounded by input length times the result limit.
+On dependency upgrades, recheck the sole consumer and the matching/expansion API,
+regenerate or remove the patch with `bun patch`, then run
+`scripts/next-eslint-root-dirs.test.ts`, a clean frozen install, raw audit and full
+gates. The regression fixtures preserve literal/relative, trailing-slash, recursive,
+brace, extglob, negative, hidden, symlink and Windows-normalized roots and actual
+Next link-rule enforcement. Broader tinyglobby/glob replacements were rejected
+because differential tests found behavior changes.
+
## Locked native build bootstrap
The installer provisions `node-gyp` from the dedicated manifest and integrity-locked
@@ -219,10 +241,10 @@ the normal user cache). Cache hits require matching manifests and the expected
runner version. Failed downloads cannot publish a partial runner, replace the
installer recovery trap, or remove the application's `node_modules`.
-node-gyp 12.4.0 is the newest release whose engines (`^20.17.0 || >=22.9.0`) still
-cover MSO's Node range and whose lockfile does not include `http-cache-semantics`.
-node-gyp 13 requires `^22.22.2 || ^24.15.0 || >=26.0.0`, which is narrower than
-`^22.12.0`, so Dependabot keeps ignoring node-gyp major updates.
+node-gyp 12.4.0 replaces `make-fetch-happen` with `undici`, removing
+`http-cache-semantics`. Its engines (`^20.17.0 || >=22.9.0`) cover MSO's Node range.
+node-gyp 13 requires `^22.22.2 || ^24.15.0 || >=26.0.0`, narrower than `^22.12.0`,
+so Dependabot continues ignoring node-gyp major updates.
Update the exact tool version in that manifest and regenerate its lock with
`npm install --package-lock-only --ignore-scripts --no-audit --no-fund --prefix scripts/install/node-gyp`.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 5aa08427..4ba578e7 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,9 +1,72 @@
+## 2026-10-05: Reconcile reviewed shell and tenant candidates
+
+CI keeps the strict dependency-audit wrapper, including its timeout, malformed-report checks and redacted diagnostics, and adds the native Bun high/critical audit as a separate required step. Both run after removal of the vulnerable dependency chain and its exception files. Workflow permissions remain read-only. A contract test prevents either audit from becoming optional.
+
+The integration starts from current GitHub main and preserves its content-versioned wallpaper URLs and dependency updates. It combines the managed-app return refresh, linked-worktree lint boundary, disabled-by-default tenant identity and durable memory runtime, reviewed macOS chrome, and privacy-safe iOS lock and home changes. Tenant credentials retain exact issuer, subject and binding-generation checks; the normal legacy mode remains the default and no live tenant registry, grants or storage are configured.
+
+The macOS source tree is reproduced from reviewed candidate dc74b7af, while its deleted intermediate wallpaper PNGs remain in the preserved source history. The iOS history is preserved through 846dbfea. The dependency reconciliation retains Vitest and coverage 5.0.2 and removes the vulnerable braces chain through the reviewed bounded expansion patches; neither the advisory-wide local ignore nor the superseded scoped waiver is carried forward. Full repository, raw/strict dependency, isolated-build, mandatory release, macOS and iOS browser checks must all pass on the combined head before publication. This source integration does not rebuild or restart the live installation.
+
+## 2026-10-05 — Refresh managed-app install state when returning to App Store
+
+The managed-app backend already detected a healthy Docker-managed 9Router installation, but the App Store catalog read `/api/v1/managed-apps` only once when mounted. Installing 9Router in its separate MSO window could therefore leave the background Store card showing `Not installed` until the Store was reloaded, even though the server was already running. The catalog now refreshes managed-app state when the document becomes visible again or the window regains focus, while leaving the remote MANEF catalog fetch mount-only and avoiding background polling. This changes only Store state synchronization; 9Router lifecycle, container detection, credentials and runtime configuration are unchanged.
+
+The release gate also now ignores `.claude/worktrees/**`, which are Git-ignored linked task checkouts and must be linted from their own roots rather than re-scanned from canonical `main`. This does not relax lint rules for tracked MSO source.
+
+## 2026-10-04 — iOS lock safety and integration candidate
+
+The PR 104 follow-through removes automatic geolocation and external weather requests, restores the original non-iOS privacy curtain, removes the inactive camera button, and labels the existing actions accurately as Lock screen and Hide from Home. Weather remains unavailable pending a separately reviewed explicit opt-in. The iOS Unlock control now has a 44px target, visible keyboard focus, Tab containment, and focus restoration. Locale matching compares complete language/region subtags rather than a partially anchored regular expression. These safety changes supersede the weather, camera, and biometric-label behavior described in earlier candidate entries below.
+
+The isolated candidate passed 366 tests across 52 files, architecture/docs checks, targeted lint, a production build, and four mock-only browser cases covering phone/tablet, light/dark, keyboard and focus, no location/provider calls, and the original macOS lock/unlock after landscape switching. Current-main integration preserves both progress histories; its full gates are verified separately. This is not a deployment or a claim of Figma pixel fidelity.
+
+## 2026-10-04 — Lock time Semibold
+
+The lock time stays 92pt cream and one device-local line. The weight is Semibold, the Headline and emphasized Title 3 weight, because Regular was still too light. It does not return to 96pt.
+
+## 2026-10-04 — Smaller home widgets, lock time weight, glass fill
+
+Home widgets sit in an 80px icon grid instead of stretching with the page. Small is 2×2, medium is 4×2, large is 3×3 with icons beside it, and extra-large is 4×3 with icons below, so none of them fills the home. The lock time is 92pt Regular, the next SF Pro size under 96pt and the Large Title weight, with tracking 0, still one cream line. Search, the dock, lock complications, and Control Center tiles paint the glass fill, including the tiles that render outside the shell.
+
+## 2026-10-04 — Lock date line and cream time
+
+The lock date is a short device date, Footnote size, tight above the time. The city is added on that line only after the location grant returns a name. The time is 96pt light cream at 78% opacity. Weather fallback, wallpaper, flashlight, camera, and complications stay.
+
+## 2026-10-04 — iOS lock screen on the shell wallpaper
+
+The iOS lock face now follows the lock-screen frame: status bar, date, one large time, weather, activity rings, a round clock, flashlight, camera, and the home indicator. It uses the shell wallpaper. The home stays hidden, so the curtain is not a blur of the icons. Clock, date, and timezone come from the browser Date and Intl. Weather is a client geolocation prompt plus a client forecast; a denial shows Unavailable and does not ask this server for a place. In a standalone PWA the system status bar keeps the top inset and the shell does not paint a second one. The macOS curtain is unchanged.
+
+## 2026-10-03 — Lock date tracking and full-screen cover
+
+The lock date keeps Title 3 emphasized (20/25 Semibold) and now uses tracking +0.38. While the iOS shell is locked, the home does not paint through the curtain, so the lock surface covers it. Flashlight and camera stay the circular glass buttons. Other type sizes are unchanged.
+
+## 2026-10-03 — iOS type styles and touch sizes
+
+Home labels, the search pill, widget titles, menu rows, the lock date and time, and Control Center type now use Apple’s Large Dynamic Type styles instead of nearby one-off sizes. Icon labels are Caption 1 (12/16 Regular). The search pill and menu rows are Body (17/22 Regular) with a 44pt target and 16pt inset. Widget and card titles are Headline (17/22 Semibold). The lock date is Title 3 emphasized (20/25 Semibold) and the lock time is 96pt Regular, which is the size whose SF Pro tracking is 0. The macOS shell is unchanged.
+
+## 2026-10-03 — Widget homes, lock type, Control Center mosaic
+
+The purple widget sizes were stacked on Today, which hid the icon grid. Each size is now its own home screen: one placeholder in the 4×6 grid and the existing apps in the cells around it. The plain icon home, search pill, and icon dock stay. The lock clock was rendering the day period as a second giant line in black on the blurred wallpaper; it is now one light 12-hour time under a small light date. iOS Control Center is a single packed mosaic (circle group, tall card, two lower tiles) of the toggles this shell already has.
+
+## 2026-10-03 — iOS 27 home screen frames
+
+The first pass treated a third-party tab-bar measurement as the Home Screen. The linked Figma page is a different frame: the dock is a glass capsule of app icons with no labels, and Search is a separate pill above it. Grid icons keep their labels, and the page dots stay. Today shows the four widget sizes as purple placeholders named for the widgets this shell already has. The lock screen keeps the clock and puts the date above it, with flashlight and camera controls. iOS Control Center is a glass tile mosaic; the macOS menu-bar popover keeps the shared labeled list. A home-icon long-press is a floating menu (Remove App, Require Face ID, Edit Home Screen, then that app's own actions) instead of a bottom sheet. The macOS shell is unchanged.
## 2026-10-04 — Version replaced default wallpaper URLs
The deployed light wallpaper reused an immutable one-year URL. Browser evidence still returned the old 40,480-byte mountain image while origin served the new 47,714-byte light asset. The CSS now includes each default image's content hash in its URL, so existing client/CDN caches request new bytes without clearing custom wallpaper preferences. A regression ties both light and dark URL versions to their actual image bytes.
+## 2026-10-04 — Descriptor assertions and validated trace snapshots
+
+The native installer fixture checks file permissions and reads its content through one no-follow descriptor, closing it in finally rather than checking and reopening a pathname. A2A trace persistence now requires primitive session/workflow identifiers, rejects accessors and unknown fields, builds a fresh allowlisted scalar snapshot, and serializes it before filesystem awaits. Caller mutation or toJSON hooks cannot replace validated content. Private exclusive JSON writes and atomic rename remain; the byte cap matches readState's limit. Regression tests cover malformed IDs, custom hooks, asynchronous mutation and valid maximum escaped metadata. These are real validation fixes; closure of the network-to-file review finding still requires fresh exact-commit CodeQL evidence.
+
+## 2026-10-04 — Remove vulnerable build and lint dependencies
+
+The locked node-gyp bootstrap moves from 11.5.0 to 12.4.0, removing make-fetch-happen and http-cache-semantics while retaining MSO's Node support. Next ESLint's fast-glob traversal stays unchanged. Its micromatch dependency aliases the same underlying picomatch 2.3.2 matcher; a versioned Bun patch replaces only brace expansion with maintained brace-expansion 5.0.12. A second patch makes both CJS and ESM expansion entrypoints throw on result, encoded-length, depth or rewrite exhaustion instead of silently returning partial patterns. Regression fixtures cover actual lint diagnostics, path and brace semantics, escaping and each limit. Broader tinyglobby and glob replacements were rejected after differential tests found compatibility changes. The vulnerable braces package is removed without exemptions.
+
+Semgrep's parser rejected the inline import type in a mocked-module spread. A named type alias preserves the same mocked exports and assertions while restoring complete strict parsing. Raw dependency audit and scanner policies remain unchanged; PR 105's exceptions are not adopted. Final CI and integrated UI verification remain release-candidate gates.
+
## 2026-10-04 — Security Core dependency and Semgrep gates
+Historical PR 105 decision: the temporary braces exception described below has been retired by the verified dependency replacement above. Raw audit and OSV scanning no longer exempt it.
+
OSV-Scanner 2.5.1, Trivy, and `bun audit --audit-level=high` were red on `2690b5e` and on PR 104 (`ec38f332`) for two unfixed HIGH advisories. npm still lists braces 3.0.3 and http-cache-semantics 4.2.0 as the newest releases. node-gyp 12.4.0 replaces `make-fetch-happen` with `undici`, still accepts MSO's Node range (`^20.17.0 || >=22.9.0`), and the regenerated `scripts/install/node-gyp/package-lock.json` no longer contains `http-cache-semantics` or `make-fetch-happen`. `npm audit --omit=dev --audit-level=high` on that prefix is clean, so the Trivy filesystem finding and the OSV finding for GHSA-ch52-4w7c-c8xp leave with the package. node-gyp 13 was not used because it requires `^22.22.2 || ^24.15.0 || >=26.0.0`.
braces 3.0.3 remains only on the dev chain `eslint-config-next → @next/eslint-plugin-next → fast-glob → micromatch` in `bun.lock`. The Next plugin calls fast-glob only when `settings.next.rootDir` is set, and `eslint.config.mjs` does not set it. No MSO source imports braces. Root `osv-scanner.toml` ignores GHSA-vfj7-8cjw-p6xm until 2026-12-03T00:00:00Z and, because OSV config does not propagate to child directories, does not cover any other lockfile. `scripts/audit-exceptions.mjs` applies the same GHSA, instant, and chain check; CI's audit step calls `bun run audit:strict` instead of a blanket `bun audit --ignore`. A second parent, a production dependency, a different package, or the expiry date fails the audit again.
diff --git a/docs/README.md b/docs/README.md
index e1118f46..fc74e265 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -81,6 +81,9 @@ evidence and review freshness. The repository quality gate runs both automatical
| Document | Status |
|---|---|
| [`EXTERNAL-FEATURE-CONTRACT.md`](./EXTERNAL-FEATURE-CONTRACT.md) | v1 target contract for modular shell/external features; implementation status is explicit |
+| [`TENANT-PREVIEW.md`](./TENANT-PREVIEW.md) | Disabled identity and scoped-memory runtime; live activation and full production isolation remain unimplemented |
+| [`TENANT-PERSISTENCE.md`](./TENANT-PERSISTENCE.md) | Source-only durable registry, scoped memory and audit; transactions, recovery limits and operational gates |
+| [`TENANT-ROLLOUT.md`](./TENANT-ROLLOUT.md) | Finite engineering, operational approval and acceptance gates for shared-gateway multiuser deployment |
| [`NATIVE-HOST-RELAY.md`](./NATIVE-HOST-RELAY.md) | Requested native macOS/Windows hosts and shared no-domain MCP relay; implementation and verification gates remain explicit |
## Generated/current records
diff --git a/docs/TENANT-PERSISTENCE.md b/docs/TENANT-PERSISTENCE.md
new file mode 100644
index 00000000..967250a1
--- /dev/null
+++ b/docs/TENANT-PERSISTENCE.md
@@ -0,0 +1,133 @@
+# Durable tenant persistence candidate
+
+Status: source-only, default disabled. Runtime composition now requires explicit
+server-owned configuration. No live identity grants, root, credentials, migration or
+deployment are created.
+
+## Implementation and entry points
+
+`openTenantPersistence({ root })` supplies a durable registry, scoped memory port,
+trusted administration methods and a tenant audit interface. The caller must supply
+an existing canonical absolute Linux directory owned by the service UID with mode0700.
+There is no HOME, environment, owner-store or default-directory fallback.
+
+The source factory is internal control-plane code, not an authentication boundary.
+Its administration methods are not exposed through a route, MCP tool or CLI.
+Calling them in production requires separately reviewed administrative authorization.
+The optional initialize:true creates only an empty snapshot, with no memberships,
+and only when no state file exists. Ordinary operations never recreate missing state.
+
+The actual capability kernel can read this adapter through an opaque authenticated
+context. Tests exercise that path with two real temporary storage namespaces.
+`writeTenantMemory` remains an internal raw-document CAS seam. The public tenant MCP
+path supports read/search/remember/forget through typed scoped claims, without owner
+storage or telemetry. Runtime composition opens existing state only; it never initializes it.
+
+## Transaction model
+
+A single bounded JSON snapshot holds registry bindings, memory records and successful
+mutation audit events. Every read and mutation takes the same cross-process exclusive
+lock, reloads and validates the snapshot, then releases its own lock. A lock is never
+stolen based on age or PID. A crashed lock fails closed and needs reviewed operator recovery.
+
+Trusted administrative and raw-document mutations require the exact expected store
+revision. Raw memory also requires the current document version, where0 denotes absence.
+Public typed operations read and update the current ledger inside the same lock; they
+return a scoped snapshot without exposing the global store revision. Registry changes allocate a new monotonically
+increasing mapping generation. Every change, including disable/re-enable, invalidates
+old contexts. Tenant-enabled changes update all bindings for that tenant in the same
+transaction and record a tenant-scoped event.
+
+The memory writer revalidates subject, binding generation, enabled flags and credential
+expiry inside the transaction. Authorization is evaluated at transaction admission;
+this is not a guarantee that physical disk commit finishes before wall-clock token expiry.
+The shared lock orders revocation against memory commits. A revocation committed first
+prevents the queued write; a write committed first remains part of history.
+
+Data and its required audit event are serialized together to a private unique temporary
+file, fsynced, renamed atomically, then the directory is fsynced. A pre-rename failure
+leaves the previous snapshot. A post-rename durability or lock-cleanup failure returns
+TenantCommitUncertain with an operation ID. Never blindly retry that outcome.
+Trusted administration.operationStatus(id) reconciles it against the surviving snapshot.
+A missing event after restart means the operation is absent from surviving state,
+not proof that every possible external effect never happened. This adapter has no external effects.
+
+## Capacity, records and audit
+
+Bounds:16 MiB snapshot,1000 bindings,4000 memory records,10,000 audit events and
+64 KiB cumulative content per memory document, including retained typed history.
+Typed memory additionally allows at most256 claims and512 KiB encoded ledger. All integers, booleans, record keys, UTF-8 and schema fields
+are validated. Unknown fields and duplicate records and malformed state fail closed.
+
+Tenant reads/authentication close at audit exhaustion or within128 KiB of the byte cap.
+The byte reserve allows bounded registry revocation updates; capacity cannot silently
+leave an active tenant readable while its revocation is unable to fit. No automatic
+pruning or history deletion is provided. Capacity/recovery must be designed before scale-up.
+
+Memory is keyed by tenant, principal, mapping generation, collection and fixed document
+name. A generation change leaves old bytes retained but inaccessible through the new
+binding. There is no automatic migration across generations. Only USER.md and MEMORY.md
+are public documents; the fixed internal CLAIMS.v1 record stores validated typed history.
+Unknown fields, duplicate IDs, invalid references or mixed nonempty raw/typed state
+are refused. Raw documents are never automatically migrated. The reserved collection
+types do not implement sessions/jobs/projects.
+
+Audit currently covers successful binding and memory mutations. It is not read,
+denial, tool-execution or owner telemetry. Events contain bounded server-generated IDs,
+timestamps, fixed tool/document identifiers and scope metadata, never credentials,
+subjects, caller memory keys or memory contents. Tenant-wide events
+returned through the scoped audit port omit the other principal's identifier.
+Trusted administrative reconciliation retains the complete event.
+
+## Filesystem trust boundary
+
+The adapter pins the root's inode/device and opens it with NOFOLLOW. Transaction paths
+are anchored through that open directory descriptor using Linux /proc/self/fd.
+State leaves must be regular service-owned0600 single-link files and are opened with
+NOFOLLOW and NONBLOCK. Symlink roots/leaves, hardlinks, root replacement, unexpected
+permissions, oversized state and invalid UTF-8 are refused. The root inode/device is
+checked again after acquiring a queued lock before admitting the transaction.
+
+An optional server-owned guard checks the selected mode/root before opening, after
+reading locked state, before mutation and immediately before rename. This prevents
+queued work admitted after configuration changes. Once rename is in flight, admission
+semantics apply: disabling configuration is not cancellation of every in-flight commit.
+The open directory descriptor prevents path replacement from redirecting an admitted
+operation. Operational replacement still requires draining/revoking the old runtime.
+
+This is application-state separation under a trusted service account. It does not
+sandbox malicious code running as the same Unix UID or root, protect a compromised host,
+or implement tenant process/browser/network isolation. The existing disposable worker
+pilot provides separate evidence; it is not silently provisioned or wired here.
+
+## Reproduce
+
+```sh
+umask 077
+mkdir -p .tenant-test-home
+HOME="$PWD/.tenant-test-home" XDG_STATE_HOME="$PWD/.tenant-test-home/.state" \
+ VITEST_MAX_WORKERS=2 bun run test lib/tenancy lib/mcp/tenant-capability-integration.test.ts
+node_modules/.bin/tsc --noEmit --incremental false
+node_modules/.bin/eslint lib/tenancy --max-warnings=0
+```
+
+Tests use synthetic temporary data and delete only their own temporary directories.
+Coverage includes disk reopen, independent-process CAS, barrier-controlled queued-write
+revocation, disable/re-enable, equal document keys, corrupt snapshots, symlinks/hardlinks,
+capacity exhaustion, abandoned locks and injected pre/post-rename failures.
+The exact-commit build must use scripts/verify-build.sh, never a live in-place build.
+
+## Remaining integration decisions
+
+Engineering still needed: authenticated enrollment and approved registry administration,
+real credential issuance integration, scoped sessions/jobs/projects/artifacts/backups,
+read/denial audit, safe recovery/retention and worker adapters. Versioned credential
+preservation and the public typed memory operations now have source implementations.
+Every unsupported tenant capability remains denied.
+
+Operational approval is needed before creating a real tenant root or binding records,
+issuing or configuring credentials, enabling the runtime, assigning workers, changing
+network/security settings, migrating data or deploying. Sharing installed binaries is
+compatible with isolated workers; sharing a service UID or application credential pool
+does not provide that isolation. 9Router private provider routing still needs explicit
+per-tenant grants and no cross-account fallback, or an explicitly approved shared pool.
diff --git a/docs/TENANT-PREVIEW.md b/docs/TENANT-PREVIEW.md
new file mode 100644
index 00000000..fbf7cf0a
--- /dev/null
+++ b/docs/TENANT-PREVIEW.md
@@ -0,0 +1,175 @@
+# Tenant preview: identity and scoped memory
+
+Status: isolated implementation candidate, disabled by default. This is not a
+production multiuser release. No live tenant registry/storage activation, provisioning,
+credential issuance, account migration or app runtime wiring is supplied.
+
+## Purpose and mode
+
+OS_TENANCY_MODE is absent or legacy by default. Existing owner behavior is unchanged.
+The tenant-preview value selects a fail-closed experimental MCP/capability path.
+Unknown values fail closed. Do not enable this setting on a production/shared-user
+deployment without the separate operational approval and release checks below.
+OS_TENANCY_STORAGE_ROOT must explicitly select an existing, initialized private store.
+The runtime never creates a root, initializes state or enrolls an identity.
+
+A server token carrying a tenant binding or deprecated tenantSubject marker cannot fall back to owner authority when
+preview is disabled. An opaque tenant context also stops working after mode disablement.
+
+The flag does not turn browser device roles, owner /api/v1 routes, A2A ingress,
+managed-app dashboards or the host account into tenant endpoints. Those surfaces
+need their own reviewed identity and isolation work before multiuser deployment.
+
+## Actual integration points
+
+- app/mcp/route.ts validates the existing bearer, resource binding and protocol,
+ then resolves a server-owned named subject before any legacy session/client-state work
+- lib/mcp/tenant-dispatch.ts provides a separate metadata/tool path without the
+ owner activity/audit, session, workflow or standby dispatcher
+- lib/capabilities/execute.ts checks tenant mode/context before legacy presence,
+ workflow lookup, title changes, activity, session events or tool execution
+- lib/tenancy/authority.ts issues opaque process-local contexts from a trusted registry
+- lib/tenancy/storage.ts derives and verifies scoped storage addresses
+- lib/tenancy/runtime.ts lazily composes the durable adapter from server-owned configuration
+- lib/tenancy/public-memory.ts derives read/search/write grants from the opaque context
+- Capability invocation context propagation must preserve the opaque tenant context;
+ loss of context in preview fails closed rather than restoring host authority
+
+## Identity contract
+
+The versioned binding comes from the already validated, server-owned MCP token record.
+It is not taken from request JSON, MCP metadata, session headers, clientId, labels,
+integration profiles or filesystem folders.
+
+Owner consent and PAT issuance do not assign tenantBinding. Existing tokens remain
+legacy credentials when preview is off and are refused in preview because they have
+no approved versioned binding. This candidate creates no live grants or persistent access.
+
+A trusted registry resolves issuer+subject to one enabled binding:
+tenantId, principalId and mappingRevision. The tenant must also be enabled.
+An ambiguous lookup must fail; it must never choose a default tenant.
+
+The binding is cloned and frozen in an opaque WeakMap-backed context. Callers cannot
+forge it by copying fields. Every access revalidates expiry, revocation, principal,
+tenant and revision. A principal reassignment requires a newly approved credential, not merely a new context.
+
+Registry implementations must provide authoritative, consistent results, and increment
+mappingRevision whenever a binding changes. This library validates the revision;
+it cannot enforce an external registry writer.
+
+## Credential lifecycle and runtime composition
+
+TenantCredentialBinding version1 pins issuer, subject, tenantId, principalId and
+mappingRevision. Issuers are bounded internal registry IDs, not arbitrary OIDC URLs.
+Every tenant request compares that exact immutable stamp with the current authoritative
+registry before context creation. Disable/re-enable and remapping never upgrade an old
+credential to the new binding. Missing, malformed, unknown-version and deprecated
+subject-only stamps are denied, including attempts to downgrade into legacy owner mode.
+
+The injected runtime factory accepts registry, storage, verifier, mode and clock ports.
+Its bearer entry point calls the verifier; resolveValidatedToken is reserved for
+transports that already verified the bearer. The default runtime opens no store while
+preview is disabled. In preview, it requires a valid versioned token stamp and explicit
+OS_TENANCY_STORAGE_ROOT, then opens that store with initialize:false. It never infers
+identities or enrolls anyone. Changing the configured root after composition fails
+closed and requires a reviewed restart; a failed open is not silently retried elsewhere.
+
+McpCode, access and refresh records preserve the same stamp. Code exchange and refresh
+inspect the full persisted record before deletion or field projection. Issuance also
+reauthorizes before storing replacements. Rotation and grant-family revocation retain
+the existing OAuth-store lock, and revocation remains possible for stale bindings.
+Inputs are captured before queued mutations; request body fields never select identity.
+
+The OAuth store and registry are separate transactions. A registry change racing an
+issuance can leave an unusable old-generation record; every later request denies it.
+This is not cross-store atomic issuance or cancellation of every in-flight request.
+The source APIs do not grant enrollment authority, and no live verifier/root is configured.
+
+## Storage contract
+
+A read address contains tenantId, principalId, mappingRevision, collection and key.
+Every field is derived from the authenticated context or a bounded server operation.
+There is no directory argument and no owner/global fallback.
+
+The storage port must query using the complete address. Returned envelopes must echo
+the exact address or the read is refused. Binding state is checked again after the
+await, so an expired/revoked/remapped identity does not receive the result.
+
+The public MCP path implements scoped memory read, search, remember and forget.
+Collection types reserve memory, sessions, jobs, projects, artifacts and backups;
+these types are not permission to expose those other collections.
+
+A source-only durable registry/memory/audit adapter now exists; see [Tenant persistence](TENANT-PERSISTENCE.md).
+The source runtime composition requires an explicit private root. No live root or
+mode has been configured by this work. OS isolation and production administrative
+authorization remain separate requirements.
+
+## Capability contract
+
+Tenant preview implements the existing agent_memory_read, agent_memory_search,
+agent_memory_remember and agent_memory_forget contracts. USER.md and MEMORY.md are
+scoped by tenant, principal and mapping generation. Missing records yield empty
+memory, never owner memory. Typed claims preserve kind, confidence, sensitivity,
+validity, supersession, conflict and retraction semantics without invoking owner storage.
+
+The internal CLAIMS.v1 ledger is never a caller-selectable document. It holds at most
+256 records and512 KiB encoded state, with64 KiB cumulative content per document,
+including history. Capacity fails closed; forget retracts rather than purges history.
+Existing raw documents are readable but are not silently converted into typed history;
+nonempty raw state requires an explicit reviewed migration before typed operations.
+
+The kernel still enforces token tool allowlists, argument constraints, scopes and
+declared rate limits. Rate keys use the verified tenant principal. Every memory tool
+rejects caller-provided tenant/user/path/workflow selectors and unexpected arguments.
+Writes revalidate current binding, expiry and configuration inside the shared durable
+transaction and commit their success audit atomically. Reads are revalidated after awaits.
+
+Exec, filesystem, browser, managed apps, integrations, project MCP, sessions,
+workflows and every unknown capability are denied before the legacy handler.
+
+Tenant metadata exposes only the four implemented tools. Resources are empty; resource
+reads are denied. It retains Origin, SSE and modern-protocol HTTP rules.
+No owner telemetry is written in preview; the durable candidate records internal successful mutations only.
+The memory mutation audit contains fixed tool/document identifiers and derived scope,
+never memory keys, values, subjects or tokens. Read/denial auditing still needs integration.
+GET metadata reports whether a root string is configured, not store health or readiness.
+
+## Verification
+
+The candidate has fixture-based authority/storage, kernel/dispatcher and HTTP-boundary
+coverage plus legacy MCP route, authorization, protocol and environment regressions.
+Fixtures use synthetic subjects/storage. Basic HTTP-boundary tests mock handoff;
+the persistent-route suite instead exercises actual POST, runtime composition,
+dispatch, kernel and temporary durable storage while faking only bearer verification.
+This is integration coverage, not an operational tenant authentication deployment.
+
+Reproduce the focused suite after installing the repository's existing dependencies:
+
+```sh
+umask 077
+mkdir -p .tenant-test-home
+HOME="$PWD/.tenant-test-home" XDG_STATE_HOME="$PWD/.tenant-test-home/.state" \
+ OS_FS_READ_ROOTS="$PWD:$PWD/.tenant-test-home" VITEST_MAX_WORKERS=2 \
+ bun run test lib/tenancy \
+ lib/mcp/tenant-capability-integration.test.ts app/mcp/tenant-route.test.ts \
+ app/mcp/tenant-persistent-route.test.ts \
+ app/mcp/route.test.ts app/mcp/route-protocol.test.ts \
+ lib/mcp/dispatch-authorization.test.ts lib/config/env-example.test.ts --maxWorkers=2
+```
+
+The ignored fake HOME keeps incidental test state separate from the operator's real
+home. Do not stage it. A fixture pass does not replace typecheck, compilation, full
+regression, tenant backend verification, integration review or deployment approval.
+
+## Remaining release gates
+
+1. Verify the exact candidate and current integration base with typecheck, supported isolated build and release tests
+2. Review and authorize durable registry/memory activation; implement the remaining scoped stores
+3. Authorize named enrollment and real credential issuance using the implemented binding lifecycle
+4. Wire guarded file/exec/job/browser workers and tenant-aware audit without owner fallback
+5. Verify each actual Hermes/OpenClaw/9Router adapter and its provider retry semantics
+6. Cover other ingress surfaces, real-user E2E, recovery, quotas and security review
+7. Integrate on the current canonical base and verify before separately approved deployment
+
+No new public MCP tool names or schemas are introduced. The full legacy catalog stays
+unchanged; tenant preview advertises only its four implemented memory tools.
diff --git a/docs/TENANT-ROLLOUT.md b/docs/TENANT-ROLLOUT.md
new file mode 100644
index 00000000..59c8f4f4
--- /dev/null
+++ b/docs/TENANT-ROLLOUT.md
@@ -0,0 +1,104 @@
+# Tenant rollout gates
+
+Status: implementation plan, not a production-readiness declaration. The shared
+front gateway may route distinct users, but sharing a folder name or application
+profile does not create an OS security boundary. Installed binaries can be shared;
+untrusted users need verified worker, storage, credential and session separation.
+
+## 1. Identity and durable memory foundation
+
+The isolated source candidate implements versioned server-owned identity bindings,
+revocation generations, guarded durable storage and scoped memory
+read/search/remember/forget. Writes commit a sanitized audit event atomically.
+Actual MCP route tests use fake verified identities and temporary durable state.
+Default behavior remains legacy; no production tenant has been enrolled.
+
+Acceptance: adversarial identity, argument, storage, concurrency and corruption tests;
+legacy regressions; independent review; exact-commit isolated build and release E2E.
+See [Tenant preview](TENANT-PREVIEW.md) and [Tenant persistence](TENANT-PERSISTENCE.md).
+
+## 2. Enrollment, administration and credentials
+
+Implement a reviewed administrative flow for named identities, exact tenant/principal
+bindings, approvals, revocation and recovery. A tenant cannot self-select a directory,
+provider, tenant ID or principal ID. Bind credentials to the approved current generation;
+never grandfather an unbound credential into tenant authority.
+
+Acceptance: wrong issuer/subject, duplicate mapping, stale generation, revoked identity,
+concurrent grant/revoke, refresh replay and root replacement all fail closed. Recovery
+preserves generation continuity or explicitly revokes old credentials. No credential
+value belongs in source, command arguments, audit events or documentation.
+
+Operational gate: approval for actual named enrollment, persistent grants and credential
+configuration. Source tests alone do not authorize those actions.
+
+## 3. Isolated workers and remaining stores
+
+Build a server-owned broker mapping an authenticated context to an exact worker identity.
+Enforce ownership of filesystem operations, exec/PTY, jobs, processes, sockets, browser
+profiles, sessions, projects, artifacts and backups. A worker must not receive the host
+Docker socket, owner credentials, unrelated host mounts or a permissive shared HOME.
+
+Acceptance: traversal/symlink/hardlink tests; peer file/process/socket denial; cross-user
+job cancellation and output denial; browser cookie/profile separation; restart ownership;
+bounded CPU/memory/PID/disk quotas; scoped logs and backup/restore. A mock broker cannot
+prove OS containment. The earlier disposable shell-worker pilot is evidence for those
+tested primitives only, not verification of managed application adapters.
+
+Operational gate: exact worker images, identities, mounts, network rules and resource
+limits must be approved before provisioning or changing live isolation settings.
+
+## 4. Shared application routing
+
+- Hermes: verify the installed version's profile/HOME/config routing and every tool's
+ backend authority. Multiple named profiles alone do not constrain same-UID host access
+- OpenClaw: route mutually untrusted users to separate verified trust domains; one
+ front gateway does not require one shared privileged application process
+- 9Router: decide explicitly whether provider accounts form an intentionally shared
+ pool. Private provider ownership requires tenant grants on every selection and retry,
+ with no cross-tenant fallback, or separated application runtimes
+
+Acceptance: each adapter has an explicit capability/trust matrix; unsupported operations
+remain denied. Tests cover credentials, retry/fallback, session state, browser state,
+logs and restart routing without exposing real provider secrets.
+
+Operational gate: approve real application/credential routing and the intended provider
+sharing model. Reusing installed software is distinct from sharing private credentials.
+
+## 5. User MCP endpoint and UI
+
+Provide tenant-aware connection setup and user-facing state while preserving an owner
+administrative recovery path. All accepted ingress must resolve the same authenticated
+principal policy. Browser device roles, owner API routes, A2A and managed-app dashboards
+are not automatically tenant endpoints.
+
+The current global tenant-preview mode refuses unbound legacy MCP tokens, including
+owner connectors. Do not switch a live installation into that mode before the endpoint,
+token audience and administrative cutover/recovery design is verified.
+
+Acceptance: each user sees only allowed tools and their own state; direct tool calls
+still enforce authorization when bypassing discovery/UI; cross-endpoint token replay and
+caller-supplied tenant selectors fail; owner recovery survives a tenant outage.
+
+## 6. Approved operational pilot
+
+Prepare a concrete two-synthetic-user run using the actual chosen worker and application
+adapters. Name exact image identities, limits, mounts, private/loopback networking,
+secret-entry method, cleanup scope and recovery steps. Never reuse a completed pilot's
+approval as blanket authority to provision another environment.
+
+Acceptance: adversarial separation plus ordinary end-to-end user work, restart and
+revocation, quotas, audit redaction and rollback. Retain sanitized evidence; delete only
+the exact approved temporary resources and synthetic data after verification.
+
+## 7. Canonical integration and release
+
+Reconcile the preserved candidate with current canonical changes through the supported
+workflow. Do not overwrite concurrent WIP or force/reset branches. Run complete release
+and security gates, dependency evidence, recovery and capacity tests on the exact
+integrated revision. A feature branch is not a shipped release.
+
+Operational gate: explicit deployment/cutover scope, approved real identities and app
+routing, a recovery path and a verified rollback. After deployment, prove the intended
+revision is served and repeat real endpoint acceptance. Do not claim the overall
+multiuser goal complete while any required worker/app/credential boundary is unverified.
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 653aa2bd..8ae83867 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -8,6 +8,7 @@ const config = [
ignores: [
".next/**",
"node_modules/**",
+ ".claude/worktrees/**", // linked task checkouts; lint each worktree from its own root
"os-browser/**", // separate sidecar package (plain Node)
"public/**",
"next-env.d.ts",
diff --git a/frontend/slices/app-store/components/managed-apps-catalog.tsx b/frontend/slices/app-store/components/managed-apps-catalog.tsx
index bb09684f..b6d13077 100644
--- a/frontend/slices/app-store/components/managed-apps-catalog.tsx
+++ b/frontend/slices/app-store/components/managed-apps-catalog.tsx
@@ -15,16 +15,39 @@ export function ManagedAppsCatalog({ query }: { query: string }) {
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
- void fetch("/api/v1/managed-apps", { cache: "no-store", signal: controller.signal }).then(async response => {
- if (!response.ok) throw new Error("Could not load installable apps.");
- const data = await response.json() as { apps: ManagedAppView[] };
- setApps(data.apps); setError("");
- }).catch(reason => { if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : "Could not load apps."); });
+ const loadApps = async () => {
+ try {
+ const response = await fetch("/api/v1/managed-apps", { cache: "no-store", signal: controller.signal });
+ if (!response.ok) throw new Error("Could not load installable apps.");
+ const data = await response.json() as { apps: ManagedAppView[] };
+ setApps(data.apps);
+ setError("");
+ } catch (reason) {
+ if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : "Could not load apps.");
+ }
+ };
+
+ void loadApps();
void fetch("/api/v1/app-catalog", { cache: "no-store", signal: controller.signal }).then(async response => {
if (!response.ok) throw new Error("Catalog unavailable.");
setCatalog(await response.json() as CatalogState);
}).catch(() => { if (!controller.signal.aborted) setCatalog({ status: "unavailable", entries: [] }); });
- return () => controller.abort();
+
+ // Installing a managed app happens in a separate MSO window. The App Store can
+ // remain mounted behind it, so a mount-only read leaves the card saying "Not
+ // installed" even after the server is running. Refresh only on user-return
+ // signals; no background polling is needed for this catalog surface.
+ const refreshVisible = () => {
+ if (!document.hidden) void loadApps();
+ };
+ document.addEventListener("visibilitychange", refreshVisible);
+ window.addEventListener("focus", refreshVisible);
+
+ return () => {
+ controller.abort();
+ document.removeEventListener("visibilitychange", refreshVisible);
+ window.removeEventListener("focus", refreshVisible);
+ };
}, []);
const managedIds = useMemo(() => catalog?.entries.filter(entry => entry.kind === "managed").map(entry => entry.id) ?? [], [catalog]);
diff --git a/frontend/slices/appshell/components/desktop.tsx b/frontend/slices/appshell/components/desktop.tsx
index fed63ac7..1fd7fd78 100644
--- a/frontend/slices/appshell/components/desktop.tsx
+++ b/frontend/slices/appshell/components/desktop.tsx
@@ -50,6 +50,8 @@ function Surface() {
// hotkey would silently snap the hidden focused window under a single-pane or
// mobile shell, surprising the user when they switch back.
useWindowSnapKeys(!!desc.windowed);
+ // A mobile shell on a wide viewport (device override = phone, or a portrait
+ // tablet) previews inside a phone frame; a real narrow screen fills.
const framed = surface === "mobile" && r.vw >= 768;
// The shell renders ONLY after mount, and this is a correctness fix, not caution.
diff --git a/frontend/slices/appshell/components/dock-parts.tsx b/frontend/slices/appshell/components/dock-parts.tsx
index e6fd2c06..9698ceca 100644
--- a/frontend/slices/appshell/components/dock-parts.tsx
+++ b/frontend/slices/appshell/components/dock-parts.tsx
@@ -21,7 +21,7 @@ import type { AppDescriptor, WindowState } from "../lib/types";
// (window list); otherwise a compact macOS name caption centred over the icon.
export function HoverPanel({ wide, children }: { wide?: boolean; children: React.ReactNode }) {
return (
- <div className="pointer-events-none invisible absolute bottom-full left-1/2 z-[60] -translate-x-1/2 pb-4 opacity-0 transition-all duration-150 group-hover:visible group-hover:opacity-100 group-hover:pointer-events-auto">
+ <div className="pointer-events-none invisible absolute bottom-full left-1/2 z-[60] -translate-x-1/2 pb-4 opacity-0 transition-all duration-150 group-hover:visible group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:visible group-focus-within:opacity-100 group-focus-within:pointer-events-auto">
<div
className={
"glass rounded-xl border border-border shadow-[0_12px_40px_-8px_rgba(0,0,0,0.55)] " +
diff --git a/frontend/slices/appshell/components/dock.test.ts b/frontend/slices/appshell/components/dock.test.ts
index e1b4be2b..240a402c 100644
--- a/frontend/slices/appshell/components/dock.test.ts
+++ b/frontend/slices/appshell/components/dock.test.ts
@@ -35,6 +35,13 @@ describe("dockFit", () => {
expect(dockFit(900, 27, 2, MED, false).base).toBeGreaterThan(dockFit(900, 27, 2, MED, true).base);
});
+ it("reserves the entire hover pool inside the viewport", () => {
+ for (const vw of [844, 1024, 1280, 1512]) {
+ const { base, cramped, dockExtra } = dockFit(vw, 27, 2, MED, true);
+ if (!cramped) expect(base * 25 + 8 * 26 + 13 * 2 + 32 + dockExtra).toBeLessThanOrEqual(vw);
+ }
+ });
+
it("never divides by zero on an empty dock", () => {
expect(dockFit(1024, 0, 0, MED, false).base).toBe(MED);
});
diff --git a/frontend/slices/appshell/components/dock.tsx b/frontend/slices/appshell/components/dock.tsx
index 67f0d070..6165f0c0 100644
--- a/frontend/slices/appshell/components/dock.tsx
+++ b/frontend/slices/appshell/components/dock.tsx
@@ -29,7 +29,7 @@ const MIN_ICON = 22; // shrink floor — past it the row scrolls instead
// feature, i.e. dozens of extra slots. Past the floor even shrinking can't fit the
// row, so it scrolls; magnification is off there (it assumes an unscrolled row).
export function dockFit(vw: number, count: number, seps: number, max: number, magnify: boolean) {
- const reserve = magnify ? Math.round(max * 0.6) : 0; // hover growth headroom
+ const reserve = magnify ? Math.round(max * 2.2) : 0; // reserve the full magnification pool
const room = vw - 32 - GAP * (count - 1) - SEP_W * seps - reserve;
const fit = Math.floor(room / Math.max(1, count - seps));
const cramped = fit < MIN_ICON;
@@ -175,7 +175,7 @@ export function Dock({ onMissionControl }: { onMissionControl?: () => void }) {
ref={rowRef}
onPointerMove={(e) => { mouseX.current = e.clientX; schedule(); }}
onPointerLeave={() => { mouseX.current = null; schedule(); }}
- className={`glass pointer-events-auto flex items-end rounded-[22px] border border-white/40 px-2.5 py-2 shadow-[0_1px_0_rgba(255,255,255,0.4)_inset,0_18px_50px_-10px_rgba(0,0,0,0.5)] dark:border-white/10 ${cramped ? "w-max" : ""}`}
+ className={`macos-dock glass pointer-events-auto flex items-end rounded-[22px] border border-white/40 px-2.5 py-2 shadow-[0_1px_0_rgba(255,255,255,0.4)_inset,0_18px_50px_-10px_rgba(0,0,0,0.5)] dark:border-white/10 ${cramped ? "w-max" : ""}`}
style={{ background: "var(--dock-bg)", gap: GAP }}
>
{slots.map((s, i) => {
diff --git a/frontend/slices/appshell/components/macos-chrome.test.ts b/frontend/slices/appshell/components/macos-chrome.test.ts
new file mode 100644
index 00000000..81371c81
--- /dev/null
+++ b/frontend/slices/appshell/components/macos-chrome.test.ts
@@ -0,0 +1,67 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+import { TOPBAR } from "../lib/store-geometry";
+
+const css = readFileSync("frontend/slices/appshell/components/shells/macos/macos-shell.css", "utf8");
+type Color = [number, number, number, number];
+function color(raw: string): Color {
+ if (raw.startsWith("#")) {
+ const hex = raw.slice(1);
+ const full = hex.length === 3 ? [...hex].map(c => c + c).join("") : hex;
+ return [0, 2, 4].map(i => parseInt(full.slice(i, i + 2), 16)).concat(1) as Color;
+ }
+ const parts = raw.match(/[\d.]+/g)!.map(Number);
+ return [parts[0], parts[1], parts[2], parts[3] ?? 1];
+}
+function over(front: Color, back: Color): Color {
+ return [0, 1, 2].map(i => front[i] * front[3] + back[i] * (1 - front[3])).concat(1) as Color;
+}
+function luminance(c: Color) {
+ const values = c.slice(0, 3).map(n => {
+ const s = n / 255;
+ return s <= .04045 ? s / 12.92 : ((s + .055) / 1.055) ** 2.4;
+ });
+ return values[0] * .2126 + values[1] * .7152 + values[2] * .0722;
+}
+function contrast(a: Color, b: Color) {
+ const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x);
+ return (high + .05) / (low + .05);
+}
+function declaration(block: string, name: string) {
+ const value = new RegExp("(?:^|[;\\n])\\s*" + name + ":\\s*([^;]+)").exec(block)?.[1];
+ if (!value) throw new Error("Missing CSS declaration: " + name);
+ return color(value.trim());
+}
+
+describe("macOS chrome reference and contrast contract", () => {
+ const bar = css.match(/\.macos-menubar\s*\{([^}]*)\}/)![1];
+ const interaction = css.match(/\.macos-menu-trigger\[data-state="open"\]\s*\{([^}]*)\}/)![1];
+ const text = declaration(bar, "color");
+ const white: Color = [255, 255, 255, 1];
+
+ it("normal, hover and open menu labels and status clock remain AA over white wallpaper", () => {
+ expect(css).toContain(".macos-menubar .macos-status button:hover,\n.macos-menu-trigger[data-state=\"open\"]");
+ const background = over(declaration(bar, "background"), white);
+ const hover = over(declaration(interaction, "background"), background);
+ expect(contrast(text, background)).toBeGreaterThanOrEqual(4.5);
+ expect(contrast(text, hover)).toBeGreaterThanOrEqual(4.5);
+ });
+ it.each(["light", "dark"])("%s menu text remains AA over every wallpaper endpoint", mode => {
+ const selector = mode === "light" ? /\.macos-menu\s*\{([^}]*)\}/ : /\[data-theme="dark"\] \.macos-menu\s*\{([^}]*)\}/;
+ const block = css.match(selector)![1];
+ for (const shade of [0, 255]) {
+ const surface = over(declaration(block, "background"), [shade, shade, shade, 1]);
+ expect(contrast(declaration(block, "color"), surface)).toBeGreaterThanOrEqual(4.5);
+ }
+ });
+ it("selected menu rows retain AA contrast", () => {
+ const block = css.slice(css.indexOf('.macos-menu [role^="menuitem"]:is')).match(/\{([^}]*)\}/)![1];
+ expect(contrast(declaration(block, "color"), declaration(block, "background"))).toBeGreaterThanOrEqual(4.5);
+ });
+ it("macOS work area uses the same 34px reference bar", () => expect(TOPBAR).toBe(34));
+ it("reference styles stay scoped and never replace Spotlight tokens", () => {
+ expect(css).not.toMatch(/:root|--glass-panel:|--glass-menu:|--text:|--surface:/);
+ expect(css).toContain('[data-shell="macos"][data-shell]');
+ expect(css).toContain("--shell-radius-win: 16px");
+ });
+});
diff --git a/frontend/slices/appshell/components/menu-bar-menus.tsx b/frontend/slices/appshell/components/menu-bar-menus.tsx
index b7ec4e73..4dbbc5ab 100644
--- a/frontend/slices/appshell/components/menu-bar-menus.tsx
+++ b/frontend/slices/appshell/components/menu-bar-menus.tsx
@@ -182,15 +182,13 @@ export function Menu(props: { label: string; bold?: boolean; children: React.Rea
<DropdownMenu>
<DropdownMenuTrigger
className={
- // Smooth macOS feel: snappy colour transition, subtle hover wash, and a
- // solid accent highlight (blue + white text) while the menu is open.
- "rounded-[6px] px-2 py-[3px] outline-none transition-colors duration-150 hover:bg-[var(--hover-strong)] data-[state=open]:bg-primary data-[state=open]:text-primary-foreground " +
- (props.bold ? "font-bold" : "font-medium")
+ "macos-menu-trigger shrink-0 rounded-full px-[9px] py-1 leading-4 outline-none transition-colors duration-150 " +
+ (props.bold ? "font-extrabold" : "font-semibold")
}
>
{props.label}
</DropdownMenuTrigger>
- <DropdownMenuContent align="start" sideOffset={6} className="rounded-xl">
+ <DropdownMenuContent align="start" sideOffset={5} className="macos-menu rounded-xl">
{props.children}
</DropdownMenuContent>
</DropdownMenu>
diff --git a/frontend/slices/appshell/components/menu-bar-status.tsx b/frontend/slices/appshell/components/menu-bar-status.tsx
index edd2df75..b0f63be2 100644
--- a/frontend/slices/appshell/components/menu-bar-status.tsx
+++ b/frontend/slices/appshell/components/menu-bar-status.tsx
@@ -16,12 +16,12 @@ export function StatusCluster() {
const unread = useNotifications().some((n) => !n.read);
return (
- <div className="ml-auto flex items-center gap-0.5 text-muted-foreground">
+ <div className="macos-status ml-auto flex shrink-0 items-center gap-0.5">
<span data-slot="system-status-host" data-status-placement="menu-bar" className="flex items-center">
<Slot region="systemStatus" />
</span>
{cpu != null && (
- <span className="flex items-center gap-1 rounded-md px-2 py-0.5 tabular-nums">
+ <span data-slot="macos-cpu" className="flex items-center gap-1 rounded-md px-2 py-0.5 tabular-nums">
<Activity className="size-3.5" />
{cpu}%
</span>
diff --git a/frontend/slices/appshell/components/menu-bar.tsx b/frontend/slices/appshell/components/menu-bar.tsx
index 15670962..797bf0bc 100644
--- a/frontend/slices/appshell/components/menu-bar.tsx
+++ b/frontend/slices/appshell/components/menu-bar.tsx
@@ -5,6 +5,7 @@ import {
DropdownMenuSeparator,
DropdownMenuShortcut,
} from "@/components/ui/dropdown-menu";
+import { TOPBAR } from "../lib/store-geometry";
import { useApps } from "../lib/registry";
import { useBrand } from "../registry/brand";
import { useFocused } from "../hooks/use-shell";
@@ -34,10 +35,11 @@ export function MenuBar() {
return (
<header
- className="glass absolute inset-x-0 top-0 z-[900] flex h-[30px] items-center gap-0.5 border-b border-border px-2.5 text-[13px] font-medium font-[family-name:var(--shell-font)]"
- style={{ background: "var(--glass-bar)" }}
+ className="macos-menubar absolute inset-x-0 top-0 z-[900] flex items-center gap-1 px-2.5 text-[13px] font-medium font-[family-name:var(--shell-font)]"
+ style={{ height: TOPBAR }}
>
- <span className="grid size-4 place-items-center rounded-[5px] bg-primary text-[10px] font-extrabold text-primary-foreground">
+ <div className="flex min-w-0 items-center overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+ <span aria-hidden className="grid shrink-0 size-4 place-items-center rounded-[5px] bg-primary text-[10px] font-extrabold text-primary-foreground">
{brand.logo}
</span>
@@ -90,6 +92,7 @@ export function MenuBar() {
<WindowMenu focusedId={focusedId} />
<HelpMenu />
+ </div>
<StatusCluster />
</header>
);
diff --git a/frontend/slices/appshell/components/mobile-app-library-parts.tsx b/frontend/slices/appshell/components/mobile-app-library-parts.tsx
index 0e386a37..5be05c9f 100644
--- a/frontend/slices/appshell/components/mobile-app-library-parts.tsx
+++ b/frontend/slices/appshell/components/mobile-app-library-parts.tsx
@@ -54,7 +54,7 @@ export function FolderCard({
{!overflow &&
Array.from({ length: 4 - big.length }).map((_, i) => <span key={`pad-${i}`} />)}
</div>
- <span className={cn("max-w-full truncate text-[12px] font-medium text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]")}>
+ <span className={cn("max-w-full truncate text-[12px] font-normal leading-4 text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]")}>
{name}
</span>
</Button>
@@ -83,7 +83,7 @@ export function AlphaList({
return (
<div key={a.id}>
{header && (
- <div className="px-1 pb-1 pt-2 text-[12px] font-bold text-white/70 [text-shadow:0_1px_2px_rgba(0,0,0,0.5)]">
+ <div className="px-1 pb-1 pt-2 text-[13px] font-semibold leading-[18px] tracking-[-0.08px] text-white/70 [text-shadow:0_1px_2px_rgba(0,0,0,0.5)]">
{header}
</div>
)}
@@ -91,12 +91,12 @@ export function AlphaList({
type="button"
variant="ghost"
onClick={() => onOpen(a)}
- className="h-auto flex w-full items-center gap-3 rounded-xl px-1 py-1.5 text-left hover:bg-white/10"
+ className="flex h-auto min-h-11 w-full items-center gap-3 rounded-xl px-4 py-1.5 text-left hover:bg-white/10"
>
<span className="size-9 shrink-0">
<AppIcon app={a} />
</span>
- <span className="text-sm font-medium text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.5)]">{a.title}</span>
+ <span className="text-[17px] font-normal leading-[22px] tracking-[-0.43px] text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.5)]">{a.title}</span>
</Button>
</div>
);
diff --git a/frontend/slices/appshell/components/mobile-app-library.tsx b/frontend/slices/appshell/components/mobile-app-library.tsx
index 9debec69..e5d64254 100644
--- a/frontend/slices/appshell/components/mobile-app-library.tsx
+++ b/frontend/slices/appshell/components/mobile-app-library.tsx
@@ -58,19 +58,19 @@ export function MobileAppLibrary({
return (
<div className="relative flex h-full flex-col px-4 py-3">
- <h2 className="mb-2 px-1 text-lg font-bold text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]">
+ <h2 className="mb-2 px-1 text-[28px] font-bold leading-[34px] tracking-[0.38px] text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]">
App Library
</h2>
<label
- className="mb-3 flex items-center gap-2 rounded-xl border border-white/15 px-3 py-2 backdrop-blur-xl"
+ className="mb-3 flex min-h-11 items-center gap-2 rounded-xl border border-white/15 px-4 backdrop-blur-xl"
style={{ background: "var(--glass-menu)" }}
>
- <Search className="size-4 text-muted-foreground" />
+ <Search className="size-[17px] text-muted-foreground" />
<input
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="App Library"
- className="w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
+ className="w-full bg-transparent text-[17px] font-normal leading-[22px] tracking-[-0.43px] outline-none placeholder:text-muted-foreground"
/>
</label>
@@ -94,7 +94,7 @@ export function MobileAppLibrary({
style={{ background: "var(--glass-menu)" }}
onClick={(e) => e.stopPropagation()}
>
- <h3 className="mb-3 text-center text-base font-semibold">{folder}</h3>
+ <h3 className="mb-3 text-center text-[17px] font-semibold leading-[22px] tracking-[-0.43px]">{folder}</h3>
<div className="grid grid-cols-4 gap-x-3 gap-y-4">
{folderApps.map((a) => (
<Button key={a.id} type="button" variant="ghost" onClick={() => onOpen(a)} className="h-auto p-0 hover:bg-transparent flex flex-col items-center gap-1.5">
@@ -105,7 +105,7 @@ export function MobileAppLibrary({
<span className="aspect-square w-full max-w-[60px]">
<AppIcon app={a} />
</span>
- <span className="max-w-full truncate text-[11px] font-medium leading-[13px]">{a.title}</span>
+ <span className="max-w-full truncate text-[12px] font-normal leading-4">{a.title}</span>
</Button>
))}
</div>
diff --git a/frontend/slices/appshell/components/mobile-home-parts.tsx b/frontend/slices/appshell/components/mobile-home-parts.tsx
index dec7fdf7..9e497c68 100644
--- a/frontend/slices/appshell/components/mobile-home-parts.tsx
+++ b/frontend/slices/appshell/components/mobile-home-parts.tsx
@@ -1,6 +1,6 @@
"use client";
/* iPhone-home sub-surfaces — ONE page of the app grid (upward-swipe search +
- long-press quick actions) and the haptic-touch action sheet. Split from
+ long-press point). The quick-actions menu lives in shells/ios. Split from
mobile-home.tsx (≤200-LOC modularity gate). */
import { useMemo, useRef } from "react";
import { Button } from "@/components/ui/button";
@@ -16,47 +16,6 @@ import { QuicklinkIcon } from "./quicklink-icon";
// and quicklinks spend the same budget, so three bookmarks tipped 390 over too.
const ICONS_PER_PAGE = 24;
-// Long-press quick-actions sheet (iPhone's haptic-touch menu): Open + whatever
-// menu items the app declares for the macOS menu bar — one declaration, both OSes.
-export function AppActionSheet({
- app, onOpen, onClose,
-}: {
- app: AppDescriptor; onOpen: () => void; onClose: () => void;
-}) {
- const items = (app.menus ?? []).flatMap((m) => m.items).filter(
- (it): it is Extract<typeof it, { label: string }> => !("sep" in it),
- );
- return (
- <div className="absolute inset-0 z-[45] flex flex-col justify-end" onClick={onClose}>
- <div className="absolute inset-0 bg-black/35 backdrop-blur-[2px]" />
- <div
- className="relative mx-4 mb-6 overflow-hidden rounded-2xl bg-card/95 text-card-foreground shadow-2xl"
- onClick={(e) => e.stopPropagation()}
- >
- <div className="flex items-center gap-2.5 border-b border-border px-4 py-3">
- <span className="size-9"><AppIcon app={app} /></span>
- <strong className="text-[15px]">{app.title}</strong>
- </div>
- <Button type="button" variant="ghost" onClick={onOpen} className="h-auto block w-full justify-start rounded-none px-4 py-3 text-left text-[15px] font-medium">
- Open
- </Button>
- {items.slice(0, 4).map((it, i) => (
- <Button
- key={i}
- type="button"
- variant="ghost"
- disabled={it.disabled}
- onClick={() => { onClose(); it.onSelect?.(); }}
- className="h-auto block w-full justify-start rounded-none border-t border-border px-4 py-3 text-left text-[15px]"
- >
- {it.label}
- </Button>
- ))}
- </div>
- </div>
- );
-}
-
export type HomeTile =
| { key: string; kind: "app"; app: AppDescriptor }
| { key: string; kind: "link"; link: QuickLink };
@@ -100,10 +59,9 @@ function Tile({
{/* No max-w — width follows height via aspect-square. Clamping the width too
made the tile 58.5×60, visibly non-square, on a 360px-wide phone. */}
<span className="aspect-square min-h-0 max-h-[60px] flex-1">{icon}</span>
- {/* 11px/13px — iOS home labels are 11pt SF, one line, tight leading. Was 12px
- inheriting the Button's 1.43 (17.1px measured), wasting 4px per row — 24px
- over six rows, which is the margin six rows fit by. */}
- <span className="max-w-full shrink-0 truncate text-[11px] font-medium leading-[13px] text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]">
+ {/* Caption 1: 12/16 Regular. Leading is set so the Button's text-sm
+ line-height cannot stretch the six-row grid. */}
+ <span className="max-w-full shrink-0 truncate text-[12px] font-normal leading-4 text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]">
{label}
</span>
</Button>
@@ -116,7 +74,8 @@ export function AppsGrid({
tiles, onLaunch, onSearch, onContext,
}: {
tiles: HomeTile[]; onSearch: () => void;
- onLaunch: (app: AppDescriptor) => void; onContext: (app: AppDescriptor) => void;
+ onLaunch: (app: AppDescriptor) => void;
+ onContext: (app: AppDescriptor, point: { x: number; y: number }) => void;
}) {
const { open: openLink } = useQuickLinks();
// Long-press bookkeeping: a fired hold must swallow the click that follows.
@@ -138,7 +97,7 @@ export function AppsGrid({
holdTimer.current = window.setTimeout(() => {
held.current = true;
cancel();
- onContext(app);
+ onContext(app, { x: sx, y: sy });
}, 450);
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
@@ -190,7 +149,7 @@ export function AppsGrid({
label={app.title}
icon={<AppIcon app={app} />}
onPointerDown={startHold(app)}
- onContextMenu={(e) => { e.preventDefault(); onContext(app); }}
+ onContextMenu={(e) => { e.preventDefault(); onContext(app, { x: e.clientX, y: e.clientY }); }}
onClick={() => { if (held.current) { held.current = false; return; } onLaunch(app); }}
/>
);
diff --git a/frontend/slices/appshell/components/mobile-home.tsx b/frontend/slices/appshell/components/mobile-home.tsx
index b5099721..8db200b7 100644
--- a/frontend/slices/appshell/components/mobile-home.tsx
+++ b/frontend/slices/appshell/components/mobile-home.tsx
@@ -1,18 +1,20 @@
"use client";
import { useLayoutEffect, useRef, useState } from "react";
-import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { AppDescriptor } from "../lib/types";
-import { AppIcon } from "./app-icon";
import { Slot } from "../registry/feature-registry";
import { MobileAppLibrary } from "./mobile-app-library";
-import { AppActionSheet, AppsGrid, useHomePages } from "./mobile-home-parts";
+import { AppsGrid, useHomePages } from "./mobile-home-parts";
import { ShellContextMenu, useShellContextMenu } from "./shells/context-menu";
+import { IosHomeChrome } from "./shells/ios/ios-home-chrome";
+import { IosQuickActions } from "./shells/ios/ios-quick-actions";
+import { IOS_WIDGET_HOMES, IosWidgetHome } from "./shells/ios/ios-widget-home";
+import { lock } from "../lib/lock";
-// Paged iPhone home: [Today widgets] · [App grid ×N] · [App Library]. The dock,
-// page dots and home-indicator persist across pages. The app grid is N pages of
-// 24 (iPhone's 6×4), not one vertical scroller — see mobile-home-parts.
+// Paged iPhone home: [Today widgets] · [App grid ×N] · [App Library]. Page dots,
+// the search pill and the icon dock persist. The app grid is N pages of 24
+// (iPhone's 6×4) — see mobile-home-parts.
export function MobileHome({
apps,
dockApps,
@@ -34,10 +36,14 @@ export function MobileHome({
}) {
const pagerRef = useRef<HTMLDivElement>(null);
const [page, setPage] = useState(1); // 0 widgets · 1…N apps · N+1 library
- const [ctxApp, setCtxApp] = useState<AppDescriptor | null>(null); // long-press sheet
+ const [hidden, setHidden] = useState<string[]>([]);
+ const [ctxApp, setCtxApp] = useState<{ app: AppDescriptor; x: number; y: number } | null>(null);
const menu = useShellContextMenu("ios", "mobile"); // home background long-press menu
- const gridPages = useHomePages(apps);
- const pageCount = gridPages.length + 2; // + Today + App Library
+ const visible = apps.filter((app) => !hidden.includes(app.id));
+ const gridPages = useHomePages(visible);
+ // Today, plain icon pages, one home per widget size, then the App Library.
+ const widgetStart = gridPages.length + 1;
+ const pageCount = widgetStart + IOS_WIDGET_HOMES.length + 1;
// Open on the app grid (the middle page), like iPhone's default home.
useLayoutEffect(() => {
@@ -47,7 +53,9 @@ export function MobileHome({
const onScroll = () => {
const el = pagerRef.current;
- if (el) setPage(Math.round(el.scrollLeft / el.clientWidth));
+ if (!el) return;
+ const next = Math.round(el.scrollLeft / el.clientWidth);
+ setPage(next);
};
// Swipe DOWN from the top safe-area: LEFT half → Notification Center,
@@ -90,14 +98,14 @@ export function MobileHome({
This 2.25rem is ON TOP of --sai-top, which globals.css floors at 2.75rem
for data-shell="ios" — they ADD, so iOS starts the pager 80px down even in
a browser reporting no inset. Read that before "reclaiming" space here:
- 80px + 34px of dots + a 100px dock block + a 36px indicator = 250px, and
+ 80px + 34px of dots + the search pill and icon dock + a 36px indicator, and
what is left is what caps the home icon (60px at 844 tall, 45.5 at 667). */}
<div
+ data-slot="ios-top-gesture"
className="shrink-0 [touch-action:none]"
style={{ height: "calc(2.25rem + var(--sai-top))" }}
onPointerDown={onTopPointerDown}
/>
-
<div
ref={pagerRef}
onScroll={onScroll}
@@ -106,13 +114,28 @@ export function MobileHome({
<Page active={page === 0}>
{/* Today keeps its OWN scroller — a widget stack is genuinely taller than
the page. The app pages deliberately do not scroll (see AppsGrid). */}
- <div className="h-full overflow-y-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+ <div
+ className="h-full overflow-y-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
+ >
<Slot region="today" />
</div>
</Page>
{gridPages.map((tiles, i) => (
<Page key={tiles[0]?.key ?? `home-${i}`} active={page === i + 1}>
- <AppsGrid tiles={tiles} onLaunch={onLaunch} onSearch={onSearch} onContext={setCtxApp} />
+ <AppsGrid tiles={tiles} onLaunch={onLaunch} onSearch={onSearch} onContext={(app, point) => setCtxApp({ app, ...point })} />
+ </Page>
+ ))}
+ {IOS_WIDGET_HOMES.map((widget, i) => (
+ <Page key={widget.size} active={page === widgetStart + i}>
+ <IosWidgetHome
+ apps={visible}
+ size={widget.size}
+ title={widget.title}
+ span={widget.span}
+ slots={widget.slots}
+ onLaunch={onLaunch}
+ onContext={(app, point) => setCtxApp({ app, ...point })}
+ />
</Page>
))}
<Page active={page === pageCount - 1}>
@@ -138,25 +161,19 @@ export function MobileHome({
))}
</div>
- {dockApps.length > 0 && (
- <div
- className="glass mx-3 mb-3.5 flex justify-around rounded-[30px] border border-white/15 px-3.5 py-3"
- style={{ background: "var(--glass-bar)", boxShadow: "inset 0 0.5px 0 var(--glass-hi), 0 12px 34px rgba(0,0,0,0.30)" }}
- >
- {dockApps.map((app) => (
- <Button key={app.id} type="button" variant="ghost" size="icon" aria-label={app.title} onClick={() => onLaunch(app)} className="h-auto w-auto hover:bg-transparent size-[60px] p-0">
- <AppIcon app={app} />
- </Button>
- ))}
- </div>
- )}
+ <IosHomeChrome dockApps={dockApps} onLaunch={onLaunch} onSearch={onSearch} />
{indicator}
{ctxApp && (
- <AppActionSheet
- app={ctxApp}
- onOpen={() => { setCtxApp(null); onLaunch(ctxApp); }}
+ <IosQuickActions
+ app={ctxApp.app}
+ point={ctxApp}
+ onOpen={() => onLaunch(ctxApp.app)}
+ onRemove={() => setHidden((ids) => ids.includes(ctxApp.app.id) ? ids : [...ids, ctxApp.app.id])}
+ onLock={lock}
+ onEditHome={() => pagerRef.current?.scrollTo({ left: 0, behavior: "smooth" })}
+ onSearch={onSearch}
onClose={() => setCtxApp(null)}
/>
)}
diff --git a/frontend/slices/appshell/components/mobile-shell.tsx b/frontend/slices/appshell/components/mobile-shell.tsx
index a9230368..476234c3 100644
--- a/frontend/slices/appshell/components/mobile-shell.tsx
+++ b/frontend/slices/appshell/components/mobile-shell.tsx
@@ -13,6 +13,7 @@ import { MobileHome } from "./mobile-home";
import { MobileNotifications } from "./mobile-notifications";
import { Slot } from "../registry/feature-registry";
import { ShellUIProvider, type ShellUI } from "../registry/shell-ui";
+import { useLocked } from "../lib/lock";
import { useMobileNavigationInfo } from "../lib/mobile-navigation";
import { IosFeatureHeader } from "./shells/ios/ios-feature-header";
@@ -27,6 +28,7 @@ export function MobileShell() {
const [nc, setNc] = useState(false); // notification center (pull down, left half)
const [appScrolled, setAppScrolled] = useState(false); // iOS nav-bar frost-on-scroll
const [closing, setClosing] = useState(false); // playing the dismiss-to-home slide
+ const locked = useLocked();
// Dock = manifest-pinned apps (AppDescriptor.pinned — the generic shell never
// hardcodes project app ids); falls back to the first 4 dockable apps.
@@ -153,7 +155,7 @@ export function MobileShell() {
{/* --sai-top (notch/Dynamic-Island floor) now comes from the shared
[data-shell="ios"] rule in globals.css — one source of truth for both
touch shells, inherited by every iOS surface (home, nav, spotlight). */}
- <div className="absolute inset-0 z-[10] flex flex-col">
+ <div className={cn("absolute inset-0 z-[10] flex flex-col", locked && "invisible")} inert={locked || undefined}>
<div
data-slot="system-status-host"
data-status-placement="ios-status-bar"
diff --git a/frontend/slices/appshell/components/shells/context-menu-parts.test.ts b/frontend/slices/appshell/components/shells/context-menu-parts.test.ts
index 59fdc914..c1be9b3c 100644
--- a/frontend/slices/appshell/components/shells/context-menu-parts.test.ts
+++ b/frontend/slices/appshell/components/shells/context-menu-parts.test.ts
@@ -9,11 +9,15 @@ import { SUBMENU_ID, menuMetrics } from "./context-menu-parts";
const src = readFileSync(resolve(__dirname, "context-menu-parts.tsx"), "utf8");
describe("menuMetrics", () => {
- it("reserves 44px rows on touch shells and 34/30px on desktop personas", () => {
+ it("reserves 44px rows on touch shells and 34/24px on desktop personas", () => {
expect(menuMetrics("ios").rowH).toBe(44);
expect(menuMetrics("android").rowH).toBe(44);
expect(menuMetrics("windows").rowH).toBe(34);
- expect(menuMetrics("macos").rowH).toBe(30);
+ expect(menuMetrics("macos").rowH).toBe(24);
+ expect(menuMetrics("dashboard").rowH).toBe(30);
+ expect(menuMetrics("macos").width).toBe(244);
+ expect(menuMetrics("windows").chrome).toBe("");
+ expect(menuMetrics("ios").chrome).toBe("");
});
it("switches submenus to tap-to-open on touch shells only (fine pointer here)", () => {
diff --git a/frontend/slices/appshell/components/shells/context-menu-parts.tsx b/frontend/slices/appshell/components/shells/context-menu-parts.tsx
index f9a23ad2..78a268a7 100644
--- a/frontend/slices/appshell/components/shells/context-menu-parts.tsx
+++ b/frontend/slices/appshell/components/shells/context-menu-parts.tsx
@@ -26,15 +26,19 @@ export const SUBMENU_ID = "shell-context-submenu";
* shell, so a persona-only rowH under-reserves height and the menu clips. */
export function menuMetrics(shell: string) {
const isWin = shell === "windows";
+ const isMac = shell === "macos";
const isTouch = shell === "ios" || shell === "android";
const coarse = typeof matchMedia !== "undefined" && matchMedia("(pointer: coarse)").matches;
return {
isWin,
+ isMac,
+ width: isMac ? 244 : 220,
+ chrome: isMac ? "macos-menu" : "",
isTouch,
/** No hover on a coarse pointer → submenus open on TAP instead. */
tap: isTouch || coarse,
- rowH: isTouch || coarse ? 44 : isWin ? 34 : 30,
- item: isWin ? "h-[34px] rounded-[4px]" : isTouch ? "min-h-11 rounded-lg py-2.5 text-[15px]" : "rounded-md py-1",
+ rowH: isTouch || coarse ? 44 : isWin ? 34 : isMac ? 24 : 30,
+ item: isWin ? "h-[34px] rounded-[4px]" : isTouch ? "min-h-11 rounded-lg py-2.5 text-[15px]" : isMac ? "h-6 rounded-lg py-0" : "rounded-md py-1",
motion: isWin ? "fade-in-0 slide-in-from-top-2 duration-150" : "fade-in zoom-in-95 duration-100",
radius: isWin ? "rounded-lg" : isTouch ? "rounded-2xl" : "rounded-xl",
iconSize: isTouch ? "size-[18px]" : "size-4",
@@ -92,7 +96,7 @@ export function SubPanel({ item, m, onClose, pos, panelRef, onEnter, onLeave }:
aria-label={item.label}
onMouseEnter={onEnter}
onMouseLeave={onLeave}
- className={cn(PANEL, "z-[1202]", m.radius, m.motion)}
+ className={cn(PANEL, "z-[1202]", m.radius, m.chrome, m.motion)}
style={{ left: pos.x, top: pos.y }}
>
<MenuRows items={item.items} m={m} onClose={onClose} />
@@ -144,7 +148,7 @@ export function MenuRows({ items, m, onClose, sub }: { items: MenuItem[]; m: Men
{/* Selection is a GLYPH, never colour alone (a11y). */}
{it.checked && <Check className="size-4 shrink-0" />}
{/* macOS-style right-aligned keyboard hint (display only). */}
- {it.shortcut && <span className="shrink-0 pl-4 text-xs tabular-nums opacity-50 group-hover:opacity-80">{it.shortcut}</span>}
+ {it.shortcut && <span className={cn("shrink-0 pl-4 text-xs tabular-nums", !m.isMac && "opacity-50 group-hover:opacity-80")}>{it.shortcut}</span>}
</>
}
/>
diff --git a/frontend/slices/appshell/components/shells/context-menu.tsx b/frontend/slices/appshell/components/shells/context-menu.tsx
index 68f08344..452971c1 100644
--- a/frontend/slices/appshell/components/shells/context-menu.tsx
+++ b/frontend/slices/appshell/components/shells/context-menu.tsx
@@ -183,11 +183,11 @@ export function ContextMenu({ pos, items, onClose }: { pos: Pos; items: MenuItem
// Clamp on all four edges (Math.max lower-bounds so a click near the bottom/right
// of a small viewport can't push the menu offscreen). Per-row height is variant-
// aware so the bottom clamp reserves enough for the taller touch rows.
- const x = Math.max(8, Math.min(pos.x, window.innerWidth - 220));
+ const x = Math.max(8, Math.min(pos.x, window.innerWidth - m.width - 8));
const y = Math.max(8, Math.min(pos.y, window.innerHeight - items.length * m.rowH - 12));
const open = sub && items[sub.i]?.type === "submenu" ? (items[sub.i] as Extract<MenuItem, { type: "submenu" }>) : null;
const sp = sub && open
- ? submenuPos(sub.row, subSize ?? { w: 220, h: open.items.length * m.rowH + 8 }, { w: window.innerWidth, h: window.innerHeight })
+ ? submenuPos(sub.row, subSize ?? { w: m.width, h: open.items.length * m.rowH + 8 }, { w: window.innerWidth, h: window.innerHeight })
: null;
return createPortal(
@@ -200,7 +200,7 @@ export function ContextMenu({ pos, items, onClose }: { pos: Pos; items: MenuItem
ref={menuRef}
role="menu"
onMouseLeave={leaveSub}
- className={cn(PANEL, "z-[1201]", m.radius, m.motion)}
+ className={cn(PANEL, "z-[1201]", m.radius, m.chrome, m.motion)}
style={{ left: x, top: y }}
>
<MenuRows items={items} m={m} onClose={onClose} sub={{ open: sub?.i ?? null, onOpen: openSub, onLeave: leaveSub }} />
diff --git a/frontend/slices/appshell/components/shells/ios/ios-feature-header.tsx b/frontend/slices/appshell/components/shells/ios/ios-feature-header.tsx
index b4cac6ec..46e8effb 100644
--- a/frontend/slices/appshell/components/shells/ios/ios-feature-header.tsx
+++ b/frontend/slices/appshell/components/shells/ios/ios-feature-header.tsx
@@ -10,12 +10,15 @@ export function IosFeatureHeader({
onBack,
onAI,
scrolled,
+ safeTop = true,
}: {
title: string;
backLabel: string;
onBack: () => void;
onAI: () => void;
scrolled: boolean;
+ /** Skip the notch pad when a parent already cleared the status area (iPad tab bar). */
+ safeTop?: boolean;
}) {
return (
<header
@@ -24,7 +27,7 @@ export function IosFeatureHeader({
"shrink-0 border-b transition-[background-color,border-color] duration-200",
scrolled ? "glass border-border bg-[var(--glass-bar)]" : "border-transparent bg-transparent",
)}
- style={{ paddingTop: "var(--sai-top)" }}
+ style={safeTop ? { paddingTop: "var(--sai-top)" } : undefined}
>
<div className="relative flex h-[46px] items-center px-1.5">
<Button
@@ -32,12 +35,12 @@ export function IosFeatureHeader({
variant="ghost"
onClick={onBack}
aria-label={`Back to ${backLabel}`}
- className="absolute left-1 top-1/2 h-[44px] max-w-[34%] -translate-y-1/2 gap-0 overflow-hidden px-1 text-[17px] font-normal text-info hover:bg-transparent hover:text-info"
+ className="absolute left-1 top-1/2 h-[44px] max-w-[34%] -translate-y-1/2 gap-0 overflow-hidden px-1 text-[17px] font-normal leading-[22px] tracking-[-0.43px] text-info hover:bg-transparent hover:text-info"
>
<ChevronLeft className="size-[25px] shrink-0" aria-hidden />
<span className="truncate">{backLabel}</span>
</Button>
- <span className="mx-auto max-w-[44%] truncate text-[17px] font-semibold tracking-[-0.01em] text-foreground">{title}</span>
+ <span className="mx-auto max-w-[44%] truncate text-[17px] font-semibold leading-[22px] tracking-[-0.43px] text-foreground">{title}</span>
<Button
type="button"
variant="ghost"
diff --git a/frontend/slices/appshell/components/shells/ios/ios-home-chrome.test.tsx b/frontend/slices/appshell/components/shells/ios/ios-home-chrome.test.tsx
new file mode 100644
index 00000000..45dd8fee
--- /dev/null
+++ b/frontend/slices/appshell/components/shells/ios/ios-home-chrome.test.tsx
@@ -0,0 +1,83 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { FolderOpen } from "lucide-react";
+import { describe, expect, it } from "vitest";
+import type { AppDescriptor } from "../../../lib/types";
+import { IosHomeChrome } from "./ios-home-chrome";
+import { IosQuickActions } from "./ios-quick-actions";
+import { IOS_WIDGET_HOMES, IosWidgetHome } from "./ios-widget-home";
+
+function app(id: string, title: string): AppDescriptor {
+ return {
+ id,
+ title,
+ icon: FolderOpen,
+ gradient: "linear-gradient(#333,#111)",
+ load: async () => ({ default: () => null }),
+ } as AppDescriptor;
+}
+
+describe("iOS 27 home chrome", () => {
+ it("keeps Search in its own pill and the dock as icons without labels", () => {
+ const html = renderToStaticMarkup(
+ <IosHomeChrome dockApps={[app("files", "Files"), app("terminal", "Terminal")]} onLaunch={() => {}} onSearch={() => {}} />,
+ );
+ expect(html).toContain('data-slot="ios-search-pill"');
+ expect(html).toContain("text-[17px]");
+ expect(html).toContain("h-11");
+ expect(html).toContain(">Search<");
+ expect(html).toContain('data-slot="ios-dock"');
+ expect(html).toContain('aria-label="Files"');
+ expect(html).not.toContain(">Files<");
+ expect(html).not.toContain(">Terminal<");
+ expect(html).not.toContain("ios-tab-label");
+ });
+
+ it("opens a floating quick-actions menu with the home-screen rows", () => {
+ const html = renderToStaticMarkup(
+ <IosQuickActions
+ app={app("files", "Files")}
+ point={{ x: 40, y: 80 }}
+ onOpen={() => {}}
+ onRemove={() => {}}
+ onLock={() => {}}
+ onEditHome={() => {}}
+ onSearch={() => {}}
+ onClose={() => {}}
+ />,
+ );
+ expect(html).toContain('data-slot="ios-quick-actions"');
+ expect(html).toContain("text-[17px]");
+ expect(html).toContain("min-h-11");
+ expect(html).toContain("Hide from Home");
+ expect(html).toContain("text-destructive");
+ expect(html).toContain("Lock screen");
+ expect(html).not.toContain("Require Face ID");
+ expect(html).not.toContain("Remove App");
+ expect(html).toContain("Edit Home Screen");
+ expect(html).not.toContain("justify-end");
+ });
+
+ it("gives each widget size its own home with one placeholder and icons around it", () => {
+ const cells = { small: 4, medium: 8, large: 9, "extra-large": 12 };
+ for (const widget of IOS_WIDGET_HOMES) {
+ expect(widget.slots + cells[widget.size]).toBe(24);
+ const html = renderToStaticMarkup(
+ <IosWidgetHome
+ apps={[app("files", "Files"), app("terminal", "Terminal")]}
+ size={widget.size}
+ title={widget.title}
+ span={widget.span}
+ slots={widget.slots}
+ onLaunch={() => {}}
+ onContext={() => {}}
+ />,
+ );
+ expect(html.match(/data-slot="ios-widget-placeholder"/g)).toHaveLength(1);
+ expect(html).toContain("text-[12px]");
+ expect(html).toContain("text-[17px]");
+ expect(html).toContain(`data-size="${widget.size}"`);
+ expect(html).toContain(widget.span);
+ expect(html).toContain('aria-label="Files"');
+ }
+ });
+});
diff --git a/frontend/slices/appshell/components/shells/ios/ios-home-chrome.tsx b/frontend/slices/appshell/components/shells/ios/ios-home-chrome.tsx
new file mode 100644
index 00000000..47f5ec2e
--- /dev/null
+++ b/frontend/slices/appshell/components/shells/ios/ios-home-chrome.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { Search } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import type { AppDescriptor } from "../../../lib/types";
+import { AppIcon } from "../../app-icon";
+
+const GLASS = "glass border border-white/25 bg-[var(--glass-bar)] shadow-[0_10px_28px_rgba(0,0,0,0.22)]";
+
+/** Home-screen chrome from the iOS 27 Home Screen frame: a search pill, then a
+ * separate icon-only dock. Labels stay on the grid, not under the dock icons. */
+export function IosHomeChrome({
+ dockApps,
+ onLaunch,
+ onSearch,
+}: {
+ dockApps: AppDescriptor[];
+ onLaunch: (app: AppDescriptor) => void;
+ onSearch: () => void;
+}) {
+ return (
+ <div data-slot="ios-home-chrome" className="flex flex-col items-center gap-2 px-4 pb-1">
+ <Button
+ type="button"
+ variant="ghost"
+ data-slot="ios-search-pill"
+ onClick={onSearch}
+ className={`${GLASS} h-11 gap-2 rounded-full px-4 text-[17px] font-normal leading-[22px] tracking-[-0.43px] text-white/80 hover:bg-white/10 hover:text-white [&_svg]:size-[17px]`}
+ >
+ <Search aria-hidden />
+ Search
+ </Button>
+ {dockApps.length > 0 && (
+ <div data-slot="ios-dock" className={`${GLASS} flex w-max max-w-full flex-nowrap items-center gap-3.5 rounded-[32px] px-2.5 py-2`}>
+ {dockApps.map((app) => (
+ <Button
+ key={app.id}
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={app.title}
+ onClick={() => onLaunch(app)}
+ className="size-[54px] shrink-0 p-0 hover:bg-transparent"
+ >
+ <AppIcon app={app} />
+ </Button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/slices/appshell/components/shells/ios/ios-quick-actions.tsx b/frontend/slices/appshell/components/shells/ios/ios-quick-actions.tsx
new file mode 100644
index 00000000..ca94c59f
--- /dev/null
+++ b/frontend/slices/appshell/components/shells/ios/ios-quick-actions.tsx
@@ -0,0 +1,97 @@
+"use client";
+
+import { AppWindow, LayoutGrid, Lock, MinusCircle, Search, type LucideIcon } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import type { AppDescriptor } from "../../../lib/types";
+
+type Point = { x: number; y: number };
+
+/** Home-icon quick actions. A floating menu, not a bottom sheet: Hide from Home,
+ * Lock screen, Edit Home Screen, then the app's own actions, and a footer
+ * of the same real shortcuts. */
+export function IosQuickActions({
+ app,
+ point,
+ onOpen,
+ onRemove,
+ onLock,
+ onEditHome,
+ onSearch,
+ onClose,
+}: {
+ app: AppDescriptor;
+ point: Point;
+ onOpen: () => void;
+ onRemove: () => void;
+ onLock: () => void;
+ onEditHome: () => void;
+ onSearch: () => void;
+ onClose: () => void;
+}) {
+ const extras = (app.menus ?? []).flatMap((m) => m.items).filter(
+ (it): it is Extract<typeof it, { label: string }> => !("sep" in it),
+ ).slice(0, 4);
+ const left = typeof window === "undefined" ? point.x : Math.min(Math.max(12, point.x - 28), window.innerWidth - 272);
+ const top = typeof window === "undefined" ? point.y : Math.min(Math.max(12, point.y + 8), window.innerHeight - 360);
+
+ return (
+ <div className="absolute inset-0 z-[45]" onClick={onClose}>
+ <div
+ data-slot="ios-quick-actions"
+ role="menu"
+ className="glass absolute w-[250px] overflow-hidden rounded-[22px] border border-white/30 bg-[var(--glass-menu)] text-[var(--text)] shadow-2xl"
+ style={{ left, top }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Row icon={MinusCircle} label="Hide from Home" destructive onClick={() => { onClose(); onRemove(); }} />
+ <Row icon={Lock} label="Lock screen" onClick={() => { onClose(); onLock(); }} />
+ <Row icon={LayoutGrid} label="Edit Home Screen" onClick={() => { onClose(); onEditHome(); }} />
+ {extras.map((it, i) => (
+ <Row key={i} label={it.label} disabled={it.disabled} onClick={() => { onClose(); it.onSelect?.(); }} />
+ ))}
+ <div className="grid grid-cols-4 border-t border-border">
+ <Footer icon={AppWindow} label={`Open ${app.title}`} onClick={() => { onClose(); onOpen(); }} />
+ <Footer icon={Search} label="Search" onClick={() => { onClose(); onSearch(); }} />
+ <Footer icon={Lock} label="Lock" onClick={() => { onClose(); onLock(); }} />
+ <Footer icon={LayoutGrid} label="Edit Home Screen" onClick={() => { onClose(); onEditHome(); }} />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function Row({
+ icon: Icon,
+ label,
+ destructive = false,
+ disabled = false,
+ onClick,
+}: {
+ icon?: LucideIcon;
+ label: string;
+ destructive?: boolean;
+ disabled?: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ role="menuitem"
+ disabled={disabled}
+ onClick={onClick}
+ className={`h-auto min-h-11 w-full justify-start gap-3 rounded-none border-t border-border px-4 py-2.5 text-left text-[17px] font-normal leading-[22px] tracking-[-0.43px] first:border-t-0 hover:bg-foreground/5 [&_svg]:size-[17px] ${destructive ? "text-destructive hover:text-destructive" : ""}`}
+ >
+ {Icon && <Icon className="shrink-0" aria-hidden />}
+ <span className="truncate">{label}</span>
+ </Button>
+ );
+}
+
+function Footer({ icon: Icon, label, onClick }: { icon: LucideIcon; label: string; onClick: () => void }) {
+ return (
+ <Button type="button" variant="ghost" aria-label={label} onClick={onClick} className="h-11 min-h-11 rounded-none p-0 hover:bg-foreground/5 [&_svg]:size-[17px]">
+ <Icon aria-hidden />
+ </Button>
+ );
+}
diff --git a/frontend/slices/appshell/components/shells/ios/ios-widget-home.tsx b/frontend/slices/appshell/components/shells/ios/ios-widget-home.tsx
new file mode 100644
index 00000000..17ede73d
--- /dev/null
+++ b/frontend/slices/appshell/components/shells/ios/ios-widget-home.tsx
@@ -0,0 +1,64 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import type { AppDescriptor } from "../../../lib/types";
+import { AppIcon } from "../../app-icon";
+
+/** One home screen per kit size. The purple widget occupies a block of the
+ * 4×6 icon grid; the shell's own apps fill the cells around it. */
+export const IOS_WIDGET_HOMES = [
+ { size: "small", title: "CPU", span: "col-span-2 row-span-2", slots: 20 },
+ { size: "medium", title: "Memory", span: "col-span-4 row-span-2", slots: 16 },
+ { size: "large", title: "Storage", span: "col-span-3 row-span-3", slots: 15 },
+ { size: "extra-large", title: "Clock", span: "col-span-4 row-span-3", slots: 12 },
+] as const;
+
+export type IosWidgetSize = (typeof IOS_WIDGET_HOMES)[number]["size"];
+
+export function IosWidgetHome({
+ apps,
+ size,
+ title,
+ span,
+ slots,
+ onLaunch,
+ onContext,
+}: {
+ apps: AppDescriptor[];
+ size: IosWidgetSize;
+ title: string;
+ span: string;
+ slots: number;
+ onLaunch: (app: AppDescriptor) => void;
+ onContext: (app: AppDescriptor, point: { x: number; y: number }) => void;
+}) {
+ return (
+ <div className="grid h-full content-start grid-cols-4 grid-rows-[repeat(6,minmax(0,80px))] gap-x-[26px] gap-y-2 overflow-hidden px-6 pb-6 pt-[18px]">
+ <div
+ data-slot="ios-widget-placeholder"
+ data-size={size}
+ className={`flex min-h-0 items-end rounded-[22px] p-4 text-[17px] font-semibold leading-[22px] tracking-[-0.43px] text-white ${span}`}
+ >
+ {title}
+ </div>
+ {apps.slice(0, slots).map((app) => (
+ <Button
+ key={app.id}
+ type="button"
+ variant="ghost"
+ aria-label={app.title}
+ onClick={() => onLaunch(app)}
+ onContextMenu={(e) => { e.preventDefault(); onContext(app, { x: e.clientX, y: e.clientY }); }}
+ className="h-auto min-h-0 p-0 hover:bg-transparent flex flex-col items-center gap-1"
+ >
+ <span className="size-[60px] max-h-full shrink-0">
+ <AppIcon app={app} />
+ </span>
+ <span className="max-w-full shrink-0 truncate text-[12px] font-normal leading-4 text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]">
+ {app.title}
+ </span>
+ </Button>
+ ))}
+ </div>
+ );
+}
diff --git a/frontend/slices/appshell/components/shells/macos/macos-shell.css b/frontend/slices/appshell/components/shells/macos/macos-shell.css
new file mode 100644
index 00000000..0cc2b28f
--- /dev/null
+++ b/frontend/slices/appshell/components/shells/macos/macos-shell.css
@@ -0,0 +1,93 @@
+/* macOS 27 chrome: Figma Examples 4440:8154/8155 and 4440:8164/8165.
+ Tokens stay local to chrome so app content and other shells keep their palette. */
+[data-shell="macos"][data-shell] {
+ --mac-window: #fff;
+ --mac-title: #222;
+ --mac-divider: rgba(0, 0, 0, .06);
+ --mac-inactive-light: #d4d4d4;
+ --mac-window-shadow: 0 0 1px rgba(0, 0, 0, .8), 0 18px 54px rgba(0, 0, 0, .3);
+ --mac-inactive-shadow: 0 0 1px rgba(0, 0, 0, .8), 0 7px 21px rgba(0, 0, 0, .2);
+ --mac-close: #ff5c60;
+ --mac-minimize: #fac800;
+ --mac-maximize: #35c759;
+ --shell-radius-win: 16px;
+}
+[data-theme="dark"] [data-shell="macos"] {
+ --mac-window: #1e1e1e;
+ --mac-title: #f2f2f2;
+ --mac-divider: rgba(255, 255, 255, .1);
+ --mac-inactive-light: #424242;
+ --mac-window-shadow: 0 0 1px rgba(0, 0, 0, .8), 0 18px 54px rgba(0, 0, 0, .55);
+ --mac-inactive-shadow: 0 0 1px rgba(0, 0, 0, .8), 0 7px 21px rgba(0, 0, 0, .35);
+}
+.macos-menubar {
+ color: #fff;
+ /* Keep white status text legible even over a user-supplied white wallpaper. */
+ background: rgba(24, 24, 28, .62);
+ backdrop-filter: blur(var(--blur));
+}
+.macos-status { --foreground: #fff; --muted-foreground: #eee; --info: #fff; }
+.macos-menu-trigger:hover,
+.macos-menubar .macos-status button:hover,
+.macos-menu-trigger[data-state="open"] { background: #555557; }
+.macos-menubar button:focus-visible {
+ outline: 2px solid #fff;
+ outline-offset: -2px;
+}
+.macos-menu:focus-visible { border-radius: 12px; }
+.macos-menu {
+ border-radius: 12px;
+ width: 244px;
+ max-width: calc(100vw - 16px);
+ padding: 5px;
+ color: #1a1a1a;
+ background: rgba(255, 255, 255, .75);
+ box-shadow: 0 8px 48px rgba(0, 0, 0, .25);
+ font-family: system-ui;
+}
+.macos-menu [role^="menuitem"] {
+ padding: 3px 7px;
+ border-radius: 8px;
+ line-height: 18px;
+}
+.macos-menu [role^="menuitem"]:is(:focus, :hover):not(:disabled, [data-disabled]) {
+ color: #fff;
+ background: #0062e6;
+}
+.macos-menu [role^="menuitem"] > span:last-child { opacity: 1; }
+[data-theme="dark"] .macos-menu {
+ color: #f5f5f5;
+ background: rgba(44, 44, 48, .88);
+ box-shadow: 0 8px 48px rgba(0, 0, 0, .45);
+}
+[data-shell="macos"] [data-window-chrome="macos"] {
+ background: var(--mac-window);
+ border-color: var(--mac-divider);
+ box-shadow: var(--mac-window-shadow);
+}
+[data-shell="macos"] [data-window-chrome="macos"][data-focused="false"] {
+ box-shadow: var(--mac-inactive-shadow);
+}
+.macos-titlebar {
+ background: var(--mac-window);
+ border-bottom: .5px solid var(--mac-divider);
+ color: var(--mac-title);
+}
+.macos-light {
+ background: var(--mac-light);
+ box-shadow: inset 0 0 0 .5px rgba(0, 0, 0, .35);
+}
+[data-focused="false"] .macos-light { background: var(--mac-inactive-light); }
+.macos-light-button:hover .macos-light,
+.macos-light-button:focus-visible .macos-light { background: var(--mac-light); }
+.macos-light-button:focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: 1px;
+}
+.reduce-glass .macos-menubar { background: #333337; backdrop-filter: none; }
+.reduce-glass .macos-menu { background: #f5f5f5; backdrop-filter: none; }
+.reduce-glass[data-theme="dark"] .macos-menu { background: #2a2a2d; }
+
+@media (max-height: 500px) {
+ .macos-titlebar { height: 32px; }
+}
diff --git a/frontend/slices/appshell/components/shells/macos/macos-shell.tsx b/frontend/slices/appshell/components/shells/macos/macos-shell.tsx
index 2d78ca89..d90fa832 100644
--- a/frontend/slices/appshell/components/shells/macos/macos-shell.tsx
+++ b/frontend/slices/appshell/components/shells/macos/macos-shell.tsx
@@ -1,5 +1,7 @@
"use client";
+import "./macos-shell.css";
+
// The macOS chrome — menu bar, desktop surface + window layer, dock, launcher,
// Mission Control. Split out of desktop.tsx so it can be React.lazy()'d in
// register-shells.tsx: it used to sit in the same module as Surface, which put
@@ -30,6 +32,7 @@ import { Slot } from "../../../registry/feature-registry";
import { useShellAppearance } from "../../../registry/capabilities";
import { ForceQuitDialog } from "../../../features/force-quit/force-quit";
import { DesktopIcons, useDesktopMarquee } from "../../../features/desktop-icons";
+import { TOPBAR } from "../../../lib/store-geometry";
import { cn } from "@/lib/utils";
export function DesktopChrome() {
@@ -59,7 +62,8 @@ export function DesktopChrome() {
<>
<MenuBar />
<section
- className={cn("absolute inset-x-0 bottom-0 top-[30px] z-[10]", interactive && "pointer-events-none [&>*]:pointer-events-auto")}
+ style={{ top: TOPBAR }}
+ className={cn("absolute inset-x-0 bottom-0 z-[10]", interactive && "pointer-events-none [&>*]:pointer-events-auto")}
// Open the desktop menu for any right-click NOT inside a window. Icons +
// widgets stopPropagation their own menus (never reach here); windows are
// excluded via [data-window]. The old `target===currentTarget` guard
diff --git a/frontend/slices/appshell/components/traffic-lights.tsx b/frontend/slices/appshell/components/traffic-lights.tsx
index 31a1cd0a..7fa7a382 100644
--- a/frontend/slices/appshell/components/traffic-lights.tsx
+++ b/frontend/slices/appshell/components/traffic-lights.tsx
@@ -2,40 +2,32 @@
import { Button } from "@/components/ui/button";
-// macOS window controls. Glyphs fade in on hover of the cluster (os-rr).
+// A 24px hit area surrounds each 14px macOS control.
export function TrafficLights({
- onClose,
- onMinimize,
- onMaximize,
+ onClose, onMinimize, onMaximize, focused = true,
}: {
onClose: () => void;
onMinimize: () => void;
onMaximize: () => void;
+ focused?: boolean;
}) {
return (
- <div className="group/lights flex gap-2">
- <Light color="#ff5f57" stroke="#7a0a00" label="Close window" onClick={onClose}>
- <path d="M1.6 1.6l4.8 4.8M6.4 1.6l-4.8 4.8" strokeWidth="1.2" strokeLinecap="round" />
+ <div className="group/lights flex shrink-0" data-focused={focused}>
+ <Light color="var(--mac-close)" label="Close window" onClick={onClose}>
+ <path d="M1.6 1.6l4.8 4.8M6.4 1.6l-4.8 4.8" />
</Light>
- <Light color="#febc2e" stroke="#7a4b00" label="Minimize window" onClick={onMinimize}>
- <path d="M1.4 4h5.2" strokeWidth="1.4" strokeLinecap="round" />
+ <Light color="var(--mac-minimize)" label="Minimize window" onClick={onMinimize}>
+ <path d="M1.4 4h5.2" />
</Light>
- <Light color="#28c840" stroke="#0a5200" label="Maximize window" onClick={onMaximize}>
- <path d="M2 6V2h4M6 2L2 6" strokeWidth="1.2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
+ <Light color="var(--mac-maximize)" label="Maximize window" onClick={onMaximize}>
+ <path d="M2 6V2h4M6 2L2 6" />
</Light>
</div>
);
}
-function Light({
- color,
- stroke,
- label,
- onClick,
- children,
-}: {
+function Light({ color, label, onClick, children }: {
color: string;
- stroke: string;
label: string;
onClick: () => void;
children: React.ReactNode;
@@ -46,21 +38,16 @@ function Light({
variant="ghost"
size="icon"
aria-label={label}
- onClick={(e) => {
- e.stopPropagation();
- onClick();
- }}
+ onClick={(e) => { e.stopPropagation(); onClick(); }}
onPointerDown={(e) => e.stopPropagation()}
- className="h-auto w-auto hover:bg-transparent grid size-3 place-items-center rounded-full shadow-[inset_0_0_0_0.5px_rgba(0,0,0,0.18)]"
- style={{ background: color }}
+ className="macos-light-button grid size-6 rounded-full p-0 hover:bg-transparent"
+ style={{ "--mac-light": color } as React.CSSProperties}
>
- <svg
- viewBox="0 0 8 8"
- className="size-2 opacity-0 group-hover/lights:opacity-60"
- stroke={stroke}
- >
- {children}
- </svg>
+ <span className="macos-light grid size-[14px] place-items-center rounded-full" aria-hidden>
+ <svg viewBox="0 0 8 8" className="size-2 text-black opacity-0 group-hover/lights:opacity-70 group-focus-within/lights:opacity-70" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round">
+ {children}
+ </svg>
+ </span>
</Button>
);
}
diff --git a/frontend/slices/appshell/components/window.tsx b/frontend/slices/appshell/components/window.tsx
index 3a5c7c89..0c60c5e3 100644
--- a/frontend/slices/appshell/components/window.tsx
+++ b/frontend/slices/appshell/components/window.tsx
@@ -84,6 +84,8 @@ export const Window = memo(function Window({ id, variant = "macos" }: { id: WinI
<div
ref={ref}
data-window
+ data-window-chrome={variant}
+ data-focused={focused}
data-app={win.app}
className={cn(
"win-geo absolute flex flex-col overflow-hidden border border-border bg-card shadow-[var(--shadow-win)]",
@@ -97,7 +99,7 @@ export const Window = memo(function Window({ id, variant = "macos" }: { id: WinI
onAnimationEnd={(e) => {
// Finalize the deferred store action once the exit animation ends.
if (e.animationName === "winClose") closeWindow(id);
- else if (e.animationName === "winMin") minimizeWindow(id);
+ else if (e.animationName === "winMin") { setPhase("in"); minimizeWindow(id); }
}}
>
{isWin ? (
@@ -125,21 +127,20 @@ export const Window = memo(function Window({ id, variant = "macos" }: { id: WinI
</div>
) : (
<div
- className="glass flex h-[38px] shrink-0 cursor-grab items-center gap-2 border-b border-border px-3 font-[family-name:var(--shell-font)] active:cursor-grabbing"
- style={{ background: "var(--window-head)" }}
+ className="macos-titlebar flex h-[52px] shrink-0 cursor-grab items-center gap-3 pl-3 pr-[18px] font-[family-name:var(--shell-font)] active:cursor-grabbing"
onPointerDown={onBarDown}
onDoubleClick={() => toggleMaximize(id)}
onContextMenu={ctx.open}
>
<TrafficLights
+ focused={focused}
onClose={beginClose}
onMinimize={beginMinimize}
onMaximize={() => toggleMaximize(id)}
/>
- <div className="pointer-events-none flex-1 truncate text-center text-[13px] font-semibold text-muted-foreground">
+ <div className="macos-window-title pointer-events-none flex-1 truncate text-[13px] font-semibold">
{title}
</div>
- <div className="min-w-[54px]" />
</div>
)}
diff --git a/frontend/slices/appshell/design/ios/design.md b/frontend/slices/appshell/design/ios/design.md
index 543a1ce4..7680deb9 100644
--- a/frontend/slices/appshell/design/ios/design.md
+++ b/frontend/slices/appshell/design/ios/design.md
@@ -5,10 +5,14 @@ Source of truth: the project Apple-platform design reference (Apple HIG/Liquid G
## Contract
- Clarity, deference, depth. Content is solid; glass belongs to navigation/overlays, never content cards.
- 16–20pt side margins, 4/8pt rhythm, continuous/concentric corners.
-- SF-style system typography; body 17pt, navigation title 17pt semibold. Large titles are allowed inside feature content only when they do not duplicate the shell-owned centered root title.
+- SF-style system typography at the Large Dynamic Type size. Body and menu rows are 17/22 Regular (tracking −0.43). Navigation titles are Headline 17/22 Semibold. Home icon labels are Caption 1, 12/16 Regular. Screen titles such as Today are Title 1 emphasized, 28/34 Bold. The lock date is a short Footnote line (13/18 Regular) tight above the time. The lock time is 92pt Semibold (SF Pro tracking 0 at 92pt; Semibold is the Headline and emphasized Title 3 weight) in cream at about 78% opacity. Controls are at least 44×44pt and sit on a 16pt side margin.
- Root feature header: **`< Home`** left, feature title centered, AI icon right; 44pt minimum targets.
- Drill-down uses the same single header: parent on the left, detail title centered, AI right. Never render a second navigation header inside content.
- Settings: the MSO root contract keeps `Settings` in the centered shell bar, so the content begins with Search (no second large “Settings”). Use grouped inset cards, ~16–18pt radius, 50–52pt rows, inset separators, muted section labels, system-green switches.
- Forms/actions that interrupt flow use a bottom drawer/sheet. Keep destructive actions red and separated.
- Navigation/overlay materials may use glass; content cards remain solid.
+- Home screen: page dots, then a small glass search pill (magnifying glass and the word Search), then a separate glass dock of app icons with no labels. Grid icons keep their labels. Each widget size is its own home screen: one purple placeholder (small, medium, large, or extra large) with app icons in the remaining cells. The lock screen sits on the shell wallpaper: a safe-area status bar (left empty when the installed PWA draws the system status bar), a short date, one 92pt Semibold cream time, then weather, activity rings, and a round clock, with a circular screen-light button and a keyboard-focusable 44pt unlock indicator. Clock, date, and timezone are the browser Date and Intl. Weather remains unavailable. This shell does not request geolocation or contact external weather providers; any future provider integration needs a separately reviewed explicit opt-in. Control Center is one packed glass mosaic. A home-icon long-press is a floating menu: Hide from Home, Lock screen, Edit Home Screen, then that app's own actions.
- Respect safe areas, Reduce Motion, Reduce Transparency and high contrast.
+
+## Current acceptance boundary
+The candidate preserves the existing iOS layout direction. Fidelity to the supplied Figma URL is unverified: its selected node is a keyboard sheet and full design context was unavailable. ENERGY 1 / RHYTHM 1 / MOTION 1: restrained utility chrome, consistent navigation, and only state transitions. The unavailable-weather state avoids fabricated readings; action labels describe the implemented privacy lock and local home visibility rather than biometrics or uninstalling apps. Non-iOS lock curtains retain their original layout and behavior.
diff --git a/frontend/slices/appshell/design/macos/design.md b/frontend/slices/appshell/design/macos/design.md
index 7df5be2d..4ef884c7 100644
--- a/frontend/slices/appshell/design/macos/design.md
+++ b/frontend/slices/appshell/design/macos/design.md
@@ -1,13 +1,33 @@
# macOS design.md
-Source family: the project Apple-platform design reference, macOS sections.
-
-## Contract
-- Desktop-first, compact density, SF typography, translucent navigation/sidebar layers with solid content.
-- Windows use native title-bar semantics, traffic lights, subtle depth and ~10px window radius.
-- System Settings uses a searchable grouped sidebar, colored category icons and a persistent selected detail pane; narrow windows use a side sheet.
-- Finder uses compact navigation/view/action controls, inline folder search, blue folders, an icon-grid default and a compact status bar. Enter renames; Space previews.
-- Toolbars are compact and contextual. Avoid iOS large-title/grouped-page treatment in desktop windows.
-- Modal workflows use centered dialogs; long secondary workflows may use side panels/sheets.
-- Do not stack glass surfaces. Sidebars/toolbars can be glass; tables/cards/content stay solid.
-- Keep keyboard, pointer, focus, hover, resizable-window behavior first-class.
+Source: [macOS 27 Examples](https://www.figma.com/design/f3ivRnEohVvr87qszwuQiw/macOS-27--Community-?node-id=121-18094).
+
+## Component selection
+- Reference nodes: menus 4440:8154/8155, windows 4440:8164/8165, unified titlebar 4440:8159.
+- Candidate A 5cdad278 supplies 34px bar geometry, solid 52px titlebar, 16px windows, 14px traffic lights inside 24px targets, and focus-dependent shadows.
+- PR103 candidate B 5efbe7ea supplies the direction for semibold/heavy bar labels, focus-stable 12px menus, 24px fine-pointer context rows and translucent menu material.
+- Combined menus retain A's readable shortcut text and selection contrast. Coarse-pointer rows remain at least 44px; Windows and Dashboard metrics retain their existing values.
+- Existing Radix controls, shell store, app registry and docking interactions remain authoritative.
+- The Examples page has no dock specimen. Preserve existing artwork; reserve the full hover-growth pool so controls stay reachable.
+- macOS CSS loads with its lazy shell component. No global palette replacement or extra design dependency.
+- Do not import PR103's unrelated iOS/chat modifications or unconditional Force Quit styling.
+
+## Newer wallpaper direction
+Canonical commit 998632c8 refreshes the user-requested light/dark WebP defaults.
+Preserve that newer project behavior rather than masking it with A's Figma PNG override.
+The supplied Figma screenshots remain chrome references; wallpaper is an intentional difference.
+Custom/live and per-shell wallpaper preferences retain canonical precedence.
+
+## Accessibility and behavior
+ENERGY 1 / RHYTHM 1 / MOTION 1: compact system chrome for server operators.
+White bar text uses a dark scrim so custom backgrounds remain legible.
+Status labels and links inherit bar-specific text tokens, without recoloring app content.
+Window minimization clears its exit phase before restoration; dock clicks reuse existing windows.
+Viewports up to 500px tall use a compact 32px titlebar, preserving 24px controls and usable app content.
+App content retains its existing structure, data and permissions.
+
+## Verification
+Reproduce scoped desktop/light/dark/mobile/keyboard checks with scripts/e2e/macos-figma.mjs.
+Static declarations do not establish browser geometry: measure settled animation states and visible hit targets.
+Merge requires the exact candidate's required tests, build, budget, security gates and independent review.
+Known dependency audit failures must not be suppressed or treated as cosmetic.
diff --git a/frontend/slices/appshell/features/control-center/components/control-center-ios.tsx b/frontend/slices/appshell/features/control-center/components/control-center-ios.tsx
new file mode 100644
index 00000000..46a89a8a
--- /dev/null
+++ b/frontend/slices/appshell/features/control-center/components/control-center-ios.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { type LucideIcon, Bell, Moon, MoonStar, Sun, Server, Cloud, Sparkles, Layers, Search } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { useWindowOrder } from "../../../hooks/use-shell";
+import { closeAll, toggleInspector, toggleSpotlight } from "../../../lib/store";
+import { toggleFocusMode, useFocusMode } from "../../../lib/focus-mode";
+import { useShellAppearance, useServerToggle } from "../../../registry/capabilities";
+
+const WELL = "glass border border-white/15 bg-[var(--glass-bar)]";
+
+/** Packed glass mosaic: a 2×2 circle group, a tall card beside it, then two
+ * lower tiles. Only real MSO toggles. The macOS popover keeps the labeled list. */
+export function IosControlCenter({ onClose }: { onClose: () => void }) {
+ const { theme, setTheme } = useShellAppearance();
+ const server = useServerToggle();
+ const openCount = useWindowOrder().length;
+ const focus = useFocusMode();
+ const dark = theme === "dark";
+ const windowsLabel = openCount ? `Close all (${openCount})` : "None open";
+
+ return (
+ <div data-slot="ios-control-center" className="grid grid-cols-4 gap-2">
+ <div data-slot="ios-cc-cluster" className={cn(WELL, "col-span-2 row-span-2 grid grid-cols-2 place-items-center gap-2.5 rounded-[28px] p-3")}>
+ <Orb icon={dark ? Moon : Sun} label="Appearance" on={dark} onClick={() => setTheme(dark ? "light" : "dark")} />
+ <Orb icon={focus ? MoonStar : Bell} label="Focus" on={focus} onClick={toggleFocusMode} />
+ <Orb icon={Search} label="Search" onClick={() => { onClose(); toggleSpotlight(); }} />
+ {server ? (
+ <Orb icon={server.live ? Cloud : Server} label="Server" on={server.live} disabled={server.locked} onClick={server.toggle} />
+ ) : (
+ <Orb icon={Layers} label="Windows" disabled={openCount === 0} onClick={() => { closeAll(); onClose(); }} />
+ )}
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ data-slot="ios-cc-card"
+ onClick={() => { onClose(); toggleInspector(); }}
+ className={cn(WELL, "col-span-2 row-span-2 h-auto min-h-[168px] flex-col items-start justify-between rounded-[28px] p-4 text-left text-white hover:bg-white/25")}
+ >
+ <span className="grid size-11 place-items-center rounded-2xl bg-white/20">
+ <Sparkles className="size-5" aria-hidden />
+ </span>
+ <span>
+ <span className="block text-[17px] font-semibold leading-[22px] tracking-[-0.43px]">Alfa</span>
+ <span className="block text-[15px] font-normal leading-5 tracking-[-0.23px] text-white/70">Ask about this app</span>
+ </span>
+ </Button>
+ <Tile
+ icon={Layers}
+ label="Windows"
+ value={windowsLabel}
+ disabled={openCount === 0}
+ onClick={() => { closeAll(); onClose(); }}
+ />
+ <Tile
+ icon={server ? (server.live ? Cloud : Server) : Search}
+ label={server ? "Server" : "Search"}
+ value={server ? server.label : "Spotlight"}
+ disabled={server?.locked}
+ onClick={() => {
+ if (server) server.toggle();
+ else { onClose(); toggleSpotlight(); }
+ }}
+ />
+ </div>
+ );
+}
+
+function Orb({
+ icon: Icon, label, on = false, disabled = false, onClick,
+}: { icon: LucideIcon; label: string; on?: boolean; disabled?: boolean; onClick: () => void }) {
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ aria-label={label}
+ disabled={disabled}
+ onClick={onClick}
+ className={cn("size-[52px] rounded-full p-0", on ? "bg-primary text-primary-foreground hover:bg-primary" : "bg-white/25 text-white hover:bg-white/35")}
+ >
+ <Icon className="size-6" />
+ </Button>
+ );
+}
+
+function Tile({
+ icon: Icon, label, value, disabled = false, onClick,
+}: { icon: LucideIcon; label: string; value: string; disabled?: boolean; onClick: () => void }) {
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ disabled={disabled}
+ onClick={onClick}
+ className={cn(WELL, "col-span-2 h-[78px] flex-col items-start justify-between rounded-[22px] px-4 py-2 text-left text-white hover:bg-white/25 disabled:opacity-40")}
+ data-slot="ios-cc-tile"
+ >
+ <Icon className="size-5" aria-hidden />
+ <span>
+ <span className="block text-[13px] font-semibold leading-[18px] tracking-[-0.08px]">{label}</span>
+ <span className="block truncate text-[11px] font-normal leading-[13px] tracking-[0.06px] text-white/70">{value}</span>
+ </span>
+ </Button>
+ );
+}
diff --git a/frontend/slices/appshell/features/control-center/components/control-center.tsx b/frontend/slices/appshell/features/control-center/components/control-center.tsx
index eca5312e..c907ed35 100644
--- a/frontend/slices/appshell/features/control-center/components/control-center.tsx
+++ b/frontend/slices/appshell/features/control-center/components/control-center.tsx
@@ -5,6 +5,7 @@ import { cn } from "@/lib/utils";
import { useShellDesign } from "../../../design";
import { useShellUI } from "../../../registry/shell-ui";
import { ControlCenterTiles } from "./control-center-tiles";
+import { IosControlCenter } from "./control-center-ios";
// One quick-settings behavior model, shell-native presentation. iOS uses a glass
// pull-down; Android uses a solid/tonal Material sheet. No fake Wi-Fi/cellular
@@ -24,14 +25,14 @@ export function ControlCenter() {
className={cn(
"border-border p-4 pt-[max(2.25rem,var(--sai-top,0px))]",
apple
- ? "glass rounded-b-[28px] bg-[var(--glass-menu)]"
+ ? "rounded-b-[34px] border-white/10 bg-black/35 shadow-none backdrop-blur-2xl"
: "rounded-b-[28px] bg-card shadow-xl",
)}
>
<SheetTitle className="sr-only">Control Center</SheetTitle>
<SheetDescription className="sr-only">Quick system toggles</SheetDescription>
<div className="mx-auto w-full max-w-md">
- <ControlCenterTiles onClose={() => onOpenChange(false)} />
+ {apple ? <IosControlCenter onClose={() => onOpenChange(false)} /> : <ControlCenterTiles onClose={() => onOpenChange(false)} />}
</div>
</SheetContent>
</Sheet>
diff --git a/frontend/slices/appshell/features/lock-screen/components/ios-lock-complications.tsx b/frontend/slices/appshell/features/lock-screen/components/ios-lock-complications.tsx
new file mode 100644
index 00000000..873a0b24
--- /dev/null
+++ b/frontend/slices/appshell/features/lock-screen/components/ios-lock-complications.tsx
@@ -0,0 +1,75 @@
+"use client";
+
+import { useSystemStats } from "../../../registry/capabilities";
+import { lockZone } from "./ios-lock-format";
+import { type LockWeather } from "./ios-lock-weather";
+
+function Ring({ r, pct }: { r: number; pct: number }) {
+ const clamped = Math.max(0, Math.min(100, pct));
+ return (
+ <circle
+ cx="18" cy="18" r={r} fill="none" stroke="currentColor" strokeWidth="2.4"
+ strokeLinecap="round" pathLength={100} strokeDasharray={`${clamped} 100`}
+ transform="rotate(-90 18 18)"
+ />
+ );
+}
+
+function ActivityRings() {
+ const stats = useSystemStats();
+ const cpu = stats?.cpu.pct ?? 0;
+ const mem = stats && stats.mem.total > 0 ? (stats.mem.used / stats.mem.total) * 100 : 0;
+ const disk = stats && stats.disk.total > 0 ? (stats.disk.used / stats.disk.total) * 100 : 0;
+ const label = stats
+ ? `Activity, CPU ${Math.round(cpu)} percent, memory ${Math.round(mem)} percent, storage ${Math.round(disk)} percent`
+ : "Activity unavailable";
+ return (
+ <div data-slot="ios-lock-rings" data-state={stats ? "ready" : "unavailable"} className="grid size-[72px] shrink-0 place-items-center rounded-full glass bg-[var(--glass-bar)] text-white" aria-label={label}>
+ <svg viewBox="0 0 36 36" className="size-14" aria-hidden>
+ <g className="text-white/30">
+ <circle cx="18" cy="18" r="16" fill="none" stroke="currentColor" strokeWidth="2.4" />
+ <circle cx="18" cy="18" r="12" fill="none" stroke="currentColor" strokeWidth="2.4" />
+ <circle cx="18" cy="18" r="8" fill="none" stroke="currentColor" strokeWidth="2.4" />
+ </g>
+ <g className={stats ? "text-white" : "text-transparent"}>
+ <Ring r={16} pct={cpu} />
+ <g className="opacity-70"><Ring r={12} pct={mem} /></g>
+ <g className="opacity-45"><Ring r={8} pct={disk} /></g>
+ </g>
+ </svg>
+ </div>
+ );
+}
+
+function hand(cx: number, cy: number, length: number, degrees: number): string {
+ const rad = ((degrees - 90) * Math.PI) / 180;
+ return `M ${cx} ${cy} L ${cx + Math.cos(rad) * length} ${cy + Math.sin(rad) * length}`;
+}
+
+function AnalogClock({ now }: { now: Date }) {
+ const hours = (now.getHours() % 12) + now.getMinutes() / 60;
+ const minutes = now.getMinutes() + now.getSeconds() / 60;
+ const zone = lockZone(now);
+ return (
+ <div data-slot="ios-lock-analog" className="grid size-[72px] shrink-0 place-items-center rounded-full glass bg-[var(--glass-bar)] text-white" aria-label={zone ? `Clock, ${zone}` : "Clock"}>
+ <svg viewBox="0 0 36 36" className="size-14" aria-hidden>
+ <circle cx="18" cy="18" r="15" fill="none" stroke="currentColor" strokeWidth="1" className="text-white/50" />
+ <path d={hand(18, 18, 7, hours * 30)} stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
+ <path d={hand(18, 18, 11, minutes * 6)} stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
+ <circle cx="18" cy="18" r="1.2" fill="currentColor" />
+ </svg>
+ </div>
+ );
+}
+
+export function IosLockComplications({ now, weather }: { now: Date; weather: LockWeather }) {
+ return (
+ <div data-slot="ios-lock-complications" className="mt-4 flex w-full max-w-[360px] items-center gap-3 px-4">
+ <div data-slot="ios-lock-weather" data-state={weather.status} className="flex h-[72px] min-w-0 flex-1 items-center rounded-[22px] glass bg-[var(--glass-bar)] px-3 text-[15px] leading-5 text-white">
+ Weather unavailable
+ </div>
+ <ActivityRings />
+ <AnalogClock now={now} />
+ </div>
+ );
+}
diff --git a/frontend/slices/appshell/features/lock-screen/components/ios-lock-format.test.ts b/frontend/slices/appshell/features/lock-screen/components/ios-lock-format.test.ts
new file mode 100644
index 00000000..2e832bef
--- /dev/null
+++ b/frontend/slices/appshell/features/lock-screen/components/ios-lock-format.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from "vitest";
+import { temperatureUnit } from "./ios-lock-format";
+
+describe("lock weather temperature locale boundaries", () => {
+ it.each(["en-US", "en-LR", "my-MM", "EN-us", "MY-mm", "en-US-u-hc-h12"])(
+ "uses Fahrenheit for %s",
+ (language) => expect(temperatureUnit(language)).toBe("fahrenheit"),
+ );
+
+ it.each(["en-GB", "en", "", "x-my-MM", "notmy-MM", "my-MMjunk", "en-USA", "en-LRjunk", "en-USfoo", "en-US\n", "prefix-en-US"])(
+ "does not accept an embedded or partial locale in %j",
+ (language) => expect(temperatureUnit(language)).toBe("celsius"),
+ );
+});
diff --git a/frontend/slices/appshell/features/lock-screen/components/ios-lock-format.ts b/frontend/slices/appshell/features/lock-screen/components/ios-lock-format.ts
new file mode 100644
index 00000000..33d7dc2b
--- /dev/null
+++ b/frontend/slices/appshell/features/lock-screen/components/ios-lock-format.ts
@@ -0,0 +1,40 @@
+/** Device-local lock clock. Callers pass a browser `Date`; nothing here reads the host clock. */
+
+export function lockTime(now: Date): string {
+ const hour = now.getHours() % 12 || 12;
+ const minute = String(now.getMinutes()).padStart(2, "0");
+ return `${hour}:${minute}`;
+}
+
+/** Short device date, for the small line tight above the lock time. */
+export function lockShortDate(now: Date): string {
+ return now.toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" });
+}
+
+export function lockZone(now: Date): string {
+ const part = new Intl.DateTimeFormat(undefined, { timeZoneName: "short" })
+ .formatToParts(now)
+ .find((p) => p.type === "timeZoneName");
+ return part?.value ?? "";
+}
+
+export function temperatureUnit(language: string): "fahrenheit" | "celsius" {
+ const [code, region] = language.toLowerCase().split("-", 3);
+ const fahrenheit = (code === "en" && (region === "us" || region === "lr"))
+ || (code === "my" && region === "mm");
+ return fahrenheit ? "fahrenheit" : "celsius";
+}
+
+/** WMO weather interpretation codes, shortened for the complication. */
+export function weatherCondition(code: number): string {
+ if (code === 0) return "Clear";
+ if (code <= 3) return "Cloudy";
+ if (code === 45 || code === 48) return "Fog";
+ if (code <= 57) return "Drizzle";
+ if (code <= 67) return "Rain";
+ if (code <= 77) return "Snow";
+ if (code <= 82) return "Showers";
+ if (code <= 86) return "Snow showers";
+ if (code >= 95) return "Storm";
+ return "Weather";
+}
diff --git a/frontend/slices/appshell/features/lock-screen/components/ios-lock-safety.test.ts b/frontend/slices/appshell/features/lock-screen/components/ios-lock-safety.test.ts
new file mode 100644
index 00000000..4139b77c
--- /dev/null
+++ b/frontend/slices/appshell/features/lock-screen/components/ios-lock-safety.test.ts
@@ -0,0 +1,37 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+const root = "frontend/slices/appshell/features/lock-screen/components/";
+const source = (name: string) => readFileSync(root + name, "utf8");
+
+describe("iOS lock privacy and cross-shell boundaries", () => {
+ it("does not request device location or load external weather", () => {
+ for (const file of ["ios-lock-screen.tsx", "ios-lock-complications.tsx", "ios-lock-weather.ts"]) {
+ const text = source(file);
+ expect(text).not.toMatch(/getCurrentPosition|navigator\.geolocation|loadDeviceWeather|fetch\(/);
+ expect(text).not.toMatch(/open-meteo|bigdatacloud/);
+ }
+ expect(readFileSync("proxy.ts", "utf8")).not.toMatch(/open-meteo|bigdatacloud/);
+ });
+
+ it("keeps the existing non-iOS curtain and native keyboard unlock", () => {
+ const curtain = source("lock-screen.tsx");
+ expect(curtain).toContain('shell.id === "ios" ? <IosLockScreen /> : <LockCurtain />');
+ expect(curtain).toContain("text-6xl font-light tracking-tight");
+ expect(curtain).toContain('window.addEventListener("keydown", onKey)');
+ expect(curtain).not.toContain("ios-lock-camera");
+ expect(curtain).not.toContain("ios-lock-time");
+ });
+
+ it("provides a focused native unlock button with a 44px target", () => {
+ const face = source("ios-lock-screen.tsx");
+ expect(face).toContain('aria-label="Unlock"');
+ expect(face).toContain("button.current?.focus()");
+ expect(face).toContain("min-h-11");
+ expect(face).toContain("ios-lock-focus");
+ const css = readFileSync("app/globals.css", "utf8");
+ expect(css).toContain("outline: 2px solid Canvas");
+ expect(css).toContain("box-shadow: 0 0 0 4px CanvasText");
+ expect(face).not.toContain("ios-lock-camera");
+ });
+});
diff --git a/frontend/slices/appshell/features/lock-screen/components/ios-lock-screen.tsx b/frontend/slices/appshell/features/lock-screen/components/ios-lock-screen.tsx
new file mode 100644
index 00000000..bccc7680
--- /dev/null
+++ b/frontend/slices/appshell/features/lock-screen/components/ios-lock-screen.tsx
@@ -0,0 +1,156 @@
+"use client";
+
+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
+import { Flashlight } from "lucide-react";
+import { requestUnlock } from "../../../lib/lock";
+import { lockShortDate, lockTime } from "./ios-lock-format";
+import { IosLockComplications } from "./ios-lock-complications";
+
+function subscribeStandalone(onChange: () => void) {
+ const queries = ["(display-mode: standalone)", "(display-mode: fullscreen)"].map((q) => window.matchMedia(q));
+ queries.forEach((mq) => mq.addEventListener("change", onChange));
+ return () => queries.forEach((mq) => mq.removeEventListener("change", onChange));
+}
+
+function standaloneNow(): boolean {
+ const nav = navigator as Navigator & { standalone?: boolean };
+ return nav.standalone === true
+ || window.matchMedia("(display-mode: standalone)").matches
+ || window.matchMedia("(display-mode: fullscreen)").matches;
+}
+
+function useStandalone(): boolean {
+ return useSyncExternalStore(subscribeStandalone, standaloneNow, () => false);
+}
+
+function BatteryPercent() {
+ const [label, setLabel] = useState<string | null>(null);
+ useEffect(() => {
+ const nav = navigator as Navigator & { getBattery?: () => Promise<{ level: number; charging: boolean }> };
+ if (!nav.getBattery) return;
+ let live = true;
+ nav.getBattery().then((battery) => {
+ if (!live) return;
+ const pct = Math.round(battery.level * 100);
+ setLabel(battery.charging ? `${pct}% charging` : `${pct}%`);
+ }).catch(() => {});
+ return () => { live = false; };
+ }, []);
+ if (!label) return null;
+ return <span className="text-[12px] font-normal leading-4">{label}</span>;
+}
+
+function LockStatus({ now }: { now: Date }) {
+ const standalone = useStandalone();
+ return (
+ <div
+ data-slot="ios-lock-status"
+ data-standalone={standalone ? "true" : "false"}
+ className="flex shrink-0 items-center justify-between px-5 text-white"
+ style={{ height: "var(--sai-top, 0px)" }}
+ >
+ {standalone ? null : (
+ <>
+ <span className="text-[15px] font-semibold leading-5 tracking-[-0.23px]">{lockTime(now)}</span>
+ <BatteryPercent />
+ </>
+ )}
+ </div>
+ );
+}
+
+function LockHomeIndicator({ onUnlock }: { onUnlock: () => void }) {
+ const button = useRef<HTMLButtonElement>(null);
+ useEffect(() => {
+ const previous = document.activeElement;
+ const frame = requestAnimationFrame(() => button.current?.focus());
+ return () => {
+ cancelAnimationFrame(frame);
+ requestAnimationFrame(() => {
+ const homeSearch = document.querySelector<HTMLButtonElement>('[data-slot="ios-search-pill"]');
+ const target = previous instanceof HTMLElement && previous !== document.body && previous.isConnected
+ ? previous : homeSearch;
+ if (target && !target.closest("[inert]")) target.focus();
+ });
+ };
+ }, []);
+ return (
+ <div className="flex justify-center pt-[5px]" style={{ paddingBottom: "calc(7px + var(--sai-bottom, 0px))" }}>
+ <button
+ type="button"
+ ref={button}
+ data-slot="ios-lock-home-indicator"
+ aria-label="Unlock"
+ onClick={(e) => { e.stopPropagation(); onUnlock(); }}
+ className="flex min-h-11 items-center justify-center rounded-full px-12 py-1.5 ios-lock-focus"
+ >
+ <span className="h-[5px] w-[134px] rounded-full bg-white/75" />
+ </button>
+ </div>
+ );
+}
+
+/** iOS 27 lock face on the shell wallpaper. Clock values are the browser's Date. */
+export function IosLockFace({ now }: { now: Date }) {
+ const [torch, setTorch] = useState(false);
+ const weather = { status: "unavailable" } as const;
+
+ const unlock = () => void requestUnlock();
+ return (
+ <div
+ data-slot="ios-lock"
+ role="dialog"
+ aria-modal="true"
+ aria-label="Screen locked"
+ onKeyDown={(event) => {
+ if (event.key !== "Tab") return;
+ const controls = event.currentTarget.querySelectorAll<HTMLButtonElement>("button");
+ const first = controls[0];
+ const last = controls[controls.length - 1];
+ if (event.shiftKey && document.activeElement === first) {
+ event.preventDefault();
+ last?.focus();
+ } else if (!event.shiftKey && document.activeElement === last) {
+ event.preventDefault();
+ first?.focus();
+ }
+ }}
+ className="absolute inset-0 z-[var(--z-lock-screen)] flex cursor-pointer flex-col text-white"
+ onClick={unlock}
+ >
+ <LockStatus now={now} />
+ <div className="flex flex-col items-center pt-6">
+ <div data-slot="ios-lock-date" className="text-[13px] font-normal leading-[18px] tracking-[-0.08px] text-white/80">
+ <span>{lockShortDate(now)}</span>
+ </div>
+ <div data-slot="ios-lock-time" className="-mt-1 whitespace-nowrap text-[92px] font-semibold leading-none tracking-normal text-[oklch(0.94_0.03_95/0.78)]">
+ {lockTime(now)}
+ </div>
+ <IosLockComplications now={now} weather={weather} />
+ </div>
+ <div className="mt-auto flex w-full items-center justify-between px-4 pb-2">
+ <button
+ type="button"
+ data-slot="ios-lock-flashlight"
+ aria-label="Screen light"
+ aria-pressed={torch}
+ onClick={(e) => { e.stopPropagation(); setTorch((on) => !on); }}
+ className={`glass grid size-12 place-items-center rounded-full border border-white/35 ios-lock-focus ${torch ? "bg-white text-black" : "bg-white/20 text-white"}`}
+ >
+ <Flashlight className="size-5" aria-hidden />
+ </button>
+ </div>
+ <LockHomeIndicator onUnlock={unlock} />
+ {torch && <div className="pointer-events-none absolute inset-0 bg-white/75" style={{ zIndex: -1 }} />}
+ </div>
+ );
+}
+
+export function IosLockScreen() {
+ const [now, setNow] = useState<Date>(() => new Date());
+ useEffect(() => {
+ const t = setInterval(() => setNow(new Date()), 1000);
+ return () => clearInterval(t);
+ }, []);
+ return <IosLockFace now={now} />;
+}
diff --git a/frontend/slices/appshell/features/lock-screen/components/ios-lock-weather.ts b/frontend/slices/appshell/features/lock-screen/components/ios-lock-weather.ts
new file mode 100644
index 00000000..3871d868
--- /dev/null
+++ b/frontend/slices/appshell/features/lock-screen/components/ios-lock-weather.ts
@@ -0,0 +1,2 @@
+/** Weather stays unavailable until a separately reviewed, explicit opt-in exists. */
+export type LockWeather = { status: "unavailable" };
diff --git a/frontend/slices/appshell/features/lock-screen/components/ios-lock.test.tsx b/frontend/slices/appshell/features/lock-screen/components/ios-lock.test.tsx
new file mode 100644
index 00000000..4be5fce6
--- /dev/null
+++ b/frontend/slices/appshell/features/lock-screen/components/ios-lock.test.tsx
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+import { renderToStaticMarkup } from "react-dom/server";
+import { lockShortDate, lockTime, lockZone, temperatureUnit, weatherCondition } from "./ios-lock-format";
+import { IosLockFace } from "./ios-lock-screen";
+
+describe("iOS lock clock", () => {
+ const now = new Date(2026, 9, 4, 15, 7);
+
+ it("formats the device date and a 12-hour time from the given Date", () => {
+ expect(lockTime(now)).toBe("3:07");
+ expect(lockShortDate(now)).toContain("Oct");
+ expect(lockShortDate(now)).toContain("4");
+ expect(lockShortDate(now)).not.toContain("October");
+ expect(lockShortDate(now)).not.toContain("April");
+ expect(lockZone(now).length).toBeGreaterThan(0);
+ expect(temperatureUnit("en-US")).toBe("fahrenheit");
+ expect(temperatureUnit("en-GB")).toBe("celsius");
+ expect(weatherCondition(0)).toBe("Clear");
+ });
+
+ it("renders that clock on the lock face without a fixed sample time", () => {
+ const html = renderToStaticMarkup(<IosLockFace now={now} />);
+ expect(html).toContain('data-slot="ios-lock"');
+ expect(html).toContain('data-slot="ios-lock-status"');
+ expect(html).toContain('data-slot="ios-lock-complications"');
+ expect(html).toContain('data-slot="ios-lock-weather"');
+ expect(html).toContain('data-slot="ios-lock-rings"');
+ expect(html).toContain('data-slot="ios-lock-analog"');
+ expect(html).toContain('data-slot="ios-lock-flashlight"');
+ expect(html).not.toContain('data-slot="ios-lock-camera"');
+ expect(html).toContain("Weather unavailable");
+ expect(html).toContain("min-h-11");
+ expect(html).toContain('data-slot="ios-lock-home-indicator"');
+ expect(html).toContain(">3:07<");
+ expect(html).toContain("text-[92px] font-semibold");
+ expect(html).not.toContain("font-light");
+ expect(html).not.toContain("text-[96px]");
+ expect(html).toContain("text-[13px]");
+ expect(html).not.toContain("text-[20px]");
+ expect(html).not.toContain('data-slot="ios-lock-city"');
+ expect(html).not.toContain("9:41");
+ expect(html).not.toContain("April 1");
+ expect(html).not.toContain("San Francisco");
+ expect(html).not.toContain("backdrop-blur");
+ });
+});
diff --git a/frontend/slices/appshell/features/lock-screen/components/lock-screen.tsx b/frontend/slices/appshell/features/lock-screen/components/lock-screen.tsx
index 1863fa99..74a1c562 100644
--- a/frontend/slices/appshell/features/lock-screen/components/lock-screen.tsx
+++ b/frontend/slices/appshell/features/lock-screen/components/lock-screen.tsx
@@ -2,6 +2,8 @@
import { useEffect, useState } from "react";
import { Lock } from "lucide-react";
+import { useActiveShell } from "../../../registry/shells";
+import { IosLockScreen } from "./ios-lock-screen";
import { autoLockMinutes, lock, requestUnlock, useLocked } from "../../../lib/lock";
// Fullscreen privacy curtain: blurred backdrop, big clock, click/key unlocks
@@ -28,7 +30,9 @@ export function LockScreen() {
};
}, []);
- return locked ? <LockCurtain /> : null;
+ const shell = useActiveShell();
+ if (!locked) return null;
+ return shell.id === "ios" ? <IosLockScreen /> : <LockCurtain />;
}
function LockCurtain() {
diff --git a/frontend/slices/appshell/features/widgets/components/mobile-widget-layout.test.ts b/frontend/slices/appshell/features/widgets/components/mobile-widget-layout.test.ts
index f7d653d8..7f9ee7b4 100644
--- a/frontend/slices/appshell/features/widgets/components/mobile-widget-layout.test.ts
+++ b/frontend/slices/appshell/features/widgets/components/mobile-widget-layout.test.ts
@@ -18,5 +18,6 @@ describe("mobile widget layout policy", () => {
expect(mobile).toContain("overflow-x-clip");
expect(mobile).toContain('data-slot="quick-open-grid"');
expect(mobile).toContain("grid-cols-4");
+ expect(mobile).not.toContain('data-slot="ios-widget-placeholder"');
});
});
diff --git a/frontend/slices/appshell/features/widgets/components/mobile-widgets.tsx b/frontend/slices/appshell/features/widgets/components/mobile-widgets.tsx
index dd4189eb..47a8ca69 100644
--- a/frontend/slices/appshell/features/widgets/components/mobile-widgets.tsx
+++ b/frontend/slices/appshell/features/widgets/components/mobile-widgets.tsx
@@ -25,11 +25,16 @@ export function MobileWidgets() {
const { enabled } = useWidgetState();
const quick = quickIds.map((id) => apps.find((a) => a.id === id)).filter(Boolean) as AppDescriptor[];
+ const ios = shell.id !== "android";
return (
<div data-slot="mobile-widgets" className="flex h-full w-full min-w-0 max-w-full flex-col gap-3 overflow-x-clip overflow-y-auto px-4 py-3 [scrollbar-width:none]">
<div className="flex items-center justify-between px-1">
- <h2 className="text-[28px] font-extrabold tracking-[-0.02em] text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]">{shell.id === "android" ? "Widgets" : "Today"}</h2>
+ <h2 className={ios
+ ? "text-[28px] font-bold leading-[34px] tracking-[0.38px] text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]"
+ : "text-[28px] font-extrabold tracking-[-0.02em] text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]"}>
+ {shell.id === "android" ? "Widgets" : "Today"}
+ </h2>
{/* Edit the glanceable VPS telemetry set right from the phone — opens the
shared widget picker (add/remove Clock/Notes/Quicklinks/CPU/Mem/…). */}
<Button
@@ -37,7 +42,9 @@ export function MobileWidgets() {
variant="ghost"
size="sm"
onClick={() => setPickerOpen(true)}
- className="h-8 gap-1.5 rounded-full bg-white/15 px-3 text-[13px] font-medium text-white backdrop-blur hover:bg-white/25 hover:text-white [@media(pointer:coarse)]:min-h-[44px]"
+ className={ios
+ ? "h-11 gap-2 rounded-full bg-white/15 px-4 text-[17px] font-normal leading-[22px] tracking-[-0.43px] text-white backdrop-blur hover:bg-white/25 hover:text-white"
+ : "h-8 gap-1.5 rounded-full bg-white/15 px-3 text-[13px] font-medium text-white backdrop-blur hover:bg-white/25 hover:text-white [@media(pointer:coarse)]:min-h-[44px]"}
>
<Plus className="size-4" /> Edit
</Button>
@@ -50,14 +57,14 @@ export function MobileWidgets() {
{quick.length > 0 && (
<Card>
- <span className="mb-2 block text-[12px] font-semibold text-muted-foreground">Quick open</span>
+ <span className={ios ? "mb-2 block text-[12px] font-semibold leading-4 text-muted-foreground" : "mb-2 block text-[12px] font-semibold text-muted-foreground"}>Quick open</span>
<div data-slot="quick-open-grid" className="grid min-w-0 max-w-full grid-cols-4 gap-x-3 gap-y-3 overflow-x-clip">
{quick.map((app) => (
<Button key={app.id} type="button" variant="ghost" onClick={() => onOpen(app)} className="h-auto min-w-0 max-w-full p-0 hover:bg-transparent flex flex-col items-center gap-1.5 overflow-hidden">
<span className="size-12">
<AppIcon app={app} />
</span>
- <span className="max-w-[56px] truncate text-[10.5px] font-medium">{app.title}</span>
+ <span className={ios ? "max-w-[56px] truncate text-[12px] font-normal leading-4" : "max-w-[56px] truncate text-[10.5px] font-medium"}>{app.title}</span>
</Button>
))}
</div>
diff --git a/frontend/slices/appshell/lib/store-geometry.ts b/frontend/slices/appshell/lib/store-geometry.ts
index 9c5ce26a..769745f8 100644
--- a/frontend/slices/appshell/lib/store-geometry.ts
+++ b/frontend/slices/appshell/lib/store-geometry.ts
@@ -4,7 +4,7 @@ import type { Rect, SnapZone } from "./types";
// stateful store. Window coords are relative to the desktop surface, which
// already starts below the menu bar at top:TOPBAR (we DON'T add TOPBAR again).
-export const TOPBAR = 30;
+export const TOPBAR = 34;
export const DOCK_RESERVE = 92;
export const GAP = 8;
diff --git a/frontend/slices/appshell/responsive/responsive-provider.test.ts b/frontend/slices/appshell/responsive/responsive-provider.test.ts
index 2fe77437..546a009b 100644
--- a/frontend/slices/appshell/responsive/responsive-provider.test.ts
+++ b/frontend/slices/appshell/responsive/responsive-provider.test.ts
@@ -71,7 +71,6 @@ describe("shouldUseMobileSurface", () => {
});
});
-
describe("effectiveVisualViewportHeight", () => {
it("tracks browser chrome and keyboard at normal scale", () => {
expect(effectiveVisualViewportHeight(844, 706.4, 1)).toBe(706);
diff --git a/frontend/slices/appshell/responsive/responsive-provider.tsx b/frontend/slices/appshell/responsive/responsive-provider.tsx
index 6f432215..dceeb714 100644
--- a/frontend/slices/appshell/responsive/responsive-provider.tsx
+++ b/frontend/slices/appshell/responsive/responsive-provider.tsx
@@ -26,7 +26,6 @@ export function shouldUseMobileSurface(device: DeviceMode, vw: number, vh: numbe
return vw < MOBILE_W || (coarse && vw < TABLET_W);
}
-
/** The visual viewport is the actually visible browser area after dynamic URL bars
* and the soft keyboard are accounted for. Ignore it while pinch-zoomed: resizing
* the entire shell to a zoomed viewport makes content jump under accessibility zoom. */
diff --git a/lib/capabilities/actors.ts b/lib/capabilities/actors.ts
index 8c1cef93..34fd71b9 100644
--- a/lib/capabilities/actors.ts
+++ b/lib/capabilities/actors.ts
@@ -1,6 +1,7 @@
+import type { TenantContext } from "@/lib/tenancy/authority";
import type { CapabilityToolProfile } from "./tool";
-export interface CapabilityAgentContext { principal?: string; sessionId?: string; workflowActorOverride?: string; toolProfile?: CapabilityToolProfile; trustedOpenAiFileParams?: boolean; allowedTools?: readonly string[]; toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>; }
+export interface CapabilityAgentContext { tenantContext?: TenantContext; principal?: string; sessionId?: string; workflowActorOverride?: string; toolProfile?: CapabilityToolProfile; trustedOpenAiFileParams?: boolean; allowedTools?: readonly string[]; toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>; }
export function workflowActor(actor: string | undefined, context?: CapabilityAgentContext): string | undefined {
if (context?.workflowActorOverride) return context.workflowActorOverride;
return context?.principal && context.sessionId ? `${context.principal}#session:${context.sessionId}` : actor;
diff --git a/lib/capabilities/execute.ts b/lib/capabilities/execute.ts
index ac5eda48..a1fbfd8d 100644
--- a/lib/capabilities/execute.ts
+++ b/lib/capabilities/execute.ts
@@ -1,3 +1,6 @@
+import { TenantMemoryInputError } from "@/lib/tenancy/memory-tools";
+import { TenantCommitUncertain } from "@/lib/tenancy/persistence-file";
+import { tenantCapabilityPlan } from "@/lib/tenancy/capability";
import { capabilityReportedFailure } from "./result-outcome";
import { audit } from "@/lib/host/audit-api";
import { maybeAutoTitleAgentSession } from "@/lib/agent/session-store";
@@ -38,6 +41,18 @@ export async function executeCapabilityCall(input: {
if (context?.allowedTools && !context.allowedTools.includes(name)) return { kind: "error", message: "tool is not allowed for this token" };
const constraints = context?.toolArgumentConstraints?.[name];
if (constraints && Object.entries(constraints).some(([key, allowed]) => typeof args[key] !== "string" || !allowed.includes(args[key] as string))) return { kind: "error", message: "tool input is not allowed for this token" };
+ try {
+ const tenantPlan = await tenantCapabilityPlan(context?.tenantContext, name);
+ if (tenantPlan) {
+ if (!allows(scope, tool.scope)) return { kind: "error", message: "error: insufficient tenant tool scope" };
+ if (capabilityRateLimited(tool, args, tenantPlan.principal)) return { kind: "error", message: "error: tenant tool is rate limited" };
+ return { kind: "success", result: await tenantPlan.run(args) };
+ }
+ } catch (error) {
+ if (error instanceof TenantMemoryInputError) return { kind: "protocol_error", code: -32602, message: error.message };
+ if (error instanceof TenantCommitUncertain) return { kind: "error", message: "error: tenant mutation outcome uncertain; do not retry automatically; operation " + error.operationId };
+ return { kind: "error", message: "error: tenant capability unavailable or unauthorized" };
+ }
const presence = context?.principal?.startsWith("mcp-") && context.sessionId
? { principal: context.principal, sessionId: context.sessionId, instanceId: `mcp:${context.sessionId}` }
: null;
@@ -109,6 +124,7 @@ export async function executeCapabilityCall(input: {
const result = await tool.run(args, {
actor,
principal: context?.principal,
+ tenantContext: context?.tenantContext,
sessionId: context?.sessionId,
scope,
workflowId: activeWorkflow?.id,
diff --git a/lib/capabilities/runtime.ts b/lib/capabilities/runtime.ts
index b897ca34..f1398e15 100644
--- a/lib/capabilities/runtime.ts
+++ b/lib/capabilities/runtime.ts
@@ -1,3 +1,4 @@
+import type { TenantContext } from "@/lib/tenancy/authority";
import type { Scope } from "./scope";
export type { McpContent as CapabilityContent } from "@/lib/contracts/mcp-content";
@@ -11,6 +12,7 @@ export interface CapabilityDescriptor {
}
export interface CapabilityInvocation {
+ tenantContext?: TenantContext;
name: string;
args?: Record<string, unknown>;
scope: Scope;
diff --git a/lib/capabilities/tool.ts b/lib/capabilities/tool.ts
index 93cdb26f..04f28cc8 100644
--- a/lib/capabilities/tool.ts
+++ b/lib/capabilities/tool.ts
@@ -1,3 +1,4 @@
+import type { TenantContext } from "@/lib/tenancy/authority";
import type { AuditAction } from "@/lib/contracts/audit";
import type { CapabilityRuntime } from "./runtime";
import type { Scope } from "./scope";
@@ -56,6 +57,7 @@ export type CapabilityActionContract = {
};
export interface CapabilityRunContext {
+ tenantContext?: TenantContext;
actor?: string;
principal?: string;
sessionId?: string;
diff --git a/lib/mcp/capability-runtime.ts b/lib/mcp/capability-runtime.ts
index 3e9af712..738ce136 100644
--- a/lib/mcp/capability-runtime.ts
+++ b/lib/mcp/capability-runtime.ts
@@ -33,6 +33,7 @@ export const msoCapabilityRuntime: CapabilityRuntime = {
scope: input.scope,
actor: input.actor,
context: {
+ tenantContext: input.tenantContext,
principal: input.principal,
sessionId: input.sessionId,
...(input.workflowActor ? { workflowActorOverride: input.workflowActor } : {}),
diff --git a/lib/mcp/dispatch-types.ts b/lib/mcp/dispatch-types.ts
index 1783861b..99fca8c1 100644
--- a/lib/mcp/dispatch-types.ts
+++ b/lib/mcp/dispatch-types.ts
@@ -1,3 +1,4 @@
+import type { TenantContext } from "@/lib/tenancy/authority";
import type { CapabilityRuntime } from "@/lib/capabilities/runtime";
import type { McpToolProfile } from "./tool-contract";
@@ -19,6 +20,7 @@ export interface RpcRequest {
}
export interface McpAgentContext {
+ tenantContext?: TenantContext;
principal?: string;
sessionId?: string;
toolProfile?: McpToolProfile;
diff --git a/lib/mcp/store-types.ts b/lib/mcp/store-types.ts
index f26f0469..38850dd7 100644
--- a/lib/mcp/store-types.ts
+++ b/lib/mcp/store-types.ts
@@ -1,3 +1,4 @@
+import type { TenantCredentialBinding } from "@/lib/tenancy/types";
import type { Scope } from "./scope";
import type { McpToolProfile } from "./tool-contract";
@@ -9,6 +10,7 @@ export interface McpClient {
}
export interface McpCode {
+ tenantBinding?: Readonly<TenantCredentialBinding>;
clientId: string;
redirectUri: string;
codeChallenge: string;
@@ -20,6 +22,9 @@ export interface McpCode {
}
export interface McpToken {
+ tenantBinding?: Readonly<TenantCredentialBinding>;
+ /** Deprecated marker: subject-only credentials are rejected, never automatically upgraded. */
+ tenantSubject?: string;
label: string;
clientId: string;
scope: Scope;
@@ -35,6 +40,7 @@ export interface McpToken {
}
export interface McpRefreshToken {
+ tenantBinding?: Readonly<TenantCredentialBinding>;
grantId: string;
clientId: string;
scope: Scope;
diff --git a/lib/mcp/store.ts b/lib/mcp/store.ts
index 52d53a32..a197c8a9 100644
--- a/lib/mcp/store.ts
+++ b/lib/mcp/store.ts
@@ -1,3 +1,7 @@
+import { TenantDenied } from "@/lib/tenancy/authority";
+import { tenantCredentialFields } from "@/lib/tenancy/credentials";
+import { authorizeMcpTenantGrant } from "@/lib/tenancy/runtime";
+import type { TenantCredentialBinding } from "@/lib/tenancy/types";
import { randomUUID } from "node:crypto";
import { sha256hex } from "./pkce";
import type { Scope } from "./scope";
@@ -41,9 +45,10 @@ export async function getClient(clientId: string): Promise<McpClient | null> {
}
export function storeCode(code: string, rec: McpCode): Promise<void> {
+ const captured = structuredClone(rec), tenant = tenantCredentialFields(captured);
return mutate(async () => {
const store = sweep(await read());
- store.codes[sha256hex(code)] = rec;
+ store.codes[sha256hex(code)] = { ...captured, ...tenant };
await write(store);
});
}
@@ -55,6 +60,7 @@ export function consumeCode(code: string): Promise<McpCode | null> {
const hash = sha256hex(code);
const rec = store.codes[hash];
if (!rec || rec.expiresAt < Date.now()) return null;
+ try { await authorizeMcpTenantGrant(rec); } catch (error) { if (error instanceof TenantDenied) return null; throw error; }
delete store.codes[hash];
await write(store);
return rec;
@@ -62,15 +68,17 @@ export function consumeCode(code: string): Promise<McpCode | null> {
}
export function storeToken(token: string, rec: Omit<McpToken, "createdAt" | "expiresAt">): Promise<void> {
+ const captured = structuredClone(rec), tenant = tenantCredentialFields(captured);
return mutate(async () => {
const store = sweep(await read());
const now = Date.now();
- store.tokens[sha256hex(token)] = { ...rec, createdAt: now, expiresAt: now + TOKEN_TTL_MS };
+ store.tokens[sha256hex(token)] = { ...captured, ...tenant, createdAt: now, expiresAt: now + TOKEN_TTL_MS };
await write(store);
});
}
export function storeOAuthGrant(input: {
+ tenantBinding?: Readonly<TenantCredentialBinding>;
accessToken: string;
refreshToken: string;
label: string;
@@ -81,26 +89,30 @@ export function storeOAuthGrant(input: {
offlineAccess?: boolean;
grantId: string;
}): Promise<void> {
+ const captured = structuredClone(input), tenant = tenantCredentialFields(captured);
return mutate(async () => {
const store = sweep(await read());
const now = Date.now();
- store.tokens[sha256hex(input.accessToken)] = {
- label: input.label,
- clientId: input.clientId,
- scope: input.scope,
- resource: input.resource,
- profile: input.profile,
- grantId: input.grantId,
+ await authorizeMcpTenantGrant({ ...captured, ...tenant, expiresAt: now + OAUTH_ACCESS_TOKEN_TTL_MS });
+ store.tokens[sha256hex(captured.accessToken)] = {
+ ...tenant,
+ label: captured.label,
+ clientId: captured.clientId,
+ scope: captured.scope,
+ resource: captured.resource,
+ profile: captured.profile,
+ grantId: captured.grantId,
createdAt: now,
expiresAt: now + OAUTH_ACCESS_TOKEN_TTL_MS,
};
- store.refreshTokens[sha256hex(input.refreshToken)] = {
- grantId: input.grantId,
- clientId: input.clientId,
- scope: input.scope,
- resource: input.resource,
- profile: input.profile,
- offlineAccess: input.offlineAccess,
+ store.refreshTokens[sha256hex(captured.refreshToken)] = {
+ ...tenant,
+ grantId: captured.grantId,
+ clientId: captured.clientId,
+ scope: captured.scope,
+ resource: captured.resource,
+ profile: captured.profile,
+ offlineAccess: captured.offlineAccess,
createdAt: now,
expiresAt: now + REFRESH_TOKEN_TTL_MS,
};
@@ -116,15 +128,19 @@ export function rotateOAuthGrant(input: {
clientId: string;
resource: string;
}): Promise<McpRefreshToken | null> {
+ const captured = structuredClone(input);
return mutate(async () => {
const store = sweep(await read());
- const oldHash = sha256hex(input.oldRefreshToken);
+ const oldHash = sha256hex(captured.oldRefreshToken);
const rec = store.refreshTokens[oldHash];
- if (!rec || rec.revokedAt || rec.expiresAt < Date.now() || rec.clientId !== input.clientId || rec.resource !== input.resource) return null;
+ if (!rec || rec.revokedAt || rec.expiresAt < Date.now() || rec.clientId !== captured.clientId || rec.resource !== captured.resource) return null;
+ try { await authorizeMcpTenantGrant(rec); } catch (error) { if (error instanceof TenantDenied) return null; throw error; }
+ const tenant = tenantCredentialFields(rec);
delete store.refreshTokens[oldHash];
const now = Date.now();
- store.tokens[sha256hex(input.accessToken)] = {
- label: input.label,
+ store.tokens[sha256hex(captured.accessToken)] = {
+ ...tenant,
+ label: captured.label,
clientId: rec.clientId,
scope: rec.scope,
resource: rec.resource,
@@ -133,8 +149,8 @@ export function rotateOAuthGrant(input: {
createdAt: now,
expiresAt: now + OAUTH_ACCESS_TOKEN_TTL_MS,
};
- store.refreshTokens[sha256hex(input.refreshToken)] = {
- ...rec,
+ store.refreshTokens[sha256hex(captured.refreshToken)] = {
+ ...rec, ...tenant,
createdAt: now,
expiresAt: now + REFRESH_TOKEN_TTL_MS,
};
@@ -149,7 +165,7 @@ export async function validateToken(token: string): Promise<(McpToken & { hash:
const rec = (await read()).tokens[hash];
if (!rec || rec.revokedAt) return null;
if (rec.expiresAt > 0 && rec.expiresAt < Date.now()) return null;
- return { ...rec, hash };
+ try { return { ...rec, ...tenantCredentialFields(rec), hash }; } catch { return null; }
}
export function touchToken(hash: string): Promise<void> {
diff --git a/lib/mcp/tenant-capability-integration.test.ts b/lib/mcp/tenant-capability-integration.test.ts
new file mode 100644
index 00000000..0470a0c0
--- /dev/null
+++ b/lib/mcp/tenant-capability-integration.test.ts
@@ -0,0 +1,137 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { CapabilityTool } from "@/lib/capabilities/tool";
+import { fixture as persistentFixture } from "@/lib/tenancy/persistence-test-fixtures";
+import { writeTenantMemory } from "@/lib/tenancy/memory-write";
+import { tenantFixture } from "@/lib/tenancy/test-fixtures";
+
+const spies = vi.hoisted(() => ({
+ audit: vi.fn(), presence: vi.fn(), workflow: vi.fn(async () => null), step: vi.fn(),
+ title: vi.fn(), activity: vi.fn(), event: vi.fn(), run: vi.fn(async () => ({ legacy: true })),
+ rate: vi.fn(() => false),
+}));
+vi.mock("@/lib/host/audit-api", () => ({ audit: spies.audit }));
+vi.mock("@/lib/agent/session-store", () => ({ maybeAutoTitleAgentSession: spies.title }));
+vi.mock("@/lib/agent/local-agent-presence", () => ({ touchLocalAgentPresence: spies.presence }));
+vi.mock("@/lib/workflow", () => ({ activeWorkflowForActor: spies.workflow, recordWorkflowStep: spies.step, replayHandlesFromResult: () => [] }));
+vi.mock("@/lib/capabilities/activity", () => ({ activityTarget: () => "", newActivityId: () => "test", recordCapabilityActivity: spies.activity }));
+vi.mock("@/lib/capabilities/execution-support", () => ({
+ flowFields: () => ({}), recordAgentEvent: spies.event, sessionDetail: () => "", workflowFromResult: () => null,
+}));
+vi.mock("@/lib/capabilities/rate-limit", () => ({ capabilityRateLimited: spies.rate }));
+vi.mock("@/lib/mcp/tools", () => ({
+ TOOLS_BY_NAME: new Map([["agent_memory_read", {
+ name: "agent_memory_read", description: "Read memory", scope: "read",
+ inputSchema: { type: "object", properties: {} }, run: spies.run,
+ }]]),
+}));
+vi.mock("@/lib/mcp/dispatch-tool-support", () => ({ structuredResult: (_name: string, value: unknown) => ({ value }) }));
+
+import { executeCapabilityCall } from "@/lib/capabilities/execute";
+import { dispatchTenantRpc } from "@/lib/mcp/tenant-dispatch";
+const tool: CapabilityTool = { name: "agent_memory_read", description: "Read memory", scope: "read",
+ inputSchema: { type: "object", properties: {} }, run: spies.run };
+const call = (name = "agent_memory_read", args = {}) => ({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
+function noLegacyEffects() {
+ for (const spy of [spies.audit, spies.presence, spies.workflow, spies.step, spies.title, spies.activity, spies.event, spies.run]) {
+ expect(spy).not.toHaveBeenCalled();
+ }
+}
+beforeEach(() => { vi.clearAllMocks(); spies.rate.mockReturnValue(false); vi.stubEnv("OS_TENANCY_MODE", "tenant-preview"); });
+afterEach(() => vi.unstubAllEnvs());
+
+describe("actual capability kernel tenant seam", () => {
+ it("reads scoped memory without invoking legacy tool or telemetry", async () => {
+ const f = tenantFixture(), tenantContext = await f.authority.authenticate(f.identity());
+ const result = await executeCapabilityCall({ tool, args: {}, scope: "read", actor: "untrusted-label",
+ context: { tenantContext, principal: "mcp-client:shared", sessionId: "legacy-session" } });
+ expect(result).toMatchObject({ kind: "success", result: { user: "tenant-a:USER.md", memory: "tenant-a:MEMORY.md" } });
+ expect(spies.rate).toHaveBeenCalledWith(tool, {}, expect.stringMatching(/^tenant:/));
+ noLegacyEffects();
+ });
+ it("reads two real persistent namespaces through the capability kernel", async () => {
+ const f = await persistentFixture();
+ try {
+ await writeTenantMemory(f.contextA, "MEMORY.md", "disk-A", 2, 0);
+ await writeTenantMemory(f.contextB, "MEMORY.md", "disk-B", 3, 0);
+ const results = await Promise.all([f.contextA, f.contextB].map(tenantContext =>
+ executeCapabilityCall({ tool, args: {}, scope: "read", context: { tenantContext } })));
+ expect(results[0]).toMatchObject({ kind: "success", result: { memory: "disk-A" } });
+ expect(results[1]).toMatchObject({ kind: "success", result: { memory: "disk-B" } });
+ noLegacyEffects();
+ } finally { await f.cleanup(); }
+ });
+ it("retains ordinary legacy execution when mode is disabled", async () => {
+ vi.stubEnv("OS_TENANCY_MODE", "legacy");
+ expect(await executeCapabilityCall({ tool, args: {}, scope: "read" })).toMatchObject({ kind: "success", result: { legacy: true } });
+ expect(spies.run).toHaveBeenCalledOnce();
+ });
+ it.each(["exec_run", "fs_read", "browser_status", "apps_power", "integration_query", "project_mcp_call",
+ "agent_sessions_list", "exec_job_start"])("denies unsupported tenant capability %s", async name => {
+ const f = tenantFixture(), tenantContext = await f.authority.authenticate(f.identity());
+ const result = await executeCapabilityCall({ tool: { ...tool, name }, args: {}, scope: "exec", context: { tenantContext } });
+ expect(result.kind).toBe("error"); expect(f.reads).toHaveLength(0); noLegacyEffects();
+ });
+ it("missing or forged tenant context never falls back into legacy host authority", async () => {
+ for (const context of [undefined, { tenantContext: { kind: "tenant-preview" as const } }]) {
+ expect((await executeCapabilityCall({ tool, args: {}, scope: "exec", context })).kind).toBe("error");
+ }
+ noLegacyEffects();
+ });
+ it("scope and rate limits still apply before storage reads", async () => {
+ const f = tenantFixture(), tenantContext = await f.authority.authenticate(f.identity());
+ expect((await executeCapabilityCall({ tool: { ...tool, scope: "exec" }, args: {}, scope: "read", context: { tenantContext } })).kind).toBe("error");
+ spies.rate.mockReturnValue(true);
+ expect((await executeCapabilityCall({ tool, args: {}, scope: "read", context: { tenantContext } })).kind).toBe("error");
+ expect(f.reads).toHaveLength(0); noLegacyEffects();
+ });
+ it("token allowlists/constraints are not bypassed", async () => {
+ const f = tenantFixture(), tenantContext = await f.authority.authenticate(f.identity());
+ for (const extra of [{ allowedTools: [] }, { toolArgumentConstraints: { agent_memory_read: { user: ["other"] } } }]) {
+ expect((await executeCapabilityCall({ tool, args: {}, scope: "read", context: { tenantContext, ...extra } })).kind).toBe("error");
+ }
+ expect(f.reads).toHaveLength(0); noLegacyEffects();
+ });
+ it.each([{ tenantId: "tenant-b" }, { user: "bob" }, { workflow_id: "foreign" }, { path: "/other" }])("rejects caller selectors %j", async args => {
+ const f = tenantFixture(), tenantContext = await f.authority.authenticate(f.identity());
+ expect((await executeCapabilityCall({ tool, args, scope: "read", context: { tenantContext } })).kind).toBe("protocol_error");
+ expect(f.reads).toHaveLength(0); noLegacyEffects();
+ });
+ it("adapter failure text is not exposed", async () => {
+ const f = tenantFixture(), tenantContext = await f.authority.authenticate(f.identity());
+ f.overrideRead(() => { throw new Error("private backend failure"); });
+ const result = await executeCapabilityCall({ tool, args: {}, scope: "read", context: { tenantContext } });
+ expect(JSON.stringify(result)).not.toContain("private backend"); noLegacyEffects();
+ });
+});
+describe("tenant-only MCP dispatcher", () => {
+ it("lists only the implemented tenant tool", async () => {
+ const f = tenantFixture(), tenantContext = await f.authority.authenticate(f.identity());
+ const result = await dispatchTenantRpc({ id: 1, method: "tools/list" }, "exec", "actor", { tenantContext });
+ expect((result.result as { tools: { name: string }[] }).tools.map(t => t.name)).toEqual(["agent_memory_read"]);
+ noLegacyEffects();
+ });
+ it.each(["initialize", "ping", "resources/list", "resources/templates/list", "prompts/list"])("metadata %s has no owner-state side effect", async method => {
+ const f = tenantFixture(), tenantContext = await f.authority.authenticate(f.identity());
+ await dispatchTenantRpc({ id: 1, method }, "read", "actor", { tenantContext });
+ expect(f.reads).toHaveLength(0); noLegacyEffects();
+ });
+ it("modern discovery is tenant-only without protocol activity", async () => {
+ const f = tenantFixture(), tenantContext = await f.authority.authenticate(f.identity());
+ const result = await dispatchTenantRpc({ id: 1, method: "server/discover",
+ params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } } }, "read", "actor", { tenantContext });
+ expect(result.result).toMatchObject({ capabilities: { tools: {} } }); noLegacyEffects();
+ });
+ it("resources and unsupported tools cannot reach the legacy dispatcher", async () => {
+ const f = tenantFixture(), tenantContext = await f.authority.authenticate(f.identity());
+ expect(await dispatchTenantRpc({ id: 1, method: "resources/read", params: { uri: "file:///other" } }, "exec", "actor", { tenantContext })).toHaveProperty("error");
+ expect(await dispatchTenantRpc(call("exec_run"), "exec", "actor", { tenantContext })).toHaveProperty("error");
+ noLegacyEffects();
+ });
+ it("routes two concurrent subjects to distinct storage namespaces", async () => {
+ const f = tenantFixture(), a = await f.authority.authenticate(f.identity()), b = await f.authority.authenticate(f.identity("bob"));
+ const results = await Promise.all([a, b].map(tenantContext => dispatchTenantRpc(call(), "read", "same-client", { tenantContext })));
+ expect(results[0]).toMatchObject({ result: { value: { user: "tenant-a:USER.md" } } });
+ expect(results[1]).toMatchObject({ result: { value: { user: "tenant-b:USER.md" } } });
+ noLegacyEffects();
+ });
+});
diff --git a/lib/mcp/tenant-dispatch.ts b/lib/mcp/tenant-dispatch.ts
new file mode 100644
index 00000000..3d09d843
--- /dev/null
+++ b/lib/mcp/tenant-dispatch.ts
@@ -0,0 +1,51 @@
+import { TENANT_MEMORY_TOOLS } from "@/lib/tenancy/memory-tools";
+import { executeCapabilityCall } from "@/lib/capabilities/execute";
+import { allows, type Scope } from "@/lib/capabilities/scope";
+import { tenantPrincipal } from "@/lib/tenancy/authority";
+import { TOOLS_BY_NAME } from "./tools";
+import { toolDescriptor, toolAllowedForProfile } from "./tool-contract";
+import { MCP_PROTOCOL_LATEST, MCP_PROTOCOLS, negotiateMcpProtocol } from "./protocol";
+import { MCP_SERVER_VERSION } from "./toolset";
+import { rpcFail, rpcOk, type McpAgentContext, type RpcRequest } from "./dispatch-types";
+import { structuredResult } from "./dispatch-tool-support";
+
+const INSTRUCTIONS = "Tenant preview supports scoped memory read, search, remember and forget. Host, browser, app, project, session and provider operations are unavailable.";
+export async function dispatchTenantRpc(req: RpcRequest, scope: Scope, actor: string, context: McpAgentContext): Promise<Record<string, unknown>> {
+ const id = req.id ?? null;
+ if (!context.tenantContext) return rpcFail(id, -32001, "tenant identity is required");
+ try { await tenantPrincipal(context.tenantContext); }
+ catch { return rpcFail(id, -32001, "tenant identity is unavailable"); }
+ const modern = req.params?._meta?.["io.modelcontextprotocol/protocolVersion"] === MCP_PROTOCOL_LATEST;
+ if (modern && ["initialize", "notifications/initialized"].includes(req.method ?? "")) {
+ return rpcFail(id, -32601, "initialize is only supported in the legacy MCP era");
+ }
+ const profile = context.toolProfile ?? "full";
+ const visible = TENANT_MEMORY_TOOLS.map(name => TOOLS_BY_NAME.get(name)).filter(tool => tool !== undefined)
+ .filter(tool => allows(scope, tool.scope) && toolAllowedForProfile(tool.name, profile)
+ && (!context.allowedTools || context.allowedTools.includes(tool.name)));
+ switch (req.method) {
+ case "server/discover":
+ return modern ? rpcOk(id, { supportedVersions: [...MCP_PROTOCOLS], capabilities: { tools: {} },
+ instructions: INSTRUCTIONS, cacheScope: "private", ttlMs: 0 }) : rpcFail(id, -32601, "modern metadata required");
+ case "initialize":
+ return rpcOk(id, { protocolVersion: negotiateMcpProtocol(req.params?.protocolVersion),
+ capabilities: { tools: { listChanged: false } },
+ serverInfo: { name: "mso", version: MCP_SERVER_VERSION }, instructions: INSTRUCTIONS });
+ case "ping":
+ case "notifications/initialized": return rpcOk(id, {});
+ case "tools/list": return rpcOk(id, { tools: visible.map(tool => toolDescriptor(tool, profile)), cacheScope: "private", ttlMs: 0 });
+ case "resources/list": return rpcOk(id, { resources: [] });
+ case "resources/templates/list": return rpcOk(id, { resourceTemplates: [] });
+ case "prompts/list": return rpcOk(id, { prompts: [] });
+ case "tools/call": {
+ const tool = visible.find(candidate => candidate.name === req.params?.name);
+ if (!tool) return rpcFail(id, -32602, "tool unavailable in tenant preview");
+ const args = req.params?.arguments ?? {};
+ const outcome = await executeCapabilityCall({ tool, args, scope, actor, context });
+ if (outcome.kind === "protocol_error") return rpcFail(id, outcome.code, outcome.message);
+ if (outcome.kind === "error") return rpcOk(id, { content: [{ type: "text", text: outcome.message }], isError: true });
+ return rpcOk(id, structuredResult(tool.name, outcome.result, profile));
+ }
+ default: return rpcFail(id, -32601, "method unavailable in tenant preview");
+ }
+}
diff --git a/lib/mcp/tenant-grant-lifecycle.test.ts b/lib/mcp/tenant-grant-lifecycle.test.ts
new file mode 100644
index 00000000..9dfef42c
--- /dev/null
+++ b/lib/mcp/tenant-grant-lifecycle.test.ts
@@ -0,0 +1,150 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { createTenantRuntime } from "@/lib/tenancy/runtime-factory";
+import type { TenantBinding, TenantCredentialBinding } from "@/lib/tenancy/types";
+
+const injected = vi.hoisted(() => ({ runtime: null as ReturnType<typeof createTenantRuntime> | null }));
+vi.mock("@/lib/tenancy/runtime", () => ({
+ authorizeMcpTenantGrant: async (record: Parameters<ReturnType<typeof createTenantRuntime>["resolveValidatedToken"]>[0]) => {
+ await injected.runtime!.resolveValidatedToken(record);
+ },
+}));
+const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-tenant-grants-"));
+const previous = process.env.OS_MCP_STORE;
+process.env.OS_MCP_STORE = root + "/synthetic-mcp.json";
+const store = await import("./store");
+const { sha256hex } = await import("./pkce");
+const stamp: TenantCredentialBinding = { version: 1, issuer: "fixture", subject: "alice", tenantId: "tenant-a", principalId: "person-a", mappingRevision: 1 };
+let enabled = true;
+let binding: TenantBinding;
+const issue = (tenantBinding: TenantCredentialBinding | undefined = stamp) => store.storeOAuthGrant({
+ accessToken: "fixture-access", refreshToken: "fixture-refresh", label: "synthetic only", clientId: "fixture-client", scope: "read",
+ resource: "https://fixture.invalid/mcp", grantId: "fixture-grant", tenantBinding,
+});
+const rotate = (oldRefreshToken = "fixture-refresh", suffix = "two") => store.rotateOAuthGrant({
+ oldRefreshToken, accessToken: "fixture-access-" + suffix, refreshToken: "fixture-refresh-" + suffix, label: "synthetic",
+ clientId: "fixture-client", resource: "https://fixture.invalid/mcp",
+});
+beforeEach(async () => {
+ await fs.rm(root, { recursive: true, force: true });
+ await fs.mkdir(root, { mode: 0o700 });
+ enabled = true;
+ binding = { tenantId: "tenant-a", principalId: "person-a", mappingRevision: 1, enabled: true, tenantEnabled: true };
+ injected.runtime = createTenantRuntime({ enabled: () => enabled, registry: {
+ resolve: async identity => identity.issuer === "fixture" && identity.subject === "alice" ? { ...binding } : null,
+ }, storage: { read: async () => null }, verifyAccessToken: bearer => store.validateToken(bearer) });
+});
+afterAll(async () => {
+ await fs.rm(root, { recursive: true, force: true });
+ if (previous === undefined) delete process.env.OS_MCP_STORE; else process.env.OS_MCP_STORE = previous;
+});
+describe("actual OAuth store with synthetic tenant grants", () => {
+ it("preserves exact binding through code exchange and repeated rotation", async () => {
+ await store.storeCode("fixture-code", { clientId: "fixture-client", redirectUri: "https://fixture.invalid/cb",
+ codeChallenge: "synthetic", scope: "read", expiresAt: Date.now() + 60000, tenantBinding: stamp });
+ expect((await store.consumeCode("fixture-code"))?.tenantBinding).toEqual(stamp);
+ expect(await store.consumeCode("fixture-code")).toBeNull();
+ await issue();
+ expect((await store.validateToken("fixture-access"))?.tenantBinding).toEqual(stamp);
+ expect((await rotate())?.tenantBinding).toEqual(stamp);
+ expect((await store.validateToken("fixture-access-two"))?.tenantBinding).toEqual(stamp);
+ expect((await rotate("fixture-refresh-two", "three"))?.tenantBinding).toEqual(stamp);
+ const disk = JSON.parse(await fs.readFile(root + "/synthetic-mcp.json", "utf8"));
+ expect(disk.refreshTokens[sha256hex("fixture-refresh-three")].tenantBinding).toEqual(stamp);
+ expect(await fs.readFile(root + "/synthetic-mcp.json", "utf8")).not.toContain("fixture-access-three");
+ });
+ it.each(["tenantId", "principalId", "mappingRevision", "enabled", "tenantEnabled"] as const)("refuses rotation after %s changes without replacement writes", async field => {
+ await issue();
+ Object.assign(binding, { [field]: field === "mappingRevision" ? 2 : field.endsWith("Enabled") || field === "enabled" ? false : "different" });
+ expect(await rotate()).toBeNull();
+ expect(await store.validateToken("fixture-access-two")).toBeNull();
+ const disk = JSON.parse(await fs.readFile(root + "/synthetic-mcp.json", "utf8"));
+ expect(disk.refreshTokens[sha256hex("fixture-refresh")]).toBeDefined();
+ expect(disk.refreshTokens[sha256hex("fixture-refresh-two")]).toBeUndefined();
+ });
+ it("rechecks the pinned generation on each actual stored access-token request", async () => {
+ await issue();
+ expect(await injected.runtime!.authenticateBearer("fixture-access")).toBeDefined();
+ binding.mappingRevision = 2;
+ await expect(injected.runtime!.authenticateBearer("fixture-access")).rejects.toThrow();
+ });
+ it("copies a caller-supplied stamp before asynchronous store mutation", async () => {
+ const source = { ...stamp };
+ const pending = issue(source);
+ source.tenantId = "changed-after-call";
+ await pending;
+ expect((await store.validateToken("fixture-access"))?.tenantBinding).toEqual(stamp);
+ });
+ it("refuses code exchange after a binding generation changes", async () => {
+ await store.storeCode("fixture-code", { clientId: "fixture-client", redirectUri: "https://fixture.invalid/cb",
+ codeChallenge: "synthetic", scope: "read", expiresAt: Date.now() + 60000, tenantBinding: stamp });
+ binding.mappingRevision = 2;
+ expect(await store.consumeCode("fixture-code")).toBeNull();
+ });
+ it("does not upgrade old credentials after disable and re-enable", async () => {
+ await issue(); binding.enabled = false; binding.mappingRevision = 2;
+ expect(await rotate()).toBeNull();
+ binding.enabled = true; binding.mappingRevision = 3;
+ expect(await rotate()).toBeNull();
+ });
+ it.each(["rotate-first", "revoke-first"])("preserves family revocation when rotation races: %s", async order => {
+ await issue();
+ const id = (await store.listTokens())[0].id;
+ await Promise.all(order === "rotate-first" ? [rotate(), store.revokeToken(id)] : [store.revokeToken(id), rotate()]);
+ expect(await store.validateToken("fixture-access")).toBeNull();
+ expect(await store.validateToken("fixture-access-two")).toBeNull();
+ expect(await rotate("fixture-refresh-two", "three")).toBeNull();
+ });
+ it("rotates a refresh credential at most once under concurrent calls", async () => {
+ await issue();
+ const results = await Promise.all([rotate("fixture-refresh", "one"), rotate("fixture-refresh", "two")]);
+ expect(results.filter(Boolean)).toHaveLength(1);
+ const replacements = await Promise.all(["fixture-access-one", "fixture-access-two"].map(store.validateToken));
+ expect(replacements.filter(Boolean)).toHaveLength(1);
+ });
+ it("never acquires a tenant marker added after an unbound queued call", async () => {
+ enabled = false;
+ const source = { label: "synthetic", clientId: "fixture-client", scope: "read" as const,
+ tenantBinding: undefined as TenantCredentialBinding | undefined };
+ const pending = store.storeToken("fixture-unbound", source);
+ source.tenantBinding = stamp;
+ await pending;
+ expect(await store.validateToken("fixture-unbound")).not.toHaveProperty("tenantBinding");
+ const code = { clientId: "fixture-client", redirectUri: "https://fixture.invalid/cb", codeChallenge: "fake",
+ scope: "read" as const, expiresAt: Date.now() + 60000, tenantBinding: undefined as TenantCredentialBinding | undefined };
+ const pendingCode = store.storeCode("fixture-unbound-code", code);
+ code.tenantBinding = stamp;
+ await pendingCode;
+ expect(await store.consumeCode("fixture-unbound-code")).not.toHaveProperty("tenantBinding");
+ });
+ it("allows revocation even when the binding is stale or tenant mode is off", async () => {
+ await issue(); binding.mappingRevision = 2; enabled = false;
+ expect(await store.revokeToken((await store.listTokens())[0].id)).toBe(true);
+ expect(await rotate()).toBeNull();
+ });
+ it("never downgrades tenant records into owner credentials when mode is off", async () => {
+ await issue(); enabled = false;
+ expect(await rotate()).toBeNull();
+ await expect(issue()).rejects.toThrow();
+ });
+ it("unbound legacy grants work only in legacy mode", async () => {
+ await expect(store.storeOAuthGrant({ accessToken: "fixture-u", refreshToken: "fixture-ur", label: "synthetic",
+ clientId: "fixture-client", scope: "read", resource: "https://fixture.invalid/mcp", grantId: "fixture-u" })).rejects.toThrow();
+ enabled = false;
+ await store.storeOAuthGrant({ accessToken: "fixture-u", refreshToken: "fixture-ur", label: "synthetic",
+ clientId: "fixture-client", scope: "read", resource: "https://fixture.invalid/mcp", grantId: "fixture-u" });
+ expect(await store.validateToken("fixture-u")).not.toBeNull();
+ enabled = true;
+ expect(await rotate("fixture-ur")).toBeNull();
+ });
+ it.each([{ tenantSubject: "alice" }, { tenantBinding: null }, { tenantBinding: { ...stamp, version: 9 } }])("refuses malformed persisted markers %j before rotation", async bad => {
+ await issue(); enabled = false;
+ const file = root + "/synthetic-mcp.json", disk = JSON.parse(await fs.readFile(file, "utf8"));
+ Object.assign(disk.refreshTokens[sha256hex("fixture-refresh")], bad);
+ await fs.writeFile(file, JSON.stringify(disk));
+ expect(await rotate()).toBeNull();
+ expect(await store.validateToken("fixture-access-two")).toBeNull();
+ });
+});
diff --git a/lib/tenancy/authority-storage.test.ts b/lib/tenancy/authority-storage.test.ts
new file mode 100644
index 00000000..f821a963
--- /dev/null
+++ b/lib/tenancy/authority-storage.test.ts
@@ -0,0 +1,122 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { tenantAccess, tenantPrincipal, type TenantContext } from "./authority";
+import { readTenantMemory, readTenantValue } from "./storage";
+import { tenantCapabilityPlan } from "./capability";
+import { resolveMcpTenant } from "./runtime";
+import { tenantFixture } from "./test-fixtures";
+
+afterEach(() => vi.unstubAllEnvs());
+describe("authenticated tenant authority", () => {
+ it("separates named subjects independently of application identity", async () => {
+ const f = tenantFixture();
+ const a = await f.authority.authenticate(f.identity()), b = await f.authority.authenticate(f.identity("bob"));
+ expect(await tenantPrincipal(a)).not.toBe(await tenantPrincipal(b));
+ expect((await tenantAccess(a)).binding.tenantId).toBe("tenant-a");
+ });
+ it.each(["unknown", "../alice", "", "__proto__"])("rejects unmapped/invalid subject %s", async subject => {
+ const f = tenantFixture();
+ await expect(f.authority.authenticate(f.identity(subject))).rejects.toThrow();
+ });
+ it("rejects another issuer and expired identities", async () => {
+ const f = tenantFixture();
+ await expect(f.authority.authenticate({ ...f.identity(), issuer: "other" })).rejects.toThrow();
+ await expect(f.authority.authenticate({ ...f.identity(), expiresAt: 1000 })).rejects.toThrow();
+ });
+ it("rejects forged and copied contexts", async () => {
+ const f = tenantFixture(), context = await f.authority.authenticate(f.identity());
+ expect(Object.isFrozen(context)).toBe(true);
+ await expect(tenantAccess({ ...context })).rejects.toThrow();
+ await expect(tenantAccess({ kind: "tenant-preview" } as TenantContext)).rejects.toThrow();
+ });
+ it.each(["tenantId", "principalId", "mappingRevision", "enabled", "tenantEnabled"] as const)("invalidates changed %s", async field => {
+ const f = tenantFixture(), context = await f.authority.authenticate(f.identity());
+ const patch = { tenantId: "tenant-b", principalId: "other", mappingRevision: 2, enabled: false, tenantEnabled: false };
+ Object.assign(f.bindings.alice, { [field]: patch[field] });
+ await expect(tenantAccess(context)).rejects.toThrow();
+ });
+ it.each([0, -1, 0.5, Infinity, Number.MAX_SAFE_INTEGER + 1])("rejects invalid mapping revision %s", async mappingRevision => {
+ const f = tenantFixture(); f.bindings.alice.mappingRevision = mappingRevision;
+ await expect(f.authority.authenticate(f.identity())).rejects.toThrow();
+ });
+});
+describe("tenant-scoped storage", () => {
+ it("derives address from opaque context without accepting tenant selectors", async () => {
+ const f = tenantFixture(), context = await f.authority.authenticate(f.identity());
+ expect(await readTenantValue(context, "memory", "USER.md")).toBe("tenant-a:USER.md");
+ expect(f.reads).toEqual([{ tenantId: "tenant-a", principalId: "principal-a", mappingRevision: 1, collection: "memory", key: "USER.md" }]);
+ });
+ it.each(["tenantId", "principalId", "mappingRevision", "collection", "key"] as const)("refuses wrongly scoped adapter row: %s", async field => {
+ const f = tenantFixture(), context = await f.authority.authenticate(f.identity());
+ f.overrideRead(address => ({ ...address, value: "foreign", [field]: field === "mappingRevision" ? 2 : "foreign" }));
+ await expect(readTenantValue(context, "memory", "USER.md")).rejects.toThrow("scope mismatch");
+ });
+ it("has no global/owner fallback for an absent record", async () => {
+ const f = tenantFixture(), context = await f.authority.authenticate(f.identity());
+ f.overrideRead(() => null);
+ expect(await readTenantMemory(context)).toMatchObject({ user: "", memory: "" });
+ expect(f.reads).toHaveLength(2);
+ });
+ it.each(["../USER.md", "/absolute", "", "x/y"])("rejects path-shaped storage key %s", async key => {
+ const f = tenantFixture(), context = await f.authority.authenticate(f.identity());
+ await expect(readTenantValue(context, "memory", key)).rejects.toThrow();
+ expect(f.reads).toHaveLength(0);
+ });
+ it.each(["revoke", "expire"])("rechecks %s after storage awaits", async change => {
+ const f = tenantFixture(), context = await f.authority.authenticate(f.identity());
+ f.overrideRead(address => {
+ if (change === "revoke") f.bindings.alice.enabled = false; else f.setNow(5000);
+ return { ...address, value: "not-returned" };
+ });
+ await expect(readTenantValue(context, "memory", "USER.md")).rejects.toThrow();
+ });
+ it.each([42, "x".repeat(65537)])("rejects malformed or oversized memory", async value => {
+ const f = tenantFixture(), context = await f.authority.authenticate(f.identity());
+ f.overrideRead(address => ({ ...address, value }));
+ await expect(readTenantMemory(context)).rejects.toThrow("invalid tenant memory");
+ });
+});
+describe("disabled-by-default runtime", () => {
+ it("leaves legacy unmarked tokens unchanged", async () => {
+ vi.stubEnv("OS_TENANCY_MODE", "");
+ await expect(resolveMcpTenant({ expiresAt: 0 })).resolves.toBeUndefined();
+ await expect(tenantCapabilityPlan(undefined, "exec_run")).resolves.toBeNull();
+ });
+ it("never downgrades a tenant credential/context into owner legacy mode", async () => {
+ vi.stubEnv("OS_TENANCY_MODE", "legacy");
+ await expect(resolveMcpTenant({ tenantSubject: "alice", expiresAt: 5000 })).rejects.toThrow();
+ const f = tenantFixture(), context = await f.authority.authenticate(f.identity());
+ await expect(tenantCapabilityPlan(context, "agent_memory_read")).rejects.toThrow();
+ });
+ it("invalid mode fails closed", async () => {
+ vi.stubEnv("OS_TENANCY_MODE", "typo");
+ await expect(resolveMcpTenant({ expiresAt: 0 })).rejects.toThrow("invalid tenancy mode");
+ await expect(tenantCapabilityPlan(undefined, "exec_run")).rejects.toThrow();
+ });
+ it("preview has no live subject minting or storage provisioning path", async () => {
+ vi.stubEnv("OS_TENANCY_MODE", "tenant-preview");
+ await expect(resolveMcpTenant({ expiresAt: Date.now() + 10000 })).rejects.toThrow("versioned tenant credential");
+ await expect(resolveMcpTenant({ tenantSubject: "alice", expiresAt: Date.now() + 10000 })).rejects.toThrow("unversioned");
+ await expect(resolveMcpTenant({ tenantBinding: { version: 1, issuer: "mso-local", subject: "alice",
+ tenantId: "tenant-a", principalId: "principal-a", mappingRevision: 1 }, expiresAt: Date.now() + 10000 })).rejects.toThrow("not configured");
+ });
+});
+
+describe("parallel tenant read lifecycle", () => {
+ it("settles every started read before returning a sibling failure", async () => {
+ const f = tenantFixture(), context = await f.authority.authenticate(f.identity());
+ let release!: () => void;
+ const blocked = new Promise<void>(resolve => { release = resolve; });
+ const read = f.storage.read.bind(f.storage);
+ f.storage.read = async address => {
+ if (address.key === "USER.md") throw new Error("synthetic read failure");
+ await blocked;
+ return read(address);
+ };
+ let settled = false;
+ const pending = readTenantMemory(context);
+ void pending.then(() => { settled = true; }, () => { settled = true; });
+ await new Promise(resolve => setImmediate(resolve));
+ try { expect(settled).toBe(false); } finally { release(); }
+ await expect(pending).rejects.toThrow("synthetic read failure");
+ });
+});
diff --git a/lib/tenancy/authority.ts b/lib/tenancy/authority.ts
new file mode 100644
index 00000000..77c92bf4
--- /dev/null
+++ b/lib/tenancy/authority.ts
@@ -0,0 +1,53 @@
+import { createHash } from "node:crypto";
+import type { AuthenticatedSubject, TenantBinding, TenantRegistryPort, TenantStoragePort } from "./types";
+
+export interface TenantContext { readonly kind: "tenant-preview"; }
+type Record = {
+ identity: Readonly<AuthenticatedSubject>;
+ binding: Readonly<TenantBinding>;
+ registry: TenantRegistryPort;
+ storage: TenantStoragePort;
+ now: () => number;
+};
+const contexts = new WeakMap<TenantContext, Record>();
+const id = (value: unknown): value is string => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value);
+export class TenantDenied extends Error {
+ constructor(message = "tenant request denied") { super(message); this.name = "TenantDenied"; }
+}
+function validBinding(value: TenantBinding | null): value is TenantBinding {
+ return Boolean(value && id(value.tenantId) && id(value.principalId) && value.enabled === true
+ && value.tenantEnabled === true && Number.isSafeInteger(value.mappingRevision) && value.mappingRevision > 0);
+}
+type BindingKey = Pick<TenantBinding, "tenantId" | "principalId" | "mappingRevision">;
+function sameBinding(a: Readonly<BindingKey>, b: Readonly<BindingKey>) {
+ return a.tenantId === b.tenantId && a.principalId === b.principalId && a.mappingRevision === b.mappingRevision;
+}
+export function createTenantAuthority(registry: TenantRegistryPort, storage: TenantStoragePort, now = Date.now) {
+ return Object.freeze({
+ async authenticate(identity: AuthenticatedSubject, expected?: Readonly<BindingKey>): Promise<TenantContext> {
+ const pinned = expected === undefined ? undefined : Object.freeze({ ...expected });
+ if (pinned && !validBinding({ ...pinned, enabled: true, tenantEnabled: true })) throw new TenantDenied();
+ if (!id(identity.issuer) || !id(identity.subject) || !Number.isFinite(identity.expiresAt) || identity.expiresAt <= now()) {
+ throw new TenantDenied();
+ }
+ const copy = Object.freeze({ ...identity });
+ const binding = await registry.resolve(copy);
+ if (!validBinding(binding) || (pinned && !sameBinding(binding, pinned)) || copy.expiresAt <= now()) throw new TenantDenied();
+ const context = Object.freeze({ kind: "tenant-preview" as const });
+ contexts.set(context, { identity: copy, binding: Object.freeze({ ...binding }), registry, storage, now });
+ return context;
+ },
+ });
+}
+export async function tenantAccess(context: TenantContext) {
+ const record = contexts.get(context);
+ if (!record || record.identity.expiresAt <= record.now()) throw new TenantDenied();
+ const live = await record.registry.resolve(record.identity);
+ if (!validBinding(live) || !sameBinding(record.binding, live) || record.identity.expiresAt <= record.now()) throw new TenantDenied();
+ return { identity: record.identity, binding: record.binding, storage: record.storage };
+}
+export async function tenantPrincipal(context: TenantContext): Promise<string> {
+ const { binding } = await tenantAccess(context);
+ const digest = createHash("sha256").update(JSON.stringify([binding.tenantId, binding.principalId])).digest("hex");
+ return "tenant:" + digest;
+}
diff --git a/lib/tenancy/capability.ts b/lib/tenancy/capability.ts
new file mode 100644
index 00000000..6da24e91
--- /dev/null
+++ b/lib/tenancy/capability.ts
@@ -0,0 +1,15 @@
+import { tenantPrincipal, TenantDenied, type TenantContext } from "./authority";
+import { tenantPreviewEnabled } from "./mode";
+import { invokeTenantMemory } from "./public-memory";
+import { tenantMemoryTool } from "./memory-tools";
+
+export async function tenantCapabilityPlan(context: TenantContext | undefined, tool: string) {
+ if (!tenantPreviewEnabled()) {
+ if (context) throw new TenantDenied("tenant context is disabled");
+ return null;
+ }
+ if (!context) throw new TenantDenied("tenant context is required");
+ const principal = await tenantPrincipal(context);
+ if (!tenantMemoryTool(tool)) throw new TenantDenied("capability is not implemented for tenant preview");
+ return { principal, run: (args: Record<string, unknown>) => invokeTenantMemory(context, tool, args) };
+}
diff --git a/lib/tenancy/configured-runtime.test.ts b/lib/tenancy/configured-runtime.test.ts
new file mode 100644
index 00000000..b7d4fc57
--- /dev/null
+++ b/lib/tenancy/configured-runtime.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import { createConfiguredTenantRuntime } from "./configured-runtime";
+import { tenantAccess } from "./authority";
+import { tenantFile } from "./persistence-file";
+import { alice, fixture } from "./persistence-test-fixtures";
+import type { TenantPublicMemoryPort } from "./types";
+const cleanups: Array<() => Promise<void>> = [];
+afterEach(async () => { vi.restoreAllMocks(); for (const cleanup of cleanups.splice(0)) await cleanup(); });
+async function setup() {
+ const f = await fixture(); cleanups.push(f.cleanup);
+ let enabled = true, selectedRoot = f.root;
+ const b = (await f.store.registry.resolve(alice))!;
+ const token = { expiresAt: alice.expiresAt, tenantBinding: { version: 1, issuer: alice.issuer, subject: alice.subject,
+ tenantId: b.tenantId, principalId: b.principalId, mappingRevision: b.mappingRevision } };
+ const runtime = await createConfiguredTenantRuntime({ storageRoot: f.root, enabled: () => enabled,
+ selectedRoot: () => selectedRoot, verifyAccessToken: async raw => raw === "fixture" ? token : null });
+ const context = (await runtime.authenticateBearer("fixture"))!, access = await tenantAccess(context);
+ return { ...f, runtime, access, disable: () => { enabled = false; }, changeRoot: () => { selectedRoot = f.root + "-other"; } };
+}
+it("does not open or create tenant storage when disabled", async () => {
+ const open = vi.spyOn(fs, "open");
+ await expect(createConfiguredTenantRuntime({ storageRoot: "/not-a-configured-tenant-root", enabled: () => false,
+ selectedRoot: () => undefined, verifyAccessToken: async () => null })).rejects.toThrow();
+ expect(open).not.toHaveBeenCalled();
+});
+it.each(["disable", "changeRoot"] as const)("denies a queued mutation after %s", async change => {
+ const f = await setup(), file = await tenantFile(f.root);
+ let release!: () => void, entered!: () => void;
+ const wait = new Promise<void>(resolve => { release = resolve; }), held = new Promise<void>(resolve => { entered = resolve; });
+ const holding = file.transaction(async () => { entered(); await wait; });
+ await held;
+ const pending = (f.access.storage as TenantPublicMemoryPort).operateMemory({ identity: f.access.identity, binding: f.access.binding },
+ "agent_memory_remember", { document: "MEMORY.md", key: "blocked", value: "not committed" });
+ const refused = expect(pending).rejects.toThrow("configuration changed");
+ await new Promise(resolve => setTimeout(resolve, 25));
+ f[change](); release(); await holding; await refused;
+ expect(await f.store.administration.status()).toEqual({ revision: 2, auditEntries: 2 });
+});
+it("checks configuration again immediately before publishing staged bytes", async () => {
+ const f = await setup(), open = fs.open.bind(fs);
+ vi.spyOn(fs, "open").mockImplementation(async (...args) => {
+ const handle = await open(...args);
+ if (String(args[0]).endsWith(".tmp")) {
+ const sync = handle.sync.bind(handle);
+ handle.sync = async () => { await sync(); f.disable(); };
+ }
+ return handle;
+ });
+ await expect((f.access.storage as TenantPublicMemoryPort).operateMemory({ identity: f.access.identity, binding: f.access.binding },
+ "agent_memory_remember", { document: "MEMORY.md", key: "blocked", value: "not committed" })).rejects.toThrow("configuration changed");
+ vi.restoreAllMocks();
+ expect(await f.store.administration.status()).toEqual({ revision: 2, auditEntries: 2 });
+});
+it("rejects root replacement while a request waits for the old lock", async () => {
+ const f = await setup(), file = await tenantFile(f.root);
+ let release!: () => void, entered!: () => void;
+ const wait = new Promise<void>(resolve => { release = resolve; }), held = new Promise<void>(resolve => { entered = resolve; });
+ const holding = file.transaction(async () => { entered(); await wait; });
+ await held;
+ const pending = (f.access.storage as TenantPublicMemoryPort).operateMemory({ identity: f.access.identity, binding: f.access.binding },
+ "agent_memory_remember", { document: "MEMORY.md", key: "blocked", value: "not committed" });
+ const refused = expect(pending).rejects.toThrow("invalid tenant root");
+ await new Promise(resolve => setTimeout(resolve, 25));
+ await fs.rename(f.root, f.root + "-old"); await fs.mkdir(f.root, { mode: 0o700 });
+ cleanups.push(() => fs.rm(f.root + "-old", { recursive: true, force: true }));
+ release(); await holding; await refused;
+ expect(await fs.readdir(f.root)).toEqual([]);
+ expect(JSON.parse(await fs.readFile(f.root + "-old/state.json", "utf8")).revision).toBe(2);
+});
diff --git a/lib/tenancy/configured-runtime.ts b/lib/tenancy/configured-runtime.ts
new file mode 100644
index 00000000..ad91ed39
--- /dev/null
+++ b/lib/tenancy/configured-runtime.ts
@@ -0,0 +1,29 @@
+import { TenantDenied } from "./authority";
+import { openTenantPersistence } from "./persistence";
+import { createTenantRuntime, type VerifiedTenantToken } from "./runtime-factory";
+
+export async function createConfiguredTenantRuntime(config: {
+ storageRoot: string;
+ enabled: () => boolean;
+ selectedRoot: () => string | undefined;
+ verifyAccessToken: (bearer: string) => Promise<VerifiedTenantToken | null>;
+}) {
+ const root = config.storageRoot;
+ const selected = () => {
+ if (!config.enabled() || config.selectedRoot() !== root) throw new TenantDenied("tenant runtime configuration changed");
+ };
+ selected();
+ const backend = await openTenantPersistence({ root, initialize: false, guard: selected });
+ selected();
+ return createTenantRuntime({
+ enabled: config.enabled,
+ verifyAccessToken: config.verifyAccessToken,
+ storage: backend.storage,
+ registry: { resolve: async identity => {
+ selected();
+ const binding = await backend.registry.resolve(identity);
+ selected();
+ return binding;
+ } },
+ });
+}
diff --git a/lib/tenancy/credentials.test.ts b/lib/tenancy/credentials.test.ts
new file mode 100644
index 00000000..5e748ada
--- /dev/null
+++ b/lib/tenancy/credentials.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+import { parseTenantCredential, tenantCredentialFields } from "./credentials";
+const stamp = { version: 1, issuer: "issuer-a", subject: "alice", tenantId: "tenant-a", principalId: "person-a", mappingRevision: 7 } as const;
+describe("versioned server-owned tenant credential binding", () => {
+ it("copies and freezes every binding field without normalization", () => {
+ const source = { ...stamp };
+ const parsed = parseTenantCredential(source);
+ expect(parsed).toEqual(source); expect(parsed).not.toBe(source); expect(Object.isFrozen(parsed)).toBe(true);
+ expect(tenantCredentialFields({})).toEqual({});
+ });
+ it.each([null, [], {}, "alice", { ...stamp, version: 2 }, { ...stamp, issuer: "" },
+ { ...stamp, subject: "../alice" }, { ...stamp, tenantId: "" }, { ...stamp, principalId: "" },
+ { ...stamp, mappingRevision: 0 }, { ...stamp, mappingRevision: 1.5 },
+ { ...stamp, mappingRevision: Number.MAX_SAFE_INTEGER + 1 }, { ...stamp, extra: "forged" }])("rejects malformed binding %j", value => {
+ expect(() => parseTenantCredential(value)).toThrow();
+ });
+ it.each(["alice", null, "", 0])("does not upgrade deprecated subject-only marker %j", tenantSubject => {
+ expect(() => tenantCredentialFields({ tenantSubject })).toThrow("unversioned");
+ expect(() => tenantCredentialFields({ tenantSubject, tenantBinding: stamp })).toThrow("unversioned");
+ });
+ it.each([null, [], {}, { ...stamp, version: 9 }])("never erases a malformed tenant marker %j", tenantBinding => {
+ expect(() => tenantCredentialFields({ tenantBinding })).toThrow();
+ });
+});
diff --git a/lib/tenancy/credentials.ts b/lib/tenancy/credentials.ts
new file mode 100644
index 00000000..4e68049d
--- /dev/null
+++ b/lib/tenancy/credentials.ts
@@ -0,0 +1,25 @@
+import { TenantDenied } from "./authority";
+import type { TenantBinding, TenantCredentialBinding } from "./types";
+
+const id = (v: unknown): v is string => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(v);
+const fields = ["version", "issuer", "subject", "tenantId", "principalId", "mappingRevision"];
+export function parseTenantCredential(value: unknown): Readonly<TenantCredentialBinding> {
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TenantDenied("invalid tenant credential binding");
+ const v = value as Record<string, unknown>;
+ if (Object.keys(v).some(key => !fields.includes(key)) || v.version !== 1
+ || !id(v.issuer) || !id(v.subject) || !id(v.tenantId) || !id(v.principalId)
+ || !Number.isSafeInteger(v.mappingRevision) || Number(v.mappingRevision) < 1) {
+ throw new TenantDenied("invalid tenant credential binding");
+ }
+ return Object.freeze({ version: 1, issuer: v.issuer, subject: v.subject, tenantId: v.tenantId,
+ principalId: v.principalId, mappingRevision: v.mappingRevision as number });
+}
+export function tenantCredentialFields(record: { tenantSubject?: unknown; tenantBinding?: unknown }): { tenantBinding?: Readonly<TenantCredentialBinding> } {
+ // Subject-only records have no approved generation and cannot be grandfathered.
+ if (record.tenantSubject !== undefined) throw new TenantDenied("unversioned tenant credential");
+ return record.tenantBinding === undefined ? {} : { tenantBinding: parseTenantCredential(record.tenantBinding) };
+}
+export function credentialMatchesBinding(stamp: Readonly<TenantCredentialBinding>, binding: Readonly<TenantBinding>) {
+ return binding.enabled === true && binding.tenantEnabled === true && stamp.tenantId === binding.tenantId
+ && stamp.principalId === binding.principalId && stamp.mappingRevision === binding.mappingRevision;
+}
diff --git a/lib/tenancy/memory-ledger.test.ts b/lib/tenancy/memory-ledger.test.ts
new file mode 100644
index 00000000..b085c5c1
--- /dev/null
+++ b/lib/tenancy/memory-ledger.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vitest";
+import { randomUUID } from "node:crypto";
+import { applyMemoryTool, validateTenantLedger } from "./memory-ledger";
+import { validateMemoryArguments } from "./memory-tools";
+import type { AgentMemoryLedger } from "@/lib/agent/memory-types";
+const now = "2026-01-01T00:00:00.000Z";
+function ledger() {
+ const value: AgentMemoryLedger = { schemaVersion: 1, updatedAt: now, records: [] };
+ for (const key of ["one", "two"]) applyMemoryTool(value, "agent_memory_remember",
+ validateMemoryArguments("agent_memory_remember", { document: "MEMORY.md", key, value: key }), now);
+ return value;
+}
+describe("strict tenant claim ledger", () => {
+ it("validates a generated typed ledger", () => { expect(validateTenantLedger(ledger()).records).toHaveLength(2); });
+ it.each(["duplicate-id", "unknown-field", "unknown-provenance", "bad-confidence", "bad-date", "bad-kind",
+ "bad-sensitivity", "nul-key", "foreign-supersedes", "foreign-supersededBy", "missing-reference", "future-created"])("rejects %s", kind => {
+ const value = ledger(), r = value.records[1];
+ if (kind === "duplicate-id") r.id = value.records[0].id;
+ if (kind === "unknown-field") Object.assign(r, { token: "synthetic" });
+ if (kind === "unknown-provenance") Object.assign(r.provenance, { subject: "other" });
+ if (kind === "bad-confidence") r.confidence = NaN;
+ if (kind === "bad-date") r.validUntil = "2025-01-01T00:00:00.000Z";
+ if (kind === "bad-kind") Object.assign(r, { kind: "unknown" });
+ if (kind === "bad-sensitivity") Object.assign(r, { sensitivity: null });
+ if (kind === "nul-key") r.key = "bad\u0000key";
+ if (kind === "foreign-supersedes") r.supersedes = [value.records[0].id];
+ if (kind === "foreign-supersededBy") r.supersededBy = value.records[0].id;
+ if (kind === "missing-reference") r.supersedes = ["mem_" + randomUUID()];
+ if (kind === "future-created") r.createdAt = "2030-01-01T00:00:00.000Z";
+ expect(() => validateTenantLedger(value)).toThrow();
+ });
+ it("bounds total record count", () => {
+ const value = ledger();
+ value.records = Array.from({ length: 257 }, () => ({ ...value.records[0], id: "mem_" + randomUUID() }));
+ expect(() => validateTenantLedger(value)).toThrow();
+ });
+ it("bounds cumulative document text including history", () => {
+ const value = ledger();
+ value.records = Array.from({ length: 8 }, (_, i) => ({ ...value.records[0], id: "mem_" + randomUUID(), key: "key-" + i, value: "x".repeat(8192) }));
+ expect(() => validateTenantLedger(value)).toThrow();
+ });
+ it("bounds encoded claim history even when displayed text is short", () => {
+ const value = ledger();
+ value.records = Array.from({ length: 256 }, () => ({ ...value.records[0], id: "mem_" + randomUUID() }));
+ for (let i = 1; i < value.records.length; i++) value.records[i].supersedes = value.records.slice(0, i).map(r => r.id);
+ expect(() => validateTenantLedger(value)).toThrow();
+ });
+ it("deduplicates an ordinary repeated replace without discarding explicit claims", () => {
+ const value = ledger(), args = { document: "MEMORY.md", key: "one", value: "one" };
+ applyMemoryTool(value, "agent_memory_remember", validateMemoryArguments("agent_memory_remember", args), now);
+ expect(value.records).toHaveLength(2);
+ applyMemoryTool(value, "agent_memory_remember", validateMemoryArguments("agent_memory_remember", { ...args, mode: "claim" }), now);
+ expect(value.records).toHaveLength(3);
+ });
+});
diff --git a/lib/tenancy/memory-ledger.ts b/lib/tenancy/memory-ledger.ts
new file mode 100644
index 00000000..0cbc3e02
--- /dev/null
+++ b/lib/tenancy/memory-ledger.ts
@@ -0,0 +1,82 @@
+import { randomUUID } from "node:crypto";
+import { recordCanBeEffectiveAtOrAfter, recordEffectiveAt, resolveMemoryKey, resolveMemoryLedger } from "@/lib/agent/memory-resolution";
+import { queryMemoryLedger } from "@/lib/agent/memory-query";
+import type { AgentMemoryDocument, AgentMemoryKind, AgentMemoryLedger, AgentMemoryRecord, AgentMemorySensitivity } from "@/lib/agent/memory-types";
+import { TenantMemoryInputError, type TenantMemoryTool } from "./memory-tools";
+
+export const TENANT_LEDGER_KEY = "CLAIMS.v1";
+export const MAX_TENANT_LEDGER_BYTES = 512 * 1024;
+const object = (v: unknown): v is Record<string, unknown> => Boolean(v && typeof v === "object" && !Array.isArray(v));
+const exact = (v: object, fields: string[]) => Object.keys(v).every(key => fields.includes(key));
+const iso = (v: unknown): v is string => typeof v === "string" && v.length <= 32 && Number.isFinite(Date.parse(v)) && new Date(v).toISOString() === v;
+const id = (v: unknown): v is string => typeof v === "string" && /^mem_[0-9a-f-]{36}$/.test(v);
+export function validateTenantLedger(value: unknown): AgentMemoryLedger {
+ const fail = (): never => { throw new Error("invalid tenant claim ledger"); };
+ if (!object(value) || !exact(value, ["schemaVersion", "updatedAt", "records"]) || value.schemaVersion !== 1
+ || !iso(value.updatedAt) || !Array.isArray(value.records) || value.records.length > 256) return fail();
+ const ledger = value as unknown as AgentMemoryLedger;
+ const ids = new Set<string>(), bytes = { "USER.md": 0, "MEMORY.md": 0 };
+ for (const r of ledger.records) {
+ if (!object(r) || !exact(r, ["id", "document", "key", "value", "kind", "confidence", "sensitivity", "validFrom", "validUntil",
+ "createdAt", "provenance", "supersedes", "supersededAt", "supersededBy", "retractedAt"])
+ || !id(r.id) || ids.has(r.id) || !["USER.md", "MEMORY.md"].includes(r.document)
+ || typeof r.key !== "string" || !/^[^\r\n\0]{1,80}$/.test(r.key) || r.key.startsWith("#")
+ || typeof r.value !== "string" || !r.value || Buffer.byteLength(r.value) > 8192
+ || !["semantic", "episodic", "procedural"].includes(r.kind) || !["normal", "private", "restricted"].includes(r.sensitivity)
+ || !Number.isFinite(r.confidence) || r.confidence < 0 || r.confidence > 1 || !iso(r.createdAt) || !iso(r.validFrom)
+ || (r.validUntil !== undefined && (!iso(r.validUntil) || Date.parse(r.validUntil) <= Date.parse(r.validFrom)))
+ || (r.supersededAt !== undefined && !iso(r.supersededAt)) || (r.retractedAt !== undefined && !iso(r.retractedAt))
+ || (r.supersededBy !== undefined && !id(r.supersededBy))
+ || (r.supersedes !== undefined && (!Array.isArray(r.supersedes) || r.supersedes.length > 256 || r.supersedes.some(x => !id(x))))
+ || !object(r.provenance) || !exact(r.provenance, ["authority", "channel", "observedAt"])
+ || r.provenance.authority !== "explicit" || r.provenance.channel !== "mcp" || !iso(r.provenance.observedAt)) return fail();
+ ids.add(r.id); bytes[r.document] += Buffer.byteLength("## " + r.key + "\n" + r.value + "\n\n");
+ }
+ if (Object.values(bytes).some(n => n > 65536) || Buffer.byteLength(JSON.stringify(ledger)) > MAX_TENANT_LEDGER_BYTES) return fail();
+ const records = new Map(ledger.records.map(r => [r.id, r]));
+ for (const r of ledger.records) {
+ if (Date.parse(r.createdAt) > Date.parse(ledger.updatedAt) || r.provenance.observedAt !== r.createdAt) return fail();
+ for (const ref of [...(r.supersedes ?? []), ...(r.supersededBy ? [r.supersededBy] : [])]) {
+ const target = records.get(ref);
+ if (!target || target.id === r.id || target.document !== r.document || target.key !== r.key) return fail();
+ }
+ }
+ return ledger;
+}
+export function memorySnapshot(ledger: AgentMemoryLedger, at = new Date().toISOString()) {
+ const docs: Record<AgentMemoryDocument, string[]> = { "USER.md": [], "MEMORY.md": [] };
+ for (const { record } of resolveMemoryLedger(ledger, at)) docs[record.document].push("## " + record.key + "\n" + record.value);
+ const text = (document: AgentMemoryDocument) => docs[document].length ? docs[document].join("\n\n") + "\n" : "";
+ return { capturedAt: at, user: text("USER.md"), memory: text("MEMORY.md"), schemaVersion: 1, recordCount: ledger.records.length };
+}
+export function applyMemoryTool(ledger: AgentMemoryLedger, tool: TenantMemoryTool, a: Readonly<Record<string, unknown>>, now: string) {
+ if (tool === "agent_memory_read") return memorySnapshot(ledger, now);
+ if (tool === "agent_memory_search") return queryMemoryLedger(ledger, { query: a.query as string | undefined,
+ document: a.document as AgentMemoryDocument | undefined, kind: a.kind as AgentMemoryKind | undefined,
+ at: a.at as string | undefined, limit: a.limit as number | undefined, includeHistory: a.include_history === true });
+ const document = a.document as AgentMemoryDocument, key = (a.key as string).trim();
+ if (tool === "agent_memory_forget") {
+ for (const r of ledger.records) if (r.document === document && r.key === key && recordCanBeEffectiveAtOrAfter(r, now)) r.retractedAt = now;
+ } else {
+ const validFrom = a.valid_from === undefined ? now : new Date(a.valid_from as string).toISOString();
+ const validUntil = a.valid_until === undefined ? undefined : new Date(a.valid_until as string).toISOString();
+ if (validUntil && Date.parse(validUntil) <= Date.parse(validFrom)) throw new TenantMemoryInputError("invalid tenant memory validity interval");
+ const r: AgentMemoryRecord = { id: "mem_" + randomUUID(), document, key, value: (a.value as string).trim(),
+ kind: (a.kind as AgentMemoryKind | undefined) ?? "semantic", confidence: Math.round(((a.confidence as number | undefined) ?? 1) * 1000) / 1000,
+ sensitivity: (a.sensitivity as AgentMemorySensitivity | undefined) ?? "normal", validFrom, ...(validUntil ? { validUntil } : {}), createdAt: now,
+ provenance: { authority: "explicit", channel: "mcp", observedAt: now } };
+ const current = resolveMemoryKey(ledger, document, key, now)?.record;
+ const mode = a.mode ?? "replace";
+ if (mode === "replace" && a.valid_from === undefined && a.valid_until === undefined && current
+ && current.value === r.value && current.kind === r.kind && current.confidence === r.confidence && current.sensitivity === r.sensitivity) return memorySnapshot(ledger, now);
+ if (mode === "replace") {
+ const old = ledger.records.filter(v => v.document === document && v.key === key && recordEffectiveAt(v, validFrom));
+ if (old.length) r.supersedes = old.map(v => v.id);
+ for (const v of old) { v.supersededAt = validFrom; v.supersededBy = r.id; }
+ }
+ ledger.records.push(r);
+ }
+ ledger.updatedAt = now;
+ validateTenantLedger(ledger);
+ return memorySnapshot(ledger, now);
+}
diff --git a/lib/tenancy/memory-tools.ts b/lib/tenancy/memory-tools.ts
new file mode 100644
index 00000000..08add14c
--- /dev/null
+++ b/lib/tenancy/memory-tools.ts
@@ -0,0 +1,35 @@
+export const TENANT_MEMORY_TOOLS = ["agent_memory_read", "agent_memory_search", "agent_memory_remember", "agent_memory_forget"] as const;
+export type TenantMemoryTool = typeof TENANT_MEMORY_TOOLS[number];
+export class TenantMemoryInputError extends Error {}
+export function tenantMemoryTool(value: string): value is TenantMemoryTool {
+ return (TENANT_MEMORY_TOOLS as readonly string[]).includes(value);
+}
+const keys: Record<TenantMemoryTool, readonly string[]> = {
+ agent_memory_read: [],
+ agent_memory_search: ["query", "document", "kind", "at", "limit", "include_history"],
+ agent_memory_remember: ["document", "key", "value", "kind", "confidence", "sensitivity", "valid_from", "valid_until", "mode"],
+ agent_memory_forget: ["document", "key"],
+};
+export function validateMemoryArguments(tool: TenantMemoryTool, input: Record<string, unknown>) {
+ const fail = (field: string): never => { throw new TenantMemoryInputError("invalid tenant memory " + field); };
+ if (!input || typeof input !== "object" || Array.isArray(input)) fail("arguments");
+ if (Object.keys(input).some(key => !keys[tool].includes(key))) fail("argument or routing selector");
+ const a = { ...input };
+ const option = (key: string, allowed: readonly unknown[]) => {
+ if (a[key] !== undefined && !allowed.includes(a[key])) fail(key);
+ };
+ option("document", ["USER.md", "MEMORY.md"]); option("kind", ["semantic", "episodic", "procedural"]);
+ option("sensitivity", ["normal", "private", "restricted"]); option("mode", ["replace", "claim"]);
+ if (a.key !== undefined && (typeof a.key !== "string" || !/^[^\r\n\0]{1,80}$/.test(a.key.trim()) || a.key.trim().startsWith("#"))) fail("key");
+ if (a.value !== undefined && (typeof a.value !== "string" || !a.value.trim() || Buffer.byteLength(a.value.trim()) > 8192)) fail("value");
+ if (a.confidence !== undefined && (typeof a.confidence !== "number" || !Number.isFinite(a.confidence) || a.confidence < 0 || a.confidence > 1)) fail("confidence");
+ for (const key of ["at", "valid_from", "valid_until"]) {
+ if (a[key] !== undefined && (typeof a[key] !== "string" || a[key].length > 64 || !Number.isFinite(Date.parse(a[key])))) fail(key);
+ }
+ if (a.query !== undefined && (typeof a.query !== "string" || Buffer.byteLength(a.query) > 2048)) fail("query");
+ if (a.limit !== undefined && (typeof a.limit !== "number" || !Number.isInteger(a.limit) || a.limit < 1 || a.limit > 100)) fail("limit");
+ if (a.include_history !== undefined && typeof a.include_history !== "boolean") fail("include_history");
+ const required = tool === "agent_memory_remember" ? ["document", "key", "value"] : tool === "agent_memory_forget" ? ["document", "key"] : [];
+ if (required.some(key => a[key] === undefined)) fail("required arguments");
+ return Object.freeze(a);
+}
diff --git a/lib/tenancy/memory-write.ts b/lib/tenancy/memory-write.ts
new file mode 100644
index 00000000..d47d7afc
--- /dev/null
+++ b/lib/tenancy/memory-write.ts
@@ -0,0 +1,17 @@
+import { tenantAccess, TenantDenied, type TenantContext } from "./authority";
+import { memoryKey, revision, validText } from "./persistence-schema";
+import type { TenantMemoryWritePort } from "./types";
+
+/** Internal seam: no public tenant write tool is enabled until its protocol/audit contract is reviewed. */
+export async function writeTenantMemory(context: TenantContext, key: "USER.md" | "MEMORY.md", value: string,
+ expectedStoreRevision: number, expectedDocumentVersion: number) {
+ if (!memoryKey(key) || !validText(value) || !revision(expectedStoreRevision) || !revision(expectedDocumentVersion)) {
+ throw new TenantDenied();
+ }
+ const access = await tenantAccess(context);
+ const port = access.storage as Partial<TenantMemoryWritePort>;
+ if (typeof port.writeMemory !== "function") throw new TenantDenied("tenant memory writes are not configured");
+ // The persistent adapter checks this grant again inside its write/revocation transaction.
+ return port.writeMemory({ identity: access.identity, binding: access.binding }, key, value,
+ expectedStoreRevision, expectedDocumentVersion);
+}
diff --git a/lib/tenancy/mode.ts b/lib/tenancy/mode.ts
new file mode 100644
index 00000000..1e8f6877
--- /dev/null
+++ b/lib/tenancy/mode.ts
@@ -0,0 +1,8 @@
+import { TenantDenied } from "./authority";
+
+export function tenantPreviewEnabled(): boolean {
+ const mode = process.env.OS_TENANCY_MODE;
+ if (mode === undefined || mode === "" || mode === "legacy") return false;
+ if (mode === "tenant-preview") return true;
+ throw new TenantDenied("invalid tenancy mode");
+}
diff --git a/lib/tenancy/persistence-boundary.test.ts b/lib/tenancy/persistence-boundary.test.ts
new file mode 100644
index 00000000..b93170a9
--- /dev/null
+++ b/lib/tenancy/persistence-boundary.test.ts
@@ -0,0 +1,109 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { promises as fs } from "node:fs";
+import { openTenantPersistence } from "./persistence";
+import { createTenantAuthority } from "./authority";
+import { readTenantMemory } from "./storage";
+import { MAX_AUDIT, MAX_STORE_BYTES } from "./persistence-schema";
+import { alice, bindingA, fixture } from "./persistence-test-fixtures";
+
+const cleanups: Array<() => Promise<void>> = [];
+async function setup() { const f = await fixture(); cleanups.push(f.cleanup); return f; }
+afterEach(async () => { for (const cleanup of cleanups.splice(0)) await cleanup(); });
+describe("tenant persistence fail-closed boundary", () => {
+ it.each(["", ".", "/", "/tmp/../tmp"])("requires an explicit canonical root: %s", async root => {
+ await expect(openTenantPersistence({ root })).rejects.toThrow();
+ });
+ it("rejects symlink roots without creating files", async () => {
+ const f = await setup();
+ const alias = f.root + "-alias";
+ await fs.symlink(f.root, alias);
+ cleanups.push(() => fs.unlink(alias));
+ await expect(openTenantPersistence({ root: alias })).rejects.toThrow("symlinks");
+ });
+ it("rejects changed root identity", async () => {
+ const f = await setup();
+ await fs.rename(f.root, f.root + "-original");
+ cleanups.push(() => fs.rm(f.root + "-original", { recursive: true, force: true }));
+ await fs.mkdir(f.root, { mode: 0o700 });
+ await expect(f.store.administration.status()).rejects.toThrow("invalid tenant root");
+ expect(await fs.readdir(f.root)).toEqual([]);
+ });
+ it.each(["symlink", "hardlink", "directory", "loose-mode"])("rejects an unsafe state leaf: %s", async kind => {
+ const f = await setup();
+ await fs.rename(f.root + "/state.json", f.root + "/preserved.json");
+ if (kind === "symlink") await fs.symlink("preserved.json", f.root + "/state.json");
+ if (kind === "hardlink") await fs.link(f.root + "/preserved.json", f.root + "/state.json");
+ if (kind === "directory") await fs.mkdir(f.root + "/state.json", { mode: 0o700 });
+ if (kind === "loose-mode") {
+ await fs.copyFile(f.root + "/preserved.json", f.root + "/state.json");
+ await fs.chmod(f.root + "/state.json", 0o644);
+ }
+ await expect(f.store.administration.status()).rejects.toThrow();
+ });
+ it("rejects an overly permissive synthetic root", async () => {
+ const f = await setup();
+ await fs.chmod(f.root, 0o755);
+ await expect(f.store.administration.status()).rejects.toThrow();
+ });
+ it.each(["truncated", "unknown-schema", "duplicate-binding", "duplicate-memory", "extra-field", "invalid-boolean",
+ "unsafe-revision", "invalid-utf8", "inconsistent-tenant"])("rejects corrupted state: %s", async kind => {
+ const f = await setup();
+ const state = JSON.parse(await fs.readFile(f.root + "/state.json", "utf8"));
+ if (kind === "unknown-schema") state.schema = 2;
+ if (kind === "duplicate-binding") state.bindings.push(state.bindings[0]);
+ if (kind === "duplicate-memory") state.memory = Array(2).fill({
+ tenantId: "tenant-a", principalId: "person-a", mappingRevision: 1, collection: "memory", key: "USER.md", value: "", version: 1,
+ });
+ if (kind === "extra-field") state.audit[0].secret = "should-never-load";
+ if (kind === "invalid-boolean") state.bindings[0].enabled = "true";
+ if (kind === "unsafe-revision") state.revision = Number.MAX_SAFE_INTEGER + 1;
+ if (kind === "inconsistent-tenant") state.bindings.push({ ...state.bindings[0], subject: "peer", principalId: "peer", tenantEnabled: false });
+ let bytes: string | Buffer = JSON.stringify(state);
+ if (kind === "truncated") bytes = bytes.slice(0, -1);
+ if (kind === "invalid-utf8") bytes = Buffer.concat([Buffer.from('{"bad":"'), Buffer.from([0xc3, 0x28]), Buffer.from('"}')]);
+ await fs.writeFile(f.root + "/state.json", bytes);
+ await expect(openTenantPersistence({ root: f.root, initialize: true })).rejects.toThrow();
+ await expect(f.store.registry.resolve(alice)).rejects.toThrow();
+ });
+ it("bounds bytes before parsing", async () => {
+ const f = await setup();
+ await fs.truncate(f.root + "/state.json", MAX_STORE_BYTES + 1);
+ await expect(f.store.administration.status()).rejects.toThrow("invalid tenant state file");
+ });
+ it("audit exhaustion denies tenant access while retaining administrative reconciliation", async () => {
+ const f = await setup();
+ const state = JSON.parse(await fs.readFile(f.root + "/state.json", "utf8"));
+ for (let i = 3; i <= MAX_AUDIT; i++) state.audit.push({ ...state.audit[0], id: "event-" + i, revision: i });
+ state.revision = MAX_AUDIT;
+ await fs.writeFile(f.root + "/state.json", JSON.stringify(state));
+ await expect(createTenantAuthority(f.store.registry, f.store.storage).authenticate(alice)).rejects.toThrow("capacity");
+ await expect(readTenantMemory(f.contextA)).rejects.toThrow("capacity");
+ await expect(f.store.administration.setBinding(alice, { ...bindingA, enabled: false }, MAX_AUDIT)).rejects.toThrow("capacity");
+ expect(await f.store.administration.operationStatus("event-" + MAX_AUDIT)).toMatchObject({ revision: MAX_AUDIT });
+ });
+ it("closes tenant reads near byte capacity before revocation space is exhausted", async () => {
+ const f = await setup();
+ const state = JSON.parse(await fs.readFile(f.root + "/state.json", "utf8"));
+ state.revision = 254;
+ for (let i = 3; i <= 254; i++) state.audit.push({ ...state.audit[0], id: "event-" + i, revision: i });
+ state.memory = Array.from({ length: 254 }, (_, i) => ({
+ tenantId: "historical-" + i, principalId: "p", mappingRevision: 1,
+ collection: "memory", key: "MEMORY.md", value: "x".repeat(65536), version: 1,
+ }));
+ const bytes = JSON.stringify(state);
+ expect(Buffer.byteLength(bytes)).toBeGreaterThan(MAX_STORE_BYTES - 131072);
+ expect(Buffer.byteLength(bytes)).toBeLessThan(MAX_STORE_BYTES);
+ await fs.writeFile(f.root + "/state.json", bytes);
+ await expect(readTenantMemory(f.contextA)).rejects.toThrow("capacity");
+ await f.store.administration.setBinding(alice, { ...bindingA, enabled: false }, 254);
+ expect((await f.store.administration.status()).revision).toBe(255);
+ });
+ it("projects control-plane inputs rather than persisting injected subject or payload fields", async () => {
+ const f = await setup();
+ await f.store.administration.setBinding(alice, { ...bindingA, issuer: "attacker", subject: "other", token: "fake-secret" } as typeof bindingA, 2);
+ const state = await fs.readFile(f.root + "/state.json", "utf8");
+ expect(state).not.toContain("fake-secret");
+ expect(state).not.toContain("attacker");
+ expect(await f.store.registry.resolve(alice)).toMatchObject({ mappingRevision: 3 });
+ });
+});
diff --git a/lib/tenancy/persistence-concurrency.test.ts b/lib/tenancy/persistence-concurrency.test.ts
new file mode 100644
index 00000000..eb6a7fdf
--- /dev/null
+++ b/lib/tenancy/persistence-concurrency.test.ts
@@ -0,0 +1,73 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { tenantFile } from "./persistence-file";
+import { openTenantPersistence } from "./persistence";
+import { alice, bindingA, child, compileChild, fixture } from "./persistence-test-fixtures";
+
+const cleanup: Array<() => Promise<void>> = [];
+afterEach(async () => { for (const fn of cleanup.splice(0)) await fn(); });
+describe("tenant persistence cross-process ordering", () => {
+ it("allows exactly one process to commit the same expected revision", async () => {
+ const f = await fixture(); cleanup.push(f.cleanup);
+ const code = await fs.mkdtemp(path.join(os.tmpdir(), "mso-tenant-child-"));
+ cleanup.push(() => fs.rm(code, { recursive: true, force: true }));
+ await compileChild(code);
+ const script = `const {openTenantPersistence}=require(process.argv[1]); (async()=>{
+ const s=await openTenantPersistence({root:process.argv[2]});
+ try { await s.administration.setBinding({issuer:"fixture",subject:process.argv[3]},
+ {tenantId:"tenant-"+process.argv[3],principalId:"p",enabled:true,tenantEnabled:true},2); console.log("committed"); }
+ catch(e) { if(e.message.includes("revision conflict")) console.log("conflict"); else throw e; }
+ })().catch(e=>{console.error(e.message);process.exitCode=1});`;
+ const run = (who: string) => child(process.execPath, ["-e", script, code + "/tenancy/persistence.js", f.root, who], { timeout: 8000 });
+ const results = await Promise.all([run("one"), run("two")]);
+ expect(results.map(r => r.stdout.trim()).sort()).toEqual(["committed", "conflict"]);
+ expect(await f.store.administration.status()).toEqual({ revision: 3, auditEntries: 3 });
+ });
+ it("reloads a queued write after a barrier-controlled revocation commits", async () => {
+ const f = await fixture(); cleanup.push(f.cleanup);
+ const grant = { identity: alice, binding: (await f.store.registry.resolve(alice))! };
+ const disk = await tenantFile(f.root);
+ let release!: () => void;
+ let entered!: () => void;
+ const barrier = new Promise<void>(resolve => { release = resolve; });
+ const acquired = new Promise<void>(resolve => { entered = resolve; });
+ const revoking = disk.transaction(async (directory, sync) => {
+ const state = await disk.read(directory);
+ entered();
+ await barrier;
+ state.bindings[0].enabled = false;
+ state.bindings[0].mappingRevision = 3;
+ state.revision = 3;
+ state.audit.push({ id: "barrier-revocation", revision: 3, at: new Date().toISOString(),
+ tenantId: "tenant-a", principalId: "person-a", mappingRevision: 3, scope: "principal", action: "binding.changed" });
+ await disk.write(directory, sync, state, "barrier-revocation");
+ });
+ await acquired;
+ const pending = f.store.storage.writeMemory(grant, "MEMORY.md", "must-not-commit", 3, 0);
+ const refused = expect(pending).rejects.toThrow("tenant request denied");
+ await new Promise(resolve => setTimeout(resolve, 25));
+ release();
+ await revoking;
+ await refused;
+ const state = JSON.parse(await fs.readFile(f.root + "/state.json", "utf8"));
+ expect(state.memory).toEqual([]);
+ expect(state.revision).toBe(3);
+ });
+ it("does not steal an abandoned lock even when its timestamp is old", async () => {
+ const f = await fixture(); cleanup.push(f.cleanup);
+ await child(process.execPath, ["-e",
+ 'require("node:fs").writeFileSync(process.argv[1]+"/state.lock","",{flag:"wx",mode:0o600})', f.root], { timeout: 3000 });
+ await fs.utimes(f.root + "/state.lock", 1, 1);
+ await expect(f.store.administration.setBinding(alice, bindingA, 2)).rejects.toThrow("abandoned locks require reviewed recovery");
+ expect(JSON.parse(await fs.readFile(f.root + "/state.json", "utf8")).revision).toBe(2);
+ }, 6000);
+ it("does not recreate missing established state", async () => {
+ const f = await fixture(); cleanup.push(f.cleanup);
+ await fs.rename(f.root + "/state.json", f.root + "/preserved.json");
+ await expect(f.store.administration.status()).rejects.toThrow();
+ await expect(openTenantPersistence({ root: f.root })).rejects.toThrow();
+ await expect(fs.stat(f.root + "/state.json")).rejects.toThrow();
+ });
+});
diff --git a/lib/tenancy/persistence-fault.test.ts b/lib/tenancy/persistence-fault.test.ts
new file mode 100644
index 00000000..39a9daa8
--- /dev/null
+++ b/lib/tenancy/persistence-fault.test.ts
@@ -0,0 +1,66 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import { TenantCommitUncertain } from "./persistence-file";
+import { writeTenantMemory } from "./memory-write";
+import { readTenantMemory } from "./storage";
+import { fixture } from "./persistence-test-fixtures";
+
+const cleanups: Array<() => Promise<void>> = [];
+async function setup() { const f = await fixture(); cleanups.push(f.cleanup); return f; }
+afterEach(async () => { vi.restoreAllMocks(); for (const cleanup of cleanups.splice(0)) await cleanup(); });
+describe("atomic tenant data and audit commits", () => {
+ it("leaves old state intact when rename fails", async () => {
+ const f = await setup();
+ vi.spyOn(fs, "rename").mockRejectedValueOnce(new Error("synthetic rename failure"));
+ await expect(writeTenantMemory(f.contextA, "MEMORY.md", "must-not-commit", 2, 0)).rejects.toThrow("synthetic");
+ vi.restoreAllMocks();
+ expect((await f.store.administration.status()).revision).toBe(2);
+ expect((await readTenantMemory(f.contextA)).memory).toBe("");
+ expect((await fs.readdir(f.root)).sort()).toEqual(["state.json"]);
+ });
+ it("leaves old state intact when temporary file fsync fails", async () => {
+ const f = await setup();
+ const open = fs.open.bind(fs);
+ vi.spyOn(fs, "open").mockImplementation(async (...args) => {
+ const handle = await open(...args);
+ if (String(args[0]).endsWith(".tmp")) handle.sync = async () => { throw new Error("synthetic temp sync failure"); };
+ return handle;
+ });
+ await expect(writeTenantMemory(f.contextA, "MEMORY.md", "must-not-commit", 2, 0)).rejects.toThrow("synthetic");
+ vi.restoreAllMocks();
+ expect((await f.store.administration.status()).revision).toBe(2);
+ expect((await fs.readdir(f.root)).sort()).toEqual(["state.json"]);
+ });
+ it("reports an uncertain commit after rename if directory fsync fails, with reconcilable operation ID", async () => {
+ const f = await setup();
+ const open = fs.open.bind(fs);
+ vi.spyOn(fs, "open").mockImplementation(async (...args) => {
+ const handle = await open(...args);
+ if (String(args[0]) === f.root) handle.sync = async () => { throw new Error("synthetic directory sync failure"); };
+ return handle;
+ });
+ let error: unknown;
+ try { await writeTenantMemory(f.contextA, "MEMORY.md", "possibly-committed", 2, 0); } catch (e) { error = e; }
+ vi.restoreAllMocks();
+ expect(error).toBeInstanceOf(TenantCommitUncertain);
+ const event = await f.store.administration.operationStatus((error as TenantCommitUncertain).operationId);
+ expect(event).toMatchObject({ action: "memory.written", revision: 3 });
+ expect((await readTenantMemory(f.contextA)).memory).toBe("possibly-committed");
+ await expect(writeTenantMemory(f.contextA, "MEMORY.md", "blind-retry", 2, 0)).rejects.toThrow("revision conflict");
+ });
+ it("preserves committed outcome when lock cleanup fails", async () => {
+ const f = await setup();
+ const unlink = fs.unlink.bind(fs);
+ let error: unknown;
+ vi.spyOn(fs, "unlink").mockImplementation(async target => {
+ if (String(target).endsWith("/state.lock")) throw new Error("synthetic unlock failure");
+ await unlink(target);
+ });
+ try { await f.store.administration.setBinding({ issuer: "fixture", subject: "third" },
+ { tenantId: "third", principalId: "third", enabled: true, tenantEnabled: true }, 2); } catch (e) { error = e; }
+ vi.restoreAllMocks();
+ expect(error).toBeInstanceOf(TenantCommitUncertain);
+ await fs.unlink(f.root + "/state.lock"); // Exact synthetic lock from the injected failure.
+ expect(await f.store.administration.operationStatus((error as TenantCommitUncertain).operationId)).toMatchObject({ revision: 3 });
+ });
+});
diff --git a/lib/tenancy/persistence-file.ts b/lib/tenancy/persistence-file.ts
new file mode 100644
index 00000000..eef85c4d
--- /dev/null
+++ b/lib/tenancy/persistence-file.ts
@@ -0,0 +1,109 @@
+import { constants as C, promises as fs, type Stats } from "node:fs";
+import { randomUUID } from "node:crypto";
+import path from "node:path";
+import { performance } from "node:perf_hooks";
+import { MAX_STORE_BYTES, validateSnapshot, type TenantSnapshot } from "./persistence-schema";
+
+export class TenantStoreConflict extends Error {}
+export class TenantCommitUncertain extends Error {
+ constructor(readonly operationId: string) { super("tenant commit durability is uncertain; reconcile operation ID before retry"); }
+}
+type Pin = { dev: number; ino: number };
+const safeFile = (s: Stats) =>
+ s.isFile() && s.nlink === 1 && s.uid === process.getuid?.() && (s.mode & 0o777) === 0o600;
+export async function tenantFile(root: string) {
+ if (process.platform !== "linux" || !root || !path.isAbsolute(root) || path.resolve(root) !== root || root === "/") {
+ throw new Error("explicit canonical Linux tenant root required");
+ }
+ async function pin(expected?: Pin) {
+ if (await fs.realpath(root) !== root) throw new Error("tenant root must not contain symlinks");
+ const handle = await fs.open(root, C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW);
+ try {
+ const s = await handle.stat();
+ if (!s.isDirectory() || s.uid !== process.getuid?.() || (s.mode & 0o777) !== 0o700
+ || (expected && (s.dev !== expected.dev || s.ino !== expected.ino))) throw new Error("invalid tenant root");
+ return { handle, pin: { dev: s.dev, ino: s.ino }, directory: "/proc/self/fd/" + handle.fd };
+ } catch (error) { await handle.close(); throw error; }
+ }
+ const initial = await pin();
+ const identity = initial.pin;
+ await initial.handle.close();
+ async function transaction<T>(fn: (directory: string, sync: () => Promise<void>) => Promise<T>) {
+ const p = await pin(identity);
+ const lock = p.directory + "/state.lock";
+ let held: Awaited<ReturnType<typeof fs.open>> | undefined;
+ let result: T | undefined;
+ let failure: unknown;
+ let cleanupFailure: unknown;
+ try {
+ const deadline = performance.now() + 3000;
+ while (!held) {
+ try { held = await fs.open(lock, C.O_RDWR | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW, 0o600); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ if (performance.now() >= deadline) throw new Error("tenant store busy; abandoned locks require reviewed recovery");
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ }
+ const selected = await pin(identity);
+ await selected.handle.close();
+ result = await fn(p.directory, () => p.handle.sync());
+ } catch (error) { failure = error; }
+ finally {
+ try {
+ if (held) {
+ try {
+ const ours = await held.stat();
+ const current = await fs.lstat(lock);
+ if (current.ino !== ours.ino || current.dev !== ours.dev) throw new Error("tenant lock replaced");
+ await fs.unlink(lock);
+ } finally { await held.close(); }
+ }
+ } catch (error) { cleanupFailure = error; }
+ finally { await p.handle.close().catch(error => { cleanupFailure ??= error; }); }
+ }
+ if (failure) throw failure;
+ if (cleanupFailure) {
+ const operationId = (result as { operationId?: string } | undefined)?.operationId;
+ if (operationId) throw new TenantCommitUncertain(operationId);
+ throw cleanupFailure;
+ }
+ return result as T;
+ }
+
+ async function read(directory: string): Promise<TenantSnapshot> {
+ const handle = await fs.open(directory + "/state.json", C.O_RDONLY | C.O_NOFOLLOW | C.O_NONBLOCK);
+ try {
+ const stat = await handle.stat();
+ if (!safeFile(stat) || stat.size < 1 || stat.size > MAX_STORE_BYTES) throw new Error("invalid tenant state file");
+ const bytes = Buffer.alloc(stat.size + 1);
+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
+ if (bytesRead !== stat.size) throw new Error("tenant state changed during read");
+ return validateSnapshot(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, bytesRead))));
+ } finally { await handle.close(); }
+ }
+ async function write(directory: string, sync: () => Promise<void>, state: TenantSnapshot, operationId: string, guard?: () => void) {
+ validateSnapshot(state);
+ const bytes = JSON.stringify(state);
+ if (Buffer.byteLength(bytes) > MAX_STORE_BYTES) throw new Error("tenant store capacity reached");
+ const temporary = directory + "/state-" + randomUUID() + ".tmp";
+ const handle = await fs.open(temporary, C.O_WRONLY | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW, 0o600);
+ let renamed = false;
+ try {
+ await handle.writeFile(bytes, "utf8");
+ await handle.sync();
+ await handle.close();
+ guard?.();
+ await fs.rename(temporary, directory + "/state.json");
+ renamed = true;
+ await sync();
+ } catch (error) {
+ if (renamed) throw new TenantCommitUncertain(operationId);
+ throw error;
+ } finally {
+ await handle.close().catch(() => undefined);
+ if (!renamed) await fs.unlink(temporary).catch(() => undefined);
+ }
+ }
+ return { transaction, read, write };
+}
diff --git a/lib/tenancy/persistence-memory.ts b/lib/tenancy/persistence-memory.ts
new file mode 100644
index 00000000..8b38030f
--- /dev/null
+++ b/lib/tenancy/persistence-memory.ts
@@ -0,0 +1,47 @@
+import { TenantDenied } from "./authority";
+import { addressKey, sameBinding, subjectKey, validBinding, validSubject, type TenantSnapshot } from "./persistence-schema";
+import { applyMemoryTool, memorySnapshot, TENANT_LEDGER_KEY, validateTenantLedger } from "./memory-ledger";
+import type { TenantAddress, TenantGrant } from "./types";
+import type { TenantMemoryTool } from "./memory-tools";
+
+function address(grant: TenantGrant, key: string): TenantAddress {
+ return { tenantId: grant.binding.tenantId, principalId: grant.binding.principalId,
+ mappingRevision: grant.binding.mappingRevision, collection: "memory", key };
+}
+export function authorizeMemoryGrant(s: TenantSnapshot, grant: TenantGrant) {
+ if (!validSubject(grant.identity) || !validBinding(grant.binding)) throw new TenantDenied();
+ const live = s.bindings.find(b => subjectKey(b) === subjectKey(grant.identity));
+ if (!live || !sameBinding(live, grant.binding) || !live.enabled || !live.tenantEnabled
+ || !Number.isFinite(grant.identity.expiresAt) || grant.identity.expiresAt <= Date.now()) throw new TenantDenied();
+ return live;
+}
+export function rawMemoryValue(s: TenantSnapshot, scope: TenantAddress) {
+ return s.memory.find(m => addressKey(m) === addressKey(scope));
+}
+export function readMemoryValue(s: TenantSnapshot, scope: TenantAddress): string | null {
+ const row = rawMemoryValue(s, { ...scope, key: TENANT_LEDGER_KEY });
+ if (row && (scope.key === "USER.md" || scope.key === "MEMORY.md")) {
+ const view = memorySnapshot(validateTenantLedger(JSON.parse(row.value)));
+ return scope.key === "USER.md" ? view.user : view.memory;
+ }
+ return rawMemoryValue(s, scope)?.value ?? null;
+}
+export function executeMemoryOnSnapshot(s: TenantSnapshot, grant: TenantGrant, tool: TenantMemoryTool, args: Readonly<Record<string, unknown>>) {
+ const live = authorizeMemoryGrant(s, grant), now = new Date().toISOString();
+ const scope = address(grant, TENANT_LEDGER_KEY), old = rawMemoryValue(s, scope);
+ const user = rawMemoryValue(s, address(grant, "USER.md"))?.value ?? "";
+ const memory = rawMemoryValue(s, address(grant, "MEMORY.md"))?.value ?? "";
+ if (old && (user || memory)) throw new TenantDenied("ambiguous tenant memory storage");
+ if (!old && (user || memory)) {
+ if (tool === "agent_memory_read") return { result: { capturedAt: now, user, memory } };
+ throw new TenantDenied("raw tenant memory requires a separately reviewed import");
+ }
+ const ledger = old ? validateTenantLedger(JSON.parse(old.value)) : { schemaVersion: 1 as const, updatedAt: now, records: [] };
+ const result = applyMemoryTool(ledger, tool, args, now);
+ if (tool === "agent_memory_read" || tool === "agent_memory_search") return { result };
+ const value = JSON.stringify(validateTenantLedger(ledger));
+ if (old) { old.value = value; old.version += 1; }
+ else s.memory.push({ ...scope, value, version: 1 });
+ return { result, event: { tenantId: live.tenantId, principalId: live.principalId, mappingRevision: live.mappingRevision,
+ scope: "principal" as const, action: "memory.written" as const, key: args.document as string, tool } };
+}
diff --git a/lib/tenancy/persistence-schema.ts b/lib/tenancy/persistence-schema.ts
new file mode 100644
index 00000000..b62fef6b
--- /dev/null
+++ b/lib/tenancy/persistence-schema.ts
@@ -0,0 +1,70 @@
+import { MAX_TENANT_LEDGER_BYTES, TENANT_LEDGER_KEY, validateTenantLedger } from "./memory-ledger";
+import type { AuthenticatedSubject, TenantAddress, TenantBinding, TenantAuditEvent } from "./types";
+
+export const MAX_STORE_BYTES = 16 * 1024 * 1024;
+export const MAX_AUDIT = 10_000;
+export const validId = (v: unknown): v is string => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(v);
+export const revision = (v: unknown): v is number => Number.isSafeInteger(v) && Number(v) >= 0;
+export const memoryKey = (v: unknown): v is "USER.md" | "MEMORY.md" => v === "USER.md" || v === "MEMORY.md";
+export const validText = (v: unknown): v is string => typeof v === "string" && Buffer.byteLength(v, "utf8") <= 65536;
+export type SubjectKey = Pick<AuthenticatedSubject, "issuer" | "subject">;
+export type Membership = SubjectKey & TenantBinding;
+export type MemoryRecord = TenantAddress & { value: string; version: number };
+export type { TenantAuditEvent } from "./types";
+export type TenantSnapshot = {
+ schema: 1; revision: number; bindings: Membership[]; memory: MemoryRecord[]; audit: TenantAuditEvent[];
+};
+export function subjectKey(v: SubjectKey) { return JSON.stringify([v.issuer, v.subject]); }
+export function addressKey(v: TenantAddress) {
+ return JSON.stringify([v.tenantId, v.principalId, v.mappingRevision, v.collection, v.key]);
+}
+export function validSubject(v: SubjectKey) { return validId(v.issuer) && validId(v.subject); }
+export function validBinding(v: TenantBinding) {
+ return validId(v.tenantId) && validId(v.principalId) && revision(v.mappingRevision) && v.mappingRevision > 0
+ && typeof v.enabled === "boolean" && typeof v.tenantEnabled === "boolean";
+}
+export function sameBinding(a: TenantBinding, b: TenantBinding) {
+ return a.tenantId === b.tenantId && a.principalId === b.principalId && a.mappingRevision === b.mappingRevision
+ && a.enabled === b.enabled && a.tenantEnabled === b.tenantEnabled;
+}
+export function validAddress(v: TenantAddress) {
+ return validId(v.tenantId) && validId(v.principalId) && revision(v.mappingRevision) && v.mappingRevision > 0
+ && v.collection === "memory" && (memoryKey(v.key) || v.key === TENANT_LEDGER_KEY);
+}
+function storedMemory(m: MemoryRecord) {
+ if (m.key !== TENANT_LEDGER_KEY) return validText(m.value);
+ if (typeof m.value !== "string" || Buffer.byteLength(m.value) > MAX_TENANT_LEDGER_BYTES) return false;
+ try { validateTenantLedger(JSON.parse(m.value)); return true; } catch { return false; }
+}
+const object = (v: unknown): v is Record<string, unknown> => Boolean(v && typeof v === "object" && !Array.isArray(v));
+function keys(v: object, allowed: string[]) { return Object.keys(v).every(k => allowed.includes(k)); }
+function unique(values: string[]) { return new Set(values).size === values.length; }
+export function validateSnapshot(value: unknown): TenantSnapshot {
+ const fail = () => { throw new Error("invalid tenant persistence snapshot"); };
+ if (!object(value) || !keys(value, ["schema", "revision", "bindings", "memory", "audit"]) || value.schema !== 1 || !revision(value.revision)
+ || !Array.isArray(value.bindings) || value.bindings.length > 1000
+ || !Array.isArray(value.memory) || value.memory.length > 4000
+ || !Array.isArray(value.audit) || value.audit.length > MAX_AUDIT) return fail();
+ const s = value as unknown as TenantSnapshot;
+ if (s.bindings.some(b => !object(b) || !keys(b, ["issuer", "subject", "tenantId", "principalId", "mappingRevision", "enabled", "tenantEnabled"]) || !validSubject(b) || !validBinding(b) || b.mappingRevision > s.revision)
+ || !unique(s.bindings.map(subjectKey))
+ || !unique(s.bindings.map(b => JSON.stringify([b.tenantId, b.principalId])))) return fail();
+ if (s.bindings.some(b => s.bindings.some(other => b.tenantId === other.tenantId && b.tenantEnabled !== other.tenantEnabled))) return fail();
+ if (s.memory.some(m => !object(m) || !keys(m, ["tenantId", "principalId", "mappingRevision", "collection", "key", "value", "version"]) || !validAddress(m) || !storedMemory(m)
+ || !revision(m.version) || m.version < 1 || m.version > s.revision || m.mappingRevision > s.revision)
+ || !unique(s.memory.map(addressKey))) return fail();
+ for (const ledger of s.memory.filter(m => m.key === TENANT_LEDGER_KEY)) {
+ if (s.memory.some(m => m.tenantId === ledger.tenantId && m.principalId === ledger.principalId
+ && m.mappingRevision === ledger.mappingRevision && m.key !== TENANT_LEDGER_KEY && m.value !== "")) return fail();
+ }
+ if (s.audit.length !== s.revision || s.audit.some((a, i) => !object(a) || !keys(a, ["id", "revision", "at", "tenantId", "principalId", "mappingRevision", "scope", "action", "key", "tool"]) || !validId(a.id)
+ || a.revision !== i + 1 || !validId(a.tenantId) || !validId(a.principalId)
+ || !revision(a.mappingRevision) || a.mappingRevision < 1 || a.mappingRevision > a.revision
+ || typeof a.at !== "string" || a.at.length > 32 || !Number.isFinite(Date.parse(a.at))
+ || !["principal", "tenant"].includes(a.scope) || (a.action === "memory.written" && a.scope !== "principal")
+ || !["binding.changed", "memory.written"].includes(a.action)
+ || (a.tool !== undefined && (a.action !== "memory.written" || !["agent_memory_remember", "agent_memory_forget"].includes(a.tool)))
+ || (a.action === "memory.written" ? !memoryKey(a.key) : a.key !== undefined))
+ || !unique(s.audit.map(a => a.id))) return fail();
+ return s;
+}
diff --git a/lib/tenancy/persistence-test-fixtures.ts b/lib/tenancy/persistence-test-fixtures.ts
new file mode 100644
index 00000000..f8cb645f
--- /dev/null
+++ b/lib/tenancy/persistence-test-fixtures.ts
@@ -0,0 +1,38 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import ts from "typescript";
+import { openTenantPersistence } from "./persistence";
+import { createTenantAuthority } from "./authority";
+
+export const alice = { issuer: "fixture", subject: "alice", expiresAt: Date.now() + 3600000 };
+export const bob = { issuer: "fixture", subject: "bob", expiresAt: Date.now() + 3600000 };
+export const bindingA = { tenantId: "tenant-a", principalId: "person-a", enabled: true, tenantEnabled: true };
+export const bindingB = { tenantId: "tenant-b", principalId: "person-b", enabled: true, tenantEnabled: true };
+export async function fixture() {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-tenant-persistence-"));
+ const store = await openTenantPersistence({ root, initialize: true });
+ await store.administration.setBinding(alice, bindingA, 0);
+ await store.administration.setBinding(bob, bindingB, 1);
+ const authority = createTenantAuthority(store.registry, store.storage);
+ return { root, store, authority, contextA: await authority.authenticate(alice), contextB: await authority.authenticate(bob),
+ cleanup: () => fs.rm(root, { recursive: true, force: true }) };
+}
+export async function compileChild(directory: string) {
+ const files = ["tenancy/persistence", "tenancy/persistence-file", "tenancy/persistence-schema",
+ "tenancy/persistence-memory", "tenancy/memory-ledger", "tenancy/memory-tools", "tenancy/authority",
+ "agent/memory-resolution", "agent/memory-query"];
+ for (const name of files) {
+ const source = (await fs.readFile(path.join(process.cwd(), "lib", name + ".ts"), "utf8"))
+ .replaceAll('"@/lib/agent/', '"../agent/');
+ const target = path.join(directory, name + ".js");
+ await fs.mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
+ await fs.writeFile(target, ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true },
+ }).outputText, { mode: 0o600 });
+ }
+ await fs.copyFile(path.join(process.cwd(), "lib/agent/memory-context.mjs"), path.join(directory, "agent/memory-context.mjs"));
+}
+export const child = promisify(execFile);
diff --git a/lib/tenancy/persistence.test.ts b/lib/tenancy/persistence.test.ts
new file mode 100644
index 00000000..5ea26ef8
--- /dev/null
+++ b/lib/tenancy/persistence.test.ts
@@ -0,0 +1,99 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { promises as fs } from "node:fs";
+import { createTenantAuthority } from "./authority";
+import { readTenantMemory } from "./storage";
+import { writeTenantMemory } from "./memory-write";
+import { openTenantPersistence } from "./persistence";
+import { alice, bob, bindingA, bindingB, fixture } from "./persistence-test-fixtures";
+
+const cleanups: Array<() => Promise<void>> = [];
+async function setup() { const f = await fixture(); cleanups.push(f.cleanup); return f; }
+afterEach(async () => { for (const cleanup of cleanups.splice(0)) await cleanup(); });
+describe("durable tenant registry and memory", () => {
+ it("persists registry, memory and scoped audit across independent instances", async () => {
+ const f = await setup();
+ const result = await writeTenantMemory(f.contextA, "MEMORY.md", "synthetic alice", 2, 0);
+ expect(result.revision).toBe(3);
+ const reopened = await openTenantPersistence({ root: f.root });
+ const context = await createTenantAuthority(reopened.registry, reopened.storage).authenticate(alice);
+ expect((await readTenantMemory(context)).memory).toBe("synthetic alice");
+ expect((await readTenantMemory(f.contextB)).memory).toBe("");
+ const binding = await reopened.registry.resolve(alice);
+ const events = await reopened.audit.read(binding!);
+ expect(events.map(e => e.action)).toEqual(["binding.changed", "memory.written"]);
+ expect(JSON.stringify(events)).not.toContain("synthetic alice");
+ expect(JSON.stringify(events)).not.toContain("fixture");
+ });
+ it("separates equal keys for two tenants and enforces document/store CAS", async () => {
+ const f = await setup();
+ await writeTenantMemory(f.contextA, "USER.md", "A", 2, 0);
+ await expect(writeTenantMemory(f.contextB, "USER.md", "B", 2, 0)).rejects.toThrow("revision conflict");
+ await writeTenantMemory(f.contextB, "USER.md", "B", 3, 0);
+ await expect(writeTenantMemory(f.contextA, "USER.md", "overwrite", 4, 0)).rejects.toThrow("version conflict");
+ expect((await readTenantMemory(f.contextA)).user).toBe("A");
+ expect((await readTenantMemory(f.contextB)).user).toBe("B");
+ expect((await f.store.administration.status()).revision).toBe(4);
+ });
+ it("revocation first denies writes; re-enable never revives the old context", async () => {
+ const f = await setup();
+ await f.store.administration.setBinding(alice, { ...bindingA, enabled: false }, 2);
+ await expect(writeTenantMemory(f.contextA, "MEMORY.md", "denied", 3, 0)).rejects.toThrow();
+ await f.store.administration.setBinding(alice, bindingA, 3);
+ await expect(readTenantMemory(f.contextA)).rejects.toThrow();
+ const next = await f.authority.authenticate(alice);
+ expect((await readTenantMemory(next)).memory).toBe("");
+ expect((await f.store.administration.status()).revision).toBe(4);
+ });
+ it("writes ordered before revocation remain committed without later access", async () => {
+ const f = await setup();
+ await writeTenantMemory(f.contextA, "MEMORY.md", "committed first", 2, 0);
+ await f.store.administration.setBinding(alice, { ...bindingA, enabled: false }, 3);
+ await expect(readTenantMemory(f.contextA)).rejects.toThrow();
+ const state = JSON.parse(await fs.readFile(f.root + "/state.json", "utf8"));
+ expect(state.memory[0].value).toBe("committed first");
+ expect(state.audit.map((e: { action: string }) => e.action)).toEqual([
+ "binding.changed", "binding.changed", "memory.written", "binding.changed",
+ ]);
+ });
+ it("rejects direct stale grants and expired grants inside the transaction", async () => {
+ const f = await setup();
+ const old = (await f.store.registry.resolve(alice))!;
+ await f.store.administration.setBinding(alice, { ...bindingA, enabled: false }, 2);
+ await expect(f.store.storage.writeMemory({ identity: alice, binding: old }, "MEMORY.md", "bad", 3, 0)).rejects.toThrow();
+ const live = (await f.store.registry.resolve(bob))!;
+ await expect(f.store.storage.writeMemory({ identity: { ...bob, expiresAt: 1 }, binding: live },
+ "MEMORY.md", "bad", 3, 0)).rejects.toThrow();
+ expect((await f.store.administration.status()).revision).toBe(3);
+ });
+ it("does not expose other collections, paths or fabricated generations", async () => {
+ const f = await setup();
+ const base = { tenantId: "tenant-a", principalId: "person-a", mappingRevision: 1, collection: "memory" as const, key: "MEMORY.md" };
+ for (const changed of [{ mappingRevision: 2 }, { principalId: "person-b" }, { key: "../owner" }, { collection: "jobs" }]) {
+ await expect(f.store.storage.read({ ...base, ...changed } as typeof base)).rejects.toThrow();
+ }
+ await expect(f.authority.authenticate({ ...alice, subject: "unknown" })).rejects.toThrow();
+ });
+ it("rejects ambiguous principals and keeps failed mutations out of state", async () => {
+ const f = await setup();
+ await expect(f.store.administration.setBinding(bob, bindingA, 2)).rejects.toThrow("already bound");
+ expect((await f.store.administration.status()).revision).toBe(2);
+ expect(await f.store.registry.resolve(bob)).toMatchObject(bindingB);
+ });
+ it("invalidates all same-tenant bindings on tenant disable and re-enable", async () => {
+ const f = await setup();
+ const other = { ...bob, subject: "alice-peer" };
+ await f.store.administration.setBinding(other, { ...bindingA, principalId: "peer" }, 2);
+ const context = await f.authority.authenticate(other);
+ await f.store.administration.setBinding(alice, { ...bindingA, tenantEnabled: false }, 3);
+ await expect(readTenantMemory(context)).rejects.toThrow();
+ await f.store.administration.setBinding(alice, bindingA, 4);
+ await expect(readTenantMemory(context)).rejects.toThrow();
+ const live = (await f.store.registry.resolve(other))!;
+ expect(live.mappingRevision).toBe(5);
+ const audit = await f.store.audit.read(live);
+ expect(audit).toHaveLength(1);
+ expect(audit[0]).toMatchObject({ scope: "tenant" });
+ expect(audit[0]).not.toHaveProperty("principalId");
+ expect(JSON.stringify(audit)).not.toContain("person-a");
+ });
+});
diff --git a/lib/tenancy/persistence.ts b/lib/tenancy/persistence.ts
new file mode 100644
index 00000000..b50cc095
--- /dev/null
+++ b/lib/tenancy/persistence.ts
@@ -0,0 +1,156 @@
+import { executeMemoryOnSnapshot, rawMemoryValue, readMemoryValue } from "./persistence-memory";
+import { TENANT_LEDGER_KEY } from "./memory-ledger";
+import { tenantMemoryTool, validateMemoryArguments } from "./memory-tools";
+import { randomUUID } from "node:crypto";
+import { TenantDenied } from "./authority";
+import { tenantFile, TenantStoreConflict } from "./persistence-file";
+import {
+ addressKey, MAX_AUDIT, MAX_STORE_BYTES, memoryKey, revision, sameBinding, subjectKey, validAddress,
+ validBinding, validId, validSubject, validText, type Membership, type SubjectKey,
+ type TenantAuditEvent, type TenantSnapshot,
+} from "./persistence-schema";
+import type { AuthenticatedSubject, TenantAddress, TenantBinding, TenantPublicMemoryPort, TenantAuditPort } from "./types";
+
+export async function openTenantPersistence(options: { root: string; initialize?: boolean; guard?: () => void }) {
+ options.guard?.();
+ const file = await tenantFile(options.root);
+ await file.transaction(async (directory, sync) => {
+ try { await file.read(directory); options.guard?.(); return undefined; }
+ catch (error) {
+ if (!options.initialize || (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ await file.write(directory, sync, { schema: 1, revision: 0, bindings: [], memory: [], audit: [] }, "initialize", options.guard);
+ return { operationId: "initialize" };
+ }
+ });
+ async function inspect<T>(fn: (state: TenantSnapshot) => T) {
+ return file.transaction(async directory => { const s = await file.read(directory); options.guard?.(); return fn(s); });
+ }
+ function available(s: TenantSnapshot) { if (s.audit.length >= MAX_AUDIT || Buffer.byteLength(JSON.stringify(s)) >= MAX_STORE_BYTES - 131072) {
+ throw new TenantDenied("tenant store capacity requires recovery");
+ } }
+ function matching(state: TenantSnapshot, address: TenantAddress) {
+ return state.bindings.some(b => b.enabled && b.tenantEnabled && b.tenantId === address.tenantId
+ && b.principalId === address.principalId && b.mappingRevision === address.mappingRevision);
+ }
+ async function mutate<T>(expected: number | null, fn: (s: TenantSnapshot, next: number) => { result: T; event: Omit<TenantAuditEvent, "id" | "revision" | "at"> }) {
+ if (expected !== null && !revision(expected)) throw new TenantStoreConflict("invalid expected store revision");
+ return file.transaction(async (directory, sync) => {
+ const s = await file.read(directory);
+ options.guard?.();
+ if (expected !== null && s.revision !== expected) throw new TenantStoreConflict("tenant store revision conflict");
+ if (s.audit.length >= MAX_AUDIT || s.revision === Number.MAX_SAFE_INTEGER) throw new Error("tenant store capacity reached");
+ const next = s.revision + 1;
+ const { result, event } = fn(s, next);
+ const id = randomUUID();
+ s.revision = next;
+ s.audit.push({ ...event, id, revision: next, at: new Date().toISOString() });
+ await file.write(directory, sync, s, id, options.guard);
+ return { result, revision: next, operationId: id };
+ });
+ }
+ const registry = Object.freeze({
+ async resolve(identity: Readonly<AuthenticatedSubject>) {
+ const subject = { issuer: identity.issuer, subject: identity.subject };
+ if (!validSubject(subject)) throw new TenantDenied();
+ return inspect(s => {
+ available(s);
+ const b = s.bindings.find(b => subjectKey(b) === subjectKey(subject));
+ if (!b) return null;
+ return { tenantId: b.tenantId, principalId: b.principalId, mappingRevision: b.mappingRevision,
+ enabled: b.enabled, tenantEnabled: b.tenantEnabled };
+ });
+ },
+ });
+ const storage = Object.freeze<TenantPublicMemoryPort>({
+ async read(address: Readonly<TenantAddress>) {
+ const scope = { ...address };
+ if (!validAddress(scope)) throw new TenantDenied();
+ return inspect(s => {
+ available(s);
+ if (!matching(s, scope)) throw new TenantDenied();
+ const value = readMemoryValue(s, scope);
+ return value === null ? null : { ...scope, value };
+ });
+ },
+ async writeMemory(grant, key, value, expectedStoreRevision, expectedDocumentVersion) {
+ const request = structuredClone({ grant, key, value });
+ if (!validSubject(request.grant.identity) || !validBinding(request.grant.binding)
+ || !memoryKey(key) || !validText(value) || !revision(expectedDocumentVersion)) throw new TenantDenied();
+ return mutate(expectedStoreRevision, (s) => {
+ const { identity, binding } = request.grant;
+ const live = s.bindings.find(b => subjectKey(b) === subjectKey(identity));
+ if (!live || !sameBinding(live, binding) || !live.enabled || !live.tenantEnabled
+ || !Number.isFinite(identity.expiresAt) || identity.expiresAt <= Date.now()) throw new TenantDenied();
+ const address: TenantAddress = { tenantId: live.tenantId, principalId: live.principalId,
+ mappingRevision: live.mappingRevision, collection: "memory", key: request.key };
+ if (rawMemoryValue(s, { ...address, key: TENANT_LEDGER_KEY })) throw new TenantDenied("typed memory requires public memory operations");
+ const old = s.memory.find(m => addressKey(m) === addressKey(address));
+ if ((old?.version ?? 0) !== expectedDocumentVersion) throw new TenantStoreConflict("tenant document version conflict");
+ const version = expectedDocumentVersion + 1;
+ if (old) { old.value = request.value; old.version = version; }
+ else s.memory.push({ ...address, value: request.value, version });
+ return { result: { version }, event: { tenantId: live.tenantId, principalId: live.principalId,
+ mappingRevision: live.mappingRevision, scope: "principal", action: "memory.written", key: request.key } };
+ });
+ },
+ async operateMemory(grant, tool, args) {
+ if (!tenantMemoryTool(tool)) throw new TenantDenied();
+ const request = structuredClone({ grant, tool, args: validateMemoryArguments(tool, args) });
+ if (tool === "agent_memory_read" || tool === "agent_memory_search") {
+ return inspect(s => { available(s); return executeMemoryOnSnapshot(s, request.grant, tool, request.args).result; });
+ }
+ const committed = await mutate(null, s => {
+ available(s);
+ const outcome = executeMemoryOnSnapshot(s, request.grant, tool, request.args);
+ if (!outcome.event) throw new TenantDenied();
+ return { result: outcome.result, event: outcome.event };
+ });
+ return committed.result;
+ },
+ });
+ // Internal control-plane adapter only. No route, tool or token grants access to these methods.
+ const administration = Object.freeze({
+ async setBinding(subject: SubjectKey, binding: Omit<TenantBinding, "mappingRevision">, expectedRevision: number) {
+ const input = structuredClone({ subject, binding });
+ if (!validSubject(input.subject) || !validBinding({ ...input.binding, mappingRevision: 1 })) throw new TenantDenied();
+ return mutate(expectedRevision, (s, next) => {
+ const b: Membership = { issuer: input.subject.issuer, subject: input.subject.subject,
+ tenantId: input.binding.tenantId, principalId: input.binding.principalId, enabled: input.binding.enabled,
+ tenantEnabled: input.binding.tenantEnabled, mappingRevision: next };
+ const tenantChanged = s.bindings.some(v => v.tenantId === b.tenantId && v.tenantEnabled !== b.tenantEnabled);
+ if (tenantChanged) for (const v of s.bindings) {
+ if (v.tenantId === b.tenantId) { v.tenantEnabled = b.tenantEnabled; v.mappingRevision = next; }
+ }
+ if (s.bindings.some(v => subjectKey(v) !== subjectKey(b) && v.tenantId === b.tenantId && v.principalId === b.principalId)) {
+ throw new TenantDenied("principal already bound");
+ }
+ const index = s.bindings.findIndex(v => subjectKey(v) === subjectKey(b));
+ if (index < 0) s.bindings.push(b); else s.bindings[index] = b;
+ return { result: { ...b }, event: { tenantId: b.tenantId, principalId: b.principalId,
+ mappingRevision: next, scope: tenantChanged ? "tenant" : "principal", action: "binding.changed" } };
+ });
+ },
+ async operationStatus(id: string) {
+ if (!validId(id)) throw new TenantDenied();
+ return inspect(s => s.audit.find(a => a.id === id) ?? null);
+ },
+ async status() { return inspect(s => ({ revision: s.revision, auditEntries: s.audit.length })); },
+ });
+ const audit = Object.freeze<TenantAuditPort>({
+ async read(binding: Readonly<TenantBinding>) {
+ const copy = { ...binding };
+ if (!validBinding(copy)) throw new TenantDenied();
+ return inspect(s => {
+ available(s);
+ if (!s.bindings.some(b => sameBinding(b, copy) && b.enabled && b.tenantEnabled)) throw new TenantDenied();
+ return s.audit.filter(a => a.tenantId === copy.tenantId && (a.scope === "tenant" || a.principalId === copy.principalId)
+ && a.mappingRevision === copy.mappingRevision).map(a => {
+ if (a.scope !== "tenant") return { ...a };
+ return { id: a.id, revision: a.revision, at: a.at, tenantId: a.tenantId,
+ mappingRevision: a.mappingRevision, scope: a.scope, action: a.action };
+ });
+ });
+ },
+ });
+ return Object.freeze({ registry, storage, administration, audit });
+}
diff --git a/lib/tenancy/public-memory.test.ts b/lib/tenancy/public-memory.test.ts
new file mode 100644
index 00000000..df17ad94
--- /dev/null
+++ b/lib/tenancy/public-memory.test.ts
@@ -0,0 +1,96 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { promises as fs } from "node:fs";
+import { createTenantAuthority } from "./authority";
+import { invokeTenantMemory } from "./public-memory";
+import { openTenantPersistence } from "./persistence";
+import { alice, bindingA, fixture } from "./persistence-test-fixtures";
+import type { TenantContext } from "./authority";
+const cleanups: Array<() => Promise<void>> = [];
+async function setup() { const f = await fixture(); cleanups.push(f.cleanup); return f; }
+afterEach(async () => { for (const clean of cleanups.splice(0)) await clean(); });
+const remember = (context: TenantContext, key: string, value: string, extra = {}) =>
+ invokeTenantMemory(context, "agent_memory_remember", { document: "MEMORY.md", key, value, ...extra });
+const read = (context: TenantContext) => invokeTenantMemory(context, "agent_memory_read", {}) as Promise<{ memory: string; user: string }>;
+const search = (context: TenantContext, extra = {}) =>
+ invokeTenantMemory(context, "agent_memory_search", extra) as Promise<{ total: number; records: Array<{ record: { key: string; value: string; retractedAt?: string }; conflicts: unknown[] }> }>;
+describe("public tenant memory with durable typed claims", () => {
+ it("separates identical keys across tenants and never logs keys or values", async () => {
+ const f = await setup();
+ await Promise.all([remember(f.contextA, "private-key-A", "private-value-A"), remember(f.contextB, "private-key-A", "private-value-B")]);
+ expect((await read(f.contextA)).memory).toContain("private-value-A");
+ expect((await read(f.contextA)).memory).not.toContain("private-value-B");
+ expect((await read(f.contextB)).memory).toContain("private-value-B");
+ const state = JSON.parse(await fs.readFile(f.root + "/state.json", "utf8"));
+ expect(state.audit.filter((e: { tool?: string }) => e.tool)).toHaveLength(2);
+ const audit = JSON.stringify(state.audit);
+ for (const secret of ["private-key-A", "private-value-A", "private-value-B", "fixture", "alice"]) expect(audit).not.toContain(secret);
+ expect(audit).toContain("agent_memory_remember");
+ expect(await f.store.administration.status()).toEqual({ revision: 4, auditEntries: 4 });
+ });
+ it("keeps same-tenant principals separate and serializes concurrent keyed writes", async () => {
+ const f = await setup(), peer = { ...alice, subject: "peer" };
+ await f.store.administration.setBinding(peer, { ...bindingA, principalId: "peer" }, 2);
+ const context = await f.authority.authenticate(peer);
+ await Promise.all(Array.from({ length: 10 }, (_, i) => remember(i % 2 ? context : f.contextA, "key-" + i, "value-" + i)));
+ expect((await search(f.contextA)).total).toBe(5);
+ expect((await search(context)).total).toBe(5);
+ expect((await read(f.contextA)).memory).not.toContain("value-1");
+ expect((await read(context)).memory).not.toContain("value-0");
+ });
+ it("preserves claim conflicts, replacement, typed metadata and reopen behavior", async () => {
+ const f = await setup();
+ await remember(f.contextA, "Region", "A", { kind: "semantic", confidence: 0.9, sensitivity: "private" });
+ await remember(f.contextA, "Region", "B", { mode: "claim", confidence: 0.8 });
+ expect((await search(f.contextA, { query: "Region" })).records[0].conflicts).toHaveLength(1);
+ await remember(f.contextA, "Region", "C");
+ expect((await read(f.contextA)).memory).toContain("C");
+ expect((await search(f.contextA, { include_history: true })).total).toBe(3);
+ const reopened = await openTenantPersistence({ root: f.root });
+ const context = await createTenantAuthority(reopened.registry, reopened.storage).authenticate(alice);
+ expect((await search(context, { include_history: true })).total).toBe(3);
+ });
+ it("does not reinterpret multiline headings as new keys, and forget retains history", async () => {
+ const f = await setup();
+ await remember(f.contextA, "safe", "first\n## manufactured\nsecond");
+ expect((await search(f.contextA)).records.map(r => r.record.key)).toEqual(["safe"]);
+ await invokeTenantMemory(f.contextA, "agent_memory_forget", { document: "MEMORY.md", key: "manufactured" });
+ expect((await search(f.contextA)).total).toBe(1);
+ await invokeTenantMemory(f.contextA, "agent_memory_forget", { document: "MEMORY.md", key: "safe" });
+ expect((await read(f.contextA)).memory).toBe("");
+ expect((await search(f.contextA, { include_history: true })).records[0].record.retractedAt).toBeDefined();
+ });
+ it("preserves temporal validity and rejects malformed intervals without mutation", async () => {
+ const f = await setup();
+ await remember(f.contextA, "future", "scheduled", { valid_from: "2030-01-01T00:00:00Z", valid_until: "2032-01-01T00:00:00Z" });
+ expect((await search(f.contextA, { at: "2029-01-01T00:00:00Z" })).total).toBe(0);
+ expect((await search(f.contextA, { at: "2031-01-01T00:00:00Z" })).total).toBe(1);
+ expect((await search(f.contextA, { at: "2033-01-01T00:00:00Z" })).total).toBe(0);
+ const before = await f.store.administration.status();
+ await expect(remember(f.contextA, "bad", "bad", { valid_from: "2032-01-01", valid_until: "2030-01-01" })).rejects.toThrow();
+ expect(await f.store.administration.status()).toEqual(before);
+ });
+ it.each([{ tenantId: "tenant-b" }, { path: "/owner" }, { user: "bob" }, { workflow_id: "foreign" },
+ { document: "CLAIMS.v1" }, { key: "bad\u0000key" }, { confidence: "1" }, { mode: "other" },
+ { sensitivity: null }, { value: "" }, { value: "x".repeat(8193) }])("rejects malformed/routing arguments %j", async extra => {
+ const f = await setup(), before = await f.store.administration.status();
+ await expect(remember(f.contextA, "safe", "safe", extra)).rejects.toThrow();
+ expect(await f.store.administration.status()).toEqual(before);
+ });
+ it("revalidates revocation inside the mutation transaction", async () => {
+ const f = await setup();
+ const storage = { ...f.store.storage, operateMemory: async (...args: Parameters<typeof f.store.storage.operateMemory>) => {
+ await f.store.administration.setBinding(alice, { ...bindingA, enabled: false }, 2);
+ return f.store.storage.operateMemory(...args);
+ } };
+ const context = await createTenantAuthority(f.store.registry, storage).authenticate(alice);
+ await expect(remember(context, "denied", "never stored")).rejects.toThrow();
+ const state = JSON.parse(await fs.readFile(f.root + "/state.json", "utf8"));
+ expect(state.memory).toEqual([]); expect(state.audit).toHaveLength(3);
+ });
+ it("refuses implicit conversion or ambiguous mixing of raw and typed memory", async () => {
+ const f = await setup();
+ await f.store.storage.writeMemory({ identity: alice, binding: (await f.store.registry.resolve(alice))! }, "MEMORY.md", "unstructured original", 2, 0);
+ await expect(remember(f.contextA, "new", "new")).rejects.toThrow("reviewed import");
+ expect((await read(f.contextA)).memory).toBe("unstructured original");
+ });
+});
diff --git a/lib/tenancy/public-memory.ts b/lib/tenancy/public-memory.ts
new file mode 100644
index 00000000..a7279126
--- /dev/null
+++ b/lib/tenancy/public-memory.ts
@@ -0,0 +1,16 @@
+import { tenantAccess, TenantDenied, type TenantContext } from "./authority";
+import { readTenantMemory } from "./storage";
+import { validateMemoryArguments, type TenantMemoryTool } from "./memory-tools";
+import type { TenantPublicMemoryPort } from "./types";
+
+export async function invokeTenantMemory(context: TenantContext, tool: TenantMemoryTool, args: Record<string, unknown>) {
+ const parsed = validateMemoryArguments(tool, args);
+ const access = await tenantAccess(context), port = access.storage as Partial<TenantPublicMemoryPort>;
+ if (typeof port.operateMemory !== "function") {
+ if (tool === "agent_memory_read") return readTenantMemory(context);
+ throw new TenantDenied("tenant memory writes are not configured");
+ }
+ const result = await port.operateMemory({ identity: access.identity, binding: access.binding }, tool, parsed);
+ if (tool === "agent_memory_read" || tool === "agent_memory_search") await tenantAccess(context);
+ return result;
+}
diff --git a/lib/tenancy/runtime-factory.test.ts b/lib/tenancy/runtime-factory.test.ts
new file mode 100644
index 00000000..f32bb0af
--- /dev/null
+++ b/lib/tenancy/runtime-factory.test.ts
@@ -0,0 +1,103 @@
+import { fixture as persistentFixture, alice } from "./persistence-test-fixtures";
+import { describe, expect, it } from "vitest";
+import { createTenantRuntime, type VerifiedTenantToken } from "./runtime-factory";
+import { tenantAccess } from "./authority";
+import type { TenantBinding, TenantCredentialBinding, TenantRegistryPort } from "./types";
+
+const stampA: TenantCredentialBinding = { version: 1, issuer: "issuer-a", subject: "alice", tenantId: "tenant-a", principalId: "person-a", mappingRevision: 1 };
+function fixture() {
+ let enabled = true;
+ const bindings = new Map<string, TenantBinding>([
+ ["issuer-a:alice", { tenantId: "tenant-a", principalId: "person-a", mappingRevision: 1, enabled: true, tenantEnabled: true }],
+ ["issuer-b:alice", { tenantId: "tenant-b", principalId: "person-b", mappingRevision: 2, enabled: true, tenantEnabled: true }],
+ ]);
+ const token: VerifiedTenantToken = { tenantBinding: { ...stampA }, expiresAt: 5000 };
+ const tokens = new Map([["fixture-A", token]]);
+ const registry: TenantRegistryPort = { resolve: async identity => bindings.get(identity.issuer + ":" + identity.subject) ?? null };
+ const runtime = createTenantRuntime({ registry, storage: { read: async () => null },
+ verifyAccessToken: async bearer => tokens.get(bearer) ?? null, enabled: () => enabled, now: () => 1000 });
+ return { runtime, token, tokens, registry, bindings, enable: (value: boolean) => { enabled = value; } };
+}
+describe("injected tenant runtime with a fake verifier", () => {
+ it("resolves the exact verified issuer and generation", async () => {
+ const f = fixture();
+ const context = (await f.runtime.authenticateBearer("fixture-A"))!;
+ expect((await tenantAccess(context)).binding.tenantId).toBe("tenant-a");
+ const other = { ...stampA, issuer: "issuer-b", tenantId: "tenant-b", principalId: "person-b", mappingRevision: 2 };
+ f.tokens.set("fixture-B", { tenantBinding: other, expiresAt: 5000 });
+ expect((await tenantAccess((await f.runtime.authenticateBearer("fixture-B"))!)).binding.tenantId).toBe("tenant-b");
+ });
+ it.each(["issuer", "subject", "tenantId", "principalId", "mappingRevision"] as const)("denies a mismatched %s", async field => {
+ const f = fixture();
+ f.token.tenantBinding = { ...stampA, [field]: field === "mappingRevision" ? 2 : "foreign" };
+ await expect(f.runtime.authenticateBearer("fixture-A")).rejects.toThrow();
+ });
+ it.each(["tenantId", "principalId", "mappingRevision", "enabled", "tenantEnabled"] as const)("denies fresh requests after registry %s changes", async field => {
+ const f = fixture();
+ await f.runtime.authenticateBearer("fixture-A");
+ Object.assign(f.bindings.get("issuer-a:alice")!, { [field]: field === "mappingRevision" ? 2 : field.endsWith("Enabled") || field === "enabled" ? false : "changed" });
+ await expect(f.runtime.authenticateBearer("fixture-A")).rejects.toThrow();
+ });
+ it("does not reactivate old credentials after disable and re-enable", async () => {
+ const f = fixture(), binding = f.bindings.get("issuer-a:alice")!;
+ binding.enabled = false; binding.mappingRevision = 2;
+ await expect(f.runtime.authenticateBearer("fixture-A")).rejects.toThrow();
+ binding.enabled = true; binding.mappingRevision = 3;
+ await expect(f.runtime.authenticateBearer("fixture-A")).rejects.toThrow();
+ });
+ it.each([{ expiresAt: 0 }, { expiresAt: 999 }, { expiresAt: Infinity }, { expiresAt: 5000, revokedAt: 1 },
+ { expiresAt: 5000 }, { expiresAt: 5000, tenantSubject: "alice" }])("denies invalid or unbound record %j", async input => {
+ const f = fixture();
+ const value = "tenantSubject" in input || Object.keys(input).length === 1 && input.expiresAt === 5000
+ ? input : { tenantBinding: stampA, ...input };
+ await expect(f.runtime.resolveValidatedToken(value)).rejects.toThrow();
+ });
+ it("preserves legacy behavior only for unmarked records with mode off", async () => {
+ const f = fixture(); f.enable(false);
+ await expect(f.runtime.resolveValidatedToken({ expiresAt: 0 })).resolves.toBeUndefined();
+ for (const value of [f.token, { expiresAt: 5000, tenantSubject: "alice" }, { expiresAt: 5000, tenantBinding: null }]) {
+ await expect(f.runtime.resolveValidatedToken(value)).rejects.toThrow();
+ }
+ });
+ it("does not let unknown bearers or caller objects act as credentials", async () => {
+ const f = fixture();
+ for (const raw of ["", "unknown", "x".repeat(8193)]) await expect(f.runtime.authenticateBearer(raw)).rejects.toThrow();
+ await expect(f.runtime.authenticateBearer({ tenantBinding: stampA } as unknown as string)).rejects.toThrow();
+ });
+ it("captures the stamp before asynchronous registry work", async () => {
+ const f = fixture();
+ let release!: () => void, entered!: () => void;
+ const barrier = new Promise<void>(resolve => { release = resolve; });
+ const started = new Promise<void>(resolve => { entered = resolve; });
+ f.registry.resolve = async () => { entered(); await barrier; return f.bindings.get("issuer-a:alice")!; };
+ const pending = f.runtime.authenticateBearer("fixture-A");
+ await started;
+ (f.token.tenantBinding as TenantCredentialBinding).tenantId = "tenant-b";
+ release();
+ const context = (await pending)!;
+ expect((await tenantAccess(context)).binding.tenantId).toBe("tenant-a");
+ });
+ it("fails closed when preview is disabled while resolving", async () => {
+ const f = fixture();
+ f.registry.resolve = async () => { f.enable(false); return f.bindings.get("issuer-a:alice")!; };
+ await expect(f.runtime.authenticateBearer("fixture-A")).rejects.toThrow();
+ });
+});
+
+it("denies a fresh request after a durable registry generation changes", async () => {
+ const f = await persistentFixture();
+ try {
+ const binding = (await f.store.registry.resolve(alice))!;
+ const token = { expiresAt: alice.expiresAt, tenantBinding: { version: 1 as const, issuer: alice.issuer, subject: alice.subject,
+ tenantId: binding.tenantId, principalId: binding.principalId, mappingRevision: binding.mappingRevision } };
+ const runtime = createTenantRuntime({ registry: f.store.registry, storage: f.store.storage,
+ verifyAccessToken: async raw => raw === "fixture-access" ? token : null, enabled: () => true });
+ expect(await runtime.authenticateBearer("fixture-access")).toBeDefined();
+ await f.store.administration.setBinding(alice, { ...binding, enabled: false }, 2);
+ await expect(runtime.authenticateBearer("fixture-access")).rejects.toThrow();
+ await f.store.administration.setBinding(alice, { ...binding, enabled: true }, 3);
+ const freshRuntime = createTenantRuntime({ registry: f.store.registry, storage: f.store.storage,
+ verifyAccessToken: async raw => raw === "fixture-access" ? token : null, enabled: () => true });
+ await expect(freshRuntime.authenticateBearer("fixture-access")).rejects.toThrow();
+ } finally { await f.cleanup(); }
+});
diff --git a/lib/tenancy/runtime-factory.ts b/lib/tenancy/runtime-factory.ts
new file mode 100644
index 00000000..c4f502b9
--- /dev/null
+++ b/lib/tenancy/runtime-factory.ts
@@ -0,0 +1,40 @@
+import { createTenantAuthority, tenantAccess, TenantDenied, type TenantContext } from "./authority";
+import { credentialMatchesBinding, tenantCredentialFields } from "./credentials";
+import type { TenantRegistryPort, TenantStoragePort } from "./types";
+
+export interface VerifiedTenantToken {
+ tenantSubject?: unknown;
+ tenantBinding?: unknown;
+ expiresAt: number;
+ revokedAt?: number;
+}
+export function createTenantRuntime(dependencies: {
+ registry: TenantRegistryPort;
+ storage: TenantStoragePort;
+ verifyAccessToken: (bearer: string) => Promise<VerifiedTenantToken | null>;
+ enabled: () => boolean;
+ now?: () => number;
+}) {
+ const now = dependencies.now ?? Date.now;
+ const authority = createTenantAuthority(dependencies.registry, dependencies.storage, now);
+ async function resolveValidatedToken(token: VerifiedTenantToken): Promise<TenantContext | undefined> {
+ const binding = tenantCredentialFields(token).tenantBinding;
+ if (!dependencies.enabled()) {
+ if (binding) throw new TenantDenied("tenant credential is disabled");
+ return undefined;
+ }
+ if (!binding) throw new TenantDenied("versioned tenant credential is required");
+ if (token.revokedAt !== undefined || !Number.isFinite(token.expiresAt) || token.expiresAt <= now()) throw new TenantDenied();
+ const context = await authority.authenticate({ issuer: binding.issuer, subject: binding.subject, expiresAt: token.expiresAt }, binding);
+ const access = await tenantAccess(context);
+ if (!dependencies.enabled() || !credentialMatchesBinding(binding, access.binding)) throw new TenantDenied("tenant credential binding changed");
+ return context;
+ }
+ async function authenticateBearer(bearer: string) {
+ if (typeof bearer !== "string" || !bearer || bearer.length > 8192) throw new TenantDenied();
+ const token = await dependencies.verifyAccessToken(bearer);
+ if (!token) throw new TenantDenied();
+ return resolveValidatedToken(token);
+ }
+ return Object.freeze({ resolveValidatedToken, authenticateBearer });
+}
diff --git a/lib/tenancy/runtime.ts b/lib/tenancy/runtime.ts
new file mode 100644
index 00000000..145a7603
--- /dev/null
+++ b/lib/tenancy/runtime.ts
@@ -0,0 +1,31 @@
+import { TenantDenied } from "./authority";
+import { tenantPreviewEnabled } from "./mode";
+import { tenantCredentialFields } from "./credentials";
+import { createConfiguredTenantRuntime } from "./configured-runtime";
+import { createTenantRuntime, type VerifiedTenantToken } from "./runtime-factory";
+
+const disabled = createTenantRuntime({
+ registry: { resolve: async () => { throw new TenantDenied("tenant registry is not configured"); } },
+ storage: { read: async () => { throw new TenantDenied("tenant storage is not configured"); } },
+ verifyAccessToken: async () => null, enabled: tenantPreviewEnabled,
+});
+let configured: { root: string; runtime: ReturnType<typeof createConfiguredTenantRuntime> } | undefined;
+/** Only transports that have already verified their bearer may pass records here. */
+export async function resolveMcpTenant(token: VerifiedTenantToken) {
+ if (!tenantPreviewEnabled()) return disabled.resolveValidatedToken(token);
+ if (!tenantCredentialFields(token).tenantBinding) throw new TenantDenied("versioned tenant credential is required");
+ const root = process.env.OS_TENANCY_STORAGE_ROOT;
+ if (!root) throw new TenantDenied("tenant registry is not configured");
+ if (configured && configured.root !== root) throw new TenantDenied("tenant root change requires reviewed restart");
+ if (!configured) configured = { root, runtime: createConfiguredTenantRuntime({
+ storageRoot: root, selectedRoot: () => process.env.OS_TENANCY_STORAGE_ROOT,
+ enabled: tenantPreviewEnabled, verifyAccessToken: async () => null,
+ }) };
+ return (await configured.runtime).resolveValidatedToken(token);
+}
+export async function authorizeMcpTenantGrant(record: VerifiedTenantToken): Promise<void> {
+ await resolveMcpTenant(record);
+}
+export function tenantRuntimeConfigurationPresent() {
+ return Boolean(process.env.OS_TENANCY_STORAGE_ROOT);
+}
diff --git a/lib/tenancy/storage.ts b/lib/tenancy/storage.ts
new file mode 100644
index 00000000..699036e4
--- /dev/null
+++ b/lib/tenancy/storage.ts
@@ -0,0 +1,34 @@
+import { tenantAccess, TenantDenied, type TenantContext } from "./authority";
+import type { TenantAddress, TenantCollection } from "./types";
+
+const collections: readonly TenantCollection[] = ["memory", "sessions", "jobs", "projects", "artifacts", "backups"];
+export async function readTenantValue(context: TenantContext, collection: TenantCollection, key: string): Promise<unknown | null> {
+ if (!collections.includes(collection) || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(key)) throw new TenantDenied();
+ const before = await tenantAccess(context);
+ const address: Readonly<TenantAddress> = Object.freeze({ tenantId: before.binding.tenantId, principalId: before.binding.principalId,
+ mappingRevision: before.binding.mappingRevision, collection, key });
+ const result = await before.storage.read(address);
+ const after = await tenantAccess(context);
+ if (after.storage !== before.storage || after.binding !== before.binding) throw new TenantDenied();
+ if (result === null) return null;
+ if (!result || typeof result !== "object" || Array.isArray(result)) throw new TenantDenied("invalid tenant storage envelope");
+ for (const field of ["tenantId", "principalId", "mappingRevision", "collection", "key"] as const) {
+ if (result[field] !== address[field]) throw new TenantDenied("tenant storage scope mismatch");
+ }
+ return structuredClone(result.value);
+}
+function document(value: unknown): string {
+ if (value === null) return "";
+ if (typeof value !== "string" || Buffer.byteLength(value, "utf8") > 65536) throw new TenantDenied("invalid tenant memory document");
+ return value;
+}
+export async function readTenantMemory(context: TenantContext) {
+ const results = await Promise.allSettled([
+ readTenantValue(context, "memory", "USER.md"), readTenantValue(context, "memory", "MEMORY.md"),
+ ]);
+ const failure = results.find(result => result.status === "rejected");
+ if (failure?.status === "rejected") throw failure.reason;
+ const [user, memory] = results.map(result => result.status === "fulfilled" ? result.value : null);
+ await tenantAccess(context);
+ return { capturedAt: new Date().toISOString(), user: document(user), memory: document(memory) };
+}
diff --git a/lib/tenancy/test-fixtures.ts b/lib/tenancy/test-fixtures.ts
new file mode 100644
index 00000000..42a9e463
--- /dev/null
+++ b/lib/tenancy/test-fixtures.ts
@@ -0,0 +1,27 @@
+import { createTenantAuthority } from "./authority";
+import type { TenantAddress, TenantBinding, TenantStoredValue, TenantStoragePort } from "./types";
+
+export function tenantFixture() {
+ let now = 1000;
+ const bindings: Record<string, TenantBinding> = {
+ alice: { tenantId: "tenant-a", principalId: "principal-a", mappingRevision: 1, enabled: true, tenantEnabled: true },
+ bob: { tenantId: "tenant-b", principalId: "principal-b", mappingRevision: 1, enabled: true, tenantEnabled: true },
+ };
+ const reads: TenantAddress[] = [];
+ let override: ((address: Readonly<TenantAddress>) => TenantStoredValue | null) | undefined;
+ const storage: TenantStoragePort = {
+ read: async (address) => {
+ reads.push({ ...address });
+ return override ? override(address) : { ...address, value: address.tenantId + ":" + address.key };
+ },
+ };
+ const authority = createTenantAuthority({
+ resolve: async (identity) => identity.issuer === "mso-local" && bindings[identity.subject]
+ ? { ...bindings[identity.subject] } : null,
+ }, storage, () => now);
+ return { authority, bindings, reads, storage,
+ identity: (subject = "alice") => ({ issuer: "mso-local", subject, expiresAt: 5000 }),
+ setNow: (value: number) => { now = value; },
+ overrideRead: (value: typeof override) => { override = value; },
+ };
+}
diff --git a/lib/tenancy/types.ts b/lib/tenancy/types.ts
new file mode 100644
index 00000000..e29efeec
--- /dev/null
+++ b/lib/tenancy/types.ts
@@ -0,0 +1,55 @@
+import type { TenantMemoryTool } from "./memory-tools";
+export type TenantCollection = "memory" | "sessions" | "jobs" | "projects" | "artifacts" | "backups";
+export interface AuthenticatedSubject { issuer: string; subject: string; expiresAt: number; }
+export interface TenantBinding {
+ tenantId: string;
+ principalId: string;
+ mappingRevision: number;
+ enabled: boolean;
+ tenantEnabled: boolean;
+}
+export interface TenantRegistryPort {
+ resolve(identity: Readonly<AuthenticatedSubject>): Promise<TenantBinding | null>;
+}
+export interface TenantAddress {
+ tenantId: string;
+ principalId: string;
+ mappingRevision: number;
+ collection: TenantCollection;
+ key: string;
+}
+export interface TenantStoredValue extends TenantAddress { value: unknown; }
+export interface TenantStoragePort {
+ /** Implementations must scope lookup by every address field; never fall back to owner/global data. */
+ read(address: Readonly<TenantAddress>): Promise<TenantStoredValue | null>;
+}
+
+export interface TenantMemoryWritePort extends TenantStoragePort {
+ writeMemory(grant: { identity: Readonly<AuthenticatedSubject>; binding: Readonly<TenantBinding> },
+ key: "USER.md" | "MEMORY.md", value: string, expectedStoreRevision: number, expectedDocumentVersion: number):
+ Promise<{ result: { version: number }; revision: number; operationId: string }>;
+}
+
+export type TenantAuditEvent = {
+ id: string; revision: number; at: string; tenantId: string; principalId: string;
+ mappingRevision: number; scope: "principal" | "tenant";
+ action: "binding.changed" | "memory.written"; key?: string; tool?: TenantMemoryTool;
+};
+export type TenantAuditView = Omit<TenantAuditEvent, "principalId"> & { principalId?: string };
+export interface TenantAuditPort {
+ read(binding: Readonly<TenantBinding>): Promise<TenantAuditView[]>;
+}
+
+export interface TenantCredentialBinding {
+ version: 1;
+ issuer: string;
+ subject: string;
+ tenantId: string;
+ principalId: string;
+ mappingRevision: number;
+}
+
+export type TenantGrant = { identity: Readonly<AuthenticatedSubject>; binding: Readonly<TenantBinding> };
+export interface TenantPublicMemoryPort extends TenantMemoryWritePort {
+ operateMemory(grant: TenantGrant, tool: TenantMemoryTool, args: Readonly<Record<string, unknown>>): Promise<unknown>;
+}
diff --git a/osv-scanner.toml b/osv-scanner.toml
deleted file mode 100644
index 40ac1d20..00000000
--- a/osv-scanner.toml
+++ /dev/null
@@ -1,7 +0,0 @@
-# OSV-Scanner loads this file only for lockfiles in this directory (bun.lock).
-# It does not apply to scripts/install/node-gyp/package-lock.json or other children.
-
-[[IgnoredVulns]]
-id = "GHSA-vfj7-8cjw-p6xm"
-ignoreUntil = 2026-12-03T00:00:00Z
-reason = "braces 3.0.3 is reachable only through the devDependency chain eslint-config-next → @next/eslint-plugin-next → fast-glob → micromatch in bun.lock. @next/eslint-plugin-next calls fast-glob only when ESLint settings.next.rootDir is set, and eslint.config.mjs does not set it. No MSO source imports braces or passes a pattern to it. npm still publishes 3.0.3 as the newest braces release. This exception expires at 2026-12-03T00:00:00Z and the root osv-scanner.toml applies only to bun.lock."
diff --git a/package.json b/package.json
index fd7edc1b..2a994386 100644
--- a/package.json
+++ b/package.json
@@ -96,7 +96,8 @@
"postcss": "^8.5.10",
"sharp": "^0.35.4",
"nanoid": "^3.3.18",
- "js-yaml": "^4.3.2"
+ "js-yaml": "^4.3.2",
+ "micromatch": "npm:[email protected]"
},
"devDependencies": {
"@axe-core/playwright": "^4.13.0",
@@ -114,7 +115,12 @@
"simple-icons": "^16.33.0",
"tailwindcss": "^4.3.0",
"typescript": "^5.9.3",
- "vitest": "5.0.2"
+ "vitest": "5.0.2",
+ "brace-expansion": "5.0.12"
},
- "packageManager": "[email protected]"
+ "packageManager": "[email protected]",
+ "patchedDependencies": {
+ }
}
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 00000000..104bb533
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,164 @@
+diff --git a/dist/commonjs/index.js b/dist/commonjs/index.js
+--- a/dist/commonjs/index.js
++++ b/dist/commonjs/index.js
+@@ -147,14 +147,14 @@
+ for (let a = 0; a < acc.length; a++) {
+ for (let v = 0; v < values.length; v++) {
+ if (out.length >= max)
++ throw new RangeError('Brace expansion exceeds configured result limit');
+- return out;
+ const expansion = acc[a] + pre + values[v];
+ // Bash drops empty results at the top level. Skip them before they count
+ // against `max`, so `max` bounds the number of *kept* results.
+ if (dropEmpties && !expansion)
+ continue;
+ if (length + expansion.length > maxLength)
++ throw new RangeError('Brace expansion exceeds configured length limit');
+- return out;
+ out.push(expansion);
+ length += expansion.length;
+ }
+@@ -187,7 +187,8 @@
+ }
+ const pad = n.some(isPadded);
+ let length = 0;
++ for (let i = x; test(i, y); i += incr) {
++ if (N.length >= max) throw new RangeError('Brace expansion exceeds configured result limit');
+- for (let i = x; test(i, y) && N.length < max; i += incr) {
+ let c;
+ if (isAlphaSequence) {
+ c = String.fromCharCode(i);
+@@ -211,18 +212,16 @@
+ }
+ }
+ if (length + c.length > maxLength)
++ throw new RangeError('Brace expansion exceeds configured length limit');
+- break;
+ N.push(c);
+ length += c.length;
+ }
+ return N;
+ }
+ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) {
++ // A partial expansion could hide a lint target. Limits must fail closed.
+- // Too deeply nested to keep following: treat the rest as literal, the same
+- // way a group that cannot expand is already handled. Truncating rather than
+- // throwing keeps `expand` total, matching `max` and `maxLength`.
+ if (depth > maxDepth) {
++ throw new RangeError('Brace expansion exceeds configured depth limit');
+- return [str];
+ }
+ // Consume the string's top-level brace groups left to right, threading a
+ // running set of combined prefixes (`acc`). Expanding the tail iteratively -
+@@ -262,7 +261,8 @@
+ const isOptions = m.body.indexOf(',') >= 0;
+ if (!isSequence && !isOptions) {
+ // {a},b}
++ if (m.post.match(/,(?!,).*\}/)) {
++ if (rewrites >= maxRewrites) throw new RangeError('Brace expansion exceeds configured rewrite limit');
+- if (rewrites < maxRewrites && m.post.match(/,(?!,).*\}/)) {
+ rewrites++;
+ str = m.pre + '{' + m.body + escClose + m.post;
+ isTop = true;
+@@ -308,16 +308,14 @@
+ }
+ values = [];
+ let valuesLength = 0;
++ for (let j = 0; j < n.length; j++) {
+- outer: for (let j = 0; j < n.length; j++) {
+ const expanded = expand_(n[j], max, maxLength, maxDepth, depth + 1, maxRewrites, false);
+ for (let k = 0; k < expanded.length; k++) {
+ const v = expanded[k];
+ if (dropsEmpties && !v)
+ continue;
++ if (values.length >= max) throw new RangeError('Brace expansion exceeds configured result limit');
++ if (valuesLength + v.length > maxLength) throw new RangeError('Brace expansion exceeds configured length limit');
+- if (values.length >= max ||
+- valuesLength + v.length > maxLength) {
+- break outer;
+- }
+ values.push(v);
+ valuesLength += v.length;
+ }
+diff --git a/dist/esm/index.js b/dist/esm/index.js
+--- a/dist/esm/index.js
++++ b/dist/esm/index.js
+@@ -143,14 +143,14 @@
+ for (let a = 0; a < acc.length; a++) {
+ for (let v = 0; v < values.length; v++) {
+ if (out.length >= max)
++ throw new RangeError('Brace expansion exceeds configured result limit');
+- return out;
+ const expansion = acc[a] + pre + values[v];
+ // Bash drops empty results at the top level. Skip them before they count
+ // against `max`, so `max` bounds the number of *kept* results.
+ if (dropEmpties && !expansion)
+ continue;
+ if (length + expansion.length > maxLength)
++ throw new RangeError('Brace expansion exceeds configured length limit');
+- return out;
+ out.push(expansion);
+ length += expansion.length;
+ }
+@@ -183,7 +183,8 @@
+ }
+ const pad = n.some(isPadded);
+ let length = 0;
++ for (let i = x; test(i, y); i += incr) {
++ if (N.length >= max) throw new RangeError('Brace expansion exceeds configured result limit');
+- for (let i = x; test(i, y) && N.length < max; i += incr) {
+ let c;
+ if (isAlphaSequence) {
+ c = String.fromCharCode(i);
+@@ -207,18 +208,16 @@
+ }
+ }
+ if (length + c.length > maxLength)
++ throw new RangeError('Brace expansion exceeds configured length limit');
+- break;
+ N.push(c);
+ length += c.length;
+ }
+ return N;
+ }
+ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) {
++ // A partial expansion could hide a lint target. Limits must fail closed.
+- // Too deeply nested to keep following: treat the rest as literal, the same
+- // way a group that cannot expand is already handled. Truncating rather than
+- // throwing keeps `expand` total, matching `max` and `maxLength`.
+ if (depth > maxDepth) {
++ throw new RangeError('Brace expansion exceeds configured depth limit');
+- return [str];
+ }
+ // Consume the string's top-level brace groups left to right, threading a
+ // running set of combined prefixes (`acc`). Expanding the tail iteratively -
+@@ -258,7 +257,8 @@
+ const isOptions = m.body.indexOf(',') >= 0;
+ if (!isSequence && !isOptions) {
+ // {a},b}
++ if (m.post.match(/,(?!,).*\}/)) {
++ if (rewrites >= maxRewrites) throw new RangeError('Brace expansion exceeds configured rewrite limit');
+- if (rewrites < maxRewrites && m.post.match(/,(?!,).*\}/)) {
+ rewrites++;
+ str = m.pre + '{' + m.body + escClose + m.post;
+ isTop = true;
+@@ -304,16 +304,14 @@
+ }
+ values = [];
+ let valuesLength = 0;
++ for (let j = 0; j < n.length; j++) {
+- outer: for (let j = 0; j < n.length; j++) {
+ const expanded = expand_(n[j], max, maxLength, maxDepth, depth + 1, maxRewrites, false);
+ for (let k = 0; k < expanded.length; k++) {
+ const v = expanded[k];
+ if (dropsEmpties && !v)
+ continue;
++ if (values.length >= max) throw new RangeError('Brace expansion exceeds configured result limit');
++ if (valuesLength + v.length > maxLength) throw new RangeError('Brace expansion exceeds configured length limit');
+- if (values.length >= max ||
+- valuesLength + v.length > maxLength) {
+- break outer;
+- }
+ values.push(v);
+ valuesLength += v.length;
+ }
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 00000000..dff5922e
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,30 @@
+diff --git a/out/utils/pattern.js b/out/utils/pattern.js
+index 0f5e9ca7308230601294f1d3a66d641e3b50c267..a200adc828e539b3dc49dcf70c77c28a53814728 100644
+--- a/out/utils/pattern.js
++++ b/out/utils/pattern.js
+@@ -4,6 +4,7 @@ exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe
+ const path = require("path");
+ const globParent = require("glob-parent");
+ const micromatch = require("micromatch");
++const { expand } = require("brace-expansion");
+ const GLOBSTAR = '**';
+ const ESCAPE_SYMBOL = '\\';
+ const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
+@@ -134,7 +135,16 @@ function expandPatternsWithBraceExpansion(patterns) {
+ }
+ exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
+ function expandBraceExpansion(pattern) {
+- const patterns = micromatch.braces(pattern, { expand: true, nodupes: true });
++ if (pattern.length > 4096) throw new RangeError('Brace pattern exceeds 4096 characters');
++ let depth = 0;
++ for (let i = 0; i < pattern.length; i++) {
++ if (pattern.charCodeAt(i) === 92) { i++; continue; }
++ if (pattern[i] === '{' && ++depth > 32) throw new RangeError('Brace nesting exceeds 32 levels');
++ if (pattern[i] === '}') depth = Math.max(0, depth - 1);
++ }
++ const expanded = expand(pattern, { max: 1001, maxLength: 4100096, maxDepth: 32, maxRewrites: 32 });
++ if (expanded.length > 1000) throw new RangeError('Brace expansion exceeds 1000 results');
++ const patterns = [...new Set(expanded)];
+ /**
+ * Sort the patterns by length so that the same depth patterns are processed side by side.
+ * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']`
diff --git a/scripts/a2a-trace-support.mjs b/scripts/a2a-trace-support.mjs
index 29c71773..00c82024 100644
--- a/scripts/a2a-trace-support.mjs
+++ b/scripts/a2a-trace-support.mjs
@@ -66,23 +66,40 @@ async function statePath(id) {
}
const STATE_LIMITS = { runId: 80, agent: 48, project: 240, sessionId: 120, sessionLabel: 120, workflowId: 120, status: 24, startedAt: 40, updatedAt: 40, lastFingerprint: 600 };
+function stateIdentifier(value) {
+ if (typeof value !== "string" || !/^[a-zA-Z0-9_-]{1,120}$/.test(value)) fail("invalid A2A trace identifiers");
+ return value;
+}
function checkState(state) {
- if (!state || state.version !== 1 || typeof state.runId !== "string" || state.runId !== validRunId(state.runId)) fail("invalid A2A trace state");
- if (!/^[a-zA-Z0-9_-]{1,120}$/.test(state.sessionId) || !/^[a-zA-Z0-9_-]{1,120}$/.test(state.workflowId)) fail("invalid A2A trace identifiers");
- if (!["active", "attached", "finished", "failed", "cancelled"].includes(state.status)) fail("invalid A2A trace status");
- for (const [key, value] of Object.entries(state)) {
- if (key === "version") continue;
- if (key === "lastEventMs") { if (!Number.isSafeInteger(value) || value < 0) fail("invalid A2A trace timestamp"); continue; }
- if (!Object.hasOwn(STATE_LIMITS, key) || (value !== undefined && (typeof value !== "string" || value.length > STATE_LIMITS[key]))) fail("invalid A2A trace field: " + key);
+ if (!state || typeof state !== "object" || Array.isArray(state)) fail("invalid A2A trace state");
+ const fields = Object.getOwnPropertyDescriptors(state);
+ if (Object.values(fields).some((field) => !Object.hasOwn(field, "value"))) fail("invalid A2A trace accessor");
+ const runId = fields.runId?.value, status = fields.status?.value;
+ if (fields.version?.value !== 1 || typeof runId !== "string" || runId !== validRunId(runId)) fail("invalid A2A trace state");
+ if (!["active", "attached", "finished", "failed", "cancelled"].includes(status)) fail("invalid A2A trace status");
+ const snapshot = {
+ version: 1, runId, status,
+ sessionId: stateIdentifier(fields.sessionId?.value),
+ workflowId: stateIdentifier(fields.workflowId?.value),
+ };
+ for (const [key, field] of Object.entries(fields)) {
+ if (Object.hasOwn(snapshot, key)) continue;
+ const value = field.value;
+ if (key === "lastEventMs") {
+ if (!Number.isSafeInteger(value) || value < 0) fail("invalid A2A trace timestamp");
+ } else if (!Object.hasOwn(STATE_LIMITS, key) || (value !== undefined && (typeof value !== "string" || value.length > STATE_LIMITS[key]))) fail("invalid A2A trace field: " + key);
+ snapshot[key] = value;
}
- return state;
+ return snapshot;
}
export async function saveState(state) {
- checkState(state);
- const file = await statePath(state.runId);
+ const snapshot = checkState(state);
+ const body = JSON.stringify(snapshot, null, 2) + "\n";
+ if (Buffer.byteLength(body, "utf8") > 8192) fail("invalid A2A trace state size");
+ const file = await statePath(snapshot.runId);
const temp = file + "." + process.pid + "." + Date.now() + ".tmp";
- await fs.writeFile(temp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600, flag: "wx" });
+ await fs.writeFile(temp, body, { mode: 0o600, flag: "wx" });
await fs.rename(temp, file);
}
diff --git a/scripts/a2a-trace.test.ts b/scripts/a2a-trace.test.ts
index beb7cb10..0c6efdb2 100644
--- a/scripts/a2a-trace.test.ts
+++ b/scripts/a2a-trace.test.ts
@@ -95,6 +95,66 @@ describe("A2A workflow trace bridge", () => {
await expect(support.readState("a2a-huge")).rejects.toThrow("invalid A2A trace state file");
});
+ function fixture(runId) {
+ return {
+ version: 1, runId, agent: "test", sessionId: "session-1", workflowId: "workflow-1",
+ status: "active", sessionLabel: "original",
+ startedAt: "2026-10-04T00:00:00.000Z", updatedAt: "2026-10-04T00:00:00.000Z",
+ };
+ }
+
+ it("requires present primitive session and workflow identifiers", async () => {
+ const support = await import("./a2a-trace-support.mjs");
+ for (const key of ["sessionId", "workflowId"]) {
+ const missing = fixture("a2a-schema");
+ delete missing[key];
+ await expect(support.saveState(missing)).rejects.toThrow("invalid A2A trace identifiers");
+ for (const value of [undefined, null, 123, {}, []]) {
+ await expect(support.saveState({ ...fixture("a2a-schema"), [key]: value })).rejects.toThrow("invalid A2A trace identifiers");
+ }
+ }
+ });
+
+ it("rejects accessors and never serializes caller-provided toJSON hooks", async () => {
+ const support = await import("./a2a-trace-support.mjs");
+ const getter = vi.fn(() => "session-1"), accessor = fixture("a2a-accessor");
+ Object.defineProperty(accessor, "sessionId", { enumerable: true, get: getter });
+ await expect(support.saveState(accessor)).rejects.toThrow("invalid A2A trace accessor");
+ expect(getter).not.toHaveBeenCalled();
+ const toJSON = vi.fn(() => ({ sessionId: "injected" })), own = fixture("a2a-ownjson");
+ Object.defineProperty(own, "toJSON", { value: toJSON });
+ await expect(support.saveState(own)).rejects.toThrow("invalid A2A trace field");
+ const inherited = Object.assign(Object.create({ toJSON }), fixture("a2a-inherited"));
+ await support.saveState(inherited);
+ expect(await support.readState("a2a-inherited")).toMatchObject({ sessionId: "session-1" });
+ expect(toJSON).not.toHaveBeenCalled();
+ });
+
+ it("persists the validated snapshot even when the caller mutates during filesystem awaits", async () => {
+ const support = await import("./a2a-trace-support.mjs");
+ const state = fixture("a2a-snapshot"), pending = support.saveState(state);
+ state.runId = "a2a-swapped";
+ state.sessionId = "changed-session";
+ state.sessionLabel = "changed";
+ await pending;
+ expect(await support.readState("a2a-snapshot")).toMatchObject({
+ runId: "a2a-snapshot", sessionId: "session-1", sessionLabel: "original",
+ });
+ });
+
+ it("round-trips maximum allowed escaped metadata within the read-size budget", async () => {
+ const support = await import("./a2a-trace-support.mjs");
+ const state = {
+ ...fixture("a2a-escaped"), agent: "\u0001".repeat(48), project: "\u0001".repeat(240),
+ sessionLabel: "\u0001".repeat(120), lastFingerprint: "\u0001".repeat(600),
+ startedAt: "\u0001".repeat(40), updatedAt: "\u0001".repeat(40),
+ };
+ await support.saveState(state);
+ const body = await readFile(path.join(stateDir, "a2a-escaped.json"), "utf8");
+ expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(8192);
+ expect(await support.readState("a2a-escaped")).toEqual(state);
+ });
+
it("does not expose hidden reasoning as a trace event type", async () => {
await expect(mod.main(["reasoning", "--run", "a2a-test", "--message", "private thoughts"])).rejects.toThrow("unknown A2A trace command");
});
diff --git a/scripts/audit-exceptions.mjs b/scripts/audit-exceptions.mjs
deleted file mode 100644
index 5ffd01ce..00000000
--- a/scripts/audit-exceptions.mjs
+++ /dev/null
@@ -1,59 +0,0 @@
-// Time-boxed, GHSA-named exceptions. A match also requires the named lockfile
-// graph; a new parent, a production dependency, or a newer version fails closed.
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-
-export const BRACES_DEV_LINT = {
- id: "GHSA-vfj7-8cjw-p6xm",
- cve: "CVE-2026-93687",
- pkg: "braces",
- version: "3.0.3",
- until: "2026-12-03T00:00:00Z",
- lockfile: "bun.lock",
- reason: "braces 3.0.3 is reachable only through the devDependency chain eslint-config-next → @next/eslint-plugin-next → fast-glob → micromatch in bun.lock. @next/eslint-plugin-next calls fast-glob only when ESLint settings.next.rootDir is set, and eslint.config.mjs does not set it. No MSO source imports braces or passes a pattern to it. npm still publishes 3.0.3 as the newest braces release. This exception expires at 2026-12-03T00:00:00Z and the root osv-scanner.toml applies only to bun.lock.",
-};
-
-const BRACES_PARENTS = ["micromatch", "fast-glob", "@next/eslint-plugin-next", "eslint-config-next"];
-
-export function readRepoLock() {
- return readFileSync(fileURLToPath(new URL("../bun.lock", import.meta.url)), "utf8");
-}
-
-function parseLock(lockText) {
- return JSON.parse(lockText.replace(/,(\s*[}\]])/g, "$1"));
-}
-
-function depsOf(entry) {
- const meta = entry.find((part) => part && typeof part === "object" && !Array.isArray(part));
- return meta?.dependencies ?? {};
-}
-
-function parentsOf(packages, name) {
- return Object.entries(packages)
- .filter(([, entry]) => Object.hasOwn(depsOf(entry), name))
- .map(([key]) => key)
- .sort();
-}
-
-export function bracesDevLintAllows(pkg, ids, lockText, now = new Date()) {
- if (pkg !== BRACES_DEV_LINT.pkg || !ids.includes(BRACES_DEV_LINT.id)) return false;
- if (!(now < new Date(BRACES_DEV_LINT.until))) return false;
- let lock;
- try { lock = parseLock(lockText); } catch { return false; }
- const packages = lock?.packages;
- const workspace = lock?.workspaces?.[""];
- if (!packages || !workspace) return false;
- const specs = Object.values(packages)
- .map((entry) => entry?.[0])
- .filter((spec) => typeof spec === "string" && spec.startsWith("braces@"));
- if (specs.length !== 1 || specs[0] !== `braces@${BRACES_DEV_LINT.version}`) return false;
- const expected = ["braces", ...BRACES_PARENTS];
- for (let i = 0; i < BRACES_PARENTS.length; i += 1) {
- const parents = parentsOf(packages, expected[i]);
- if (parents.length !== 1 || parents[0] !== BRACES_PARENTS[i]) return false;
- }
- const dev = workspace.devDependencies ?? {};
- const prod = workspace.dependencies ?? {};
- return Object.hasOwn(dev, "eslint-config-next") && !Object.hasOwn(prod, "eslint-config-next")
- && !Object.hasOwn(prod, "braces");
-}
diff --git a/scripts/audit-exceptions.test.ts b/scripts/audit-exceptions.test.ts
deleted file mode 100644
index 1d9e6ade..00000000
--- a/scripts/audit-exceptions.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-import { BRACES_DEV_LINT, bracesDevLintAllows, readRepoLock } from "./audit-exceptions.mjs";
-
-const IDS = [BRACES_DEV_LINT.id, BRACES_DEV_LINT.cve];
-const OPEN = new Date("2026-10-04T00:00:00Z");
-const EXPIRED = new Date(BRACES_DEV_LINT.until);
-type Deps = Record<string, string>;
-type Lock = {
- workspaces: { "": { dependencies: Deps; devDependencies: Deps } };
- packages: Record<string, [string, string, { dependencies: Deps }]>;
-};
-
-function lock(mutate: (row: Lock) => void = () => {}) {
- const row: Lock = {
- workspaces: { "": { dependencies: { next: "1" }, devDependencies: { "eslint-config-next": "1" } } },
- packages: {
- braces: ["[email protected]", "", { dependencies: {} }],
- micromatch: ["[email protected]", "", { dependencies: { braces: "^3.0.3" } }],
- "fast-glob": ["[email protected]", "", { dependencies: { micromatch: "^4.0.4" } }],
- "@next/eslint-plugin-next": ["@next/[email protected]", "", { dependencies: { "fast-glob": "3.3.1" } }],
- "eslint-config-next": ["[email protected]", "", { dependencies: { "@next/eslint-plugin-next": "16.3.8" } }],
- },
- };
- mutate(row);
- return JSON.stringify(row);
-}
-
-describe("braces dev-lint exception", () => {
- it("allows only the named GHSA while the dev chain and date still match", () => {
- expect(bracesDevLintAllows("braces", IDS, lock(), OPEN)).toBe(true);
- expect(bracesDevLintAllows("braces", IDS, readRepoLock(), OPEN)).toBe(true);
- });
- it("refuses another package, a missing GHSA, expiry, a second parent, or a production edge", () => {
- expect(bracesDevLintAllows("micromatch", IDS, lock(), OPEN)).toBe(false);
- expect(bracesDevLintAllows("braces", ["CVE-2026-93687"], lock(), OPEN)).toBe(false);
- expect(bracesDevLintAllows("braces", IDS, lock(), EXPIRED)).toBe(false);
- const extra = lock((row) => { row.packages.other = ["[email protected]", "", { dependencies: { braces: "3.0.3" } }]; });
- expect(bracesDevLintAllows("braces", IDS, extra, OPEN)).toBe(false);
- const prod = lock((row) => { row.workspaces[""].dependencies["eslint-config-next"] = "1"; });
- expect(bracesDevLintAllows("braces", IDS, prod, OPEN)).toBe(false);
- const bumped = lock((row) => { row.packages.braces[0] = "[email protected]"; });
- expect(bracesDevLintAllows("braces", IDS, bumped, OPEN)).toBe(false);
- });
- it("keeps the OSV ignore on the same GHSA, instant, and reason", () => {
- const toml = readFileSync(new URL("../osv-scanner.toml", import.meta.url), "utf8");
- expect(toml).toContain(`id = "${BRACES_DEV_LINT.id}"`);
- expect(toml).toContain(`ignoreUntil = ${BRACES_DEV_LINT.until}`);
- expect(toml).toContain(`reason = "${BRACES_DEV_LINT.reason}"`);
- expect(toml).not.toContain("GHSA-ch52-4w7c-c8xp");
- });
-});
diff --git a/scripts/audit.mjs b/scripts/audit.mjs
index 161d5324..37eeaa87 100644
--- a/scripts/audit.mjs
+++ b/scripts/audit.mjs
@@ -2,7 +2,6 @@
// Local development tolerates an unavailable registry; --strict never treats a
// skipped/incomplete dependency audit as success. CI and security assurance use strict mode.
import { spawnSync } from "node:child_process";
-import { bracesDevLintAllows, readRepoLock } from "./audit-exceptions.mjs";
const FLOOR = new Set(["high", "critical"]);
const AUDIT_TIMEOUT_MS = 15_000;
@@ -12,9 +11,8 @@ if (process.argv.slice(2).some((arg) => arg !== "--strict")) {
process.exit(2);
}
-// Path-scoped exceptions are proved from bun.lock. A GHSA id alone is not enough.
-let repoLock = "";
-try { repoLock = readRepoLock(); } catch { repoLock = ""; }
+// GHSA/CVE -> reason + acceptance date, only when no upstream fix exists.
+const IGNORE = {};
function unavailable(reason) {
console.error(`audit: ${reason}; ${STRICT ? "INCOMPLETE (strict gate failed)" : "SKIPPED (not a security pass)"}`);
process.exit(STRICT ? 2 : 0);
@@ -57,7 +55,7 @@ for (const [pkg, advisories] of Object.entries(report)) {
const ghsa = /(GHSA-[a-z0-9-]+)/i.exec(String(advisory.url ?? ""))?.[1];
const ids = [ghsa, advisory.github_advisory_id, advisory.id, advisory.cve,
...(Array.isArray(advisory.cves) ? advisory.cves : [])].filter(Boolean).map(String);
- if (bracesDevLintAllows(pkg, ids, repoLock)) continue;
+ if (ids.some((id) => Object.hasOwn(IGNORE, id))) continue;
// Print only bounded identifiers, never arbitrary registry text/URLs.
hits.push({ pkg: pkg.replace(/[^a-zA-Z0-9@/_.-]/g, "").slice(0, 160),
id: ghsa ?? "unidentified-advisory", severity: advisory.severity.toUpperCase() });
diff --git a/scripts/audit.test.ts b/scripts/audit.test.ts
index 29cd9bc2..cb5a470d 100644
--- a/scripts/audit.test.ts
+++ b/scripts/audit.test.ts
@@ -44,11 +44,12 @@ describe("dependency audit evidence boundary", () => {
expect(result.status).toBe(1); expect(result.stderr).toContain("GHSA-test-test-test");
expect(result.stderr).not.toContain("private-registry-diagnostic");
});
- it("accepts the dev-lint braces advisory only while bun.lock still matches that chain", () => {
- const allowed = audit(JSON.stringify({ braces: [{ severity: "high", url: "https://github.com/advisories/GHSA-vfj7-8cjw-p6xm" }] }), 1);
- expect(allowed.status).toBe(0);
- const moved = audit(JSON.stringify({ micromatch: [{ severity: "high", url: "https://github.com/advisories/GHSA-vfj7-8cjw-p6xm" }] }), 1);
- expect(moved.status).toBe(1);
+ it("does not exempt the formerly waived braces advisory", () => {
+ for (const pkg of ["braces", "micromatch"]) {
+ const result = audit(JSON.stringify({ [pkg]: [{ severity: "high", url: "https://github.com/advisories/GHSA-vfj7-8cjw-p6xm" }] }), 1);
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain("GHSA-vfj7-8cjw-p6xm");
+ }
});
it("applies the documented high/critical threshold to a valid lower-severity report", () => {
const result = audit(JSON.stringify({ example: [{ severity: "moderate", id: 1 }] }), 1);
diff --git a/scripts/ci-audit-contract.test.ts b/scripts/ci-audit-contract.test.ts
new file mode 100644
index 00000000..5fc79135
--- /dev/null
+++ b/scripts/ci-audit-contract.test.ts
@@ -0,0 +1,28 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+import { parse } from "yaml";
+
+type Step = { name?: string; run?: string; "continue-on-error"?: boolean };
+type Job = { steps: Step[]; permissions?: Record<string, string>; "continue-on-error"?: boolean };
+const workflow = parse(readFileSync(new URL("../.github/workflows/ci.yml", import.meta.url), "utf8")) as {
+ permissions: Record<string, string>;
+ jobs: { verify: Job; "dependency-watch": Job };
+};
+
+describe("CI dependency audit safeguards", () => {
+ it("requires strict validation before the additional native audit", () => {
+ const steps = workflow.jobs.verify.steps;
+ const strict = steps.findIndex(step => step.run === "bun run audit:strict");
+ const native = steps.findIndex(step => step.run === "bun audit --audit-level=high");
+ expect(strict).toBeGreaterThanOrEqual(0);
+ expect(native).toBeGreaterThan(strict);
+ expect(steps[strict]["continue-on-error"]).toBeUndefined();
+ expect(steps[native]["continue-on-error"]).toBeUndefined();
+ expect(workflow.jobs.verify["continue-on-error"]).toBeUndefined();
+ });
+ it("retains scheduled strict auditing and read-only workflow authority", () => {
+ expect(workflow.jobs["dependency-watch"].steps.some(step => step.run === "bun run audit:strict")).toBe(true);
+ expect(workflow.permissions).toEqual({ contents: "read" });
+ expect(workflow.jobs.verify.permissions).toBeUndefined();
+ });
+});
diff --git a/scripts/e2e/ios-lock.mjs b/scripts/e2e/ios-lock.mjs
new file mode 100644
index 00000000..ef39955a
--- /dev/null
+++ b/scripts/e2e/ios-lock.mjs
@@ -0,0 +1,151 @@
+#!/usr/bin/env node
+import sharp from "sharp";
+import { chromium, expect as assertion } from "@playwright/test";
+import { mkdir } from "node:fs/promises";
+import path from "node:path";
+import { releaseFixture } from "./release-fixture.mjs";
+
+process.umask(0o077);
+const expect = assertion.configure({ timeout: 15000 });
+
+const luminance = rgb => rgb.slice(0, 3).map(value => {
+ const channel = value / 255;
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
+}).reduce((sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index], 0);
+async function assertFocusContrast(page, control, label) {
+ const focus = await control.evaluate(element => {
+ const style = getComputedStyle(element), rect = element.getBoundingClientRect();
+ const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d");
+ ctx.fillStyle = style.outlineColor; ctx.fillRect(0, 0, 1, 1);
+ const color = [...ctx.getImageData(0, 0, 1, 1).data];
+ ctx.clearRect(0, 0, 1, 1);
+ ctx.fillStyle = style.boxShadow.slice(0, style.boxShadow.indexOf(")") + 1);
+ ctx.fillRect(0, 0, 1, 1);
+ return { color, shadow: [...ctx.getImageData(0, 0, 1, 1).data], shadowCss: style.boxShadow, width: parseFloat(style.outlineWidth),
+ offset: parseFloat(style.outlineOffset), style: style.outlineStyle,
+ box: { x: rect.x, y: rect.y, width: rect.width, height: rect.height } };
+ });
+ expect(focus.style).toBe("solid");
+ expect(focus.width).toBeGreaterThanOrEqual(2);
+ const { data, info } = await sharp(await page.screenshot()).removeAlpha().raw().toBuffer({ resolveWithObject: true });
+ expect(focus.shadowCss).toContain("4px");
+ expect(focus.shadow[3]).toBe(255);
+ const { x, y, width, height } = focus.box, gap = focus.width + focus.offset + 2;
+ const pixelAt = (sx, sy) => {
+ const pixel = (Math.max(0, Math.min(info.height - 1, Math.round(sy))) * info.width
+ + Math.max(0, Math.min(info.width - 1, Math.round(sx)))) * info.channels;
+ return [...data.subarray(pixel, pixel + 3)];
+ };
+ const bands = [[pixelAt(x + width / 2, y - focus.offset - focus.width / 2), focus.color],
+ [pixelAt(x + width / 2, y - 1), focus.shadow]];
+ for (const [actual, expected] of bands) {
+ expect(Math.max(...actual.map((value, index) => Math.abs(value - expected[index])))).toBeLessThanOrEqual(8);
+ }
+ const samples = [[x + width / 2, y - gap], [x + width / 2, y + height + gap],
+ [x - gap, y + height / 2], [x + width + gap, y + height / 2]];
+ const ratios = samples.map(([sx, sy]) => {
+ const pixel = (Math.max(0, Math.min(info.height - 1, Math.round(sy))) * info.width
+ + Math.max(0, Math.min(info.width - 1, Math.round(sx)))) * info.channels;
+ const bg = [...data.subarray(pixel, pixel + 3)];
+ return Math.max(...[focus.color, focus.shadow].map(color => {
+ const fg = color.slice(0, 3).map((value, i) => value * color[3] / 255 + bg[i] * (1 - color[3] / 255));
+ const a = luminance(fg), b = luminance(bg);
+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
+ }));
+ });
+ console.log("FOCUS", label, JSON.stringify({ outline: focus.color, shadow: focus.shadow, ratios }));
+ expect(Math.min(...ratios)).toBeGreaterThanOrEqual(3);
+}
+
+const fixture = await releaseFixture();
+const output = process.env.MSO_SCREENSHOT_DIR;
+if (output) await mkdir(output, { recursive: true, mode: 0o700 });
+let browser;
+try {
+ browser = await chromium.launch({ headless: true });
+ for (const viewport of [{ width: 390, height: 844 }, { width: 768, height: 1024 }]) {
+ for (const theme of ["light", "dark"]) {
+ const context = await browser.newContext({ viewport, hasTouch: true, reducedMotion: "reduce", colorScheme: theme });
+ const external = [];
+ await context.route("**/*", async route => {
+ const url = new URL(route.request().url());
+ if (url.origin === fixture.base) await route.continue();
+ else { external.push(url.hostname); await route.abort(); }
+ });
+ await context.addInitScript(({ theme }) => {
+ localStorage.setItem("sv:shell", JSON.stringify({ desktop: "macos", mobile: "ios" }));
+ localStorage.setItem("mso:onboarding:v1", "done");
+ window.__geolocationCalls = 0;
+ Object.defineProperty(navigator, "geolocation", { configurable: true, value: {
+ getCurrentPosition() { window.__geolocationCalls++; throw new Error("Unexpected location request"); },
+ } });
+ }, { theme });
+ const page = await context.newPage();
+ const errors = [];
+ page.on("pageerror", error => errors.push(error.message));
+ await page.goto(fixture.base);
+ await expect(page.locator('#main-content[data-shell="ios"]')).toBeVisible();
+ await page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
+ const search = page.getByRole("combobox", { name: "Spotlight search" });
+ await page.locator('[data-slot="ios-search-pill"]').focus();
+ await page.keyboard.press("Control+k");
+ await expect(search).toBeVisible();
+ await search.fill("Lock screen");
+ await page.keyboard.press("Enter");
+ const face = page.locator('[data-slot="ios-lock"]');
+ await expect(face).toBeVisible();
+ const unlock = face.getByRole("button", { name: "Unlock", exact: true });
+ const light = face.getByRole("button", { name: "Screen light", exact: true });
+ await expect(unlock).toBeFocused();
+ expect((await unlock.boundingBox()).height).toBeGreaterThanOrEqual(44);
+ await expect(face.getByText("Weather unavailable", { exact: true })).toBeVisible();
+ await expect(face.locator('[data-slot="ios-lock-camera"]')).toHaveCount(0);
+ await assertFocusContrast(page, unlock, `${viewport.width} ${theme} Unlock`);
+ await page.keyboard.press("Tab");
+ await expect(light).toBeFocused();
+ await assertFocusContrast(page, light, `${viewport.width} ${theme} Screen light`);
+ await page.keyboard.press("Space");
+ await expect(light).toHaveAttribute("aria-pressed", "true");
+ await assertFocusContrast(page, light, `${viewport.width} ${theme} Screen light ON`);
+ await page.keyboard.press("Space");
+ await expect(light).toHaveAttribute("aria-pressed", "false");
+ await page.keyboard.press("Tab");
+ await expect(unlock).toBeFocused();
+ expect(await page.evaluate(() => window.__geolocationCalls)).toBe(0);
+ expect(external.filter(host => /open-meteo|bigdatacloud/.test(host))).toEqual([]);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);
+ if (output) await page.screenshot({ path: path.join(output, `ios-lock-${viewport.width}-${theme}.png`) });
+ await page.keyboard.press("Enter");
+ await expect(face).toHaveCount(0);
+ await expect(page.locator('[data-slot="ios-search-pill"]')).toBeFocused();
+ const tile = page.locator('button[aria-label="Files"]:visible').first();
+ await tile.click({ button: "right" });
+ const menu = page.locator('[data-slot="ios-quick-actions"]');
+ await expect(menu).toBeVisible();
+ await expect(menu.getByRole("menuitem", { name: "Hide from Home", exact: true })).toBeVisible();
+ await expect(menu.getByRole("menuitem", { name: "Lock screen", exact: true })).toBeVisible();
+ await expect(menu.getByText("Require Face ID", { exact: true })).toHaveCount(0);
+ await menu.getByRole("menuitem", { name: "Lock screen", exact: true }).click();
+ await expect(face).toBeVisible();
+ await unlock.click();
+ await expect(face).toHaveCount(0);
+ await page.setViewportSize({ width: 1024, height: 768 });
+ await expect(page.locator('#main-content[data-shell="macos"]')).toBeVisible();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);
+ await page.keyboard.press("Control+k");
+ await expect(search).toBeVisible();
+ await search.fill("Lock screen");
+ await page.keyboard.press("Enter");
+ await expect(page.getByText("Click to unlock", { exact: true })).toBeVisible();
+ await expect(page.locator('[data-slot="ios-lock"]')).toHaveCount(0);
+ await page.keyboard.press("Space");
+ await expect(page.getByText("Click to unlock", { exact: true })).toHaveCount(0);
+ expect(errors).toEqual([]);
+ console.log(`PASS iOS lock ${viewport.width}x${viewport.height} ${theme}: focus, keyboard,44px, privacy, action labels, landscape, no page errors`);
+ await context.close();
+ }
+ }
+} finally {
+ await browser?.close();
+ await fixture.close();
+}
diff --git a/scripts/e2e/macos-figma.mjs b/scripts/e2e/macos-figma.mjs
new file mode 100644
index 00000000..a6c6ddb2
--- /dev/null
+++ b/scripts/e2e/macos-figma.mjs
@@ -0,0 +1,194 @@
+#!/usr/bin/env node
+import { chromium, expect } from "@playwright/test";
+import AxeBuilder from "@axe-core/playwright";
+import { mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { desktopMenu, menuEvidence } from "./macos-menu-evidence.mjs";
+import { releaseFixture } from "./release-fixture.mjs";
+
+process.umask(0o077);
+const dir = path.resolve(process.env.MSO_SCREENSHOT_DIR || "zz-macos-qa");
+await mkdir(dir, { recursive: true });
+const fixture = await releaseFixture();
+const browser = await chromium.launch({ headless: true });
+const results = [];
+const screenshots = [];
+let page;
+async function shot(name) {
+ const file = path.join(dir, name + ".png");
+ await page.screenshot({ path: file });
+ screenshots.push(file);
+}
+async function check(name, run) {
+ try { await run(); results.push({ name, passed: true }); console.log("PASS", name); }
+ catch (e) { results.push({ name, passed: false, error: e.message }); console.log("FAIL", name, e.message); await page.keyboard.press("Escape"); await page.keyboard.press("Escape"); }
+}
+try {
+ const context = await browser.newContext({ viewport: { width: 1512, height: 982 } });
+ await context.addInitScript(() => {
+ localStorage.setItem("mso:onboarding:v1", "done");
+ localStorage.setItem("sv:shell", JSON.stringify({ desktop: "macos", mobile: "ios" }));
+ });
+ page = await context.newPage();
+ const errors = [];
+ page.on("pageerror", e => errors.push(e.message));
+ await page.goto(fixture.base);
+ await expect(page.locator('#main-content[data-shell="macos"]')).toBeVisible();
+ const wallpaper = page.locator("div.wp-aurora.absolute.inset-0");
+ const wallpaperUrl = () => wallpaper.evaluate(el => getComputedStyle(el).backgroundImage.split('"')[1]);
+ if ((await wallpaperUrl()).includes("aurora-dark")) await page.getByRole("button", { name: "Toggle theme", exact: true }).click();
+ await expect.poll(async () => (await wallpaperUrl()).includes("aurora.webp")).toBe(true);
+ await shot("light-desktop");
+ await check("34px menu bar and canonical WebP wallpaper", async () => {
+ expect((await page.locator(".macos-menubar").boundingBox()).height).toBe(34);
+ expect(await wallpaperUrl()).toContain("/wallpapers/aurora.webp");
+ const response = await page.request.get(await wallpaperUrl());
+ expect(response.ok()).toBe(true);
+ const bytes = (await response.body()).length;
+ expect(bytes).toBeLessThan(100_000);
+ results.push({ name: "light wallpaper delivered bytes", bytes });
+ });
+ await page.getByRole("link", { name: /^(System )?Settings(?: \(running\))?$/ }).first().click();
+ const win = page.locator('[data-window][data-app="os-settings"]').last();
+ await expect(win).toBeVisible();
+ await check("52px titlebar, 16px window radius, 24px control targets", async () => {
+ await expect.poll(async () => (await win.locator(".macos-titlebar").boundingBox()).height).toBe(52);
+ expect(await win.evaluate(el => getComputedStyle(el).borderRadius)).toBe("16px");
+ for (const b of await win.locator(".macos-light-button").all()) expect((await b.boundingBox()).width).toBe(24);
+ expect((await win.locator(".macos-light").first().boundingBox()).width).toBe(14);
+ });
+ await expect(page.getByText(/Loading settings/)).toHaveCount(0);
+ await shot("light-window");
+
+ await menuEvidence({ page, check, shot }, "light");
+ await check("menu opens by keyboard, arrow navigation, Escape restores trigger", async () => {
+ const trigger = page.locator(".macos-menubar").getByRole("button", { name: "View", exact: true });
+ await trigger.focus(); await page.keyboard.press("Enter");
+ await expect(page.locator(".macos-menu")).toBeVisible();
+ await page.keyboard.press("ArrowDown"); await shot("light-menu");
+ await page.keyboard.press("Escape"); await expect(page.locator(".macos-menu")).toHaveCount(0);
+ await expect(trigger).toBeFocused();
+ });
+ await check("maximize, restore and window drag", async () => {
+ const before = await win.boundingBox();
+ await win.getByRole("button", { name: "Maximize window" }).click();
+ await expect.poll(async () => (await win.boundingBox()).width).toBe(1496);
+ await win.getByRole("button", { name: "Maximize window" }).click();
+ await expect.poll(async () => (await win.boundingBox()).width).toBe(before.width);
+ const bar = await win.locator(".macos-titlebar").boundingBox();
+ await page.mouse.move(bar.x + bar.width / 2, bar.y + 25); await page.mouse.down();
+ await page.mouse.move(bar.x + bar.width / 2 + 70, bar.y + 65, { steps: 8 }); await page.mouse.up();
+ await expect.poll(async () => (await win.boundingBox()).x).toBeGreaterThan(before.x);
+ });
+ await check("resize keeps titlebar reachable", async () => {
+ const before = await win.boundingBox();
+ const handle = await win.locator(".cursor-nwse-resize").boundingBox();
+ await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2); await page.mouse.down();
+ await page.mouse.move(before.x + before.width + 45, before.y + before.height + 35, { steps: 8 }); await page.mouse.up();
+ await expect.poll(async () => (await win.boundingBox()).width).toBeGreaterThan(before.width);
+ expect((await win.boundingBox()).y).toBeGreaterThanOrEqual(34);
+ });
+ await check("minimize and repeated dock activation restore a single window", async () => {
+ await win.getByRole("button", { name: "Minimize window" }).click(); await expect(win).toHaveCount(0);
+ const dock = page.locator(".macos-dock").getByRole("link", { name: /Settings/ }).first();
+ await dock.click(); await expect(win).toBeVisible();
+ await expect.poll(() => win.evaluate(el => getComputedStyle(el).animationName)).toContain("winOpen");
+ await dock.click();
+ await expect(page.locator('[data-window][data-app="os-settings"]')).toHaveCount(1);
+ await dock.focus(); await expect(dock).toBeFocused();
+ });
+ await page.getByRole("button", { name: "Toggle theme", exact: true }).click();
+ await expect.poll(async () => (await wallpaperUrl()).includes("aurora-dark.webp")).toBe(true);
+ await expect(page.getByText(/Loading settings/)).toHaveCount(0);
+ await expect.poll(() => win.evaluate(el => getComputedStyle(el).backgroundColor)).toBe("rgb(30, 30, 30)");
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ await shot("dark-window");
+ await check("settled dark settings content contrast", async () => {
+ const axe = await new AxeBuilder({ page }).include('[data-window][data-app="os-settings"]').withRules(["color-contrast"]).analyze();
+ expect(axe.violations.map(v => ({ id: v.id, targets: v.nodes.map(n => ({ target: n.target, summary: n.failureSummary })) }))).toEqual([]);
+ });
+ await menuEvidence({ page, check, shot }, "dark");
+ await check("dark wallpaper uses canonical WebP asset", async () => {
+ const response = await page.request.get(await wallpaperUrl());
+ const bytes = (await response.body()).length; expect(response.ok()).toBe(true); expect(bytes).toBeLessThan(100_000);
+ results.push({ name: "dark wallpaper delivered bytes", bytes });
+ });
+ await check("dark chrome WCAG A/AA accessibility", async () => {
+ const axe = await new AxeBuilder({ page }).include(".macos-menubar").include(".macos-titlebar").include(".macos-dock").withTags(["wcag2a", "wcag2aa", "wcag21aa"]).analyze();
+ expect(axe.violations.map(v => ({ id: v.id, targets: v.nodes.map(n => n.target) }))).toEqual([]);
+ });
+ await page.locator(".macos-menubar").getByRole("button", { name: "Window", exact: true }).click();
+ await shot("dark-menu"); await page.keyboard.press("Escape");
+ await check("close removes window and Escape dismisses Spotlight", async () => {
+ await win.getByRole("button", { name: "Close window" }).click(); await expect(win).toHaveCount(0);
+ await page.getByRole("button", { name: "Spotlight (⌘K)", exact: true }).click();
+ await expect(page.getByRole("combobox", { name: "Spotlight search" })).toBeVisible();
+ await expect(page.getByRole("combobox", { name: "Spotlight search" })).toBeFocused();
+ await page.keyboard.press("Escape");
+ await expect(page.getByRole("combobox", { name: "Spotlight search" })).toHaveCount(0);
+ await expect(page.getByRole("button", { name: "Spotlight (⌘K)", exact: true })).toBeFocused();
+ });
+ for (const width of [844, 390]) {
+ await page.setViewportSize({ width, height: width === 390 ? 844 : 700 });
+ await check(width + "px responsive fallback", async () => {
+ await expect(page.locator("#main-content")).toHaveAttribute("data-shell", width < 768 ? "ios" : "macos");
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
+ if (width < 768) await expect(page.getByRole("button", { name: "Go to page 2", exact: true })).toBeVisible();
+ if (width >= 768) {
+ for (const name of ["Help", "MSO"]) {
+ const trigger = page.locator(".macos-menubar").getByRole("button", { name, exact: true });
+ await trigger.focus(); await trigger.scrollIntoViewIfNeeded();
+ await expect.poll(async () => { const b = await trigger.boundingBox(); return b.x >= 0 && b.x + b.width <= width; }).toBe(true);
+ }
+ await page.mouse.move(width / 2, 300);
+ const links = page.locator(".macos-dock").getByRole("link");
+ for (const link of [links.first(), links.last()]) {
+ await link.focus(); await link.scrollIntoViewIfNeeded();
+ await expect.poll(async () => { const b = await link.boundingBox(); return b.x >= 0 && b.x + b.width <= width; }).toBe(true);
+ }
+ }
+ });
+ await shot("responsive-" + width);
+ }
+ await page.setViewportSize({ width: 844, height: 390 });
+ await check("short desktop keeps compact titlebar and 24px window targets", async () => {
+ await expect(page.locator(".macos-menubar")).toBeVisible();
+ await page.locator(".macos-dock").getByRole("link", { name: /Settings/ }).first().click();
+ await expect.poll(async () => (await win.locator(".macos-titlebar").boundingBox()).height).toBe(32);
+ for (const b of await win.locator(".macos-light-button").all()) expect((await b.boundingBox()).height).toBe(24);
+ await shot("short-desktop-window");
+ await win.getByRole("button", { name: "Close window" }).click(); await expect(win).toHaveCount(0);
+ });
+ await check("coarse-pointer desktop preserves 44px context targets", async () => {
+ const touch = await browser.newContext({ viewport: { width: 1512, height: 982 }, hasTouch: true });
+ await touch.addInitScript(() => localStorage.setItem("mso:onboarding:v1", "done"));
+ const p = await touch.newPage();
+ await p.goto(fixture.base);
+ await expect(p.locator('#main-content[data-shell="macos"]')).toBeVisible();
+ await expect(p.locator(".macos-menubar")).toBeVisible();
+ await p.mouse.click(40, 700, { button: "right" });
+ const menu = p.locator('.macos-menu[role="menu"]');
+ await expect(menu).toBeVisible();
+ await expect.poll(async () => (await menu.boundingBox()).width).toBe(244);
+ for (const item of await menu.getByRole("menuitem").all()) expect((await item.boundingBox()).height).toBeGreaterThanOrEqual(44);
+ await touch.close();
+ });
+ await page.setViewportSize({ width: 1512, height: 982 });
+ await expect(page.locator(".macos-menubar")).toBeVisible();
+ await check("Windows and macOS switching preserves scoped chrome", async () => {
+ const macMenu = await desktopMenu(page, "View as Windows");
+ await macMenu.getByRole("menuitem", { name: "View as Windows", exact: true }).click();
+ await expect(page.locator("#main-content")).toHaveAttribute("data-shell", "windows");
+ await expect(page.locator(".macos-menubar")).toHaveCount(0);
+ const windowsMenu = await desktopMenu(page, "View as macOS");
+ await expect(windowsMenu).not.toHaveClass(/macos-menu/);
+ await windowsMenu.getByRole("menuitem", { name: "View as macOS", exact: true }).click();
+ await expect(page.locator(".macos-menubar")).toBeVisible();
+ await menuEvidence({ page, check, shot }, "returned-macos");
+ });
+ await check("no uncaught browser errors", async () => expect(errors).toEqual([]));
+} finally {
+ await writeFile(path.join(dir, "report.json"), JSON.stringify({ results, screenshots }, null, 2));
+ await browser.close(); await fixture.close();
+}
+if (results.some(r => r.passed === false)) process.exitCode = 1;
diff --git a/scripts/e2e/macos-menu-evidence.mjs b/scripts/e2e/macos-menu-evidence.mjs
new file mode 100644
index 00000000..21b06d26
--- /dev/null
+++ b/scripts/e2e/macos-menu-evidence.mjs
@@ -0,0 +1,63 @@
+import { expect } from "@playwright/test";
+import AxeBuilder from "@axe-core/playwright";
+
+export async function menuEvidence({ page, check, shot }, theme) {
+ await check(theme + " chrome WCAG A/AA", async () => {
+ const axe = await new AxeBuilder({ page }).include(".macos-menubar").include(".macos-titlebar").include(".macos-dock").withTags(["wcag2a", "wcag2aa", "wcag21aa"]).analyze();
+ expect(axe.violations.map(v => ({ id: v.id, targets: v.nodes.map(n => n.target) }))).toEqual([]);
+ });
+ await check(theme + " desktop context menu bounds and radius", async () => {
+ await page.mouse.click(1504, 160, { button: "right" });
+ const menu = page.locator('.macos-menu[role="menu"]');
+ await expect(menu).toBeVisible();
+ await expect.poll(async () => (await menu.boundingBox()).width).toBe(244);
+ const box = await menu.boundingBox();
+ expect(box.width).toBe(244);
+ expect(box.x + box.width).toBeLessThanOrEqual(1512);
+ expect(box.y + box.height).toBeLessThanOrEqual(982);
+ expect(await menu.evaluate(el => getComputedStyle(el).borderRadius)).toBe("12px");
+ for (const item of await menu.getByRole("menuitem").all()) expect((await item.boundingBox()).height).toBeGreaterThanOrEqual(24);
+ await page.mouse.move(750, 50);
+ await page.keyboard.press("ArrowDown");
+ await expect.poll(() => page.evaluate(() => getComputedStyle(document.activeElement).color)).toBe("rgb(255, 255, 255)");
+ await expect.poll(() => page.evaluate(() => getComputedStyle(document.activeElement).backgroundColor)).toBe("rgb(0, 98, 230)");
+ await shot(theme + "-context-menu");
+ const axe = await new AxeBuilder({ page }).include(".macos-menu").withTags(["wcag2a", "wcag2aa", "wcag21aa"]).analyze();
+ await page.keyboard.press("Escape");
+ await expect(menu).toHaveCount(0);
+ expect(axe.violations.map(v => ({ id: v.id, targets: v.nodes.map(n => n.target) }))).toEqual([]);
+ });
+ await check(theme + " open menu WCAG A/AA", async () => {
+ await page.locator(".macos-menubar").getByRole("button", { name: "View", exact: true }).click();
+ const menu = page.locator(".macos-menu");
+ await expect(menu).toBeVisible();
+ expect(await menu.evaluate(el => getComputedStyle(el).borderRadius)).toBe("12px");
+ const axe = await new AxeBuilder({ page }).include(".macos-menu").withTags(["wcag2a", "wcag2aa", "wcag21aa"]).analyze();
+ await page.keyboard.press("Escape");
+ expect(axe.violations.map(v => ({ id: v.id, targets: v.nodes.map(n => n.target) }))).toEqual([]);
+ });
+ }
+
+export async function desktopMenu(page, itemName) {
+ const surface = page.locator("#main-content");
+ const viewport = page.viewportSize();
+ console.log("SHELL_SWITCH_GEOMETRY", JSON.stringify({ before: await surface.boundingBox(), viewport }));
+ await expect.poll(async () => {
+ const box = await surface.boundingBox();
+ return { width: Math.round(box.width), height: Math.round(box.height) };
+ }).toEqual(viewport);
+ const point = await surface.locator("section").first().evaluate(section => {
+ const rect = section.getBoundingClientRect();
+ for (const x of [rect.right - 8, rect.left + rect.width / 2, rect.left + 8]) {
+ for (const y of [rect.top + rect.height / 2, rect.top + 16, rect.bottom - 160]) {
+ if (document.elementFromPoint(x, y) === section) return { x, y };
+ }
+ }
+ throw new Error("No bare desktop target found");
+ });
+ await page.mouse.click(point.x, point.y, { button: "right" });
+ const menu = page.getByRole("menu").last();
+ await expect(menu).toBeVisible();
+ await expect(menu.getByRole("menuitem", { name: itemName, exact: true })).toBeVisible();
+ return menu;
+}
diff --git a/scripts/install-native.test.ts b/scripts/install-native.test.ts
index 796e0dae..6d2fe605 100644
--- a/scripts/install-native.test.ts
+++ b/scripts/install-native.test.ts
@@ -19,8 +19,12 @@ function install(name: string, seed?: (root: string) => void, fileSystem = fs) {
}
describe("native installer atomic private environment creation", () => {
it("creates a private file and preserves an existing environment", () => {
- const file = install("fresh"); expect(fs.statSync(file).mode & 0o777).toBe(0o600);
- expect(fs.readFileSync(file, "utf8")).toContain("OS_SESSION_SECRET=");
+ const file = install("fresh");
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
+ try {
+ expect(fs.fstatSync(fd).mode & 0o777).toBe(0o600);
+ expect(fs.readFileSync(fd, "utf8")).toContain("OS_SESSION_SECRET=");
+ } finally { fs.closeSync(fd); }
const existing = install("existing", root => fs.writeFileSync(path.join(root, ".env.local"), "keep"));
expect(fs.readFileSync(existing, "utf8")).toBe("keep");
});
diff --git a/scripts/install-node-gyp.test.ts b/scripts/install-node-gyp.test.ts
index 2963d097..f0e0056b 100644
--- a/scripts/install-node-gyp.test.ts
+++ b/scripts/install-node-gyp.test.ts
@@ -53,6 +53,8 @@ describe("locked isolated node-gyp bootstrap", () => {
expect(Object.keys(lock.packages).some((name) => /http-cache-semantics|make-fetch-happen/.test(name))).toBe(false);
expect(VERSION).toMatch(/^\d+\.\d+\.\d+$/);
expect(lock.lockfileVersion).toBe(3);
+ expect(lock.packages["node_modules/http-cache-semantics"]).toBeUndefined();
+ expect(lock.packages["node_modules/make-fetch-happen"]).toBeUndefined();
for (const [name, row] of Object.entries(lock.packages) as [string, { version: string; resolved: string; integrity: string }][]) {
if (!name) continue;
expect(row.version).toMatch(/^\d+\.\d+\.\d+/);
diff --git a/scripts/next-eslint-root-dirs.test.ts b/scripts/next-eslint-root-dirs.test.ts
new file mode 100644
index 00000000..75c41cf2
--- /dev/null
+++ b/scripts/next-eslint-root-dirs.test.ts
@@ -0,0 +1,161 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { createRequire } from "node:module";
+import { Linter, type ESLint } from "eslint";
+import { afterEach, describe, expect, it } from "vitest";
+
+const require = createRequire(import.meta.url);
+const plugin = require("@next/eslint-plugin-next") as ESLint.Plugin;
+const { getRootDirs } = require("@next/eslint-plugin-next/dist/utils/get-root-dirs.js") as {
+ getRootDirs(context: { cwd: string; settings: { next?: { rootDir?: unknown } } }): string[];
+};
+const roots: string[] = [];
+afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
+
+function fixture() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-next-glob-"));
+ roots.push(root);
+ for (const dir of ["one/pages", "one/nested/app", "two/pages", ".hidden", "with space/pages"]) {
+ fs.mkdirSync(path.join(root, dir), { recursive: true });
+ }
+ fs.writeFileSync(path.join(root, "one/pages/about.js"), "export default function About() {}\n");
+ fs.writeFileSync(path.join(root, "two/pages/contact.js"), "export default function Contact() {}\n");
+ fs.writeFileSync(path.join(root, "not-a-directory"), "fixture");
+ const resolve = (rootDir?: unknown) => getRootDirs({ cwd: root, settings: { next: { rootDir } } });
+ return { root, resolve, one: path.join(root, "one"), two: path.join(root, "two") };
+}
+
+function messages(rootDir: string, href: string) {
+ return new Linter().verify(`export default () => <a href="${href}">Link</a>`, [{
+ languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } },
+ settings: { next: { rootDir } },
+ plugins: { "@next/next": plugin },
+ rules: { "@next/next/no-html-link-for-pages": "error" },
+ }]);
+}
+
+describe("Next ESLint root discovery without the vulnerable braces chain", () => {
+ it("uses the maintained replacement only for the audited Next plugin consumer", () => {
+ const lock = JSON.parse(fs.readFileSync("bun.lock", "utf8").replace(/,(\s*[}\]])/g, "$1"));
+ expect(require("fast-glob/package.json").name).toBe("fast-glob");
+ expect(require("micromatch/package.json").name).toBe("picomatch");
+ expect(require("micromatch/package.json").version).toBe("2.3.2");
+ expect(require("fast-glob/package.json").version).toBe("3.3.1");
+ expect(lock.packages.braces).toBeUndefined();
+ expect(lock.packages.micromatch[0]).toBe("[email protected]");
+ const consumers = Object.entries(lock.packages).filter(([, row]) => {
+ const entry = row as [string, string, { dependencies?: Record<string, string> }];
+ return Object.hasOwn(entry[2]?.dependencies ?? {}, "micromatch");
+ }).map(([name]) => name);
+ expect(consumers).toEqual(["fast-glob"]);
+ });
+
+ it("preserves default cwd and literal roots without expanding descendants", () => {
+ const f = fixture();
+ expect(f.resolve()).toEqual([f.root]);
+ expect(f.resolve(f.one)).toEqual([f.one]);
+ const relative = path.relative(process.cwd(), f.one).replace(/\\/g, "/");
+ expect(f.resolve(relative)).toEqual([relative]);
+ expect(f.resolve(path.join(f.root, "with space"))).toEqual([path.join(f.root, "with space")]);
+ expect(f.resolve(path.join(f.root, "absent"))).toEqual([]);
+ expect(f.resolve(path.join(f.root, "not-a-directory"))).toEqual([]);
+ });
+
+ it("preserves directory-only wildcards, braces, extglobs and hidden-file defaults", () => {
+ const f = fixture();
+ expect(f.resolve(`${f.root}/*`).sort()).toEqual([f.one, f.two, path.join(f.root, "with space")].sort());
+ expect(f.resolve(`${f.root}/{one,two}`).sort()).toEqual([f.one, f.two]);
+ expect(f.resolve(`${f.root}/@(one|two)`).sort()).toEqual([f.one, f.two]);
+ expect(f.resolve(`${f.root}/!(two)`).sort()).toEqual([f.one, path.join(f.root, ".hidden"), path.join(f.root, "with space")].sort());
+ expect(f.resolve(`${f.root}/.*`)).toEqual([path.join(f.root, ".hidden")]);
+ });
+
+ it("keeps Next's per-pattern array semantics and Windows slash normalization", () => {
+ const f = fixture();
+ expect(f.resolve([f.two, f.one, 7])).toEqual([f.two, f.one]);
+ expect(f.resolve(`!${f.one}`)).toEqual([]);
+ expect(f.resolve([`${f.root}/{one,two}`, `!${f.two}`]).sort()).toEqual([f.one, f.two]);
+ expect(f.resolve(f.one.replace(/\//g, "\\"))).toEqual([f.one]);
+ });
+
+ it("follows directory symlinks without treating a literal root as recursive", () => {
+ const f = fixture(), alias = path.join(f.root, "linked");
+ fs.symlinkSync(f.one, alias, process.platform === "win32" ? "junction" : "dir");
+ expect(f.resolve(alias)).toEqual([alias]);
+ expect(f.resolve(`${f.root}/link*`)).toEqual([alias]);
+ });
+
+ it("still reports forbidden Next page links for literal and globbed roots", () => {
+ const f = fixture();
+ for (const rootDir of [f.one, `${f.root}/{one,two}`, `${f.root}/*`]) {
+ expect(messages(rootDir, "/about")).toEqual([expect.objectContaining({
+ ruleId: "@next/next/no-html-link-for-pages", severity: 2,
+ })]);
+ expect(messages(rootDir, "https://example.com/about")).toEqual([]);
+ }
+ });
+ it("preserves trailing slashes and recursive roots without including their parent", () => {
+ const f = fixture();
+ expect(f.resolve(`${f.one}/`)).toEqual([`${f.one}/`]);
+ expect(f.resolve(`${f.one}/**`).sort()).toEqual([
+ `${f.one}/nested`, `${f.one}/nested/app`, `${f.one}/pages`,
+ ]);
+ const alias = path.join(f.root, "linked");
+ fs.symlinkSync(f.one, alias, process.platform === "win32" ? "junction" : "dir");
+ expect(f.resolve(`${alias}/**`).sort()).toEqual([
+ `${alias}/nested`, `${alias}/nested/app`, `${alias}/pages`,
+ ]);
+ });
+
+ it("preserves brace alternatives, ranges, escaping and deduplication", () => {
+ const { expandBraceExpansion: expand } = require("fast-glob/out/utils/pattern.js") as {
+ expandBraceExpansion(pattern: string): string[];
+ };
+ const cases: [string, string[]][] = [
+ ["{a,a,b}", ["a", "b"]],
+ ["x{a,{b,c}}y", ["xay", "xby", "xcy"]],
+ ["{1..3}", ["1", "2", "3"]],
+ ["{03..01}", ["03", "02", "01"]],
+ ["{a..c}", ["a", "b", "c"]],
+ ["{a,b}{1,2}", ["a1", "a2", "b1", "b2"]],
+ [String.raw`a\{b,c\}`, ["a{b,c}"]],
+ [String.raw`a{b\,c,d}`, ["ad", "ab,c"]],
+ ["{a,}", ["a"]],
+ ["a/{b,}/{c,}/*", ["a///*", "a/b//*", "a//c/*", "a/b/c/*"]],
+ ["${a,b}", ["${a,b}"]],
+ ["{{a,b}}", ["{a}", "{b}"]],
+ ];
+ for (const [pattern, expected] of cases) expect(expand(pattern), pattern).toEqual(expected);
+ expect(expand(String.raw`\{`.repeat(40))).toEqual(["{".repeat(40)]);
+ });
+
+ it("fails closed on excessive range, product, nesting or input size", () => {
+ const { expandBraceExpansion: expand } = require("fast-glob/out/utils/pattern.js") as {
+ expandBraceExpansion(pattern: string): string[];
+ };
+ expect(expand("{1..1000}")).toHaveLength(1000);
+ expect(() => expand("{1..1001}")).toThrow("exceeds 1000 results");
+ expect(() => expand("{a,b}".repeat(10))).toThrow(RangeError);
+ expect(() => expand("{".repeat(33) + "a,b" + "}".repeat(33))).toThrow("exceeds 32 levels");
+ expect(() => expand("a".repeat(4097))).toThrow("exceeds 4096 characters");
+ });
+
+ it("rejects every library truncation limit consistently through CJS and ESM", async () => {
+ type Expand = (pattern: string, options?: {
+ max?: number; maxLength?: number; maxDepth?: number; maxRewrites?: number;
+ }) => string[];
+ const cjs = require("brace-expansion") as { expand: Expand };
+ const esm = await import("brace-expansion");
+ for (const expand of [cjs.expand, esm.expand]) {
+ expect(expand("{1..2}", { max: 2, maxLength: 2 })).toEqual(["1", "2"]);
+ expect(() => expand("{1..3}", { max: 2 })).toThrow("configured result limit");
+ expect(() => expand("{aa,bb}", { maxLength: 2 })).toThrow("configured length limit");
+ expect(() => expand(String.raw`\{`.repeat(20) + "{a,b}", { maxLength: 20 })).toThrow("configured length limit");
+ expect(() => expand("x{a,{b,c}}y", { maxDepth: 0 })).toThrow("configured depth limit");
+ expect(() => expand("{a},b}", { maxRewrites: 0 })).toThrow("configured rewrite limit");
+ expect(() => expand("{a}" + "}".repeat(40) + ",z}", { maxRewrites: 32 })).toThrow("configured rewrite limit");
+ }
+ });
+
+});
diff --git a/scripts/verify-build.sh b/scripts/verify-build.sh
index 70ba7478..d054b691 100755
--- a/scripts/verify-build.sh
+++ b/scripts/verify-build.sh
@@ -95,6 +95,12 @@ if ! node scripts/e2e/bundle-performance.mjs; then
exit 43
fi
+echo "== verify reviewed macOS chrome"
+node scripts/e2e/macos-figma.mjs
+
+echo "== verify privacy-safe iOS lock"
+node scripts/e2e/ios-lock.mjs
+
# Optional deeper media/native acceptance, using the same isolated built tree.
if [ "${1:-}" = "--extended" ]; then
echo "== verify extended: desktop native acceptance"
diff --git a/scripts/worktree-gates.test.ts b/scripts/worktree-gates.test.ts
index e8ca056d..fd7692b4 100644
--- a/scripts/worktree-gates.test.ts
+++ b/scripts/worktree-gates.test.ts
@@ -58,6 +58,8 @@ function fixture(script: string) {
["scripts/e2e/bundle-performance.mjs", "deferred performance"],
["scripts/e2e/google-integrations.mjs", "native Google UI"],
["scripts/e2e/assistant-chat-ux.mjs", "Assistant chat UX"],
+ ["scripts/e2e/macos-figma.mjs", "macOS chrome"],
+ ["scripts/e2e/ios-lock.mjs", "iOS lock"],
]) {
writeFileSync(path.join(repo, file),
`import fs from 'node:fs'; if (!fs.existsSync('.build-verified') || fs.existsSync('.env.local')) throw Error('unsafe bundle fixture'); console.log('isolated ${label} fixture passed');`);
@@ -136,6 +138,8 @@ describe("isolated worktree release guards", () => {
expect(run.stdout).toContain("isolated deferred performance fixture passed");
expect(run.stdout).toContain("isolated native Google UI fixture passed");
expect(run.stdout).toContain("isolated Assistant chat UX fixture passed");
+ expect(run.stdout).toContain("isolated macOS chrome fixture passed");
+ expect(run.stdout).toContain("isolated iOS lock fixture passed");
expect(readFileSync(path.join(repo, ".next/keep"), "utf8")).toBe(
"live marker",
);