Build the platform's routers before any request, awaiting nothing; give the fallback draft models room; record smoke's throwaway before init
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Router build (W10-D7): `apps/platform/src/router-build.ts` builds a router's layer with `Effect.runSyncExit` and serves it through `HttpEffect.toWebHandlerWith`, so `serve` and sign-in's handler exist when the Worker module has loaded and no request ever awaits a build another request started. A layer that awaits a promise or a timer while built throws `RouterBuildAwaited` where the handler is made, so the Worker cannot start (or deploy) with one; any other build failure fails each request with its error, as effect's `toWebHandler` did. Request fibers keep the default scheduler (the built context carries no `Scheduler`). - Found: two layers awaited a promise at build. The visibility cartridge's vault imported `MASTER_KEY` through `crypto.subtle.importKey` (now decoded and checked at build, imported per `open`/`put`); the MCP prompt `contribute` hashed the skill's `SKILL.md` through `crypto.subtle.digest` (now made from agent-kit's new `platformSkillParts`, the same name, description and body without the frontmatter hash). - One reasoned escape pair in `router-build.ts`: an assertion that drops `HttpRouter.Request` markers from the layer's requirements (phantom types naming what each request is given, never a build service; effect's own `toWebHandler` casts the same way), with a SAFETY comment, an oxlint disable block and an `unsafeEffectTypeAssertion` escape; and `anyUnknownInErrorContext` on the router's own effect, whose unhandled route errors `toWebHandlerWith` turns into responses (404 for no route). - Fallback models (W10-D8): `modelSettings(model)` in `drafter/binding.ts`; kimi-k2.7-code and any unlisted model keep 12,000 tokens and no reasoning key; glm-5.3 and gpt-oss-120b get 32,000 and `reasoning_effort: "low"`, the chat-call key both input schemas take in `@cloudflare/workers-types` 5.20261006.1 (`Base_Ai_Cf_Zai_Org_Glm_5_3`, `Base_Ai_Cf_Openai_Gpt_Oss_120B`). The settings' `reasoning` is typed `ReasoningInputs` rather than the issue's `Record<string, unknown>`, which `anti-slop/no-unsafe-dictionary-type` refuses. ASSUMPTION until 1009's probe: low effort and 32,000 tokens are enough for the drafting prompt. - Smoke ledger (W10-D12): the loop's init step lists projects as the decider (`projectIsFree`, `<cli> projects`), stops on a taken name with a plain line before anything is made or recorded, writes the `project` and `repo` lines, then runs `init`. The claim fork's line still follows the claim, since its name is known only then (module comment says so). - Tests: `apps/platform/test/router-build.test.ts` (a build is done when the handler is made and no request builds again, counted; a layer awaiting a promise is refused; the Worker module loads with both handlers built and no binding touched; both real compositions build at once over `fakeEnv` and answer `/health`); `packages/visibility/test/vault.test.ts` (the vault builds synchronously); `packages/agent-kit/test/generate.test.ts` (`platformSkillParts` equals what `SKILL.md` says); `packages/drafting/test/binding.test.ts` (settings per model through the fake `AiLike`); `packages/config/test/smoke-loop.test.ts` (a scripted platform: init that fails after making the project leaves both lines; a listed name stops before init and writes nothing). - Outside the stated territory, conflict-free in group A: `packages/visibility/src/vault/webcrypto.ts`, `packages/agent-kit/src/platform.ts`, `surfaces.ts`'s `contribute`, `scripts/lib/smoke/core-loop.ts` (`projectIsFree`), and the new `apps/platform/src/router-build.ts`.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+677 added−75 removed
- tests:+403 added−2 removed
- other:+274 added−73 removed
Provenance
- Commit
ab61611- Tree
211bde1- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
51f046c
14 files changed+677 added−75 removed
modified:apps/platform/src/auth/provider.ts+6 added-6 removed
13 unmodified lines14 */15 import { OAuthAuthorizationServer } from "@cloudflare/workers-oauth-provider";16 import { D1Client } from "@effect/sql-d1";17 import { Context, Layer, Option, Redacted } from "effect";18-import { HttpRouter } from "effect/http";18 19 import { AccountsD1 } from "../adapters/accounts-d1.ts";20 import { WorkerFetch } from "../adapters/fetch.ts";21 import { IdentitiesD1 } from "../adapters/identities-d1.ts";22 import type { TokenReader } from "../adapters/sessions-oauth.ts";23 import type { PlatformConfig } from "../platform.ts";24+import { buildHandler } from "../router-build.ts";25 import { SignInAttemptsBinding } from "./attempts/binding.ts";26 import { GOOGLE_ACCOUNTS, GoogleClient, googleRoutes } from "./google.ts";27 import type { GoogleServices } from "./google.ts";28 import { OAuthStore } from "./oauth-store.ts";45 unmodified lines74 ) => Promise<Response>;75 76 /**77 * The Worker's fetch: OAuth and sign-in in front of `platformFetch`. The78- * sign-in routes are built once from `services` (a failure to build them79- * answers 500 on those paths only); each origin's authorization server is78+ * sign-in routes are built once from `services`, now, awaiting nothing79+ * (`router-build.ts`; a failure to build them answers 500 on those paths80+ * only); each origin's authorization server is81 * made on its first request and kept for the isolate's life (a Worker is82 * reached only on its own hostnames).83 */84 export const oauthProvider = <E>(85 services: Layer.Layer<GoogleServices, E>,86 platformFetch: PlatformFetch87 ) => {87- const { dispose, handler } = HttpRouter.toWebHandler(88- Layer.mergeAll(signInRoutes, googleRoutes).pipe(Layer.provide(services)),89- { disableLogger: true }88+ const { dispose, handler } = buildHandler(89+ Layer.mergeAll(signInRoutes, googleRoutes).pipe(Layer.provide(services))90 );91 92 const servers = new Map<string, OAuthAuthorizationServer<OAuthEnv>>();93 110 unmodified linesadded:apps/platform/src/router-build.ts+102 added
1+/**2+ * A router's fetch handler, built before it answers anything.3+ *4+ * effect's `HttpRouter.toWebHandler` starts the layer's build when the5+ * handler is made and has every request await that one build. On Workers6+ * a request whose client goes away is cancelled where it stands, its7+ * fibers never resumed: had the build awaited I/O a request started, every8+ * later request would wait on it for the isolate's life (the 1101 hang9+ * the code cache once had). Here the build runs at once, synchronously, so10+ * it cannot await anything: a layer that awaits a promise or a timer while11+ * it is built throws where the handler is made, which at module load stops12+ * the Worker from starting (and a deploy from going out). Such work belongs13+ * in the request path, per request. A build that fails otherwise (an env14+ * that did not decode) fails every request with its error, as effect's does.15+ */16+import { Cause, Context, Data, Effect, Exit, Layer, Scope } from "effect";17+import type { HttpServerRequest } from "effect/http";18+import { HttpEffect, HttpRouter } from "effect/http";19+20+/** A router's build awaited a promise or a timer; nothing was served. */21+export class RouterBuildAwaited extends Data.TaggedError("RouterBuildAwaited")<{22+ readonly message: string;23+}> {}24+25+/** What a request needs beyond itself: the services `R`'s routes require of it. */26+type RequestNeeds<A, R> = Exclude<27+ | HttpRouter.Request.Only<"Requires", R>28+ | HttpRouter.Request.Only<"GlobalRequires", R>,29+ A | Scope.Scope | HttpServerRequest.HttpServerRequest30+>;31+32+/**33+ * `appLayer`'s routes as a fetch handler, its layer built now; a request34+ * that needs services of its own (`RequestNeeds`) is given them as its35+ * context. `dispose` closes what the build opened.36+ */37+export const buildHandler = <38+ A,39+ E,40+ R extends41+ | HttpRouter.HttpRouter42+ | HttpRouter.Request<"Requires", unknown>43+ | HttpRouter.Request<"GlobalRequires", unknown>44+ | HttpRouter.Request<"Error", unknown>45+ | HttpRouter.Request<"GlobalError", unknown>,46+>(47+ appLayer: Layer.Layer<A, E, R>48+) => {49+ const scope = Scope.makeUnsafe();50+51+ // SAFETY: what `R` adds to `HttpRouter` are `HttpRouter.Request` markers,52+ // which name what each request is given (its context) or may fail with,53+ // never a service the build needs; effect's `toWebHandler` drops them the54+ // same way.55+ /* oxlint-disable typescript/no-unsafe-type-assertion -- the markers are phantom types with no service behind them; see SAFETY. */56+ // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off -- the markers are phantom types with no service behind them; see SAFETY.57+ const routed = Layer.provideMerge(appLayer, HttpRouter.layer) as Layer.Layer<58+ A | HttpRouter.HttpRouter,59+ E60+ >;61+ /* oxlint-enable typescript/no-unsafe-type-assertion */62+63+ const built = Effect.runSyncExit(Layer.buildWithScope(routed, scope));64+65+ const awaited =66+ Exit.isFailure(built) &&67+ built.cause.reasons.some(68+ (reason) =>69+ Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)70+ );71+72+ if (awaited) {73+ throw new RouterBuildAwaited({74+ message:75+ "The router's build awaited a promise or a timer: move that work into the request path.",76+ });77+ }78+79+ const serveRequest = Exit.match(built, {80+ onFailure: (cause) => () => Effect.runPromise(Effect.failCause(cause)),81+ onSuccess: (context) =>82+ HttpEffect.toWebHandlerWith<83+ A | HttpRouter.HttpRouter,84+ HttpServerRequest.HttpServerRequest | Scope.Scope,85+ never86+ >(context)(87+ // @effect-diagnostics-next-line anyUnknownInErrorContext:off -- the router's own effect fails with whatever a route left unhandled, which `toWebHandlerWith` turns into a response (404 for no route), as effect's `toWebHandler` does with the same effect.88+ Context.get(context, HttpRouter.HttpRouter).asHttpEffect()89+ ),90+ });91+92+ /** One request, given `context` beside it: what `R`'s routes require of it. */93+ const handler = (94+ request: Request,95+ context?: Context.Context<RequestNeeds<A, R>>96+ ): Promise<Response> => serveRequest(request, context);97+98+ return {99+ dispose: () => Effect.runPromise(Scope.close(scope, Exit.void)),100+ handler,101+ };102+};modified:apps/platform/src/surfaces.ts+14 added-16 removed
1 import { commandDocs } from "@repo/agent-kit/command-doc";2-import { platformSkill } from "@repo/agent-kit/platform";2+import { platformSkillParts } from "@repo/agent-kit/platform";3 import { RepoHost } from "@repo/artifacts/repo-host";4 import { Brand } from "@repo/brand";5 import { Upstream } from "@repo/git/upstream";6 import { CodeStore } from "@repo/project/code-store";3 unmodified lines10 import { authenticated, bearerToken } from "@repo/protocol/authenticate";11 import { Client, Contracts, surfaced } from "@repo/protocol/contracts";12 import { ProjectName } from "@repo/protocol/ids";13 import { toToolkit } from "@repo/protocol/mcp";14-import {15- briefResources,16- skillIn,17- skillPrompt,18-} from "@repo/protocol/mcp-extras";14+import { briefResources, skillPrompt } from "@repo/protocol/mcp-extras";15 import { Authenticated } from "@repo/protocol/principal";16 import type { Person } from "@repo/protocol/principal";17 import { Context, Effect, Layer, Option, Schema } from "effect";18 import { McpProtocol, McpServer } from "effect/ai";18 unmodified lines37 import { LayerGate } from "./layer-gate.ts";38 import { rawResponse } from "./raw.ts";39 import { releaseRoutes } from "./releases.ts";40 import type { ReleaseStore } from "./releases.ts";41+import { buildHandler } from "./router-build.ts";42 import { Sessions } from "./sessions.ts";43 import { isFramed } from "./watch.ts";44 import { agentSkillRoutes } from "./well-known.ts";45 239 unmodified lines285 286 /**287 * The platform's skill as the prompt `contribute`, made when the server288 * starts from agent-kit's command list, the one the CLI's prompt and the292- * web's `llms.txt` read, so they say the same.289+ * web's `llms.txt` read, so they say the same. Made from the skill's parts,290+ * not its `SKILL.md`, whose hash is a promise the router's build may not291+ * await (`router-build.ts`).292 */294-const contribute = Layer.unwrap(295- Effect.map(296- skillIn(platformSkill({ commands: commandDocs(Contracts) })),297- skillPrompt298- )293+const contribute = skillPrompt(294+ platformSkillParts({ commands: commandDocs(Contracts) })295 );296 297 /**298 * The MCP-surfaced contracts as tools at `/mcp`, beside each ask's brief165 unmodified lines464 }465 })466 );467 472-/** The platform's fetch handler over `services`. */468+/**469+ * The platform's fetch handler over `services`, its router built now,470+ * before any request, awaiting nothing (`router-build.ts`).471+ */472 export const serve = <E>(services: Layer.Layer<Services, E>) =>474- HttpRouter.toWebHandler(473+ buildHandler(474 Layer.mergeAll(475 home,476 health,477 discovery,3 unmodified lines481 rpc,482 releaseRoutes,483 agentSkillRoutes,484 identifyCaller486- ).pipe(Layer.provide(services)),487- { disableLogger: true }485+ ).pipe(Layer.provide(services))486 );modified:apps/platform/src/worker.ts+5 added-2 removed
12 unmodified lines1314151617181718192021222324258 unmodified lines12 unmodified lines
// Built once per isolate, at module load, touching no binding: the env is// decoded once for the fetch handler, and both the platform's services and// sign-in's are made from what it decoded to; an env that fails to decode// fails them both, on use. (Each Project DO and Workflow decodes the same// env the same way, for its own ports.)// fails them both, on use. Both routers are built here, before any request,// and their builds await nothing (`router-build.ts` refuses one that does),// so no request ever waits on a build another request started. (Each// Project DO and Workflow decodes the same env the same way, for its own// ports.)const config = Effect.runSyncExit(decodeEnv(env));
const platform = serve(Layer.unwrap(Effect.map(config, platformOf)));
8 unmodified linesadded:apps/platform/test/router-build.test.ts+139 added
1+/**2+ * The router's handlers are built at module load, before any request, and3+ * the build awaits nothing. Workers cancels a request whose client4+ * left without interrupting its fibers, so a build that awaited a request's5+ * I/O would leave every later request waiting on it. `buildHandler` builds6+ * the router's layer at once or refuses: a layer that awaits a promise or7+ * a timer while it is built throws where the handler is made, so the8+ * Worker cannot start with one.9+ */10+import { describe, expect, it } from "@effect/vitest";11+import { untouchable } from "@repo/testkit/untouchable";12+import { env } from "cloudflare:workers";13+import { Effect, Layer, Schema } from "effect";14+import { HttpRouter, HttpServerResponse } from "effect/http";15+16+import { oauthProvider, signInServices } from "../src/auth/provider.ts";17+import { decodeEnv, platformOf } from "../src/platform.ts";18+import { buildHandler } from "../src/router-build.ts";19+import { serve } from "../src/surfaces.ts";20+import { callsTo, fakeEnv } from "./fake-env.ts";21+import { origin } from "./harness.ts";22+23+/** A Worker's context, which nothing here needs. */24+const context = untouchable<ExecutionContext>("ExecutionContext");25+26+/** One route, `GET /ping`, answering `pong`. */27+const ping = HttpRouter.use((router) =>28+ router.add("GET", "/ping", Effect.succeed(HttpServerResponse.text("pong")))29+);30+31+/** `ping`, beside a layer that counts each time it is built. */32+const counted = () => {33+ const builds: number[] = [];34+35+ const layer = Layer.merge(36+ ping,37+ Layer.effectDiscard(Effect.sync(() => builds.push(builds.length + 1)))38+ );39+40+ return { builds, layer };41+};42+43+/** `ping`, beside a layer that awaits a promise while it is built. */44+const awaiting = Layer.merge(45+ ping,46+ Layer.effectDiscard(Effect.promise(() => Promise.resolve()))47+);48+49+const pinged = (handler: (request: Request) => Promise<Response>) =>50+ Effect.promise(() => handler(new Request(`${origin}/ping`))).pipe(51+ Effect.flatMap((response) => Effect.promise(() => response.text()))52+ );53+54+describe("the router's build", () => {55+ it.effect(56+ "is done when the handler is made, and no request builds it again",57+ () =>58+ Effect.gen(function* () {59+ const { builds, layer } = counted();60+61+ const { dispose, handler } = buildHandler(layer);62+63+ expect(builds).toStrictEqual([1]);64+65+ const answers = yield* Effect.all([66+ pinged(handler),67+ pinged(handler),68+ pinged(handler),69+ ]);70+71+ expect(answers).toStrictEqual(["pong", "pong", "pong"]);72+ expect(builds).toStrictEqual([1]);73+74+ yield* Effect.promise(dispose);75+ })76+ );77+78+ it("refuses a layer that awaits a promise while it is built, where the handler is made", () => {79+ expect(() => buildHandler(awaiting)).toThrow(/awaited/u);80+ });81+});82+83+/** What `/health` answers. */84+const Health = Schema.fromJsonString(85+ Schema.Struct({ ok: Schema.Boolean, stage: Schema.String })86+);87+88+describe("the Worker's two handlers", () => {89+ it.effect(90+ "are built when the Worker module has loaded, before any request",91+ () =>92+ Effect.gen(function* () {93+ const before = callsTo(env.PROJECT).length;94+95+ // Loading runs `serve` and `oauthProvider`, each of which throws if96+ // its build awaited anything: a module that loads has both built.97+ const worker = yield* Effect.promise(() => import("../src/worker.ts"));98+99+ expect(Object.keys(worker.default)).toStrictEqual(["fetch"]);100+ expect(callsTo(env.PROJECT)).toHaveLength(before);101+ })102+ );103+104+ it.effect(105+ "build at once from the decoded env, touching no binding, and answer the first request",106+ () =>107+ Effect.gen(function* () {108+ const shim = fakeEnv();109+110+ const config = yield* decodeEnv(shim).pipe(Effect.orDie);111+112+ // As `worker.ts` composes them: each would throw here if its build113+ // awaited anything, and `fakeEnv`'s bindings throw when touched.114+ const platform = serve(platformOf(config));115+116+ const { handler } = oauthProvider(signInServices(config), (request) =>117+ platform.handler(request)118+ );119+120+ expect(callsTo(shim.PROJECT)).toStrictEqual([]);121+122+ const health = yield* Effect.promise(() =>123+ Promise.resolve(124+ handler.fetch(new Request(`${origin}/health`), env, context)125+ )126+ );127+128+ expect(health.status).toBe(200);129+ expect(130+ yield* Effect.promise(() => health.text()).pipe(131+ Effect.flatMap(Schema.decodeEffect(Health)),132+ Effect.orDie133+ )134+ ).toStrictEqual({ ok: true, stage: "local" });135+136+ yield* Effect.promise(platform.dispose);137+ })138+ );139+});modified:packages/agent-kit/src/platform.ts+13 added-6 removed
97 unmodified lines98 ...refusalSection(),99 ...unfencedSection(),100 ]);101 102+/**103+ * The platform's skill as the prompt `contribute` serves it: its name, its104+ * description and its Markdown, made at once. The platform builds the105+ * prompt where nothing may be awaited (its router, at module load), and106+ * `SKILL.md`'s frontmatter hashes the body through WebCrypto, a promise.107+ */108+export const platformSkillParts = (input: PlatformInput) => ({109+ body: platformBody(input),110+ description,111+ name: Brand.slug,112+});113+114 const skillFile = (input: PlatformInput) =>103- frontmatter({104- body: platformBody(input),105- description,106- landed: Option.none(),107- name: Brand.slug,108- });115+ frontmatter({ ...platformSkillParts(input), landed: Option.none() });116 117 /** `skills/<slug>/SKILL.md`: the platform's skill, which comes from no landing. */118 export const platformSkill = (119 input: PlatformInput107 unmodified linesmodified:packages/agent-kit/test/generate.test.ts+31 added-2 removed
1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4-import { Effect, Schema } from "effect";4+import { Effect, Option, Schema } from "effect";5 6 import { agentsBlock, upsertAgentsBlock } from "../src/agents-block.ts";7-import { contentHash } from "../src/generated-file.ts";7+import {8+ contentHash,9+ describedIn,10+ readManaged,11+} from "../src/generated-file.ts";12 import type { GeneratedFile } from "../src/generated-file.ts";13 import type { HookEvent } from "../src/hook-events.ts";14 import { claudeEventOf } from "../src/hook-events.ts";15 import {16 agentPluginsBundle,17 claudePlugin,18 platformSkill,19+ platformSkillParts,20 } from "../src/platform.ts";21 import { projectSkill } from "../src/project-skill.ts";22 import { wellKnownSkills } from "../src/well-known.ts";23 import { commands, landed, platformUrl, policy, project } from "./fixtures.ts";24 import { expectGolden, transcript } from "./golden.ts";25 26 const plugin = `plugins/${Brand.slug}`;27 28+/** The `name:` line of a file's frontmatter; none without one. */29+const frontmatterName = (content: string) =>30+ Option.fromNullishOr(/^name: (?<name>.+)$/mu.exec(content)?.groups?.name);31+32 const skill = `${project}-contribute`;33 34 /** `sha256("hello\n")`, as every tool that hashes prints it. */35 const helloDigest =258 unmodified lines294 })295 );296 });297 298+describe("the platform's skill as the prompt contribute serves it", () => {299+ it.effect("has the name, description and body its SKILL.md gives", () =>300+ Effect.gen(function* () {301+ const [own] = yield* platformSkill({ commands, platformUrl });302+ const content = own?.content ?? "";303+ const parts = platformSkillParts({ commands, platformUrl });304+305+ expect({306+ body: Option.map(readManaged(content), ({ body }) => body),307+ description: describedIn(content),308+ name: frontmatterName(content),309+ }).toStrictEqual({310+ body: Option.some(parts.body),311+ description: Option.some(parts.description),312+ name: Option.some(parts.name),313+ });314+ })315+ );316+});317+318 describe("the Claude Code plugin's hooks", () => {319 it.effect(320 "send PreToolUse on edits, Stop and SessionStart to the CLI's hook command",321 () =>134 unmodified linesmodified:packages/config/test/smoke-loop.test.ts+176 added
203 unmodified lines204 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),205 };206 });207 208+/**209+ * A platform scripted at the process boundary: `status` names the decider,210+ * `projects` lists `listed`, git does what it is asked, and `init` makes211+ * the project on the platform and then fails (as a push that answered 500212+ * after the project was made did on a dev stage). What was spawned is kept, git by213+ * its subcommand and the CLI by its command.214+ */215+const scripted = (listed: readonly string[]) =>216+ Effect.gen(function* () {217+ const asked = yield* Ref.make<readonly string[]>([]);218+219+ // Each CLI command's `--json` envelope, as the CLI prints it.220+ const replies = new Map([221+ [222+ "status",223+ {224+ code: 0,225+ stdout: JSON.stringify({226+ command: "status",227+ data: { handle: decider },228+ ok: true,229+ v: 1,230+ }),231+ },232+ ],233+ [234+ "projects",235+ {236+ code: 0,237+ stdout: JSON.stringify({238+ command: "projects",239+ data: {240+ projects: listed.map((project) => ({241+ openAsks: 0,242+ posture: "open",243+ project,244+ })),245+ },246+ ok: true,247+ v: 1,248+ }),249+ },250+ ],251+ ["init", { code: 1, stdout: "" }],252+ ]);253+254+ const spawner = ChildProcessSpawner.make((command) =>255+ Effect.gen(function* () {256+ const [program, args] = ChildProcess.isStandardCommand(command)257+ ? [command.command, command.args]258+ : ["a pipe", []];259+260+ // The CLI runs as `bun <entry> <command> … --json`.261+ const said =262+ program === "bun" ? (args[1] ?? "") : `${program} ${args[0] ?? ""}`;263+264+ yield* Ref.update(asked, (all) => [...all, said]);265+266+ const reply = replies.get(said) ?? { code: 0, stdout: "" };267+268+ return ChildProcessSpawner.makeHandle({269+ all: Stream.empty,270+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(reply.code)),271+ getInputFd: () => Sink.drain,272+ getOutputFd: () => Stream.empty,273+ isRunning: Effect.succeed(false),274+ kill: () => Effect.void,275+ pid: ChildProcessSpawner.ProcessId(1),276+ stderr: Stream.empty,277+ stdin: Sink.drain,278+ stdout: Stream.make(new TextEncoder().encode(reply.stdout)),279+ unref: Effect.succeed(Effect.void),280+ });281+ })282+ );283+284+ return {285+ asked: Ref.get(asked),286+ layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),287+ };288+ });289+290+/**291+ * The loop for run `r1` on the scripted platform, with the ledger in a file292+ * of its own: how it ended, the CLI commands it ran, and the ledger's lines.293+ */294+const loopOnScripted = (listed: readonly string[]) =>295+ Effect.gen(function* () {296+ const fs = yield* FileSystem.FileSystem;297+ const path = yield* Path.Path;298+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "smoke-ledger-" });299+ const ledger = path.join(dir, "created.jsonl");300+ const platform = yield* scripted(listed);301+302+ const failure = yield* smokeLoop({303+ answerer: tokens.answerer,304+ decider: tokens.decider,305+ origin: "https://platform-dev.example.workers.dev",306+ run: "r1",307+ stage: "dev-example",308+ }).pipe(309+ Effect.catchTag("DemoStageRefused", Effect.die),310+ Effect.flip,311+ Effect.provide(platform.layer),312+ Effect.provideService(LedgerFile, ledger)313+ );314+315+ const lines = yield* readLedger.pipe(316+ Effect.provideService(LedgerFile, ledger)317+ );318+319+ return {320+ cli: (yield* platform.asked).filter((said) => !said.startsWith("git ")),321+ failure,322+ ledger: lines.map(({ by, kind, name, stage }) => ({323+ by,324+ kind,325+ name,326+ stage,327+ })),328+ };329+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));330+331+describe("smoke --loop's throwaway ledger", () => {332+ it.live(333+ "writes the project and its repo before init, so an init that made the project and then failed leaves them in the ledger",334+ () =>335+ Effect.gen(function* () {336+ const { cli, failure, ledger } = yield* loopOnScripted([]);337+338+ expect({ cli, ledger, step: failure.step }).toStrictEqual({339+ cli: ["status", "status", "projects", "init"],340+ ledger: [341+ {342+ by: "smoke",343+ kind: "project",344+ name: "smoke-r1",345+ stage: "dev-example",346+ },347+ {348+ by: "smoke",349+ kind: "repo",350+ name: "smoke-r1",351+ stage: "dev-example",352+ },353+ ],354+ step: "init",355+ });356+ })357+ );358+359+ it.live(360+ "stops before init on a name the platform already lists, and writes nothing",361+ () =>362+ Effect.gen(function* () {363+ const { cli, failure, ledger } = yield* loopOnScripted([364+ "datekit",365+ "smoke-r1",366+ ]);367+368+ expect({369+ cli,370+ ledger,371+ reason: failure.reason,372+ step: failure.step,373+ }).toStrictEqual({374+ cli: ["status", "status", "projects"],375+ ledger: [],376+ reason:377+ "smoke-r1 is on the platform already, so nothing was made or recorded: a run a second later takes another name",378+ step: "init",379+ });380+ })381+ );382+});383+384 describe("smoke --loop on demo", () => {385 it.live(386 "is refused with DemoStageRefused before any request or process: a throwaway project would show on demo's front page",387 () =>143 unmodified linesmodified:packages/drafting/src/drafter/binding.ts+53 added-8 removed
27 unmodified lines28 readonly role: "system" | "user";29 }30 31 /**32+ * How hard a reasoning model thinks before it answers, in the key a Workers33+ * AI chat call takes it (glm-5.3: max, high or low; gpt-oss-120b: low,34+ * medium or high; `@cloudflare/workers-types` 5.20261006.1).35+ */36+export interface ReasoningInputs {37+ readonly reasoning_effort: "low";38+}39+40+/**41 * What the drafter sends: the messages, the JSON Schema the reply must33- * match, and the sampling it asks for. A type alias, not an interface, so34- * it fits the binding's open `Record` of inputs.42+ * match, the sampling it asks for, and the model's own settings43+ * (`modelSettings`). A type alias, not an interface, so it fits the44+ * binding's open `Record` of inputs.45 */36-// oxlint-disable-next-line typescript/consistent-type-definitions -- an interface has no implicit index signature, so it would not fit the generated Ai's `Record<string, unknown>` inputs37-export type ChatInputs = {46+export type ChatInputs = Partial<ReasoningInputs> & {47 readonly max_completion_tokens: number;48 readonly messages: readonly ChatMessage[];49 readonly response_format: {50 readonly json_schema: JsonSchema.JsonSchema;2 unmodified lines53 readonly seed: number;54 readonly temperature: number;55 };56 57+/** What a model is asked with beyond the prompt: its output cap, and how hard it reasons. */58+export interface ModelSettings {59+ readonly max_completion_tokens: number;60+ /** The model's own reasoning input, sent as it stands; none sends nothing. */61+ readonly reasoning?: ReasoningInputs;62+}63+64+/** What a model not in `MODEL_SETTINGS` is asked with: `DRAFT_MODEL`'s settings. */65+const DEFAULT_SETTINGS: ModelSettings = { max_completion_tokens: 12_000 };66+67+/**68+ * The fallback models reason before they answer, and spent 12,000 tokens69+ * doing so on the drafting prompt before the JSON was done. Each70+ * gets more room and a low effort, in the key its Workers AI input schema71+ * takes for a chat call (`ReasoningInputs`).72+ */73+const FALLBACK_SETTINGS: ModelSettings = {74+ max_completion_tokens: 32_000,75+ reasoning: { reasoning_effort: "low" },76+};77+78+/** Settings by Workers AI model id; `DRAFT_MODEL` (kimi-k2.7-code) takes the defaults. */79+const MODEL_SETTINGS: ReadonlyMap<string, ModelSettings> = new Map([80+ ["@cf/moonshotai/kimi-k2.7-code", DEFAULT_SETTINGS],81+ ["@cf/zai-org/glm-5.3", FALLBACK_SETTINGS],82+ ["@cf/openai/gpt-oss-120b", FALLBACK_SETTINGS],83+]);84+85+/** What `model` is asked with beyond the prompt; the defaults for a model not listed. */86+export const modelSettings = (model: string): ModelSettings =>87+ MODEL_SETTINGS.get(model) ?? DEFAULT_SETTINGS;88+89 /** `DraftedAsk` as JSON Schema, for `response_format`: an object root, no `$ref`. */90 const responseSchema = (() => {91 const { definitions, schema } = Schema.toJsonSchemaDocument(DraftedAsk);92 67 unmodified lines160 `${input.context.project}:${input.context.at}:${input.attempt}:${input.want}`161 )162 );163 123-/** The drafter over `ai`, asking `model` (the platform's `DRAFT_MODEL`). */164+/** The drafter over `ai`, asking `model` (the platform's `DRAFT_MODEL`) with its settings. */165 export const DrafterWorkersAi = (166 ai: AiLike,167 model: string127-): Layer.Layer<Drafter> =>128- Layer.succeed(168+): Layer.Layer<Drafter> => {169+ const settings = modelSettings(model);170+171+ return Layer.succeed(172 Drafter,173 Drafter.of({174 draft: (input) =>175 Effect.gen(function* () {8 unmodified lines184 )185 ),186 try: () =>187 ai.run(model, {145- max_completion_tokens: 12_000,188+ ...settings.reasoning,189+ max_completion_tokens: settings.max_completion_tokens,190 messages: [191 {192 content: systemPrompt(input.context.policy),193 role: "system",16 unmodified lines210 );211 }),212 })213 );214+};modified:packages/drafting/test/binding.test.ts+44 added
113 unmodified lines114 expect(call.inputs.seed).toBe((yield* callOf).inputs.seed);115 })116 );117 118+ it.effect(119+ "gives each model its own room: the fallbacks more tokens and low reasoning, anything else the defaults",120+ () =>121+ Effect.gen(function* () {122+ const asked = yield* Effect.forEach(123+ [124+ "@cf/moonshotai/kimi-k2.7-code",125+ "@cf/zai-org/glm-5.3",126+ "@cf/openai/gpt-oss-120b",127+ model,128+ ],129+ (name) =>130+ Effect.gen(function* () {131+ const { ai, calls } = fakeAi(chat(json));132+133+ yield* Drafter.use(({ draft }) => draft(input)).pipe(134+ Effect.provide(DrafterWorkersAi(ai, name))135+ );136+137+ const call = yield* Effect.fromNullishOr(calls[0]);138+139+ return {140+ max: call.inputs.max_completion_tokens,141+ model: call.model,142+ reasoning: Object.hasOwn(call.inputs, "reasoning_effort")143+ ? call.inputs.reasoning_effort144+ : "none sent",145+ };146+ })147+ );148+149+ expect(asked).toStrictEqual([150+ {151+ max: 12_000,152+ model: "@cf/moonshotai/kimi-k2.7-code",153+ reasoning: "none sent",154+ },155+ { max: 32_000, model: "@cf/zai-org/glm-5.3", reasoning: "low" },156+ { max: 32_000, model: "@cf/openai/gpt-oss-120b", reasoning: "low" },157+ { max: 12_000, model, reasoning: "none sent" },158+ ]);159+ })160+ );161+162 it.effect("asks for JSON Schema with no null and no Infinity in it", () =>163 Effect.gen(function* () {164 const { response_format: format } = (yield* callOf).inputs;165 const text = JSON.stringify(format.json_schema);122 unmodified linesmodified:packages/visibility/src/vault/webcrypto.ts+26 added-14 removed
76 unmodified lines77 ? Option.some(bytes.subarray(0, end))78 : Option.none();79 };80 81-/** The master key as an AES-KW key that can only wrap and unwrap. */82-const importMasterKey = (masterKey: Redacted.Redacted) =>81+/** The master key's 32 bytes, decoded from its hex; a defect for any other form. */82+const masterKeyBytes = (masterKey: Redacted.Redacted) =>83 Schema.decodeEffect(Schema.Uint8ArrayFromHex)(Redacted.value(masterKey)).pipe(84 Effect.mapError(() => new MasterKeyUnusable()),85 Effect.filterOrFail(86 (bytes) => bytes.length === KEY_BYTES,87 () => new MasterKeyUnusable()88 ),89- Effect.flatMap((bytes) =>90- Effect.promise(() =>91- crypto.subtle.importKey("raw", owned(bytes), "AES-KW", false, [92- "wrapKey",93- "unwrapKey",94- ])95- )96- ),89+ Effect.map(owned),90 Effect.orDie91 );92 93+/**94+ * The master key as an AES-KW key that can only wrap and unwrap, imported95+ * for each call: WebCrypto's import is a promise, and the layer is built96+ * where nothing may be awaited (the platform's router, at module load).97+ */98+const importMasterKey = (bytes: Uint8Array<ArrayBuffer>) =>99+ Effect.promise(() =>100+ crypto.subtle.importKey("raw", bytes, "AES-KW", false, [101+ "wrapKey",102+ "unwrapKey",103+ ])104+ );105+106 /** A fresh data key, from WebCrypto's random bytes, extractable only to be wrapped. */107 const freshDataKey = Effect.sync(() =>108 crypto.getRandomValues(new Uint8Array(KEY_BYTES))109 ).pipe(105 unmodified lines215 masterKey: Redacted.Redacted216 ): Layer.Layer<WriteOnlyValues> =>217 Layer.effect(218 WriteOnlyValues,213- importMasterKey(masterKey).pipe(214- Effect.map((master) =>219+ masterKeyBytes(masterKey).pipe(220+ Effect.map((bytes) =>221 WriteOnlyValues.of({216- open: (sealed) => unseal(master, sealed),217- put: (input) => seal(master, input),222+ open: (sealed) =>223+ Effect.flatMap(importMasterKey(bytes), (master) =>224+ unseal(master, sealed)225+ ),226+ put: (input) =>227+ Effect.flatMap(importMasterKey(bytes), (master) =>228+ seal(master, input)229+ ),230 })231 )232 )233 );modified:packages/visibility/test/vault.test.ts+13 added
4 unmodified lines5 import {6 Cause,7 Effect,8 Exit,9+ Layer,10 Option,11 Predicate,12 Redacted,13 Result,131 unmodified lines145 ]);146 })147 );148 149+ it("is built at once, awaiting nothing: the master key is imported per call", () => {150+ // The platform builds its router at module load and refuses a build151+ // that awaits (`router-build.ts`), so the vault's layer must build synchronously.152+ const built = Effect.runSyncExit(153+ Layer.build(masterKey).pipe(Effect.scoped)154+ );155+156+ expect(Exit.isFailure(built) ? Cause.pretty(built.cause) : "built").toBe(157+ "built"158+ );159+ });160+161 it.effect("does not open a value under another master key", () =>162 Effect.gen(function* () {163 const sealed = yield* put(token).pipe(Effect.provide(masterKey));164 152 unmodified linesmodified:scripts/lib/smoke/core-loop.ts+29 added-2 removed
19 unmodified lines20 import { Decision, DecisionSubject } from "@repo/protocol/domain/decision";21 import { Outcome } from "@repo/protocol/domain/outcome";22 import { DraftState, Proposal } from "@repo/protocol/domain/proposal";23 import { Envelope } from "@repo/protocol/envelope";24+import {25+ AskId,26+ CommitSha,27+ Handle,28+ LandedSha,29+ ProjectName,24-import { AskId, CommitSha, Handle, LandedSha } from "@repo/protocol/ids";25-import type { ProjectName, ProposalId } from "@repo/protocol/ids";30+} from "@repo/protocol/ids";31+import type { ProposalId } from "@repo/protocol/ids";32 import { explain } from "@repo/protocol/render";33 import {34 Array,35 Config,423 unmodified lines459 yield* gitOk(step, person, cwd, ["rev-parse", "HEAD"])460 );461 });462 463+const Listed = Schema.Struct({464+ projects: Schema.Array(Schema.Struct({ project: ProjectName })),465+});466+467+/**468+ * Whether `project` is free on the platform, as `person` lists every469+ * project (`<cli> projects`): a taken name fails the step, before470+ * anything is made.471+ */472+export const projectIsFree = (person: LoopPerson, project: ProjectName) =>473+ Effect.flatMap(cli("init", person, ["projects"], Listed), ({ projects }) =>474+ projects.some((listed) => listed.project === project)475+ ? Effect.fail(476+ failed(477+ "init",478+ `${project} is on the platform already, so nothing was made or recorded: a run a second later takes another name`479+ )480+ )481+ : Effect.void482+ );483+484 const Inited = Schema.Struct({485 pushed: Schema.Boolean,486 remote: Schema.NonEmptyString,487 });544 unmodified linesmodified:scripts/lib/smoke/loop.ts+26 added-19 removed
2 unmodified lines3 * the CLI and git, as its people would take it (`core-loop.ts` holds the4 * steps):5 *6 * 1. `people`: who the decider's and the answerer's tokens name;7- * 2. `init`: the decider makes a throwaway project, `smoke-<run>`, and8- * pushes its first commit;7+ * 2. `init`: the decider checks `smoke-<run>` is free, records it, then8+ * makes it a throwaway project and pushes its first commit;9 * 3. `open-ask`: the decider opens an ask, red twice on main first;10 * 4. `claim`: the answerer claims it, and gets a fork;11 * 5. `out-of-scope`: an answer that reaches outside the ask's territory is12 * refused, `OutOfScope` in git's own output;11 unmodified lines24 * that opened its ask discloses the drafter (`Assisted-by:`) and25 * credits the answerer as its asker.26 *27 * Each step is timed and printed as it passes; the first that fails ends28- * the run. The throwaway project, its repo and the claim's fork are written29- * to the throwaway ledger (`infra/created.ts`, by `smoke`) as soon as each30- * exists. It never runs on `demo`: a throwaway project would show on the31- * front page the user records.28+ * the run. Every throwaway is written to the throwaway ledger29+ * (`infra/created.ts`, by `smoke`): the project and its repo before `init`30+ * makes them, once the platform's list of projects shows the name free (a31+ * taken name stops the run, recording nothing), so an `init` that fails32+ * after making the project still leaves it recorded; the claim's fork just33+ * after the claim, since its name is known only then. It never runs on34+ * `demo`: a throwaway project would show on the front page the user35+ * records.36 */37 import { Brand } from "@repo/brand";38 import { ProjectName } from "@repo/protocol/ids";39 import type { LandedSha } from "@repo/protocol/ids";20 unmodified lines60 initProject,61 LoopFailed,62 openAsk,63 personAt,64+ projectIsFree,65 proposeDraft,66 pushAnswer,67 pushOutOfScope,68 readLanding,182 unmodified lines251 }),252 })253 );254 255+ // The name is checked free, then recorded, then made: an init that256+ // makes the project and then fails still leaves it in the ledger, and257+ // a name someone else holds never enters teardown's plan.258 const [, init] = yield* timed(259 stage,260 "init"261 )(254- initProject({255- answerer: answerer.handle,256- decider,257- dir: `${dir}/start`,258- project,259- }).pipe(260- Effect.tap(() =>261- Effect.andThen(262- recordThrowaway(stage, "project", project),263- recordThrowaway(stage, "repo", project)264- )265- )266- )262+ Effect.gen(function* () {263+ yield* projectIsFree(decider, project);264+ yield* recordThrowaway(stage, "project", project);265+ yield* recordThrowaway(stage, "repo", project);266+267+ return yield* initProject({268+ answerer: answerer.handle,269+ decider,270+ dir: `${dir}/start`,271+ project,272+ });273+ })274 );275 276 const [, opened] = yield* timed(277 stage,149 unmodified lines