import { assertEquals, assertStrictEquals } from "@std/assert"; import { expect } from "@std/expect"; import { spy } from "@std/testing/mock"; import { Identity } from "@commonfabric/identity"; import { resolveScopeKey } from "@commonfabric/memory/v2"; import { read } from "@commonfabric/memory/v2/engine"; import { SERVER_EXECUTION_DEFAULT_ENABLED } from "@commonfabric/memory/v2/server-execution-default"; import type { Runtime, RuntimeOptions } from "@commonfabric/runner"; import { EmulatedStorageManager, newLoopbackServer, StorageManager, } from "@commonfabric/runner/storage/cache.deno"; import { cfcPosture, publishCfcPosture } from "@/lib/cfc-posture.ts"; import { experimentalPosture, publishExperimentalPosture, } from "@/lib/experimental-posture.ts"; import { attachRuntimeOtelBridge, createToolshedRuntime, detachRuntimeOtelBridgeIfAttached, toolshedRuntimeOptions, } from "@/runtime-options.ts"; Deno.test("toolshedRuntimeOptions splits MEMORY_URL/API_URL and honors the env reader", () => { // Pins toolshed's runtime wiring decisions (CT-1814): the runtime's storage // base is MEMORY_URL while patterns fetch against the public API_URL; the // storage manager passes through untouched; EXPERIMENTAL_* flags come from // the injected env reader via the canonical mapping; and the shared // first-party posture (the CFC pin) rides along from the preset. const storageManager = { sentinel: true, } as unknown as RuntimeOptions["storageManager"]; const options = toolshedRuntimeOptions( { MEMORY_URL: "http://memory.test:8000/", API_URL: "http://api.test:9000/", API_INTERNAL_URL: undefined, }, storageManager, (name) => name === "EXPERIMENTAL_MODERN_CELL_REP" ? "true" : undefined, ); assertEquals(options.apiUrl.href, "http://memory.test:8000/"); assertEquals( options.patternEnvironment?.apiUrl.href, "http://api.test:9000/", ); assertStrictEquals(options.storageManager, storageManager); assertEquals(options.experimental?.modernCellRep, true); // Unset flags stay unset (tri-state fidelity), not coerced. assertEquals(options.experimental?.lazyMaterialization, undefined); // EXCEPT the posture: the deployed-topology preset resolves an unset // serverExecution to the first-party default, so this server-side // process always runs a declared arm. assertEquals( options.experimental?.serverExecution, SERVER_EXECUTION_DEFAULT_ENABLED, ); assertEquals(options.cfcEnforcementMode, "enforce-strict"); }); Deno.test("toolshedRuntimeOptions sends self-addressed requests to API_INTERNAL_URL and changes no URL", async () => { // A co-hosted toolshed's own requests take the internal origin (OW55) by // way of the runtime's fetch, and only by way of it: the storage base // stays MEMORY_URL and the pattern base stays the public API_URL, so what // the runtime records and compares is unchanged. Unset, the runtime keeps // the platform fetch, so a deployment without the setting is unchanged. const storageManager = { sentinel: true, } as unknown as RuntimeOptions["storageManager"]; const base = { MEMORY_URL: "http://memory.test:8000/", API_URL: "https://api.test/", }; const internal = toolshedRuntimeOptions( { ...base, API_INTERNAL_URL: "http://127.0.0.1:8007" }, storageManager, () => undefined, ); assertEquals(internal.apiUrl.href, "http://memory.test:8000/"); assertEquals(internal.patternEnvironment?.apiUrl.href, "https://api.test/"); const sent: string[] = []; const platform = globalThis.fetch; globalThis.fetch = ((input: RequestInfo | URL) => { sent.push(new Request(input).url); return Promise.resolve(new Response("ok")); }) as typeof fetch; try { await internal.fetch!("https://api.test/api/patterns/x.tsx"); await internal.fetch!("https://elsewhere.test/y"); } finally { globalThis.fetch = platform; } assertEquals(sent, [ "http://127.0.0.1:8007/api/patterns/x.tsx", "https://elsewhere.test/y", ]); const unset = toolshedRuntimeOptions( { ...base, API_INTERNAL_URL: undefined }, storageManager, () => undefined, ); assertEquals(unset.fetch, undefined); assertEquals(unset.patternEnvironment?.apiUrl.href, "https://api.test/"); }); Deno.test("createToolshedRuntime attaches the OTel bridge only when enabled", async () => { // The runtime→OTel bridge attach rides Runtime construction (CT plan: the // bridge is a second consumer of the RuntimeTelemetry bus). Off by default; // on OTEL_ENABLED it attaches and flips the preflight-telemetry gate. Without // a registered OTel provider the API hands the bridge no-op instruments, so // the enabled path is safe to exercise in a test. const signer = await Identity.fromPassphrase("runtime-options-otel-test"); const config = { MEMORY_URL: "http://memory.test:8000/", API_URL: "http://api.test:9000/", API_INTERNAL_URL: undefined, OTEL_SERVICE_NAME: "toolshed-test", ENV: "test", }; for (const enabled of [false, true]) { const storageManager = StorageManager.emulate({ as: signer }); const runtime = createToolshedRuntime( { ...config, OTEL_ENABLED: enabled }, storageManager, () => undefined, ); // The construction path fire-and-forgets the attach; assert the attach // behavior directly (same runtime, same config). assertEquals( await attachRuntimeOtelBridge(runtime, { ...config, OTEL_ENABLED: enabled, }), enabled, ); await runtime.dispose(); await storageManager.close(); } // A successful attach registers the shutdown detach; detaching is // idempotent and reports whether a bridge was live. assertEquals(detachRuntimeOtelBridgeIfAttached(), true); assertEquals(detachRuntimeOtelBridgeIfAttached(), false); // Attach failures are logged, never fatal: a runtime whose preflight gate // throws must resolve false, not reject. const throwingRuntime = { telemetry: new EventTarget(), scheduler: { setEventPreflightTelemetryEnabled() { throw new Error("gate unavailable"); }, }, } as unknown as Parameters[0]; assertEquals( await attachRuntimeOtelBridge(throwingRuntime, { OTEL_ENABLED: true, OTEL_SERVICE_NAME: "toolshed-test", ENV: "test", }), false, ); }); Deno.test("createToolshedRuntime publishes the posture it resolved", async () => { // What `/api/meta` reports, and therefore what a client not built alongside // this server adopts (docs/development/EXPERIMENTAL_OPTIONS.md). The // published posture includes constructor defaults and the deployment's // client policies, all resolved from one environment reading. const signer = await Identity.fromPassphrase("runtime-options-posture-test"); const storageManager = StorageManager.emulate({ as: signer }); publishExperimentalPosture(null); let runtime: Runtime | undefined; try { runtime = createToolshedRuntime( { MEMORY_URL: "http://memory.test:8000/", API_URL: "http://api.test:9000/", API_INTERNAL_URL: undefined, OTEL_ENABLED: false, OTEL_SERVICE_NAME: "toolshed-test", ENV: "test", }, storageManager, (name) => name === "EXPERIMENTAL_MODERN_CELL_REP" ? "true" : undefined, ); const posture = experimentalPosture(); // The CFC posture publishes alongside, from the same constructed Runtime // (lib/cfc-posture.ts): the preset core pin plus constructor defaults. const cfc = cfcPosture(); assertEquals(cfc?.enforcementMode.rung, "enforce-strict"); assertEquals(cfc?.flowLabels.rung, "persist"); assertEquals(cfc?.flowLabels.diagnosticOnly, false); assertEquals(cfc?.policyDigest, null); // Every known sink is named, none of them ceilinged: a server that has // configured nothing publishes every sink as ungated rather than an empty // list a reader could take for full coverage. assertEquals(cfc?.sinks.length, 12); assertEquals(cfc?.sinks.every((sink) => "ungated" in sink), true); assertEquals(posture?.modernCellRep, true); // Resolved, not passed: the env reader said nothing about these, and a // client adopting the posture needs the values in effect rather than the // subset someone happened to set. assertEquals(posture?.commitPreconditions, true); assertEquals( posture?.serverExecution, SERVER_EXECUTION_DEFAULT_ENABLED, ); } finally { await runtime?.dispose(); await storageManager.close(); publishExperimentalPosture(null); publishCfcPosture(null); } }); Deno.test("createToolshedRuntime declares dedicated connections for its own storage manager", async () => { // Under routed Mode A MEMORY_URL routes by the space in the address, so the // toolshed's own storage manager dials dedicated connections whatever the // deployment's flag says (runtime-options.ts), while the posture it // publishes still carries the flag for the clients that open Memory on the // router. The manager keeps the choice private, so observe what the // construction path declares on it. const signer = await Identity.fromPassphrase( "runtime-options-own-memory-test", ); const storageManager = StorageManager.emulate({ as: signer }); using declared = spy(storageManager, "setSharedMemoryConnection"); publishExperimentalPosture(null); let runtime: Runtime | undefined; try { runtime = createToolshedRuntime( { MEMORY_URL: "http://memory.test:8000/", API_URL: "http://api.test:9000/", API_INTERNAL_URL: undefined, OTEL_ENABLED: false, OTEL_SERVICE_NAME: "toolshed-test", ENV: "test", }, storageManager, (name) => name === "EXPERIMENTAL_SHARED_MEMORY_CONNECTION" ? "true" : undefined, ); // The Runtime resolved the deployment's flag and `/api/meta` publishes it // unchanged. assertEquals(runtime.experimental.sharedMemoryConnection, true); assertEquals(experimentalPosture()?.sharedMemoryConnection, true); // The Runtime declared that flag on the manager; the toolshed then // declared dedicated connections for its own sessions, before any opened. assertEquals( declared.calls.map((call) => call.args[0]), [true, false], ); } finally { await runtime?.dispose(); await storageManager.close(); publishExperimentalPosture(null); publishCfcPosture(null); } }); Deno.test("createToolshedRuntime synchronizes its session state while publishing local client storage", async () => { const signer = await Identity.fromPassphrase( "toolshed persistent session storage", ); const server = newLoopbackServer({ subscriptionRefreshDelayMs: 0 }); const config = { MEMORY_URL: "http://memory.test:8000/", API_URL: "http://api.test:9000/", API_INTERNAL_URL: undefined, OTEL_ENABLED: false, OTEL_SERVICE_NAME: "toolshed-test", ENV: "test", } as const; const env = (name: string) => name === "EXPERIMENTAL_LOCAL_SESSION_DOCUMENTS" ? "true" : name === "EXPERIMENTAL_SERVER_EXECUTION" ? "false" : undefined; let storage = EmulatedStorageManager.connectTo(server, { as: signer, id: "webhook-session", }); let runtime: Runtime | undefined; try { runtime = createToolshedRuntime(config, storage, env); expect(experimentalPosture()?.localSessionDocuments).toBe(true); expect(runtime.experimental.localSessionDocuments).toBe(false); const cell = runtime.getCell( signer.did(), "webhook-state", undefined, undefined, "session", ); const id = cell.getAsNormalizedFullLink().id; const scopeKey = resolveScopeKey("session", runtime.scopeKeyIdentity); const tx = runtime.edit(); cell.withTx(tx).set(42); expect((await tx.commit().settled).error).toBeUndefined(); await storage.synced(); const engine = await server.engineForSpace(signer.did()); expect(read(engine, { id, scopeKey })?.value).toBe(42); await runtime.dispose(); runtime = undefined; await storage.close(); storage = EmulatedStorageManager.connectTo(server, { as: signer, id: "webhook-session", }); runtime = createToolshedRuntime(config, storage, env); expect(read(engine, { id, scopeKey })?.value).toBe(42); } finally { await runtime?.dispose(); await storage.close(); await server.close(); publishExperimentalPosture(null); publishCfcPosture(null); } });