diff --git a/.brain/data/git-snapshot.json b/.brain/data/git-snapshot.json index 781ddebf..cc753148 100644 --- a/.brain/data/git-snapshot.json +++ b/.brain/data/git-snapshot.json @@ -171,12 +171,12 @@ "apps/cli/src/cli.ts": "a77711f6928a77fb0fe4fb99f4fcdbf8f0218960ea4b8fde404d910c70a61e7a", "apps/cli/src/command.ts": "0713234a5d3fe60d0fdcd8fc6e1231105d791dd88bee1e8f860f59b5588cba46", "apps/cli/src/surfaces.ts": "1099760ff5cec2bd7f1462f175a2b491c573642729ecff5ce3232a7f9c3b7a8a", - "apps/infra/alchemy.run.ts": "030a27ceda1b0bd5854a430e74f4e6fb29be294bbe585f7d1528850cb4865813", + "apps/infra/alchemy.run.ts": "ce440301dcb5881289bf8870297b4c8a6e5cf9343d6335ddfdf202fd7318d221", "apps/site/src/capabilities/search.ts": "031dc99d762c4710c8fa1aba58d140f4943552cf35efa553f7b8d1a90e7eb2e0", "apps/site/src/events.ts": "320aaf33bcd4f1801f5f2ecb5b17cf417e78cd0917e19a57c5daae045f6da458", "apps/site/src/interest/interest-durable-object.ts": "110d38d7a92d5f4cc647dd6c3e12c2744566e0a9ab87fbd748a56517bf4ab390", "apps/site/src/interest/join-contact-cell.ts": "06e4de93ca209b7ecda32eb4ff491925e18d9ffb77f5b618418d97dd258104e8", - "apps/site/src/worker.ts": "3aa6e8f5ee2bb4cbc6cf0e8a85823f979a0fcc9903ef4fc8f43b45dc7b94dd2a", + "apps/site/src/worker.ts": "3346d78a41d369a77e98cb173d1f701ab7bb05b728acda61ef03d09e1840702e", "apps/web/src/client/docs/command.ts": "858fb626d70610cf8ccb47a28128734aebe2845376941a78a94dcc6349c19275", "apps/web/src/client/docs/message.ts": "d345b21c25b00dcccd44f172a9d7487f265b932c285729da37eb6686ef20eeb0", "apps/web/src/client/docs/queries.ts": "bf531ec4f3abaf2b590c63772f8331e2fd9ae089ba02f0d74c7023f770b28347", @@ -601,12 +601,12 @@ "[\"rat-stack\",\"show\",\"HEAD:apps/cli/src/cli.ts\"]": "#!/usr/bin/env node\n\nimport { NodeRuntime, NodeServices } from \"@effect/platform-node\";\nimport { Approval } from \"@rat-stack/capability\";\nimport { FileInspector } from \"@rat-stack/core\";\nimport { FlagActor } from \"@rat-stack/core/flag-control\";\nimport { eventFlags, Flags } from \"@rat-stack/core/flags\";\nimport { Console, Effect, Layer } from \"effect\";\n\nimport { localCafeDirectoryLayer } from \"./cafe.js\";\nimport { runCommand } from \"./command.js\";\nimport { remoteJoinInterestLayer } from \"./join-interest.js\";\nimport { localLearnLayer } from \"./learn-layer.js\";\nimport { localPromptLibraryLayer } from \"./prompts.js\";\n\nconst program = runCommand(process.argv.slice(2)).pipe(\n Effect.provideService(FlagActor, \"local-cli\"),\n // oxlint-disable-next-line promise/prefer-await-to-callbacks -- Oxlint mistakes this Effect handler for an async Promise callback.\n Effect.catchTag(\"FileStatsError\", (error) =>\n Console.error(error.message).pipe(Effect.andThen(Effect.fail(error)))\n ),\n Effect.provide(\n Layer.mergeAll(\n Layer.provideMerge(FileInspector.layer, NodeServices.layer),\n remoteJoinInterestLayer,\n localPromptLibraryLayer.pipe(Layer.provide(NodeServices.layer)),\n localCafeDirectoryLayer.pipe(Layer.provide(NodeServices.layer)),\n localLearnLayer,\n Flags.defaults(eventFlags),\n Approval.denyAll\n )\n )\n);\n\nNodeRuntime.runMain(program);\n", "[\"rat-stack\",\"show\",\"HEAD:apps/cli/src/command.ts\"]": "import { toCommand } from \"@rat-stack/capability\";\nimport { formatFileStats, inspectFile } from \"@rat-stack/core\";\nimport { flipFeatureFlag } from \"@rat-stack/core/flag-write-capabilities\";\nimport { Console, Effect, Layer } from \"effect\";\nimport { Command, Flag } from \"effect/cli\";\n\nimport { intakeCommand } from \"./intake.js\";\nimport {\n commandCapabilities,\n SERVE_HOST,\n DEVTOOLS_MCP_PATH,\n codeMode,\n devtoolsWebServer,\n http,\n mcpServer,\n webServer,\n} from \"./surfaces.js\";\nimport { VERSION } from \"./version.js\";\n\nexport { VERSION } from \"./version.js\";\n\nconst capabilityCommands = commandCapabilities.map((capability) => {\n const command =\n capability === inspectFile\n ? toCommand(capability, {\n positional: [\"path\"],\n render: formatFileStats,\n }).pipe(Command.withAlias(\"stats\"))\n : toCommand(\n capability,\n capability === flipFeatureFlag\n ? { promptForApproval: true }\n : undefined\n );\n\n return command;\n});\n\nconst openapiCommand = Command.make(\"openapi\", {}, () =>\n Console.log(JSON.stringify(http.openApi(), null, 2))\n).pipe(Command.withDescription(\"Print the OpenAPI document for the REST API\"));\n\nconst devtoolsFlag = Flag.Boolean(\"devtools\").pipe(\n Flag.withDefault(false),\n Flag.withDescription(\n \"Record every capability call and add the rat_* devtools tools\"\n )\n);\n\nconst serveCommand = Command.make(\n \"serve\",\n {\n devtools: devtoolsFlag,\n port: Flag.Int(\"port\").pipe(\n Flag.withDefault(3000),\n Flag.withDescription(\"TCP port to listen on\")\n ),\n },\n ({ devtools, port }) =>\n devtools\n ? Console.error(\n `🐀 devtools MCP: http://${SERVE_HOST}:${port}${DEVTOOLS_MCP_PATH}`\n ).pipe(\n Effect.andThen(Layer.launch(devtoolsWebServer(port))),\n Effect.orDie\n )\n : Layer.launch(webServer(port))\n).pipe(\n Command.withDescription(\n \"Serve the REST API, /openapi.json, and /docs until interrupted; --devtools adds MCP at /__rat/mcp on 127.0.0.1\"\n )\n);\n\nconst mcpCommand = Command.make(\n \"mcp\",\n {\n codeMode: Flag.Boolean(\"code-mode\").pipe(\n Flag.withDefault(false),\n Flag.withDescription(\n \"Expose search and execute instead of one tool per capability\"\n )\n ),\n devtools: devtoolsFlag,\n },\n ({ codeMode: enabled, devtools }) => {\n if (devtools) {\n return enabled\n ? Layer.launch(mcpServer.devtoolsCodeMode).pipe(Effect.orDie)\n : Layer.launch(mcpServer.devtools).pipe(Effect.orDie);\n }\n\n return enabled\n ? Layer.launch(mcpServer.codeMode).pipe(Effect.orDie)\n : Layer.launch(mcpServer.tools).pipe(Effect.orDie);\n }\n).pipe(\n Command.withDescription(\"Serve the capabilities as an MCP server over stdio\")\n);\n\nconst catalogCommand = Command.make(\n \"catalog\",\n {\n types: Flag.Boolean(\"types\").pipe(\n Flag.withDefault(false),\n Flag.withDescription(\n \"Print the TypeScript declarations a code-mode program sees\"\n )\n ),\n },\n ({ types }) =>\n Console.log(\n types ? codeMode.declarations : JSON.stringify(codeMode.catalog, null, 2)\n )\n).pipe(\n Command.withDescription(\n \"Print the capability catalog as JSON Schema, or as TypeScript with --types\"\n )\n);\n\nexport const rootCommand = Command.make(\"rat-stack\").pipe(\n Command.withDescription(\"Agent-first file inspection: CLI, REST, and MCP\"),\n Command.withSubcommands([\n ...capabilityCommands,\n catalogCommand,\n intakeCommand,\n openapiCommand,\n serveCommand,\n mcpCommand,\n ])\n);\n\nexport const runCommand = Command.runWith(rootCommand, { version: VERSION });\n", "[\"rat-stack\",\"show\",\"HEAD:apps/cli/src/surfaces.ts\"]": "// @effect-diagnostics-next-line nodeBuiltinImport:off -- The Node HTTP server is the one place where nothing in Effect wraps the built-in: `NodeHttpServer.layer` takes a `node:http` server factory.\nimport { createServer } from \"node:http\";\n\nimport { NodeHttpServer } from \"@effect/platform-node\";\nimport type { AnyCapability } from \"@rat-stack/capability\";\nimport {\n layerSubprocess,\n toCodeMode,\n toHttpApi,\n toToolkit,\n} from \"@rat-stack/capability\";\nimport { capabilities as coreCapabilities } from \"@rat-stack/core\";\nimport { flagWriteCapabilities } from \"@rat-stack/core/flag-write-capabilities\";\nimport { devtools, devtoolsLayer } from \"@rat-stack/devtools\";\nimport { learnCapabilities } from \"@rat-stack/learn\";\nimport { localLearnCapabilities } from \"@rat-stack/learn/local\";\nimport { Effect, Layer, Logger } from \"effect\";\nimport { McpServer } from \"effect/ai\";\nimport { HttpRouter } from \"effect/http\";\nimport { HttpApiBuilder, HttpApiScalar } from \"effect/http-api\";\n\nimport { mcpProtocols } from \"./mcp-protocols.js\";\nimport { mcpSkills } from \"./mcp-skills.js\";\nimport { VERSION } from \"./version.js\";\n\nexport const capabilities = [\n ...coreCapabilities,\n ...learnCapabilities,\n] as const;\n\nexport const cliCapabilities = [\n ...coreCapabilities,\n ...localLearnCapabilities,\n] as const;\n\nexport const commandCapabilities = [\n ...cliCapabilities,\n ...flagWriteCapabilities,\n] as const;\n\nexport const http = toHttpApi(\"RatStack\", capabilities);\n\nexport const tools = toToolkit(cliCapabilities);\n\nexport const codeMode = toCodeMode(cliCapabilities);\n\nexport const routes = Layer.merge(\n HttpApiBuilder.layer(http.api, { openapiPath: \"/openapi.json\" }).pipe(\n Layer.provide(http.layer)\n ),\n HttpApiScalar.layer(http.api, { path: \"/docs\" })\n);\n\nexport const SERVE_HOST = \"127.0.0.1\";\n\nexport const serverLayer = (port: number) =>\n NodeHttpServer.layer(() => createServer(), { host: SERVE_HOST, port });\n\nexport const webServer = (port: number) =>\n HttpRouter.serve(routes).pipe(Layer.provide(serverLayer(port)));\n\nconst stdio = McpServer.layerStdio({\n name: \"rat-stack\",\n protocols: mcpProtocols,\n registrations: mcpSkills,\n version: VERSION,\n});\n\nconst withStdio = (server: Layer.Layer) =>\n server.pipe(\n Layer.provide(stdio),\n Layer.provide(Layer.succeed(Logger.LogToStderr, true))\n );\n\nexport const DEVTOOLS_MCP_PATH = \"/__rat/mcp\";\n\nconst withDevtools = (\n caps: Caps,\n build: (\n projected: Effect.Success>>\n ) => Layer.Layer\n) => Layer.unwrap(Effect.map(devtools(caps), build));\n\nconst toolkitServer = (\n all: Caps\n) => {\n const projected = toToolkit(all);\n\n return McpServer.toolkit(projected.toolkit).pipe(\n Layer.provideMerge(projected.layer)\n );\n};\n\nexport const devtoolsRoutes = withDevtools(\n capabilities,\n ({ capabilities: all, recorded }) => {\n const api = toHttpApi(\"RatStack\", recorded);\n\n return Layer.mergeAll(\n HttpApiBuilder.layer(api.api, { openapiPath: \"/openapi.json\" }).pipe(\n Layer.provide(api.layer)\n ),\n HttpApiScalar.layer(api.api, { path: \"/docs\" }),\n toolkitServer(all).pipe(\n Layer.provide(\n McpServer.layerHttp({\n name: \"rat-stack-devtools\",\n path: DEVTOOLS_MCP_PATH,\n protocols: mcpProtocols,\n version: VERSION,\n })\n )\n )\n );\n }\n);\n\nexport const devtoolsWebServer = (port: number) =>\n HttpRouter.serve(devtoolsRoutes).pipe(\n Layer.provide(devtoolsLayer()),\n Layer.provide(serverLayer(port))\n );\n\nexport const mcpServer = {\n codeMode: withStdio(\n McpServer.toolkit(codeMode.toolkit).pipe(\n Layer.provideMerge(codeMode.layer),\n Layer.provide(layerSubprocess())\n )\n ),\n devtools: withStdio(\n withDevtools(cliCapabilities, ({ capabilities: all }) => toolkitServer(all))\n ).pipe(Layer.provide(devtoolsLayer())),\n devtoolsCodeMode: withStdio(\n withDevtools(cliCapabilities, ({ capabilities: all }) => {\n const projected = toCodeMode(all);\n\n return McpServer.toolkit(projected.toolkit).pipe(\n Layer.provideMerge(projected.layer),\n Layer.provide(layerSubprocess())\n );\n })\n ).pipe(Layer.provide(devtoolsLayer())),\n tools: withStdio(\n McpServer.toolkit(tools.toolkit).pipe(Layer.provideMerge(tools.layer))\n ),\n} as const;\n", - "[\"rat-stack\",\"show\",\"HEAD:apps/infra/alchemy.run.ts\"]": "import * as Cloudflare from \"@alchemy.run/cloudflare\";\nimport * as DomainCloudflare from \"@alchemy.run/domain/Cloudflare\";\nimport * as Drizzle from \"@alchemy.run/drizzle/Providers\";\nimport CatalogWorker from \"@rat-stack/catalog-server/CatalogWorker\";\nimport { turboCache } from \"@rat-stack/turbo-cache\";\nimport * as Alchemy from \"alchemy\";\nimport { adopt } from \"alchemy/AdoptPolicy\";\nimport { retain } from \"alchemy/RemovalPolicy\";\nimport { Stage } from \"alchemy/Stage\";\nimport * as Config from \"effect/Config\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\n\nimport privateAuth from \"../site/src/auth/private-worker.js\";\nimport Mischief from \"../site/src/worker.js\";\nimport Workshop from \"../site/src/workshop-worker.js\";\nimport { Website } from \"../web/src/website.js\";\nimport { ratstackState } from \"./src/state-store.js\";\n\nexport default Alchemy.Stack(\n \"RatStack\",\n {\n providers: Layer.mergeAll(\n Cloudflare.providers(),\n DomainCloudflare.providers(),\n Drizzle.providers()\n ),\n state: ratstackState(),\n },\n Effect.gen(function* stack() {\n const dev = yield* Alchemy.ALCHEMY_DEV;\n\n if (!dev) {\n const zone = yield* Cloudflare.Zone.Zone(\"RatstackZone\", {\n name: \"ratstack.sh\",\n }).pipe(\n adopt(true),\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Every main Stack stage adopts the same production zone; deleting it destroys shared DNS.\n retain()\n );\n\n const dnsAidService = (\n id: string,\n name:\n | `_a2a._agents.${string}`\n | `_index._agents.${string}`\n | `_mcp._agents.${string}`\n ) =>\n Cloudflare.DNS.Record(id, {\n content: {\n priority: 1,\n target: \"ratstack.sh.\",\n value: 'mandatory=\"alpn,port\" alpn=\"h2\" port=\"443\"',\n },\n name,\n ttl: 3600,\n type: \"SVCB\",\n zoneId: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- This fixed ratstack.sh discovery record is shared with production in every main Stack stage.\n retain()\n );\n\n yield* dnsAidService(\"DnsAidIndexSvcb\", \"_index._agents.ratstack.sh\");\n yield* dnsAidService(\"DnsAidA2aSvcb\", \"_a2a._agents.ratstack.sh\");\n yield* dnsAidService(\"DnsAidMcpSvcb\", \"_mcp._agents.ratstack.sh\");\n yield* Cloudflare.DNS.Record(\"DnsAidIndexTxt\", {\n content: '\"agents=rat-stack:mcp,rat-stack:a2a\"',\n name: \"_index._agents.ratstack.sh\",\n ttl: 3600,\n type: \"TXT\",\n zoneId: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- This fixed ratstack.sh discovery record is shared with production in every main Stack stage.\n retain()\n );\n\n yield* Cloudflare.DNS.Record(\"PostShibaDkimCname\", {\n content: \"174.customers.postshiba.com\",\n name: \"ps1._domainkey.ratstack.sh\",\n proxied: false,\n ttl: 3600,\n type: \"CNAME\",\n zoneId: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Production mail uses this fixed DKIM record across all main Stack stages.\n retain()\n );\n\n yield* Cloudflare.DNS.Record(\"PostShibaReturnPathCname\", {\n content: \"rp.postshiba.com\",\n name: \"rp.ratstack.sh\",\n proxied: false,\n ttl: 3600,\n type: \"CNAME\",\n zoneId: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Production mail uses this fixed return-path record across all main Stack stages.\n retain()\n );\n\n yield* Cloudflare.DNS.Record(\"DmarcTxt\", {\n content: '\"v=DMARC1; p=none;\"',\n name: \"_dmarc.ratstack.sh\",\n ttl: 3600,\n type: \"TXT\",\n zoneId: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Production mail uses this fixed DMARC record across all main Stack stages.\n retain()\n );\n\n const forwardTo = yield* Config.schema(\n Schema.Redacted(Schema.NonEmptyString),\n \"EMAIL_FORWARD_TO\"\n );\n\n const routing = yield* Cloudflare.Email.Routing(\"RatstackEmailRouting\", {\n zone: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Disabling routing on the shared ratstack.sh zone breaks production mail in every main Stack stage.\n retain()\n );\n\n const address = yield* Cloudflare.Email.Address(\n \"WorkshopForwardAddress\",\n {\n email: Redacted.value(forwardTo),\n }\n ).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- This configured production forwarding destination may be shared by other stages and mail rules.\n retain()\n );\n\n yield* Cloudflare.Email.Rule(\"WorkshopForwardRule\", {\n actions: [{ type: \"forward\", value: [address.email] }],\n enabled: true,\n matchers: [\n { field: \"to\", type: \"literal\", value: \"workshop@ratstack.sh\" },\n ],\n name: \"workshop\",\n zone: routing.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Every main Stack stage names the same production workshop forwarding rule on ratstack.sh.\n retain()\n );\n\n yield* Cloudflare.DNS.Dnssec(\"RatstackDnssec\", {\n status: \"active\",\n zoneId: zone.zoneId,\n }).pipe(\n adopt(true),\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Every main Stack stage adopts production DNSSEC; removing it breaks the shared zone's trust chain.\n retain()\n );\n }\n\n const website = yield* Website;\n\n const mischief = yield* Mischief;\n\n yield* Workshop;\n yield* turboCache;\n\n const catalog = yield* CatalogWorker.pipe(\n retain(Stage.pipe(Effect.map((stage) => stage === \"prod\")))\n );\n\n yield* mischief.bind`${website}`({\n bindings: [\n { name: \"WEBSITE\", service: website.workerName, type: \"service\" },\n ],\n });\n\n return {\n catalogUrl: catalog.url,\n mischiefUrl: mischief.url,\n websiteUrl: website.url,\n };\n }).pipe(\n Effect.provide(\n Layer.unwrap(\n Config.Boolean(\"AUTH_ENABLED\").pipe(\n Config.withDefault(false),\n Effect.map((enabled) => (enabled ? privateAuth : Layer.empty))\n )\n )\n )\n )\n);\n", + "[\"rat-stack\",\"show\",\"HEAD:apps/infra/alchemy.run.ts\"]": "import * as Cloudflare from \"@alchemy.run/cloudflare\";\nimport * as DomainCloudflare from \"@alchemy.run/domain/Cloudflare\";\nimport * as Drizzle from \"@alchemy.run/drizzle/Providers\";\nimport CatalogWorker from \"@rat-stack/catalog-server/CatalogWorker\";\nimport { turboCache } from \"@rat-stack/turbo-cache\";\nimport * as Alchemy from \"alchemy\";\nimport { adopt } from \"alchemy/AdoptPolicy\";\nimport { retain } from \"alchemy/RemovalPolicy\";\nimport { Stage } from \"alchemy/Stage\";\nimport * as Config from \"effect/Config\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\n\nimport privateAuth from \"../site/src/auth/private-worker.js\";\nimport { instituteStage } from \"../site/src/institute-mount.js\";\nimport Mischief from \"../site/src/worker.js\";\nimport Workshop from \"../site/src/workshop-worker.js\";\nimport { Website } from \"../web/src/website.js\";\nimport { instituteWorker } from \"./src/institute.js\";\nimport { ratstackState } from \"./src/state-store.js\";\n\nconst gateway = Effect.gen(function* declareGateway() {\n const website = yield* Website;\n const mischief = yield* Mischief;\n\n yield* mischief.bind`${website}`({\n bindings: [\n { name: \"WEBSITE\", service: website.workerName, type: \"service\" },\n ],\n });\n\n const institute = yield* instituteWorker;\n\n if (institute !== null) {\n yield* mischief.bind`${institute}`({\n bindings: [\n { name: \"INSTITUTE\", service: institute.workerName, type: \"service\" },\n ],\n });\n }\n\n return { mischiefUrl: mischief.url, websiteUrl: website.url };\n});\n\nexport default Alchemy.Stack(\n \"RatStack\",\n {\n providers: Layer.mergeAll(\n Cloudflare.providers(),\n DomainCloudflare.providers(),\n Drizzle.providers()\n ),\n state: ratstackState(),\n },\n Effect.gen(function* stack() {\n const stage = yield* Stage;\n\n if (stage === instituteStage) {\n return { ...(yield* gateway), catalogUrl: undefined };\n }\n\n const dev = yield* Alchemy.ALCHEMY_DEV;\n\n if (!dev) {\n const zone = yield* Cloudflare.Zone.Zone(\"RatstackZone\", {\n name: \"ratstack.sh\",\n }).pipe(\n adopt(true),\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Every main Stack stage adopts the same production zone; deleting it destroys shared DNS.\n retain()\n );\n\n const dnsAidService = (\n id: string,\n name:\n | `_a2a._agents.${string}`\n | `_index._agents.${string}`\n | `_mcp._agents.${string}`\n ) =>\n Cloudflare.DNS.Record(id, {\n content: {\n priority: 1,\n target: \"ratstack.sh.\",\n value: 'mandatory=\"alpn,port\" alpn=\"h2\" port=\"443\"',\n },\n name,\n ttl: 3600,\n type: \"SVCB\",\n zoneId: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- This fixed ratstack.sh discovery record is shared with production in every main Stack stage.\n retain()\n );\n\n yield* dnsAidService(\"DnsAidIndexSvcb\", \"_index._agents.ratstack.sh\");\n yield* dnsAidService(\"DnsAidA2aSvcb\", \"_a2a._agents.ratstack.sh\");\n yield* dnsAidService(\"DnsAidMcpSvcb\", \"_mcp._agents.ratstack.sh\");\n yield* Cloudflare.DNS.Record(\"DnsAidIndexTxt\", {\n content: '\"agents=rat-stack:mcp,rat-stack:a2a\"',\n name: \"_index._agents.ratstack.sh\",\n ttl: 3600,\n type: \"TXT\",\n zoneId: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- This fixed ratstack.sh discovery record is shared with production in every main Stack stage.\n retain()\n );\n\n yield* Cloudflare.DNS.Record(\"PostShibaDkimCname\", {\n content: \"174.customers.postshiba.com\",\n name: \"ps1._domainkey.ratstack.sh\",\n proxied: false,\n ttl: 3600,\n type: \"CNAME\",\n zoneId: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Production mail uses this fixed DKIM record across all main Stack stages.\n retain()\n );\n\n yield* Cloudflare.DNS.Record(\"PostShibaReturnPathCname\", {\n content: \"rp.postshiba.com\",\n name: \"rp.ratstack.sh\",\n proxied: false,\n ttl: 3600,\n type: \"CNAME\",\n zoneId: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Production mail uses this fixed return-path record across all main Stack stages.\n retain()\n );\n\n yield* Cloudflare.DNS.Record(\"DmarcTxt\", {\n content: '\"v=DMARC1; p=none;\"',\n name: \"_dmarc.ratstack.sh\",\n ttl: 3600,\n type: \"TXT\",\n zoneId: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Production mail uses this fixed DMARC record across all main Stack stages.\n retain()\n );\n\n const forwardTo = yield* Config.schema(\n Schema.Redacted(Schema.NonEmptyString),\n \"EMAIL_FORWARD_TO\"\n );\n\n const routing = yield* Cloudflare.Email.Routing(\"RatstackEmailRouting\", {\n zone: zone.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Disabling routing on the shared ratstack.sh zone breaks production mail in every main Stack stage.\n retain()\n );\n\n const address = yield* Cloudflare.Email.Address(\n \"WorkshopForwardAddress\",\n {\n email: Redacted.value(forwardTo),\n }\n ).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- This configured production forwarding destination may be shared by other stages and mail rules.\n retain()\n );\n\n yield* Cloudflare.Email.Rule(\"WorkshopForwardRule\", {\n actions: [{ type: \"forward\", value: [address.email] }],\n enabled: true,\n matchers: [\n { field: \"to\", type: \"literal\", value: \"workshop@ratstack.sh\" },\n ],\n name: \"workshop\",\n zone: routing.zoneId,\n }).pipe(\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Every main Stack stage names the same production workshop forwarding rule on ratstack.sh.\n retain()\n );\n\n yield* Cloudflare.DNS.Dnssec(\"RatstackDnssec\", {\n status: \"active\",\n zoneId: zone.zoneId,\n }).pipe(\n adopt(true),\n // oxlint-disable-next-line rat-stack-patterns/retain-needs-stage-policy -- Every main Stack stage adopts production DNSSEC; removing it breaks the shared zone's trust chain.\n retain()\n );\n }\n\n const gatewayUrls = yield* gateway;\n\n yield* Workshop;\n yield* turboCache;\n\n const catalog = yield* CatalogWorker.pipe(retain(stage === \"prod\"));\n\n return { ...gatewayUrls, catalogUrl: catalog.url };\n }).pipe(\n Effect.provide(\n Layer.unwrap(\n Config.Boolean(\"AUTH_ENABLED\").pipe(\n Config.withDefault(false),\n Effect.map((enabled) => (enabled ? privateAuth : Layer.empty))\n )\n )\n )\n )\n);\n", "[\"rat-stack\",\"show\",\"HEAD:apps/site/src/capabilities/search.ts\"]": "import { implement } from \"@rat-stack/capability/implement\";\nimport { searchContract } from \"@rat-stack/core/contracts\";\nimport { Effect } from \"effect\";\n\nimport { ContentStore } from \"../content-store.js\";\n\nexport const search = implement(searchContract, ({ limit, query }) =>\n ContentStore.use((store) => store.search(query, limit)).pipe(\n Effect.map((matches) => ({ matches, total: matches.length }))\n )\n);\n", "[\"rat-stack\",\"show\",\"HEAD:apps/site/src/events.ts\"]": "export { events, memoryEvents } from \"@rat-stack/events/site\";\n", "[\"rat-stack\",\"show\",\"HEAD:apps/site/src/interest/interest-durable-object.ts\"]": "import * as Cloudflare from \"@alchemy.run/cloudflare\";\nimport { InterestStore, runInterestMachine } from \"@rat-stack/core/interest\";\nimport type { CaptureRequest, InterestRecord } from \"@rat-stack/core/interest\";\nimport type { SealedRow, TicketBinding } from \"@rat-stack/intake-live\";\nimport type { RuntimeContext } from \"alchemy/RuntimeContext\";\nimport * as Effect from \"effect/Effect\";\n\nimport { joinContactCell } from \"./join-contact-cell.js\";\n\nconst RECORD_KEY = \"record\";\n\nconst TICKET_KEY = \"ticket\";\n\nconst INTAKE_KEY = \"intake-key\";\n\nconst INTAKE_STATEMENT_PREFIX = \"intake-statement:\";\n\ninterface TicketHold {\n readonly expiresAt: number;\n readonly submissionId: string;\n}\n\nexport default class Interest extends Cloudflare.DurableObject()(\n \"Interest\",\n Effect.gen(function* makeInterest() {\n const state = yield* Cloudflare.DurableObjectState;\n\n // @effect-diagnostics-next-line returnEffectInGen:off -- Alchemy's DurableObject contract returns the per-instance Effect.\n return Effect.gen(function* makeInstance() {\n const runtime = yield* Effect.context();\n\n const store = {\n load: state.storage\n .get(RECORD_KEY)\n .pipe(Effect.provideContext(runtime)),\n save: (record: InterestRecord) =>\n state.storage\n .put(RECORD_KEY, record)\n .pipe(Effect.provideContext(runtime)),\n };\n\n const run = (\n address: string,\n command: \"confirm\" | \"mailFailed\" | \"register\",\n capture?: CaptureRequest\n ) =>\n runInterestMachine(address, command, capture).pipe(\n Effect.provideService(InterestStore, store)\n );\n\n const storage = (effect: Effect.Effect) =>\n effect.pipe(Effect.provideContext(runtime));\n\n const bindTicket = (submissionId: string, expiresAt: number) =>\n Effect.gen(function* bind() {\n const held = yield* storage(\n state.storage.get(TICKET_KEY)\n );\n\n if (held === undefined) {\n yield* storage(\n state.storage.put(TICKET_KEY, { expiresAt, submissionId })\n );\n\n return \"first\" satisfies TicketBinding;\n }\n\n return held.submissionId === submissionId ? \"same\" : \"other\";\n });\n\n const intakeKey = (candidate: string) =>\n Effect.gen(function* key() {\n const held = yield* storage(state.storage.get(INTAKE_KEY));\n\n if (held !== undefined) {\n return held;\n }\n\n yield* storage(state.storage.put(INTAKE_KEY, candidate));\n\n return candidate;\n });\n\n const intakeStore = (rows: readonly SealedRow[]) =>\n Effect.gen(function* storeRows() {\n for (const row of rows) {\n const key = `${INTAKE_STATEMENT_PREFIX}${row.id}`;\n const held = yield* storage(state.storage.get(key));\n\n if (held === undefined) {\n yield* storage(state.storage.put(key, row.sealed));\n }\n }\n });\n\n return {\n bindTicket,\n confirm: (address: string) => run(address, \"confirm\"),\n forget: () =>\n state.storage.delete(RECORD_KEY).pipe(Effect.provideContext(runtime)),\n intakeErase: () => storage(state.storage.deleteAll()),\n intakeKey,\n intakeRead: () =>\n Effect.all({\n key: storage(state.storage.get(INTAKE_KEY)),\n rows: storage(\n state.storage.list({ prefix: INTAKE_STATEMENT_PREFIX })\n ).pipe(\n Effect.map((entries) =>\n [...entries].map(([id, sealed]) => ({\n id: id.slice(INTAKE_STATEMENT_PREFIX.length),\n sealed,\n }))\n )\n ),\n }),\n intakeStore,\n ...joinContactCell({\n delete: (key) => storage(state.storage.delete(key)),\n get: (key) => storage(state.storage.get(key)),\n put: (key, value) => storage(state.storage.put(key, value)),\n setAlarm: (deadlineAt) => storage(state.storage.setAlarm(deadlineAt)),\n }),\n mailFailed: (address: string) => run(address, \"mailFailed\"),\n register: (address: string, capture?: CaptureRequest) =>\n run(address, \"register\", capture),\n };\n });\n })\n) {}\n", "[\"rat-stack\",\"show\",\"HEAD:apps/site/src/interest/join-contact-cell.ts\"]": "import {\n JOIN_CONTACT_RETENTION_MILLIS,\n JoinErasureSchema,\n} from \"@rat-stack/core/join-interest\";\nimport { Clock, DateTime, Effect, Option, Schema } from \"effect\";\n\nexport const JOIN_CONTACT_KEY = \"join-contact\";\n\nexport const JOIN_ERASED_KEY = \"join-erased\";\n\nconst StoredContact = Schema.Struct({\n erase: Schema.Boolean,\n retentionDeadlineAt: Schema.optionalKey(Schema.Finite),\n sealed: Schema.String,\n});\n\nconst CONTACT_META_KEY = \"join-contact-meta\";\n\nconst ERASE_REQUEST_KEY = \"join-erase-request\";\n\nexport type JoinCellValue =\n | boolean\n | typeof StoredContact.Type\n | typeof JoinErasureSchema.Type;\n\nexport interface JoinCellStorage {\n readonly get: (key: string) => Effect.Effect;\n readonly put: (key: string, value: JoinCellValue) => Effect.Effect;\n readonly delete: (key: string) => Effect.Effect;\n readonly setAlarm: (deadlineAt: number) => Effect.Effect;\n}\n\nconst decodeStored = Schema.decodeUnknownOption(StoredContact);\n\nconst decodeLegacy = Schema.decodeUnknownOption(Schema.String);\n\nexport const joinContactCell = (storage: JoinCellStorage) => {\n const current = storage.get(JOIN_CONTACT_KEY).pipe(\n Effect.map((value) =>\n Option.orElse(decodeStored(value), () =>\n Option.orElse(\n Option.map(decodeLegacy(value), (sealed) => ({\n erase: false,\n retentionDeadlineAt: undefined,\n sealed,\n })),\n () =>\n value === undefined\n ? Option.none()\n : Option.some({\n erase: false,\n retentionDeadlineAt: undefined,\n sealed: \"\",\n })\n )\n )\n )\n );\n\n const metadata = storage\n .get(CONTACT_META_KEY)\n .pipe(Effect.map(Schema.decodeUnknownOption(JoinErasureSchema)));\n\n const readErasure = () =>\n storage\n .get(ERASE_REQUEST_KEY)\n .pipe(\n Effect.map(Schema.decodeUnknownOption(JoinErasureSchema)),\n Effect.map(Option.getOrUndefined)\n );\n\n const joinErase = () =>\n storage\n .put(JOIN_ERASED_KEY, true)\n .pipe(Effect.andThen(storage.delete(JOIN_CONTACT_KEY)), Effect.asVoid);\n\n const expire = Effect.gen(function* expireContact() {\n yield* joinErase();\n yield* Effect.logWarning(\"join contact erased at retention deadline\");\n });\n\n const readLive = Effect.gen(function* readLiveContact() {\n const contact = yield* current;\n\n if (Option.isNone(contact)) {\n return contact;\n }\n\n const now = yield* Clock.currentTimeMillis;\n const { retentionDeadlineAt } = contact.value;\n\n if (retentionDeadlineAt !== undefined && now >= retentionDeadlineAt) {\n yield* expire;\n\n return Option.none();\n }\n\n return contact;\n });\n\n return {\n alarm: () =>\n readLive.pipe(\n Effect.flatMap((contact) =>\n Option.isSome(contact) &&\n contact.value.retentionDeadlineAt !== undefined\n ? storage.setAlarm(contact.value.retentionDeadlineAt)\n : Effect.void\n )\n ),\n joinErase,\n joinReadSnapshot: () =>\n readLive.pipe(\n Effect.map(\n Option.map(({ sealed, retentionDeadlineAt }) =>\n retentionDeadlineAt === undefined\n ? { sealed }\n : { sealed, retentionDeadlineAt }\n )\n ),\n Effect.map(Option.getOrUndefined)\n ),\n joinReadRetentionDeadline: () =>\n current.pipe(\n Effect.map(\n Option.flatMap((contact) =>\n Option.fromUndefinedOr(contact.retentionDeadlineAt)\n )\n ),\n Effect.map(Option.getOrUndefined)\n ),\n joinReadErasure: readErasure,\n joinReadHandoff: () => metadata.pipe(Effect.map(Option.getOrUndefined)),\n joinRequestErase: () =>\n Effect.gen(function* requestErase() {\n const marker = yield* metadata;\n\n if (Option.isSome(marker)) {\n yield* storage.put(ERASE_REQUEST_KEY, marker.value);\n }\n\n yield* joinErase();\n\n return Option.getOrUndefined(marker);\n }),\n joinCompleteErasure: () =>\n storage.delete(ERASE_REQUEST_KEY).pipe(Effect.asVoid),\n joinMarkHandedToDrovr: (legacy = false) =>\n Effect.gen(function* markHandedToDrovr() {\n const marker = yield* metadata;\n\n if (Option.isNone(marker)) {\n return yield* Effect.die(\n new Error(\n \"Join contact handoff metadata is missing. Erasure forwarding needs a durable contact reference. Fix: call `joinRetentionBackfill` before retrying delivery.\"\n )\n );\n }\n\n const handedToDrovrAt =\n legacy || marker.value.handedToDrovr\n ? marker.value.handedToDrovrAt\n : DateTime.formatIso(yield* DateTime.now);\n\n const handed = {\n ...marker.value,\n handedToDrovr: true,\n handedToDrovrAt,\n };\n\n yield* storage.put(CONTACT_META_KEY, handed);\n\n if ((yield* readErasure()) !== undefined) {\n yield* storage.put(ERASE_REQUEST_KEY, handed);\n }\n\n return yield* Effect.void;\n }),\n joinRead: () =>\n readLive.pipe(\n Effect.map(Option.map(({ sealed }) => sealed)),\n Effect.map(Option.getOrUndefined)\n ),\n joinSave: (\n sealed: string,\n erase: boolean,\n deadlineAt?: number,\n contactRef?: string\n ) =>\n Effect.gen(function* saveUnlessErased() {\n if (contactRef !== undefined && Option.isNone(yield* metadata)) {\n const marker = yield* Schema.decodeEffect(JoinErasureSchema)({\n contactRef,\n handedToDrovr: false,\n handedToDrovrAt: null,\n pending: \"erase\",\n }).pipe(Effect.orDie);\n\n yield* storage.put(CONTACT_META_KEY, marker);\n }\n\n if (erase) {\n const marker = yield* metadata;\n\n if (Option.isSome(marker)) {\n yield* storage.put(ERASE_REQUEST_KEY, marker.value);\n }\n }\n\n const erased = yield* storage.get(JOIN_ERASED_KEY);\n\n if (erased === true) {\n return;\n }\n\n const held = yield* current;\n\n if (Option.isSome(held) && held.value.erase && !erase) {\n return;\n }\n\n const now = yield* Clock.currentTimeMillis;\n\n const retentionDeadlineAt = Math.min(\n Option.isSome(held)\n ? (held.value.retentionDeadlineAt ??\n now + JOIN_CONTACT_RETENTION_MILLIS)\n : now + JOIN_CONTACT_RETENTION_MILLIS,\n deadlineAt ?? now + JOIN_CONTACT_RETENTION_MILLIS\n );\n\n if (now >= retentionDeadlineAt) {\n yield* expire;\n\n return;\n }\n\n yield* storage.setAlarm(retentionDeadlineAt);\n yield* storage.put(JOIN_CONTACT_KEY, {\n erase,\n retentionDeadlineAt,\n sealed,\n });\n }),\n };\n};\n", - "[\"rat-stack\",\"show\",\"HEAD:apps/site/src/worker.ts\"]": "import * as Cloudflare from \"@alchemy.run/cloudflare\";\nimport {\n Flags,\n eventsEnabled,\n eventsIdentityMode,\n} from \"@rat-stack/core/flags\";\nimport { InterestMode, InterestTokens } from \"@rat-stack/core/interest\";\nimport type { InterestDirectory } from \"@rat-stack/core/interest\";\nimport type { RequestCaptureSettings } from \"@rat-stack/core/request-capture\";\nimport { webCryptoLayer } from \"@rat-stack/core/web-crypto\";\nimport { intakeLiveLayer, intakeInstance } from \"@rat-stack/intake-live\";\nimport { subscriberDeliveryLayer } from \"@rat-stack/subscriber-delivery\";\nimport { Stage } from \"alchemy\";\nimport { Duration, Schema } from \"effect\";\nimport * as Config from \"effect/Config\";\nimport * as Effect from \"effect/Effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport * as HttpRouter from \"effect/http/HttpRouter\";\nimport * as HttpServerRequest from \"effect/http/HttpServerRequest\";\nimport * as HttpServerResponse from \"effect/http/HttpServerResponse\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\n\nimport { mischiefRoutes, readerResponseHeaders } from \"./app.js\";\nimport type { MischiefRouteOptions } from \"./app.js\";\nimport { contentAssetsForBuild } from \"./asset-deployment.js\";\nimport { feedbackGatewayBuild } from \"./auth/build-options.js\";\nimport type { feedbackAccess } from \"./auth/feedback-access.js\";\nimport { feedbackInfrastructure } from \"./auth/infrastructure.js\";\nimport { staticAssetGeneration } from \"./bundled-content.generated.js\";\nimport { mischiefConfigFingerprint } from \"./config-fingerprint.js\";\nimport { ContentStore } from \"./content-store.js\";\nimport CrashTail from \"./crash-tail.js\";\nimport { ErrorPageRenderer, websiteErrorPages } from \"./error-page-renderer.js\";\nimport { events as eventsFor } from \"./events.js\";\nimport { flagsLayer, liveFlagsLayer } from \"./flags.js\";\nimport { intakeApplicationsLayer } from \"./interest/applications.js\";\nimport { interestDirectoryLayer } from \"./interest/directory.js\";\nimport {\n SWEEP_PENDING_INTAKE_CRON,\n deliveryDeadlineLayer,\n scheduleIntakeSweep,\n} from \"./interest/intake-sweep.js\";\nimport Interest from \"./interest/interest-durable-object.js\";\nimport InterestIndex from \"./interest/interest-index-durable-object.js\";\nimport { agentSignupLayer } from \"./interest/join-layer.js\";\nimport type { AgentSignupOptions } from \"./interest/join-layer.js\";\nimport { interestOperatorOptions } from \"./interest/operator-options.js\";\nimport LegacyMcp from \"./legacy-mcp/durable-object.js\";\nimport { LEGACY_SESSION_HEADER } from \"./legacy-mcp/session.js\";\nimport {\n privateTelemetry,\n traceObservability,\n traceSettings,\n} from \"./observability.js\";\nimport { outerHttpPrivacyRegistration } from \"./outer-http-privacy.js\";\nimport { rateLimitsFrom, rateLimitDeclarations } from \"./rate-limits.js\";\nimport type { RateLimitBindings } from \"./rate-limits.js\";\nimport { withReaderWebsite } from \"./reader-website.js\";\nimport {\n logRequestIncident,\n observeRequestIncidents,\n} from \"./request-incidents.js\";\nimport { observeRequestLog } from \"./request-log.js\";\nimport { layerWorkerLoader, sandboxLimits } from \"./sandbox-loader.js\";\nimport type { WorkerLoaderBinding } from \"./sandbox-worker-loader.js\";\nimport { AssetBindingSchema, StaticAssets } from \"./static-assets.js\";\nimport {\n chromeWebMcpTrialToken,\n edgeWebMcpTrialToken,\n withWebMcpOriginTrials,\n} from \"./web-mcp-origin-trials.js\";\n\nconst cloudflareStaticCache = {\n match: (request: Request) => caches.default.match(request),\n put: (request: Request, response: Response) =>\n caches.default.put(request, response),\n};\n\nconst inBackground = (effect: Effect.Effect) =>\n Effect.gen(function* registerBackgroundWork() {\n const execution = yield* Cloudflare.WorkerExecutionContext;\n\n yield* execution.waitUntil(effect);\n });\n\nexport type RequestCapture = (\n settings: RequestCaptureSettings\n) => (\n app: Effect.Effect\n) => Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n E,\n R | RB | HttpServerRequest.HttpServerRequest\n>;\n\nexport const makeMischief = (\n legacyMcp: NonNullable,\n interestDirectory: Layer.Layer,\n capture?: RequestCapture,\n agentSignup?: AgentSignupOptions,\n feedback?: ReturnType,\n liveFlags?: Flags[\"Service\"]\n) =>\n Effect.gen(function* makeMischiefInit() {\n if (globalThis.__ALCHEMY_RUNTIME__ !== true) {\n const stageRateLimits = rateLimitDeclarations(yield* Stage);\n yield* Cloudflare.RateLimit(\"API_PER_IP\", stageRateLimits.API_PER_IP);\n yield* Cloudflare.RateLimit(\n \"EXECUTE_GLOBAL\",\n stageRateLimits.EXECUTE_GLOBAL\n );\n yield* Cloudflare.RateLimit(\n \"EXECUTE_PER_IP\",\n stageRateLimits.EXECUTE_PER_IP\n );\n yield* Cloudflare.RateLimit(\n \"INTEREST_PER_IP\",\n stageRateLimits.INTEREST_PER_IP\n );\n }\n\n const webBotAuthEnabled = yield* Config.Boolean(\n \"WEB_BOT_AUTH_ENABLED\"\n ).pipe(Config.withDefault(false));\n\n const webBotAuthPrivateJwk = yield* Config.option(\n Config.Redacted(\"WEB_BOT_AUTH_PRIVATE_JWK\")\n );\n\n const interestMode = yield* Config.schema(\n Schema.Literals([\"capture\", \"doi\", \"drovr\"]),\n \"INTEREST_MODE\"\n ).pipe(Config.withDefault(\"doi\" as const));\n\n const interestTokenSecret = yield* Config.option(\n Config.Redacted(\"INTEREST_TOKEN_SECRET\")\n );\n\n const interestOperatorToken = yield* Config.option(\n Config.Redacted(\"INTEREST_OPERATOR_TOKEN\")\n );\n\n const drovrIntakeUrl = yield* Config.option(\n Config.String(\"DROVR_INTAKE_URL\")\n );\n\n const drovrIntakeTimeoutSeconds = yield* Config.option(\n Config.schema(\n Schema.Int.check(Schema.isBetween({ maximum: 60, minimum: 1 })),\n \"DROVR_INTAKE_TIMEOUT_SECONDS\"\n )\n );\n\n const joinDeliveryDeadlineSeconds = yield* Config.option(\n Config.schema(\n Schema.Int.check(Schema.isBetween({ maximum: 28, minimum: 5 })),\n \"JOIN_DELIVERY_DEADLINE_SECONDS\"\n )\n );\n\n const drovrApiBase = yield* Config.option(Config.String(\"DROVR_API_BASE\"));\n\n const drovrAgentIntakeCredential = yield* Config.option(\n Config.Redacted(\"DROVR_AGENT_INTAKE_CREDENTIAL\")\n );\n\n const drovrIntakeCredential = yield* Config.option(\n Config.Redacted(\"DROVR_INTAKE_CREDENTIAL\")\n );\n\n const identityMode = yield* Flags.use((flags) =>\n flags.get(eventsIdentityMode, {}).pipe(Effect.orDie)\n ).pipe(Effect.provide(flagsLayer));\n\n const environment = yield* Cloudflare.WorkerEnvironment;\n\n // SAFETY: these are the native runtime bindings declared above. Alchemy types the environment as a dictionary it fills in at runtime, so this is the one boundary cast.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Alchemy types the Worker environment as a dictionary, so the declared bindings need one boundary cast.\n const bindings = environment as RateLimitBindings & {\n readonly CODE_SANDBOX: WorkerLoaderBinding;\n };\n\n const loader = bindings.CODE_SANDBOX;\n\n const rateLimits = rateLimitsFrom({\n API_PER_IP: bindings.API_PER_IP,\n EXECUTE_GLOBAL: bindings.EXECUTE_GLOBAL,\n EXECUTE_PER_IP: bindings.EXECUTE_PER_IP,\n INTEREST_PER_IP: bindings.INTEREST_PER_IP,\n });\n\n const interestServices = Option.isNone(interestTokenSecret)\n ? undefined\n : yield* Layer.build(\n Layer.mergeAll(\n interestDirectory,\n InterestTokens.layer(interestTokenSecret.value),\n InterestMode.layer(interestMode),\n subscriberDeliveryLayer({\n agentIntake: {\n credential: drovrAgentIntakeCredential,\n url: drovrIntakeUrl,\n },\n confirm: {\n base: drovrApiBase,\n credential: drovrIntakeCredential,\n },\n intake: {\n credential: drovrIntakeCredential,\n url: drovrIntakeUrl,\n },\n intakeTimeout: drovrIntakeTimeoutSeconds.pipe(\n Option.map(Duration.seconds),\n Option.getOrUndefined\n ),\n })\n )\n );\n\n const interest =\n interestServices === undefined\n ? undefined\n : {\n operatorToken: interestOperatorToken.pipe(\n Option.map(Redacted.value),\n Option.getOrUndefined\n ),\n services: interestServices,\n };\n\n const joinServices =\n agentSignup !== undefined && interestServices !== undefined\n ? yield* Layer.build(\n agentSignupLayer(agentSignup, interestServices).pipe(\n Layer.provide(deliveryDeadlineLayer(joinDeliveryDeadlineSeconds))\n )\n )\n : undefined;\n\n yield* scheduleIntakeSweep(agentSignup, joinServices);\n\n const operatorOptions = yield* interestOperatorOptions(\n agentSignup,\n joinServices\n );\n\n const assetBinding = Schema.decodeUnknownOption(AssetBindingSchema)(\n environment.ASSETS\n );\n\n const assets = Option.isNone(assetBinding)\n ? undefined\n : yield* StaticAssets.pipe(\n Effect.provide(StaticAssets.layer(assetBinding.value))\n );\n\n const contentStore = yield* ContentStore.pipe(\n Effect.provide(\n ContentStore.layer.pipe(\n Layer.provide(\n Layer.succeed(\n StaticAssets,\n assets ??\n Option.getOrElse(\n yield* Effect.serviceOption(StaticAssets),\n () => StaticAssets.unavailable\n )\n )\n )\n )\n )\n );\n\n const workerRoutes = mischiefRoutes({\n assets,\n contentStore,\n feedback,\n flags: liveFlags,\n interest:\n interest === undefined\n ? undefined\n : { ...interest, ...operatorOptions },\n joinTokens: interestServices,\n legacyMcp,\n rateLimits,\n staticCache: cloudflareStaticCache,\n webBotAuth: {\n enabled: webBotAuthEnabled,\n privateJwk: webBotAuthPrivateJwk.pipe(\n Option.map(Redacted.value),\n Option.getOrUndefined\n ),\n },\n }).pipe(\n Layer.provide(layerWorkerLoader(loader, sandboxLimits)),\n Layer.provide(\n joinServices === undefined\n ? Layer.empty\n : Layer.succeedContext(joinServices)\n )\n );\n\n const website = Schema.decodeUnknownEffect(AssetBindingSchema)(\n environment.WEBSITE\n );\n\n const app = (yield* HttpRouter.toHttpEffect(workerRoutes).pipe(\n Effect.orDie\n )).pipe(\n Effect.provideService(ErrorPageRenderer, websiteErrorPages(website))\n );\n\n const chromeToken = yield* chromeWebMcpTrialToken;\n const edgeToken = yield* edgeWebMcpTrialToken;\n\n const readerApp = withReaderWebsite(\n website.pipe(Effect.orDie),\n withWebMcpOriginTrials(\n [chromeToken, edgeToken],\n readerResponseHeaders(contentStore)\n )\n )(app);\n\n return {\n fetch: observeRequestLog(\n observeRequestIncidents(\n capture === undefined\n ? readerApp\n : Effect.gen(function* captureWithLiveIdentity() {\n const currentIdentity =\n liveFlags === undefined\n ? identityMode\n : yield* liveFlags\n .get(eventsIdentityMode, {})\n .pipe(\n Effect.catch((error) =>\n Effect.logError(\n \"Flag read failed; using Config fallback.\",\n error\n ).pipe(Effect.andThen(Effect.succeed(identityMode)))\n )\n );\n\n return yield* capture({\n captureCity: true,\n identityMode: currentIdentity,\n runInBackground: inBackground,\n })(readerApp);\n })\n ).pipe(Effect.provide(webCryptoLayer))\n ),\n };\n });\n\nconst makeMischiefWorker = Effect.gen(function* makeMischiefWorker() {\n if (globalThis.__ALCHEMY_RUNTIME__ !== true) {\n yield* Cloudflare.WorkerLoader(\"CODE_SANDBOX\");\n }\n\n const feedback = (yield* feedbackInfrastructure).pipe(Option.getOrUndefined);\n const liveFlags = yield* Flags.pipe(Effect.provide(liveFlagsLayer));\n\n const legacyMcp = yield* LegacyMcp;\n const interests = yield* Interest;\n const interestIndex = yield* InterestIndex;\n const sweepCron = yield* Cloudflare.Workers.CronEventSource;\n\n const tokenSecret = yield* Config.option(\n Config.Redacted(\"INTEREST_TOKEN_SECRET\")\n );\n\n const typesafeApiKey = yield* Config.option(\n Config.Redacted(\"TYPESAFE_API_KEY\")\n );\n\n const agentSignup = Option.isNone(tokenSecret)\n ? undefined\n : ({\n applications: intakeApplicationsLayer(\n () => interestIndex.getByName(\"index\").applicationIds(),\n (actor) => interests.getByName(intakeInstance(actor))\n ),\n applicationIds: () => interestIndex.getByName(\"index\").applicationIds(),\n contacts: (submissionId: string) =>\n interests.getByName(`join:${submissionId}`),\n intake: intakeLiveLayer({\n interests: (name) => interests.getByName(name),\n tokenSecret: tokenSecret.value,\n typesafeApiKey,\n }).pipe(Layer.provide(FetchHttpClient.layer)),\n markPending: (submissionId, pending) =>\n interestIndex.getByName(\"index\").markPending(submissionId, pending),\n noteApplication: (submissionId) =>\n interestIndex.getByName(\"index\").noteApplication(submissionId),\n sweep: {\n ids: () => interestIndex.getByName(\"index\").pendingIds(),\n schedule: (run) => sweepCron(SWEEP_PENDING_INTAKE_CRON, () => run),\n },\n } satisfies AgentSignupOptions | undefined);\n\n const enabled = yield* Flags.use((flags) =>\n flags.get(eventsEnabled, {}).pipe(Effect.orDie)\n ).pipe(Effect.provide(flagsLayer));\n\n const capture = yield* eventsFor({ enabled, id: \"Mischief\" });\n\n return yield* makeMischief(\n {\n forward: (session, request) => {\n const headers = new Headers(request.headers);\n headers.set(LEGACY_SESSION_HEADER, session);\n\n return legacyMcp\n .getByName(session)\n .fetch(HttpServerRequest.fromWeb(new Request(request, { headers })))\n .pipe(\n Effect.map((response) => HttpServerResponse.toWeb(response)),\n Effect.orDie\n );\n },\n },\n interestDirectoryLayer(\n (address) => interests.getByName(address),\n () => interestIndex.getByName(\"index\")\n ),\n capture,\n agentSignup,\n feedback,\n liveFlags\n );\n}).pipe(\n Effect.provide(\n Layer.mergeAll(\n Cloudflare.Workers.RateLimitBinding,\n Cloudflare.Workers.FetchBinding,\n Cloudflare.Workers.CronEventSourceLive,\n outerHttpPrivacyRegistration,\n privateTelemetry\n )\n ),\n Effect.tapCause((cause) =>\n logRequestIncident(cause, \"initialization\").pipe(\n Effect.provide(webCryptoLayer),\n Effect.asVoid\n )\n )\n);\n\nexport default class Mischief extends Cloudflare.Worker()(\n \"Mischief\",\n Effect.gen(function* mischiefProps() {\n const traces = yield* traceSettings.pipe(Effect.orDie);\n\n const assets = yield* contentAssetsForBuild(\n new URL(\"../dist/content\", import.meta.url).pathname,\n staticAssetGeneration\n ).pipe(Effect.orDie);\n\n return {\n assets,\n build: feedbackGatewayBuild,\n compatibility: { date: traces.enabled ? \"2026-07-28\" : \"2026-05-28\" },\n dev: { port: 1337 },\n domain: { name: \"ratstack.sh\", redirects: [\"www.ratstack.sh\"] },\n env: {\n MISCHIEF_CONFIG_FINGERPRINT: mischiefConfigFingerprint,\n WEB_MCP_CHROME_TRIAL_TOKEN: chromeWebMcpTrialToken,\n WEB_MCP_EDGE_TRIAL_TOKEN: edgeWebMcpTrialToken,\n },\n main: import.meta.url,\n observability: traceObservability(traces),\n tailConsumers: [yield* CrashTail],\n };\n }),\n makeMischiefWorker\n) {}\n", + "[\"rat-stack\",\"show\",\"HEAD:apps/site/src/worker.ts\"]": "import * as Cloudflare from \"@alchemy.run/cloudflare\";\nimport {\n Flags,\n eventsEnabled,\n eventsIdentityMode,\n} from \"@rat-stack/core/flags\";\nimport { InterestMode, InterestTokens } from \"@rat-stack/core/interest\";\nimport type { InterestDirectory } from \"@rat-stack/core/interest\";\nimport type { RequestCaptureSettings } from \"@rat-stack/core/request-capture\";\nimport { webCryptoLayer } from \"@rat-stack/core/web-crypto\";\nimport { intakeLiveLayer, intakeInstance } from \"@rat-stack/intake-live\";\nimport { subscriberDeliveryLayer } from \"@rat-stack/subscriber-delivery\";\nimport { Stage } from \"alchemy\";\nimport { Duration, Schema } from \"effect\";\nimport * as Config from \"effect/Config\";\nimport * as Effect from \"effect/Effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport * as HttpRouter from \"effect/http/HttpRouter\";\nimport * as HttpServerRequest from \"effect/http/HttpServerRequest\";\nimport * as HttpServerResponse from \"effect/http/HttpServerResponse\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\n\nimport { mischiefRoutes, readerResponseHeaders } from \"./app.js\";\nimport type { MischiefRouteOptions } from \"./app.js\";\nimport { contentAssetsForBuild } from \"./asset-deployment.js\";\nimport { feedbackGatewayBuild } from \"./auth/build-options.js\";\nimport type { feedbackAccess } from \"./auth/feedback-access.js\";\nimport { feedbackInfrastructure } from \"./auth/infrastructure.js\";\nimport { staticAssetGeneration } from \"./bundled-content.generated.js\";\nimport { mischiefConfigFingerprint } from \"./config-fingerprint.js\";\nimport { ContentStore } from \"./content-store.js\";\nimport CrashTail from \"./crash-tail.js\";\nimport { ErrorPageRenderer, websiteErrorPages } from \"./error-page-renderer.js\";\nimport { events as eventsFor } from \"./events.js\";\nimport { flagsLayer, liveFlagsLayer } from \"./flags.js\";\nimport { instituteStage, withInstitute } from \"./institute-mount.js\";\nimport { intakeApplicationsLayer } from \"./interest/applications.js\";\nimport { interestDirectoryLayer } from \"./interest/directory.js\";\nimport {\n SWEEP_PENDING_INTAKE_CRON,\n deliveryDeadlineLayer,\n scheduleIntakeSweep,\n} from \"./interest/intake-sweep.js\";\nimport Interest from \"./interest/interest-durable-object.js\";\nimport InterestIndex from \"./interest/interest-index-durable-object.js\";\nimport { agentSignupLayer } from \"./interest/join-layer.js\";\nimport type { AgentSignupOptions } from \"./interest/join-layer.js\";\nimport { interestOperatorOptions } from \"./interest/operator-options.js\";\nimport LegacyMcp from \"./legacy-mcp/durable-object.js\";\nimport { LEGACY_SESSION_HEADER } from \"./legacy-mcp/session.js\";\nimport {\n privateTelemetry,\n traceObservability,\n traceSettings,\n} from \"./observability.js\";\nimport { outerHttpPrivacyRegistration } from \"./outer-http-privacy.js\";\nimport { rateLimitsFrom, rateLimitDeclarations } from \"./rate-limits.js\";\nimport type { RateLimitBindings } from \"./rate-limits.js\";\nimport { withReaderWebsite } from \"./reader-website.js\";\nimport {\n logRequestIncident,\n observeRequestIncidents,\n} from \"./request-incidents.js\";\nimport { observeRequestLog } from \"./request-log.js\";\nimport { layerWorkerLoader, sandboxLimits } from \"./sandbox-loader.js\";\nimport type { WorkerLoaderBinding } from \"./sandbox-worker-loader.js\";\nimport { AssetBindingSchema, StaticAssets } from \"./static-assets.js\";\nimport {\n chromeWebMcpTrialToken,\n edgeWebMcpTrialToken,\n withWebMcpOriginTrials,\n} from \"./web-mcp-origin-trials.js\";\n\nconst cloudflareStaticCache = {\n match: (request: Request) => caches.default.match(request),\n put: (request: Request, response: Response) =>\n caches.default.put(request, response),\n};\n\nconst inBackground = (effect: Effect.Effect) =>\n Effect.gen(function* registerBackgroundWork() {\n const execution = yield* Cloudflare.WorkerExecutionContext;\n\n yield* execution.waitUntil(effect);\n });\n\nexport type RequestCapture = (\n settings: RequestCaptureSettings\n) => (\n app: Effect.Effect\n) => Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n E,\n R | RB | HttpServerRequest.HttpServerRequest\n>;\n\nexport const makeMischief = (\n legacyMcp: NonNullable,\n interestDirectory: Layer.Layer,\n capture?: RequestCapture,\n agentSignup?: AgentSignupOptions,\n feedback?: ReturnType,\n liveFlags?: Flags[\"Service\"]\n) =>\n Effect.gen(function* makeMischiefInit() {\n if (globalThis.__ALCHEMY_RUNTIME__ !== true) {\n const stageRateLimits = rateLimitDeclarations(yield* Stage);\n yield* Cloudflare.RateLimit(\"API_PER_IP\", stageRateLimits.API_PER_IP);\n yield* Cloudflare.RateLimit(\n \"EXECUTE_GLOBAL\",\n stageRateLimits.EXECUTE_GLOBAL\n );\n yield* Cloudflare.RateLimit(\n \"EXECUTE_PER_IP\",\n stageRateLimits.EXECUTE_PER_IP\n );\n yield* Cloudflare.RateLimit(\n \"INTEREST_PER_IP\",\n stageRateLimits.INTEREST_PER_IP\n );\n }\n\n const webBotAuthEnabled = yield* Config.Boolean(\n \"WEB_BOT_AUTH_ENABLED\"\n ).pipe(Config.withDefault(false));\n\n const webBotAuthPrivateJwk = yield* Config.option(\n Config.Redacted(\"WEB_BOT_AUTH_PRIVATE_JWK\")\n );\n\n const interestMode = yield* Config.schema(\n Schema.Literals([\"capture\", \"doi\", \"drovr\"]),\n \"INTEREST_MODE\"\n ).pipe(Config.withDefault(\"doi\" as const));\n\n const interestTokenSecret = yield* Config.option(\n Config.Redacted(\"INTEREST_TOKEN_SECRET\")\n );\n\n const interestOperatorToken = yield* Config.option(\n Config.Redacted(\"INTEREST_OPERATOR_TOKEN\")\n );\n\n const drovrIntakeUrl = yield* Config.option(\n Config.String(\"DROVR_INTAKE_URL\")\n );\n\n const drovrIntakeTimeoutSeconds = yield* Config.option(\n Config.schema(\n Schema.Int.check(Schema.isBetween({ maximum: 60, minimum: 1 })),\n \"DROVR_INTAKE_TIMEOUT_SECONDS\"\n )\n );\n\n const joinDeliveryDeadlineSeconds = yield* Config.option(\n Config.schema(\n Schema.Int.check(Schema.isBetween({ maximum: 28, minimum: 5 })),\n \"JOIN_DELIVERY_DEADLINE_SECONDS\"\n )\n );\n\n const drovrApiBase = yield* Config.option(Config.String(\"DROVR_API_BASE\"));\n\n const drovrAgentIntakeCredential = yield* Config.option(\n Config.Redacted(\"DROVR_AGENT_INTAKE_CREDENTIAL\")\n );\n\n const drovrIntakeCredential = yield* Config.option(\n Config.Redacted(\"DROVR_INTAKE_CREDENTIAL\")\n );\n\n const identityMode = yield* Flags.use((flags) =>\n flags.get(eventsIdentityMode, {}).pipe(Effect.orDie)\n ).pipe(Effect.provide(flagsLayer));\n\n const environment = yield* Cloudflare.WorkerEnvironment;\n\n // SAFETY: these are the native runtime bindings declared above. Alchemy types the environment as a dictionary it fills in at runtime, so this is the one boundary cast.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Alchemy types the Worker environment as a dictionary, so the declared bindings need one boundary cast.\n const bindings = environment as RateLimitBindings & {\n readonly CODE_SANDBOX: WorkerLoaderBinding;\n };\n\n const loader = bindings.CODE_SANDBOX;\n\n const rateLimits = rateLimitsFrom({\n API_PER_IP: bindings.API_PER_IP,\n EXECUTE_GLOBAL: bindings.EXECUTE_GLOBAL,\n EXECUTE_PER_IP: bindings.EXECUTE_PER_IP,\n INTEREST_PER_IP: bindings.INTEREST_PER_IP,\n });\n\n const interestServices = Option.isNone(interestTokenSecret)\n ? undefined\n : yield* Layer.build(\n Layer.mergeAll(\n interestDirectory,\n InterestTokens.layer(interestTokenSecret.value),\n InterestMode.layer(interestMode),\n subscriberDeliveryLayer({\n agentIntake: {\n credential: drovrAgentIntakeCredential,\n url: drovrIntakeUrl,\n },\n confirm: {\n base: drovrApiBase,\n credential: drovrIntakeCredential,\n },\n intake: {\n credential: drovrIntakeCredential,\n url: drovrIntakeUrl,\n },\n intakeTimeout: drovrIntakeTimeoutSeconds.pipe(\n Option.map(Duration.seconds),\n Option.getOrUndefined\n ),\n })\n )\n );\n\n const interest =\n interestServices === undefined\n ? undefined\n : {\n operatorToken: interestOperatorToken.pipe(\n Option.map(Redacted.value),\n Option.getOrUndefined\n ),\n services: interestServices,\n };\n\n const joinServices =\n agentSignup !== undefined && interestServices !== undefined\n ? yield* Layer.build(\n agentSignupLayer(agentSignup, interestServices).pipe(\n Layer.provide(deliveryDeadlineLayer(joinDeliveryDeadlineSeconds))\n )\n )\n : undefined;\n\n yield* scheduleIntakeSweep(agentSignup, joinServices);\n\n const operatorOptions = yield* interestOperatorOptions(\n agentSignup,\n joinServices\n );\n\n const assetBinding = Schema.decodeUnknownOption(AssetBindingSchema)(\n environment.ASSETS\n );\n\n const assets = Option.isNone(assetBinding)\n ? undefined\n : yield* StaticAssets.pipe(\n Effect.provide(StaticAssets.layer(assetBinding.value))\n );\n\n const contentStore = yield* ContentStore.pipe(\n Effect.provide(\n ContentStore.layer.pipe(\n Layer.provide(\n Layer.succeed(\n StaticAssets,\n assets ??\n Option.getOrElse(\n yield* Effect.serviceOption(StaticAssets),\n () => StaticAssets.unavailable\n )\n )\n )\n )\n )\n );\n\n const workerRoutes = mischiefRoutes({\n assets,\n contentStore,\n feedback,\n flags: liveFlags,\n interest:\n interest === undefined\n ? undefined\n : { ...interest, ...operatorOptions },\n joinTokens: interestServices,\n legacyMcp,\n rateLimits,\n staticCache: cloudflareStaticCache,\n webBotAuth: {\n enabled: webBotAuthEnabled,\n privateJwk: webBotAuthPrivateJwk.pipe(\n Option.map(Redacted.value),\n Option.getOrUndefined\n ),\n },\n }).pipe(\n Layer.provide(layerWorkerLoader(loader, sandboxLimits)),\n Layer.provide(\n joinServices === undefined\n ? Layer.empty\n : Layer.succeedContext(joinServices)\n )\n );\n\n const website = Schema.decodeUnknownEffect(AssetBindingSchema)(\n environment.WEBSITE\n );\n\n const app = (yield* HttpRouter.toHttpEffect(workerRoutes).pipe(\n Effect.orDie\n )).pipe(\n Effect.provideService(ErrorPageRenderer, websiteErrorPages(website))\n );\n\n const chromeToken = yield* chromeWebMcpTrialToken;\n const edgeToken = yield* edgeWebMcpTrialToken;\n\n const readerApp = withInstitute({\n ALCHEMY_STAGE: environment.ALCHEMY_STAGE,\n INSTITUTE: environment.INSTITUTE,\n INSTITUTE_ENABLED: environment.INSTITUTE_ENABLED,\n })(\n withReaderWebsite(\n website.pipe(Effect.orDie),\n withWebMcpOriginTrials(\n [chromeToken, edgeToken],\n readerResponseHeaders(contentStore)\n )\n )(app)\n );\n\n return {\n fetch: observeRequestLog(\n observeRequestIncidents(\n capture === undefined\n ? readerApp\n : Effect.gen(function* captureWithLiveIdentity() {\n const currentIdentity =\n liveFlags === undefined\n ? identityMode\n : yield* liveFlags\n .get(eventsIdentityMode, {})\n .pipe(\n Effect.catch((error) =>\n Effect.logError(\n \"Flag read failed; using Config fallback.\",\n error\n ).pipe(Effect.andThen(Effect.succeed(identityMode)))\n )\n );\n\n return yield* capture({\n captureCity: true,\n identityMode: currentIdentity,\n runInBackground: inBackground,\n })(readerApp);\n })\n ).pipe(Effect.provide(webCryptoLayer))\n ),\n };\n });\n\nconst makeMischiefWorker = Effect.gen(function* makeMischiefWorker() {\n if (globalThis.__ALCHEMY_RUNTIME__ !== true) {\n yield* Cloudflare.WorkerLoader(\"CODE_SANDBOX\");\n }\n\n const feedback = (yield* feedbackInfrastructure).pipe(Option.getOrUndefined);\n const liveFlags = yield* Flags.pipe(Effect.provide(liveFlagsLayer));\n\n const legacyMcp = yield* LegacyMcp;\n const interests = yield* Interest;\n const interestIndex = yield* InterestIndex;\n const sweepCron = yield* Cloudflare.Workers.CronEventSource;\n\n const tokenSecret = yield* Config.option(\n Config.Redacted(\"INTEREST_TOKEN_SECRET\")\n );\n\n const typesafeApiKey = yield* Config.option(\n Config.Redacted(\"TYPESAFE_API_KEY\")\n );\n\n const agentSignup = Option.isNone(tokenSecret)\n ? undefined\n : ({\n applications: intakeApplicationsLayer(\n () => interestIndex.getByName(\"index\").applicationIds(),\n (actor) => interests.getByName(intakeInstance(actor))\n ),\n applicationIds: () => interestIndex.getByName(\"index\").applicationIds(),\n contacts: (submissionId: string) =>\n interests.getByName(`join:${submissionId}`),\n intake: intakeLiveLayer({\n interests: (name) => interests.getByName(name),\n tokenSecret: tokenSecret.value,\n typesafeApiKey,\n }).pipe(Layer.provide(FetchHttpClient.layer)),\n markPending: (submissionId, pending) =>\n interestIndex.getByName(\"index\").markPending(submissionId, pending),\n noteApplication: (submissionId) =>\n interestIndex.getByName(\"index\").noteApplication(submissionId),\n sweep: {\n ids: () => interestIndex.getByName(\"index\").pendingIds(),\n schedule: (run) => sweepCron(SWEEP_PENDING_INTAKE_CRON, () => run),\n },\n } satisfies AgentSignupOptions | undefined);\n\n const enabled = yield* Flags.use((flags) =>\n flags.get(eventsEnabled, {}).pipe(Effect.orDie)\n ).pipe(Effect.provide(flagsLayer));\n\n const capture = yield* eventsFor({ enabled, id: \"Mischief\" });\n\n return yield* makeMischief(\n {\n forward: (session, request) => {\n const headers = new Headers(request.headers);\n headers.set(LEGACY_SESSION_HEADER, session);\n\n return legacyMcp\n .getByName(session)\n .fetch(HttpServerRequest.fromWeb(new Request(request, { headers })))\n .pipe(\n Effect.map((response) => HttpServerResponse.toWeb(response)),\n Effect.orDie\n );\n },\n },\n interestDirectoryLayer(\n (address) => interests.getByName(address),\n () => interestIndex.getByName(\"index\")\n ),\n capture,\n agentSignup,\n feedback,\n liveFlags\n );\n}).pipe(\n Effect.provide(\n Layer.mergeAll(\n Cloudflare.Workers.RateLimitBinding,\n Cloudflare.Workers.FetchBinding,\n Cloudflare.Workers.CronEventSourceLive,\n outerHttpPrivacyRegistration,\n privateTelemetry\n )\n ),\n Effect.tapCause((cause) =>\n logRequestIncident(cause, \"initialization\").pipe(\n Effect.provide(webCryptoLayer),\n Effect.asVoid\n )\n )\n);\n\nexport default class Mischief extends Cloudflare.Worker()(\n \"Mischief\",\n Effect.gen(function* mischiefProps() {\n const traces = yield* traceSettings.pipe(Effect.orDie);\n const stage = yield* Stage;\n\n const instituteEnabled = yield* Config.Boolean(\"INSTITUTE_ENABLED\").pipe(\n Config.withDefault(false)\n );\n\n const assets = yield* contentAssetsForBuild(\n new URL(\"../dist/content\", import.meta.url).pathname,\n staticAssetGeneration\n ).pipe(Effect.orDie);\n\n const env = {\n MISCHIEF_CONFIG_FINGERPRINT: mischiefConfigFingerprint,\n WEB_MCP_CHROME_TRIAL_TOKEN: chromeWebMcpTrialToken,\n WEB_MCP_EDGE_TRIAL_TOKEN: edgeWebMcpTrialToken,\n };\n\n return {\n assets,\n build: feedbackGatewayBuild,\n compatibility: { date: traces.enabled ? \"2026-07-28\" : \"2026-05-28\" },\n dev: { port: 1337 },\n ...(stage === instituteStage\n ? { workersDev: { enabled: false, previewsEnabled: false } }\n : { domain: { name: \"ratstack.sh\", redirects: [\"www.ratstack.sh\"] } }),\n env: instituteEnabled ? { ...env, INSTITUTE_ENABLED: \"true\" } : env,\n main: import.meta.url,\n observability: traceObservability(traces),\n tailConsumers: [yield* CrashTail],\n };\n }),\n makeMischiefWorker\n) {}\n", "[\"rat-stack\",\"show\",\"HEAD:apps/web/src/client/docs/command.ts\"]": "import { ResourceNotFound } from \"@rat-stack/core/contracts\";\nimport { Effect, Option, Schema } from \"effect\";\nimport { Command } from \"foldkit\";\nimport { load, pushUrl, replaceUrl } from \"foldkit/navigation\";\nimport { fromString } from \"foldkit/url\";\n\nimport { Message } from \"./message.js\";\nimport { DocumentQueries } from \"./queries.js\";\n\nexport const SearchDocs = Command.define(\"SearchDocs\", {\n args: { generation: Schema.Finite, query: Schema.String },\n execute: ({ query, generation }) =>\n DocumentQueries.use((queries) => queries.search(query)).pipe(\n Effect.map((result) => Message.SucceededSearch({ generation, result })),\n Effect.orElseSucceed(() => Message.FailedSearch({ generation }))\n ),\n messages: [Message.SucceededSearch, Message.FailedSearch],\n});\n\nexport const ReadDoc = Command.define(\"ReadDoc\", {\n args: { generation: Schema.Finite, id: Schema.String },\n execute: ({ id, generation }) =>\n DocumentQueries.use((queries) => queries.read(id)).pipe(\n Effect.match({\n onFailure: (error) =>\n Message.FailedRead({\n generation,\n message: Schema.is(ResourceNotFound)(error)\n ? error.message\n : \"The document could not be loaded. Try again in a moment.\",\n notFound: Schema.is(ResourceNotFound)(error),\n }),\n onSuccess: (document) =>\n Message.SucceededRead({ document, generation }),\n })\n ),\n messages: [Message.SucceededRead, Message.FailedRead],\n});\n\nexport const Navigate = Command.define(\"Navigate\", {\n args: { url: Schema.String },\n execute: ({ url }) =>\n pushUrl(url).pipe(\n Effect.andThen(\n Effect.sync(() => {\n window.scrollTo(0, 0);\n })\n ),\n Effect.as(Message.CompletedNavigate())\n ),\n messages: [Message.CompletedNavigate],\n});\n\nexport const ReadLocation = Command.define(\"ReadLocation\", {\n execute: Effect.sync(() =>\n Option.match(fromString(window.location.href), {\n onNone: () => Message.CompletedNavigate(),\n onSome: (url) => Message.ChangedUrl({ url }),\n })\n ),\n messages: [Message.ChangedUrl, Message.CompletedNavigate],\n});\n\nexport const ReplaceUrl = Command.define(\"ReplaceUrl\", {\n args: { url: Schema.String },\n execute: ({ url }) =>\n replaceUrl(url).pipe(Effect.as(Message.CompletedNavigate())),\n messages: [Message.CompletedNavigate],\n});\n\nexport const LoadExternal = Command.define(\"LoadExternal\", {\n args: { href: Schema.String },\n execute: ({ href }) =>\n load(href).pipe(Effect.as(Message.CompletedLoadExternal())),\n messages: [Message.CompletedLoadExternal],\n});\n", "[\"rat-stack\",\"show\",\"HEAD:apps/web/src/client/docs/message.ts\"]": "import { ReadOutput, SearchOutput } from \"@rat-stack/core/contracts\";\nimport { Schema } from \"effect\";\nimport { defineMessageUnion } from \"foldkit/message\";\nimport { UrlRequest } from \"foldkit/navigation\";\nimport { Url } from \"foldkit/url\";\n\nexport const Message = defineMessageUnion({\n ChangedUrl: { url: Url },\n ClickedLink: { request: UrlRequest },\n CompletedLoadExternal: {},\n CompletedNavigate: {},\n FailedRead: {\n generation: Schema.Finite,\n message: Schema.String,\n notFound: Schema.Boolean,\n },\n FailedSearch: { generation: Schema.Finite },\n SubmittedSearch: {},\n SucceededRead: { document: ReadOutput, generation: Schema.Finite },\n SucceededSearch: { generation: Schema.Finite, result: SearchOutput },\n UpdatedQuery: { value: Schema.String },\n});\n\nexport type AppMessage = typeof Message.Type;\n", "[\"rat-stack\",\"show\",\"HEAD:apps/web/src/client/docs/queries.ts\"]": "import { toRpcGroup } from \"@rat-stack/capability/rpc-group\";\nimport { readContract, searchContract } from \"@rat-stack/core/contracts\";\nimport { Cache, Context, Effect, Layer } from \"effect\";\nimport { RpcClient } from \"effect/rpc\";\n\nimport { readerRpcProtocol } from \"../rpc.js\";\n\nconst { group } = toRpcGroup([searchContract, readContract]);\n\nconst make = Effect.gen(function* makeDocumentQueries() {\n const client = yield* RpcClient.make(group).pipe(\n Effect.provide(readerRpcProtocol)\n );\n\n const search = yield* Cache.make({\n capacity: Number.POSITIVE_INFINITY,\n lookup: (query: string) => client.search({ limit: 10, query }),\n timeToLive: \"30 seconds\",\n });\n\n const read = yield* Cache.make({\n capacity: Number.POSITIVE_INFINITY,\n lookup: (id: string) => client.read({ id }),\n });\n\n return {\n read: (id: string) => Cache.get(read, id),\n search: (query: string) => Cache.get(search, query),\n };\n});\n\nexport class DocumentQueries extends Context.Service<\n DocumentQueries,\n Effect.Success\n>()(\"@rat-stack/web/DocumentQueries\", { make }) {\n static readonly layer = Layer.effect(this, this.make);\n}\n", diff --git a/.env.schema b/.env.schema index 0f466def..03fc8dba 100644 --- a/.env.schema +++ b/.env.schema @@ -108,6 +108,16 @@ PREVIEW_ORIGIN= # @sensitive=false AUTH_ENABLED=false +# Optional absolute path to an already built Institute dist directory. Unset declares no Institute. +# @type=string +# @sensitive=false +INSTITUTE_ARTIFACT= + +# Enable Mischief dispatch only if an Institute service binding is also present. +# @type=boolean +# @sensitive=false +INSTITUTE_ENABLED=false + # Native Effect tracing is opt-in. Cloudflare owns head sampling and export. # @type=boolean # @sensitive=false diff --git a/apps/infra/alchemy.run.ts b/apps/infra/alchemy.run.ts index 984d1fe6..9eb0c5ac 100644 --- a/apps/infra/alchemy.run.ts +++ b/apps/infra/alchemy.run.ts @@ -14,11 +14,36 @@ import * as Redacted from "effect/Redacted"; import * as Schema from "effect/Schema"; import privateAuth from "../site/src/auth/private-worker.js"; +import { instituteStage } from "../site/src/institute-mount.js"; import Mischief from "../site/src/worker.js"; import Workshop from "../site/src/workshop-worker.js"; import { Website } from "../web/src/website.js"; +import { instituteWorker } from "./src/institute.js"; import { ratstackState } from "./src/state-store.js"; +const gateway = Effect.gen(function* declareGateway() { + const website = yield* Website; + const mischief = yield* Mischief; + + yield* mischief.bind`${website}`({ + bindings: [ + { name: "WEBSITE", service: website.workerName, type: "service" }, + ], + }); + + const institute = yield* instituteWorker; + + if (institute !== null) { + yield* mischief.bind`${institute}`({ + bindings: [ + { name: "INSTITUTE", service: institute.workerName, type: "service" }, + ], + }); + } + + return { mischiefUrl: mischief.url, websiteUrl: website.url }; +}); + export default Alchemy.Stack( "RatStack", { @@ -30,6 +55,12 @@ export default Alchemy.Stack( state: ratstackState(), }, Effect.gen(function* stack() { + const stage = yield* Stage; + + if (stage === instituteStage) { + return { ...(yield* gateway), catalogUrl: undefined }; + } + const dev = yield* Alchemy.ALCHEMY_DEV; if (!dev) { @@ -157,28 +188,14 @@ export default Alchemy.Stack( ); } - const website = yield* Website; - - const mischief = yield* Mischief; + const gatewayUrls = yield* gateway; yield* Workshop; yield* turboCache; - const catalog = yield* CatalogWorker.pipe( - retain(Stage.pipe(Effect.map((stage) => stage === "prod"))) - ); - - yield* mischief.bind`${website}`({ - bindings: [ - { name: "WEBSITE", service: website.workerName, type: "service" }, - ], - }); + const catalog = yield* CatalogWorker.pipe(retain(stage === "prod")); - return { - catalogUrl: catalog.url, - mischiefUrl: mischief.url, - websiteUrl: website.url, - }; + return { ...gatewayUrls, catalogUrl: catalog.url }; }).pipe( Effect.provide( Layer.unwrap( diff --git a/apps/infra/src/institute.ts b/apps/infra/src/institute.ts new file mode 100644 index 00000000..8e477c8e --- /dev/null +++ b/apps/infra/src/institute.ts @@ -0,0 +1,35 @@ +import * as Cloudflare from "@alchemy.run/cloudflare"; +import { Config, Effect, Option, Path, Schema } from "effect"; + +import { silentObservability } from "../../site/src/observability.js"; + +export const instituteWorker = Effect.gen(function* declareInstitute() { + const path = yield* Path.Path; + + const artifact = yield* Config.option( + Config.schema( + Schema.String.check( + Schema.makeFilter((directory) => path.isAbsolute(directory)) + ), + "INSTITUTE_ARTIFACT" + ) + ); + + if (Option.isSome(artifact)) { + return yield* Cloudflare.Worker("Institute", { + assets: { + directory: path.join(artifact.value, "client"), + notFoundHandling: "none", + runWorkerFirst: ["/institute/content/*"], + }, + bundle: false, + compatibility: { date: "2026-05-25", flags: ["nodejs_compat"] }, + main: path.join(artifact.value, "server/index.js"), + observability: silentObservability, + rules: [{ globs: ["**/*.js", "**/*.mjs"] }], + workersDev: { enabled: false, previewsEnabled: false }, + }); + } + + return null; +}); diff --git a/apps/infra/test/institute-binding.test.ts b/apps/infra/test/institute-binding.test.ts new file mode 100644 index 00000000..2de9d8b9 --- /dev/null +++ b/apps/infra/test/institute-binding.test.ts @@ -0,0 +1,217 @@ +import * as Cloudflare from "@alchemy.run/cloudflare"; +import { NodeServices } from "@effect/platform-node"; +import { expect, it } from "@effect/vitest"; +import { AuthProviders, Stage } from "alchemy"; +import { AlchemyContextLive } from "alchemy/AlchemyContext"; +import { + Artifacts, + createArtifactStore, + makeScopedArtifacts, +} from "alchemy/Artifacts"; +import * as Output from "alchemy/Output"; +import { + ConfigProvider, + Effect, + FileSystem, + Layer, + Path, + Schema, +} from "effect"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as HttpClient from "effect/http/HttpClient"; + +import { instituteStage } from "../../site/src/institute-mount.js"; +import stack from "../alchemy.run.js"; + +const services = Layer.mergeAll( + AlchemyContextLive, + Layer.succeed(AuthProviders, {}), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => + Effect.die("Institute declarations must not call the provider") + ) + ) +).pipe( + Layer.provideMerge( + Layer.mergeAll( + NodeServices.layer, + SecureRandom.layerWebCrypto, + Digest.layerWebCrypto + ) + ) +); + +const compile = (stage: string, artifact?: string) => + stack.pipe( + Effect.provide(services), + Effect.provideService(Stage, stage), + Effect.provide( + ConfigProvider.layer( + ConfigProvider.fromUnknown({ + EMAIL_FORWARD_TO: "forward@example.test", + INSTITUTE_ARTIFACT: artifact, + INSTITUTE_ENABLED: artifact !== undefined, + }) + ) + ) + ); + +it.effect( + "does not change Mischief bindings or declare Institute without an artifact", + () => + Effect.gen(function* checkDefault() { + const compiled = yield* compile("prod"); + expect(compiled.resources.Institute).toBeUndefined(); + expect(compiled.resources.Mischief?.Props).not.toHaveProperty( + "env.INSTITUTE_ENABLED" + ); + expect( + compiled.bindings.Mischief?.some( + (binding) => binding.sid === "Institute" + ) + ).toBe(false); + }) +); + +const InstituteProps = Schema.Struct({ + assets: Schema.Struct({ + base: Schema.optionalKey(Schema.String), + directory: Schema.String, + notFoundHandling: Schema.Literal("none"), + runWorkerFirst: Schema.Array(Schema.String), + }), + bundle: Schema.Literal(false), + main: Schema.String, + rules: Schema.Array(Schema.Struct({ globs: Schema.Array(Schema.String) })), +}); + +it.effect( + "binds the prebuilt modules and mounted assets without creating a public stage or declaring production DNS", + () => + Effect.gen(function* checkMount() { + const fs = yield* FileSystem.FileSystem; + const { join } = yield* Path.Path; + + const artifact = yield* fs.makeTempDirectoryScoped({ + prefix: "institute-dist-", + }); + + yield* fs.makeDirectory(join(artifact, "server/assets"), { + recursive: true, + }); + yield* fs.makeDirectory(join(artifact, "client/institute/content"), { + recursive: true, + }); + yield* fs.writeFileString( + join(artifact, "server/index.js"), + 'export { default } from "./assets/ssr.js";' + ); + yield* fs.writeFileString( + join(artifact, "server/assets/ssr.js"), + 'export default { fetch: () => new Response("institute") };' + ); + yield* fs.writeFileString(join(artifact, "server/index.js.map"), "{}"); + yield* fs.writeFileString(join(artifact, "server/wrangler.json"), "{}"); + yield* fs.writeFileString( + join(artifact, "client/institute/content/manifest.json"), + "{}" + ); + + const compiled = yield* compile(instituteStage, artifact); + + expect(compiled.resources.Workshop).toBeUndefined(); + expect(compiled.resources.Mischief?.Props).toHaveProperty( + "env.INSTITUTE_ENABLED", + "true" + ); + expect( + Object.values(compiled.resources).filter((resource) => + /^Cloudflare\.(?:DNS\.|Email\.|Zone$)/u.test(resource.Type) + ) + ).toEqual([]); + + for (const id of ["Institute", "Mischief"]) { + const props: unknown = compiled.resources[id]?.Props; + expect(props).toMatchObject({ + workersDev: { enabled: false, previewsEnabled: false }, + }); + expect(props).not.toHaveProperty("domain"); + expect(props).not.toHaveProperty("routes"); + } + + const binding = yield* Schema.decodeUnknownEffect( + Schema.Struct({ + bindings: Schema.Tuple([ + Schema.Struct({ + name: Schema.Literal("INSTITUTE"), + service: Schema.Unknown, + type: Schema.Literal("service"), + }), + ]), + }) + )( + compiled.bindings.Mischief?.find((entry) => entry.sid === "Institute") + ?.data + ); + + expect( + Output.resolveUpstream(binding.bindings[0].service) + ).toHaveProperty("Institute"); + expect( + compiled.bindings.Mischief?.find((entry) => entry.sid === "Website") + ?.data + ).toMatchObject({ + bindings: [{ name: "WEBSITE", type: "service" }], + }); + + const props = yield* Schema.decodeUnknownEffect(InstituteProps)( + compiled.resources.Institute?.Props + ); + + const workerProps = { + ...props, + assets: { + ...props.assets, + runWorkerFirst: [...props.assets.runWorkerFirst], + }, + rules: [...props.rules], + } satisfies Cloudflare.Workers.WorkerProps; + + const source = yield* Cloudflare.Workers.resolveSource(workerProps); + + const output = yield* source.build( + Cloudflare.Workers.makeSourceContext({ + compatibility: { date: "2026-05-25", flags: ["nodejs_compat"] }, + fqn: "Institute", + id: "Institute", + props: workerProps, + stack: { name: "RatStack", stage: instituteStage }, + workerName: "fixture-institute", + }) + ); + + expect(output.bundle?.files.map((file) => file.path)).toEqual([ + "index.js", + "assets/ssr.js", + ]); + + const assets = yield* Cloudflare.Workers.readAssets(workerProps.assets); + + expect(Object.keys(assets.manifest)).toEqual([ + "/institute/content/manifest.json", + ]); + expect(workerProps.assets.runWorkerFirst).toEqual([ + "/institute/content/*", + ]); + }).pipe( + Effect.provide(services), + Effect.provideServiceEffect( + Artifacts, + Effect.sync(() => + makeScopedArtifacts(createArtifactStore(), "Institute") + ) + ) + ) +); diff --git a/apps/site/src/institute-mount.ts b/apps/site/src/institute-mount.ts new file mode 100644 index 00000000..cc0eff0b --- /dev/null +++ b/apps/site/src/institute-mount.ts @@ -0,0 +1,62 @@ +import { Effect, Option, Schema } from "effect"; +import * as HttpServerRequest from "effect/http/HttpServerRequest"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +import { AssetBindingSchema } from "./static-assets.js"; + +export const instituteStage = "institute-private"; + +export const withInstitute = (environment: { + readonly ALCHEMY_STAGE?: unknown; + readonly INSTITUTE?: unknown; + readonly INSTITUTE_ENABLED?: unknown; +}) => { + const binding = Schema.decodeUnknownOption(AssetBindingSchema)( + environment.INSTITUTE + ); + + const enabled = environment.INSTITUTE_ENABLED === "true"; + const privateStage = environment.ALCHEMY_STAGE === instituteStage; + + return ( + fallback: Effect.Effect + ) => { + const dispatch = + !enabled || Option.isNone(binding) + ? fallback + : Effect.gen(function* routeInstitute() { + const request = yield* HttpServerRequest.HttpServerRequest; + + const original = yield* HttpServerRequest.toWeb(request).pipe( + Effect.orDie + ); + + const { hostname, pathname } = new URL(original.url); + + const allowedHost = + hostname === "ratstack.sh" || + (privateStage && hostname !== "www.ratstack.sh"); + + if ( + !allowedHost || + (pathname !== "/institute" && !pathname.startsWith("/institute/")) + ) { + return yield* fallback; + } + + const institute = binding.value; + + const response = yield* Effect.promise( + institute.fetch.bind(institute, original) + ); + + return HttpServerResponse.fromWeb(response); + }); + + return privateStage + ? dispatch.pipe( + Effect.map(HttpServerResponse.setHeader("x-robots-tag", "noindex")) + ) + : dispatch; + }; +}; diff --git a/apps/site/src/worker.ts b/apps/site/src/worker.ts index 522261d9..e7476cd8 100644 --- a/apps/site/src/worker.ts +++ b/apps/site/src/worker.ts @@ -35,6 +35,7 @@ import CrashTail from "./crash-tail.js"; import { ErrorPageRenderer, websiteErrorPages } from "./error-page-renderer.js"; import { events as eventsFor } from "./events.js"; import { flagsLayer, liveFlagsLayer } from "./flags.js"; +import { instituteStage, withInstitute } from "./institute-mount.js"; import { intakeApplicationsLayer } from "./interest/applications.js"; import { interestDirectoryLayer } from "./interest/directory.js"; import { @@ -315,13 +316,19 @@ export const makeMischief = ( const chromeToken = yield* chromeWebMcpTrialToken; const edgeToken = yield* edgeWebMcpTrialToken; - const readerApp = withReaderWebsite( - website.pipe(Effect.orDie), - withWebMcpOriginTrials( - [chromeToken, edgeToken], - readerResponseHeaders(contentStore) - ) - )(app); + const readerApp = withInstitute({ + ALCHEMY_STAGE: environment.ALCHEMY_STAGE, + INSTITUTE: environment.INSTITUTE, + INSTITUTE_ENABLED: environment.INSTITUTE_ENABLED, + })( + withReaderWebsite( + website.pipe(Effect.orDie), + withWebMcpOriginTrials( + [chromeToken, edgeToken], + readerResponseHeaders(contentStore) + ) + )(app) + ); return { fetch: observeRequestLog( @@ -452,23 +459,32 @@ export default class Mischief extends Cloudflare.Worker()( "Mischief", Effect.gen(function* mischiefProps() { const traces = yield* traceSettings.pipe(Effect.orDie); + const stage = yield* Stage; + + const instituteEnabled = yield* Config.Boolean("INSTITUTE_ENABLED").pipe( + Config.withDefault(false) + ); const assets = yield* contentAssetsForBuild( new URL("../dist/content", import.meta.url).pathname, staticAssetGeneration ).pipe(Effect.orDie); + const env = { + MISCHIEF_CONFIG_FINGERPRINT: mischiefConfigFingerprint, + WEB_MCP_CHROME_TRIAL_TOKEN: chromeWebMcpTrialToken, + WEB_MCP_EDGE_TRIAL_TOKEN: edgeWebMcpTrialToken, + }; + return { assets, build: feedbackGatewayBuild, compatibility: { date: traces.enabled ? "2026-07-28" : "2026-05-28" }, dev: { port: 1337 }, - domain: { name: "ratstack.sh", redirects: ["www.ratstack.sh"] }, - env: { - MISCHIEF_CONFIG_FINGERPRINT: mischiefConfigFingerprint, - WEB_MCP_CHROME_TRIAL_TOKEN: chromeWebMcpTrialToken, - WEB_MCP_EDGE_TRIAL_TOKEN: edgeWebMcpTrialToken, - }, + ...(stage === instituteStage + ? { workersDev: { enabled: false, previewsEnabled: false } } + : { domain: { name: "ratstack.sh", redirects: ["www.ratstack.sh"] } }), + env: instituteEnabled ? { ...env, INSTITUTE_ENABLED: "true" } : env, main: import.meta.url, observability: traceObservability(traces), tailConsumers: [yield* CrashTail], diff --git a/apps/site/test/institute-mount.test.ts b/apps/site/test/institute-mount.test.ts new file mode 100644 index 00000000..105aaf26 --- /dev/null +++ b/apps/site/test/institute-mount.test.ts @@ -0,0 +1,118 @@ +import { expect, it } from "@effect/vitest"; +import { Effect, Schema } from "effect"; +import * as HttpServerRequest from "effect/http/HttpServerRequest"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +import { instituteStage, withInstitute } from "../src/institute-mount.js"; + +const fallback = HttpServerResponse.text("Mischief", { status: 404 }); + +const dispatch = ( + request: Request, + environment: Parameters[0] +) => + withInstitute(environment)(Effect.succeed(fallback)).pipe( + Effect.provideService( + HttpServerRequest.HttpServerRequest, + HttpServerRequest.fromWeb(request) + ) + ); + +it.effect.prop( + "mounts only the institute segment on the apex, and only with the switch and service", + { + arbitraryPath: Schema.String, + nestedSegment: Schema.String, + }, + ({ arbitraryPath, nestedSegment }) => + Effect.gen(function* testDispatch() { + for (const [host, path, enabled, hasBinding] of [ + ["ratstack.sh", "/institute", true, true], + ["ratstack.sh", "/institute/", true, true], + ["ratstack.sh", "/institute/content/clip.mp3", true, true], + ["ratstack.sh", `/institute/${nestedSegment}`, true, true], + ["ratstack.sh", "/institutes", true, true], + ["ratstack.sh", "/institute-x", true, true], + ["ratstack.sh", "/lore", true, true], + ["ratstack.sh", `/${arbitraryPath}`, true, true], + ["www.ratstack.sh", "/institute", true, true], + ["other.example.test", "/institute", true, true], + ["ratstack.sh", "/institute", false, true], + ["ratstack.sh", "/institute", true, false], + ] as const) { + const url = new URL(`https://${host}`); + url.pathname = path; + url.searchParams.set("revision", "a/b"); + + const request = new Request(url, { headers: { range: "bytes=0-31" } }); + + const response = yield* dispatch(request, { + INSTITUTE: hasBinding + ? { + fetch: (forwarded: Request) => { + expect(forwarded).toBe(request); + + return Promise.resolve( + new Response("clip", { + headers: { "content-range": "bytes 0-31/100" }, + status: 206, + }) + ); + }, + } + : undefined, + INSTITUTE_ENABLED: enabled ? "true" : undefined, + }); + + if ( + enabled && + hasBinding && + host === "ratstack.sh" && + url.pathname.split("/")[1] === "institute" + ) { + expect(response.status).toBe(206); + expect(response.headers["content-range"]).toBe("bytes 0-31/100"); + expect(response.headers["x-robots-tag"]).toBeUndefined(); + } else { + expect(response).toBe(fallback); + } + } + }) +); + +it.effect( + "keeps the stage noindex and passes the same request body to the service", + () => + Effect.gen(function* proveStage() { + const request = new Request( + "https://stage.example.test/institute?rev=2", + { + body: "payload", + method: "POST", + } + ); + + const response = yield* dispatch(request, { + ALCHEMY_STAGE: instituteStage, + INSTITUTE: { + fetch: (forwarded: Request) => { + expect(forwarded).toBe(request); + + return forwarded.text().then((body) => { + expect(body).toBe("payload"); + + return new Response(null, { + headers: { location: "/institute/intro" }, + status: 307, + }); + }); + }, + }, + INSTITUTE_ENABLED: "true", + }); + + expect(response.status).toBe(307); + expect(response.headers.location).toBe("/institute/intro"); + expect(response.headers["x-robots-tag"]).toBe("noindex"); + }) +);