Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
fix(mcp): repair observation workflows and connection diagnostics
Abdurrahman Fakhrul7c90d9435052
diff --git a/.env.example b/.env.exampleindex d0bea876..012e72fb 100644--- a/.env.example+++ b/.env.example@@ -154,6 +154,10 @@ OS_SESSION_SECRET=# usable the policy emits `frame-ancestors 'none'` and the window stays blank —# closed, on purpose, rather than naming a guessed origin as a permitted framer.# OS_PUBLIC_ORIGIN=https://mso.example.com+# Optional operator-declared role shown in private connection diagnostics.+# Allowed: development, test, staging, production. Unset/invalid means not configured.+# This is independent of NODE_ENV; a production build does not identify a production host.+# OS_INSTANCE_ENVIRONMENT=staging# Compatibility fallbacks for MCP/browser origin discovery when OS_PUBLIC_ORIGIN is unset.# Prefer OS_PUBLIC_ORIGIN for normal MSO deployments.# APP_URL=https://mso.example.comdiff --git a/app/api/mcp/tokens/route.test.ts b/app/api/mcp/tokens/route.test.tsindex 28c2d83c..6627bed5 100644--- a/app/api/mcp/tokens/route.test.ts+++ b/app/api/mcp/tokens/route.test.ts@@ -4,6 +4,7 @@ const mocks = vi.hoisted(() => ({verifyAuth: vi.fn(async () => true),listTokens: vi.fn(async () => []),publicOrigin: vi.fn(() => "https://mso.example.test"),+ getRuntimeIdentity: vi.fn(() => ({ hostname: "fixture-host", serviceUser: "fixture-user", runtimeInstanceId: "runtime-fixture", environment: null })),mintPatToken: vi.fn(async (input: { label: string; scope: string; ttlDays?: number | null }) => ({rawToken: "mso_pat_test123",tokenView: {@@ -18,6 +19,7 @@ const mocks = vi.hoisted(() => ({})),}));+vi.mock("@/lib/host/system-api", () => ({ getRuntimeIdentity: mocks.getRuntimeIdentity }));vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));vi.mock("@/lib/mcp/store", () => ({listTokens: mocks.listTokens,@@ -38,7 +40,8 @@ describe("Settings MCP state", () => {const request = new Request("http://127.0.0.1:4005/api/mcp/tokens");const response = await GET(request);expect(response.status).toBe(200);- await expect(response.json()).resolves.toMatchObject({ enabled: true, maxScope: "exec", origin: "https://mso.example.test" });+ await expect(response.json()).resolves.toMatchObject({ enabled: true, maxScope: "exec", origin: "https://mso.example.test", targetIdentity: mocks.getRuntimeIdentity() });+ expect(mocks.verifyAuth).toHaveBeenCalledWith(request, "owner");expect(mocks.publicOrigin).toHaveBeenCalledWith(request);});@@ -47,6 +50,9 @@ describe("Settings MCP state", () => {const { GET } = await import("./route");const response = await GET(new Request("https://mso.example.test/api/mcp/tokens"));expect(response.status).toBe(401);+ expect(mocks.getRuntimeIdentity).not.toHaveBeenCalled();+ expect(mocks.listTokens).not.toHaveBeenCalled();+ expect(mocks.publicOrigin).not.toHaveBeenCalled();});it("mints Personal Access Tokens (PAT) via POST with owner auth", async () => {diff --git a/app/api/mcp/tokens/route.ts b/app/api/mcp/tokens/route.tsindex 04e346ff..708ac76b 100644--- a/app/api/mcp/tokens/route.ts+++ b/app/api/mcp/tokens/route.ts@@ -5,6 +5,7 @@ import { mcpEnabled, maxScope, parseScope, clampScope } from "@/lib/mcp/scope";import { TOOLS } from "@/lib/mcp/tools";import { toolsetInfo } from "@/lib/mcp/toolset";import { publicOrigin } from "@/lib/mcp/origin";+import { getRuntimeIdentity } from "@/lib/host/system-api";// Token management for Settings → MCP. Under /api on purpose: this one IS// cookie-authenticated and DOES want the depth-2 CSRF gate in proxy.ts, unlike@@ -13,7 +14,7 @@ export const dynamic = "force-dynamic";export async function GET(req: Request) {if (!(await verifyAuth(req, "owner"))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });- return NextResponse.json({ enabled: mcpEnabled(), maxScope: maxScope(), origin: publicOrigin(req), toolset: toolsetInfo(TOOLS), tokens: await listTokens() });+ return NextResponse.json({ enabled: mcpEnabled(), maxScope: maxScope(), origin: publicOrigin(req), toolset: toolsetInfo(TOOLS), tokens: await listTokens(), targetIdentity: getRuntimeIdentity() });}export async function POST(req: Request) {diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 8fbddcae..97be9d29 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -63,6 +63,10 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh- `domains` provision persistent managed-app subdomains from CLI- `models` discover model ids from custom endpoints+**Fixed**++- `mcp` repair observation workflows and connection diagnostics+**Docs**- `progress` preserve managed-domain CLI handoff and remaining gatesdiff --git a/docs/LAUNCH-READINESS.md b/docs/LAUNCH-READINESS.mdindex 284ee845..9b0cc1bd 100644--- a/docs/LAUNCH-READINESS.md+++ b/docs/LAUNCH-READINESS.md@@ -36,13 +36,19 @@ The OS metaphor is presentation. The product is the control plane. Anything that| 12 | Memory / second brain | Memory has provenance, scope, review/admission, supersession/forget semantics, poisoning tests and visible coverage limits. No memory can authorize destructive cleanup. | Memory lifecycle/adversarial suite + UI coverage receipt. | JEV admission and full learning-coverage review remain incomplete. || 13 | Backup / recovery | 3-2-1 posture for critical state: production + independent backup + encrypted offsite copy; restore drill proves RPO/RTO; local snapshot is complete or explicitly partial. | Encrypted offsite backup + isolated restore drill. | Current verified backup is local, partial, not offsite. || 14 | Security model | Complete mediation in downstream tools, least privilege, tool risk classes, explicit approvals for high-impact actions, prompt-injection/memory-poisoning/exfiltration/privilege abuse tests. | SECURITY-ASSURANCE + agent abuse-case matrix + current alert inventory. | No third-party audit; some agentic threat gates still need dedicated launch evidence. |-| 15 | Concurrency safety | Automated source mutation never leaves canonical `main` as a shared scratchpad: one task = one isolated worktree; release integration occurs only from clean, proven candidates. | Tool-enforced workspace lease + collision tests + protected main/ruleset evidence. | Current incident proved policy is not yet tool-enforced; GitHub rulesets list is empty. |+| 15 | Concurrency safety | Automated source mutation never leaves canonical `main` as a shared scratchpad: one task = one isolated worktree; release integration occurs only from clean, proven candidates. | Tool-enforced workspace lease + collision tests + protected main/ruleset evidence. | Workspace guards exist; `main` reports protected with eight required checks (2026-10-17). Full protection settings, complete mediation and current collision/integration evidence remain unverified. || 16 | Release engineering | Exact SHA → full verify → isolated production build → browser E2E → integration queue/canary → rollback → exact live SHA/chunk health. Build/release is repeatable and no unique snowflake. | Release receipt per version. | Existing exact-SHA gates are strong; staged/canary policy still needs formal production evidence. || 17 | Operational resilience | Published SLIs/SLOs, error-budget/change-freeze policy, disk/memory thresholds, alerting, restore/runbook ownership, and failure-mode drills. | SLO dashboard + alert/fire-drill receipts. | Disk pressure and capacity policy are not yet a complete product SLO. || 18 | Documentation | Docs follow Tutorial / How-to / Reference / Explanation separation; one 10-minute tutorial is the canonical first route. | Docs map + link/check-doc gate + user completion test. | Excellent reference depth, but onboarding is still reference-heavy. || 19 | Demoability | A reproducible ≤3-minute demo shows one project → agent/tool action → workflow/evidence → resume/handoff without secrets or hidden manual setup. | Recorded demo + script + clean fixture. | Existing demo is broad rather than one launch narrative. || 20 | Launch readiness | Public beta only when all P0 gates are green, every known limitation is published, rollback/recovery is proven, and current main/live evidence matches the release claim. Stable label requires sustained SLO + recovery history. | Signed/dated release readiness receipt. | Public Alpha/Developer Preview remains the accurate label today. |+### Source concurrency evidence checked 2026-10-17++[`workflow-workspace-guard.ts`](../lib/mcp/workflow-workspace-guard.ts) contains guards for source-workflow filesystem paths, shell working directories and project execution targets. This establishes implementation presence, not complete mediation or a passing current concurrency drill.++The [GitHub main branch summary](https://api.github.com/repos/rahmanef63/mso/branches/main) reported `protected: true` with eight required checks and `non_admins` enforcement. The [rulesets collection](https://api.github.com/repos/rahmanef63/mso/rulesets) was empty; that does not establish an unprotected branch. Detailed branch-protection access returned 403 for the installed integration, so administrator bypass, force-push/deletion restrictions and integration-authority settings are not verified by this receipt.+## P0 before public beta1. **Enforce source concurrency**, not merely document it: isolated task worktrees, canonical-main mutation guard, clean integration authority, remote protection/ruleset/status checks. See [`SOURCE-CONCURRENCY.md`](./SOURCE-CONCURRENCY.md).@@ -52,6 +58,17 @@ The OS metaphor is presentation. The product is the control plane. Anything that5. **One killer journey** across README, Product Hunt, demo and onboarding.6. **SLO + operational policy**: availability/latency/failed-action/disk-pressure SLIs, error budget, change freeze and rollback policy. See [`RELIABILITY.md`](./RELIABILITY.md).+### Follow-up: configured project roots and durable identity++A configured project container may itself be the intended repository. The current recovery path is to inspect an exact container path already returned by `projects_list` with `project_get`; a container entry alone does not prove repository contents. Root-row discovery remains separate work until these acceptance cases pass:++- List, exact-ID, path, name and linked-worktree resolution agree for configured roots, overlapping roots and a root with a same-named child. Existing child identities remain stable.+- Root and marker validation preserves ownership, credential exclusions and no-symlink checks. Hidden runtime state gains no new access. No marker or an invalid marker produces no repository claim.+- Root rows appear exactly once across entry, project, deadline and page limits, with truthful raw-directory cursor positions and no lost child rows.+- Before any logical root-ID change, prove that existing Agent Vault snapshots, user annotations and personal notes remain visible. A bounded legacy lookup must verify the exact canonical project path and select the same physical store for reads, writes and locking. Conflicting legacy/current stores must be reported without automatic merging or deletion.+- Project-skill identities and continuation, historical task references and flow-receipt lookup remain usable. Reusing a flow idempotency key across the change must not replay an uncertain mutation or silently select another project.+- Record migration and rollback evidence separately from discovery tests; retain Alpha/Developer Preview until the independent launch gates are satisfied.+## P1 before “stable”- Sustained SLO history across releases rather than one green release.diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex d9e7112f..e07ff546 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -157,6 +157,19 @@ Provisioning first checks the deployed MSO app-host authorization gate, the seleNested application names require a certificate covering those exact hosts. DNS creation is not presented as TLS success, and no paid certificate is purchased automatically. Current setup, repair and migration boundaries are documented in `docs/MANAGED-DOMAINS.md`; the old RFC is retained as historical context rather than an active setup recipe.Verification on the inspected fallback-runtime host found no Docker executable, daemon socket or configured remote Docker host. The existing mandatory Tool Forge sandbox tests therefore remain an environment prerequisite for release; no live DNS, application installation or deployment is claimed from candidate-only checks.+## 2026-10-17: Repair observation workflows and show what connection checks actually verify++A hostname request could be treated as source mutation when its constraints said “do not modify files” or “jangan edit file.” The classifier now removes directly negated mutation verbs, including explicit coordinated lists, while retaining affirmative changes elsewhere and conservatively isolating ambiguous comma clauses. Declared affected paths also reach classification when there is no collision. This remains a bounded heuristic: the separate high-risk-domain policy is unchanged, and observational classification does not turn an exec grant into read-only shell access.++Compact clients now receive the exact workflow workspace, canonical project path, isolation policy and available base Git identity. File reads and optimistic writes gain only the exact workspace from the authenticated session's active workflow. Read tools pin that workspace only when a bounded filesystem read needs additional authority, so status and configured-root reads remain available when the workspace is missing. Concurrent reads share one pin; cleanup revokes additional authority before awaiting its closure, including detached continuations. The kernel clears inherited additional read authority before nested dispatch. Write and exec isolation still pin eagerly. Configured read roots, credential checks, descriptor validation and write boundaries remain in force.++Settings → MCP → Connection details now shows owner-only hostname, service user, runtime instance and an optional operator-declared environment from OS_INSTANCE_ENVIRONMENT. The environment is independent of NODE_ENV; a production build does not identify a production host. The public health response is unchanged. Connection checks record the observed origin, configured endpoint and time; health, HTTPS, MCP descriptor, OAuth challenge and metadata have separate evidence. Each request has an eight-second deadline and JSON has a 64 KiB limit. A changed or missing expected runtime identity prompts target verification. The selected external AI account and its cached tools stay unknown; a local discovery pass is not evidence that those client states are current.++When project discovery returns no matched rows, its recovery hint explains child-directory scanning and continuation, then points to exact configured-container-path inspection when that path matches the target. It does not rename root-project identities. Root enumeration needs a separate compatibility change because project IDs also key Vault storage, skill references and flow idempotency. LAUNCH-READINESS records that acceptance scope and corrects the earlier inference that an empty rulesets list meant unprotected main.++Compact tool descriptions now end at a word boundary where possible, preserving the existing character cap and full descriptor. The ChatGPT profile retains all 120 tools and serializes to 94,001 bytes, below the existing 92 KiB limit; schemas and budget limits are unchanged. Gateway child-process fixtures explicitly select test mode so an inherited production NODE_ENV does not change their expected behavior. The dedicated production listener-ownership regression still selects production mode explicitly.++Recorded WSL verification passed typecheck and lint, then ran 4,551 tests across 742 files: 4,548 passed and three Forge tests failed because the required Docker sandbox was unavailable. The full verify gate therefore remains failed; no Forge test is skipped or substituted. Focused filesystem/status verification passed 50 tests across five files, including workspace replacement, ownership, concurrent and nested calls, missing workspaces and pending pin cleanup. The connection browser journey is included in the existing mandatory release fixture at desktop, phone and landscape sizes. Build, required CI and live deployment evidence remain separate gates. These changes do not satisfy the off-host restore, fresh-user cohort, sustained SLO or dedicated agent-abuse readiness gates; Alpha/Developer Preview remains the release label.## 2026-10-17: Deploying on a host with no `mso.service`, and why `bun run ship` cannot finalize therediff --git a/frontend/slices/os-settings/components/mcp-client-core.ts b/frontend/slices/os-settings/components/mcp-client-core.tsindex b87552eb..d722eca5 100644--- a/frontend/slices/os-settings/components/mcp-client-core.ts+++ b/frontend/slices/os-settings/components/mcp-client-core.ts@@ -24,11 +24,23 @@ export type McpGuideStep = {copy?: { label: string; value: string; multiline?: boolean };};-export type McpProbeCheckId = "mcp" | "challenge" | "resource" | "oauth";-+export type McpProbeCheckId = "server" | "https" | "mcp" | "challenge" | "resource" | "oauth" | "account" | "client-tools";+export type McpProbeCheckState = "passed" | "failed" | "unknown";+export type McpProbeCheck = {+ id: McpProbeCheckId;+ state: McpProbeCheckState;+ ok: boolean;+ detail: string;+ guidance?: string;+ httpStatus?: number;+};export type McpProbeResult = {+ /** Readiness covers the observed server and discovery, not external client state. */ready: boolean;- checks: Array<{ id: McpProbeCheckId; ok: boolean }>;+ checks: McpProbeCheck[];+ observedOrigin: string;+ configuredOrigin: string;+ checkedAt: string;};export const MCP_CLIENTS: Array<{@@ -48,6 +60,10 @@ export const MCP_CLIENTS: Array<{];export const MCP_PROBE_LABELS: Record<McpProbeCheckId, string> = {+ server: "Server",+ https: "HTTPS to configured origin",+ account: "Selected AI app account",+ "client-tools": "AI app tool cache",mcp: "MCP endpoint",challenge: "OAuth challenge",resource: "Protected resource",diff --git a/frontend/slices/os-settings/components/mcp-client-guides.test.ts b/frontend/slices/os-settings/components/mcp-client-guides.test.tsindex cf7933cb..d19ef495 100644--- a/frontend/slices/os-settings/components/mcp-client-guides.test.ts+++ b/frontend/slices/os-settings/components/mcp-client-guides.test.ts@@ -17,7 +17,7 @@ describe("MCP client setup guides", () => {expect(endpoints.protectedResource).toContain("/.well-known/oauth-protected-resource");});- it("distinguishes a remotely reachable HTTPS origin from local loopback", () => {+ it("distinguishes a configured remote HTTPS origin from local loopback", () => {expect(isRemoteMcpOrigin("https://mso.example.test")).toBe(true);expect(isRemoteMcpOrigin("https://localhost:4005")).toBe(false);expect(isRemoteMcpOrigin("http://127.0.0.1:4005")).toBe(false);@@ -54,6 +54,7 @@ describe("MCP client setup guides", () => {it("accepts only matching endpoint, challenge and OAuth discovery metadata", async () => {const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {const url = String(input);+ if (url.endsWith("/api/health")) return Response.json({ status: "ok", service: "mso", version: "fixture", buildId: "fixture" });if (url.endsWith("/mcp") && init?.method === "POST") {return new Response(JSON.stringify({ error: "unauthorized" }), {status: 401,diff --git a/frontend/slices/os-settings/components/mcp-connection-section.tsx b/frontend/slices/os-settings/components/mcp-connection-section.tsxindex 6ae5160e..ba07d1c2 100644--- a/frontend/slices/os-settings/components/mcp-connection-section.tsx+++ b/frontend/slices/os-settings/components/mcp-connection-section.tsx@@ -2,8 +2,9 @@import { Button } from "@/components/ui/button";import { SettingsBlock } from "@/features/shell-settings";+import type { RuntimeIdentity } from "@/lib/contracts/runtime-identity";import { RefreshCw } from "lucide-react";-import { useCallback, useEffect, useState } from "react";+import { useEffect, useState } from "react";import { isRemoteMcpOrigin, mcpEndpoints, type McpProbeResult } from "./mcp-client-core";import { McpConnectionMode } from "./mcp-connection-mode";import { McpCopyField } from "./mcp-copy-field";@@ -12,23 +13,46 @@ import { McpProbeStatus } from "./mcp-probe-status";function sameOriginFetch(input: RequestInfo | URL, init?: RequestInit) {const target = new URL(String(input));- return fetch(`${target.pathname}${target.search}`, init);+ return fetch(target.pathname + target.search, init);}-export function McpConnectionSection({ origin }: { origin: string }) {- const [result, setResult] = useState<McpProbeResult | null>(null);- const [checking, setChecking] = useState(true);+type ProbeSnapshot = { origin: string; attempt: number; expectedInstance: string | null; result: McpProbeResult | null };++export function McpConnectionSection({ origin, targetIdentity }: { origin: string; targetIdentity?: RuntimeIdentity | null }) {+ const [snapshot, setSnapshot] = useState<ProbeSnapshot | null>(null);+ const [attempt, setAttempt] = useState(0);+ const expectedInstance = targetIdentity?.runtimeInstanceId ?? null;+ const current = snapshot?.origin === origin && snapshot.attempt === attempt && snapshot.expectedInstance === expectedInstance ? snapshot : null;+ const result = current?.result ?? null;+ const checking = current === null;const endpoints = mcpEndpoints(origin);- const apply = useCallback((next: McpProbeResult | null) => { setResult(next); setChecking(false); }, []);useEffect(() => {- let current = true;- probeMcpConnection(origin, sameOriginFetch).then(next => { if (current) apply(next); }).catch(() => { if (current) apply(null); });- return () => { current = false; };- }, [origin, apply]);- async function check() { setChecking(true); apply(await probeMcpConnection(origin, sameOriginFetch).catch(() => null)); }+ const controller = new AbortController();+ probeMcpConnection(origin, sameOriginFetch, {+ observedOrigin: window.location.origin, signal: controller.signal, expectedRuntimeInstanceId: expectedInstance,+ }).then(next => {+ if (!controller.signal.aborted) setSnapshot({ origin, attempt, expectedInstance, result: next });+ }).catch(() => {+ if (!controller.signal.aborted) setSnapshot({ origin, attempt, expectedInstance, result: null });+ });+ return () => controller.abort();+ }, [origin, attempt, expectedInstance]);+return <div className="space-y-4">+ {targetIdentity && <SettingsBlock className="space-y-3 py-4">+ <h3 className="text-sm font-medium">Current server</h3>+ <p className="text-sm text-muted-foreground">Identity loaded with Settings. The runtime ID is checked again when available; it can change after a restart.</p>+ <dl aria-label="Current server identity" className="grid gap-3 text-sm @min-[520px]:grid-cols-2">+ {[+ ["Hostname", targetIdentity.hostname],+ ["Service user", targetIdentity.serviceUser ?? "Unavailable"],+ ["Runtime instance", targetIdentity.runtimeInstanceId ?? "Unavailable"],+ ["Environment", targetIdentity.environment ?? "Not configured"],+ ].map(([label, value]) => <div key={label}><dt className="text-muted-foreground">{label}</dt><dd className="break-all">{value}</dd></div>)}+ </dl>+ </SettingsBlock>}<SettingsBlock className="space-y-3 py-4"><McpProbeStatus state={checking ? "checking" : result?.ready ? "ready" : "error"} result={result} endpoint={endpoints.mcp} />- <Button variant="secondary" disabled={checking} onClick={() => void check()} className="min-h-11"><RefreshCw className="size-4" />{checking ? "Checking…" : "Check connection"}</Button>+ <Button variant="secondary" disabled={checking} onClick={() => setAttempt(value => value + 1)} className="min-h-11"><RefreshCw aria-hidden className="size-4" />{checking ? "Checking…" : "Check connection"}</Button></SettingsBlock><SettingsBlock className="py-4"><McpConnectionMode endpoints={endpoints} remote={isRemoteMcpOrigin(origin)} /></SettingsBlock><SettingsBlock className="py-4">diff --git a/frontend/slices/os-settings/components/mcp-probe-request.ts b/frontend/slices/os-settings/components/mcp-probe-request.tsnew file mode 100644index 00000000..160fb311--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-probe-request.ts@@ -0,0 +1,87 @@+export type ProbeFetcher = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;+export type ProbeResponse = {+ httpStatus?: number;+ data: Record<string, unknown> | null;+ challenge: string;+ issue?: "network" | "timeout" | "invalid-json" | "redirect" | "too-large";+};+export type ProbeRequestOptions = { fetcher: ProbeFetcher; signal?: AbortSignal; timeoutMs: number };++export function probeRecord(value: unknown): Record<string, unknown> | null {+ return value !== null && typeof value === "object" && !Array.isArray(value)+ ? value as Record<string, unknown> : null;+}++const MAX_PROBE_BYTES = 64 * 1024;+class ProbeBodyTooLarge extends Error {}++async function readProbeJson(response: Response, signal: AbortSignal) {+ if (Number(response.headers.get("content-length")) > MAX_PROBE_BYTES) {+ void response.body?.cancel().catch(() => {});+ throw new ProbeBodyTooLarge();+ }+ if (!response.body) return null;+ const reader = response.body.getReader(), decoder = new TextDecoder();+ const cancel = () => { void reader.cancel().catch(() => {}); };+ signal.addEventListener("abort", cancel, { once: true });+ let bytes = 0, text = "";+ try {+ signal.throwIfAborted();+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ bytes += value.byteLength;+ if (bytes > MAX_PROBE_BYTES) { cancel(); throw new ProbeBodyTooLarge(); }+ text += decoder.decode(value, { stream: true });+ }+ return probeRecord(JSON.parse(text + decoder.decode()));+ } finally { signal.removeEventListener("abort", cancel); reader.releaseLock(); }+}++export function requestMcpProbe(url: string, init: RequestInit, options: ProbeRequestOptions): Promise<ProbeResponse> {+ return new Promise((resolve, reject) => {+ const controller = new AbortController();+ let timer: ReturnType<typeof setTimeout> | undefined;+ let complete = false;+ let httpStatus: number | undefined;+ const empty = (): ProbeResponse => ({ httpStatus, data: null, challenge: "" });+ const cleanup = () => {+ clearTimeout(timer);+ options.signal?.removeEventListener("abort", cancel);+ };+ const finish = (value: ProbeResponse) => {+ if (complete) return;+ complete = true;+ cleanup();+ resolve(value);+ };+ const cancel = () => {+ if (complete) return;+ complete = true;+ cleanup();+ controller.abort(options.signal?.reason);+ reject(options.signal?.reason ?? new DOMException("Probe cancelled", "AbortError"));+ };+ if (options.signal?.aborted) { cancel(); return; }+ options.signal?.addEventListener("abort", cancel, { once: true });+ timer = setTimeout(() => {+ finish({ ...empty(), issue: "timeout" });+ controller.abort(new DOMException("Probe timed out", "TimeoutError"));+ }, options.timeoutMs);++ void (async () => {+ const response = await options.fetcher(url, {+ ...init, cache: "no-store", credentials: "omit", redirect: "error", signal: controller.signal,+ });+ if (controller.signal.aborted) { void response.body?.cancel().catch(() => {}); return; }+ httpStatus = response.status;+ if (response.redirected) { void response.body?.cancel().catch(() => {}); return finish({ ...empty(), issue: "redirect" }); }+ const result = { httpStatus, data: null, challenge: response.headers.get("www-authenticate") ?? "" };+ if (!response.ok || init.method === "POST") { void response.body?.cancel().catch(() => {}); return finish(result); }+ try {+ const data = await readProbeJson(response, controller.signal);+ finish(data ? { ...result, data } : { ...result, issue: "invalid-json" });+ } catch (error) { finish({ ...result, issue: error instanceof ProbeBodyTooLarge ? "too-large" : "invalid-json" }); }+ })().catch(() => finish({ ...empty(), issue: "network" }));+ });+}diff --git a/frontend/slices/os-settings/components/mcp-probe-status.tsx b/frontend/slices/os-settings/components/mcp-probe-status.tsxindex 96c99b3c..8e3aa8fc 100644--- a/frontend/slices/os-settings/components/mcp-probe-status.tsx+++ b/frontend/slices/os-settings/components/mcp-probe-status.tsx@@ -5,28 +5,36 @@ import { cn } from "@/lib/utils";import { MCP_PROBE_LABELS, type McpProbeResult } from "./mcp-client-core";export type ProbeState = "checking" | "ready" | "error";+const stateLabels = { passed: "Passed", failed: "Failed", unknown: "Unknown" };export function McpProbeStatus({ state, result, endpoint }: { state: ProbeState; result: McpProbeResult | null; endpoint: string }) {const ready = state === "ready";return (- <div role="status" aria-live="polite" className={cn(- "space-y-2 rounded-lg border px-3 py-2.5",- ready ? "border-success/30 bg-success/10" : state === "error" ? "border-destructive/30 bg-destructive/10" : "border-border bg-secondary/35",- )}>+ <div role="status" aria-live="polite" aria-busy={state === "checking"} className="space-y-3 rounded-lg border border-border px-3 py-3"><div className="flex items-start gap-2">- {ready ? <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-success" /> : <CircleAlert className="mt-0.5 size-4 shrink-0 text-muted-foreground" />}+ {ready ? <CheckCircle2 aria-hidden className="mt-0.5 size-4 shrink-0 text-success" /> : <CircleAlert aria-hidden className="mt-0.5 size-4 shrink-0 text-muted-foreground" />}<div className="min-w-0">- <p className="text-sm font-medium">{ready ? "MCP + OAuth discovery ready" : state === "error" ? "One or more connection checks failed" : "Checking MCP + OAuth discovery…"}</p>- <p className="mt-0.5 break-all font-mono text-xs text-muted-foreground">{endpoint}</p>+ <p className="text-sm font-medium">{ready ? "Server discovery checks passed" : state === "error" ? "Some server checks need attention" : "Checking this server…"}</p>+ {state === "error" && !result && <p className="mt-1 text-sm text-muted-foreground">The check could not finish. Verify the server address and try again.</p>}</div></div>- {result && (- <div className="flex flex-wrap gap-1.5 pl-6">- {result.checks.map((check) => (- <span key={check.id} className={cn("rounded-md px-2 py-1 text-xs font-medium", check.ok ? "bg-success/10 text-success" : "bg-destructive/10 text-destructive")}>{check.ok ? "Ready: " : "Failed: "}{MCP_PROBE_LABELS[check.id]}</span>- ))}- </div>- )}+ <dl className="space-y-2 text-sm">+ <div><dt className="text-muted-foreground">Observed origin</dt><dd className="break-all">{result?.observedOrigin ?? "Checking…"}</dd></div>+ <div><dt className="text-muted-foreground">Configured MCP endpoint</dt><dd className="break-all">{endpoint}</dd></div>+ {result && <div><dt className="text-muted-foreground">Checked</dt><dd><time dateTime={result.checkedAt}>{new Date(result.checkedAt).toLocaleString()}</time></dd></div>}+ </dl>+ {result && <ul aria-label="Connection checks" className="divide-y divide-border">+ {result.checks.map(check => (+ <li key={check.id} data-probe-check={check.id} className="space-y-1 py-3">+ <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">+ <p className="text-sm font-medium">{MCP_PROBE_LABELS[check.id]}</p>+ <span className={cn("text-sm font-medium", check.state === "failed" ? "text-destructive" : "text-foreground")}>{stateLabels[check.state]}</span>+ </div>+ <p className="text-sm text-muted-foreground">{check.detail}</p>+ {check.guidance && <p className="text-sm text-foreground">{check.guidance}</p>}+ </li>+ ))}+ </ul>}</div>);}diff --git a/frontend/slices/os-settings/components/mcp-probe.test.ts b/frontend/slices/os-settings/components/mcp-probe.test.tsnew file mode 100644index 00000000..56f8c40b--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-probe.test.ts@@ -0,0 +1,181 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { probeMcpConnection } from "./mcp-probe";+import type { McpProbeCheckId, McpProbeResult } from "./mcp-client-core";+import type { ProbeFetcher } from "./mcp-probe-request";++const origin = "https://mso.example.test";+const health = { status: "ok", service: "mso", version: "fixture", buildId: "fixture", runtimeInstanceId: "runtime-a" };+const oauth = {+ issuer: origin, authorization_endpoint: origin + "/oauth/authorize", token_endpoint: origin + "/oauth/token",+ registration_endpoint: origin + "/oauth/register", code_challenge_methods_supported: ["S256"], token_endpoint_auth_methods_supported: ["none"],+};+const respond: ProbeFetcher = async (input, init) => {+ const url = String(input);+ if (url.endsWith("/api/health")) return Response.json(health);+ if (url.endsWith("/mcp") && init?.method === "POST") return new Response(null, {+ status: 401, headers: { "www-authenticate": 'Bearer realm="mso", resource_metadata="' + origin + '/.well-known/oauth-protected-resource"' },+ });+ if (url.endsWith("/mcp")) return Response.json({ name: "mso MCP", authorization_servers: [origin] });+ if (url.endsWith("oauth-protected-resource")) return Response.json({ resource: origin + "/mcp", authorization_servers: [origin] });+ return Response.json(oauth);+};+const check = (result: McpProbeResult, id: McpProbeCheckId) => result.checks.find(row => row.id === id);+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });++describe("MCP connection evidence", () => {+ it("keeps account selection and client cache unknown after server discovery passes", async () => {+ const fetcher = vi.fn(respond);+ const result = await probeMcpConnection(origin, fetcher);+ expect(result.ready).toBe(true);+ expect(result.checks).toHaveLength(8);+ for (const id of ["account", "client-tools"] as const) expect(check(result, id)).toMatchObject({ state: "unknown", ok: false });+ for (const id of ["server", "https", "mcp", "challenge", "resource", "oauth"] as const) expect(check(result, id)?.state).toBe("passed");+ expect(check(result, "challenge")?.httpStatus).toBe(401);+ expect(result.observedOrigin).toBe(origin);+ expect(result.configuredOrigin).toBe(origin);+ expect(Number.isNaN(Date.parse(result.checkedAt))).toBe(false);+ expect(fetcher).toHaveBeenCalledTimes(5);+ expect(fetcher.mock.calls.every(([, init]) => init?.credentials === "omit" && init.redirect === "error" && init.cache === "no-store")).toBe(true);+ expect(fetcher.mock.calls.every(([, init]) => !new Headers(init?.headers).has("authorization"))).toBe(true);+ });++ it("does not infer public HTTPS reachability from a successful loopback probe", async () => {+ const result = await probeMcpConnection(origin, respond, { observedOrigin: "http://127.0.0.1:4005" });+ expect(result.ready).toBe(true);+ expect(result.observedOrigin).toBe("http://127.0.0.1:4005");+ expect(check(result, "https")).toMatchObject({ state: "unknown" });+ expect(check(result, "https")?.guidance).toContain("configured HTTPS origin");+ });++ it("keeps HTTPS unknown for a local configured endpoint", async () => {+ const result = await probeMcpConnection("http://localhost:4005", respond);+ expect(check(result, "https")?.state).toBe("unknown");+ });++ it("reports server health separately when MCP is unavailable", async () => {+ const result = await probeMcpConnection(origin, async (input, init) =>+ String(input).endsWith("/mcp") ? new Response(null, { status: 404 }) : respond(input, init));+ expect(result.ready).toBe(false);+ expect(check(result, "server")?.state).toBe("passed");+ expect(check(result, "mcp")).toMatchObject({ state: "failed", httpStatus: 404 });+ expect(check(result, "mcp")?.guidance).toContain("MCP is enabled");+ });++ it("preserves healthy stages when one request fails", async () => {+ const result = await probeMcpConnection(origin, async (input, init) => {+ if (String(input).endsWith("oauth-authorization-server")) throw new TypeError("network");+ return respond(input, init);+ });+ expect(check(result, "oauth")).toMatchObject({ state: "failed", detail: "No response was received." });+ expect(check(result, "server")?.state).toBe("passed");+ expect(check(result, "resource")?.state).toBe("passed");+ });++ it.each([null, [], "metadata", { name: "mso MCP", authorization_servers: origin },+ { name: "mso MCP", authorization_servers: {} }].map(data => ({ data })))("rejects malformed descriptor $data without throwing", async ({ data }) => {+ const result = await probeMcpConnection(origin, (input, init) =>+ String(input).endsWith("/mcp") && init?.method !== "POST" ? Promise.resolve(Response.json(data)) : respond(input, init));+ expect(check(result, "mcp")?.state).toBe("failed");+ expect(check(result, "oauth")?.state).toBe("passed");+ });++ it("rejects string PKCE/auth-method values instead of matching substrings", async () => {+ const result = await probeMcpConnection(origin, (input, init) =>+ String(input).endsWith("oauth-authorization-server")+ ? Promise.resolve(Response.json({ ...oauth, code_challenge_methods_supported: "S256", token_endpoint_auth_methods_supported: "none" }))+ : respond(input, init));+ expect(check(result, "oauth")?.state).toBe("failed");+ });++ it("reports invalid JSON on only its own stage", async () => {+ const result = await probeMcpConnection(origin, (input, init) =>+ String(input).endsWith("/api/health") ? Promise.resolve(new Response("<html>unavailable</html>")) : respond(input, init));+ expect(check(result, "server")?.detail).toContain("valid JSON object");+ expect(check(result, "mcp")?.state).toBe("passed");+ });++ it("rejects a challenge and issuer for another deployment", async () => {+ const result = await probeMcpConnection(origin, (input, init) => {+ if (String(input).endsWith("/mcp") && init?.method === "POST") return Promise.resolve(new Response(null, {+ status: 401, headers: { "www-authenticate": 'Bearer resource_metadata="https://other.test/.well-known/oauth-protected-resource"' },+ }));+ if (String(input).endsWith("oauth-authorization-server")) return Promise.resolve(Response.json({ ...oauth, issuer: "https://other.test" }));+ return respond(input, init);+ });+ expect(check(result, "challenge")?.state).toBe("failed");+ expect(check(result, "oauth")?.state).toBe("failed");+ });++ it("detects a different runtime without inventing identity when none was supplied", async () => {+ const changed = await probeMcpConnection(origin, respond, { expectedRuntimeInstanceId: "runtime-b" });+ expect(changed.ready).toBe(false);+ expect(check(changed, "server")?.detail).toContain("runtime identity changed");+ expect(check(changed, "server")?.guidance).toContain("Reload Settings");+ expect(check(changed, "server")?.httpStatus).toBe(200);+ expect((await probeMcpConnection(origin, respond, { expectedRuntimeInstanceId: null })).ready).toBe(true);+ });++ it("retains liveness evidence but cannot verify a missing expected runtime identity", async () => {+ const result = await probeMcpConnection(origin, (input, init) =>+ String(input).endsWith("/api/health") ? Promise.resolve(Response.json({ ...health, runtimeInstanceId: null })) : respond(input, init),+ { expectedRuntimeInstanceId: "runtime-a" });+ expect(result.ready).toBe(false);+ expect(check(result, "server")).toMatchObject({ state: "unknown", httpStatus: 200 });+ expect(check(result, "server")?.detail).toContain("MSO responded");+ });++ it.each([true, false])("bounds oversized JSON with declared content length %s", async declared => {+ const result = await probeMcpConnection(origin, (input, init) => String(input).endsWith("/api/health")+ ? Promise.resolve(new Response("x".repeat(70_000), { headers: declared ? { "content-length": "70000" } : undefined })) : respond(input, init));+ expect(check(result, "server")?.detail).toContain("64 KiB");+ expect(check(result, "oauth")?.state).toBe("passed");+ });++ it("times out and aborts only the hanging stage even if its fetch ignores abort", async () => {+ vi.useFakeTimers();+ const stalled: (AbortSignal | null | undefined)[] = [];+ const pending = probeMcpConnection(origin, (input, init) => {+ if (String(input).endsWith("/mcp") && init?.method !== "POST") { stalled.push(init?.signal); return new Promise(() => {}); }+ return respond(input, init);+ }, { timeoutMs: 50 });+ await vi.advanceTimersByTimeAsync(50);+ const result = await pending;+ expect(check(result, "mcp")?.detail).toBe("This check timed out.");+ expect(check(result, "oauth")?.state).toBe("passed");+ expect(stalled[0]?.aborted).toBe(true);+ expect(vi.getTimerCount()).toBe(0);+ });++ it("bounds a response whose JSON body never finishes", async () => {+ vi.useFakeTimers();+ const pending = probeMcpConnection(origin, (input, init) => {+ if (!String(input).endsWith("/api/health")) return respond(input, init);+ return Promise.resolve(new Response(new ReadableStream({ start(controller) {+ controller.enqueue(new TextEncoder().encode('{"status":'));+ } })));+ }, { timeoutMs: 50 });+ await vi.advanceTimersByTimeAsync(50);+ expect(check(await pending, "server")?.detail).toBe("This check timed out.");+ });++ it("cancels every stage and removes timers when the caller abandons a probe", async () => {+ vi.useFakeTimers();+ const controller = new AbortController(), signals: (AbortSignal | null | undefined)[] = [];+ const pending = probeMcpConnection(origin, (_input, init) => {+ signals.push(init?.signal); return new Promise(() => {});+ }, { signal: controller.signal });+ const rejected = expect(pending).rejects.toMatchObject({ name: "AbortError" });+ controller.abort();+ await rejected;+ expect(signals).toHaveLength(5);+ expect(signals.every(signal => signal?.aborted)).toBe(true);+ expect(vi.getTimerCount()).toBe(0);+ });++ it("does not start requests for an already cancelled caller", async () => {+ const controller = new AbortController(), fetcher = vi.fn(respond);+ controller.abort();+ await expect(probeMcpConnection(origin, fetcher, { signal: controller.signal })).rejects.toMatchObject({ name: "AbortError" });+ expect(fetcher).not.toHaveBeenCalled();+ });+});diff --git a/frontend/slices/os-settings/components/mcp-probe.ts b/frontend/slices/os-settings/components/mcp-probe.tsindex 9a4e3192..629e8ffe 100644--- a/frontend/slices/os-settings/components/mcp-probe.ts+++ b/frontend/slices/os-settings/components/mcp-probe.ts@@ -1,61 +1,103 @@-import { mcpEndpoints, type McpProbeResult } from "./mcp-client-core";+import { isRemoteMcpOrigin, mcpEndpoints, type McpProbeCheck, type McpProbeCheckId, type McpProbeResult } from "./mcp-client-core";+import { requestMcpProbe, type ProbeFetcher, type ProbeResponse } from "./mcp-probe-request";-type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;+export type McpProbeOptions = {+ observedOrigin?: string;+ signal?: AbortSignal;+ timeoutMs?: number;+ expectedRuntimeInstanceId?: string | null;+};-async function jsonOrNull(response: Response): Promise<Record<string, unknown> | null> {- if (!response.ok) return null;- try {- return (await response.json()) as Record<string, unknown>;- } catch {- return null;- }+function includesString(value: unknown, expected: string) {+ return Array.isArray(value) && value.every(item => typeof item === "string") && value.includes(expected);}--function headerHasResourceMetadata(response: Response, expectedUrl: string) {- if (response.status !== 401) return false;- const challenge = response.headers.get("www-authenticate") ?? "";- return challenge.toLowerCase().startsWith("bearer ") && challenge.includes(`resource_metadata=\"${expectedUrl}\"`);+function presentText(value: unknown): value is string {+ return typeof value === "string" && value.length > 0 && value.length <= 160;+}+function makeCheck(id: McpProbeCheckId, state: McpProbeCheck["state"], detail: string, guidance?: string): McpProbeCheck {+ return { id, state, ok: state === "passed", detail, ...(guidance ? { guidance } : {}) };+}+function checkResponse(id: McpProbeCheckId, response: ProbeResponse, valid: boolean, detail: string, guidance: string): McpProbeCheck {+ const issue = response.issue === "timeout" ? "This check timed out."+ : response.issue === "network" ? "No response was received."+ : response.issue === "invalid-json" ? "The response is not a valid JSON object."+ : response.issue === "too-large" ? "The response exceeded the 64 KiB diagnostic limit."+ : response.issue === "redirect" ? "The endpoint redirected; its identity was not verified."+ : response.httpStatus !== undefined && response.httpStatus >= 400 ? "Received HTTP " + response.httpStatus + "."+ : "The response does not match this server's discovery contract.";+ return {+ ...makeCheck(id, valid && !response.issue ? "passed" : "failed", valid && !response.issue ? detail : issue,+ valid && !response.issue ? undefined : guidance),+ ...(response.httpStatus !== undefined ? { httpStatus: response.httpStatus } : {}),+ };}-export async function probeMcpConnection(rawOrigin: string, fetcher: FetchLike = fetch): Promise<McpProbeResult> {+export async function probeMcpConnection(rawOrigin: string, fetcher: ProbeFetcher = fetch, options: McpProbeOptions = {}): Promise<McpProbeResult> {+ options.signal?.throwIfAborted();const endpoints = mcpEndpoints(rawOrigin);- const [mcpResponse, challengeResponse, resourceResponse, oauthResponse] = await Promise.all([- fetcher(endpoints.mcp, { cache: "no-store" }).catch(() => new Response(null, { status: 599 })),- fetcher(endpoints.mcp, {- method: "POST",- headers: { "content-type": "application/json" },+ const observedOrigin = new URL(options.observedOrigin ?? endpoints.origin).origin;+ const timeoutMs = options.timeoutMs ?? 8_000;+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Invalid probe timeout");+ const request = (url: string, init: RequestInit = {}) => requestMcpProbe(url, init, { fetcher, signal: options.signal, timeoutMs });+ const responses = await Promise.all([+ request(endpoints.origin + "/api/health"),+ request(endpoints.mcp),+ request(endpoints.mcp, {+ method: "POST", headers: { "content-type": "application/json" },body: JSON.stringify({ jsonrpc: "2.0", id: "settings-probe", method: "initialize", params: {} }),- cache: "no-store",- }).catch(() => new Response(null, { status: 599 })),- fetcher(endpoints.protectedResource, { cache: "no-store" }).catch(() => new Response(null, { status: 599 })),- fetcher(endpoints.authorizationServer, { cache: "no-store" }).catch(() => new Response(null, { status: 599 })),+ }),+ request(endpoints.protectedResource),+ request(endpoints.authorizationServer),]);-- const [mcp, resource, oauth] = await Promise.all([- jsonOrNull(mcpResponse),- jsonOrNull(resourceResponse),- jsonOrNull(oauthResponse),- ]);-- const authServers = (mcp?.authorization_servers as unknown[]) ?? [];- const resourceAuthServers = (resource?.authorization_servers as unknown[]) ?? [];- const pkceMethods = (oauth?.code_challenge_methods_supported as unknown[]) ?? [];- const tokenMethods = (oauth?.token_endpoint_auth_methods_supported as unknown[]) ?? [];-- const checks: McpProbeResult["checks"] = [- { id: "mcp", ok: mcp?.name === "mso MCP" && authServers.includes(endpoints.origin) },- { id: "challenge", ok: headerHasResourceMetadata(challengeResponse, endpoints.protectedResource) },- { id: "resource", ok: resource?.resource === endpoints.mcp && resourceAuthServers.includes(endpoints.origin) },- {- id: "oauth",- ok:- oauth?.issuer === endpoints.origin &&- oauth.authorization_endpoint === endpoints.authorize &&- oauth.token_endpoint === endpoints.token &&- oauth.registration_endpoint === endpoints.register &&- pkceMethods.includes("S256") &&- tokenMethods.includes("none"),- },+ options.signal?.throwIfAborted();+ const [server, descriptor, challenge, resource, oauth] = responses;+ const health = server.data, mcp = descriptor.data, resourceData = resource.data, oauthData = oauth.data;+ const serverOk = health?.status === "ok" && health.service === "mso" && presentText(health.version) && presentText(health.buildId);+ const targetChanged = serverOk && presentText(options.expectedRuntimeInstanceId) &&+ presentText(health?.runtimeInstanceId) && health.runtimeInstanceId !== options.expectedRuntimeInstanceId;+ const targetUnknown = serverOk && presentText(options.expectedRuntimeInstanceId) && !presentText(health?.runtimeInstanceId);+ const serverCheck = targetChanged || targetUnknown+ ? { ...makeCheck("server", targetChanged ? "failed" : "unknown",+ targetChanged ? "The runtime identity changed since Settings loaded." : "MSO responded, but its runtime identity could not be verified.",+ "Reload Settings and verify the server identity before continuing."), httpStatus: server.httpStatus }+ : checkResponse("server", server, serverOk, "MSO health responded at the observed origin.", "Check the MSO service, port, and gateway, then retry.");+ const metadata = challenge.challenge.match(/\bresource_metadata\s*=\s*"([^"]+)"/i);+ const discovery = [+ serverCheck,+ checkResponse("mcp", descriptor, mcp?.name === "mso MCP" && includesString(mcp.authorization_servers, endpoints.origin),+ "The MCP endpoint advertises the configured origin.", "Check that MCP is enabled on this host and the public origin is correct."),+ checkResponse("challenge", challenge, challenge.httpStatus === 401 && /^Bearer\s/i.test(challenge.challenge) && metadata?.[1] === endpoints.protectedResource,+ "Unauthenticated requests receive the expected OAuth challenge.", "Check that the proxy preserves the MCP response and WWW-Authenticate header."),+ checkResponse("resource", resource, resourceData?.resource === endpoints.mcp && includesString(resourceData.authorization_servers, endpoints.origin),+ "Protected-resource metadata identifies the configured MCP endpoint.", "Check the protected-resource metadata and configured public origin."),+ checkResponse("oauth", oauth, oauthData?.issuer === endpoints.origin &&+ oauthData.authorization_endpoint === endpoints.authorize && oauthData.token_endpoint === endpoints.token &&+ oauthData.registration_endpoint === endpoints.register && includesString(oauthData.code_challenge_methods_supported, "S256") &&+ includesString(oauthData.token_endpoint_auth_methods_supported, "none"),+ "OAuth endpoints and PKCE metadata match this server.", "Check the public origin and OAuth endpoints before reconnecting your AI app."),];- return { ready: checks.every((check) => check.ok), checks };+ let https: McpProbeCheck;+ if (!isRemoteMcpOrigin(endpoints.origin)) {+ https = makeCheck("https", "unknown", "A public HTTPS connection has not been verified.",+ "Hosted AI apps need a reachable HTTPS URL. Check the connection mode below.");+ } else if (observedOrigin !== endpoints.origin) {+ https = makeCheck("https", "unknown", "These requests reached the observed origin, not the configured public origin.",+ "Open the configured HTTPS origin and run this check there.");+ } else if (responses.some(response => response.httpStatus !== undefined && response.issue !== "redirect")) {+ https = makeCheck("https", "passed", "This browser received an HTTPS response from the configured origin.");+ } else {+ https = makeCheck("https", "unknown", "No HTTPS response was observed.",+ "Open the configured URL and check its DNS, certificate, and gateway.");+ }+ return {+ ready: discovery.every(check => check.ok),+ observedOrigin, configuredOrigin: endpoints.origin, checkedAt: new Date().toISOString(),+ checks: [+ discovery[0], https, ...discovery.slice(1),+ makeCheck("account", "unknown", "MSO cannot observe the account selected inside your AI app.",+ "Select the intended account and MSO connection there. Connected apps shows access granted on this server."),+ makeCheck("client-tools", "unknown", "Server discovery does not reveal the tools cached by your AI app.",+ "Refresh or reconnect MSO in your AI app, then try a read-only tool. Tools & updates shows the server signature."),+ ],+ };}diff --git a/frontend/slices/os-settings/components/mcp-section.tsx b/frontend/slices/os-settings/components/mcp-section.tsxindex 7f06c3d9..a71946e6 100644--- a/frontend/slices/os-settings/components/mcp-section.tsx+++ b/frontend/slices/os-settings/components/mcp-section.tsx@@ -76,7 +76,7 @@ function OwnerMcpSection() {</SettingsBlock>}{direction === "inbound" && <McpNavigation active={page} onSelect={navigate} activeCount={state.tokens.filter(token => token.status === "active").length} direction={direction} />}{page === "connect" && <McpSetupGuide origin={state.origin} maxScope={state.maxScope} />}- {page === "connection" && <McpConnectionSection origin={state.origin} />}+ {page === "connection" && <McpConnectionSection origin={state.origin} targetIdentity={state.targetIdentity} />}{page === "access" && <McpTokenSection tokens={state.tokens} origin={state.origin} maxScope={state.maxScope} onChanged={reload} onConnect={() => navigate("connect")} />}{page === "activity" && <McpActivity />}{page === "tools" && <McpToolsetCard info={state.toolset} />}diff --git a/frontend/slices/os-settings/components/mcp-state.ts b/frontend/slices/os-settings/components/mcp-state.tsindex 26c84f21..88b53862 100644--- a/frontend/slices/os-settings/components/mcp-state.ts+++ b/frontend/slices/os-settings/components/mcp-state.ts@@ -1,10 +1,11 @@"use client";+import type { RuntimeIdentity } from "@/lib/contracts/runtime-identity";import { useCallback, useEffect, useState } from "react";import type { McpTokenRow } from "./mcp-token-section";import type { McpToolsetInfo } from "./mcp-toolset-card";-export type McpState = { enabled: boolean; maxScope: string; toolset: McpToolsetInfo; tokens: McpTokenRow[]; origin: string };+export type McpState = { enabled: boolean; maxScope: string; toolset: McpToolsetInfo; tokens: McpTokenRow[]; origin: string; targetIdentity?: RuntimeIdentity };export function useMcpState() {const [state, setState] = useState<McpState | null>(null);const [error, setError] = useState("");diff --git a/lib/capabilities/execute.ts b/lib/capabilities/execute.tsindex 0efba5c1..2191db08 100644--- a/lib/capabilities/execute.ts+++ b/lib/capabilities/execute.ts@@ -36,6 +36,10 @@ export async function executeCapabilityCall(input: {actor?: string;context?: CapabilityExecutionContext;}): Promise<CapabilityExecutionResult> {+ return withIsolatedFilesystem(undefined, () => executeCall(input));+}++async function executeCall(input: Parameters<typeof executeCapabilityCall>[0]): Promise<CapabilityExecutionResult> {const startedAt = Date.now();const { tool, args, scope, actor, context } = input;const name = tool.name;@@ -122,9 +126,9 @@ export async function executeCapabilityCall(input: {if (titleHint && context?.principal && context.sessionId && !["agent_session_current", "workflow_status", "agent_subagent_run"].includes(name))await maybeAutoTitleAgentSession(context.principal, context.sessionId, titleHint).catch(() => undefined);- const needsIsolation = !lifecycle && tool.scope !== "read" && activeWorkflow?.orchestration?.isolation === "isolated-worktree";+ const needsIsolation = !lifecycle && activeWorkflow?.orchestration?.isolation === "isolated-worktree";const isolatedRoot = needsIsolation ? activeWorkflow?.orchestration?.workspacePath : undefined;- if (needsIsolation && !isolatedRoot) throw new Error("isolated workflow has no verified workspace");+ if (needsIsolation && tool.scope !== "read" && !isolatedRoot) throw new Error("isolated workflow has no verified workspace");const result = await withIsolatedFilesystem(isolatedRoot, () => tool.run(args, {signal:context?.signal,liveAuthorization:context?.liveAuthorization,@@ -141,7 +145,7 @@ export async function executeCapabilityCall(input: {capabilities: context?.capabilities,authorizationGrant: context?.authorizationGrant,toolProfile: context?.toolProfile,- }));+ }), { readOnly: tool.scope === "read" });const reportedFailure = capabilityReportedFailure(result) || trail?.outcome?.(result)?.ok === false;const completedState = reportedFailure ? "failed" : "completed";if (trail) {diff --git a/lib/contracts/runtime-identity.ts b/lib/contracts/runtime-identity.tsnew file mode 100644index 00000000..74438382--- /dev/null+++ b/lib/contracts/runtime-identity.ts@@ -0,0 +1,8 @@+export type InstanceEnvironment = "development" | "test" | "staging" | "production";++export type RuntimeIdentity = {+ hostname: string;+ serviceUser: string | null;+ runtimeInstanceId: string | null;+ environment: InstanceEnvironment | null;+};diff --git a/lib/host/fs-descriptors.ts b/lib/host/fs-descriptors.tsindex f3ee14ab..23cc7ca3 100644--- a/lib/host/fs-descriptors.ts+++ b/lib/host/fs-descriptors.ts@@ -3,8 +3,8 @@ import type { FileHandle } from "node:fs/promises";import path from "node:path";import { HostError } from "./host-error";import { isCredentialPath } from "./path-credentials";-import { isUnderRoot, readRootList, writeRootList } from "./path-roots";-import { assertIsolatedPath } from "./fs-isolation";+import { isUnderRoot, writeRootList } from "./path-roots";+import { assertIsolatedPath, readRootListWithWorkspace } from "./fs-isolation";const fdPath = (fd: number) => `/proc/self/fd/${fd}`;const VIRTUAL_FILESYSTEMS = new Set([0x9fa0, 0x62656572, 0x64626720, 0x73636673, 0x74726163, 0x27e0eb, 0x63677270, 0xcafe4a11, 0x62656570, 0x1cd1, 0x6e736673, 0xde5e81e4]);@@ -17,7 +17,7 @@ export async function descriptorPath(handle: FileHandle, write: boolean): Promisconst real = await fs.realpath(fdPath(handle.fd));if (write) await assertIsolatedPath(real);if (isCredentialPath(real)) throw new HostError("Access to credential/sensitive files is blocked");- for (const root of write ? writeRootList() : readRootList()) {+ for (const root of write ? writeRootList() : await readRootListWithWorkspace(real)) {const canonical = path.resolve(/* turbopackIgnore: true */ root);if (isUnderRoot(real, canonical)) return real;}diff --git a/lib/host/fs-isolation.ts b/lib/host/fs-isolation.tsindex 17f6d993..cf7a4d9e 100644--- a/lib/host/fs-isolation.ts+++ b/lib/host/fs-isolation.ts@@ -3,24 +3,73 @@ import { constants, promises as fs } from "node:fs";import type { FileHandle } from "node:fs/promises";import path from "node:path";import { HostError } from "./host-error";-import { isUnderRoot } from "./path-roots";+import { isUnderRoot, readRootList } from "./path-roots";type Boundary = { root: string; handle: FileHandle; held: FileHandle[] };+type ReadScope = { root: string; active: boolean; pin?: Promise<Boundary> };const boundary = new AsyncLocalStorage<Boundary>();+const readableWorkspace = new AsyncLocalStorage<ReadScope | null>();+async function assertPinnedBoundary(current: Boundary): Promise<void> {+ if (await fs.realpath(`/proc/self/fd/${current.handle.fd}`) !== current.root) throw new HostError("Path escapes the pinned isolated workflow workspace");+}+async function pinBoundary(root: string): Promise<Boundary> {+ if (process.platform !== "linux") throw new HostError("Isolated source execution requires Linux/WSL descriptors");+ if (await fs.realpath(root) !== root) throw new HostError("Path escapes the pinned isolated workflow workspace");+ const handle = await fs.open(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);+ const current = { root, handle, held: [] as FileHandle[] };+ try { await assertPinnedBoundary(current); return current; }+ catch (error) { await handle.close(); throw error; }+}+function assertActive(current: ReadScope): void {+ if (!current.active) throw new HostError("Isolated workflow read access has expired");+}+async function readableBoundary(current: ReadScope): Promise<Boundary> {+ assertActive(current);+ const pinned = await (current.pin ??= pinBoundary(current.root));+ assertActive(current);+ await assertPinnedBoundary(pinned);+ assertActive(current);+ return pinned;+}export async function assertIsolatedPath(real: string): Promise<void> {const current = boundary.getStore();if (!current) return;- if (await fs.realpath(`/proc/self/fd/${current.handle.fd}`) !== current.root || !isUnderRoot(real, current.root)) throw new HostError("Path escapes the pinned isolated workflow workspace");+ await assertPinnedBoundary(current);+ if (!isUnderRoot(real, current.root)) throw new HostError("Path escapes the pinned isolated workflow workspace");}-/** Hold the worktree across the complete capability call; host descriptors recheck it before writes. */-export async function withIsolatedFilesystem<T>(root: string | undefined, run: () => Promise<T>): Promise<T> {- if (!root) return run();- if (process.platform !== "linux") throw new HostError("Isolated source execution requires Linux/WSL descriptors");- const canonical = await fs.realpath(root);- const handle = await fs.open(canonical, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);- const current = { root: canonical, handle, held: [] as FileHandle[] };- try { return await boundary.run(current, run); }- finally { await Promise.all([...current.held, handle].map((item) => item.close())); }+/** Pin the owned worktree only when this read needs authority beyond configured roots. */+export async function readRootListWithWorkspace(requested: string): Promise<string[]> {+ const configured = readRootList(), current = readableWorkspace.getStore();+ if (!current || !isUnderRoot(requested, current.root) || configured.some(root => isUnderRoot(requested, path.resolve(root)))) return configured;+ await readableBoundary(current);+ assertActive(current);+ return [...configured, current.root];+}+export async function readableRootRealpath(root: string): Promise<string> {+ const current = readableWorkspace.getStore();+ if (current && root === current.root && !readRootList().some(configured => path.resolve(configured) === root)) {+ await readableBoundary(current);+ assertActive(current);+ return current.root;+ }+ return fs.realpath(root).catch(() => path.resolve(root));+}+/** Writes pin eagerly; reads activate a call-scoped pin only at filesystem access. */+export async function withIsolatedFilesystem<T>(root: string | undefined, run: () => Promise<T>, options: { readOnly?: boolean } = {}): Promise<T> {+ // Standalone nested calls lose the read grant while retaining the parent's write restriction.+ if (!root) return readableWorkspace.run(null, run);+ const canonical = path.resolve(root);+ const eager = options.readOnly ? undefined : await pinBoundary(canonical);+ const current: ReadScope = { root: canonical, active: true, ...(eager ? { pin: Promise.resolve(eager) } : {}) };+ try {+ const invoke = () => readableWorkspace.run(current, run);+ return await (eager ? boundary.run(eager, invoke) : invoke());+ } finally {+ current.active = false;+ // A detached read may still be opening the pin; revoke first, then own its cleanup.+ const pinned = await current.pin?.catch(() => undefined);+ if (pinned) await Promise.all([...pinned.held, pinned.handle].map(item => item.close()));+ }}export async function isolatedCwd(real: string): Promise<string> {const current = boundary.getStore();diff --git a/lib/host/fs-lazy-workspace.test.ts b/lib/host/fs-lazy-workspace.test.tsnew file mode 100644index 00000000..f7a48dd5--- /dev/null+++ b/lib/host/fs-lazy-workspace.test.ts@@ -0,0 +1,100 @@+import { promises as fs } from "node:fs";+import type { FileHandle } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { withIsolatedFilesystem } from "./fs-isolation";+import { readFile } from "./fs";++let base: string, canonical: string, workspace: string;+const data = (root: string) => path.join(root, "data.txt");+function gate() {+ let release!: () => void;+ const promise = new Promise<void>(resolve => { release = resolve; });+ return { promise, release };+}+beforeEach(async () => {+ base = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "mso-lazy-workspace-")));+ canonical = path.join(base, "canonical"); workspace = path.join(base, "cache", "task");+ for (const root of [canonical, workspace]) {+ await fs.mkdir(root, { recursive: true }); await fs.writeFile(data(root), path.basename(root));+ }+ vi.stubEnv("OS_FS_READ_ROOTS", canonical); vi.stubEnv("OS_FS_WRITE_ROOTS", base);+});+afterEach(async () => {+ vi.restoreAllMocks(); vi.unstubAllEnvs();+ await fs.rm(base, { recursive: true, force: true });+});++it("keeps metadata and configured reads independent of a removed prospective workspace", async () => {+ await fs.rm(workspace, { recursive: true });+ const open = vi.spyOn(fs, "open"), realpath = vi.spyOn(fs, "realpath");+ expect(await withIsolatedFilesystem(workspace, async () => ({ ready: true }), { readOnly: true })).toEqual({ ready: true });+ await expect(withIsolatedFilesystem(workspace, () => readFile(data(canonical)), { readOnly: true })).resolves.toBe("canonical");+ for (const spy of [open, realpath]) expect(spy.mock.calls.some(args => String(args[0]) === workspace)).toBe(false);+});++it("keeps an identical configured root on its existing read path without opening a workspace pin", async () => {+ const open = vi.spyOn(fs, "open");+ await expect(withIsolatedFilesystem(canonical, () => readFile(data(canonical)), { readOnly: true })).resolves.toBe("canonical");+ expect(open.mock.calls.some(args => String(args[0]) === canonical)).toBe(false);+});++it("shares the first pin across concurrent reads and closes it when the call completes", async () => {+ const open = fs.open.bind(fs), pins: FileHandle[] = [];+ vi.spyOn(fs, "open").mockImplementation(async (...args: Parameters<typeof fs.open>) => {+ const handle = await open(...args);+ if (String(args[0]) === workspace) pins.push(handle);+ return handle;+ });+ await withIsolatedFilesystem(workspace, async () => {+ expect(await Promise.all([readFile(data(workspace)), readFile(data(workspace))])).toEqual(["task", "task"]);+ expect(pins).toHaveLength(1); expect(pins[0].fd).toBeGreaterThanOrEqual(0);+ }, { readOnly: true });+ expect(pins[0].fd).toBe(-1);+});++it("clears a nested standalone read scope and restores the parent's prospective root", async () => {+ await withIsolatedFilesystem(workspace, async () => {+ await withIsolatedFilesystem(undefined, async () => {+ await expect(readFile(data(workspace))).rejects.toThrow(/outside readable roots/);+ await expect(readFile(data(canonical))).resolves.toBe("canonical");+ });+ await expect(readFile(data(workspace))).resolves.toBe("task");+ }, { readOnly: true });+});++it("refuses a detached continuation after the call completes without opening a new pin", async () => {+ const resume = gate(), open = vi.spyOn(fs, "open");+ let detached!: Promise<unknown>;+ await withIsolatedFilesystem(workspace, async () => {+ detached = resume.promise.then(() => readFile(data(workspace))).catch(error => error);+ }, { readOnly: true });+ resume.release();+ expect(await detached).toMatchObject({ message: expect.stringContaining("read access has expired") });+ expect(open.mock.calls.some(args => String(args[0]) === workspace)).toBe(false);+});++it.each([false, true])("revokes a pending detached pin and preserves the handler error (pinFails=%s)", async pinFails => {+ const opening = gate(), resume = gate(), finished = gate(), open = fs.open.bind(fs);+ const handlerError = new Error("fixture handler failed"), pinError = new Error("fixture pin failed");+ let pin: FileHandle | undefined, detached!: Promise<unknown>;+ vi.spyOn(fs, "open").mockImplementation(async (...args: Parameters<typeof fs.open>) => {+ if (String(args[0]) !== workspace) return open(...args);+ if (!pinFails) pin = await open(...args);+ opening.release(); await resume.promise;+ if (pinFails) throw pinError;+ return pin!;+ });+ const outcome = withIsolatedFilesystem(workspace, async () => {+ detached = readFile(data(workspace)).catch(error => error);+ await opening.promise; finished.release();+ throw handlerError;+ }, { readOnly: true }).catch(error => error);+ await finished.promise;+ await new Promise<void>(resolve => setTimeout(resolve, 0));+ resume.release();+ expect(await outcome).toBe(handlerError);+ expect(await detached).toMatchObject({ message: expect.stringContaining(pinFails ? "fixture pin failed" : "read access has expired") });+ if (!pinFails) expect(pin!.fd).toBe(-1);+});diff --git a/lib/host/fs-workspace-reads.test.ts b/lib/host/fs-workspace-reads.test.tsnew file mode 100644index 00000000..d346bf52--- /dev/null+++ b/lib/host/fs-workspace-reads.test.ts@@ -0,0 +1,162 @@+import { promises as fs, renameSync, symlinkSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { withIsolatedFilesystem } from "./fs-isolation";+import { listDir, readFile, writeFile } from "./fs";+import { readFileBytes } from "./fs-read-bytes";+import { writeFileGuarded } from "./guarded-write";+import { sha256Text } from "./hash";+import { resolveReadable } from "./paths";++let base: string, canonical: string, workspace: string, sibling: string;+const data = (root: string) => path.join(root, "data.txt");+beforeEach(async () => {+ base = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "mso-workspace-reads-")));+ canonical = path.join(base, "canonical");+ workspace = path.join(base, "cache", "task");+ sibling = path.join(base, "cache", "other-task");+ for (const root of [canonical, workspace, sibling]) {+ await fs.mkdir(root, { recursive: true });+ await fs.writeFile(data(root), path.basename(root));+ }+ vi.stubEnv("OS_FS_READ_ROOTS", canonical);+ vi.stubEnv("OS_FS_WRITE_ROOTS", base);+});+afterEach(async () => {+ vi.restoreAllMocks(); vi.unstubAllEnvs();+ await fs.rm(base, { recursive: true, force: true });+});++it.each([false, true])("reads only the pinned workspace in addition to the configured roots (readOnly=%s)", async readOnly => {+ await expect(readFile(data(workspace))).rejects.toThrow(/outside readable roots/);+ await withIsolatedFilesystem(workspace, async () => {+ await expect(readFile(data(workspace))).resolves.toBe("task");+ expect((await readFileBytes(data(workspace))).toString()).toBe("task");+ expect((await listDir(workspace)).entries.map(entry => entry.name)).toEqual(["data.txt"]);+ await expect(readFile(data(canonical))).resolves.toBe("canonical");+ await expect(readFile(data(sibling))).rejects.toThrow(/outside readable roots/);+ await expect(listDir(path.dirname(workspace))).rejects.toThrow(/outside readable roots/);+ }, { readOnly });+ await expect(readFile(data(workspace))).rejects.toThrow(/outside readable roots/);+});++it("supports existing-file hash checks while preserving stale-write and write-root refusals", async () => {+ await withIsolatedFilesystem(workspace, async () => {+ await expect(writeFileGuarded({ path: data(workspace), content: "updated", expectedSha256: sha256Text("task") }))+ .resolves.toMatchObject({ previousSha256: sha256Text("task"), sha256: sha256Text("updated") });+ await expect(writeFileGuarded({ path: data(workspace), content: "stale", expectedSha256: sha256Text("task") }))+ .rejects.toThrow(/changed since fs_read/);+ await expect(writeFile(data(canonical), "changed")).rejects.toThrow(/isolated/);+ vi.stubEnv("OS_FS_WRITE_ROOTS", canonical);+ await expect(writeFile(data(workspace), "changed")).rejects.toThrow(/outside writable roots/);+ await expect(readFile(data(workspace))).resolves.toBe("updated");+ });+ expect(await fs.readFile(data(canonical), "utf8")).toBe("canonical");+});++it.each([false, true])("keeps credential and symlink checks on the extra read root (readOnly=%s)", async readOnly => {+ await fs.writeFile(path.join(workspace, ".env"), "fixture");+ await fs.symlink(sibling, path.join(workspace, "escape"));+ await fs.symlink(path.join(workspace, ".env"), path.join(workspace, "alias"));+ await withIsolatedFilesystem(workspace, async () => {+ for (const target of [path.join(workspace, ".env"), path.join(workspace, "alias")])+ await expect(readFile(target)).rejects.toThrow(/credential|sensitive/);+ await expect(readFile(path.join(workspace, "escape", "data.txt"))).rejects.toThrow(/outside readable roots/);+ }, { readOnly });+});++it("clears nested standalone read grants without dropping the inherited write restriction", async () => {+ await withIsolatedFilesystem(workspace, async () => {+ await withIsolatedFilesystem(undefined, async () => {+ await expect(readFile(data(workspace))).rejects.toThrow(/outside readable roots/);+ await expect(readFile(data(canonical))).resolves.toBe("canonical");+ await expect(writeFile(data(canonical), "changed")).rejects.toThrow(/isolated/);+ });+ await expect(readFile(data(workspace))).resolves.toBe("task");+ });+});++it.each([false, true])("does not mix simultaneous workspace read grants (readOnly=%s)", async readOnly => {+ let entered = 0, release = () => {};+ const ready = new Promise<void>(resolve => { release = resolve; });+ await Promise.all([workspace, sibling].map(own => withIsolatedFilesystem(own, async () => {+ if (++entered === 2) release();+ await ready;+ await expect(readFile(data(own))).resolves.toBe(path.basename(own));+ await expect(readFile(data(own === workspace ? sibling : workspace))).rejects.toThrow(/outside readable roots/);+ }, { readOnly })));+});++it.each([false, true])("rejects a workspace replaced by a symlink before pinning (readOnly=%s)", async readOnly => {+ await fs.rename(workspace, workspace + "-held");+ await fs.symlink(sibling, workspace);+ const run = vi.fn(async () => readFile(data(workspace)));+ await expect(withIsolatedFilesystem(workspace, run, { readOnly })).rejects.toThrow(/isolated/);+ expect(run).toHaveBeenCalledTimes(readOnly ? 1 : 0);+});++it.each([false, true])("rejects an ancestor exchange while opening the workspace (readOnly=%s)", async readOnly => {+ const cache = path.dirname(workspace), outside = path.join(base, "outside");+ await fs.mkdir(path.join(outside, "task"), { recursive: true });+ await fs.writeFile(data(path.join(outside, "task")), "outside");+ const open = fs.open.bind(fs); let swapped = false;+ vi.spyOn(fs, "open").mockImplementation((...args: Parameters<typeof fs.open>) => {+ if (!swapped && String(args[0]) === workspace) {+ swapped = true; renameSync(cache, cache + "-held"); symlinkSync(outside, cache);+ }+ return open(...args);+ });+ const run = vi.fn(async () => readFile(data(workspace)));+ await expect(withIsolatedFilesystem(workspace, run, { readOnly })).rejects.toThrow(/isolated/);+ expect(swapped).toBe(true); expect(run).toHaveBeenCalledTimes(readOnly ? 1 : 0);+});++it.each([false, true])("checks the opened file after a descendant ancestor exchange (readOnly=%s)", async readOnly => {+ const nested = path.join(workspace, "nested"), target = data(nested);+ await fs.mkdir(nested); await fs.writeFile(target, "inside");+ const open = fs.open.bind(fs); let swapped = false;+ vi.spyOn(fs, "open").mockImplementation((...args: Parameters<typeof fs.open>) => {+ if (!swapped && String(args[0]) === target) {+ swapped = true; renameSync(nested, nested + "-held"); symlinkSync(sibling, nested);+ }+ return open(...args);+ });+ await expect(withIsolatedFilesystem(workspace, () => readFile(target), { readOnly })).rejects.toThrow(/outside readable roots/);+ expect(swapped).toBe(true);+});++it.each([false, true])("rejects replacement reads after the pinned root moves (readOnly=%s)", async readOnly => {+ await withIsolatedFilesystem(workspace, async () => {+ await expect(readFile(data(workspace))).resolves.toBe("task");+ await fs.rename(workspace, workspace + "-held");+ await fs.mkdir(workspace); await fs.writeFile(data(workspace), "replacement");+ await expect(readFile(data(workspace))).rejects.toThrow(/isolated/);+ }, { readOnly });+});++it.each([false, true])("compares resolved reads with the pinned literal root after an ABA exchange (readOnly=%s)", async readOnly => {+ const target = data(workspace), held = workspace + "-held";+ const realpath = fs.realpath.bind(fs);+ let swapped = false, restored = false;+ const restore = async () => {+ await fs.unlink(workspace); await fs.rename(held, workspace); restored = true;+ };+ vi.spyOn(fs, "realpath").mockImplementation(async (...args: Parameters<typeof fs.realpath>) => {+ const requested = String(args[0]);+ if (!swapped && requested === target) {+ await fs.rename(workspace, held); await fs.symlink(sibling, workspace); swapped = true;+ return realpath(...args);+ }+ if (swapped && !restored && requested === workspace) {+ const outsideRoot = await realpath(...args);+ await restore();+ return outsideRoot;+ }+ if (swapped && !restored && requested.startsWith("/proc/self/fd/")) await restore();+ return realpath(...args);+ });+ await expect(withIsolatedFilesystem(workspace, () => resolveReadable(target), { readOnly })).rejects.toThrow(/outside readable roots/);+ expect(swapped).toBe(true); expect(restored).toBe(true);+ expect(await fs.readFile(target, "utf8")).toBe("task");+});diff --git a/lib/host/paths.ts b/lib/host/paths.tsindex 361a02ae..79ff49e7 100644--- a/lib/host/paths.ts+++ b/lib/host/paths.ts@@ -8,6 +8,7 @@ import type { FsRoot } from "@/lib/os-api/types";import { promises as fs } from "fs";import path from "path";import { HostError } from "./host-error";+import { readRootListWithWorkspace, readableRootRealpath } from "./fs-isolation";import { isCredentialPath } from "./path-credentials";import { homeDir, isUnderRoot, readRootList, writeRootList } from "./path-roots";export { appDir, isAppSecret, isCredentialPath, isSensitivePath, looseCredentialExcludes } from "./path-credentials";@@ -76,7 +77,7 @@ export async function resolveReadable(requested: string): Promise<string> {else absolute = path.resolve(requested);const normalized = path.resolve(absolute);assertNotCredential(normalized);- const configured = lexicalRoots(readRootList());+ const configured = lexicalRoots(await readRootListWithWorkspace(normalized));// Keep each filesystem sink inside the SAFE branch of CodeQL's documented// path.relative sanitizer. Runtime-equivalent flags/helpers hide the proof from@@ -87,7 +88,7 @@ export async function resolveReadable(requested: string): Promise<string> {continue;} else {const real = await fs.realpath(normalized);- const realRoot = await fs.realpath(root).catch(() => path.resolve(root));+ const realRoot = await readableRootRealpath(root);const realRelative = path.relative(realRoot, real);if (realRelative === ".." ||diff --git a/lib/host/project-list-recovery.test.ts b/lib/host/project-list-recovery.test.tsnew file mode 100644index 00000000..516a9505--- /dev/null+++ b/lib/host/project-list-recovery.test.ts@@ -0,0 +1,67 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { promises as fs } from "fs";+import os from "os";+import path from "path";+import { listProjects } from "./project-list";+import { PROJECT_LIMITS } from "./project-roots";+import { resolveProjectHint } from "./projects";++let root: string;+beforeEach(async () => {+ root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "mso-root-recovery-")));+ vi.stubEnv("OS_FS_READ_ROOTS", root);+ vi.stubEnv("OS_PROJECT_ROOTS", "");+});+afterEach(async () => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+ await fs.rm(root, { recursive: true, force: true });+});++describe("configured-root discovery recovery", () => {+ it("offers exact-path inspection while preserving an existing root-project identity", async () => {+ await fs.writeFile(path.join(root, "package.json"), JSON.stringify({ name: "fixture-root" }));+ const before = await resolveProjectHint(root);+ expect(before).toMatchObject({ path: root, packageName: "fixture-root" });++ const result = await listProjects({ query: path.basename(root) });+ expect(result).toMatchObject({ total: 0, projects: [], scan: { truncated: false } });+ expect(result.containers.map(container => container.path)).toEqual([root]);+ expect(result.nextAction).toContain("project_get");+ expect(result.nextAction).toContain("exact path");+ const after = await resolveProjectHint(result.containers[0].path);+ expect(after).toMatchObject({ id: before!.id, path: root, packageName: "fixture-root" });+ });++ it("keeps an empty container unclassified as a repository", async () => {+ const result = await listProjects();+ expect(result).toMatchObject({ total: 0, projects: [], scan: { truncated: false } });+ expect(result.containers.map(container => container.path)).toEqual([root]);+ expect(result.nextAction).toContain("Container entries do not establish repository contents.");+ });++ it("does not suggest root recovery for an exhausted page that has matching projects", async () => {+ await fs.mkdir(path.join(root, "child"));+ const result = await listProjects({ offset: 1 });+ expect(result).toMatchObject({ total: 1, projects: [], hasMore: false });+ expect(result.nextAction).toBeUndefined();+ });++ it("keeps a zero-result deadline scan resumable", async () => {+ await fs.mkdir(path.join(root, "child"));+ const epoch = 1_800_000_000_000;+ let calls = 0;+ const clock = vi.spyOn(Date, "now").mockImplementation(() => epoch + (calls++ === 0 ? 0 : PROJECT_LIMITS.maxScanMs + 1));+ const first = await listProjects();+ expect(first).toMatchObject({ total: 0, projects: [], scan: { truncated: true, truncationReasons: ["deadline"] } });+ expect(first.nextAction).toContain("scan.continuation.cursor");+ expect(first.scan.continuation?.cursor).toBeTruthy();++ clock.mockReturnValue(epoch + PROJECT_LIMITS.maxScanMs + 1);+ const resumed = await listProjects({ cursor: first.scan.continuation!.cursor });+ expect(resumed).toMatchObject({ total: 1, scan: { truncated: false } });+ expect(resumed.projects.map(project => project.path)).toEqual([path.join(root, "child")]);+ expect(resumed.nextAction).toBeUndefined();+ });+});+diff --git a/lib/host/project-list.ts b/lib/host/project-list.tsindex 13bd46c1..29f9c11e 100644--- a/lib/host/project-list.ts+++ b/lib/host/project-list.ts@@ -15,6 +15,7 @@ export type ListProjectsResult = {limit: number;hasMore: boolean;nextOffset?: number;+ nextAction?: string;scan: ScanReport;projects: ProjectRow[];};@@ -48,6 +49,11 @@ export async function listProjects(}));const hasMore = offset + page.length < matched.length;return {+ ...(matched.length === 0 && containers.length ? {+ nextAction: "This scan lists child directories. Check scan.truncated and pass scan.continuation.cursor back as cursor when present. " ++ "A returned container may itself be the intended project; call project_get with its exact path only when it matches the target. " ++ "Container entries do not establish repository contents.",+ } : {}),roots: containers.map((c) => c.path),containers: containers.map(({ id, path: p, derived, authorizedRoot }) => ({ id, path: p, derived, authorizedRoot })),total: matched.length,diff --git a/lib/host/runtime-identity.test.ts b/lib/host/runtime-identity.test.tsnew file mode 100644index 00000000..a1d0ccec--- /dev/null+++ b/lib/host/runtime-identity.test.ts@@ -0,0 +1,29 @@+import os from "node:os";+import { afterEach, describe, expect, it, vi } from "vitest";+import { getRuntimeIdentity } from "./runtime-identity";++afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); });++describe("private runtime identity", () => {+ it("does not infer the host environment from a production build", () => {+ vi.stubEnv("NODE_ENV", "production");+ vi.stubEnv("OS_INSTANCE_ENVIRONMENT", undefined);+ vi.stubEnv("MSO_RUNTIME_INSTANCE_ID", undefined);+ vi.spyOn(os, "hostname").mockReturnValue("fixture-host");+ expect(getRuntimeIdentity()).toEqual({+ hostname: "fixture-host", serviceUser: os.userInfo().username, runtimeInstanceId: null, environment: null,+ });+ });++ it.each(["development", "test", "staging", "production"])("returns the explicitly declared %s role", environment => {+ vi.stubEnv("OS_INSTANCE_ENVIRONMENT", environment);+ vi.stubEnv("MSO_RUNTIME_INSTANCE_ID", "runtime-restart-proof");+ expect(getRuntimeIdentity()).toMatchObject({ environment, runtimeInstanceId: "runtime-restart-proof" });+ });++ it("leaves an invalid environment and an unavailable service user unknown", () => {+ vi.stubEnv("OS_INSTANCE_ENVIRONMENT", "prod");+ vi.spyOn(os, "userInfo").mockImplementation(() => { throw new Error("passwd entry unavailable"); });+ expect(getRuntimeIdentity()).toMatchObject({ serviceUser: null, environment: null });+ });+});diff --git a/lib/host/runtime-identity.ts b/lib/host/runtime-identity.tsnew file mode 100644index 00000000..4cd67944--- /dev/null+++ b/lib/host/runtime-identity.ts@@ -0,0 +1,16 @@+import os from "node:os";+import type { InstanceEnvironment, RuntimeIdentity } from "@/lib/contracts/runtime-identity";++export function getRuntimeIdentity(): RuntimeIdentity {+ let serviceUser: string | null = null;+ try { serviceUser = os.userInfo().username || null; } catch { /* The service may have no passwd entry. */ }+ const declaredEnvironment = process.env.OS_INSTANCE_ENVIRONMENT?.trim() ?? "";+ const environment = ["development", "test", "staging", "production"].includes(declaredEnvironment)+ ? declaredEnvironment as InstanceEnvironment : null;+ return {+ hostname: os.hostname(),+ serviceUser,+ runtimeInstanceId: process.env.MSO_RUNTIME_INSTANCE_ID || null,+ environment,+ };+}diff --git a/lib/host/system-api.ts b/lib/host/system-api.tsindex a5b47489..b837abe6 100644--- a/lib/host/system-api.ts+++ b/lib/host/system-api.ts@@ -1 +1,2 @@export { stats, processes } from "./sys";+export { getRuntimeIdentity } from "./runtime-identity";diff --git a/lib/mcp/tool-contract.test.ts b/lib/mcp/tool-contract.test.tsindex 60dbd758..fedf4deb 100644--- a/lib/mcp/tool-contract.test.ts+++ b/lib/mcp/tool-contract.test.ts@@ -40,4 +40,31 @@ describe("MCP advertised tool contract", () => {expect(toolDescriptor(write!, "chatgpt")._meta).not.toHaveProperty("mso/actionContract");});+ it.each([+ ["Read bounded workflow details before editing.", "Read bounded workflow details…"],+ ["Read bounded workflow snapshots from disk.", "Read bounded workflow…"],+ ["x".repeat(50), `${"x".repeat(29)}…`],+ ["Read a workflow safely now. Continue when ready.", "Read a workflow safely now.…"],+ ["Read a workflow safely now; continue when ready.", "Read a workflow safely now;…"],+ ["First call for multi-step work", "First call for multi-step work"],+ ])("compacts %j within the existing bound without unnecessary word fragments", (description, expected) => {+ const original = TOOLS.find((tool) => tool.name === "workflow_start")!;+ const tool = { ...original, description, chatgptDescription: description };+ const compact = toolDescriptor(tool, "chatgpt");+ expect(compact.description).toBe(expected);+ expect(compact.description.length).toBeLessThanOrEqual(30);+ expect(toolDescriptor(tool, "full").description).toBe(description);+ });++ it("keeps the full description when a compact client description is supplied", () => {+ const original = TOOLS.find((tool) => tool.name === "workflow_start")!;+ const description = "Read bounded workflow details before editing. Preserve this complete instruction.";+ const tool = { ...original, description, chatgptDescription: "Read bounded workflow snapshots from disk." };+ expect(toolDescriptor(tool, "chatgpt").description).toBe("Read bounded workflow…");+ const full = toolDescriptor(tool, "full");+ expect(full.description).toBe(description);+ expect(full.inputSchema).toEqual(tool.inputSchema);+ expect(full.outputSchema).toEqual(tool.outputSchema);+ });+});diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.tsindex 37e59997..4127bfee 100644--- a/lib/mcp/tool-contract.ts+++ b/lib/mcp/tool-contract.ts@@ -105,7 +105,9 @@ function compactText(value: string, max = 80): string {if (clean.length <= max) return clean;const cut = clean.slice(0, max - 1);const sentence = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("; "));- return `${(sentence > max * 0.8 ? cut.slice(0, sentence + 1) : cut).trim()}…`;+ const word = clean[max - 1] === " " ? cut.length : cut.lastIndexOf(" ");+ const end = sentence > max * 0.8 ? sentence + 1 : word > max * 0.5 ? word : cut.length;+ return `${cut.slice(0, end).trim()}…`;}function compactSchema(value: unknown): unknown {diff --git a/lib/mcp/tools-learning-shared.test.ts b/lib/mcp/tools-learning-shared.test.tsindex f658d1b2..0391e958 100644--- a/lib/mcp/tools-learning-shared.test.ts+++ b/lib/mcp/tools-learning-shared.test.ts@@ -27,6 +27,23 @@ describe("workflow_start structured projection", () => {expect(projected.context.recipe).toMatchObject({ id: "recipe-1", maturity: "verified", tools: ["browser_status", "exec_run"] });});+ it("exposes exact authorized workspace paths without unrelated orchestration data", () => {+ const workspacePath = "/srv/task worktree/" + "deep/".repeat(50);+ const projected = workflowStartProjection({+ workflow: {+ id: "wf-workspace", project: "/srv/mso", startedAt: "2026-10-17T00:00:00.000Z", steps: [],+ orchestration: { workspacePath, isolation: "isolated-worktree", baseCommit: "abc123", baseBranch: "main", reservedResources: ["private-context"] },+ },+ });+ expect(projected?.workspace).toEqual({ path: workspacePath, projectPath: "/srv/mso", isolation: "isolated-worktree", baseCommit: "abc123", baseBranch: "main" });+ expect(JSON.stringify(projected)).not.toContain("private-context");+ });++ it("does not invent a workspace for unresolved host work", () => {+ const projected = workflowStartProjection({ workflow: { id: "wf-host", project: "@host", startedAt: "2026-10-17T00:00:00.000Z", steps: [] } });+ expect(projected).not.toHaveProperty("workspace");+ });+it("falls back to projected memory plus recipe when orchestration count is absent", () => {const projected = workflowStartProjection({workflow: { id: "wf-2", startedAt: "2026-09-19T00:00:00.000Z", steps: [] },diff --git a/lib/mcp/tools-workflow-start-output.ts b/lib/mcp/tools-workflow-start-output.tsindex e0d3c877..432b5fed 100644--- a/lib/mcp/tools-workflow-start-output.ts+++ b/lib/mcp/tools-workflow-start-output.ts@@ -4,6 +4,17 @@ export const WORKFLOW_START_OUTPUT = {...WORKFLOW_PROGRESS_OUTPUT,properties: {...WORKFLOW_PROGRESS_OUTPUT.properties,+ workspace: {+ type: "object",+ properties: {+ path: { type: "string", description: "Exact authorized path for source files and exec cwd." },+ projectPath: { type: "string", description: "Canonical project path." },+ isolation: { type: "string", enum: ["direct", "optional-worktree", "isolated-worktree"] },+ baseCommit: { type: "string" },+ baseBranch: { type: "string" },+ },+ required: ["path", "isolation"], additionalProperties: false,+ },context: {type: "object",properties: {@@ -51,6 +62,19 @@ export function workflowStartProjection(result: unknown): Record<string, unknownconst row = result as Record<string, unknown>;const progress = workflowProgress(row.workflow, true);if (!progress) return undefined;+ const workflow = row.workflow as Record<string, unknown>;+ const snapshot = workflow.orchestration && typeof workflow.orchestration === "object"+ ? workflow.orchestration as Record<string, unknown> : {};+ const workspace = typeof snapshot.workspacePath === "string" && snapshot.workspacePath+ && ["direct", "optional-worktree", "isolated-worktree"].includes(String(snapshot.isolation))+ ? {+ path: snapshot.workspacePath,+ isolation: snapshot.isolation,+ ...(typeof workflow.project === "string" ? { projectPath: workflow.project } : {}),+ ...(typeof snapshot.baseCommit === "string" ? { baseCommit: snapshot.baseCommit } : {}),+ ...(typeof snapshot.baseBranch === "string" ? { baseBranch: snapshot.baseBranch } : {}),+ }+ : undefined;const bootstrap = row.bootstrap && typeof row.bootstrap === "object" ? row.bootstrap as Record<string, unknown> : {};const orchestration = bootstrap.orchestration && typeof bootstrap.orchestration === "object"? bootstrap.orchestration as Record<string, unknown> : {};@@ -112,6 +136,7 @@ export function workflowStartProjection(result: unknown): Record<string, unknown}return {...progress,+ ...(workspace ? { workspace } : {}),context: {memory: memory.slice(0, 10),memoryHits: Number.isFinite(Number(orchestration.memoryHits))diff --git a/lib/mcp/tools-workflow-start.ts b/lib/mcp/tools-workflow-start.tsindex fd519f98..0e897062 100644--- a/lib/mcp/tools-workflow-start.ts+++ b/lib/mcp/tools-workflow-start.ts@@ -58,7 +58,7 @@ export const WORKFLOW_START_TOOL: McpTool = {: { activeWorkflowCount: 0, conflictingWorkflowCount: 0, overlappingPaths: [], overlappingResources: [] };const activeProjectWorkflows = contention.activeWorkflowCount;const classification = classifyTask({- intent, constraints: opt(a, "constraints"), scope: context.scope, changedPaths, activeProjectWorkflows,+ intent, constraints: opt(a, "constraints"), scope: context.scope, changedPaths, affectedPaths, activeProjectWorkflows,collisionPaths: contention.overlappingPaths, collisionResources: contention.overlappingResources,});const memoryLimit = classification.memoryRelevance === "high" ? 5 : classification.memoryRelevance === "medium" ? 3 : 0;diff --git a/lib/mcp/workflow-filesystem.test.ts b/lib/mcp/workflow-filesystem.test.tsnew file mode 100644index 00000000..a467eb8a--- /dev/null+++ b/lib/mcp/workflow-filesystem.test.ts@@ -0,0 +1,164 @@+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { WorkflowOrchestrationSnapshot } from "@/lib/contracts/orchestration";+import type { CapabilityTool } from "@/lib/capabilities/tool";+import type { Scope } from "@/lib/capabilities/scope";+vi.mock("server-only", () => ({}));+vi.mock("@/lib/host/audit-api", async original => {+ const actual = await original() as typeof import("@/lib/host/audit-api");+ return { ...actual, audit: vi.fn(async () => {}) };+});+vi.mock("@/lib/agent/session-store", async original => {+ const actual = await original() as typeof import("@/lib/agent/session-store");+ return { ...actual, maybeAutoTitleAgentSession: vi.fn(async () => {}), appendAgentSessionEvent: vi.fn(async () => {}) };+});++const { executeCapabilityCall } = await import("@/lib/capabilities/execute");+const { workflowActor } = await import("@/lib/capabilities/actors");+const { startWorkflow, activeWorkflowForActor, cancelWorkflow, resetWorkflowStoreCache } = await import("@/lib/workflow");+const { READ_TOOLS } = await import("./tools-read");+const { MUTATE_TOOLS } = await import("./tools-mutate");+const { WORKFLOW_LIFECYCLE_TOOLS } = await import("./tools-workflow-lifecycle");+const { sha256Text, readFile: hostReadFile } = await import("@/lib/host/fs-api");+const tenancy = await import("@/lib/tenancy/capability");+const read = READ_TOOLS.find(tool => tool.name === "fs_read")!;+const write = MUTATE_TOOLS.find(tool => tool.name === "fs_write")!;+const status = WORKFLOW_LIFECYCLE_TOOLS.find(tool => tool.name === "workflow_status")!;+const actor = "mcp:workspace-read-test";+const owner = { principal: "workspace-client", sessionId: "session-a" };+let base: string, canonical: string, workspace: string, sibling: string, workflowId: string;+const data = (root: string) => path.join(root, "data.txt");+const orchestration = (workspacePath?: string): WorkflowOrchestrationSnapshot => ({+ risk: "medium", complexity: "light", contention: "none", memoryRelevance: "low",+ isolation: "isolated-worktree", verification: "affected", reasons: [], sharedResourceWarnings: [],+ changedPaths: [], affectedPaths: [], reservedResources: [], overlappingPaths: [], overlappingResources: [],+ activeProjectWorkflows: 0, conflictingWorkflowCount: 0, memoryHits: 0, contextEstimateTokens: 0,+ cleanupState: "pending", createdAt: new Date().toISOString(), workspacePath,+});+async function start(workspacePath?: string) {+ return (await startWorkflow({+ actor: workflowActor(actor, owner), scope: "exec", intent: "Fix the fixture source",+ project: canonical, orchestration: orchestration(workspacePath),+ })).workflow.id;+}+const call = (tool: CapabilityTool, args: Record<string, unknown>, scope: Scope = "read", context = owner) =>+ executeCapabilityCall({ tool, args, scope, actor, context });++beforeEach(async () => {+ base = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "mso-workflow-fs-")));+ canonical = path.join(base, "canonical"); workspace = path.join(base, "cache", "task"); sibling = path.join(base, "cache", "other");+ for (const root of [canonical, workspace, sibling]) {+ await fs.mkdir(root, { recursive: true }); await fs.writeFile(data(root), path.basename(root));+ }+ vi.stubEnv("OS_FS_READ_ROOTS", canonical); vi.stubEnv("OS_FS_WRITE_ROOTS", base);+ vi.stubEnv("OS_SKILL_MEMORY_STORE", path.join(base, "workflow.json"));+ vi.stubEnv("OS_MCP_ACTIVITY_LOG", "");+ resetWorkflowStoreCache(); workflowId = await start(workspace);+});+afterEach(async () => {+ resetWorkflowStoreCache(); vi.restoreAllMocks(); vi.unstubAllEnvs();+ await fs.rm(base, { recursive: true, force: true });+});++it("authorizes bounded worktree reads and optimistic writes through the real capability kernel", async () => {+ const result = await call(read, { path: data(workspace), workflow_id: workflowId });+ expect(result).toMatchObject({ kind: "success", result: { content: "task", sha256: sha256Text("task") } });+ const args = { path: data(workspace), content: "updated", expected_sha256: sha256Text("task"), workflow_id: workflowId };+ expect(await call(write, args, "read")).toMatchObject({ kind: "error", message: expect.stringContaining('needs "write"') });+ expect(await call(write, args, "exec")).toMatchObject({ kind: "success", result: { previousSha256: sha256Text("task") } });+ expect(await call(write, args, "exec")).toMatchObject({ kind: "error", message: expect.stringContaining("changed since fs_read") });+ expect(await call(read, { path: data(canonical), workflow_id: workflowId }))+ .toMatchObject({ kind: "success", result: { content: "canonical" } });+});++it("requires the exact active workflow owned by the current client session", async () => {+ expect(await call(read, { path: data(workspace) }))+ .toMatchObject({ kind: "error", message: expect.stringContaining("outside readable roots") });+ for (const context of [{ ...owner, sessionId: "session-b" }, { ...owner, principal: "other-client" }])+ expect(await call(read, { path: data(workspace), workflow_id: workflowId }, "read", context))+ .toMatchObject({ kind: "error", message: expect.stringContaining("not found for this MSO session") });+ expect(await call(read, { path: data(workspace), workflow_id: "missing" }))+ .toMatchObject({ kind: "error", message: expect.stringContaining("not found for this MSO session") });+ const siblingWorkflow = await start(sibling);+ expect(await call(read, { path: data(sibling), workflow_id: workflowId }))+ .toMatchObject({ kind: "error", message: expect.stringContaining("outside readable roots") });+ expect(await call(read, { path: data(sibling), workflow_id: siblingWorkflow }))+ .toMatchObject({ kind: "success", result: { content: "other" } });+ await cancelWorkflow({ actor: workflowActor(actor, owner), workflowId });+ expect(await call(read, { path: data(workspace), workflow_id: workflowId }))+ .toMatchObject({ kind: "error", message: expect.stringContaining("not found for this MSO session") });+});++it.each(["unprepared", "removed"] as const)("keeps configured reads and metadata available when the workspace is %s", async state => {+ const id = state === "unprepared" ? await start() : workflowId;+ if (state === "removed") await fs.rm(workspace, { recursive: true });+ const metadata: CapabilityTool = { ...status, name: "workspace_metadata_test", run: async () => ({ ready: true }) };+ expect(await call(metadata, { workflow_id: id })).toMatchObject({ kind: "success", result: { ready: true } });+ expect(await call(read, { path: data(canonical), workflow_id: id }))+ .toMatchObject({ kind: "success", result: { content: "canonical" } });+ expect(await call(read, { path: data(workspace), workflow_id: id })).toMatchObject({ kind: "error" });+ expect(await call(write, { path: data(workspace), content: "changed", workflow_id: id }, "exec"))+ .toMatchObject({ kind: "error", message: expect.stringContaining(state === "unprepared" ? "no verified workspace" : "ENOENT") });+});+++it.each(["unprepared", "removed"] as const)("keeps owned workflow status available when the workspace is %s", async state => {+ const id = state === "unprepared" ? await start() : workflowId;+ if (state === "removed") await fs.rm(workspace, { recursive: true });+ const before = await activeWorkflowForActor(workflowActor(actor, owner), id);+ expect(before).toMatchObject({ orchestration: { isolation: "isolated-worktree" }, steps: [] });++ const result = await call(status, { workflow_id: id });+ expect(result).toMatchObject({ kind: "success", result: { active: true, workflowId: id, project: "canonical", stepCount: 0 } });+ expect(JSON.stringify(result)).not.toContain(canonical);+ expect((await activeWorkflowForActor(workflowActor(actor, owner), id))?.steps).toEqual(before!.steps);+ for (const context of [{ ...owner, sessionId: "session-b" }, { ...owner, principal: "other-client" }])+ expect(await call(status, { workflow_id: id }, "read", context))+ .toMatchObject({ kind: "success", result: { active: false, workflowId: id, stepCount: 0, steps: [] } });+});++it("does not probe the workspace or leave read authority behind when returning status", async () => {+ const open = vi.spyOn(fs, "open"), realpath = vi.spyOn(fs, "realpath");+ expect(await call(status, { workflow_id: workflowId }))+ .toMatchObject({ kind: "success", result: { active: true, workflowId } });+ for (const spy of [open, realpath])+ expect(spy.mock.calls.some(args => String(args[0]) === workspace || String(args[0]).startsWith(workspace + path.sep))).toBe(false);+ await expect(hostReadFile(data(workspace))).rejects.toThrow(/outside readable roots/);+});++it("requires nested capability calls to forward their exact workflow id", async () => {+ const nested: CapabilityTool = {+ ...read, name: "workspace_nested_test",+ run: async args => ({+ standalone: await call(read, { path: data(workspace) }),+ correlated: await call(read, { path: data(workspace), workflow_id: args.workflow_id }),+ }),+ };+ expect(await call(nested, { path: data(workspace), workflow_id: workflowId })).toMatchObject({+ kind: "success", result: {+ standalone: { kind: "error", message: expect.stringContaining("outside readable roots") },+ correlated: { kind: "success", result: { content: "task" } },+ },+ });+});++it("clears inherited read authority before nested tenant planning", async () => {+ let planningRead: PromiseSettledResult<string> | undefined;+ const originalPlan = tenancy.tenantCapabilityPlan;+ const nested: CapabilityTool = {+ ...read, name: "workspace_tenant_entry_test",+ run: async () => {+ const spy = vi.spyOn(tenancy, "tenantCapabilityPlan").mockImplementationOnce(async (...args) => {+ [planningRead] = await Promise.allSettled([hostReadFile(data(workspace))]);+ return originalPlan(...args);+ });+ try { return await call(read, { path: data(canonical) }); }+ finally { spy.mockRestore(); }+ },+ };+ expect(await call(nested, { path: data(workspace), workflow_id: workflowId }))+ .toMatchObject({ kind: "success", result: { kind: "success", result: { content: "canonical" } } });+ expect(planningRead).toMatchObject({ status: "rejected", reason: expect.objectContaining({ message: expect.stringContaining("outside readable roots") }) });+});diff --git a/lib/mcp/workflow-source-isolation.test.ts b/lib/mcp/workflow-source-isolation.test.tsindex f17ec7d1..9619c38c 100644--- a/lib/mcp/workflow-source-isolation.test.ts+++ b/lib/mcp/workflow-source-isolation.test.ts@@ -52,6 +52,7 @@ describe("workflow_start source isolation", () => {const actor = "mcp:source-isolation";const started = await start.run({intent: "fix the source value and verify the repository",+ constraints: "Do not modify unrelated files.",project,affected_paths: ["src/value.ts"],}, { actor, scope: "exec" }) as {@@ -64,6 +65,9 @@ describe("workflow_start source isolation", () => {expect(workspace).toBeTruthy(); expect(workspace).not.toBe(project); expect(workspace!.startsWith(worktrees + path.sep)).toBe(true);expect(started.bootstrap.trace).toEqual(expect.arrayContaining([expect.stringContaining("[Workspace] task-owned worktree")]));expect(started.bootstrap.policy.workspace).toContain(workspace!);+ expect(start.toStructuredContent?.(started)).toMatchObject({+ workspace: { path: workspace, projectPath: project, isolation: "isolated-worktree", baseCommit: git("rev-parse", "HEAD") },+ });const context = { actor, workflowActor: actor, workflowId: started.workflow.id, scope: "exec" as const };await expect(write.run({ path: path.join(project, "src/value.ts"), content: "export const value = 2;\n" }, context)).rejects.toThrow(/source-isolated/i);@@ -78,6 +82,40 @@ describe("workflow_start source isolation", () => {expect(git("status", "--porcelain")).toBe("");});+ it("allows hostname observation with a negative source constraint in the canonical project", async () => {+ const { LEARNING_TOOLS } = await import("./tools-learning");+ const { MUTATE_TOOLS } = await import("./tools-mutate");+ const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;+ const exec = MUTATE_TOOLS.find((tool) => tool.name === "exec_run")!;+ const actor = "mcp:hostname-observation";+ const before = git("worktree", "list", "--porcelain");+ const started = await start.run({+ intent: "Check hostname.", constraints: "Read only; do not modify files.", project,+ }, { actor, scope: "exec" }) as { workflow: { id: string; orchestration: { isolation: string; workspacePath: string } } };+ expect(started.workflow.orchestration).toMatchObject({ isolation: "optional-worktree", workspacePath: project });+ expect(start.toStructuredContent?.(started)).toMatchObject({+ workspace: { path: project, projectPath: project, isolation: "optional-worktree" },+ });+ const result = await exec.run({ command: "hostname", cwd: project }, {+ actor, workflowActor: actor, workflowId: started.workflow.id, scope: "exec",+ }) as { code: number; stdout: string };+ expect(result.code).toBe(0);+ expect(result.stdout.trim()).toBe(os.hostname());+ expect(git("worktree", "list", "--porcelain")).toBe(before);+ expect(git("status", "--porcelain")).toBe("");+ });++ it("isolates a declared source path even without a recognized mutation verb", async () => {+ const { LEARNING_TOOLS } = await import("./tools-learning");+ const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;+ const started = await start.run({+ intent: "Sesuaikan nilai sumber.", project, affected_paths: ["src/declared.ts"],+ }, { actor: "mcp:declared-path", scope: "exec" }) as { workflow: { orchestration: { isolation: string; workspacePath: string } } };+ expect(started.workflow.orchestration.isolation).toBe("isolated-worktree");+ expect(started.workflow.orchestration.workspacePath).not.toBe(project);+ expect(git("status", "--porcelain")).toBe("");+ });+it("auto-removes only an unused clean task worktree when the workflow is cancelled", async () => {const { LEARNING_TOOLS } = await import("./tools-learning");const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;diff --git a/lib/orchestration/classifier.test.ts b/lib/orchestration/classifier.test.tsindex e52260bc..12b3c31b 100644--- a/lib/orchestration/classifier.test.ts+++ b/lib/orchestration/classifier.test.ts@@ -23,6 +23,52 @@ describe("RASMIC risk and contention classifier", () => {expect(result.isolation).toBe("direct");});+ it.each([+ ["Check hostname.", "Read only; do not modify files."],+ ["Periksa hostname.", "Hanya observasi; jangan edit file."],+ ["Periksa hostname.", "Hanya observasi; jangan ubah file."],+ ["Check hostname; do not change files.", ""],+ ["Check hostname.", "Do not write, edit, or modify files."],+ ["Check hostname.", "Do not edit, modify, or update files."],+ ["Check hostname.", "Don’t change files."],+ ["Check hostname.", "Never edit or modify files."],+ ["Periksa hostname.", "Jangan pernah edit atau modify file."],+ ])("keeps a directly negated mutation observational: %s %s", (intent, constraints) => {+ expect(sourceChangeLikely(intent, constraints)).toBe(false);+ expect(classifyTask({ intent, constraints, scope: "exec" }).isolation).toBe("optional-worktree");+ });++ it.each([+ ["Fix the source bug.", "Do not modify unrelated files."],+ ["Do not edit docs; update the source file.", ""],+ ["Do not edit docs but modify code.", ""],+ ["Do not edit docs, then write tests.", ""],+ ["Do not edit docs and update code.", ""],+ ["Not only edit docs but fix code.", ""],+ ["Do not forget to fix code.", ""],+ ["Read only; implement a feature.", ""],+ ["No source changes; write docs.", ""],+ ["Do not edit, implement the feature from scratch.", ""],+ ["Do not edit, and implement the feature from scratch.", ""],+ ["Do not edit, or implement the feature instead.", ""],+ ["Do not edit, modify, write files.", ""],+ ])("preserves positive mutation evidence: %s %s", (intent, constraints) => {+ expect(sourceChangeLikely(intent, constraints)).toBe(true);+ expect(classifyTask({ intent, constraints, scope: "exec" }).isolation).toBe("isolated-worktree");+ });++ it("isolates explicitly declared paths without requiring a recognized mutation verb or collision", () => {+ const input = { intent: "Sesuaikan nilai sumber.", constraints: "Do not edit unrelated files.", scope: "exec" as const };+ expect(sourceChangeLikely(input.intent, input.constraints, ["src/value.ts"])).toBe(true);+ expect(classifyTask({ ...input, affectedPaths: ["src/value.ts"] }).isolation).toBe("isolated-worktree");+ expect(classifyTask({ ...input, collisionPaths: ["src/value.ts"] }).isolation).toBe("isolated-worktree");+ });++ it("retains the separate high-risk policy even for a negated operation", () => {+ expect(classifyTask({ intent: "Check hostname.", constraints: "Do not deploy.", scope: "exec" }))+ .toMatchObject({ risk: "high", isolation: "isolated-worktree" });+ });+it("requires isolated work for high-risk auth/schema/infra work", () => {const result = classifyTask({intent: "refactor authentication and database schema before production deployment",diff --git a/lib/orchestration/classifier.ts b/lib/orchestration/classifier.tsindex 31c0bbd6..98794d9d 100644--- a/lib/orchestration/classifier.ts+++ b/lib/orchestration/classifier.ts@@ -39,13 +39,21 @@ const MEMORY_HIGH = [const SOURCE_CHANGE_VERB = /\b(implement|fix|edit|modify|refactor|patch|add|remove|rename|write|rewrite)\b/i;const SOURCE_CHANGE_OBJECT = /\b(code|source|files?|repo(?:sitory)?|docs?|documentation|ui|component|tests?|scripts?|config(?:uration)?|package|lockfile|feature)\b/i;const SOURCE_CHANGE_WEAK_VERB = /\b(update|change)\b/i;+const MUTATION_VERBS = "(?:" + SOURCE_CHANGE_VERB.source + "|" + SOURCE_CHANGE_WEAK_VERB.source + ")";+const CONJUNCTION = "(?:and|or|nor|dan|atau)";+const NEGATED_SOURCE_CHANGE = new RegExp(+ "\\b(?:do\\s+not|don['’]t|never|jangan(?:\\s+pernah)?)\\s+" + MUTATION_VERBS+ + "(?:\\s+" + CONJUNCTION + "\\s+" + MUTATION_VERBS+ + "|(?:\\s*,\\s*" + MUTATION_VERBS + ")+\\s*,?\\s*" + CONJUNCTION + "\\s+" + MUTATION_VERBS + ")*",+ "gi",+);/** Safety-biased signal for repository/source mutation. It is intentionally* separate from risk: a typo remains low risk but still belongs in a task-owned* worktree so canonical main never becomes shared scratch space. */export function sourceChangeLikely(intent: string, constraints = "", affectedPaths: string[] = []): boolean {if (affectedPaths.length > 0) return true;- const text = `${intent}\n${constraints}`;+ const text = `${intent}\n${constraints}`.replace(NEGATED_SOURCE_CHANGE, "");if (SOURCE_CHANGE_VERB.test(text)) return true;return SOURCE_CHANGE_WEAK_VERB.test(text) && SOURCE_CHANGE_OBJECT.test(text);}@@ -92,6 +100,7 @@ export function classifyTask(input: {constraints?: string;scope?: "read" | "write" | "exec";changedPaths?: string[];+ affectedPaths?: string[];activeProjectWorkflows?: number;collisionPaths?: string[];collisionResources?: string[];@@ -132,7 +141,9 @@ export function classifyTask(input: {if (MEMORY_HIGH.some((rule) => rule.test(text)) || complexity === "heavy") memoryRelevance = "high";else if (complexity === "medium") memoryRelevance = "medium";- const sourceChange = input.scope !== "read" && sourceChangeLikely(input.intent, input.constraints, input.collisionPaths?.length ? input.collisionPaths : []);+ const sourceChange = input.scope !== "read" && sourceChangeLikely(+ input.intent, input.constraints, [...(input.affectedPaths ?? []), ...collisionPaths],+ );if (sourceChange) reasons.push("repository/source mutation should use a task-owned worktree");const isolation: TaskClassification["isolation"] = risk === "high" || sourceChange? "isolated-worktree"diff --git a/scripts/e2e/mcp-connection.mjs b/scripts/e2e/mcp-connection.mjsnew file mode 100644index 00000000..de3f4820--- /dev/null+++ b/scripts/e2e/mcp-connection.mjs@@ -0,0 +1,91 @@+import { expect } from "@playwright/test";+import AxeBuilder from "@axe-core/playwright";++const STAGES = [+ ["server", "Server", "Passed"],+ ["https", "HTTPS to configured origin", "Unknown"],+ ["mcp", "MCP endpoint", "Passed"],+ ["challenge", "OAuth challenge", "Passed"],+ ["resource", "Protected resource", "Passed"],+ ["oauth", "OAuth metadata", "Passed"],+ ["account", "Selected AI app account", "Unknown"],+ ["client-tools", "AI app tool cache", "Unknown"],+];++async function assertDiscovery(surface) {+ await expect(surface.getByText("Server discovery checks passed", { exact: true })).toBeVisible();+ const checks = surface.getByRole("list", { name: "Connection checks", exact: true });+ await expect(checks.getByRole("listitem")).toHaveCount(STAGES.length);+ for (const [id, label, state] of STAGES) {+ const row = checks.locator(`[data-probe-check="${id}"]`);+ await expect(row.getByText(label, { exact: true })).toBeVisible();+ await expect(row.getByText(state, { exact: true })).toBeVisible();+ }+}++async function definitions(surface) {+ return surface.locator("dl").evaluateAll(lists => Object.fromEntries(lists.flatMap(list =>+ Array.from(list.querySelectorAll("dt"), term => [term.textContent.trim(), term.nextElementSibling?.textContent.trim()]),+ )));+}++export async function mcpConnectionJourney(page, fixture, capture) {+ const endpoint = fixture.base + "/mcp";+ const response = await page.request.get(fixture.base + "/api/mcp/tokens");+ expect(response.status()).toBe(200);+ const { targetIdentity } = await response.json();+ expect(targetIdentity.hostname).toEqual(expect.any(String));+ expect(targetIdentity.hostname.length).toBeGreaterThan(0);+ expect(targetIdentity.environment).toBeNull();++ await page.getByRole("navigation", { name: "MCP navigation" })+ .getByRole("button", { name: /^Connection details/ }).click();+ const surface = page.locator('[data-slot="mcp-page"]');+ await assertDiscovery(surface);+ await expect(surface.getByRole("heading", { name: "Current server", exact: true })).toBeVisible();+ await expect.poll(() => definitions(surface)).toMatchObject({+ "Observed origin": fixture.base,+ "Configured MCP endpoint": endpoint,+ Hostname: targetIdentity.hostname,+ "Service user": targetIdentity.serviceUser ?? "Unavailable",+ "Runtime instance": targetIdentity.runtimeInstanceId ?? "Unavailable",+ Environment: "Not configured",+ });+ expect((await definitions(surface)).Checked).toBeTruthy();+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);+ const accessibility = await new AxeBuilder({ page }).include('[data-slot="mcp-page"]')+ .withTags(["wcag2a", "wcag2aa", "wcag21aa"]).analyze();+ expect(accessibility.violations.map(v => ({ id: v.id, targets: v.nodes.map(n => n.target) }))).toEqual([]);+ await capture(page, `mcp-connection-${page.viewportSize().width}`);++ let release = () => {};+ const held = new Promise(resolve => { release = resolve; });+ const failDiscovery = async route => {+ if (route.request().method() !== "GET") return route.continue();+ await held;+ await route.fulfill({ status: 503, contentType: "application/json", body: '{}' });+ };+ await page.route(endpoint, failDiscovery);+ try {+ const request = page.waitForRequest(req => req.url() === endpoint && req.method() === "GET");+ await surface.getByRole("button", { name: "Check connection", exact: true }).click();+ await request;+ await expect(surface.getByText("Checking this server…", { exact: true })).toBeVisible();+ await expect(surface.getByRole("button", { name: "Checking…", exact: true })).toBeDisabled();+ release();+ await expect(surface.getByText("Some server checks need attention", { exact: true })).toBeVisible();+ await expect(surface.locator('[data-probe-check="mcp"]').getByText("Failed", { exact: true })).toBeVisible();+ await expect(surface.getByText("Server discovery checks passed", { exact: true })).toHaveCount(0);+ for (const id of ["account", "client-tools"]) {+ await expect(surface.locator(`[data-probe-check="${id}"]`).getByText("Unknown", { exact: true })).toBeVisible();+ }+ await capture(page, `mcp-connection-failure-${page.viewportSize().width}`);+ } finally {+ release();+ await page.unroute(endpoint, failDiscovery);+ }+ await surface.getByRole("button", { name: "Check connection", exact: true }).click();+ await assertDiscovery(surface);+ await page.getByRole("navigation", { name: "Breadcrumb" }).getByRole("button", { name: "MCP", exact: true }).click();+ console.log(`PASS MCP connection stages, observed target and retry ${page.viewportSize().width}x${page.viewportSize().height}`);+}diff --git a/scripts/e2e/mcp-settings.mjs b/scripts/e2e/mcp-settings.mjsindex f7bdde34..fde92753 100644--- a/scripts/e2e/mcp-settings.mjs+++ b/scripts/e2e/mcp-settings.mjs@@ -1,4 +1,5 @@import { mcpSessionsJourney } from "./mcp-sessions.mjs";+import { mcpConnectionJourney } from "./mcp-connection.mjs";// Real production Settings routes, with synthetic owner state and bounded fault injection.import path from "node:path";import { chmod } from "node:fs/promises";@@ -71,6 +72,7 @@ export async function mcpOwnerJourneys(page, fixture) {await openMcp(page);const nav = page.getByRole("navigation", { name: "MCP navigation" });await expect(nav.getByRole("button", { name: /^Connected apps/ })).toBeVisible();+ await mcpConnectionJourney(page, fixture, capture);await capture(page, `mcp-overview-${viewport.width}`);await nav.getByRole("button", { name: /^Connect an app/ }).click();await expect(page.getByRole("heading", { name: "Which app do you want to connect?" })).toBeVisible();diff --git a/scripts/gateway-lifecycle-fixture.ts b/scripts/gateway-lifecycle-fixture.tsindex e2a6e826..adaaf2d5 100644--- a/scripts/gateway-lifecycle-fixture.ts+++ b/scripts/gateway-lifecycle-fixture.ts@@ -28,7 +28,7 @@ process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000);`, { mode: 0o700 });const procTcp = path.join(dir, "proc-tcp"), procTcp6 = path.join(dir, "proc-tcp6");fs.writeFileSync(procTcp, " sl local_address rem_address st\n"); fs.writeFileSync(procTcp6, " sl local_address rem_address st\n");- const env = { ...process.env, HOME: dir, PATH: `${bin}:${process.env.PATH}`, MSO_GATEWAY_ROOT: ROOT, MSO_GATEWAY_ENV: envFile,+ const env = { ...process.env, NODE_ENV: "test" as const, HOME: dir, PATH: `${bin}:${process.env.PATH}`, MSO_GATEWAY_ROOT: ROOT, MSO_GATEWAY_ENV: envFile,MSO_GATEWAY_STATE_DIR: state, MSO_GATEWAY_CURL: curl, MSO_GATEWAY_CLOUDFLARED: cloudflared,MSO_GATEWAY_LOCAL_URL: "http://127.0.0.1:4005", MSO_GATEWAY_SKIP_PUBLIC_PROBE: "1",MSO_GATEWAY_PROC_NET_TCP: procTcp, MSO_GATEWAY_PROC_NET_TCP6: procTcp6 };diff --git a/scripts/mso-gateway-test-fixture.ts b/scripts/mso-gateway-test-fixture.tsindex 649544ce..3ba5e9bc 100644--- a/scripts/mso-gateway-test-fixture.ts+++ b/scripts/mso-gateway-test-fixture.ts@@ -75,6 +75,7 @@ setInterval(() => {}, 1000);fs.writeFileSync(procTcp6, " sl local_address rem_address st\n");const baseEnv: NodeJS.ProcessEnv = {...process.env,+ NODE_ENV: "test",HOME: dir,MSO_GATEWAY_ROOT: ROOT,MSO_GATEWAY_ENV: envFile,