Merge build/comments-platform into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents c86204f, c625830 · Browse files · 140 files·+181 added−4419 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
140 files+181 added−4419 removed
- tests:+16 added−1734 removed
- other:+165 added−2685 removed
Provenance
- Commit
ddf09e8- Tree
273e903- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
c86204f- Parent 2
c625830
140 files changed+181 added−4419 removed
This commit is too large to show whole: its files are listed by path, without their changes.
modified:apps/platform/src/adapters/accounts-d1.ts-8 removed
1-/**2- * Accounts on D1 (`FRONT_PAGE`'s database, table `accounts` from3- * `migrations/0002_accounts.sql`), through `effect/sql`, so the same code4- * runs on `@effect/sql-d1` in the Worker and on sqlite-node in tests. A5- * `SqlError` is a defect: the sign-in page answers 500, never a wrong6- * "handle or password".7- */1 import { Handle } from "@repo/protocol/ids";2 import { Array, Clock, Effect, Layer, Option, Schema } from "effect";3 import { SqlClient } from "effect/sql/SqlClient";4 5 import { Accounts, handleKey, HandleTaken } from "../auth/accounts.ts";6 import { PasswordHash } from "../auth/password.ts";7 15-// What D1 hands back is decoded like any other outside input.8 const Rows = Schema.Array(9 Schema.Struct({ handle: Handle, password_hash: PasswordHash })10 );11 49 unmodified linesmodified:apps/platform/src/adapters/alarms.ts-8 removed
1-/**2- * The project service's `Alarms` port for a Project Durable Object: its3- * storage's one alarm. The service decides when (always its earliest pending4- * deadline); the adapter only sets it, in place of any set before, as a DO's5- * alarm is.6- */1 import { Alarms } from "@repo/project/alarms";2 import { DateTime, Effect, Layer } from "effect";3 10-/** The part of a DO's storage that holds its alarm. */4 export type AlarmStorage = Pick<DurableObjectStorage, "setAlarm">;5 13-/** `Alarms` over `storage.setAlarm`. Storage that fails is a defect, as the store's is. */6 export const DoAlarms = (storage: AlarmStorage): Layer.Layer<Alarms> =>7 Layer.succeed(8 Alarms,9 Alarms.of({4 unmodified linesmodified:apps/platform/src/adapters/answer-runs-workflow.ts+1 added-22 removed
1-/**2- * The project service's `AnswerRuns` port over the `Answer` Workflow: starting3- * an answer's run makes the Workflow instance whose id is the request id,4- * with the project and the request as its params. The instance runs the5- * answer's steps through the project's DO (`Projects`), so the port's6- * in-process `queue` is not used here.7- *8- * Starting twice is starting once (principle 8): an instance with the id9- * already exists, so `create` refuses, and the adapter takes the instance it10- * finds instead. A run ends whenever the answer waits (the landing slot, a11- * finish, a decision, a retry), and the project starts the same request12- * again once it can go on, so an instance whose run has ended13- * (complete, errored or terminated) is restarted from its first step; each14- * step re-reads the run from the DO, so a fresh run picks up where the15- * answer stands. An instance still running is left alone. Any other failure16- * is a defect: the outbox row that asked for the start stays, and the17- * project's next alarm runs it again.18- */1 import { AnswerRuns } from "@repo/project/answer-runs";2 import type { ProjectName } from "@repo/protocol/ids";3 import { Effect, Layer, Schema } from "effect";4 5 import { AnswerParams } from "../answer-runs.ts";6 25-/** The part of a Workflow instance the adapter uses. */7 export interface AnswerInstance {8 readonly id: string;9 readonly restart: () => Promise<void>;10 readonly status: () => Promise<{ readonly status: InstanceStatus["status"] }>;11 }12 32-/** The part of the `Answer` Workflow binding the adapter uses. */13 export interface AnswerWorkflow {14 readonly create: (options: {15 readonly id: string;16 readonly params: typeof AnswerParams.Encoded;2 unmodified lines19 }20 21 const encodeParams = Schema.encodeEffect(AnswerParams);22 43-/** The states an instance's run has ended in, so a start must run it again. */23+// A run ends whenever the answer waits; the project starts the same request again once it can go on.24 const ended: ReadonlySet<InstanceStatus["status"]> = new Set([25 "complete",26 "errored",27 "terminated",28 ]);29 50-/** Restarts the instance when its run has ended; a running one is left alone. */30 const runAgain = (instance: AnswerInstance) =>31 Effect.gen(function* () {32 const { status } = yield* Effect.tryPromise(() => instance.status());33 30 unmodified linesmodified:apps/platform/src/adapters/check-runner-sandbox.ts+1 added-28 removed
1-/**2- * `CheckRunner` over the sandbox Worker: each run goes to the3- * Checker through the `SANDBOX` service binding, with one read token on the4- * repo it clones from and nothing else. The Checker's container never sees5- * the token; its outcome comes back as the port's own `CheckRun` or6- * `VerifierBlocked`.7- *8- * A job's sealed suite crosses as the platform read it: the9- * layer's files under the sealed areas, base64 on the wire, and one run per10- * sealed check. No layer repo, route or token goes with it, so the only11- * token is still the one on the answer's fork. Its area bits come back12- * decoded and held to the job that asked for them: one per area the job13- * sent, under the job's suite, each counting that area's checks. Bits that14- * answer some other job are the platform's trouble (`VerifierBlocked`),15- * never a result an answer earned.16- */1 import { RepoHost } from "@repo/artifacts/repo-host";2 import { CheckRunner } from "@repo/checks/check-runner";3 import type { CheckJob, CheckRun } from "@repo/checks/check-runner";4 import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";12 unmodified lines17 import { Array, Effect, Layer } from "effect";18 19 import { sandboxJob, withRemote } from "./sandbox-credentials.ts";20 37-/**38- * The sandbox Worker's entrypoint, as the platform reaches it through the39- * `SANDBOX` service binding: each method takes a job's wire, encoded, and40- * answers with the job's `Exit` as JSON, which the adapters decode before41- * they trust any of it (principle 2). Structural, so 317 passes the binding42- * itself.43- */21 export interface SandboxBinding {22 readonly check: (23 wire: typeof CheckWire.Encoded24 ) => Promise<typeof CheckExit.Encoded>;10 unmodified lines35 wire: typeof BundleWire.Encoded36 ) => Promise<typeof BundleExit.Encoded>;37 }38 62-/**63- * Whether `bits` are the area bits of `job`'s suite: each area it sent,64- * once and in order, as the Checker counts them (`areaBits`).65- */39+// Bits that answer some other job are the platform's trouble, never a result an answer earned.40 const answersJob = (job: CheckJob, bits: readonly HeldBackResult[]) => {41 const suite = job.heldBack;42 43 if (suite === undefined) {19 unmodified lines63 })64 );65 };66 93-/** A run whose area bits answer `job`, or `VerifierBlocked` with one log line naming nothing sealed. */67 const heldTo = (job: CheckJob) => (ran: CheckRun) =>68 answersJob(job, ran.heldBack)69 ? Effect.succeed(ran)70 : Effect.logError("sandbox job blocked").pipe(33 unmodified linesmodified:apps/platform/src/adapters/custody.ts+6 added-104 removed
1-/**2- * The `Custody` port (`@repo/git/custody`) for one push, by who pushes and3- * which repo the name says it is (ADR 0004).4- *5- * `admit` is stage 0, before anything reaches the upstream: what the pusher6- * may move, from the project's own record through `ProjectApi`. A canonical7- * repo takes no push (`DirectPush`) but its initializer's first8- * (`firstPusher`); a claim's fork takes its claimant's pushes while the claim9- * is live, and a decider's commits on top when they finish its answer; a10- * working fork takes its owner's. A fork takes branches only: a push of its11- * notes, a tag or the platform's own refs is `DirectPush`, whoever makes it,12- * and refuses the whole push. The platform writes its notes and merge refs13- * straight to the store (`RepoHost.push`, the Lander), never through the14- * gateway; no one writes a fork's tags.15- * `ProjectApi` has no read of the push facts the gate's parse stage takes16- * (the policy, the ask, the claim), so `admit` asks the claimant's own17- * `status` and leaves the full parse to `review`, where `recordPush` runs it.18- *19- * `custodyFor` reads what `admit` needs before the gateway starts, and20- * `admit` answers at once. The gateway makes the push's upstream body as21- * soon as it has read the command list, before it asks `admit`, and that22- * body locks the request's the moment the fiber yields: an `admit` that23- * waits on anything and then refuses finds the body locked, and the push24- * fails with a 500 (better: `@repo/git/gateway` reads that body only once25- * the push is admitted).26- *27- * `review` runs after the upstream took the push. A first push becomes the28- * project's landed SHA. A claimant's push to their fork is reported to the29- * project (`recordPush`: liveness, then stages 0–1, every stage-1 refusal at30- * once); a clean one is offered as the answer (`submitAnswer`, the same path31- * as `<cli> submit`) and the pusher reads that it is being checked. The32- * gate's later stages never run inside the push.33- *34- * A harness that pushes names itself in the basic-auth username its35- * credential helper gives (`audit;harness=pi&model=…`, `@repo/protocol/audit`).36- * Custody logs it with the push and reports it with a claimant's push, so37- * the answer's landing discloses it as `Assisted-by:`. It is38- * audit metadata only: who pushes is the token's person, and the username is39- * never identity, credit or a score.40- */1 import type { RepoName } from "@repo/artifacts/repo-host";2 import { Custody } from "@repo/git/custody";3 import type { Command } from "@repo/git/custody";4 import type { ProjectApi } from "@repo/project/project";10 unmodified lines15 16 import type { LayerTarget } from "../layer-gate.ts";17 import { RepoKind } from "../repo-names.ts";18 59-/** The branch every repo the platform makes keeps its work on. */19 const mainRef = "refs/heads/main";20 62-/** Says a line to the pusher, as a `remote:` line of git's output. */21 export type Notice = (line: string) => Effect.Effect<void>;22 65-/**66- * The request a push to a claim's fork answers with: it names the head and67- * the pusher, so two people pushing one commit make two requests. A request68- * id holds 64 characters, so the head comes first and is never cut: a long69- * handle is, and each new head is still a new request.70- */23+// A request id holds 64 characters, so the head comes first and is never cut.24 export const pushRequestId = (pusher: Handle, head: CommitSha) =>25 RequestId.make(`push-${head}-${pusher.toLowerCase()}`.slice(0, 64));26 74-/** The push event a push reports: one per (repo, head), so a replay is acted on once. */27 const pushEventId = (repo: RepoName, head: CommitSha) => `push-${repo}-${head}`;28 77-/** Every ref in the push turned away: main moves only by a landing. */29 const directPushes = (commands: readonly Command[]) =>30 commands.map(({ ref }) => new DirectPush({ ref }));31 81-/** Where a person's work goes on a fork: its branches. */32 const branchPrefix = "refs/heads/";33 84-/**85- * A fork takes branches only: every other ref, created, moved or deleted,86- * is the platform's (its verdict notes, the Lander's merge refs) or no one's87- * (a tag), so each is a direct push, whoever pushes it.88- */34+// Every ref but a branch is the platform's (notes, merge refs) or no one's (tags).35 const branchesOnly = (commands: readonly Command[]): readonly Refusal[] =>36 commands.flatMap(({ ref }) =>37 ref.startsWith(branchPrefix) ? [] : [new DirectPush({ ref })]38 );39 94-/** Where a push moves `main`, if it moves it to a commit; a deletion moves it nowhere. */40 const mainTip = (commands: readonly Command[]) =>41 Option.flatMap(42 Array.findFirst(commands, ({ ref }) => ref === mainRef),43 (command) =>44 Option.map(command.to, (head) => ({ from: command.from, head }))45 );46 102-/** Runs `judge` against the project; a project never made refuses the push. */47 const against = (48 projects: Projects["Service"],49 project: ProjectName,50 judge: (api: ProjectApi) => Effect.Effect<readonly Refusal[]>2 unmodified lines53 Effect.flatMap(judge),54 Effect.catchTag("UnknownProject", (refused) => Effect.succeed([refused]))55 );56 113-/** Custody whose `admit` decides at once, from what was read before the push. */57 const custodyOf = (58 admit: (commands: readonly Command[]) => readonly Refusal[],59 review: Custody["Service"]["review"]60 ) =>1 unmodified line62 admit: (_repo, commands) => Effect.succeed(admit(commands)),63 review,64 });65 123-/**124- * A project's canonical repo: only its initializer's first push reaches it,125- * as the project says (`firstPusher`). A project never made has no first126- * pusher, so every push there is a direct push: custody fails closed.127- */66+// A project never made has no first pusher: custody fails closed.67 const canonical = (68 projects: Projects["Service"],69 project: ProjectName,70 pusher: Person31 unmodified lines102 })103 );104 });105 167-/** The claim `person` has on `ask`, as their own `status` shows it. */106 const claimOn = (api: ProjectApi, person: Person, ask: AskId) =>107 Effect.map(api.status(person), ({ claims }) =>108 Array.findFirst(claims, (claim) => claim.ask === ask)109 );110 173-/**174- * Whether the claimant may push to their claim's fork: a live or warned175- * claim lets them; a lapsed one is `ClaimLapsed`; none, or one released or176- * answered, is `NotClaimed`.177- */111 const holds = (api: ProjectApi, person: Person, ask: AskId) =>112 Effect.map(claimOn(api, person, ask), (claim) =>113 Option.match(claim, {114 onNone: () => [NotClaimed.of(ask)],8 unmodified lines123 },124 })125 );126 194-/**195- * The claimant's push, which the fork already took: reported to the196- * project with the harness it came through, then, if stages 0–1 have197- * nothing to say, offered as the answer.198- */127 const offer = (input: {128 readonly api: ProjectApi;129 readonly ask: AskId;130 readonly audit: Option.Option<HarnessAudit>;47 unmodified lines178 onSuccess: (line) => Effect.as(input.notice(line), []),179 });180 });181 254-/** A claim's fork: its claimant while the claim is live, or a decider finishing its answer. */182 const claimFork = (183 projects: Projects["Service"],184 fork: Extract<RepoKind, { readonly _tag: "ClaimFork" }>,185 pusher: Person,37 unmodified lines223 )224 );225 });226 300-/** What a push's log lines and span carry: who pushes, to which kind of repo, through which harness. */227 type PushAnnotations = HarnessAudit & {228 readonly pusher: string;229 readonly target: RepoKind["_tag"];230 };7 unmodified lines238 pusher: pusher.handle,239 target: kind._tag,240 });241 316-/**317- * `custody` with every log line it writes annotated, and its review in a318- * span with the same attributes. `admit` stays synchronous: the gateway's319- * body locks the moment the fiber yields.320- */242+// `admit` stays synchronous: the gateway's body locks the moment the fiber yields.243 const annotated = (custody: Custody["Service"], annotations: PushAnnotations) =>244 Custody.of({245 admit: (repo, commands) =>246 custody.admit(repo, commands).pipe(Effect.annotateLogs(annotations)),5 unmodified lines252 Effect.withSpan("custody.review", { attributes: annotations })253 ),254 });255 334-/** Custody of a person's own working fork: every branch push as it comes. */256 const ownBranches = custodyOf(branchesOnly, () => Effect.succeed([]));257 337-/** Custody that takes no push at all: every ref is a direct push. */258 export const refuseAll = custodyOf(directPushes, (_repo, commands) =>259 Effect.succeed(directPushes(commands))260 );261 342-/**343- * Custody of one push by `pusher` to the repo `kind` names. `notice` says a344- * line to the pusher once the push went through: what became of the answer345- * it offered. `audit` is the harness the push came through (`auditOf` in346- * `credential.ts`), if its username named one: logged with the push and347- * reported with a claimant's, never who pushes. Only a signed-in person348- * pushes anywhere.349- */262+// `audit` is metadata only: who pushes is the token's person, never the username.263 export const custodyFor = (264 pusher: Principal,265 kind: RepoKind,266 notice: Notice = () => Effect.void,25 unmodified lines292 293 return annotated(custody, annotations);294 });295 383-/**384- * Custody of a push to a layer's repo. The gateway lets only the385- * layer's writers push there (`git.ts`, through `LayerGate`), so every ref386- * goes through; once the upstream took the push, the project hears the387- * head `main` moved to (`recordLayerPush`), which it admits at once or388- * through admission. A project never made takes no layer push.389- */296+// The gateway lets only the layer's writers push here, so every ref goes through.297 export const layerCustodyFor = (298 pusher: Person,299 target: LayerTarget300 ): Effect.Effect<Custody["Service"], never, Projects> =>13 unmodified lines314 })315 )316 );317 411-/**412- * A clone or fetch of a layer's repo, for its read log: who413- * read which layer, and the commit they asked for when their request named414- * one. A project never made logs nothing.415- */318 export const layerRead = (319 reader: Person,320 target: LayerTarget,321 sha: Option.Option<CommitSha>13 unmodified linesmodified:apps/platform/src/adapters/do-projects.ts+1 added-23 removed
1-/**2- * The project service's `Projects` port over the Project Durable Object3- * namespace: each project name is one DO (`idFromName`), and the `ProjectApi` a4- * project gets encodes each call (`encodeCall`), sends it to the DO's `call`,5- * and decodes the reply (`decodeReply`), so a refusal arrives as the same typed6- * refusal it is in the DO.7- *8- * The DO answers `UnknownProject` itself before `initProject`, so `get`9- * asks it once whether the project was made (a `listAsks`) and `create`10- * refuses a name already made with `ProjectExists`; two creates that race11- * meet `ProjectExists` from `initProject` in the DO. A project made stays12- * made, so the layer remembers each one it found.13- */1 import { envSchemaMethod } from "@repo/project/deciders";2 import type { ProjectApi } from "@repo/project/project";3 import { Projects } from "@repo/project/projects";4 import { keyOf } from "@repo/protocol/ids";11 unmodified lines16 ProjectMethod,17 SuccessOf,18 } from "../project-calls.ts";19 33-/** The part of a Project DO's stub the Worker calls. */20 export interface ProjectStub {21 readonly call: (request: typeof CallRequest.Encoded) => Promise<ExitEncoded>;22 }23 38-/** The part of the `PROJECT` namespace binding the adapter uses. */24 export interface ProjectNamespace {25 readonly idFromName: (name: string) => DurableObjectId;26 readonly get: (id: DurableObjectId) => ProjectStub;27 }28 29 const isUnknownProject = Schema.is(UnknownProject);30 46-/**47- * A call that assumes its project is made: `get` found it, or `create`'s48- * caller makes it with `initProject` first. `ProjectApi` has no room for the49- * DO's `UnknownProject`, so one that comes back is a defect.31+// `ProjectApi` has no room for the DO's `UnknownProject`, so one that comes back is a defect.50- */32 const assumingMade = <A, E>(effect: Effect.Effect<A, E>) =>33 effect.pipe(34 Effect.catchIf<E, Extract<E, UnknownProject>, never, never, never>(35 (refused): refused is Extract<E, UnknownProject> =>1 unmodified line37 (refused) => Effect.die(refused)38 )39 );40 60-/** One call on `project`'s DO, as the method's own types. */41 const remote =42 (namespace: ProjectNamespace, project: ProjectName) =>43 <M extends ProjectMethod>(44 method: M,10 unmodified lines55 56 return yield* decodeReply(method, reply);57 });58 79-/** A project's `ProjectApi`, every method a call on its DO. */59 const apiOf = (60 namespace: ProjectNamespace,61 project: ProjectName62 ): ProjectApi => {67 unmodified lines130 Projects,131 Effect.gen(function* () {132 const known = yield* Ref.make<ReadonlySet<ProjectName>>(new Set());133 155- /** Whether the project's DO holds a project: it answers a read, not `UnknownProject`. */134 const isMade = (project: ProjectName) =>135 Effect.gen(function* () {136 if ((yield* Ref.get(known)).has(project)) {137 return true;32 unmodified linesmodified:apps/platform/src/adapters/draft-runs-workflow.ts+1 added-20 removed
1-/**2- * The project service's `DraftRuns` port over the `Answer` Workflow: a3- * draft's round runs as the instance `draftId` names (one per project,4- * proposal and round), with the round as params tagged `Draft`. The5- * instance asks the project's DO for what it needs, so the port carries6- * only the round.7- *8- * Starting twice is starting once (principle 8), as `answer-runs-workflow.ts`9- * does it: `create` refuses an id that exists, and the adapter takes the10- * instance it finds. Unlike an answer's, a round's run never waits to go on,11- * so a `complete` instance is left alone (a fresh run would ask the model12- * again for a round already settled); an `errored` or `terminated` one is13- * restarted from its first step. Any other failure is a defect: the outbox14- * row that asked for the start stays, and the project's next alarm runs it15- * again.16- */1 import { DraftRuns } from "@repo/project/draft-runs";2 import { Effect, Layer, Schema } from "effect";3 4 import { DraftParams, draftId } from "../answer-runs.ts";5 22-/** The part of a Workflow instance the adapter uses. */6 export interface DraftInstance {7 readonly id: string;8 readonly restart: () => Promise<void>;9 readonly status: () => Promise<{ readonly status: InstanceStatus["status"] }>;10 }11 29-/** The part of the `Answer` Workflow binding the adapter uses. */12 export interface DraftWorkflow {13 readonly create: (options: {14 readonly id: string;15 readonly params: typeof DraftParams.Encoded;2 unmodified lines18 }19 20 const encodeParams = Schema.encodeEffect(DraftParams);21 40-/** The states a round's run must run again from: it failed, or a person stopped it. */22+// A complete round is left alone: running it again would ask the model again.23 const failed: ReadonlySet<InstanceStatus["status"]> = new Set([24 "errored",25 "terminated",26 ]);27 46-/** Restarts the instance when its run failed; a running or complete one is left alone. */28 const runAgain = (instance: DraftInstance) =>29 Effect.gen(function* () {30 const { status } = yield* Effect.tryPromise(() => instance.status());31 25 unmodified linesmodified:apps/platform/src/adapters/fetch.ts+1 added-16 removed
1-/**2- * The `Fetch` port (`@repo/artifacts/fetch`) over the Worker's own `fetch`:3- * the one place the platform calls it, so every other caller goes through4- * the port and the `globalFetch` diagnostic holds everywhere else.5- */1 import { Fetch, FetchFailed } from "@repo/artifacts/fetch";2 import { Effect, Layer } from "effect";3 4 // @effect-diagnostics globalFetch:off -- the Worker's fetch is the one HTTP client; every caller goes through this port5 const send = (request: Request) => fetch(request);6 12-/**13- * Where a request went, as an error may say it: the origin and the path,14- * never a user name, a password or a query, so no credential travels in a15- * failure's text.16- */7+// Origin and path only, so no credential travels in a failure's text.8 const placeOf = (request: Request) => {9 const url = new URL(request.url);10 11 return `${url.origin}${url.pathname}`;12 };13 23-/** Why a request got no response, in words that carry no request header. */14 const reasonOf = (cause: unknown) =>15 cause instanceof Error16 ? `the request got no response: ${cause.name}`17 : "the request got no response";18 29-/**30- * Every request through the Worker's `fetch`. A response of any status is a31- * success; only a request that got none (the network, DNS or TLS failed) is32- * `FetchFailed`.33- */19 export const WorkerFetch: Layer.Layer<Fetch> = Layer.succeed(20 Fetch,21 Fetch.of({22 fetch: (request) =>7 unmodified linesmodified:apps/platform/src/adapters/identities-d1.ts-8 removed
1-/**2- * Identities on D1 (`FRONT_PAGE`'s database, table `identities` from3- * `migrations/0003_identities.sql`), through `effect/sql`, so the same code4- * runs on `@effect/sql-d1` in the Worker and on sqlite-node in tests. A5- * `SqlError` is a defect: the sign-in page answers 500, never a wrong6- * "already linked".7- */1 import { Handle } from "@repo/protocol/ids";2 import { Array, Effect, Layer, Option, Schema } from "effect";3 import { SqlClient } from "effect/sql/SqlClient";4 5 import { handleKey } from "../auth/accounts.ts";6 import { Identities, IdentityTaken } from "../auth/identities.ts";7 15-// What D1 hands back is decoded like any other outside input.8 const Rows = Schema.Array(Schema.Struct({ handle_key: Handle }));9 10 const decodeRows = Schema.decodeUnknownEffect(Rows);11 37 unmodified linesmodified:apps/platform/src/adapters/lander-sandbox.ts+1 added-13 removed
1-/**2- * `Lander` over the sandbox Worker: each job goes to the3- * trusted Lander container through the `SANDBOX` service binding, with the4- * fewest tokens it needs. Reads take read tokens: a merge on canonical, a5- * bundle on canonical. A merge's write token is on the answer's fork alone,6- * for the merged commit the Checker fetches. A write token on canonical goes only to7- * `land`, which moves `main` with a non-force compare-and-swap, and to8- * `compose`, which pushes its compose ref alone; never to a Checker, never9- * outside the platform's Workers. The outcome comes back as10- * the port's own types or its refusals: `StaleBase`, `RepoBusy`,11- * `VerifierBlocked`.12- */1+// A write token on canonical goes only to `land` (a non-force compare-and-swap) and `compose`, never to a Checker.2 import { RepoHost } from "@repo/artifacts/repo-host";3 import type { RepoName } from "@repo/artifacts/repo-host";4 import { Lander, Rebuild } from "@repo/project/lander";5 import {15 unmodified lines21 const read = (repo: RepoName): RemoteNeed => ({ repo, scope: "read" });22 23 const write = (repo: RepoName): RemoteNeed => ({ repo, scope: "write" });24 36-/** One land, with every remote its wire carries. */25 const landing = (sandbox: SandboxBinding, wire: typeof LandWire.Type) =>26 sandboxJob({27 exit: LandExit,28 job: wire,67 unmodified linesmodified:apps/platform/src/adapters/rate-limits.ts+3 added-26 removed
1-/**2- * `RateLimits` adapters. `WorkerRateLimits` asks the Worker's rate-limit3- * bindings, one per kind, keyed by the caller's handle in lowercase (handles4- * compare without case). `MemoryRateLimits` counts in a `Ref` its layer5- * makes, for tests: a whole test is one window, so a count never resets.6- */1 import { sameHandle } from "@repo/protocol/ids";2 import type { Handle } from "@repo/protocol/ids";3 import { CapReached } from "@repo/protocol/refusal";4 import { Effect, Layer, Ref } from "effect";5 6 import { RateLimits } from "../rate-limits.ts";7 import type { Limited } from "../rate-limits.ts";8 15-/** How many of each kind one person may make. */9 export interface Limits {10 readonly claim: number;11 readonly draft: number;12 readonly proposal: number;13 }14 22-/**23- * What `wrangler.jsonc` lets each binding admit per person, every 60 s, in24- * every stage: `CLAIM_LIMIT`, `DRAFT_LIMIT` and `PROPOSAL_LIMIT`'s25- * `simple.limit`. A binding26- * can't say its own limit, so a refusal reads its cap here.27- */15+// Mirrors each binding's `simple.limit` in wrangler.jsonc: a binding can't say its own limit.16 export const WorkerCaps = {17 claim: 10,18 draft: 2,19 proposal: 5,20 } as const satisfies Limits;21 34-/** Which limit a refusal names for each kind it counts. */22 const LIMIT_OF = {23 claim: "claims",24 draft: "drafts",25 proposal: "proposals",26 } as const satisfies Record<Limited, CapReached["limit"]>;27 41-/**42- * How long a refused caller waits, in seconds: the bindings' 60 s period. A43- * binding can't say when its window resets, so the whole period is the44- * honest upper bound. It describes the bindings; it configures nothing.45- */28+// A binding can't say when its window resets, so the whole 60 s period is the honest upper bound.29 const WINDOW_SECONDS = 60;30 48-/** A refusal for one more of `kind` than `limits` allow, with when to try again. */31 const capped = (limits: Limits, kind: Limited) =>32 new CapReached({33 cap: limits[kind],34 limit: LIMIT_OF[kind],35 retryAfter: WINDOW_SECONDS,36 });37 56-/**57- * The Worker's rate limits, one binding per kind. A binding that fails is a58- * defect: a call it could not count is not let through.38+// A binding that fails is a defect: a call it could not count is not let through.59- */39 export const WorkerRateLimits = (bindings: {40 readonly claim: RateLimit;41 readonly draft: RateLimit;42 readonly proposal: RateLimit;12 unmodified lines55 ),56 })57 );58 80-/** One spend: of which kind, by whom. */59 interface Spent {60 readonly handle: Handle;61 readonly kind: Limited;62 }63 86-/** `limits` of each kind per person, counted in memory. */64 export const MemoryRateLimits = (limits: Limits): Layer.Layer<RateLimits> =>65 Layer.effect(66 RateLimits,67 Effect.gen(function* () {18 unmodified linesmodified:apps/platform/src/adapters/sandbox-credentials.ts+3 added-56 removed
1-/**2- * The only credentials a sandbox job carries, and the one way a job crosses3- * the `SANDBOX` service binding: the sandbox Worker has no4- * Artifacts binding, so each job takes a token the platform minted for it5- * alone, on one repo (tokens are per repo), with the narrowest scope6- * the job needs and a lifetime of minutes, revoked as soon as the job ends.7- * A token never appears in a result, a refusal or a log: it8- * crosses the binding in plain text, as the far side needs it, but decodes to9- * a `Redacted` on either side; refusals carry no free text (principle 3); and10- * what any failure log says, a failed revoke's included, is scrubbed of every11- * token the job carried.12- *13- * A job is encoded with the wire schemas both sides share, and its outcome14- * comes back as a JSON `Exit` decoded here (principle 2): a typed refusal15- * stays typed; anything else (a rejected call, an outcome that won't decode,16- * a defect on the far side) is `VerifierBlocked`, the gate's trouble and17- * never the answer's, with one error-level log line naming the method.18- */1 import { RepoHost } from "@repo/artifacts/repo-host";2 import type {3 RepoName,4 RepoNotFound,11 unmodified lines16 Redacted,17 Schema,18 } from "effect";19 38-/**39- * How long a job's token lives: enough for a cold container to start and40- * fetch, short enough that a token outliving its job is dead within41- * minutes (an expired token gets 403). Each is revoked when its job42- * ends, so this bounds only a revoke that failed.20+// Each token is revoked when its job ends, so this bounds only a revoke that failed.43- */21 export const jobTokenTtl = Duration.minutes(5);22 46-/** The sandbox entrypoint's methods: the one name every failure log carries. */23 export type SandboxMethod =24 | "bundleRules"25 | "check"26 | "compose"27 | "land"28 | "merge";29 54-/** One repo a job reaches, and what it may do there. */30 export interface RemoteNeed {31 readonly repo: RepoName;32 readonly scope: TokenScope;33 }34 60-/** The longest failure detail a log line keeps. */35 const DETAIL_LIMIT = 2000;36 63-/**64- * `text` without any token the job carried, cut to `DETAIL_LIMIT`: the far65- * side holds the tokens and may echo one in an error.37+// The far side holds the tokens and may echo one in an error.66- */38 const scrub = (text: string, remotes: readonly Remote[]) => {39 let scrubbed = text;40 41 for (const { token } of remotes) {6 unmodified lines48 49 return scrubbed.slice(0, DETAIL_LIMIT);50 };51 81-/**82- * The job could not run: one error-level log line, then `VerifierBlocked`,83- * which carries no free text; what went wrong goes in the annotations.84- */52 const blocked = (53 method: SandboxMethod,54 annotations: Readonly<Record<string, string>>55 ) =>1 unmodified line57 Effect.annotateLogs({ ...annotations, method }),58 Effect.andThen(Effect.fail(new VerifierBlocked({})))59 );60 94-/** A repo the store does not know: the job cannot run. */61 const unknownRepo =62 (method: SandboxMethod) =>63 ({ name }: RepoNotFound) =>64 blocked(method, { failure: "repo not found", repo: name });65 100-/**101- * Mints a `need.scope` token on `need.repo` for one job, hands `use` its102- * remote, and revokes the token once `use` ends, however it ends. A revoke103- * that fails, or dies, is logged with the token scrubbed, never raised: the104- * token dies with its lifetime. A repo the store does not know is105- * `VerifierBlocked` for `method`.106- */66+// A failed revoke is logged with the token scrubbed, never raised: the token dies with its lifetime.67 export const withRemote = <A, E, R>(68 method: SandboxMethod,69 need: RemoteNeed,70 use: (remote: Remote) => Effect.Effect<A, E, R>29 unmodified lines100 )101 );102 });103 144-/** Why a job's outcome never arrived as a typed `Exit`. */104 class Unreached extends Data.TaggedError("Unreached")<{105 readonly failure: "rejected" | "undecodable" | "unencodable";106 readonly detail: string;107 }> {}108 150-/** One job for the sandbox: what to send, and how its wire and outcome are coded. */109 export interface SandboxJob<W, WI, A, E, X> {110 readonly method: SandboxMethod;111 readonly wire: Schema.Codec<W, WI>;112 readonly exit: Schema.Codec<Exit.Exit<A, E>, X>;113 readonly job: W;156- /** Every remote `job` carries: their tokens are scrubbed from failure logs. */114 readonly remotes: readonly Remote[];158- /** The binding's method, called with the encoded job. */115 readonly send: (encoded: WI) => Promise<X>;116 }117 162-/**163- * An outcome as the port gives it: the success, a typed refusal as itself,164- * and a defect or an interruption on the far side as `VerifierBlocked`.165- */118 const settle = <A, E>(119 method: SandboxMethod,120 remotes: readonly Remote[],121 exit: Exit.Exit<A, E>8 unmodified lines130 }),131 onSome: (refusal): Effect.Effect<never, E> => Effect.fail(refusal),132 });133 182-/**183- * Sends one job and settles its outcome into the Effect's channels; a job184- * whose outcome never arrived as an `Exit` is `VerifierBlocked`. Each185- * failure is logged once, at error level.186- */134 export const sandboxJob = <W, WI, A, E, X>(135 call: SandboxJob<W, WI, A, E, X>136 ): Effect.Effect<A, E | VerifierBlocked> =>137 Schema.encodeEffect(call.wire)(call.job).pipe(25 unmodified linesmodified:apps/platform/src/adapters/sessions-oauth.ts-14 removed
1-/**2- * Sessions for the platform's own OAuth access tokens: the provider looks3- * the token up in `OAUTH_KV` by its hash and decrypts the grant's props,4- * which carry only `{ handle }`. A token the provider does not know, one5- * past its expiry, or one whose props name no handle verifies as nobody.6- * The Worker puts these first in `firstOf`, before the operator and7- * `SESSION_TOKENS` tables.8- */1 import { Handle } from "@repo/protocol/ids";2 import { Person } from "@repo/protocol/principal";3 import { Clock, Effect, Option, Schema } from "effect";4 5 import { Sessions } from "../sessions.ts";6 15-/** What a grant's props carry: who signed in. */7 const GrantProps = Schema.Struct({ handle: Handle });8 9 const decodeProps = Schema.decodeUnknownOption(GrantProps);10 20-/**21- * What a session needs from the provider: a token's record, its props22- * decrypted, or nothing for a token it does not know or that has expired23- * (`OAuthHelpers.unwrapToken`; `auth/provider.ts`'s `tokenReader`).24- */11 export interface TokenReader {12 readonly unwrapToken: (token: string) => Promise<{13 readonly expiresAt: number;14 readonly grant: { readonly props: unknown };18 unmodified linesmodified:apps/platform/src/auth/accounts/memory.ts-4 removed
1 unmodified line2 3 import { Accounts, handleKey, HandleTaken } from "../accounts.ts";4 import type { Account } from "../accounts.ts";5 6-/**7- * Accounts in memory, keyed like D1's table, for tests and local runs: a8- * fresh, empty store each time the layer is built.9- */6 export const AccountsMemory = {7 layer: Layer.effect(8 Accounts,9 Effect.gen(function* () {37 unmodified linesmodified:apps/platform/src/auth/attempts/binding.ts-5 removed
1 import { Effect, Layer } from "effect";2 3 import { SignInAttempts } from "../attempts.ts";4 5-/**6- * Attempts counted by a Workers ratelimit binding (`SIGN_IN_LIMIT`: five a7- * minute per key, per Cloudflare location). Every call counts, admitted or8- * not; a binding that cannot answer is a defect, never an admission.9- */5 export const SignInAttemptsBinding = (limiter: RateLimit) =>6 Layer.succeed(7 SignInAttempts,8 SignInAttempts.of({6 unmodified linesmodified:apps/platform/src/auth/attempts/memory.ts-5 removed
5 unmodified lines6 readonly count: number;7 readonly startedAt: number;8 }9 10-/**11- * Attempts in memory, for tests and local runs: a fixed window per key that12- * opens at its first attempt and admits `AttemptPolicy.limit` until13- * `AttemptPolicy.period` has passed. A refused attempt is not counted.14- */10 export const SignInAttemptsMemory = {11 layer: Layer.effect(12 SignInAttempts,13 Effect.gen(function* () {31 unmodified linesmodified:apps/platform/src/auth/identities/memory.ts-5 removed
2 unmodified lines3 4 import { handleKey } from "../accounts.ts";5 import { Identities, IdentityTaken } from "../identities.ts";6 7-/** A link's key: the provider and the subject, as D1's primary key pairs them. */7 const keyOf = (provider: string, subject: string) => `${provider}\n${subject}`;8 10-/**11- * Links in memory, keyed like D1's table: by (provider, subject), each to a12- * handle's key. A fresh, empty store each time the layer is built.13- */9 export const IdentitiesMemory = {10 layer: Layer.effect(11 Identities,12 Effect.gen(function* () {34 unmodified linesmodified:apps/platform/src/auth/oauth-store/memory.ts+1 added-6 removed
3 unmodified lines4 import type { OAuthStoreList } from "../oauth-store.ts";5 6 const parseJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Json));7 8-/**9- * `OAUTH_KV` in memory, for tests and local runs: values as text with their10- * metadata, listed by prefix in key order, one page. TTLs are not kept: a11- * record lives until it is deleted.8+// TTLs are not kept: a record lives until it is deleted.12- */9 const make = (): OAuthStore["Service"] => {10 const records = new Map<string, { metadata: unknown; value: string }>();11 12 return {29 unmodified lines42 };43 };44 45 export const OAuthStoreMemory = {50- /** A fresh, empty store each time the layer is built. */46 layer: Layer.sync(OAuthStore, make),47 make,48 };modified:apps/platform/src/auth/accounts.ts+1 added-12 removed
1-/**2- * Accounts: the platform's own people, each a handle and a password hash.3- * The handle is how the platform knows them; two handles that differ only4- * in case are one account (protocol's `sameHandle`).5- */1 import type { Handle } from "@repo/protocol/ids";2 import { Context, Data } from "effect";3 import type { Effect, Option } from "effect";4 5 import type { PasswordHash } from "./password.ts";6 12-/** An account as the platform keeps it: its handle as it was chosen, and its hash. */7 export interface Account {8 readonly handle: Handle;9 readonly hash: PasswordHash;10 }11 18-/** Someone already signed up with this handle, in some case. Internal to `auth/`. */12 export class HandleTaken extends Data.TaggedError("HandleTaken")<{13 readonly handle: Handle;14 }> {}15 23-/**24- * The key an account is stored under: the handle lowercased, the same rule25- * `sameHandle` compares by, so a racing second sign-up fails on the key.16+// The rule `sameHandle` compares by, so a racing second sign-up fails on the key.26- */17 export const handleKey = (handle: Handle) => handle.toLowerCase();18 29-/** Where accounts live: `/memory` for tests, D1 on Cloudflare (`adapters/accounts-d1.ts`). */19 export class Accounts extends Context.Service<20 Accounts,21 {22 readonly create: (10 unmodified linesmodified:apps/platform/src/auth/attempts.ts+1 added-8 removed
1-/**2- * Sign-in attempts: how many tries one key (a handle, or a client's3- * address) gets before the platform stops checking passwords for it for a4- * while. `/memory` for tests, the `SIGN_IN_LIMIT` ratelimit binding on5- * Cloudflare (`attempts/binding.ts`).6- */1 import { Context, Duration } from "effect";2 import type { Effect } from "effect";3 10-/** Five attempts a minute per key, as `wrangler.jsonc` sets `SIGN_IN_LIMIT`. */4+// Mirrors `SIGN_IN_LIMIT` in wrangler.jsonc.5 export const AttemptPolicy = {6 limit: 5,7 period: Duration.minutes(1),8 } as const;9 10 export class SignInAttempts extends Context.Service<11 SignInAttempts,12 {19- /** Counts one attempt under `key`; false once the key has used its allowance. */13 readonly admit: (key: string) => Effect.Effect<boolean>;14 }15 >()("platform/SignInAttempts") {}modified:apps/platform/src/auth/cli-client.ts+1 added-10 removed
1-/**2- * The CLI's OAuth client: fixed and public. It signs in with PKCE only and3- * gets its code at a loopback redirect on whatever port it listens on (RFC4- * 8252: the provider matches loopback redirects without the port). Its5- * `client_id` is the URL of this Client ID Metadata Document, which the6- * platform serves itself, so nothing is registered at bootstrap.7- */1 import { Brand } from "@repo/brand";2 10-/** Where the platform serves the CLI's metadata document; its URL is the CLI's client id. */3 export const CLI_CLIENT_PATH = "/oauth/cli";4 13-/** The CLI's client id on the platform at `origin`. */5 export const cliClientId = (origin: string) => `${origin}${CLI_CLIENT_PATH}`;6 16-/** The CLI's Client ID Metadata Document, as the platform at `origin` serves it. */7+// RFC 8252: the provider matches loopback redirects without the port.8 export const cliClientMetadata = (origin: string) => ({9 client_id: cliClientId(origin),10 client_name: `${Brand.name} CLI`,11 grant_types: ["authorization_code", "refresh_token"] as const,7 unmodified linesmodified:apps/platform/src/auth/google.ts+7 added-135 removed
1-/**2- * Google sign-in: a second way to prove who you are, beside a3- * password, offered only when the platform has a Google OAuth client4- * (`GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`; human step H4).5- *6- * The first half is Google's OpenID Connect client: the authorization7- * request (a code, `openid` only, PKCE by S256, a nonce), the code exchange8- * at the token endpoint, and the ID token's check, by WebCrypto against9- * Google's published keys. All of it goes through the `Fetch` port. The10- * person is Google's stable subject id (`sub`) alone: no email, no name,11- * and no Google token is kept after the exchange.12- *13- * The second half is its routes beside sign-in's own (`sign-in.ts`):14- * "Continue with Google" from the sign-in page, Google's redirect back, the15- * handle a first Google sign-in chooses (sign-up's rules), and linking16- * Google to an account signed in by password. Each ends as a password17- * sign-in does: the client gets a code for a token whose props are only18- * `{ handle }`. A known subject goes straight to its handle; links live19- * behind the `Identities` port.20- */1+// Only Google's stable subject id (`sub`) is kept: no email, no name, and no Google token after the exchange.2 import { Fetch } from "@repo/artifacts/fetch";3 import { Handle } from "@repo/protocol/ids";4 import {5 Array,44 unmodified lines50 SignInFailed,51 startAgain,52 } from "./state.ts";53 73-/** Google's sign-in origin: where the authorization request sends a person. */54 export const GOOGLE_ACCOUNTS = "https://accounts.google.com";55 76-/** Google's discovery document: its token endpoint and where its keys are. */56 export const GOOGLE_DISCOVERY = `${GOOGLE_ACCOUNTS}/.well-known/openid-configuration`;57 58 const AUTHORIZE_ENDPOINT = `${GOOGLE_ACCOUNTS}/o/oauth2/v2/auth`;59 81-/** The two spellings of Google's issuer an ID token may carry. */60 const ISSUERS: ReadonlySet<string> = new Set([61 GOOGLE_ACCOUNTS,62 "accounts.google.com",63 ]);64 87-/**88- * The person as Google knows them: unique among Google accounts, never89- * reused, at most 255 ASCII characters.90- */65 export const GoogleSubject = Schema.String.check(66 Schema.isNonEmpty(),67 Schema.isMaxLength(255)68 ).pipe(Schema.brand("GoogleSubject"));69 70 export type GoogleSubject = typeof GoogleSubject.Type;71 98-/** Signing in with Google did not confirm anyone, said the same way whatever the cause. */72+// Said the same way whatever the cause.73 const unconfirmed = new SignInFailed({74 reason:75 "Google did not confirm who you are. Try again, or sign in with your password.",76 });77 104-/**105- * Where Google's authorization request sends the browser: a code, scope106- * `openid` only, the PKCE challenge (S256), the platform's sealed `state`,107- * and a `nonce` the ID token must carry back.108- */78 export const googleAuthorizeUrl = (input: {79 readonly clientId: string;80 readonly codeChallenge: string;81 readonly nonce: string;15 unmodified lines97 98 return url.toString();99 };100 132-/** What the platform reads from Google's discovery document. */101 const Discovery = Schema.Struct({102 jwks_uri: Schema.String,103 token_endpoint: Schema.String,104 });105 106 type Discovery = typeof Discovery.Type;107 140-/** One RS256 signing key in Google's JWKS; any other key is skipped. */108 const SigningKey = Schema.Struct({109 alg: Schema.optionalKey(Schema.Literal("RS256")),110 e: Schema.String,111 kid: Schema.String,5 unmodified lines117 const decodeSigningKey = Schema.decodeUnknownOption(SigningKey);118 119 const KeySet = Schema.Struct({ keys: Schema.Array(Schema.Unknown) });120 154-/** What the token endpoint answers, as far as the platform reads it: only the ID token. */121 const TokenResponse = Schema.Struct({ id_token: Schema.String });122 157-/** An ID token's header: RS256 only, and the key it names. */123 const Header = Schema.Struct({124 alg: Schema.Literal("RS256"),125 kid: Schema.String,126 });127 163-/** The claims the platform checks; the rest are never read. */128 const Claims = Schema.Struct({129 aud: Schema.Union([Schema.String, Schema.Array(Schema.String)]),130 azp: Schema.optionalKey(Schema.String),131 exp: Schema.Finite,1 unmodified line133 nonce: Schema.optionalKey(Schema.String),134 sub: GoogleSubject,135 });136 173-/** A JWT segment: base64url of JSON. */137 const segment = <S extends Schema.Codec<unknown, unknown>>(schema: S) =>138 Schema.decodeEffect(139 Schema.StringFromBase64Url.pipe(140 Schema.decodeTo(Schema.fromJsonString(schema))9 unmodified lines150 const RSA = { hash: "SHA-256", name: "RSASSA-PKCS1-v1_5" } as const;151 152 const utf8 = (text: string) => new TextEncoder().encode(text);153 191-/** `request`'s answer as `schema`, or nobody confirmed: no answer, not 2xx, or not the shape. */154 const answerOf = <A>(155 fetch: Fetch["Service"],156 schema: Schema.Codec<A, unknown>,157 request: Request16 unmodified lines174 Effect.mapError(() => unconfirmed)175 );176 });177 216-/** `key` as a WebCrypto RS256 verification key, or none if it does not import. */178 const imported = (key: typeof SigningKey.Type) =>179 Effect.tryPromise(() =>180 crypto.subtle.importKey(181 "jwk",6 unmodified lines188 Effect.map((verifier) => Option.some([key.kid, verifier] as const)),189 Effect.orElseSucceed(() => Option.none())190 );191 231-/**232- * Google's endpoints and signing keys, kept for the isolate's life: the233- * discovery document is read once, and the keys by `kid` once, then read234- * again once whenever an ID token names a key not kept (Google rotates235- * them). Only a success is kept.236- */192+// Keys are read again when an ID token names one not kept (Google rotates them); only a success is kept.193 export class GoogleKeys extends Context.Service<194 GoogleKeys,195 {196 readonly discovery: Effect.Effect<Discovery, SignInFailed>;197 readonly key: (kid: string) => Effect.Effect<CryptoKey, SignInFailed>;198 }199 >()("platform/GoogleKeys") {}200 245-/**246- * `GoogleKeys` over `Fetch`, empty until first used. The sign-in routes247- * build it once, with the router, so it lives as long as the isolate.248- */201 export const GoogleKeysPerIsolate = Layer.effect(202 GoogleKeys,203 Effect.gen(function* () {204 const fetch = yield* Fetch;58 unmodified lines263 });264 })265 );266 315-/** Whether the token was issued to this client: its audience, and its authorized party when named. */267 const issuedTo = (claims: typeof Claims.Type, clientId: string) => {268 const audience = Predicate.isString(claims.aud) ? [claims.aud] : claims.aud;269 270 return (2 unmodified lines273 (audience.length === 1 || claims.azp === clientId)274 );275 };276 326-/**327- * The subject of `token`, if Google signed it (RS256, a key from its JWKS)328- * for this client, it has not expired, and it carries `nonce`.329- */277 const verifiedSubject = (278 token: string,279 expected: { readonly clientId: string; readonly nonce: string }280 ) =>44 unmodified lines325 326 return holds ? said.sub : yield* unconfirmed;327 });328 382-/**383- * The person Google confirms for `code`: the code is exchanged at Google's384- * token endpoint (with the client's secret and the PKCE verifier), and the385- * ID token in the answer is checked. Google's other tokens in the answer386- * are never read, and nothing of the answer is kept.387- */329+// Google's other tokens in the answer are never read, and nothing of it is kept.330 export const googleSubject = (input: {331 readonly clientId: string;332 readonly clientSecret: Redacted.Redacted;333 readonly code: string;30 unmodified lines364 365 return yield* verifiedSubject(id_token, input);366 });367 426-/** A Google OAuth client: its id, and its secret. */368 interface Client {369 readonly id: string;370 readonly secret: Redacted.Redacted;371 }372 432-/** The platform's Google OAuth client, when it has one: Google sign-in is offered only then. */373 export class GoogleClient extends Context.Service<374 GoogleClient,375 { readonly client: Option.Option<Client> }376 >()("platform/GoogleClient") {}377 438-/** What a Google sign-in's pages say, besides sign-in's own sentences. */378 const GoogleSays = {379 linkedElsewhere:380 "That Google account is linked to another handle. Sign in with that handle, or use another Google account.",381 } as const;382 444-/**445- * The cookie Google's leg keeps its PKCE verifier in, so the verifier446- * never travels in a URL. `SameSite=Lax`: Google's redirect back is a447- * top-level navigation from another site, which a `Strict` cookie misses.448- */383+// `SameSite=Lax`: Google's redirect back is a cross-site top-level navigation, which a `Strict` cookie misses.384 const GOOGLE_COOKIE = "__Host-google-sign-in";385 386 const googleCookie = {387 httpOnly: true,1 unmodified line389 sameSite: "lax",390 secure: true,391 } as const;392 458-/** Google's leg is over: its cookie goes. */393 const legDone = (response: HttpServerResponse.HttpServerResponse) =>394 response.pipe(395 HttpServerResponse.setCookie(GOOGLE_COOKIE, "", {396 ...googleCookie,1 unmodified line398 }),399 Effect.orDie400 );401 468-/**469- * Google's leg of a sign-in, sealed with `COOKIE_KEY` into the `state`470- * Google sends back: the sign-in it continues, the S256 challenge of the471- * verifier in this browser's cookie (so only this browser finishes it),472- * the nonce the ID token must carry, and the handle to link Google to when473- * a person signed in by password asked to link it.474- */402+// Carries the challenge of the verifier in this browser's cookie, so only this browser finishes the leg.403 const GoogleLeg = Schema.Struct({404 challenge: Schema.String,405 link: Schema.optionalKey(Handle),406 nonce: Schema.String,1 unmodified line408 });409 410 const legs = sealing("google-leg", GoogleLeg);411 484-/**485- * A first Google sign-in waiting for its handle, sealed into the form that486- * chooses it: the person Google confirmed, the sign-in it continues, and487- * the form's CSRF token.488- */412 const PendingHandle = Schema.Struct({413 csrf: Schema.String,414 request: AuthRequest,415 subject: GoogleSubject,2 unmodified lines418 const pendingHandles = sealing("google-handle", PendingHandle);419 420 const encodeBytes = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);421 499-/**500- * 32 fresh random bytes, base64url: a PKCE verifier (43 characters, RFC501- * 7636), a nonce, or a password nobody is ever told.502- */422 const freshSecret = Effect.sync(() =>423 crypto.getRandomValues(new Uint8Array(32))424 ).pipe(Effect.flatMap(encodeBytes), Effect.orDie);425 507-/** The S256 challenge of a PKCE verifier: its SHA-256, base64url. */426 const challengeOf = (verifier: string) =>427 Effect.promise(() => crypto.subtle.digest("SHA-256", utf8(verifier))).pipe(428 Effect.flatMap((digest) => encodeBytes(new Uint8Array(digest))),429 Effect.orDie430 );431 514-/** Where Google sends the browser back: this origin's callback, as H4 registers it. */432 const callbackUri = (origin: string) => `${origin}${GOOGLE_PATHS.callback}`;433 517-/**518- * To Google, for the sign-in `request` continues: a fresh PKCE verifier in519- * this browser's cookie, and the leg sealed as the `state`.520- */434 const toGoogle = (435 client: Client,436 request: AuthRequest,437 link: Option.Option<Handle>42 unmodified lines480 Effect.orDie481 );482 });483 571-/**572- * `GET /oauth/google/start?request=<sealed>`: "Continue with Google" from573- * the sign-in page this browser opened (its CSRF cookie matches the seal),574- * to Google.575- */484 const start =485 (client: Client) => (request: HttpServerRequest.HttpServerRequest) =>486 Effect.gen(function* () {487 const { cookieKey } = yield* SignInKeys;10 unmodified lines498 499 return yield* toGoogle(client, pending.request, Option.none());500 });501 594-/**595- * `POST /oauth/google/link`: "Sign in and link Google". Signed in by handle596- * and password first (sign-in's checks and limits), then to Google, to link597- * the Google account to that handle.598- */502 const link =503 (client: Client) => (request: HttpServerRequest.HttpServerRequest) =>504 byPassword(request, (handle, pending) =>505 toGoogle(client, pending.request, Option.some(handle))506 );507 605-/** The page to choose a handle on, for the person Google confirmed. */508 const pickHandle = (509 subject: GoogleSubject,510 request: AuthRequest,511 status: number,29 unmodified lines541 Effect.orDie542 );543 });544 643-/**644- * The person Google confirmed: back to the client as the handle their645- * subject is linked to, or, the first time, the page to choose one. A link646- * whose account is gone names nobody.647- */545 const signedInAs = (subject: GoogleSubject, request: AuthRequest) =>546 Effect.gen(function* () {547 const identities = yield* Identities;548 12 unmodified lines561 onSome: (found) => completed(found.handle, request),562 });563 });564 668-/**669- * Links the Google account to `handle`, then back to the client as it; a670- * Google account another handle holds stays theirs, and is refused.671- */565 const linkedTo = (566 subject: GoogleSubject,567 handle: Handle,568 request: AuthRequest15 unmodified lines584 code: Schema.optionalKey(Schema.String),585 state: Schema.String,586 });587 695-/**696- * `GET /oauth/google/callback?code=…&state=…`: Google sends the browser697- * back. A `state` this platform did not seal, or this browser did not698- * start, is a sign-in to start again. Past that, Google not confirming the699- * person (a refusal, a bad ID token) shows the sign-in page again with a700- * plain message; a confirmed person is signed in, linked, or asked for a701- * handle.702- */588 const cameBack =589 (client: Client) => (request: HttpServerRequest.HttpServerRequest) =>590 Effect.gen(function* () {591 const { cookieKey } = yield* SignInKeys;50 unmodified lines642 handle: Schema.String,643 request: Schema.String,644 });645 761-/**762- * `POST /oauth/google/handle`: the person Google confirmed takes a handle,763- * by sign-up's rules and limit, and is signed in as it, with Google linked.764- * The account's password is one nobody is told: Google signs it in. A765- * subject linked meanwhile (the form posted twice) signs in as its handle.766- */646+// The account's password is one nobody is told: Google signs it in.647 const handleChosen = (request: HttpServerRequest.HttpServerRequest) =>648 Effect.gen(function* () {649 const { cookieKey, pepper } = yield* SignInKeys;650 60 unmodified lines711 712 return yield* linkedTo(pending.subject, checked.success, pending.request);713 });714 835-/** What Google sign-in's routes run on, besides the request's own `Authorization`. */715 export type GoogleServices = Fetch | GoogleClient | Identities | SignInServices;716 838-/**839- * Google sign-in's routes, added only when the platform has a Google OAuth840- * client: without one there are none, and their paths answer 404. Each841- * runs with the services taken once when the router is built, Google's842- * keys among them, so the keys live as long as the router (the isolate).843- */717 export const googleRoutes = HttpRouter.use((router) =>718 Effect.gen(function* () {719 const { client } = yield* GoogleClient;720 11 unmodified lines732 Context.add(SignInKeys, yield* SignInKeys),733 Context.add(SignInOffers, yield* SignInOffers)734 );735 863- /** Adds a route, its failures shown as pages and the services provided. */736 const add = <R>(737 method: "GET" | "POST",738 path: HttpRouter.PathInput,739 handler: (16 unmodified linesmodified:apps/platform/src/auth/identities.ts+1 added-22 removed
1-/**2- * Identities: a person's account at an outside provider, linked to a3- * platform handle. Only the provider's stable subject id is4- * kept against the handle's key: no email, no name, no token. Google is5- * the one provider; the handle stays how the platform knows the person.6- */1 import type { Handle } from "@repo/protocol/ids";2 import { Context, Data } from "effect";3 import type { Effect, Option } from "effect";4 11-/** The outside providers a person may sign in with. */5 export type IdentityProvider = "google";6 14-/**15- * The provider's account is already linked to another handle. Internal to16- * `auth/`: it renders as a page with a plain message, never a refusal.17- */7 export class IdentityTaken extends Data.TaggedError("IdentityTaken")<{8 readonly provider: IdentityProvider;9 readonly subject: string;10 }> {}11 23-/**24- * Where links live: `/memory` for tests, D1 on Cloudflare25- * (`adapters/identities-d1.ts`). A link is keyed by (provider, subject), so26- * one outside account names one handle; linking it again to the same27- * handle, in any case, changes nothing.28- */12 export class Identities extends Context.Service<13 Identities,14 {32- /**33- * The handle the subject is linked to, as its key (lowercased, as34- * `accounts` keys it): find the account by it, and show the account's35- * own handle, never this one.36- */15+ // The handle's key, lowercased: show the account's own handle, never this one.16 readonly handleOf: (17 provider: IdentityProvider,18 subject: string19 ) => Effect.Effect<Option.Option<Handle>>;7 unmodified linesmodified:apps/platform/src/auth/oauth-store.ts+1 added-8 removed
1-/**2- * Where the OAuth provider keeps clients, grants and tokens: `OAUTH_KV` on3- * Cloudflare, `/memory` in tests. The shape is only the calls the provider4- * makes (1.2.1: `get` as text or JSON, `put` with a TTL and metadata,5- * `delete`, `list` by prefix), so a `KVNamespace` is one as it is. Tokens,6- * codes and secrets are stored there only as hashes, and props encrypted.7- */1+// Only the calls the provider makes, so a `KVNamespace` is one as it is.2 import { Context } from "effect";3 import type { Schema } from "effect";4 11-/** One page of keys under a prefix, as KV lists them. */5 export interface OAuthStoreList {6 readonly cursor?: string;7 readonly keys: readonly {8 readonly metadata?: unknown;29 unmodified linesmodified:apps/platform/src/auth/pages.ts+5 added-45 removed
1-/**2- * The sign-in and sign-up pages: small server-rendered HTML that loads3- * nothing (no script, stylesheet, font or image), so the page's CSP can be4- * `default-src 'none'`. Every value that reaches the HTML is escaped; the5- * client's name and domain come from the client itself. Google sign-in6- * adds its two choices to the sign-in page when offered, and7- * its own page for a first sign-in's handle.8- */1+// Loads nothing (no script, stylesheet, font or image), so the page's CSP can be `default-src 'none'`.2 import { Brand } from "@repo/brand";3 11-/** What the person must see about who asks (MCP: the client, and where access goes). */4 export interface Asker {5 readonly clientDomain?: string | undefined;6 readonly clientName: string;7 readonly redirectHost: string;8 readonly redirectIsLoopback: boolean;9 }10 19-/** The hidden fields a sign-in form carries back: the sealed request and its CSRF token. */11 export interface PendingForm {12 readonly csrf: string;13 readonly request: string;14 }15 25-/** What the sign-in page offers besides a password. */16 export interface Offers {17 readonly google: boolean;18 }19 30-/** The paths Google sign-in's forms and links reach (`google.ts` serves them). */20 export const GOOGLE_PATHS = {21 callback: "/oauth/google/callback",22 handle: "/oauth/google/handle",23 link: "/oauth/google/link",24 start: "/oauth/google/start",25 } as const;26 38-/** `text` safe inside HTML text and a quoted attribute (`&` first). */27+// `&` first.28 export const escapeHtml = (text: string) =>29 text30 .replaceAll("&", "&")31 .replaceAll("<", "<")32 .replaceAll(">", ">")33 .replaceAll('"', """)34 .replaceAll("'", "'");35 47-/**48- * The web's look, as far as a page that loads nothing can take it: its49- * tokens as literal colours for both schemes (paper, ink, surface, muted,50- * rule, the input border at 3:1, refused for an error, waiting for a51- * warning), square controls with hairline borders, a 2 px ink focus ring.52- * The type is the system's sans, since no font may load here.36+// The system's sans, since no font may load here.53- */37 const STYLE = `38 :root{color-scheme:light dark;--paper:#f5f8fa;--ink:#14191f;--surface:#edf0f3;--muted:#595e65;--rule:#ced1d6;--input:#82868c;--refused:#b32322;--waiting:#875814;--selection:#175fa438}39 @media (prefers-color-scheme:dark){:root{--paper:#0e1114;--ink:#e9ebee;--surface:#171a1e;--muted:#a1a5ab;--rule:#32363b;--input:#6e7278;--refused:#f87e77;--waiting:#efba64;--selection:#79b6f438}}40 *{box-sizing:border-box}31 unmodified lines72 ul{margin:0;padding-left:1.25rem}73 li{margin:0 0 8px}74 `;75 93-/** How wide a page reads: a form's one column, or a document's. */76 type Width = "form" | "document";77 96-/** A page titled `title` around `body`, which is HTML already escaped. */78+// `body` is HTML already escaped.79 export const page = (title: string, body: string, width: Width = "form") =>80 `<!doctype html>81 <html lang="en">82 <head>8 unmodified lines91 </main></body>92 </html>93 `;94 113-/** A warning's mark: a triangle drawn in the line's colour, hidden from a screen reader. */95 const WARNING_MARK = `<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M8 1.75 14.75 14H1.25z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/><path d="M8 6.25v3.5M8 11.75v.25" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>`;96 116-/**117- * The consent, first under the title in its own ruled block: who asks,118- * where access goes, and the loopback warning when it applies.119- */97 const askerParagraphs = (asker: Asker) => {98 const name = `<strong>${escapeHtml(asker.clientName)}</strong>`;99 100 const domain =20 unmodified lines121 const hiddenFields = (form: PendingForm) =>122 `<input type="hidden" name="request" value="${escapeHtml(form.request)}">123 <input type="hidden" name="csrf" value="${escapeHtml(form.csrf)}">`;124 148-/**149- * Google's two choices, when offered: signing in with Google (a link, so150- * no form posts to Google), and, beside the password form's own button,151- * signing in by password and then linking Google to the account.152- */125+// A link, so no form posts to Google.126 const googleChoices = (offers: Offers, form: PendingForm) =>127 offers.google128 ? {129 link: `<button type="submit" class="secondary" formaction="${GOOGLE_PATHS.link}">Sign in and link Google</button>`,1 unmodified line131 <p class="muted">Or sign in with your handle and password.</p>`,132 }133 : { link: "", start: "" };134 162-/** The sign-in form, posting back to `/authorize`, with a way to sign up instead. */135 export const signInPage = (136 asker: Asker,137 form: PendingForm,138 offers: Offers,19 unmodified lines158 <p>New here? <a href="/signup?request=${encodeURIComponent(form.request)}">Choose a handle and sign up</a>.</p>`159 );160 };161 190-/**191- * A first sign-in with Google: Google confirmed the person, and they choose192- * the handle the platform will know them by (sign-up's rules), posting to193- * Google sign-in's handle path. One who has a password account signs in194- * with it instead, and links Google from there.195- */162 export const pickHandlePage = (163 asker: Asker,164 form: PendingForm,165 signInHref: string,12 unmodified lines178 </form>179 <p>Have an account with a password? <a href="${escapeHtml(signInHref)}">Sign in with it</a> and choose "Sign in and link Google".</p>`180 );181 216-/** The sign-up form, posting to `/signup`, with a way back to signing in. */182 export const signUpPage = (183 asker: Asker,184 form: PendingForm,185 signInHref: string,12 unmodified lines198 </form>199 <p>Have an account? <a href="${escapeHtml(signInHref)}">Sign in</a>.</p>`200 );201 237-/**238- * A page with nothing to do but read why, and start again from the app. The239- * problem is not a refusal (a page expired, a client could not be read),240- * so it reads in ink, with one way onward.241- */202 export const problemPage = (message: string) =>203 page(204 "Sign-in problem",205 `<h1>Signing in did not work</h1>3 unmodified linesmodified:apps/platform/src/auth/password.ts+3 added-35 removed
1-/**2- * Passwords, stored only as a salted, peppered PBKDF2-SHA-256 hash through3- * WebCrypto, so the same code runs in workerd and in Node. A password and4- * the pepper never leave this module except as the hash.5- */1 import { Effect, Redacted, Schema } from "effect";2 8-/**9- * Today's setting. 100,000 iterations is the most workerd's PBKDF2 accepts10- * on Cloudflare (ASSUMPTION: the cap is a production runtime setting; the11- * open-source workerd in node_modules accepted 10,000,001 in a probe). The12- * pepper makes a stolen table useless without the Worker's secret.13- */3+// 100,000 iterations is the most workerd's PBKDF2 accepts on Cloudflare.4 export const PasswordPolicy = {5 hashBytes: 32,6 iterations: 100_000,7 saltBytes: 16,8 } as const;9 10 const ALGORITHM = "pbkdf2-sha256";11 22-/** `pbkdf2-sha256$<iterations>$<salt b64url>$<hash b64url>`: what was used, beside what it made. */12 const STORED =13 /^pbkdf2-sha256\$(?<iterations>[1-9]\d{0,5})\$(?<salt>[\w-]+)\$(?<hash>[\w-]+)$/u;14 26-/**27- * A stored password hash in the one form this platform writes, with an28- * iteration count workerd can derive (at most `PasswordPolicy.iterations`).29- */15 export const PasswordHash = Schema.String.pipe(16 Schema.check(17 Schema.makeFilter((stored) => {18 const iterations = Number(STORED.exec(stored)?.groups?.iterations ?? 0);15 unmodified lines34 const decodeBase64Url = Schema.decodeEffect(Base64Url);35 36 const utf8 = (text: string) => new TextEncoder().encode(text);37 53-/**54- * The password's HMAC-SHA-256 under the pepper: what PBKDF2 stretches, so55- * the hash means nothing without the Worker's `PASSWORD_PEPPER`.38+// The hash means nothing without the Worker's `PASSWORD_PEPPER`.56- */39 const peppered = (pepper: Redacted.Redacted, password: Redacted.Redacted) =>40 Effect.promise(() =>41 crypto.subtle.importKey(42 "raw",9 unmodified lines52 )53 )54 );55 74-/** PBKDF2-SHA-256 over the peppered password. */56 const derive = (57 pepper: Redacted.Redacted,58 password: Redacted.Redacted,59 salt: Uint8Array<ArrayBuffer>,16 unmodified lines76 ),77 Effect.map((bits) => new Uint8Array(bits))78 );79 99-/**100- * Whether the derived bytes are the stored ones, compared in constant time101- * by WebCrypto: the stored bytes are signed under a fresh random HMAC key,102- * and `verify` checks the derived bytes against that signature (BoringSSL's103- * `CRYPTO_memcmp` in workerd, `timingSafeEqual` in Node). Nothing here104- * stops at the first differing byte.105- */80+// Constant time: the stored bytes are signed under a fresh random key, and `verify` checks the derived bytes against it.81 const sameBytes = (82 derived: Uint8Array<ArrayBuffer>,83 stored: Uint8Array<ArrayBuffer>84 ) =>16 unmodified lines101 )102 )103 );104 130-/** A hash of `password` at `iterations`, with a fresh 16-byte salt. */105 export const hashPasswordWith =106 (iterations: number) =>107 (pepper: Redacted.Redacted, password: Redacted.Redacted) =>108 Effect.gen(function* () {12 unmodified lines121 [ALGORITHM, String(iterations), ...parts].join("$")122 );123 });124 151-/** A hash of `password` at today's setting. */125 export const hashPassword = hashPasswordWith(PasswordPolicy.iterations);126 154-/**155- * Whether `password` is the one `stored` was made from, compared in156- * constant time over the derived bytes, and whether `stored` was made with157- * fewer iterations than today's setting and should be replaced.158- */127 export const verifyPassword = (128 pepper: Redacted.Redacted,129 password: Redacted.Redacted,130 stored: PasswordHash23 unmodified linesmodified:apps/platform/src/auth/provider.ts+5 added-54 removed
1-/**2- * The platform as its own OAuth authorization server, in front of the rest3- * of the platform: `@cloudflare/workers-oauth-provider` 1.2.1 answers its4- * metadata and `/token`, storing grants in `OAUTH_KV`; sign-in's pages5- * answer `/authorize`, `/signup` and the CLI's client metadata document,6- * and Google sign-in's answer `/oauth/google/*` when the platform has a7- * Google OAuth client; every other request goes to the8- * platform's own fetch untouched.9- *10- * The provider's role-based `OAuthAuthorizationServer` is used, not its11- * combined `OAuthProvider`: that one requires an `apiRoute` whose bearer12- * tokens it checks itself (its constructor throws without one), while here13- * one `Sessions` checks every token (`adapters/sessions-oauth.ts`).14- */1+// The role-based server, not `OAuthProvider`: that one requires an `apiRoute` whose tokens it checks itself.2 import { OAuthAuthorizationServer } from "@cloudflare/workers-oauth-provider";3 import { D1Client } from "@effect/sql-d1";4 import { Context, Layer, Option, Redacted } from "effect";5 18 unmodified lines24 signInRoutes,25 } from "./sign-in.ts";26 import type { OAuthEnv } from "./sign-in.ts";27 41-/**42- * The authorization server for one origin: the origin is its issuer and43- * its one resource, as the protected resource metadata names it, so44- * a token is good for every path the platform serves there. The CLI's and45- * an MCP client's Client ID Metadata Documents are fetched (the Worker46- * needs `global_fetch_strictly_public`); nothing registers dynamically.47- */28+// Client ID Metadata Documents are fetched, so the Worker needs `global_fetch_strictly_public`.29 const authorizationServerFor = (origin: string) =>30 new OAuthAuthorizationServer<OAuthEnv>({31 authorizeEndpoint: "/authorize",32 clientIdMetadataDocumentEnabled: true,1 unmodified line34 resources: [origin],35 tokenEndpoint: "/token",36 });37 57-/**58- * Whether the provider or sign-in's pages answer `path`. Google's paths59- * are sign-in's whether or not Google is offered: without a Google client60- * no route serves them, and they answer 404.61- */38+// Google's paths are sign-in's even with no Google client: no route serves them, so they answer 404.39 const answersHere = (path: string) =>40 [41 ...AUTHORIZATION_SERVER_PATHS,42 ...SIGN_IN_PATHS,43 ...Object.values(GOOGLE_PATHS),44 ].some((owned) => owned === path);45 69-/** What the platform answers everything else with. */46 export type PlatformFetch = (47 request: Request,48 env: Env,49 context: ExecutionContext50 ) => Promise<Response>;51 76-/**77- * The Worker's fetch: OAuth and sign-in in front of `platformFetch`. The78- * 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- */52+// Each origin's server is made on its first request and kept: a Worker is reached only on its own hostnames.53 export const oauthProvider = <E>(54 services: Layer.Layer<GoogleServices, E>,55 platformFetch: PlatformFetch56 ) => {33 unmodified lines90 91 return { dispose, handler: { fetch } satisfies ExportedHandler<Env> };92 };93 125-/**126- * Reads the provider's access tokens from `store`, for `OAuthSessions`.127- * Unwrapping reads only the token's record and the token itself (1.2.1's128- * `unwrapToken`; the server's issuer and resources are never consulted),129- * so one reader serves every origin; its loopback issuer is a placeholder.130- */94+// Unwrapping never consults the issuer, so one reader serves every origin; its issuer is a placeholder.95 export const tokenReader = (store: OAuthStore["Service"]): TokenReader => {96 const api = authorizationServerFor("http://localhost").getOAuthApi({97 OAUTH_KV: store,98 });99 100 return { unwrapToken: (token) => api.unwrapToken(token) };101 };102 139-/** Google's OAuth client from the decoded env: both halves, or none. */103 const googleClientOf = (config: PlatformConfig) =>104 Option.all({105 id: Option.fromUndefinedOr(config.GOOGLE_CLIENT_ID),106 secret: Option.fromUndefinedOr(config.GOOGLE_CLIENT_SECRET),107 });108 146-/**147- * Sign-in's settings from the decoded env: its two secrets, the handles148- * the operator and `SESSION_TOKENS` already hold, which nobody signs up as,149- * and Google's OAuth client, offered on the sign-in page when it is set.150- */109 export const signInSettings = (config: PlatformConfig) =>110 Layer.mergeAll(111 Layer.succeed(112 GoogleClient,25 unmodified lines138 })139 )140 );141 184-/**185- * Sign-in's services on Cloudflare: the settings from the decoded env,186- * accounts and Google links in the `FRONT_PAGE` D1 database187- * (`migrations/0002_accounts.sql`, `0003_identities.sql`), attempts counted188- * by `SIGN_IN_LIMIT`, grants in `OAUTH_KV`, and Google reached through the189- * Worker's `fetch`.190- */142 export const signInServices = (143 config: PlatformConfig144 ): Layer.Layer<GoogleServices> =>145 Layer.mergeAll(9 unmodified linesmodified:apps/platform/src/auth/sign-in.ts+8 added-129 removed
1-/**2- * The platform's own sign-in: a person signs up with a handle and a3- * password, or signs in with them, on `/authorize` and `/signup`, and the4- * OAuth client that sent them there (the CLI over a loopback redirect, an5- * MCP client) gets a code for a platform token whose props are only6- * `{ handle }`. The provider validates the request and issues the code;7- * these routes decide who the person is.8- *9- * A sign-in in progress travels in the form, sealed with `COOKIE_KEY`10- * (`state.ts`), and its CSRF token in a `__Host-` cookie. Sign-in never says11- * whether a handle exists; sign-up must say a handle is taken.12- *13- * Google sign-in (`google.ts`) is offered on the same page when14- * the platform has a Google OAuth client, and reuses these pages, rules and15- * the code's completion; this module knows of it only as `SignInOffers`.16- */1 import {2 AuthorizationError,3 CimdFetchError,4 } from "@cloudflare/workers-oauth-provider";35 unmodified lines40 startAgain,41 } from "./state.ts";42 import type { AuthRequest, PendingSignIn } from "./state.ts";43 60-/** Sign-in's secrets: `COOKIE_KEY` signs forms, `PASSWORD_PEPPER` peppers passwords. */44 export class SignInKeys extends Context.Service<45 SignInKeys,46 {47 readonly cookieKey: Redacted.Redacted;48 readonly pepper: Redacted.Redacted;49 }50 >()("platform/SignInKeys") {}51 69-/**70- * What the sign-in page offers besides a password: Google's sign-in when71- * the platform has a Google OAuth client, named by the origin72- * its forms may then send a person on to (`form-action`).73- */52 export class SignInOffers extends Context.Service<53 SignInOffers,54 { readonly google: Option.Option<string> }55 >()("platform/SignInOffers") {}56 79-/**80- * The handles named sessions already hold: the operator's and each one in81- * `SESSION_TOKENS`. Nobody signs up as one, or an account82- * would call as that person.83- */57+// Nobody signs up as a handle a named session holds, or an account would call as that person.58 export class HeldHandles extends Context.Service<59 HeldHandles,60 { readonly handles: readonly Handle[] }61 >()("platform/HeldHandles") {}62 89-/** What the provider's env holds: only its store. */63 export interface OAuthEnv {64 readonly OAUTH_KV: OAuthStore["Service"];65 }66 94-/**95- * Per request: the authorization server for the origin the request reached96- * (its issuer and its one resource), and the Worker's context for it.97- */67 export class Authorization extends Context.Service<68 Authorization,69 {70 readonly context: ExecutionContext;1 unmodified line72 readonly server: OAuthAuthorizationServer<OAuthEnv>;73 }74 >()("platform/Authorization") {}75 107-/** The paths the provider answers itself: its metadata and its token endpoint. */76 export const AUTHORIZATION_SERVER_PATHS = [77 "/.well-known/oauth-authorization-server",78 "/token",79 ] as const;80 113-/** The paths sign-in's pages answer, and the CLI's client metadata document. */81 export const SIGN_IN_PATHS = [82 "/authorize",83 "/signup",84 CLI_CLIENT_PATH,85 ] as const;86 120-/**121- * Handles nobody may sign up with: the platform's own words, every word122- * the web serves its own pages at, since a handle is an owner and an owner123- * is the first segment of a project's address (ADR 0032), and every key a124- * project kept from before owners, whose address the web sends on to its125- * name (`/click/…` to `/github.com/pallets/click/…`).126- */87+// A handle is an owner, the first segment of a project's address, so it may not be a word the web serves pages at.88 const RESERVED_HANDLES: ReadonlySet<string> = new Set([89 ...reservedProjectNames,90 ...legacyProjects.map(({ key }) => key),91 Brand.slug,5 unmodified lines97 "support",98 "www",99 ]);100 140-/** An account's handle: protocol's `Handle`, at most 39 characters. */101 const AccountHandle = Handle.check(Schema.isMaxLength(39));102 103 const decodeHandle = Schema.decodeUnknownOption(AccountHandle);104 145-/** A password's length, in characters as a person counts them (graphemes), never its content. */105 const PasswordLength = { max: 256, min: 12 } as const;106 148-/** What a person reads on a page, each a plain sentence. */107 export const Says = {108 handleReserved: "That handle is reserved. Choose another.",109 handleSpelling:110 "A handle is 1 to 39 letters, digits and dashes, starting with a letter or digit.",6 unmodified lines117 "This app could not be verified: its client metadata document could not be read.",118 wrong: "The handle or password is wrong.",119 } as const;120 163-/**164- * Verified against when no account has the handle, so a missing account165- * costs the same derivation as a wrong password and timing names nobody.166- */121+// Verified against when no account has the handle, so timing names nobody.122 const STAND_IN_HASH = PasswordHash.make(123 `pbkdf2-sha256$${PasswordPolicy.iterations}$${"A".repeat(22)}$${"A".repeat(43)}`124 );125 171-/** The cookie a sign-in form's CSRF token is kept in: this site's own requests only. */126 export const CSRF_COOKIE = "__Host-sign-in";127 128 export const csrfCookie = {129 httpOnly: true,4 unmodified lines134 135 const BASE_CSP =136 "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'";137 184-/**185- * Where a form's redirect may go: the redirect URI's origin, or only its186- * scheme when its host is an IPv6 literal (`http://[::1]:<port>`), which187- * CSP's host grammar cannot name. The provider allows only https, and http188- * on a loopback host.189- */138+// CSP's host grammar cannot name an IPv6 literal host, so only its scheme.139 const redirectSource = (redirectUri: string) =>140 Option.fromNullishOr(URL.parse(redirectUri)).pipe(141 Option.filter(({ origin }) => origin !== "null"),142 Option.map(({ hostname, origin, protocol }) =>143 hostname.startsWith("[") ? protocol : origin144 )145 );146 198-/**199- * The page's CSP. A form's post is answered with a redirect to the client,200- * and browsers hold that redirect to `form-action` too, so a page with a201- * form also allows its (provider-validated) redirect URI, and any other202- * place its forms may send a person on to (`formActions`: Google's sign-in).203- */147+// Browsers hold a form post's redirect to `form-action` too, so the client's redirect URI is allowed.148 const contentSecurityPolicy = (149 redirectUri?: string,150 formActions: readonly string[] = []151 ) =>4 unmodified lines156 ),157 ...formActions,158 ].join(" ");159 216-/** An HTML page that loads nothing, cannot be framed and is never cached. */160 export const htmlPage = (161 body: string,162 status: number,163 redirectUri?: string,12 unmodified lines176 },177 status,178 });179 237-/** A provider call failed: a refusal to show the person, or a defect. */180 class ProviderFailed extends Data.TaggedError("ProviderFailed")<{181 readonly cause: unknown;182 }> {}183 242-/**243- * A provider call. Its request-validation failures become a page the244- * person reads (or the client's own error redirect, when the provider245- * validated it); anything else is a defect, a 500.246- */184 const provider = <A>(call: () => Promise<A>) =>185 Effect.tryPromise({186 catch: (cause) => new ProviderFailed({ cause }),187 try: call,15 unmodified lines203 : Effect.die(cause);204 })205 );206 270-/** The provider's helpers for this request's origin, over the store. */207 const oauthApi = Effect.gen(function* () {208 const { server } = yield* Authorization;209 210 const store = yield* OAuthStore;211 212 return server.getOAuthApi({ OAUTH_KV: store });213 });214 279-/** A sealed request in the provider's own type: an absent key stays absent, never `undefined`. */215+// An absent key stays absent, never `undefined`.216 const forProvider = (request: AuthRequest) => {217 const provided: ProviderAuthRequest = {218 clientId: request.clientId,219 redirectUri: request.redirectUri,20 unmodified lines240 241 return provided;242 };243 308-/** Who asks, as the provider describes the client (its name may be the client's own claim). */244 export const askerOf = (request: AuthRequest) =>245 Effect.gen(function* () {246 const api = yield* oauthApi;247 10 unmodified lines258 259 return asker;260 });261 327-/** Where signing in starts for `request`: `/authorize` with its own parameters. */262 export const authorizeHref = (request: AuthRequest) => {263 const query = new URLSearchParams({264 client_id: request.clientId,265 redirect_uri: request.redirectUri,18 unmodified lines284 };285 286 const encodeToken = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);287 354-/** A fresh CSRF token each time it runs: 32 random bytes, base64url. */288 export const freshCsrf = Effect.sync(() =>289 crypto.getRandomValues(new Uint8Array(32))290 ).pipe(Effect.flatMap(encodeToken), Effect.orDie);291 359-/** What a sign-in or sign-up form posts. */292 const PostedForm = Schema.Struct({293 csrf: Schema.String,294 handle: Schema.String,295 password: Schema.String,1 unmodified line297 });298 299 type PostedForm = typeof PostedForm.Type;300 369-/**370- * The posted form and the sign-in it continues: sealed by this platform371- * with `COOKIE_KEY`, not expired, and its CSRF token the same in the seal,372- * the form and this browser's cookie. Anything else starts again.373- */301 const postedSignIn = (request: HttpServerRequest.HttpServerRequest) =>302 Effect.gen(function* () {303 const { cookieKey } = yield* SignInKeys;304 11 unmodified lines316 317 return { form, pending };318 });319 393-/** The client's address, as Cloudflare saw it. */320 export const addressOf = (request: HttpServerRequest.HttpServerRequest) =>321 request.headers["cf-connecting-ip"] ?? "unknown";322 323 const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });324 399-/** Characters as a person counts them: graphemes, not UTF-16 units. */325 const lengthOf = (password: string) => [...graphemes.segment(password)].length;326 327 const passwordFits = (password: string) =>328 lengthOf(password) >= PasswordLength.min &&329 lengthOf(password) <= PasswordLength.max;330 406-/**407- * The provider records the grant and its code, and the browser goes back408- * to the client with it. The token's props carry only `{ handle }`; the409- * grant's user is the handle's key, so a grant is one account's in any case.331+// The grant's user is the handle's key, so a grant is one account's in any case.410- */332 export const completed = (handle: Handle, request: AuthRequest) =>333 Effect.gen(function* () {334 const api = yield* oauthApi;335 21 unmodified lines357 Effect.orDie358 );359 });360 440-/**441- * The sign-in page for `request` with `form`, and the ways to sign in on442- * offer: Google's too, and its origin among the places the forms may send443- * a person on to, when the platform offers it.444- */361 const offeredSignIn = (362 request: AuthRequest,363 form: PendingForm,364 status: number,11 unmodified lines376 Option.toArray(google)377 );378 });379 464-/**465- * The sign-in form for `request`, afresh: a new CSRF token, sealed with the466- * request into the form and set as this browser's cookie, and why the467- * person is here again (`message`), if they are.468- */380 export const signInPageFor = (381 request: AuthRequest,382 status: number,383 message?: string22 unmodified lines406 Effect.orDie407 );408 });409 499-/** `GET /authorize`: the provider validates the client's request; the sign-in form. */410 const showSignIn = (request: HttpServerRequest.HttpServerRequest) =>411 Effect.gen(function* () {412 const api = yield* oauthApi;413 3 unmodified lines417 418 return yield* signInPageFor(parsed, 200);419 });420 511-/** The sign-in form again, with why it did not go through. */421 const signInAgain = (422 pending: PendingSignIn,423 form: PendingForm,424 status: number,425 message: string426 ) => offeredSignIn(pending.request, form, status, message);427 519-/**520- * A posted sign-in form, by handle and password, then `signedIn` with the521- * person's handle and the sign-in it continues. The sixth attempt in a522- * minute for one handle, or from one address, is refused before any523- * password is checked; a wrong handle and a wrong password read the same,524- * and show the sign-in form again; a hash made with fewer iterations than525- * today's is replaced.526- */428+// A wrong handle and a wrong password read the same.429 export const byPassword = <E, R>(430 request: HttpServerRequest.HttpServerRequest,431 signedIn: (432 handle: Handle,56 unmodified lines489 490 return yield* signedIn(account.value.handle, pending);491 });492 591-/** `POST /authorize`: signed in by handle and password, back to the client with a code. */493 const signIn = (request: HttpServerRequest.HttpServerRequest) =>494 byPassword(request, (handle, pending) => completed(handle, pending.request));495 595-/** `GET /signup?request=<sealed>`: the sign-up form for a sign-in in progress. */496 const showSignUp = Effect.gen(function* () {497 const { cookieKey } = yield* SignInKeys;498 499 const { request: sealed } = yield* HttpServerRequest.schemaSearchParams(14 unmodified lines514 pending.request.redirectUri515 );516 });517 618-/** Why a sign-up did not go through: the page's status and its plain sentence. */518 export interface Refused {519 readonly message: string;520 readonly status: number;521 }522 624-/**625- * The handle a new account may take, or why it may not: its spelling, the626- * platform's reserved words, and the handles named sessions hold (taken,627- * like an account's). Sign-up and Google's first sign-in both use it.628- */523 export const chosenHandle = (524 handle: string,525 held: readonly Handle[]526 ): Result.Result<Handle, Refused> =>11 unmodified lines538 return Result.succeed(chosen);539 },540 });541 648-/** The handle a sign-up may take, or why it may not: `chosenHandle`'s rules, and the password's length. */542 const signUpHandle = (543 form: PostedForm,544 held: readonly Handle[]545 ): Result.Result<Handle, Refused> =>2 unmodified lines548 ? Result.succeed(handle)549 : Result.fail({ message: Says.passwordLength, status: 400 })550 );551 659-/**660- * `POST /signup`: a new account, then signed in at once. Sign-ups are661- * limited per address like sign-ins; a taken handle, in any case, is said662- * to be taken, whether an account or a named session holds it.663- */552 const signUp = (request: HttpServerRequest.HttpServerRequest) =>553 Effect.gen(function* () {554 const { pepper } = yield* SignInKeys;555 44 unmodified lines600 601 return yield* completed(checked.success, pending.request);602 });603 716-/** `GET /oauth/cli`: the CLI's client metadata document, its URL its client id. */604 const cliClient = Effect.gen(function* () {605 const { origin } = yield* Authorization;606 607 return HttpServerResponse.jsonUnsafe(cliClientMetadata(origin), {608 headers: { "cache-control": "public, max-age=300" },609 });610 });611 725-/** Metadata and the token endpoint, as the provider answers them. */612 const authorizationServer = (request: HttpServerRequest.HttpServerRequest) =>613 Effect.gen(function* () {614 const { context, server } = yield* Authorization;615 7 unmodified lines623 624 return HttpServerResponse.fromWeb(response);625 });626 741-/** A failed sign-in: the client's own error redirect, or a page to start again from. */627 export const failedPage = (failed: SignInFailed) =>628 Effect.succeed(629 failed.redirectTo === undefined630 ? htmlPage(problemPage(failed.reason), 400)2 unmodified lines633 status: 302,634 })635 );636 752-/** What the routes run on, besides the request's own `Authorization`. */637 export type SignInServices =638 | Accounts639 | HeldHandles640 | OAuthStore641 | SignInAttempts642 | SignInKeys643 | SignInOffers;644 761-/**762- * Sign-in's routes, each run with the services taken once when the router763- * is built; `Authorization` comes with each request.764- */645 export const signInRoutes = HttpRouter.use((router) =>646 Effect.gen(function* () {647 const services = Context.make(Accounts, yield* Accounts).pipe(648 Context.add(HeldHandles, yield* HeldHandles),2 unmodified lines651 Context.add(SignInKeys, yield* SignInKeys),652 Context.add(SignInOffers, yield* SignInOffers)653 );654 775- /** Adds a route, its failures shown as pages and the services provided. */655 const add = <R>(656 method: "*" | "GET" | "POST",657 path: HttpRouter.PathInput,658 handler: (21 unmodified linesmodified:apps/platform/src/auth/state.ts+3 added-45 removed
1-/**2- * A sign-in in progress travels in the sign-in form itself, sealed: the3- * OAuth request the provider validated, the form's CSRF token, and when it4- * stops being good, signed with HMAC-SHA-256 under `COOKIE_KEY` (WebCrypto).5- * The platform keeps nothing between showing the form and reading it back,6- * and a form it did not make, or made more than ten minutes ago, is refused.7- */1 import { Clock, Data, Duration, Effect, Redacted, Schema } from "effect";2 10-/**11- * The provider's `AuthRequest`, as `parseAuthRequest` returned it: the12- * client, where its code goes, its PKCE challenge, and the resource and13- * issuer the provider recorded. The provider writes an absent challenge as14- * `undefined`, so the optional keys take it (internal JSON, never a wire15- * schema).16- */3+// The provider writes an absent challenge as `undefined`, so these keys are `optional` (internal JSON, never a wire schema).4 export const AuthRequest = Schema.Struct({5 clientId: Schema.String,6 codeChallenge: Schema.optional(Schema.String),7 codeChallengeMethod: Schema.optional(Schema.String),6 unmodified lines14 });15 16 export type AuthRequest = typeof AuthRequest.Type;17 31-/** What the form carries: the OAuth request, and the CSRF token its cookie must match. */18 export const PendingSignIn = Schema.Struct({19 csrf: Schema.String,20 request: AuthRequest,21 });22 23 export type PendingSignIn = typeof PendingSignIn.Type;24 39-/** How long a sign-in form stays good. */25 export const SIGN_IN_LIFETIME = Duration.minutes(10);26 27 const Signature = Schema.Uint8ArrayFromBase64Url;28 29 const encodeSignature = Schema.encodeEffect(Signature);30 31 const decodeSignature = Schema.decodeEffect(Signature);32 48-/**49- * Signing in did not go through, for a reason the person sees as a plain50- * sentence on the page. Internal to `auth/`: never a contract refusal.51- */33 export class SignInFailed extends Data.TaggedError("SignInFailed")<{34 readonly reason: string;54- /**55- * The client's own error redirect, set only when the provider validated56- * the client and its redirect URI (`AuthorizationError.redirectTo`).57- */35+ // Set only once the provider validated the client and its redirect URI.36 readonly redirectTo?: string;37 }> {}38 61-/** The one thing a person can do with a form that is stale, forged or from another browser. */39 export const startAgain = new SignInFailed({40 reason:41 "This sign-in page expired or was not opened here. Start signing in again from your app.",42 });43 44 const utf8 = (text: string) => new TextEncoder().encode(text);45 69-/** `COOKIE_KEY` as an HMAC-SHA-256 key. */46 const hmacKey = (key: Redacted.Redacted) =>47 Effect.promise(() =>48 crypto.subtle.importKey(49 "raw",3 unmodified lines53 ["sign", "verify"]54 )55 );56 81-/**82- * Seals and opens one kind of value carried through the browser: as83- * `<payload>.<signature>`, the payload base64url JSON of the value and when84- * it stops being good (ten minutes on), signed under `COOKIE_KEY` together85- * with `purpose`. A value this platform did not seal, sealed for another86- * purpose (however its shape fits: a schema ignores extra keys), or sealed87- * too long ago, opens to `startAgain`.88- */57+// The signature covers `purpose` too: a schema ignores extra keys, so a value sealed for another purpose must not open.58 export const sealing = <A, I>(purpose: string, schema: Schema.Codec<A, I>) => {90- /** What the signature covers: the purpose, then the payload. */59 const signed = (payload: string) => utf8(`${purpose}.${payload}`);60 61 const Payload = Schema.StringFromBase64Url.pipe(62 Schema.decodeTo(6 unmodified lines69 const encodePayload = Schema.encodeEffect(Payload);70 71 const decodePayload = Schema.decodeEffect(Payload);72 105- /** `value`, good for ten minutes from now. */73 const seal = (key: Redacted.Redacted, value: A) =>74 Effect.gen(function* () {75 const now = yield* Clock.currentTimeMillis;76 10 unmodified lines87 88 return `${payload}.${yield* encodeSignature(new Uint8Array(signature)).pipe(Effect.orDie)}`;89 });90 124- /**125- * What `sealed` carries, if this platform sealed it with `key` (checked126- * in constant time by WebCrypto) and its ten minutes have not passed.127- */91 const open = (key: Redacted.Redacted, sealed: string) =>92 Effect.gen(function* () {93 const [payload = "", encoded = ""] = sealed.split(".");94 33 unmodified lines128 };129 130 const pendingSignIns = sealing("sign-in", PendingSignIn);131 169-/** `pending`, good for ten minutes from now, as `<payload>.<signature>`. */132 export const sealState = pendingSignIns.seal;133 172-/**173- * What `sealed` carries, if this platform sealed it with `key` (checked in174- * constant time by WebCrypto) and its ten minutes have not passed.175- */134 export const openState = pendingSignIns.open;modified:apps/platform/src/releases/binding.ts-10 removed
1-/**2- * `ReleaseStore` over the stage's `RELEASES` R2 bucket (`releases-<stage>`).3- * It only reads: the release script uploads with Wrangler.4- */1 import { Effect, Layer, Option } from "effect";2 3 import { ReleaseStore } from "../releases.ts";4 9-/** The one call the store makes on the bucket, which `R2Bucket` answers. */5 export interface ReleaseBucket {6 readonly get: (key: string) => Promise<{7 readonly body: ReadableStream;8 readonly size: number;9 } | null>;10 }11 17-/**18- * The store over `bucket`. A read the bucket fails is a defect, as every19- * binding's failure is here: the request answers 500 and nothing is20- * served.21- */12 export const ReleaseStoreBinding = (13 bucket: ReleaseBucket14 ): Layer.Layer<ReleaseStore> =>15 Layer.succeed(14 unmodified linesmodified:apps/platform/src/releases/memory.ts-7 removed
1-/**2- * `ReleaseStore` in memory, seeded with files by key, for tests: it records3- * every key it was asked for, in order, so a test can show what a request4- * read.5- */1 import { Context, Effect, Layer, Option, Predicate, Ref } from "effect";2 3 import { ReleaseStore } from "../releases.ts";4 10-/** Every key the memory store was asked for, in order. */5 export class ReleaseReads extends Context.Service<6 ReleaseReads,7 { readonly keys: Effect.Effect<readonly string[]> }8 >()("platform/ReleaseReads") {}9 10 const encoder = new TextEncoder();11 12 export const ReleaseStoreMemory = {19- /** A store holding `files` (text or bytes, by key), and its record of reads. */13 layer: (14 files: Readonly<Record<string, string | Uint8Array>>15 ): Layer.Layer<ReleaseStore | ReleaseReads> =>16 Layer.effectContext(23 unmodified linesmodified:apps/platform/src/sessions/first-of.ts-6 removed
1 import { Effect, Option } from "effect";2 3 import { Sessions } from "../sessions.ts";4 5-/**6- * One `Sessions` over several: a token names whom the first of `sessions`7- * that knows it says, and the rest are not asked. So every source of tokens8- * (sign-in, the operator, `SESSION_TOKENS`) is checked by one service, and9- * the order says which wins when two know one token.10- */5 export const firstOf = (6 sessions: readonly Sessions["Service"][]7 ): Sessions["Service"] =>8 Sessions.of({13 unmodified linesmodified:apps/platform/src/sessions/memory.ts-6 removed
2 unmodified lines3 import { Effect, Layer, Option } from "effect";4 5 import { Sessions } from "../sessions.ts";6 7-/** Sessions over a fixed table of tokens to handles. */7 const service = (tokens: Readonly<Record<string, Handle>>) => {8 const byToken = new Map(Object.entries(tokens));9 10 return Sessions.of({5 unmodified lines16 ),17 });18 };19 21-/**22- * Sessions from a fixed table of tokens to handles, for tests and local23- * runs: as a layer, or as the service itself, to combine with others24- * (`firstOf`).25- */20 export const MemorySessions = {21 layer: (tokens: Readonly<Record<string, Handle>>) =>22 Layer.succeed(Sessions, service(tokens)),23 service,1 unmodified linemodified:apps/platform/src/sessions/table.ts-7 removed
2 unmodified lines3 4 import { Sessions } from "../sessions.ts";5 import { MemorySessions } from "./memory.ts";6 7-/** One token the platform was given, and the handle it names. */7 export interface SessionEntry {8 readonly handle: Handle;9 readonly token: Redacted.Redacted;10 }11 13-/**14- * Sessions from tokens the stage was given: the operator's and15- * each named one in `SESSION_TOKENS`. The first entry naming a token wins,16- * so the operator's goes first.17- */12 export const sessionTable = (entries: readonly SessionEntry[]) =>13 MemorySessions.service(14 Object.fromEntries(15 entries1 unmodified line17 .map(({ handle, token }) => [Redacted.value(token), handle])18 )19 );20 27-/** `sessionTable` as the platform's one `Sessions`. */21 export const TableSessions = (entries: readonly SessionEntry[]) =>22 Layer.succeed(Sessions, sessionTable(entries));modified:apps/platform/src/visibility/env.ts-10 removed
1-/**2- * The visibility cartridge's env, as the platform provides it: the project3- * service's `ProjectEnv` over an `.env.schema` parser and the vault that seals4- * write-only values under the stage's `MASTER_KEY` (a WebCrypto envelope). It5- * reads each project's schemas at the landed SHA through the platform's6- * `RepoHost`, the public namespace's. The parser is the visibility package's7- * adapter over `@env-spec/parser`, which reads a schema into plain data and8- * runs nothing in it.9- */1 import type { RepoHost } from "@repo/artifacts/repo-host";2 import { ProjectEnvLive } from "@repo/project/visibility/env";3 import { EnvSchemaParserEnvSpec } from "@repo/visibility/env-schema/env-spec";4 import { WriteOnlyValuesWebCrypto } from "@repo/visibility/vault/webcrypto";5 import { Layer } from "effect";6 7 import type { PlatformConfig } from "../platform.ts";8 18-/** The project service's env for one stage's config, as the Worker composes it. */9 export const envLive = (10 config: PlatformConfig11 ): Layer.Layer<never, never, RepoHost> =>12 ProjectEnvLive.pipe(7 unmodified linesmodified:apps/platform/src/visibility/held-back.ts+3 added-25 removed
1-/**2- * The visibility cartridge's landing guards: the3- * no-write-down guards the `Answer` Workflow runs on an answer's merged4- * change set before any check, provided as its `LandingGuards` port.5- *6- * - `PrivatePathInPublicTree`: a path in any layer's path set, as the7- * project gives it (`layerFacts`). It names exactly which paths collide8- * only when everyone accountable for the answer reads every layer;9- * anyone else hears every path they added or modified10- * (`privatePaths`), so the refusal is no map of the layers.11- * - `LayerContentInPublicTree`: an added blob identical to a blob of a12- * layer the answerer or a finisher reads (`writeDown`). Only the13- * blobs of layers they read are compared, read here from the private14- * namespace (`LayerRepos`) at the layer's `main`; for anyone else the15- * guard says nothing, never an oracle on a layer's content.16- *17- * Nothing here names a layer's paths or content in a refusal or a log.18- */1+// Refusals and logs here never name a layer's paths or content: exact colliding paths2+// only when everyone accountable reads every layer, and blob comparison only for layers3+// the answerer or a finisher reads.4 import type { Fetch } from "@repo/artifacts/fetch";5 import { ObjectId, RefName } from "@repo/artifacts/repo-host";6 import type { RepoHost, RepoNotFound } from "@repo/artifacts/repo-host";7 import type { ProjectApi } from "@repo/project/project";12 unmodified lines20 import { layerRepos } from "./layer-repos.ts";21 22 const mainRef = RefName.make("refs/heads/main");23 39-/** A layer's repo: as declared, or `<key>--<layer>`, by the project's key. */24 const repoOf = (project: ProjectName, layer: LayerDeclaration) =>25 layer.repo ?? RepoName.make(`${keyOf(project)}--${layer.name}`);26 43-/** Every blob under `tree` in `repo`, at any depth. */27 const blobsUnder = (28 host: RepoHost["Service"],29 repo: RepoName,30 tree: string12 unmodified lines43 (nested) => nested.flat()44 )45 );46 64-/** The blobs a layer's repo holds on `main`; none for a layer with no repo yet. */47 const layerBlobs = (host: RepoHost["Service"], repo: RepoName) =>48 Effect.gen(function* () {49 const tip = (yield* host.refs(repo)).get(mainRef);50 7 unmodified lines58 ? []59 : yield* blobsUnder(host, repo, commit.value.tree);60 }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeed([])));61 80-/** Whether `handle` may read `layer`: its readers and writers. */62 const reads = (api: ProjectApi, handle: Handle, layer: LayerDeclaration) =>63 Effect.map(64 api.layerAccess(Person.make({ handle }), layer.name),65 (access) => Option.isSome(access) && access.value !== "none"66 );67 87-/** The guards on one answer's merged change set, over its project and the private namespace. */68 const guardsOver =69 (repos: RepoHost["Service"], projects: Projects["Service"]) =>70 (input: GuardInput) =>71 Effect.gen(function* () {43 unmodified lines115 ),116 ];117 });118 139-/** The landing guards over the project's layers, as `LayerRepos` holds them. */119 export const LandingGuardsLive: Layer.Layer<120 never,121 never,122 LayerRepos | Projects6 unmodified lines129 return Option.some({ check: guardsOver(repos, projects) });130 })131 );132 154-/** The landing guards for one stage, over its private namespace (`ARTIFACTS_PRIVATE`). */133 export const heldBackLive = (134 config: PlatformConfig135 ): Layer.Layer<never, never, Fetch | Projects> =>136 LandingGuardsLive.pipe(Layer.provide(layerRepos(config)));modified:apps/platform/src/visibility/layer-repos.ts-7 removed
1-/**2- * The private namespace's repos: every project's layer repos,3- * through the platform's second Artifacts binding, `ARTIFACTS_PRIVATE`, as4- * `LayerRepos` (a `RepoHost` under its own tag, so nothing that asks for the5- * public one is handed it). Only this Worker binds the namespace; the6- * Workers that serve public pages bind none (principle 7).7- */1 import type { Fetch } from "@repo/artifacts/fetch";2 import { RepoHost } from "@repo/artifacts/repo-host";3 import { RepoHostBinding } from "@repo/artifacts/repo-host/binding";4 import { LayerRepos } from "@repo/visibility/layer-repos";11 unmodified linesmodified:apps/platform/src/visibility/layers.ts+2 added-33 removed
1-/**2- * The visibility cartridge's gateway side (ADR 0007),3- * as the `LayerGate` port: which repo names are a project's declared4- * layers, how far a person reaches into one, and the private namespace's5- * git server behind them.6- *7- * - A name is a layer's repo when it reads `<project>--<layer>`8- * and the project declares that layer, from the policy at its landed SHA9- * (ADR 0005): any other such name stays an unknown repo, and claim forks10- * and working forks never get here (their names have three parts).11- * - Access comes in the same answer (`ProjectApi.layerAccess`, one DO call12- * per request): the layer's readers clone it, its writers push to it, and13- * nobody else reaches it.14- * - The upstream is git's `UpstreamRepoHost` over the private namespace's15- * repos (`LayerRepos`): its tokens are minted, cached once per isolate16- * and sent only to the store, so none leaves the platform.17- */1 import type { Fetch } from "@repo/artifacts/fetch";2 import { RepoHost } from "@repo/artifacts/repo-host";3 import { Upstream } from "@repo/git/upstream";4 import { UpstreamRepoHost } from "@repo/git/upstream/repo-host";8 unmodified lines13 import { layerRepos } from "./layer-repos.ts";14 15 const asKey = Schema.decodeOption(ProjectKey);16 34-// A layer repo's first part is its project's key (ADR 0032).17 const asProject = (first: string) => Option.flatMap(asKey(first), nameOfKey);18 19 const asLayer = Schema.decodeOption(LayerName);20 39-/** The project and layer a name `<project>--<layer>` spells, if it spells one. */21 const spelled = (repo: string): Option.Option<LayerTarget> => {22 const [first = "", second = "", ...rest] = repo.split("--");23 24 return rest.length > 025 ? Option.none()26 : Option.all({ layer: asLayer(second), project: asProject(first) });27 };28 48-/**49- * git's upstream over the private namespace, its tokens minted and cached50- * there. Fresh: the core ports build `UpstreamRepoHost` over the public51- * namespace, and a layer built twice in one memo map is shared, so without52- * it the gate would ask the public namespace for every layer repo (found53- * live by 699: every layer clone on a stage answered "no repo").54- */29+// Fresh: a layer built twice in one memo map is shared, and the core ports build30+// `UpstreamRepoHost` over the public namespace.31 const privateUpstream: Layer.Layer<Upstream, never, LayerRepos | Fetch> =32 Layer.fresh(UpstreamRepoHost).pipe(33 Layer.provide(Layer.effect(RepoHost, LayerRepos.useSync(RepoHost.of)))34 );35 60-/**61- * The live gate: layers as each project's DO declares them, and the62- * private namespace's upstream, built once with the layer.63- */36 export const LayerGateLive: Layer.Layer<37 never,38 never,39 Projects | LayerRepos | Fetch3 unmodified lines43 const projects = yield* Projects;44 const upstream = yield* Upstream;45 46 return LayerGate.of({75- // The DO answers none for a layer its project does not declare, and76- // `none` access to someone not signed in.47 classify: (repo, who) =>48 Option.match(spelled(repo), {49 onNone: () => Effect.succeedNone,50 onSome: (target) =>7 unmodified lines58 });59 })60 ).pipe(Layer.provide(privateUpstream));61 92-/** The live gate for one stage: the private namespace through `ARTIFACTS_PRIVATE`. */62 export const layersLive = (63 config: PlatformConfig64 ): Layer.Layer<never, never, Projects | Fetch> =>65 LayerGateLive.pipe(Layer.provide(layerRepos(config)));modified:apps/platform/src/visibility/live.ts-11 removed
1-/**2- * The visibility cartridge, whole (README's cut line 5): the gateway's3- * layer repos (`layers.ts`), the project service's visibility state4- * (`state.ts`) and env (`env.ts`), and the `Answer` Workflow's landing5- * guards (`held-back.ts`), for one stage's config, over the platform's own6- * ports. `ports.ts` plugs it in by one marked line;7- * deleting that line, this folder, `@repo/visibility` and the8- * `ARTIFACTS_PRIVATE` binding leaves the platform without typed visibility9- * (`packages/config/test/cartridge.test.ts` lists what to delete).10- */1 import { Layer } from "effect";2 3 import type { PlatformConfig } from "../platform.ts";4 import type { WorkerPorts } from "../ports.ts";1 unmodified line6 import { heldBackLive } from "./held-back.ts";7 import { layersLive } from "./layers.ts";8 import { stateLive } from "./state.ts";9 20-/** The cartridge's layer for one stage's config, filling `LayerGate`, `ProjectVisibility`, `ProjectEnv` and `LandingGuards`. */10 export const live = (11 config: PlatformConfig12 ): Layer.Layer<never, never, WorkerPorts> =>13 Layer.mergeAll(5 unmodified linesmodified:apps/platform/src/visibility/state.ts+2 added-20 removed
1-/**2- * The visibility cartridge's project state, as the platform provides it:3- * the project service's live `ProjectVisibility` over the private4- * namespace's repos (`LayerRepos` over `ARTIFACTS_PRIVATE`), secret salts5- * from WebCrypto's randomness at the platform's edge, and admissions6- * started as runs of the `Answer` Workflow under their own params.7- *8- * A salt is drawn here and kept only in the project's Durable Object (the9- * layer's row): no ledger entry, trailer, note or event carries it, and10- * nothing reveals it yet (`reveal` stays "on retire or dispute", as config).11- */1+// A salt is kept only in the project's Durable Object: no ledger entry, trailer,2+// note or event carries it.3 import type { Fetch } from "@repo/artifacts/fetch";4 import {5 AdmissionStarts,6 ProjectVisibilityLive,4 unmodified lines11 import { AdmissionParams, admissionId } from "../answer-runs.ts";12 import type { PlatformConfig } from "../platform.ts";13 import { layerRepos } from "./layer-repos.ts";14 24-/** 32 bytes from WebCrypto's randomness: each layer commit's commitment gets its own. */15 export const WebCryptoSalts: Layer.Layer<SaltSource> = Layer.succeed(16 SaltSource,17 SaltSource.of({18 next: Effect.sync(() => crypto.getRandomValues(new Uint8Array(32))),19 })20 );21 32-/** The part of the `Answer` Workflow binding an admission's start uses. */22 export interface AdmissionWorkflow {23 readonly create: (options: {24 readonly id: string;25 readonly params: typeof AdmissionParams.Encoded;2 unmodified lines28 }29 30 const encodeParams = Schema.encodeEffect(AdmissionParams);31 43-/**44- * Admissions as runs of the `Answer` Workflow, one instance per45- * project, layer and head (`admissionId`): starting one twice finds the46- * instance the first made, so it runs once. Any other failure is a defect,47- * and the outbox row that asked for the start runs it again.48- */32 export const admissionStarts = (33 workflow: AdmissionWorkflow34 ): Layer.Layer<AdmissionStarts> =>35 Layer.succeed(18 unmodified lines54 }).pipe(Effect.orDie),55 })56 );57 75-/** The live project state for one stage's config, over the platform's `Fetch`. */58 export const stateLive = (59 config: PlatformConfig60 ): Layer.Layer<never, never, Fetch> =>61 ProjectVisibilityLive.pipe(8 unmodified linesmodified:apps/platform/src/workflows/answer/guards.ts+4 added-50 removed
1-/**2- * The `Answer` Workflow's landing guards: before3- * any check runs on an answer's merged tree, the tree is checked again for4- * what may never enter a public tree, as it stands now (a layer may have5- * grown since the push was admitted at stage 1):6- *7- * - a path in a layer's path set: `PrivatePathInPublicTree`;8- * - a file whose blob is a layer's blob, only when the answerer or a9- * finisher reads that layer (only they could have copied it; on anyone10- * else the guard would be an oracle): `LayerContentInPublicTree`;11- * - a file holding a stored write-only value, by the project's own scan12- * (`ProjectApi.scanForValues`, where the values are; never in the13- * sandbox): the item is quarantined, for the deciders alone.14- *15- * The layer guards need the layers' contents, which only the visibility16- * cartridge reaches, so they sit behind `LandingGuards`, a port whose17- * default is no guards at all: without the cartridge there are no layers18- * and no stored values, and the program takes no guards step (its steps19- * are the ones it always took).20- */1+// Layer content is compared only for layers the answerer or a finisher reads: for2+// anyone else the guard would be an oracle on a layer's content.3 import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";4 import type { Change } from "@repo/project/landing";5 import { LandingState } from "@repo/project/landing";6 import { Projects } from "@repo/project/projects";13 unmodified lines20 import { Array, Context, Effect, Option, Schema } from "effect";21 22 import { StepRunner } from "../step.ts";23 42-/** One answer's merged change set, and the people accountable for it. */24 export interface GuardInput {25 readonly project: ProjectName;26 readonly answerer: Handle;46- /** Deciders whose finish put commits of their own on the answer. */27 readonly finishers: readonly Handle[];28 readonly changes: readonly Change[];29 }30 51-/** The no-write-down guards on a merged change set, as the visibility cartridge runs them. */31 export interface LayerGuardsPort {32 readonly check: (33 input: GuardInput34 ) => Effect.Effect<35 readonly (PrivatePathInPublicTree | LayerContentInPublicTree)[]36 >;37 }38 60-/**61- * How the Workflow reaches the layer guards: none by default, a platform62- * without typed visibility. The visibility cartridge provides them63- * (`apps/platform/src/visibility/held-back.ts`).64- */39 export const LandingGuards = Context.Reference<Option.Option<LayerGuardsPort>>(40 "platform/LandingGuards",41 { defaultValue: () => Option.none() }42 );43 70-/** What the guards step came to, kept as its value: no names but public ones. */44 export const GuardRun = Schema.TaggedUnion({72- /** An added blob could not be read: the guards try again later, never counted. */45 Blocked: { attempt: Schema.Int },74- /** The guards' refusals, and the items whose stored value an added file holds. */46 Guarded: {47 finish: AskKind.fields.finish,48 quarantined: Schema.Array(EnvKey),49 refusals: Schema.Array(Refusal),50 },80- /** The answer no longer waits on checks of this tree. */51 Moved: {},52 });53 54 export type GuardRun = typeof GuardRun.Type;55 86-/**87- * Whether the guards let the tree on to its checks: only when they ran on88- * it and found nothing. A blocked run waits, and a moved one stops.89- */56 export const passes = (run: GuardRun): boolean =>57 GuardRun.guards.Guarded(run) &&58 run.refusals.length === 0 &&59 run.quarantined.length === 0;60 95-/** Files the answer puts into the public tree: added, or modified to a new blob. */61 const written = (changes: readonly Change[]) =>62 Array.dedupe(63 changes.flatMap(({ after, status }) =>64 status === "deleted" || after === undefined ? [] : [after]65 )66 );67 103-/**104- * The guards on `tree`, as the answer's run stands: the cartridge's layer105- * guards over its change set and the people accountable for it, then each106- * blob it writes, read from its fork, through the project's scan.107- */68 const guarded = (69 params: { readonly project: ProjectName; readonly requestId: RequestId },70 tree: TreeSha,71 port: LayerGuardsPort28 unmodified lines100 });101 102 const host = yield* RepoHost;103 144- // A fork the platform cannot read leaves its files unscanned: the guards145- // try again later, and never let the tree by. An id no blob in the fork146- // has is a submodule's pointer, a commit in another repo (`tree-diff`):147- // it brings no content of its own into the tree, so there is none to scan.104+ // A fork the platform cannot read leaves its files unscanned, and the tree waits. An105+ // id no blob in the fork has is a submodule's pointer, with no content to scan.106 const read = yield* Effect.option(107 Effect.forEach(written(state.changes), (blob) =>108 host.readBlob(request.fork, ObjectId.make(blob))109 )13 unmodified lines123 refusals,124 });125 });126 169-/**170- * The guards on the tree the answer waits to have checked, as a durable171- * step named for the attempt; none when no cartridge provides them.172- */127 export const guards = (128 params: { readonly project: ProjectName; readonly requestId: RequestId },129 tree: TreeSha,130 attempt: number22 unmodified linesmodified:apps/platform/src/workflows/answer/held-back.ts+2 added-40 removed
1-/**2- * The `Answer` Workflow's held-back step: once an3- * answer's public checks pass on the merged tree, the sealed suite its4- * claim was pinned to judges it, one bit per area. The project5- * decides everything through `ProjectApi`: the job (`heldBackJob`, the6- * layer's files read at the pinned commit by the platform, so no layer7- * route or token reaches the sandbox), and the judgement of the area bits8- * (`recordHeldBack`: `HeldBackFailed`, `AttemptsExhausted`, or the9- * `Held-back:` trailer it keeps for the landing). Only answers whose run10- * says `sealed` take this step, so a platform without typed visibility runs11- * the same steps it always did.12- *13- * The suite runs in a job of its own, with no public lane beside it: the14- * public lanes passed in their own jobs, and answer code run again beside15- * the sealed files could carry bits about them that no attempt counts. Only16- * the area bits leave the step: no lane, no log, no duration.17- *18- * A held-back result carries over to a later check of the same request only19- * when the answer's `PatchId` and the pinned suite are unchanged:20- * a main that moved under a passing answer re-runs its public lanes21- * on the new merged tree, never its sealed suite.22- */1+// The layer's files are read by the platform, so no layer route or token reaches the2+// sandbox.3 import { CheckAt, CheckRunner } from "@repo/checks/check-runner";4 import { patchId } from "@repo/git/patch-id";5 import { runBlockOf } from "@repo/project/answer-runs";6 import type { AnswerRun } from "@repo/project/answer-runs";8 unmodified lines15 import { Effect, Option, Schema } from "effect";16 17 import { StepRunner } from "../step.ts";18 39-/** What the held-back step came to, kept as its value: area bits and roots only. */19 export const HeldBackRun = Schema.TaggedUnion({41- /** The Checker could not run the suite: tried again later, never counted. */20 Blocked: { attempt: Schema.Int },43- /** The suite judged the tree: its area bits, what they earned, and what they judged. */21 Judged: {22 patchId: PatchId,23 refusals: Schema.Array(Refusal),24 results: Schema.Array(HeldBackResult),25 suite: SuiteRoot,26 },50- /** Nothing sealed judges the answer, or it no longer waits on checks of this tree. */27 Unsealed: {},28 });29 30 export type HeldBackRun = typeof HeldBackRun.Type;31 56-/** A held-back run that judged a tree. */32 export type Judged = Extract<HeldBackRun, { readonly _tag: "Judged" }>;33 59-/** A held-back step with nothing to judge. */34 export const unsealed: HeldBackRun = HeldBackRun.cases.Unsealed.make({});35 62-/**63- * The area bits of the sealed suite on `tree`: the earlier run's when it64- * judged the same patch by the same suite, else a fresh run in a job of65- * the suite alone.66- */36 const areaBits = (input: {37 readonly earlier: Option.Option<Judged>;38 readonly job: HeldBackJob;39 readonly patch: PatchId;24 unmodified lines64 onSome: ({ results }) => Effect.succeed(results),65 }66 );67 99-/**100- * The sealed suite's run for one checked tree, as a durable step named for101- * the attempt: a replay reads its record back, and the project counts the102- * attempt once per tree whatever runs again (principle 8). `earlier` is103- * the last run this request's Workflow judged, which carries over to an104- * unchanged patch under an unchanged suite.105- */68 export const heldBack = (69 params: { readonly project: ProjectName; readonly requestId: RequestId },70 tree: TreeSha,71 attempt: number,53 unmodified linesmodified:apps/platform/src/workflows/answer/lanes.ts+6 added-110 removed
1-/**2- * The answer's lanes on its merged tree: the3- * cheap stage (the static lanes) and then the checks (the ask's own check4- * and every other project lane), always on the exact tree the merge made.5- * A lane whose checker never got going gets one fresh run; every lane that6- * did not pass keeps its log through `EvidenceStore`, and only the name it7- * is kept under travels on, unless the project's scan finds a stored8- * write-only value in it: that log is never kept, and its lane says9- * `withheld`. The gate classifies each failure against the same10- * lane on main (`gate.classifyFailure`).11- *12- * The merged tree is checked in the answer's fork, where `Lander.merge`13- * keeps it (under `${Brand.refsPrefix}merge/<tree>`), so a merge needs no14- * write token on the canonical repo; main is checked in the canonical repo.15- *16- * The cheap stage also counts the policy's ratchets on the merged tree, one17- * count lane per command (`measure`); the project judges the counts against18- * its baselines when the checks report. A `lintToZero` ask's own lane is a19- * count too: green at zero in its territory, whatever its lint exits with.20- */1+// The merged tree is checked in the answer's fork, where `Lander.merge` keeps it, so a2+// merge needs no write token on the canonical repo.3 import {4 CheckAt,5 CheckLane,6 CheckRunner,27 unmodified lines34 import { ChecksFailed } from "@repo/protocol/refusal";35 import type { Flake, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";36 import { Array, Effect, Option, Order, Result, Schema } from "effect";37 56-/**57- * The lanes the cheap stage runs before the costlier checks: the static58- * ones, under the names the run block finder gives them (`checks/finder`).59- * The ratchets' counts run beside them (`countRatchets`).60- */38 export const cheapLanes = ["format", "lint", "types"] as const;39 63-/** Which of the answer's lanes a stage runs. */40 export type Stage = "cheap" | "checks";41 42 const isCheap = (lane: LaneName) =>43 cheapLanes.some((name): boolean => name === lane);44 69-/** The lanes of `run` that `stage` runs; the ask's own check is never cheap. */45 export const lanesFor = (run: AnswerRun, stage: Stage): readonly CheckLane[] =>46 run.lanes.filter(47 ({ lane }) =>48 (stage === "cheap") === (isCheap(lane) && lane !== run.askLane)49 );50 76-/** What the lanes are judged against: the answer's request, its merge and its main. */51 export const Checked = Schema.Struct({78- /** The lane the ask's own check reports as: red on main by design. */52 askLane: Schema.optionalKey(LaneName),53 attempt: Schema.Int,54 base: CommitSha,82- /** Every path the answer changed against its base. */55 changed: Schema.Array(RepoPath),84- /** The env every check job of the answer carries: placeholders, never a value. */56 env: Schema.optionalKey(UnlandedRunEnv),57 finish: AskKind.fields.finish,87- /**88- * The answer's fork, which holds the merged tree: the Lander keeps it there89- * under `${Brand.refsPrefix}merge/<tree>` for the Checker to fetch.90- */58 fork: RepoName,59 main: LandedSha,60 project: ProjectName,94- /** The canonical repo, which holds main. */61 repo: RepoName,62 requestId: RequestId,97- /** The project's run block, which every check job carries; absent without a policy. */63 run: Schema.optionalKey(RunBlock),99- /** Whether a held-back suite judges the answer once its checks pass. */64 sealed: Schema.optionalKey(Schema.Boolean),65 tree: TreeSha,66 });67 68 export type Checked = typeof Checked.Type;69 106-/** One lane on the merged tree, as the gate classifies it. */70 export const LaneRun = Schema.Struct({108- /** The lane as the project runs it: what runs again on main. */71 check: CheckLane,110- /** The repo files outside tests its failure points at, when its log names any. */72 failingPaths: Schema.Array(RepoPath),112- /** How its first run on the merged tree ended. */73 first: LaneOutcome,114- /** How its fresh run ended, when the first never got going. */74 rerun: Schema.optionalKey(LaneOutcome),116- /** The result that stands, with where its log is kept when it did not pass at first. */75 result: LaneResult,76 });77 78 export type LaneRun = typeof LaneRun.Type;79 122-/** What one stage's run on the merged tree came to. */80 export const StageRun = Schema.TaggedUnion({124- /** The checker could not run at all: the project tries again later. */81 Blocked: { attempt: Schema.Int },126- /** The answer no longer waits on these checks: another run moved it on. */82 Moved: {},83 Ran: {84 checked: Checked,130- /** The cheap stage's: each ratchet's count on the merged tree, per territory. */85 counts: Schema.optionalKey(Schema.Array(MeasuredCount)),86 lanes: Schema.Array(LaneRun),133- /** The cheap stage's: a ratchet whose command printed no count the platform can read. */87 uncounted: Schema.optionalKey(RatchetName),88 },89 });90 91 export type StageRun = typeof StageRun.Type;92 93 type Ran = Extract<StageRun, { readonly _tag: "Ran" }>;94 142-/**143- * A path with a line, as a stack frame or a compiler prints one:144- * `src/lex.ts:3:7`. Its extension starts with a letter, so an address and145- * its port (`127.0.0.1:8080`) is no file.146- */95+// The extension starts with a letter, so an address and port (`127.0.0.1:8080`) is no file.96 const LOCATION =97 /(?<![\w./@+-])(?<path>(?:[\w@+-][\w.@+-]*\/)*[\w@+-][\w.@+-]*\.[A-Za-z][A-Za-z0-9]*):\d+/gu;98 150-/** A file whose failure says nothing about where the code broke: a test itself. */99 const TEST_FILE =100 /(?:^|\/)(?:tests?|__tests__)\/|\.(?:test|spec)\.[A-Za-z0-9]+$/u;101 154-/**155- * The repo files a lane's failure points at: every relative `path:line` its156- * output names, tests left out (a test failing in its own file says157- * nothing about which code broke). Absolute paths are not the repo's.158- */102 export const failingPathsOf = (output: string): readonly RepoPath[] =>103 Array.sort(104 Array.dedupe(105 [...output.matchAll(LOCATION)].flatMap(({ groups }) =>4 unmodified lines110 ),111 Order.String112 ).map((path) => RepoPath.make(path));113 171-/**172- * A lane's log, as the platform keeps it. The Checker's `CheckRun` carries173- * no raw output yet, so the log is what the run said of the lane: its end,174- * its command, and its failure's signature.175- */114 export const laneLog = (115 result: LaneResult,116 evidence: Option.Option<LaneEvidence>117 ): string =>11 unmodified lines129 )130 ),131 ].join("\n");132 195-/**196- * Where a lane's log is said to be when it was not kept because it held a197- * stored write-only value: the lane's refusal stands, its198- * log is never put in the evidence store, and nothing names the item.199- */133 export const { withheld } = ChecksFailed;134 135 const isTrouble = (result: LaneOutcome) =>136 result === "flaked" || result === "blocked";137 205-/** Each lane's result and evidence in a run, by lane. */138 interface ByLane {139 readonly evidence: ReadonlyMap<LaneName, LaneEvidence>;140 readonly results: ReadonlyMap<LaneName, LaneResult>;141 }4 unmodified lines146 });147 148 const noRun: ByLane = { evidence: new Map(), results: new Map() };149 218-/** One lane as a stage's runs left it. */150 interface Standing {151 readonly check: CheckLane;221- /** Its first run on the merged tree; `blocked` when that run left it out. */152 readonly first: LaneResult;223- /** Its fresh run, when it had one. */153 readonly again: Option.Option<LaneResult>;225- /** The result that stands: the fresh run's, else the first. */154 readonly stands: LaneResult;227- /** What the run that stands said of it, when it did not pass. */155 readonly said: Option.Option<LaneEvidence>;156 }157 158 const standingOf = (20 unmodified lines179 stands: Option.getOrElse(again, () => began),180 };181 };182 256-/** A lane as the gate classifies it, before its log is kept. */183 const laneRunOf = (checked: Checked, standing: Standing): LaneRun => {184 const signature = Option.getOrElse(185 Option.flatMap(standing.said, ({ signature: said }) =>186 Option.fromUndefinedOr(said)14 unmodified lines201 onSome: ({ result }) => ({ ...judged, rerun: result }),202 });203 };204 279-/** What the answer's state says the lanes are judged against, when it waits on checks of `tree`. */205 const checkedOf = (run: AnswerRun, tree: TreeSha): Option.Option<Checked> => {206 const { state } = run;207 208 if (!LandingState.guards.Checking(state) || state.tree !== tree) {27 unmodified lines236 run.sealed === true ? { ...carried, sealed: true } : carried237 );238 };239 315-/** A job's run with one lane's result, and its evidence, put in place of what it was. */240 const withLane = (241 ran: CheckRun,242 result: LaneResult,243 evidence: Option.Option<LaneEvidence>5 unmodified lines249 ],250 lanes: ran.lanes.map((each) => (each.lane === result.lane ? result : each)),251 });252 329-/**330- * The run with a `lintToZero` ask's lane as its count decides it: passed331- * at zero in its territory, failed above it (its signature says how many,332- * so two runs compare), and a load error when its lint printed no count. A333- * lint the Checker never got going stays as it ran, for its fresh run; its334- * exit code says nothing, since a lint with findings anywhere exits 1.335- */253+// A lint with findings anywhere exits 1, so its exit code says nothing here.254 const countedAskLane = (255 run: AnswerRun,256 ran: CheckRun257 ): Effect.Effect<CheckRun> => {43 unmodified lines301 )302 );303 };304 387-/** What the cheap stage counted: each ratchet per territory, or the one whose count it could not read. */305 interface Counted {306 readonly counts: readonly MeasuredCount[];307 readonly uncounted: Option.Option<RatchetName>;308 }309 393-/**394- * The policy's ratchets counted on the merged tree: one count lane per395- * command (named for the first ratchet that runs it), each output read for396- * every ratchet it serves and split by the project's modules (`measure`).397- */310 const countRatchets = <E, R>(311 run: AnswerRun,312 job: (lanes: readonly CheckLane[]) => Effect.Effect<CheckRun, E, R>313 ): Effect.Effect<Counted, E, R> =>32 unmodified lines346 onSuccess: (all) => ({ counts: all.flat(), uncounted: Option.none() }),347 });348 });349 438-/** What a stage run says of the counts: them, and the ratchet whose count it could not read. */350 const countFields = (counted: Counted): Pick<Ran, "counts" | "uncounted"> =>351 Option.match(counted.uncounted, {352 onNone: () => ({ counts: counted.counts }),353 onSome: (uncounted) => ({ counts: counted.counts, uncounted }),354 });355 445-/**446- * One stage's lanes on the merged tree `tree`: run, a troubled lane run447- * once more, and each lane that did not pass at first logged, unless its448- * log holds a stored value. The log's name counts the answer's merges449- * (`#1` on its first main), so a replayed step keeps its log under the450- * same name and a re-merge gets a new one. The cheap stage counts the451- * ratchets too.452- */356 export const runStage = (357 run: AnswerRun,358 tree: TreeSha,359 stage: Stage5 unmodified lines365 const runner = yield* CheckRunner;366 const evidence = yield* EvidenceStore;367 const lanes = lanesFor(run, stage);368 466- // The project scans each log for its stored values before it leaves467- // the run, where the values are; never the sandbox.369+ // The project scans each log for its stored values here, where the values are;370+ // never in the sandbox.371 const api = yield* Projects.use((projects) =>372 projects.get(checked.project)373 ).pipe(Effect.orDie);374 106 unmodified lines481 )482 ),483 });484 582-/** The lanes of a stage's run whose failure the gate classifies against main. */485 export const toCompareOnMain = (ran: Ran): readonly CheckLane[] =>486 ran.lanes487 .filter(488 ({ check, first }) =>489 first !== "passed" && check.lane !== ran.checked.askLane490 )491 .map(({ check }) => check);492 591-/**592- * Each failing lane, classified by the gate: against the same lane on main593- * (`onMain`; the ask's own check counts as green there, since it is red on594- * main by design), the fresh run, and the paths the answer changed.595- */493 export const refusalsOf = (494 ran: Ran,495 onMain: ReadonlyMap<LaneName, LaneOutcome>496 ): readonly (ChecksFailed | Flake | StaleBase | VerifierBlocked)[] => {24 unmodified lines521 )522 );523 };524 628-/** A lane's end on main: what the gate compares a failure on the merged tree with. */525 export const laneOnMain = (526 checked: Checked,527 lane: CheckLane528 ): Effect.Effect<LaneOutcome, never, CheckRunner> =>20 unmodified linesmodified:apps/platform/src/workflows/answer/program.ts+8 added-136 removed
1-/**2- * The Answer Workflow's program: one admitted answer3- * carried to its verdict and onto main through its project's answer queue,4- * each port call a named durable step.5- *6- * The project decides; the program only runs what it asks for. It loads7- * the answer's run (`answer`), then runs each port call the run waits on8- * (`merge`, the `cheap` lanes and the `checks` on the merged tree, `land`)9- * as a step whose value is the `LandingCommand` that reports it, and10- * reports it in a `record` step (`advanceAnswer`), which returns the calls11- * to run next. Every call to the project happens inside a step, so a replay12- * of the whole run follows the same path and runs nothing twice; a step13- * whose effect ran twice reports twice, and the landing lifecycle takes the14- * second report as the replay it is. Step names carry their attempt15- * (`merge#2`), so a merge onto a main that moved is a new step, not a replay.16- *17- * The run stops when the answer lands, is refused, waits on a person or on18- * the landing slot, or must wait for a retry: the project starts it again19- * then. A busy repo during a land is retried by the land step's own20- * retries first. It also stops when a port step finds nothing to do (the21- * answer no longer waits on that call), as the in-process run (`/inline`) does:22- * whatever moved the answer on carries it, and a run that went on from the23- * state it found could ask for the same call forever. Wherever it stops,24- * its last step writes the verdict, as it stands then, as the note on the25- * answer's head in its fork (`notes`).26- */1+// Step names carry their attempt (`merge#2`), so a merge onto a main that moved is a2+// new step, not a replay. The run stops when a port step finds nothing to do, or it3+// could ask for the same call forever.4 import { HostBusy } from "@repo/artifacts/repo-host";5 import type { RepoHost } from "@repo/artifacts/repo-host";6 import type { CheckRunner } from "@repo/checks/check-runner";7 import type { EvidenceStore } from "@repo/checks/evidence-store";49 unmodified lines57 toCompareOnMain,58 } from "./lanes.ts";59 import type { Stage } from "./lanes.ts";60 84-/** Every port the program runs on. */61 export type AnswerPorts =62 | CheckRunner63 | EvidenceStore64 | Lander65 | Projects66 | RepoHost67 | StepRunner;68 93-/** A run was started for a request its project does not hold: the project never does that. */69 export class UnknownRequest extends Data.TaggedError("UnknownRequest")<{70 readonly project: ProjectName;71 readonly requestId: RequestId;72 }> {}73 99-/** A land found the repo busy, at the landing's attempt: the land step's retries take it. */74 class LandBusy extends Data.TaggedError("LandBusy")<{75 readonly attempt: number;76 }> {}77 104-/** How a land step retries a busy repo before the project's own retry takes over. */78 export const landRetry: StepRetry = {79 backoff: "exponential",80 delayMs: 1000,81 limit: 3,82 };83 111-/** What a port step came to: the command that reports it, and what it saw beside it. */84 export const Reported = Schema.Struct({85 command: ReportedCommand,86 report: Schema.optionalKey(AnswerReport),87 });88 89 export type Reported = typeof Reported.Type;90 119-/** A port step's value: `None` when the answer no longer waits on that call. */91 const Reporting = Schema.Option(Reported);92 93 type NextStep = typeof NextStep.Type;94 3 unmodified lines98 NextStep,99 { readonly _tag: Tag }100 >;101 131-/** How many times each port call has run in this run: the attempt in a step's name. */102 interface Attempts {103 readonly Land: number;104 readonly Merge: number;105 readonly RunChecks: number;4 unmodified lines110 report?: AnswerReport111 ): Option.Option<Reported> =>112 Option.some(report === undefined ? { command } : { command, report });113 144-/** The port calls among a landing's effects, as a run hands them on. */114 const callsOf = (effects: readonly LandingEffect[]): readonly NextStep[] =>115 effects.flatMap((effect) =>116 LandingEffect.$match(effect, {117 Emit: (): readonly NextStep[] => [],6 unmodified lines124 RunChecks: ({ tree }) => [NextStep.cases.RunChecks.make({ tree })],125 })126 );127 159-/** What a call is about, to tell whether the run still waits on it. */128 const keyOf = (call: NextStep): string =>129 NextStep.match(call, {130 Land: ({ main, tree }) => `land ${main} ${tree}`,131 Merge: ({ head, main }) => `merge ${head} onto ${main}`,132 Retry: () => "retry",133 RunChecks: ({ tree }) => `checks ${tree}`,134 });135 168-/** Whether the answer's run waits on `call` now. */136 const waitsOn = (run: AnswerRun, call: NextStep) =>137 callsOf(nextSteps(run)).some((each) => keyOf(each) === keyOf(call));138 172-/** The answer's project, as the platform reaches it. */139 const projectOf = (project: ProjectName) =>140 Projects.use((projects) => projects.get(project)).pipe(Effect.orDie);141 176-/** The answer's run as its project holds it now. */142 const load = ({ project, requestId }: AnswerParams) =>143 Effect.flatMap(projectOf(project), (api) => api.answer(requestId));144 180-/**181- * The port call `effect` names, run as the in-process run runs it182- * (`runStep`), on the answer's run as its project holds it now (as183- * `prepare` hands it on); `None` when the run no longer waits on `call`.184- * A merge that conflicts reads the project's landings to name who moved185- * each path.186- */145 const portCall = (146 params: AnswerParams,147 call: Call<"Land" | "Merge">,148 effect: LandingEffect,13 unmodified lines162 163 return yield* runStep(ready, effect, api.landings);164 });165 208-/** A verdict as its note holds it: JSON. */166 const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));167 211-/**212- * The stored write-only value `verdict`'s note would carry, by its item:213- * the project scans the note before it leaves the run. Only the214- * platform's log hears which item, never the value.215- */168 const leakIn = (params: AnswerParams, verdict: Verdict, where: string) =>169 Effect.gen(function* () {170 const text = yield* Effect.orDie(encodeVerdict(verdict));171 const api = yield* projectOf(params.project);14 unmodified lines186 187 return found;188 });189 238-/**239- * The run as its land takes it: the verdict `Lander.land` writes as the240- * landed commit's note on canonical is left off when it holds a stored241- * value, so the landing writes no note; the verdict stands in the project.242- */190 const withSafeNote = (params: AnswerParams) => (run: AnswerRun) =>191 run.verdict === undefined192 ? Effect.succeed(run)193 : Effect.map(leakIn(params, run.verdict, "canonical"), (leaked) =>194 Option.isSome(leaked) ? Struct.omit(run, ["verdict"]) : run195 );196 250-/** The answer's head merged onto the main the call names. */197 const merge = (params: AnswerParams, call: Call<"Merge">) =>198 portCall(199 params,200 call,4 unmodified lines205 main: call.main,206 })207 );208 263-/**264- * The checked tree landed on main as the platform's commit, through the265- * project's landing slot (the run waits on a land only while it holds the266- * slot). A main that moved sends the answer back to merge; a busy repo267- * fails the step, for its retries.268- */209 const land = (params: AnswerParams, call: Call<"Land">) =>210 Effect.flatMap(211 portCall(212 params,6 unmodified lines219 ? Effect.fail(new LandBusy({ attempt: given.value.command.attempt }))220 : Effect.succeed(given)221 );222 283-/**284- * One stage's lanes on the merged tree, then each failing lane on main, one285- * step per (main, lane), and the gate's classification of each failure.286- */223 const stage = (224 params: AnswerParams,225 tree: Call<"RunChecks">["tree"],226 name: Stage,33 unmodified lines260 refusals: refusalsOf(ran, new Map<LaneName, LaneOutcome>(onMain)),261 };262 });263 328-/**329- * The refusals of the cheap stage's counts: a ratchet whose command printed330- * no count the platform can read is the gate's trouble, never the answer's331- * (`VerifierBlocked`), and the project hears which one in its log.332- */264 const uncountedRefusals = (cheap: StageRun) =>265 StageRun.guards.Ran(cheap) && cheap.uncounted !== undefined266 ? Effect.as(267 Effect.logWarning(2 unmodified lines270 [new VerifierBlocked({})]271 )272 : Effect.succeed([]);273 343-/** What a port step came to: its report, and the held-back run it judged, if any. */274 interface Ran {275 readonly given: Option.Option<Reported>;276 readonly judged: Option.Option<Judged>;277 }2 unmodified lines280 given,281 judged: Option.none(),282 });283 354-/**355- * An answer that adds a file holding a stored write-only value, until its356- * deciders can be asked: the run refuses it as the platform's trouble357- * (`VerifierBlocked`, which names nothing, so the scan is no oracle on358- * which item a guess matched), and only the platform's log says which359- * items, never a value. The `SecretInTree` decision on the deciders' Today360- * that should hold it instead (`AwaitingDecision` for its answerer) is the361- * project service's to open.362- */284+// `VerifierBlocked` names nothing, so the scan is no oracle on which item a guess285+// matched; only the platform's log names the items, never a value.286 const quarantine = (287 params: AnswerParams,288 items: readonly EnvKey[]289 ): Effect.Effect<readonly VerifierBlocked[]> =>11 unmodified lines301 ),302 [new VerifierBlocked({})]303 );304 382-/** The checks reported refused before any lane ran: the landing guards' refusals. */305 const guardedOut = (306 params: AnswerParams,307 call: Call<"RunChecks">,308 run: Extract<GuardRun, { readonly _tag: "Guarded" }>11 unmodified lines320 )321 )322 );323 402-/**403- * The checks on the exact merged tree: first the landing guards (when the404- * visibility cartridge provides them, `guards.ts`), then the cheap stage405- * (its lanes, and the ratchets' counts), then, if it passed, the ask's own406- * check and every other project lane, then, if those passed and a407- * held-back suite judges the answer, its held-back run (step 7 (d),408- * `held-back.ts`; `earlier` carries over to an unchanged patch). The first409- * stage that refuses ends them, with its refusals and its lanes. The counts410- * go to the project with the report, which judges them against its411- * baselines and opens the decisions a reasoned escape412- * asks for (step 7 (e)).413- */324 const checks = (325 params: AnswerParams,326 call: Call<"RunChecks">,327 attempt: number,88 unmodified lines416 417 return { given, judged: held };418 });419 510-/**511- * A port step's report given to the project, and the calls to run next.512- * When nothing comes next, or the step had nothing to report, the run's own513- * state says what it waits on: a person, the landing slot, a retry, or514- * nothing (the report was given already, by a step whose effect ran twice).515- */420 const record = (params: AnswerParams, given: Option.Option<Reported>) =>421 Effect.gen(function* () {422 const api = yield* projectOf(params.project);423 22 unmodified lines446 outcome: outcomeOf(run.value.state),447 } satisfies Steps;448 });449 546-/**547- * What writing an answer's verdict note came to, kept as the step's value:548- * a replay reads it back, and a note that could not be written never fails549- * the run, in this run or a replay.550- */450 const Noted = Schema.TaggedUnion({552- /** The answer has no verdict to note: no tree of it was checked. */451 Unjudged: {},554- /** The note could not be written, for this reason; the verdict stands in the project. */452 Unwritten: { reason: Schema.String },453 Written: { changed: Schema.Boolean, notesTip: CommitSha },454 });455 559-/** How often a busy fork is asked again for the note before it is given up. */456 const noteRetry = {457 schedule: Schedule.exponential("250 millis"),458 times: 2,459 while: Schema.is(HostBusy),460 };461 566-/** The verdict as `verdict` shows it: the one the checks gave, with where the answer stands now. */462 const shownVerdict = (run: AnswerRun) =>463 Option.map(Option.fromUndefinedOr(run.verdict), (made): Verdict => ({464 ...made,465 outcome: outcomeOf(run.state),466 }));467 573-/** The answer's verdict, as it stands, written as the note on its head in its fork. */468 const noteVerdict = (params: AnswerParams) =>469 Effect.gen(function* () {470 const run = yield* load(params);471 9 unmodified lines481 }482 483 const { fork, verdict } = judged.value;484 591- // The note leaves the run for the answer's fork: a note that holds a592- // stored value is not written; the verdict stands in the project.485+ // A note that holds a stored value is not written; the verdict stands in the project.486 if (Option.isSome(yield* leakIn(params, verdict, "fork"))) {487 return Noted.cases.Unwritten.make({ reason: "SecretInOutput" });488 }489 4 unmodified lines494 }).pipe(Effect.retry(noteRetry));495 496 return Noted.cases.Written.make(written);497 }).pipe(605- // Anything but an interruption is recorded: the note is bookkeeping, and606- // a fork its answerer filled with refs of their own may break it.498+ // Anything but an interruption is recorded: the note is bookkeeping, and a fork its499+ // answerer filled with refs of their own may break it.500 Effect.catchCause((cause) =>501 Cause.hasInterruptsOnly(cause)502 ? Effect.interrupt503 : Effect.as(10 unmodified lines514 )515 )516 );517 625-/**626- * Once the run stops, the verdict note on the answer's head in its fork:627- * the verdict as `verdict` shows it, so an answerer628- * reads where the answer stands with plain git, refused, waiting or629- * landed. Its own step, named for the outcome the run stopped at, so a630- * replay reads the record and a restarted run writes the same note again,631- * which changes nothing. The canonical note is `Lander.land`'s.632- */518 const notes = (519 params: AnswerParams,520 outcome: Outcome521 ): Effect.Effect<void, never, AnswerPorts> =>522 Effect.flatMap(StepRunner, ({ step }) =>523 Effect.asVoid(step(`notes:${outcome._tag}`, Noted, noteVerdict(params)))524 );525 641-/** The port call a step runs, under its name. */526 const portStep = (527 params: AnswerParams,528 call: Call<"Land" | "Merge" | "RunChecks">,529 attempt: number,27 unmodified lines557 Merge: "merge",558 RunChecks: "checks",559 } as const satisfies Record<keyof Attempts, string>;560 677-/**678- * Runs the calls `at` names, one after another, until none is left.679- * `earlier` is the last held-back run of this Workflow, which carries over680- * to a later check of an unchanged patch.681- */561 const carry = (562 params: AnswerParams,563 at: Steps,564 attempts: Attempts,565 earlier: Option.Option<Judged>566 ): Effect.Effect<Outcome, never, AnswerPorts> =>567 Effect.gen(function* () {689- // A retry is the project's to start, at its alarm.568 if (at.effects.some(NextStep.guards.Retry)) {569 return at.outcome;570 }571 27 unmodified lines599 Option.orElse(judged, () => earlier)600 );601 });602 725-/**726- * Carries one admitted answer as far as it goes now: merged onto main,727- * checked on the merged tree, and landed through its project's serial728- * queue, or refused, or waiting. The same request run again converges on729- * one outcome and one landing (principle 8).730- */603 export const runAnswer = (604 params: AnswerParams605 ): Effect.Effect<Outcome, never, AnswerPorts> =>606 Effect.gen(function* () {21 unmodified linesmodified:apps/platform/src/workflows/on-push/classify.ts-34 removed
1-/**2- * What one push event means to the platform, as a pure3- * function of the event and what the project's Durable Object says about it.4- * Pushes the platform made (landings, the landed mirror, parked composes,5- * verdict notes) and claim-fork pushes the gateway already recorded are6- * ignored; a claim-fork push the gateway never saw keeps its claim alive;7- * canonical `main` moved any other way is stray, for the deciders to adopt8- * or revert.9- */1 import { Brand } from "@repo/brand";2 import { notesRef } from "@repo/git/notes";3 import { RefNameText } from "@repo/protocol/domain/common";4 import { AskId, CommitSha, ProjectName } from "@repo/protocol/ids";2 unmodified lines7 import { RepoKind } from "../../repo-names.ts";8 import { isZero } from "./event.ts";9 import type { OnPushEvent } from "./event.ts";10 20-/** Why a push needs nothing from the platform. */11 export const IgnoredReason = Schema.Literals([22- /** Canonical `main` moved to a commit the platform landed. */12 "own landing",24- /** A ref the platform writes beside `main`: under its prefix, or its notes. */13 "bookkeeping ref",26- /** A claim-fork push the gateway recorded when it forwarded it. */14 "seen",28- /** A repo no project of the platform's has. */15 "unknown repo",30- /** A ref whose moves the platform does not track: a canonical branch other than `main`, or a decider's working fork. */16 "not main",32- /** A claim fork's ref deleted: no commit to keep the claim alive with. */17 "deleted ref",18 ]);19 20 export type IgnoredReason = typeof IgnoredReason.Type;21 38-/** What the platform does about one push event. */22 export const PushVerdict = Schema.TaggedUnion({40- /** A claim-fork push the gateway never recorded: record it, for its claim's liveness. */23 ForkPush: { ask: AskId, head: CommitSha, project: ProjectName },24 Ignored: { reason: IgnoredReason },43- /**44- * Canonical `main` moved without a landing: a `StrayPush` decision whose45- * default is revert. `after` is git's zero id when `main` was deleted,46- * `before` when it was created.47- */25 Stray: {26 after: CommitSha,27 before: CommitSha,28 project: ProjectName,2 unmodified lines31 });32 33 export type PushVerdict = typeof PushVerdict.Type;34 58-/** What the project's Durable Object says about a push event, read before it is classified. */35 export interface PushFacts {60- /** The repo, by its name; `Unknown` also when no project has that name. */36 readonly repo: RepoKind;62- /** Commits the platform landed on canonical `main`, among those the event names. */37 readonly landed: ReadonlySet<CommitSha>;64- /** Whether the gateway recorded this repo taking the event's `after`. */38 readonly seen: boolean;39 }40 68-/** The one canonical ref the platform alone moves. */41 export const mainRef = RefNameText.make("refs/heads/main");42 71-/**72- * A ref the platform writes beside `main`, in its own push after main's:73- * the landed mirror and parked composes under its prefix,74- * and its verdict notes. Each fires its own event.75- */43 export const isBookkeeping = (ref: string): boolean =>44 ref.startsWith(Brand.refsPrefix) || ref === notesRef;45 46 const ignored = (reason: IgnoredReason): PushVerdict =>47 PushVerdict.cases.Ignored.make({ reason });48 82-/** What `event` means, given what the project's Durable Object said of it. */49 export const classifyPush = (50 event: OnPushEvent,51 facts: PushFacts52 ): PushVerdict => {39 unmodified linesmodified:apps/platform/src/workflows/on-push/event.ts-18 removed
1-/**2- * What Artifacts sends the `OnPush` Workflow for every ref a push moved in3- * the public namespace: the `cf.artifacts.repo.pushed` event, verbatim.4- * The Workflow decodes its params with it before anything5- * else (principle 2); its `id` is the Workflow's instance id, so a6- * redelivered event cannot start a second run.7- */1 import { CommitSha, RepoName } from "@repo/protocol/ids";2 import { Schema } from "effect";3 11-/** A commit's author or committer, as git records one. */4 const GitIdentity = Schema.Struct({5 email: Schema.String,6 name: Schema.String,7 });8 17-/** One commit the push brought, as Artifacts lists it. */9 const PushedCommit = Schema.Struct({10 author: GitIdentity,11 committer: GitIdentity,12 id: CommitSha,5 unmodified lines18 19 export const OnPushEvent = Schema.Struct({20 id: Schema.NonEmptyString,21 payload: Schema.Struct({31- /** Where the ref points now: git's zero id when the push deleted it. */22 after: CommitSha,33- /** Where the ref pointed before: git's zero id when the push created it. */23 before: CommitSha,35- /** Empty for a ref moved to a commit the repo already held. */24 commits: Schema.Array(PushedCommit),25 commitsTruncated: Schema.Boolean,38- /** The one ref this event is about: each ref a push moves fires its own. */26 ref: Schema.NonEmptyString,27 totalCommitsCount: Schema.Int,28 }),29 source: Schema.Struct({4 unmodified lines34 });35 36 export type OnPushEvent = typeof OnPushEvent.Type;37 51-/**52- * git's all-zero id: the `before` of a ref a push created, the `after` of53- * one it deleted. It names no commit.54- */38 export const ZeroSha = CommitSha.make("0".repeat(40));39 57-/** Whether `sha` is git's zero id, which stands for "no commit". */40 export const isZero = (sha: CommitSha): boolean => sha === ZeroSha;modified:apps/platform/src/workflows/on-push/facts.ts-17 removed
1-/**2- * What OnPush asks a project's Durable Object before it classifies a push3- * event: whether canonical `main`'s new commit is a landing the platform4- * made (`landing(platform, sha)`), and whether the gateway recorded a claim5- * fork taking the pushed commit. Each read is asked only of the events it6- * can change the verdict of.7- */1 import { platformHandle } from "@repo/project/attention/effects";2 import type { ProjectApi } from "@repo/project/project";3 import { keptEvents } from "@repo/project/project-store";4 import { Projects } from "@repo/project/projects";7 unmodified lines12 import type { PushFacts } from "./classify.ts";13 import { isZero } from "./event.ts";14 import type { OnPushEvent } from "./event.ts";15 23-/** The platform itself, reading a project's public record. */16 const platform = Person.make({ handle: platformHandle });17 26-/** The project a repo belongs to, when its name says. */18 const projectOf = (kind: RepoKind): Option.Option<ProjectName> =>19 RepoKind.$match(kind, {20 Canonical: ({ project }) => Option.some(project),21 ClaimFork: ({ project }) => Option.some(project),22 Unknown: () => Option.none(),23 WorkingFork: ({ project }) => Option.some(project),24 });25 35-/** `sha` as a landing the platform made on the project's `main`, or none. */26 const landedOf = (api: ProjectApi, sha: CommitSha) =>27 Effect.map(Effect.isSuccess(api.landing(platform, sha)), (landed) =>28 landed ? new Set([sha]) : new Set<CommitSha>()29 );30 41-/**42- * Whether the gateway recorded the claim's fork taking `head`: recording a43- * claimant's push keeps the claim alive and emits `Pushed`, which the44- * project keeps among its newest events.45- */31 const seenBy = (32 api: ProjectApi,33 push: { readonly ask: AskId; readonly head: CommitSha }34 ) =>11 unmodified lines46 repo,47 seen: false,48 });49 65-/** The project and the API of the repo `event` is about, when the platform has that project. */50 export const projectFor = (event: OnPushEvent) =>51 Effect.gen(function* () {52 const kind = repoKind(event.source.repoName);53 const project = projectOf(kind);8 unmodified lines62 63 return Option.map(api, (found) => ({ api: found, kind }));64 });65 82-/** What the project's Durable Object says about `event`. */66 export const factsOf = (67 event: OnPushEvent68 ): Effect.Effect<PushFacts, never, Projects> =>69 Effect.gen(function* () {29 unmodified linesmodified:apps/platform/src/workflows/admission-steps.ts+2 added-32 removed
1-/**2- * Admission of a layer push's held-back checks, as steps of the `Answer`3- * Workflow: the project plans the runs4- * (`ProjectApi.admissionPlan`: each changed area's checks green on main k5- * times, red on each known-bad tree its manifest names), the Checker runs6- * each, and the project judges the area bits (`recordAdmission`), moving7- * the layer's landed SHA under a fresh commitment, or leaving it.8- *9- * Every step is durable, named for what it runs, inside the instance10- * `admit-<project>-<layer>-<head>`: a replay reads each recorded value back,11- * and the project's judgement changes nothing once the head is no longer12- * proposed (principle 8). What the steps record is the plan's outline (the13- * main it runs on, and each run by area and attempt or tree) and each14- * run's area bits: never a check's file, path or name. Each step asks the15- * project for the plan again and runs the planned job it names, so the16- * sealed files go from the project to the Checker and nowhere else.17- *18- * Each job runs on main as the plan found it, in the project's own repo,19- * with no public lane beside the held-back checks, and with no env: no20- * placeholder, no proxy, no value. A Checker that stays blocked through a21- * step's retries leaves the push proposed, unjudged.22- */1+// Steps record only the plan's outline and each run's area bits, never a check's2+// file, path or name: the sealed files go from the project to the Checker alone.3 import { CheckAt, CheckRunner } from "@repo/checks/check-runner";4 import { noRunEnv } from "@repo/project/env-port";5 import { Projects } from "@repo/project/projects";6 import { AdmissionRun } from "@repo/project/visibility-port";11 unmodified lines18 import type { AdmissionParams } from "../answer-runs.ts";19 import { StepRunner } from "./step.ts";20 import type { StepRetry } from "./step.ts";21 42-/** A planned run, by what names it in its plan: its area, and main's attempt or the known-bad tree. */22 const RunRef = Schema.TaggedUnion({23 OnKnownBad: { area: AreaName, tree: CommitSha },24 OnMain: { area: AreaName, attempt: Schema.Int },25 });26 27 type RunRef = typeof RunRef.Type;28 50-/** What the plan step records: the main every run checks out, and each run by reference. */29 const Outline = Schema.Struct({30 main: LandedSha,31 runs: Schema.Array(RunRef),32 });33 34 type Outline = typeof Outline.Type;35 58-/** What one run's step records: its area bits, or that its plan is gone (the head moved on). */36 const Ran = Schema.TaggedUnion({37 Bits: { areas: Schema.Array(HeldBackResult) },38 Gone: {},39 });40 41 type Ran = typeof Ran.Type;42 66-/** How a run step retries a Checker that could not run, before the push is left unjudged. */43 const admissionRetry: StepRetry = {44 backoff: "exponential",45 delayMs: 10_000,46 limit: 3,47 };48 73-/** How many runs go to the Checker at once. */49 const RUNS_AT_ONCE = 4;50 76-/** A planned run, by reference: no job, so no file. */51 const refOf = (run: AdmissionRun): RunRef =>52 AdmissionRun.guards.OnMain(run)53 ? RunRef.cases.OnMain.make({ area: run.area, attempt: run.attempt })54 : RunRef.cases.OnKnownBad.make({ area: run.area, tree: run.tree });55 82-/** A run's step name, and its identity within its plan. */56 const nameOf = (ref: RunRef) =>57 RunRef.match(ref, {58 OnKnownBad: ({ area, tree }) => `admission:${area}:known-bad:${tree}`,59 OnMain: ({ area, attempt }) => `admission:${area}:main#${attempt}`,60 });61 89-/** One admission of a layer push, carried from its plan to its judgement. */62 export const admissionSteps = (63 params: AdmissionParams64 ): Effect.Effect<void, never, CheckRunner | Projects | StepRunner> =>65 Effect.gen(function* () {66 const { step } = yield* StepRunner;67 const runner = yield* CheckRunner;68 const projects = yield* Projects;69 98- /** The project's plan as it stands now; none once nothing waits to be admitted. */70 const planNow = projects.get(params.project).pipe(71 Effect.flatMap((api) =>72 api.admissionPlan({ head: params.head, layer: params.layer })73 ),20 unmodified lines94 }95 96 const { main } = outline.value;97 127- /** One planned run, in the Checker: the plan asked for again, and the job it names run on main. */98 const runOne = (ref: RunRef) =>99 step(100 nameOf(ref),101 Ran,78 unmodified linesmodified:apps/platform/src/workflows/answer.ts+2 added-39 removed
1-/**2- * The `Answer` Workflow: carries one admitted answer through merge, checks3- * and landing, each a durable step. The class is thin:4- * it decodes its params, runs `runAnswer` with its steps over the engine's5- * `step.do`, and hands the engine the outcome encoded as JSON. The program6- * lives in `answer/program.ts`. The class name is frozen.7- *8- * Every port comes from the Worker's env through `workerPorts`, as the9- * Worker's own ports do. The project's Durable Object is reached as the10- * platform itself: its answer queue (`answer`, `advanceAnswer`) takes no11- * caller.12- *13- * The same Workflow admits a layer push's sealed checks: params14- * tagged `Admission` run `admissionSteps`, so typed visibility adds no15- * Workflow binding. An admission's output is `null`.16- *17- * So does a round of a proposal's draft: params tagged `Draft` run18- * `draftSteps` (ADR 0018), over the Worker's ports and the drafter19- * (`draftPorts`), with each step's timeout handed to the engine. A draft's20- * output is `null` too.21- */1+// The class name is frozen. Params tagged `Admission` or `Draft` run admissions and2+// draft rounds on this same Workflow, so neither adds a Workflow binding.3 import type { RepoHost } from "@repo/artifacts/repo-host";4 import type { Drafter } from "@repo/drafting/drafter";5 import type { Projects } from "@repo/project/projects";6 import { Outcome } from "@repo/protocol/domain/outcome";12 unmodified lines19 import type { EngineSteps } from "./draft-steps.ts";20 import { workflowSteps } from "./step.ts";21 import type { StepRunner, WorkflowSteps } from "./step.ts";22 42-/** An answer's outcome as the engine keeps it: JSON. */23 export const OutcomeJson = Schema.toCodecJson(Outcome);24 25 export type OutcomeEncoded = typeof OutcomeJson.Encoded;26 47-/**48- * One run of the Workflow over `ports`: the params decoded (a run that49- * can't decode them fails, and no step runs), the program run with its50- * steps over the engine's, and the outcome encoded.51- */27 export const runWorkflow = <E>(28 ports: Layer.Layer<Exclude<AnswerPorts, StepRunner>, E>,29 payload: typeof AnswerParams.Encoded,30 steps: WorkflowSteps9 unmodified lines40 Effect.orDie41 )42 );43 69-/** One admission's run of the Workflow over `ports`, its params decoded as an answer's are. */44 export const runAdmission = <E>(45 ports: Layer.Layer<Exclude<AnswerPorts, StepRunner>, E>,46 payload: typeof AdmissionParams.Encoded,47 steps: WorkflowSteps10 unmodified lines58 Effect.orDie59 )60 );61 88-/**89- * One draft round's run of the Workflow over `ports`, its params decoded90- * first, each step handed its timeout.91- */62 export const runDraftWorkflow = <E>(63 ports: Layer.Layer<Projects | Drafter | RepoHost, E>,64 payload: typeof DraftParams.Encoded,65 steps: EngineSteps8 unmodified lines74 Effect.orDie75 )76 );77 108-/** Whether the engine's params start an admission rather than an answer. */78 const admits = Schema.is(Schema.toEncoded(AdmissionParams));79 111-/** Whether the engine's params start a draft's round. */80 const drafts = Schema.is(Schema.toEncoded(DraftParams));81 82 export class Answer extends WorkflowEntrypoint<83 Env,84 typeof WorkflowParams.Encoded85 > {118- /**119- * `step` is the engine's `WorkflowStep`; the run uses only its `do`120- * (`EngineSteps`), so a test can hand it a fake engine.121- */86 override run(87 event: Readonly<WorkflowEvent<typeof WorkflowParams.Encoded>>,88 step: EngineSteps89 ): Promise<OutcomeEncoded | null> {90 const config = decodeEnv(this.env);91 const { payload } = event;92 93 if (drafts(payload)) {130- // The env decoded once: the Worker's ports and the drafter from it.94 return runDraftWorkflow(95 Layer.unwrap(96 Effect.map(config, (decoded) =>97 Layer.merge(workerPorts(decoded), draftPorts(decoded))14 unmodified linesmodified:apps/platform/src/workflows/draft-steps.ts-20 removed
1-/**2- * One round of a proposal's draft, as steps of the `Answer` Workflow3- * (ADR 0018): the program is `@repo/drafting/run`'s `runDraft`, shared with4- * the in-process run, over the Workflow's `StepRunner`. Its steps are5- * `context`, then `draft-<n>` and `rehearse-<n>` per attempt, then6- * `settle`, inside the instance `draft-<project>-<proposal>-r<round>`.7- *8- * The engine is handed a timeout with each of the run's steps9- * (`timedSteps`): a model call or a rehearsal on a cold Checker takes10- * minutes, and the other two steps are one Durable Object call each, well11- * inside the same bound.12- */1 import type { RepoHost } from "@repo/artifacts/repo-host";2 import type { Drafter } from "@repo/drafting/drafter";3 import { runDraft } from "@repo/drafting/run";4 import type { Projects } from "@repo/project/projects";3 unmodified lines8 import type { DraftParams } from "../answer-runs.ts";9 import { StepRunner } from "./step.ts";10 import type { WorkflowStepRetries, WorkflowSteps } from "./step.ts";11 24-/** How long one step of a draft's run may take before the engine fails it. */12 export const DRAFT_STEP_TIMEOUT = "10 minutes";13 27-/**28- * The part of a Workflow's `WorkflowStep` a draft's run uses: `do`, with29- * retries and a timeout. A `WorkflowStep` is one, and so is anything that30- * takes `WorkflowSteps`' narrower config.31- */14 export interface EngineSteps {15 readonly do: (16 name: string,17 config: {3 unmodified lines21 body: () => Promise<Schema.Json>22 ) => Promise<Schema.Json>;23 }24 43-/** The engine's steps, each handed the draft step timeout. */25 export const timedSteps = (engine: EngineSteps): WorkflowSteps => ({26 do: (name, config, body) =>27 engine.do(name, { ...config, timeout: DRAFT_STEP_TIMEOUT }, body),28 });29 49-/** One round of a draft, carried from its context to its settling. */30 export const draftSteps = (31 params: DraftParams32 ): Effect.Effect<void, never, StepRunner | Projects | Drafter | RepoHost> =>33 StepRunner.use((runner) => runDraft(params, { step: runner.step }));modified:apps/platform/src/workflows/generated.ts-20 removed
1-/**2- * The platform's generator for a project's own agent files:3- * the contribute skill (`.agents/skills/<key>-contribute/SKILL.md`4- * and its `.claude/skills/` copy) and the block in the project's AGENTS.md,5- * from `@repo/agent-kit`, which `@repo/project` may not import.6- *7- * The Project DO runs it after any landing that moved its landed SHA8- * (`@repo/project/generated`): when the policy read there changes what the9- * files say, the DO lands them as a separate platform commit, composed onto10- * main and landed through the Lander like every platform landing, with the11- * request id `gen-<landed>`. `ProjectSkillGenerator` is the layer a DO's12- * ports carry it in; a project whose ports leave it out generates nothing.13- */1 import { agentsBlock, upsertAgentsBlock } from "@repo/agent-kit/agents-block";2 import { projectSkill } from "@repo/agent-kit/project-skill";3 import { ProjectGenerator } from "@repo/project/generated";4 import type { Generate } from "@repo/project/generated";5 import { Effect, Layer, Option } from "effect";6 20-/** The project's own AGENTS.md: only the block between the platform's markers is written. */7 const agentsFile = "AGENTS.md";8 23-/**24- * The skill, in both places harnesses read it, and AGENTS.md as the landed25- * tree has it with the block put in (appended after a blank line when the26- * file has none; made when there is no file).27- */9 export const generate: Generate = ({ landed, policy, project, read }) =>10 Effect.gen(function* () {11 const skills = yield* projectSkill({ landed, policy, project });12 const block = yield* agentsBlock({ landed, policy, project });4 unmodified lines17 { content: upsertAgentsBlock(existing, block), path: agentsFile },18 ];19 });20 40-/** The generator, for a Project DO's ports. */21 export const ProjectSkillGenerator = Layer.succeed(ProjectGenerator, generate);modified:apps/platform/src/workflows/notes.ts+3 added-42 removed
1-/**2- * Verdict notes on an answer's fork: after the3- * platform judges an answer, its answerer reads the verdict with plain git,4- *5- * git fetch origin refs/notes/<slug>:refs/notes/<slug>6- * git notes --ref=<slug> show <head>7- *8- * in a clone of their fork. One JSON note per head, the public `Verdict`9- * encoding and nothing more; a newer verdict on the same head10- * replaces its note, and the notes on the fork's other heads stay.11- *12- * Everything goes through `RepoHost` (principle 6): the notes ref's tip from13- * the ref listing (the binding resolves no custom ref), the earlier14- * notes through reads, and the new note as one compare-and-swap push of the15- * notes ref alone, never beside a branch (no atomic multi-ref push),16- * never forced. Each new notes commit has the earlier one as its parent, so17- * the same fetch, without `+`, brings the newer note to a clone that has the18- * older. The canonical notes on landings are the Lander's.19- */1 import { HostBusy, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";2 import type {3 ObjectId,4 RepoName,7 unmodified lines12 import { DateTime, Effect, Option, Schema } from "effect";13 14 export { notesRef } from "@repo/git/notes";15 35-/** What writing a note came to: the notes ref's tip, and whether the write moved it. */16 export interface NoteWritten {17 readonly notesTip: CommitSha;18 readonly changed: boolean;19 }1 unmodified line21 const encoder = new TextEncoder();22 23 const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));24 45-/** The note's bytes as `noteCommit` writes them: the verdict's JSON and a newline. */25 const noteBytes = (verdict: Verdict) =>26 Effect.map(Effect.orDie(encodeVerdict(verdict)), (json) =>27 encoder.encode(`${json}\n`)28 );29 51-/** A blob holding `bytes` as git frames it: its header, then its content. */30 const framed = (bytes: Uint8Array) => {31 const header = encoder.encode(`blob ${bytes.byteLength}\0`);32 const raw = new Uint8Array(header.byteLength + bytes.byteLength);33 2 unmodified lines36 37 return raw;38 };39 62-/** The id git gives a blob holding `bytes`. */40 const blobId = (bytes: Uint8Array) =>41 Effect.map(42 Effect.promise(() => crypto.subtle.digest("SHA-1", framed(bytes))),43 (digest) =>1 unmodified line45 .map((byte) => byte.toString(16).padStart(2, "0"))46 .join("")47 );48 72-/** git's zlib stream, as a loose object holds it. */49 const deflate = (bytes: Uint8Array) =>50 Effect.map(51 Effect.promise(() =>52 new Response(2 unmodified lines55 ),56 (buffer) => new Uint8Array(buffer)57 );58 83-/**84- * The earlier note `blob` in the fork, put in `source` as a loose object.85- * A push over git smart HTTP (`/binding`'s) sends every object the new86- * notes tree names that it cannot tell the remote has, and the source87- * holds no earlier notes commit to tell it by, so it must hold their blobs.88- */59+// A push over smart HTTP sends every object the new notes tree names that it cannot60+// tell the remote has, and the source holds no earlier notes commit, so it must hold61+// their blobs.62 const keepEarlierNote = (63 fork: RepoName,64 source: ScratchSource,65 blob: ObjectId20 unmodified lines86 source.fs.promises.writeFile(`${dir}/${blob.slice(2)}`, loose)87 );88 });89 117-/** The notes tree's entries at `tip`, read through the port; none before the first note. */90 const notesAt = (fork: RepoName, tip: Option.Option<CommitSha>) =>91 Option.match(tip, {92 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),93 onSome: (sha) =>20 unmodified lines114 readonly head: CommitSha;115 readonly verdict: Verdict;116 }117 146-/**147- * One try: the note on top of the notes ref as listed now, pushed with a148- * compare-and-swap on that ref alone. `None` when the ref moved under it.149- */118 const once = (input: NoteInput) =>119 Effect.gen(function* () {120 const host = yield* RepoHost;121 35 unmodified lines157 ? Option.some<NoteWritten>({ changed: true, notesTip: commit })158 : Option.none();159 });160 193-/**194- * `verdict` as the note on `head` in `fork`. The same verdict already there195- * changes nothing (`changed: false`, no push). A notes ref that moved196- * between the listing and the push is listed again and the note written on197- * top of the move, once; one that moved under that too is `HostBusy`, for198- * the caller to retry.199- */161 export const writeVerdictNote = (162 input: NoteInput163 ): Effect.Effect<NoteWritten, RepoNotFound | HostBusy, RepoHost> =>164 Effect.gen(function* () {14 unmodified linesmodified:apps/platform/src/workflows/on-push.ts+7 added-48 removed
1-/**2- * The `OnPush` Workflow, the platform's backstop: Artifacts3- * starts one for every ref a push moved in the public namespace4- * (`triggers.events`), with the event's id as the instance5- * id, so a redelivered event starts nothing. Each run reads6- * what the project's Durable Object knows of the push, classifies it, and7- * records what needs recording through the DO: a claim-fork push the8- * gateway never saw keeps its claim alive, and canonical `main` moved9- * without a landing becomes a `StrayPush` decision whose default is revert.10- * It reverts nothing itself. The class name is frozen.11- */1+// The class name is frozen.2 import type { PushReport } from "@repo/project/project";3 import type { Projects } from "@repo/project/projects";4 import { Anonymous, Person } from "@repo/protocol/principal";5 import { WorkflowEntrypoint } from "cloudflare:workers";8 unmodified lines14 import { factsOf, projectFor } from "./on-push/facts.ts";15 import { StepRunner, workflowSteps } from "./step.ts";16 import type { StepRetry, WorkflowSteps } from "./step.ts";17 28-/** What the gate said of a recorded push, by tag: for whoever reads the run. */18 const Recorded = Schema.Array(Schema.String);19 31-/** `event` as the project's DO records a push: under the event's own id. */20 const reportOf = (21 event: OnPushEvent,22 pusher: PushReport["pusher"]23 ): PushReport => {8 unmodified lines32 repo: event.source.repoName,33 };34 };35 48-/**49- * `event` recorded by its project's DO, under the event's id, so the DO acts50- * on it once: a claim fork's push as its claimant's, which keeps the claim51- * alive; canonical `main`'s from nobody the platform knows, which opens the52- * `StrayPush` decision.53- */36 const recordOf = (event: OnPushEvent) =>37 Effect.gen(function* () {38 const found = yield* projectFor(event);39 11 unmodified lines51 52 return refusals.map(({ _tag }) => _tag);53 });54 73-/** `main` moved to a commit no landing made, as far as the DO knew when it was asked. */55 class LooksStray extends Data.TaggedError("LooksStray") {}56 76-/**77- * How long a `main` that looks stray is asked about again before it is78- * called stray. The platform pushes `main` before its DO records the79- * landing, and the event can arrive in between: a80- * stray verdict on the platform's own landing would ask the deciders to81- * revert it. Four more reads, 15 s to 2 min apart: about four minutes.82- */57+// The platform pushes `main` before its DO records the landing, and the event can58+// arrive in between: a stray verdict on the platform's own landing would ask the59+// deciders to revert it.60 const strayGrace: StepRetry = {61 backoff: "exponential",62 delayMs: 15_000,63 limit: 4,64 };65 89-/** What `event` means, from what the DO says of it now. */66 const verdictOf = (event: OnPushEvent) =>67 Effect.map(factsOf(event), (facts) => classifyPush(event, facts));68 93-/**94- * What `event` means; a `main` moved to a commit that may yet be recorded95- * as a landing fails, so the step asks again. A deleted `main` is no96- * landing in flight: it is stray at once.97- */69 const classified = (event: OnPushEvent) =>70 Effect.flatMap(verdictOf(event), (verdict) =>71 PushVerdict.guards.Stray(verdict) && !isZero(verdict.after)72 ? Effect.fail(new LooksStray())73 : Effect.succeed(verdict)74 );75 105-/**106- * What `event` means, then what is recorded of it, each a step run once per107- * instance (principle 8). `classify` asks again during `strayGrace` while108- * `main` looks stray. A `main` still stray after it is the step's last109- * failure, which the engine keeps and throws again, unrun, in every replay110- * (where the step's own failure is gone, so it arrives as a defect);111- * either way `settle` asks once more and records the verdict as a value,112- * which every replay reads back. `record` tells the DO of a push it must113- * hear of.114- */76+// A `main` still stray after `strayGrace` is the step's last failure, which the77+// engine throws again, unrun, in every replay (as a defect); `settle` records the78+// verdict as a value, which every replay reads back.79 export const runOnPush = (80 event: OnPushEvent81 ): Effect.Effect<PushVerdict, never, StepRunner | Projects> =>82 Effect.gen(function* () {14 unmodified lines97 98 return verdict;99 });100 137-/**138- * One instance's run: its params decoded before anything else (principle139- * 2), then the env, then the program over the stage's ports and the140- * engine's own steps. It answers the verdict as JSON, the instance's output.141- */101 export const runInstance = (102 env: Env,103 params: typeof OnPushEvent.Encoded,104 steps: WorkflowSteps23 unmodified linesmodified:apps/platform/src/workflows/step.ts+2 added-40 removed
1-/**2- * The seam between Effect programs and a Workflow's durable steps, shared by3- * the Answer and OnPush Workflows. A program names each step4- * and gives the schema of its value; over a Workflow, the engine records the5- * value encoded as JSON and a replay decodes the record instead of running6- * the step again (principle 8).7- */1 import { Context, Effect, Layer, Option, Ref, Schema } from "effect";2 10-/** How the engine retries a step that failed: as `WorkflowStepConfig` spells it. */3 export interface WorkflowStepRetries {4 readonly limit: number;5 readonly delay: number;6 readonly backoff: "constant" | "linear" | "exponential";7 }8 17-/**18- * The part of a Workflow's `WorkflowStep` this seam uses: `do`, with a19- * config, recording what its body returns. A `WorkflowStep` is one.20- */9 export interface WorkflowSteps {10 readonly do: (11 name: string,12 config: { readonly retries?: WorkflowStepRetries },13 body: () => Promise<Schema.Json>14 ) => Promise<Schema.Json>;15 }16 29-/** How often, and how far apart, a failed step runs again before the run fails. */17 export interface StepRetry {18 readonly limit: number;19 readonly delayMs: number;20 readonly backoff: "constant" | "linear" | "exponential";1 unmodified line22 23 export class StepRunner extends Context.Service<24 StepRunner,25 {39- /**40- * Runs `effect` once per (instance, name); a replay returns the recorded41- * value, decoded with `schema`. A failure is retried per `retry` (the42- * engine's default without one), records no value, and, once the43- * retries are spent, fails the step with the last failure. A replay of44- * a spent step dies: the engine keeps only an error, not the typed45- * failure, so a program that must survive one records its outcome as a46- * value in a step of its own (OnPush's `settle`).47- */26+ // A replay of a spent step dies: the engine keeps only an error, not the typed27+ // failure, so a program that must survive one records its outcome as a value.28 readonly step: <A, I, E, R>(29 name: string,30 schema: Schema.Codec<A, I>,31 effect: Effect.Effect<A, E, R>,1 unmodified line33 ) => Effect.Effect<A, E, R>;34 }35 >()("platform/StepRunner") {}36 57-/** The engine's spelling of a step's retries. */37 const configOf = (retry: StepRetry | undefined) =>38 retry === undefined39 ? {}40 : {3 unmodified lines44 limit: retry.limit,45 },46 };47 69-/** One step over a Workflow's own steps. */48 const durableStep =49 (steps: WorkflowSteps) =>50 <A, I, E, R>(51 name: string,17 unmodified lines69 steps.do(name, configOf(retry), () =>70 Effect.runPromiseWith(context)(run)71 )72 ).pipe(95- // The engine gave up: the step's own last failure, if it had one.73 Effect.catch((error) =>74 Effect.flatMap(Ref.get(failed), (last) =>75 Option.match(last, {76 onNone: () => Effect.die(error),5 unmodified lines82 83 return yield* Effect.orDie(Schema.decodeEffect(json)(recorded));84 });85 109-/**110- * Steps over a Workflow's own: the value goes out encoded as JSON, and comes111- * back decoded, whether the step ran now or is a replay.112- */86 export const workflowSteps = (steps: WorkflowSteps): Layer.Layer<StepRunner> =>87 Layer.succeed(StepRunner, StepRunner.of({ step: durableStep(steps) }));88 116-/** What the in-memory steps keep per name: a step's value, or its last failure. */89 interface MemoRecords {90 readonly values: Ref.Ref<ReadonlyMap<string, Schema.Json>>;91 readonly failures: Ref.Ref<ReadonlyMap<string, unknown>>;92 }93 122-/** One step over an in-memory record of steps, keyed by name. */94 const memoStep =95 ({ failures, values }: MemoRecords) =>96 <A, I, E, R>(97 name: string,31 unmodified lines129 130 return yield* Effect.orDie(Schema.decodeEffect(json)(encoded));131 });132 162-/**163- * Steps in memory, for tests, replaying as the engine does: the layer keeps164- * one record per step name for as long as the returned layer lives, so165- * running a program twice over it replays the second time. A failed step is166- * retried up to its limit, without waiting; once its retries are spent it167- * fails with its last failure, and a replay dies without running it, as a168- * replay over `workflowSteps` does when the engine throws the failure it169- * kept.170- */133 export const memoSteps = (): Effect.Effect<Layer.Layer<StepRunner>> =>134 Effect.map(135 Effect.all({136 failures: Ref.make<ReadonlyMap<string, unknown>>(new Map()),5 unmodified linesmodified:apps/platform/src/answer-runs.ts+2 added-37 removed
1-/**2- * What starts the `Answer` Workflow. For one answer request: the port that3- * starts it is the project service's `AnswerRuns`4- * (`@repo/project/answer-runs`); the Project Durable Object implements it with5- * its project bound, and the Workflow decodes these params. The instance id is6- * the request id, so a second start of one request changes nothing.7- *8- * For the admission of a layer push's sealed checks:9- * admission runs as steps of the same Workflow under its own tagged10- * params, so typed visibility adds no Workflow binding. Its instance id is11- * `admissionId`, so a push admitted twice runs once.12- *13- * For one round of a proposal's draft: the run (`@repo/drafting/run`) is14- * steps of the same Workflow under params tagged `Draft`, so drafting adds15- * no Workflow binding (ADR 0018). Its instance id is `draftId`, one per16- * project, proposal and round, so a round started twice runs once.17- */1 import { DraftParams as DraftRun } from "@repo/project/draft-runs";2 import {3 CommitSha,4 keyOf,9 unmodified lines14 });15 16 export type AnswerParams = typeof AnswerParams.Type;17 35-/** An admission of the head pushed to one of a project's layers. */18 export const AdmissionParams = Schema.TaggedStruct("Admission", {19 head: CommitSha,20 layer: LayerName,21 project: ProjectName,22 });23 24 export type AdmissionParams = typeof AdmissionParams.Type;25 44-/**45- * One round of a proposal's draft: its project, proposal and round, and the46- * note the round was asked with, which travels with the run.47- */26 export const DraftParams = Schema.TaggedStruct("Draft", DraftRun.fields);27 28 export type DraftParams = typeof DraftParams.Type;29 52-/** Every run the `Answer` Workflow takes: an admission's, a draft's, or an answer's. */30 export const WorkflowParams = Schema.Union([31 AdmissionParams,32 DraftParams,33 AnswerParams,34 ]);35 36 export type WorkflowParams = typeof WorkflowParams.Type;37 61-/** How long a Workflow instance id may be. */38 const ID_LENGTH = 100;39 64-/** A modulus for `tagOf`: the Mersenne prime 2^31 - 1, so every step stays a safe integer. */40+// 2^31 - 1, so every step stays a safe integer.41 const TAG_MODULUS = 2_147_483_647;42 67-/** A polynomial hash of `text`'s code points, in base 36: a short, stable tag for a name cut short. */43 const tagOf = (text: string) => {44 let hash = 0;45 46 for (const unit of text) {2 unmodified lines49 50 return hash.toString(36);51 };52 78-/**79- * An instance id of `named` then `suffix`, within the engine's length. The80- * suffix is kept whole; a name too long is cut and tagged with a hash of the81- * whole name, so two runs with different suffixes or names never share an82- * instance (one that exists is never started again).83- */53+// A name too long is cut and tagged with a hash of the whole name, so no two runs share an instance.54 const instanceId = (named: string, suffix: string) => {55 const whole = `${named}${suffix}`;56 57 if (whole.length <= ID_LENGTH) {4 unmodified lines62 63 return `${named.slice(0, ID_LENGTH - tag.length - suffix.length)}${tag}${suffix}`;64 };65 96-/** The instance an admission runs as: one per project, layer and pushed head. */66 export const admissionId = (params: AdmissionParams) =>67 instanceId(68 `admit-${keyOf(params.project)}-${params.layer}`,69 `-${params.head}`70 );71 103-/**104- * The instance a draft's round runs as: one per project, proposal and105- * round, the proposal and round kept whole.106- */72 export const draftId = (73 params: Pick<DraftParams, "project" | "proposal" | "round">74 ) =>75 instanceId(3 unmodified linesmodified:apps/platform/src/cartridges.ts+2 added-14 removed
1-/**2- * The cartridges the platform plugs in over its own ports (`ports.ts`):3- * one marked line each, re-exporting the cartridge's layer for a stage's4- * config. Deleting a cartridge's line unplugs it, and the ports it filled5- * answer their defaults again. A static re-export, not an `import()`: a6- * dynamic import would make the bundler wrap every module it reaches in a7- * lazy initializer.8- */1+// A static re-export, not an `import()`: a dynamic import would make the bundler wrap every module it reaches in a lazy initializer.2 import type { Layer } from "effect";3 4 import type { PlatformConfig } from "./platform.ts";5 import type { WorkerPorts } from "./ports.ts";6 14-/**15- * A cartridge: its layer for one stage's config, over the platform's own16- * ports. What it provides are ports with defaults, so its layer adds no17- * service a host must name. It lives here so this module keeps a line of18- * its own when its last cartridge is deleted.19- */7+// Lives here so this module keeps a line of its own when its last cartridge is deleted.8 export type Cartridge = (9 config: PlatformConfig10 ) => Layer.Layer<never, never, WorkerPorts>;11 2 unmodified linesmodified:apps/platform/src/credential.ts-15 removed
5 unmodified lines6 const BASIC = /^Basic (?<encoded>\S+)$/u;7 8 const fromBase64 = Schema.decodeOption(Schema.StringFromBase64);9 10-/** The `<user>:<password>` pair of `Authorization: Basic base64(<user>:<password>)`. */10 const basicPairOf = (headers: Headers): Option.Option<string> =>11 Option.fromNullishOr(12 BASIC.exec(headers.get("authorization") ?? "")?.groups?.encoded13 ).pipe(Option.flatMap(fromBase64));14 16-/** The password of `<user>:<password>`; the first colon ends the user name. */15 const passwordOf = (pair: string) => {16 const colon = pair.indexOf(":");17 18 return colon === -1 || colon === pair.length - 119 ? Option.none()20 : Option.some(pair.slice(colon + 1));21 };22 25-/** The user name of `<user>:<password>`: all before the first colon. */23 const userOf = (pair: string) => pair.slice(0, Math.max(pair.indexOf(":"), 0));24 28-/**29- * The platform token a request carries, if it carries one: from30- * `Authorization: Bearer <token>` (the CLI, MCP clients), or as the password31- * of `Authorization: Basic base64(<user>:<token>)`, which is how git sends32- * the token it got from the credential helper. The user name is ignored.33- */25 export const credentialOf = (headers: Headers): Option.Option<string> =>26 Option.orElse(bearerToken(headers.get("authorization") ?? undefined), () =>27 Option.flatMap(basicPairOf(headers), passwordOf)28 );29 39-/**40- * The harness a push came through, as its credential helper's basic-auth41- * user name says (`audit;harness=pi&model=kimi-k3`, `@repo/protocol/audit`);42- * none for any other user name, or a bearer token. Audit metadata, never43- * identity: who pushes is the token's person (`credentialOf`).44- */30 export const auditOf = (headers: Headers): Option.Option<HarnessAudit> =>31 Option.flatMap(basicPairOf(headers), (pair) => parseAuditUser(userOf(pair)));modified:apps/platform/src/git.ts+5 added-56 removed
1-/**2- * git's smart HTTP on the platform: clones and pushes of every project's3- * repos, reached at `/<repo>(.git)/(info/refs|git-upload-pack|git-receive-pack)`.4- * `surfaces.ts` hands every such path here, outside the 401 gate, before the5- * RPC and MCP routes.6- *7- * Who may do what (ADR 0004): anyone clones a project's canonical8- * repo; a fork is read by a signed-in person; a push needs one, and custody9- * (`adapters/custody.ts`) decides what it may move. A credential the10- * platform does not know is a 401 everywhere. A name the platform never11- * makes is a 404, unless `LayerGate` says it is a layer's repo,12- * which only the layer's readers read and its writers push to. The13- * client's credential never travels past this file: the gateway forwards14- * only the headers git's protocol needs, and the upstream adds the15- * platform's own.16- */1 import { Brand } from "@repo/brand";2 import { Custody } from "@repo/git/custody";3 import { gateway, gitRoute, plain } from "@repo/git/gateway";4 import type { GitRoute } from "@repo/git/gateway";17 unmodified lines22 import type { LayerReach } from "./layer-gate.ts";23 import { repoKind, RepoKind } from "./repo-names.ts";24 import { Sessions } from "./sessions.ts";25 42-/** What serving git needs: who is calling, their projects, and the git server behind. */26 export type GitServices = Sessions | Projects | Upstream;27 45-/** A push reads `info/refs` for receive-pack, then posts to it; everything else reads. */28 const writes = (endpoint: string, url: URL) =>29 endpoint === "git-receive-pack" ||30 (endpoint === "info/refs" &&31 url.searchParams.get("service") === "git-receive-pack");32 33 const RESULT = "application/x-git-receive-pack-result";34 53-/**54- * git asks its credential helper for a password only after a 401 that names55- * Basic; the helper answers with the person's platform token.56- */35+// git asks its credential helper for a password only after a 401 that names Basic.36 const signIn = (reason: string) =>37 plain(401, `${reason}; sign in with ${Brand.cli} login`, {38 "www-authenticate": `Basic realm="${Brand.name}"`,39 });40 41 const notFound = (name: string) => plain(404, `no repo ${name}`);42 64-/** Who the request's credential names; `None` when it names no one the platform knows. */43 const principalOf = (headers: Headers) =>44 Option.match(credentialOf(headers), {45 onNone: () => Effect.succeedSome<Principal>(Anonymous.make({})),46 onSome: (token) =>1 unmodified line48 Effect.map(Option.map((person): Principal => person))49 ),50 });51 74-/** Whether `principal` may read the repo `kind` names: a canonical repo, anyone; a fork, a signed-in person. */52 const mayRead = (principal: Principal, kind: RepoKind) =>53 RepoKind.$is("Canonical")(kind) || Principal.guards.Person(principal);54 78-/**79- * The reply to a push with `notices` first, as `remote:` lines: only when80- * the reply speaks side-band, whose first packet names its band.81- */55 const withNotices = (response: Response, notices: readonly string[]) =>56 Effect.gen(function* () {57 if (58 notices.length === 0 ||6 unmodified lines65 const read = yield* Effect.option(66 Effect.tryPromise(() => response.arrayBuffer())67 );68 96- // The gateway's own words when a push's report does not arrive whole.69 if (Option.isNone(read)) {70 return plain(502, "the push's report was cut off");71 }72 21 unmodified lines94 status: response.status,95 });96 });97 126-/** How far each access reaches: a writer also reads. */98 const REACH = {99 none: 0,100 read: 1,101 write: 2,102 } as const satisfies Record<LayerAccess, number>;103 133-/** A request body as git wrote it, inflated if git gzipped it; none if it can't be. */104 const inflated = (bytes: Uint8Array, encoding: string | null) => {105 if (encoding === null) {106 return Effect.succeedSome(bytes);107 }9 unmodified lines117 )118 : Effect.succeedNone;119 };120 151-/**152- * An upload-pack request, read whole for the read log and sent on153- * unchanged: its body is a fetch's wants and haves, never a pack. A body154- * in an encoding git never sends still counts as a read, with no commit155- * named, so the log errs toward a read. None when the body itself can't be156- * read.157- */121+// Read whole for the read log and sent on unchanged. A body in an encoding git never122+// sends still counts as a read, so the log errs toward a read.123 const uploadOf = (request: Request) =>124 Effect.gen(function* () {125 const read = yield* Effect.option(126 Effect.tryPromise(() => request.arrayBuffer())22 unmodified lines149 upload,150 });151 });152 188-/**189- * A git request to a project's layer repo (ADR 0007): only the190- * layer's readers clone it and only its writers push to it, all through the191- * private namespace's upstream. Someone not signed in is asked to sign in192- * (401, so the credential helper answers); a person the layer does not193- * admit gets 403 with one line git prints.194- *195- * Every read is logged with who and which commit: each196- * upload-pack request answered 200, but a v2 `ls-refs`, which lists refs197- * and reads nothing, so a clone is one read. A fetch that negotiates over198- * several requests logs each.199- */153+// Every upload-pack request answered 200 is logged as a read, except a v2 `ls-refs`,154+// which reads nothing, so a clone is one read.155 const serveLayer = (156 request: Request,157 route: { readonly endpoint: string; readonly name: string },158 principal: Principal,24 unmodified lines183 Effect.provideService(Custody, custody),184 Effect.provideService(Upstream, gate.upstream)185 );186 232- // Only a fetch's request reads content; the rest pass straight through.187 if (route.endpoint !== "git-upload-pack" || request.method !== "POST") {188 return yield* served(request);189 }190 12 unmodified lines203 204 return response;205 });206 253-/** A git request to `name`, as `principal` may make it. */207 const serve = (request: Request, route: GitRoute, principal: Principal) =>208 Effect.gen(function* () {256- // An address no project can have names no repo.209 if (Option.isNone(route.repo)) {210 return notFound(route.name);211 }212 213 const repo = route.repo.value;214 const kind = repoKind(repo);215 264- // A name the platform makes for no repo of its own may be a layer's.216 if (RepoKind.$is("Unknown")(kind)) {217 const layer = yield* LayerGate.use((gate) =>218 gate.classify(repo, principal)219 );15 unmodified lines235 }236 237 const notices = yield* Ref.make<readonly string[]>([]);238 288- // Only a push's own request is judged; reads never reach custody.239 const custody =240 route.endpoint === "git-receive-pack"241 ? yield* custodyFor(242 principal,9 unmodified lines252 253 return yield* withNotices(response, yield* Ref.get(notices));254 });255 306-/** The response to a git request, if `request` is one the gateway serves. */256 export const serveGit = (257 request: Request258 ): Option.Option<Effect.Effect<Response, never, GitServices>> =>259 Option.map(gitRoute(new URL(request.url).pathname), (route) =>7 unmodified linesmodified:apps/platform/src/handlers.ts+4 added-66 removed
1-/**2- * The contracts' handlers: routing, the rate limit and the fan-out, nothing3- * more. A contract that names a project calls4- * that project's `ProjectApi` (its Durable Object, through `Projects`) as5- * the caller `Authenticated` named; the cross-project reads (`listProjects`,6- * `frontPage`, `credits`) come from the front-page projection, each listed7- * project's posture read from its own ledger (`withStandingPosture`);8- * `status` and `today` without a project ask every project the projection9- * lists and merge what each says. `claim`, `proposeAsk` and `flagAsk` spend the10- * caller's rate limit first, so a call past it reaches no project; a11- * proposal with a draft, and `draftAsk`, spend the draft limit too.12- * `evidence` asks the project who may read a lane's log, which it reads13- * from the stage's `EvidenceStore`. The code reads (`listRefs`, `readTree`,14- * `listPaths`, `readFile`, `log`, `showCommit`, `why`) run here, over the15- * Worker's `RepoHost` and the project's canonical repo (`@repo/project/code`),16- * asking the project only for main's landed commit, its landings and forks. `watch` is served by `watch.ts`: live17- * for a caller on the framed `/rpc`, replayed and ended over JSON.18- *19- * Every `remote` a caller gets back is the platform's git URL for the repo,20- * at the origin the caller reached the platform by: never a storage URL.21- */1 import { RepoHost } from "@repo/artifacts/repo-host";2 import { EvidenceStore, LogRef } from "@repo/checks/evidence-store";3 import {4 codeProjectOf,28 unmodified lines33 34 import { RateLimits } from "./rate-limits.ts";35 import { servedFramed, watchHandler } from "./watch.ts";36 58-/** How many commits a page of `log` holds when the caller names no limit. */37 const LOG_PAGE = 30;38 61-/** How many projects a call without one asks at once. */39 const FAN_OUT = 8;40 64-/** The caller, as the `Authenticated` server side named them. */41 const caller = Effect.service(CurrentPrincipal);42 67-/**68- * The caller of a contract only a person may call. `Authenticated` lets an69- * anonymous call reach only a `public` contract, so anyone else here is a70- * defect in the server side, never a caller to serve.71- */43+// `Authenticated` lets an anonymous call reach only a `public` contract, so anyone44+// else here is a defect in the server side.45 const person = Effect.flatMap(caller, (principal) =>46 Principal.match(principal, {47 Anonymous: () =>48 Effect.die("a contract for signed-in people was called anonymously"),49 Person: (named) => Effect.succeed<Person>(named),50 })51 );52 80-/** The incoming request's origin: its URL's when whole, else from its host. */53 const originOf = (request: HttpServerRequest.HttpServerRequest) =>54 URL.canParse(request.originalUrl)55 ? Option.some(new URL(request.originalUrl).origin)56 : Option.map(HttpServerRequest.toURL(request), ({ origin }) => origin);57 86-/**87- * Where the caller reached the platform, which is where its git lives: the88- * incoming request's origin, or the platform's own URL for a call that came89- * from no request.90- */58 const gateway = Effect.gen(function* () {59 const request = yield* Effect.serviceOption(60 HttpServerRequest.HttpServerRequest61 );3 unmodified lines65 onSome: Effect.succeed,66 });67 });68 102-/**103- * A repo's git URL at the gateway the caller came through: a project by its104- * name, a fork by its project's name and its own parts (ADR 0032).105- */69 const remoteOf = (repo: RepoName | ProjectName) =>70 Effect.map(71 gateway,72 (origin) =>73 `${origin}/${repo.includes("/") ? repo : Option.getOrElse(addressOfRepo(RepoName.make(repo)), () => repo)}.git`74 );75 113-/** A claim, with its fork's URL at the caller's gateway. */76 const atGateway = (claim: ClaimView) =>77 Effect.map(remoteOf(claim.fork), (remote): ClaimView => ({78 ...claim,79 remote,80 }));81 120-/**121- * The caller's claims and answers, each claim at the caller's gateway, under122- * the caller's own handle (a first login has no claim to read it from).123- */82 const statusAtGateway = (83 who: Person,84 status: {85 readonly answers: readonly AnswerView[];5 unmodified lines91 claims,92 handle: who.handle,93 }));94 137-/** Decisions across projects: soonest to expire first, then oldest, then by project and id. */95 const byExpiry: Order.Order<Decision> = Order.combineAll([96 Order.mapInput(DateTime.Order, ({ expiresAt }: Decision) => expiresAt),97 Order.mapInput(DateTime.Order, ({ openedAt }: Decision) => openedAt),98 Order.mapInput(Order.String, ({ project }: Decision) => project),99 Order.mapInput(Order.String, ({ id }: Decision) => id),100 ]);101 145-/**146- * One decider's Today across the projects they decide in: each project's147- * budget added up, its decisions in one order of expiry, and the rest148- * side by side. A person who decides in none has no Today.149- */102 const acrossProjects = (103 decider: Person,104 pages: readonly Today[]105 ): Effect.Effect<Today, NotDecider> => {22 unmodified lines128 })129 : Effect.fail(new NotDecider({}));130 };131 180-/**181- * Every contract, served by the project it names or by the projection. A182- * missing contract is a type error here (`Contracts.toLayer`).183- */132 export const Handlers: Layer.Layer<133 Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>,134 never,135 Projects | FrontPage | RateLimits | EvidenceStore | RepoHost4 unmodified lines140 const rateLimits = yield* RateLimits;141 const evidence = yield* EvidenceStore;142 const host = yield* RepoHost;143 196- /** `call` on the project named `project`; one never made is `UnknownProject`. */144 const on = <A, E>(145 project: ProjectName,146 call: (api: ProjectApi) => Effect.Effect<A, E>147 ) => Effect.flatMap(projects.get(project), call);148 202- /** A code read of `project`'s canonical repo, over the Worker's `RepoHost`. */149 const code = <A, E>(150 project: ProjectName,151 read: (of: CodeProject) => Effect.Effect<A, E, RepoHost>152 ) =>2 unmodified lines155 Effect.provideService(RepoHost, host)156 )157 );158 213- /**214- * `call` on every project the projection lists, in name order. A215- * project the platform never made adds nothing, and so does one where216- * `call` finds nothing for the caller; any other failure is the call's.217- */159 const everywhere = <A, E>(160 call: (api: ProjectApi) => Effect.Effect<Option.Option<A>, E>161 ) =>162 Effect.gen(function* () {78 unmodified lines241 initProject: ({ project, ...input }) =>242 Effect.gen(function* () {243 const who = yield* person;244 304- // A project an earlier call made but could not start is this245+ // A project an earlier call made but could not start is this call's to start;246 // call's to start; one already started refuses it itself.247 const api = yield* projects248 .create(project)249 .pipe(46 unmodified lines296 proposeAsk: ({ project, ...input }) =>297 Effect.gen(function* () {298 const who = yield* person;299 359- // A draft spends the draft limit (model calls and Checker runs)360- // first, then the proposal limit, as any proposal does.300+ // A draft spends the draft limit first, then the proposal limit.301 if (input.draft === true) {302 yield* rateLimits.check("draft", who.handle);303 }304 56 unmodified lines361 if (project !== undefined) {362 return yield* on(project, (api) => api.today(who));363 }364 425- // A project the caller decides nothing in has no page for them.365 const pages = yield* everywhere((api) =>366 api.today(who).pipe(367 Effect.map(Option.some),368 Effect.catchTag("NotDecider", () => Effect.succeedNone)9 unmodified lines378 vouch: ({ project, ...input }) =>379 Effect.flatMap(person, (who) =>380 on(project, (api) => api.vouch(who, input))381 ),443- // Live over a framed `/rpc`; replayed and ended over a buffered one.382 watch: (payload) =>383 Stream.unwrap(384 Effect.map(servedFramed, (live) => watchHandler(payload, { live }))385 ).pipe(Stream.provideService(Projects, projects)),5 unmodified linesmodified:apps/platform/src/home.ts-29 removed
1-/**2- * The platform's `/`: a page saying what this host serves (clone URLs,3- * MCP, agent skills, RPC, sign-in, the CLI and its releases, drafting, the4- * web app), in HTML for a browser and in Markdown for an agent that asks5- * for `text/markdown` or `text/plain`. The Markdown is the web's6- * `/llms.txt` (`@repo/agent-kit/host-doc`), so both hosts say the same.7- *8- * Every URL is built from the request's origin, the one the client reached:9- * the platform is also the git remote, the MCP base and the CLI's URL, so10- * the page names them as the reader will type them. The projects are the11- * front page's, and nothing else: no layer and no fork is listed; each12- * one's posture is the one its own ledger stands at, as `listProjects`13- * answers it (`withStandingPosture`), so `/` and the web's `/llms.txt`14- * stay one text. Every value that reaches the HTML is escaped. Not a15- * redirect: the web app is a link, so the host stays discoverable at its16- * own address.17- */1 import { commandDocs } from "@repo/agent-kit/command-doc";2 import { frontLlms, MCP_PROTOCOL } from "@repo/agent-kit/host-doc";3 import { Brand } from "@repo/brand";4 import { FrontPage } from "@repo/project/front-page";5 unmodified lines10 11 import { escapeHtml, page } from "./auth/pages.ts";12 import { HostInfo } from "./host-info.ts";13 31-/** A minute: the page changes only when a project is made. */14 const BRIEFLY = "public, max-age=60";15 34-/** The CLI's commands, as the platform's skill and the web's `llms.txt` list them. */16 const commands = commandDocs(Contracts);17 37-/** The media ranges of an `Accept` header, each its type and its quality. */18 const rangesOf = (accept: string) =>19 accept.split(",").map((range) => {20 const [type = "", ...params] = range.split(";").map((part) => part.trim());21 9 unmodified lines31 32 return { quality, type: type.toLowerCase() };33 });34 55-/** The highest quality `ranges` give any of `types` by name; 0 for none. */35 const qualityOf = (36 ranges: ReturnType<typeof rangesOf>,37 types: readonly string[]38 ) =>1 unmodified line40 0,41 ...ranges.filter(({ type }) => types.includes(type)).map((r) => r.quality)42 );43 65-/**66- * Whether the request asks for Markdown: it names `text/markdown` or67- * `text/plain` itself, at least as high as it names `text/html`. A68- * wildcard alone (`*\/*`, or no `Accept`) gets the page, as a browser does.69- */44 const wantsMarkdown = (request: Request) => {45 const ranges = rangesOf(request.headers.get("accept") ?? "");46 const markdown = qualityOf(ranges, ["text/markdown", "text/plain"]);47 29 unmodified lines77 )78 )79 );80 107-/** The page for a browser. */81 const homeHtml = (input: {82 readonly origin: string;83 readonly projects: readonly ProjectListing[];84 readonly webUrl: Option.Option<string>;41 unmodified lines126 `<p>A member can ask the platform's agent to draft a proposed ask (Workers AI, ${code(draftModel)}); a decider accepts it, and only people are credited.</p>`127 ),128 section("Health", `<p>${link(`${origin}/health`)}</p>`),129 ].join("\n"),157- // Wider than sign-in's column, for clone and install lines.130 "document"131 );132 };133 162-/** `/` for `request`: Markdown for an agent that asks for it, else the page. */134 export const homeResponse = (135 request: Request136 ): Effect.Effect<Response, never, FrontPage | HostInfo | Projects> =>137 Effect.gen(function* () {40 unmodified linesmodified:apps/platform/src/host-info.ts-6 removed
1-/**2- * What the platform's `/` says of its host beyond the request: where the3- * web app lives (`PUBLIC_WEB_URL`, none on a stage without one) and the4- * model that drafts asks (`DRAFT_MODEL`). `platformOn` provides it from5- * the decoded env; `surfaces.ts` re-exports it with the other services.6- */1 import { Context } from "effect";2 import type { Option } from "effect";3 4 export class HostInfo extends Context.Service<6 unmodified linesmodified:apps/platform/src/layer-gate.ts-29 removed
1-/**2- * The gateway's neutral port for layer repos (ADR 0007): which repo3- * names are a project's layers, how far a person may reach into one, and4- * the private namespace's git server behind them. The default is a5- * platform without typed visibility: no name is a layer, so a layer's URL6- * is an unknown repo (404), and nothing routes to the private namespace.7- *8- * The visibility cartridge (`./visibility/layers.ts`) provides the live9- * gate: a name `<project>--<layer>` the project declares, with the caller's10- * access from the layer's readers and writers, both in one ask of the11- * project's DO, and the private namespace's upstream. The gateway (`git.ts`)12- * and custody (`adapters/custody.ts`) depend on this port only.13- */1 import { RepoNotFound } from "@repo/artifacts/repo-host";2 import type { RepoName } from "@repo/artifacts/repo-host";3 import { Upstream } from "@repo/git/upstream";4 import type { LayerAccess } from "@repo/project/visibility-port";1 unmodified line6 import type { Principal } from "@repo/protocol/principal";7 import type { Option } from "effect";8 import { Context, Effect, Layer } from "effect";9 23-/** A layer repo, by the project that declares it and the layer's name. */10 export interface LayerTarget {11 readonly layer: LayerName;12 readonly project: ProjectName;13 }14 29-/** A layer repo a request names, and how far its caller reaches into the layer. */15 export interface LayerReach {31- /** A clone needs `read`, a push `write`; someone not signed in reaches `none`. */16 readonly access: LayerAccess;17 readonly target: LayerTarget;18 }19 36-/** The gateway's view of layer repos. */20 export interface LayerGatePort {38- /**39- * The layer a repo name is, when its project declares one by that name,40- * with how far `who` reaches into it: one question to the project per41- * request. None for every other name.42- */21 readonly classify: (22 repo: RepoName,23 who: Principal24 ) => Effect.Effect<Option.Option<LayerReach>>;47- /** The git server behind the layer repos: the private namespace, with the platform's own credentials. */25 readonly upstream: Upstream["Service"];26 }27 51-/** A platform without layers: no repo name is one, and no layer repo exists. */28 export const noLayers: LayerGatePort = {29 classify: () => Effect.succeedNone,30 upstream: Upstream.of({31 exchange: (repo) => Effect.fail(new RepoNotFound({ name: repo })),32 }),33 };34 59-/**60- * How a host gives the gateway layer repos. The default is `noLayers`, so a61- * platform composed without the visibility cartridge serves none.62- */35 export const LayerGate = Context.Reference<LayerGatePort>(36 "platform/LayerGate",37 {38 defaultValue: () => noLayers,39 }40 );41 70-/** The default, said out loud: no layer repos. */42 export const NoLayers: Layer.Layer<never> = Layer.succeed(LayerGate, noLayers);modified:apps/platform/src/platform.ts+8 added-96 removed
22 unmodified lines23 import { sessionTable } from "./sessions/table.ts";24 import { HostInfo, Stage } from "./surfaces.ts";25 import type { Services } from "./surfaces.ts";26 27-/**28- * A binding the runtime hands the Worker: present, and an object. The29- * runtime vouches for the rest of it; the Worker never inspects one further.30- */27 const binding = <T>(kind: string) =>28 Schema.declare((input: unknown): input is T => Predicate.isObject(input), {29 expected: kind,30 });31 36-/** A bearer token: long enough that guessing one is hopeless. */32 const Token = Schema.String.check(Schema.isMinLength(32));33 39-/** A 256-bit key, written as 64 hex characters. */34 const HexKey = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/iu));35 42-/**43- * Named sessions: token → handle. A record with a refined key would drop a44- * short token silently, so the whole table is checked instead.45- */36+// A record with a refined key would drop a short token silently, so the whole37+// table is checked instead.38 const SessionTable = Schema.Record(Schema.String, Handle).check(39 Schema.makeFilter((table) =>40 Object.keys(table).every((token) => token.length >= 32)41 ? true42 : "every token is at least 32 characters"43 )44 );45 54-/** A stage's name: `local`, never deployed; `dev-<user>`; `demo`. */46 export const StageName = Schema.String.check(47 Schema.isPattern(/^(?:local|demo|dev-[a-z0-9]+(?:-[a-z0-9]+)*)$/u)48 );49 59-/** Which Lander lands answers: the sandbox's container, or isomorphic-git here. */50 export const LanderAdapter = Schema.Literals(["container", "isogit"]);51 62-/**63- * The bindings `wrangler.jsonc` declares, at the top level and in every64- * stage block (`test/bindings.test.ts` holds the two sets equal). Each is65- * typed by the generated `Env`, so a binding removed from `wrangler.jsonc`66- * fails `typecheck` here and wherever it is used.67- */52 export const PlatformBindings = Schema.Struct({69- /** Workers AI, which drafts asks (`DRAFT_MODEL` names the model). */53 AI: binding<Env["AI"]>("Workers AI"),54 ANSWER: binding<Env["ANSWER"]>("the Answer Workflow"),55 ARTIFACTS: binding<Env["ARTIFACTS"]>("an Artifacts namespace"),73- /**74- * The private namespace that holds every project's layer repos. Only75- * this Worker binds it: the Workers that serve public pages76- * bind no namespace at all (principle 7).77- */56 ARTIFACTS_PRIVATE: binding<Env["ARTIFACTS_PRIVATE"]>(57 "the private Artifacts namespace"58 ),59 CLAIM_LIMIT: binding<Env["CLAIM_LIMIT"]>("a rate limit"),82- /**83- * Code history (why, a path's log), kept by immutable ids so every84- * isolate reads what one computed. Only this Worker binds it: the web85- * reads code through the platform.86- */60 CODE_CACHE: binding<Env["CODE_CACHE"]>("an R2 bucket"),61 DRAFT_LIMIT: binding<Env["DRAFT_LIMIT"]>("a rate limit"),62 EVIDENCE: binding<Env["EVIDENCE"]>("an R2 bucket"),63 FRONT_PAGE: binding<Env["FRONT_PAGE"]>("a D1 database"),1 unmodified line65 OAUTH_KV: binding<Env["OAUTH_KV"]>("a KV namespace"),66 ON_PUSH: binding<Env["ON_PUSH"]>("the OnPush Workflow"),67 PROJECT: binding<Env["PROJECT"]>("the Project Durable Object"),68 PROPOSAL_LIMIT: binding<Env["PROPOSAL_LIMIT"]>("a rate limit"),96- /** The CLI's releases, served at `/install.sh` and `/releases/*`. */69 RELEASES: binding<Env["RELEASES"]>("an R2 bucket"),98- /**99- * A service binding to the sandbox Worker's default entrypoint. The100- * generated `Env` types it as a plain `Fetcher`, since this app's types101- * may not name another app's entrypoint, so its methods are declared here102- * by their wire (`SandboxBinding`, the shape a type test holds the103- * entrypoint to).104- */70+ // The generated `Env` types this as a plain `Fetcher` (an app's types may not name71+ // another app's entrypoint), so its methods are declared here by their wire.72 SANDBOX: binding<Env["SANDBOX"] & SandboxBinding>("the sandbox Worker"),73 SIGN_IN_LIMIT: binding<Env["SIGN_IN_LIMIT"]>("a rate limit"),74 });75 109-/** The vars `wrangler.jsonc` sets in every block. */76 export const PlatformVars = Schema.Struct({111- /** The Workers AI model that drafts asks: `@cf/moonshotai/kimi-k2.7-code`. */77 DRAFT_MODEL: Schema.NonEmptyString,78 LANDER_ADAPTER: LanderAdapter.pipe(79 Schema.withDecodingDefaultKey(Effect.succeed("container"))80 ),81 OPERATOR_HANDLE: Handle,117- /** The web app's own URL, which `/` links to; a stage without one links nowhere. */82 PUBLIC_WEB_URL: Schema.optionalKey(83 Schema.String.check(Schema.isPattern(/^https?:\/\//u))84 ),85 STAGE: StageName,86 });87 124-/**125- * The secrets `.env.schema` declares, each redacted but Google's client id.126- * Every one but `SESSION_TOKENS` and Google's pair is required127- * (`wrangler.jsonc`'s `secrets.required`): sign-in's cookie key and pepper128- * too, since accounts are the platform's own, and the master key.129- */88 export const PlatformSecrets = Schema.Struct({131- /** Seals a sign-in in progress into its form (`auth/state.ts`). */89 COOKIE_KEY: Schema.RedactedFromValue(Token),133- /**134- * Google sign-in's OAuth client (human step H4), set with135- * `GOOGLE_CLIENT_SECRET` or not at all. Not secret: Google shows it to136- * everyone who signs in.137- */90+ // Not secret: Google shows it to everyone who signs in.91 GOOGLE_CLIENT_ID: Schema.optionalKey(Schema.NonEmptyString),139- /** The secret of Google sign-in's OAuth client, set with its id. */92 GOOGLE_CLIENT_SECRET: Schema.optionalKey(93 Schema.RedactedFromValue(Schema.NonEmptyString)94 ),143- /**144- * Wraps the data key of every write-only env value. Losing it145- * loses every value stored under it.146- */95+ // Wraps the data key of every write-only env value: losing it loses every value.96 MASTER_KEY: Schema.RedactedFromValue(HexKey),97 OPERATOR_TOKEN: Schema.RedactedFromValue(Token),149- /** HMAC'd with every password before PBKDF2 (`auth/password.ts`). */98 PASSWORD_PEPPER: Schema.RedactedFromValue(Token),151- /** Named sessions beside accounts: JSON, token → handle. */99 SESSION_TOKENS: Schema.optionalKey(100 Schema.RedactedFromValue(Schema.fromJsonString(SessionTable))101 ),102 });103 157-/**158- * Google's client id and secret come as a pair: one without the other159- * names the missing key, so Google sign-in is either whole or off.160- */104 const googlePair = Schema.makeFilter(105 (env: {106 readonly GOOGLE_CLIENT_ID?: string;107 readonly GOOGLE_CLIENT_SECRET?: Redacted.Redacted;12 unmodified lines120 };121 }122 );123 181-/**182- * Everything the platform reads from the Worker's env, decoded once183- * (principle 2): its bindings, its vars and its secrets.184- */124 export const PlatformEnv = Schema.Struct({125 ...PlatformBindings.fields,126 ...PlatformVars.fields,127 ...PlatformSecrets.fields,128 }).check(googlePair);129 130 export type PlatformConfig = typeof PlatformEnv.Type;131 193-/**194- * The Worker's env cannot run the platform. It names the keys only: a value195- * that failed to decode may be a secret.132+// Names the keys only: a value that failed to decode may be a secret.196- */133 export class InvalidEnv extends Schema.TaggedError<InvalidEnv>()("InvalidEnv", {134 keys: Schema.Array(Schema.String),135 }) {}136 201-/**202- * The top-level key of every issue, once each: a deeper path (a session203- * table's token) may itself be secret.204- */137+// Top-level keys only: a deeper path (a session table's token) may itself be secret.138 const failingKeys = (issue: SchemaIssue.Issue) =>139 Array.sort(140 Array.dedupe(141 SchemaIssue.makeFormatterStandardSchemaV1()(issue).issues.flatMap(2 unmodified lines144 ),145 Order.String146 );147 215-/** The Worker's env, decoded once: every key that fails is named together. */148 export const decodeEnv = (env: Env) =>149 Schema.decodeUnknownEffect(PlatformEnv, { errors: "all" })(env).pipe(150 Effect.mapError(({ issue }) => new InvalidEnv({ keys: failingKeys(issue) }))151 );152 221-/**222- * Who may call, as one `Sessions`: an access token the223- * platform's OAuth server issued names the person who signed in; otherwise224- * the operator's token names the operator, and each named session in225- * `SESSION_TOKENS` its handle (the operator's wins if both name one).226- */153 const sessionsOf = (config: PlatformConfig) =>154 Layer.sync(Sessions, () =>155 firstOf([156 OAuthSessions(tokenReader(config.OAUTH_KV)),10 unmodified lines167 ]),168 ])169 );170 245-/**246- * The surfaces' services over `ports`: every contract's handler, sessions,247- * the CLI's releases (over `RELEASES`), the stage and what `/` says of the248- * host (the web's URL, the drafter's model) from the decoded env,249- * and the ports beside them (git's routes take the same `Projects` and250- * `Upstream` the handlers do). The Worker runs them over251- * `workerPorts(config)`; the core-loop test runs the same composition over252- * its own adapters of the same ports.253- */171 export const platformOn = (172 config: PlatformConfig,173 ports: Layer.Layer<WorkerPorts>174 ): Layer.Layer<Services> =>10 unmodified lines185 })186 )187 ).pipe(Layer.provideMerge(ports));188 272-/**273- * The surfaces' services from the decoded env: every contract's handler,274- * sessions, the stage, and the ports they run on, each over its binding.275- */189 export const platformOf = (config: PlatformConfig): Layer.Layer<Services> =>190 platformOn(config, workerPorts(config));191 279-/** The surfaces' services from the Worker's env, decoded once. */192 export const platform = (env: Env): Layer.Layer<Services, InvalidEnv> =>193 Layer.unwrap(decodeEnv(env).pipe(Effect.map(platformOf)));modified:apps/platform/src/ports.ts+5 added-70 removed
1-/**2- * The ports the Worker, the Project Durable Object and the Workflows run3- * on, each built once from the decoded env over the binding it needs4- * (principle 6: one job-named port per beta dependency). The Worker's5- * surfaces, each Project DO (`project-do.ts`) and both Workflows6- * (`workflows/answer.ts`, `workflows/on-push.ts`) take them from here, so7- * one stage's env decides every adapter in one place.8- *9- * Building them touches no binding: each adapter reads its binding only when10- * it is called, and whatever it keeps per isolate (the upstream's token11- * cache, the Project DO stubs it found) lives in the layer, never in the12- * module. `Alarms` and `AnswerRuns` are bound per project inside its Durable13- * Object; `Sessions` is the surfaces' (`platform.ts`).14- *15- * Cartridges plug in over these ports (`plugIn`), one marked line each in16- * `cartridges.ts`. The visibility cartridge fills `LayerGate` for17- * the gateway, and `ProjectVisibility` and `ProjectEnv` for each Project18- * DO's service; without it they answer their defaults, a platform without19- * typed visibility. Every host takes its ports from here, so the one line20- * serves them all.21- */1 import { D1Client } from "@effect/sql-d1";2 import type { Fetch } from "@repo/artifacts/fetch";3 import type { RepoHost } from "@repo/artifacts/repo-host";4 import { RepoHostBinding } from "@repo/artifacts/repo-host/binding";33 unmodified lines38 import type { PlatformConfig } from "./platform.ts";39 import type { RateLimits } from "./rate-limits.ts";40 import { ProjectSockets } from "./watch.ts";41 63-/**64- * How many code reads an isolate keeps by object id, the least recently65- * used dropped first: light ones (trees, commits; a few KiB each) and66- * heavy ones (a file's text up to 256 KiB, a path list, a commit's67- * changes, a page of the log; up to about 1 MB each), so the cache stays68- * well inside the isolate's 128 MB. Each Artifacts read is billed; what an69- * object id names never changes.70- */42+// Sized to stay well inside the isolate's 128 MB; what an object id names never43+// changes, and each Artifacts read is billed.44 const CODE_READS_KEPT = { heavy: 40, light: 2000 };45 73-/** What the Worker's code runs on, besides sessions and the contracts' handlers. */46 export type WorkerPorts =47 | CheckRunner48 | EvidenceStore49 | Fetch5 unmodified lines55 | RepoHost56 | RulesEvaluator57 | Upstream;58 87-/**88- * Every cartridge `cartridges.ts` names, merged over `ports`. Deleting a89- * cartridge's line there unplugs it: the ports it filled answer their90- * defaults again.91- */59 const plugIn = (60 config: PlatformConfig,61 ports: Layer.Layer<WorkerPorts>,62 plugged: readonly Cartridge[]2 unmodified lines65 ports,66 ...plugged.map((cartridge) => cartridge(config).pipe(Layer.provide(ports)))67 );68 102-/**103- * The front page with no database behind it: empty, beside a projection104- * nobody reads. What the platform falls back to without the D1 cartridge.105- */69 const memoryFrontPage = Layer.merge(70 FrontPageMemory.layer({ credits: [], entries: [], projects: [] }),71 ProjectionMemory72 );73 111-/**112- * The ports for one stage's env, before any cartridge: Artifacts through113- * its binding, git's upstream and every repo read over it, each project's114- * Durable Object, the sandbox's Checker, the Lander `LANDER_ADAPTER` names,115- * config folders evaluated in the Worker Loader, the front116- * page in D1, the rate limits, lane logs in the `EVIDENCE` bucket, code117- * history in the `CODE_CACHE` bucket,118- * the `PROJECT` namespace again for `watch`'s relay of each project's119- * socket, and each proposal's draft rounds as runs of the `Answer`120- * Workflow.121- */74 const corePorts = (config: PlatformConfig): Layer.Layer<WorkerPorts> =>75 Layer.mergeAll(76 memoryFrontPage,125- // The D1 cartridge: the front page and its projection in126- // `FRONT_PAGE`, in place of the memory one above, and each listed127- // project's standing posture kept beside them (a `Context.Reference`:128- // without it every list reads every project). Delete this entry (and129- // its imports) and the platform falls back to the memory front page.77+ // The D1 cartridge: delete this entry and the platform falls back to the memory78+ // front page.79 Layer.mergeAll(FrontPageD1, ProjectionD1, StandingPosturesD1).pipe(80 Layer.provide(D1Client.layer({ db: config.FRONT_PAGE })),81 Layer.orDie82 ),5 unmodified lines88 RulesEvaluatorWorker(config.LOADER).pipe(89 Layer.provide(FinishersFromChecks)90 ),91 DoProjects(config.PROJECT),143- // `watch` relays each project's DO socket; without this144- // entry it follows each project's event log instead.92 Layer.succeed(ProjectSockets, Option.some(config.PROJECT)),93 WorkerRateLimits({94 claim: config.CLAIM_LIMIT,95 draft: config.DRAFT_LIMIT,96 proposal: config.PROPOSAL_LIMIT,97 }),98 EvidenceStoreR2(config.EVIDENCE),152- // The code reads' cache, one per isolate: a `Context.Reference`, so153- // without this entry every read goes to Artifacts.99 CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy),155- // The code history's store across isolates, in `CODE_CACHE`: a156- // `Context.Reference`, so without this entry history is kept only in157- // the isolate's cache above.100 CodeStoreR2(config.CODE_CACHE),159- // A `Context.Reference`: without this entry a draft proposal starts no160- // run, and stays drafting.101+ // Without this entry a draft proposal starts no run, and stays drafting.102 DraftRunsWorkflow(config.ANSWER)103 ).pipe(104 Layer.provideMerge(RepoHostBinding.layer(config.ARTIFACTS)),105 Layer.provideMerge(WorkerFetch)106 );107 167-/** The ports for one stage's env, with every cartridge the platform plugs in. */108 export const workerPorts = (config: PlatformConfig): Layer.Layer<WorkerPorts> =>109 plugIn(config, corePorts(config), Object.values(cartridges));110 171-/**172- * What a draft's run needs beside the Worker's ports: the drafter over173- * Workers AI, asking `DRAFT_MODEL`, which a settled round names. Only the174- * `Answer` Workflow's draft rounds take it.175- */111 export const draftPorts = (config: PlatformConfig): Layer.Layer<Drafter> =>112 Layer.merge(113 DrafterWorkersAi(config.AI, config.DRAFT_MODEL),114 Layer.succeed(DraftModel, config.DRAFT_MODEL)1 unmodified linemodified:apps/platform/src/project-calls.ts+5 added-56 removed
1-/**2- * The Project Durable Object's call boundary (principle 2): every `ProjectApi`3- * method, with the schemas its arguments, success and failure cross with. The4- * schemas are the project service's `MethodSchemas`, so a contract method takes5- * its own from `Contracts` and none is written twice.6- *7- * The Worker encodes a call (`encodeCall`), the DO decodes it, runs the8- * method on the project's service, and answers the method's `Exit` encoded9- * as JSON, which the Worker decodes (`decodeReply`). A typed refusal stays a10- * typed refusal on both sides; only a defect crosses as a defect.11- */1 import { envSchemaMethod } from "@repo/project/deciders";2 import { MethodSchemas } from "@repo/project/project";3 import type { ProjectApi } from "@repo/project/project";4 import { ProjectName } from "@repo/protocol/ids";1 unmodified line6 import { UnknownProject } from "@repo/protocol/refusal";7 import { Effect, Record, Schema } from "effect";8 import type { Exit } from "effect";9 21-/** A method a Project DO serves: one of `ProjectApi`'s. */10 export type ProjectMethod = keyof ProjectApi;11 24-/** A method's own arguments, in order, caller first where it has one. */12 export type ArgsOf<M extends ProjectMethod> = Parameters<ProjectApi[M]>;13 14 type SchemasOf<M extends ProjectMethod> = (typeof MethodSchemas)[M];15 29-/** What a method succeeds with, as its schema decodes it. */16 export type SuccessOf<M extends ProjectMethod> =17 SchemasOf<M>["success"]["Type"];18 33-/**34- * What a method refuses with across the boundary, as its schema decodes it.35- * A contract method's errors carry `UnknownProject`, which the DO answers36- * itself before `initProject`; the service never does.37- */19+// A contract method's errors carry `UnknownProject`, which the DO answers itself20+// before `initProject`; the service never does.21 export type ErrorOf<M extends ProjectMethod> = SchemasOf<M>["error"]["Type"];22 40-/** One method's row: how its call and its outcome cross the boundary. */23 export interface ProjectCall<M extends ProjectMethod> {42- /**43- * Whether the method's first argument is its caller. On the wire the44- * caller travels as `CallRequest.caller`, the rest as its `payload`.45- */24 readonly caller: boolean;47- /** Every argument, in order, as one JSON tuple. */25 readonly payload: Schema.Codec<Readonly<ArgsOf<M>>, Schema.Json>;26 readonly success: Schema.Codec<SuccessOf<M>, Schema.Json>;27 readonly error: Schema.Codec<ErrorOf<M>, Schema.Json>;51- /** The method's outcome as the DO answers it: success, refusal or defect. */28 readonly exit: Schema.Codec<Exit.Exit<SuccessOf<M>, ErrorOf<M>>, Schema.Json>;53- /**54- * Whether the method answers `UnknownProject` before the project is made:55- * every method whose schema can carry it. The rest (the answer queue's,56- * the gateway's, `credits`, `events`, `onAlarm`, and `initProject` itself)57- * run on the service, which answers a project not made with empty results.58- */29 readonly refusesUnmade: boolean;30 }31 32 const unmade = new UnknownProject({33 project: ProjectName.make("oscabriel/unmade"),34 });35 66-/** One method's row, from its `MethodSchemas` entry. */36 const callOf = <37 const Args extends readonly Schema.Top[],38 Success extends Schema.Top,39 Error extends Schema.Top,11 unmodified lines51 refusesUnmade: Schema.is(Schema.toType(schemas.error))(unmade),52 success: Schema.toCodecJson(schemas.success),53 });54 86-/** Every method's row, typed by the method's own name. */55 export type ProjectCallTable = {56 readonly [M in ProjectMethod]: ProjectCall<M>;57 };58 91-/**92- * The rows as one table typed by method name, so a generic `M` reads93- * `ProjectCalls[method]` as `ProjectCall<M>` (a correlated record). Each row94- * is checked against its own method here; `satisfies` would check them too,95- * but would keep the literal type, which a generic index cannot read so.96- */59+// Typed by method name so a generic `M` reads `ProjectCalls[method]` as60+// `ProjectCall<M>`; `satisfies` would keep the literal type, which a generic index61+// cannot read.62 const byMethod = (rows: ProjectCallTable) => rows;63 99-/** Every call the Worker makes on a Project DO, with the schemas that cross the boundary. */64 export const ProjectCalls = byMethod({65 admissionPlan: callOf(MethodSchemas.admissionPlan),66 advanceAnswer: callOf(MethodSchemas.advanceAnswer),67 answer: callOf(MethodSchemas.answer),44 unmodified lines112 verdict: callOf(MethodSchemas.verdict),113 vouch: callOf(MethodSchemas.vouch),114 });115 152-/** Every method's name, for the wire's literal. */116 export const projectMethods = Record.keys(ProjectCalls);117 155-/**156- * One call as it crosses into the DO: the method, the caller (decoded in the157- * DO, which trusts only what the Worker sends) and the other arguments, each158- * encoded as JSON by the method's own schemas.159- */118 export const CallRequest = Schema.Struct({119 caller: Schema.optionalKey(Principal),120 method: Schema.Literals(projectMethods),121 payload: Schema.Array(Schema.Json),122 });123 124 export type CallRequest = typeof CallRequest.Type;125 168-/** A method's `Exit` as the DO answers it: JSON, decoded by the method's `exit`. */126 export type ExitEncoded = Schema.Json;127 128 const JsonTuple = Schema.Array(Schema.Json);129 130 const EncodedPrincipal = Schema.toEncoded(Principal);131 175-/**176- * A call, encoded for the DO. Arguments its schemas refuse are the caller's177- * defect: every caller passes values of the method's own types.178- */132 export const encodeCall = <M extends ProjectMethod>(133 method: M,134 args: ArgsOf<M>135 ): Effect.Effect<typeof CallRequest.Encoded> =>16 unmodified lines152 payload: rest,153 };154 }).pipe(Effect.orDie);155 203-/**204- * The DO's answer, decoded: the method's success, its typed refusal, or the205- * defect it died with. A reply that does not decode is a defect.206- */156 export const decodeReply = <M extends ProjectMethod>(157 method: M,158 reply: ExitEncoded159 ): Effect.Effect<SuccessOf<M>, ErrorOf<M>> =>4 unmodified linesmodified:apps/platform/src/project-do.ts+1 added-42 removed
1-/**2- * One project's Durable Object: its state, its serial landing queue and its3- * alarm, behind a typed call boundary. A thin host over `project-shell.ts`:4- * it gives the shell the DO's own SQLite, its name and the stage's ports,5- * builds it once while the DO blocks other events, and runs every call and6- * every alarm on that one runtime, which lives on the instance.7- *8- * Every project call goes through `call`, and the project's deadlines9- * through `alarm`. Its watchers (`watch`) are hibernating10- * WebSockets: `fetch` accepts one at `/watch?since=n`, and after each call11- * and alarm commits, the watch room sends every socket what it has not12- * been sent (`watch.ts`). It has no public route: only the Worker reaches13- * it, through the `PROJECT` namespace (`adapters/do-projects.ts`,14- * `watch.ts`). The class name is frozen: a Durable Object class is renamed15- * only by a migration.16- */1+// The class name is frozen: a Durable Object class is renamed only by a migration.2 import { SqliteClient } from "@effect/sql-sqlite-do";3 import { AnswerRuns } from "@repo/project/answer-runs";4 import { nameOfKey, ProjectKey } from "@repo/protocol/ids";5 import type { ProjectName } from "@repo/protocol/ids";11 unmodified lines17 import type { ProjectShell } from "./project-shell.ts";18 import { closeEnd, watchRequest, watchRoom } from "./watch.ts";19 import { ProjectSkillGenerator } from "./workflows/generated.ts";20 36-/** The shell one Project DO runs on. */21 class Shell extends Context.Service<Shell, ProjectShell>()(22 "platform/ProjectShell"23 ) {}24 41-/**42- * An answer run started by a DO with no name: it cannot say which project43- * the run is for. The Worker always names the DO (`idFromName`).44- */25 const Nameless = Layer.succeed(26 AnswerRuns,27 AnswerRuns.of({28 start: () => Effect.die("a Project DO with no name started an answer run"),29 })30 );31 52-/**53- * Every port one Project DO's service runs on but its store: the stage's,54- * the DO's own alarm, the project's answer runs, and the platform's55- * generator for the project's own agent files, which the service runs after56- * a landing that changes what they say.57- */32 export const doPorts = (input: {33 readonly config: PlatformConfig;34 readonly storage: AlarmStorage;35 readonly name: Option.Option<ProjectName>;7 unmodified lines43 }),44 ProjectSkillGenerator45 );46 73-/** The shell over the DO's storage, its name, and the stage's ports. */47 const shellOf = (ctx: DurableObjectState, env: Env) =>48 Layer.effect(49 Shell,50 Effect.gen(function* () {51 const config = yield* decodeEnv(env);52 80- // The DO is named by the project's key (ADR 0032).53 const name = Option.flatMap(54 Schema.decodeUnknownOption(ProjectKey)(ctx.id.name),55 nameOfKey56 );16 unmodified lines73 // Migrations run before the first call or alarm is let in.74 void ctx.blockConcurrencyWhile(() => this.#runtime.context());75 }76 105- /** The shell with its watchers: what every call, alarm and socket runs on. */77 #watched<A>(78 use: (room: ReturnType<typeof watchRoom>) => Effect.Effect<A>79 ): Promise<A> {80 return this.#runtime.runPromise(81 Shell.use((shell) => use(watchRoom(this.ctx, shell)))82 );83 }84 114- /**115- * One call on the project: its `Exit`, encoded by the method's schemas.116- * Every watcher then hears what it committed.117- */85 call(request: typeof CallRequest.Encoded): Promise<ExitEncoded> {86 return this.#watched((room) => room.call(request));87 }88 122- /** The project's deadlines and retries, when the alarm the service set fires; then its watchers hear what they committed. */89 override alarm(): Promise<void> {90 return this.#watched((room) => room.alarm());91 }92 127- /**128- * A watcher's socket, at `/watch?since=n` with the WebSocket upgrade:129- * accepted to hibernate and sent every kept event after `n`. Any other130- * request asks for the upgrade.131- */93 override fetch(request: Request): Promise<Response> {94 return Option.match(watchRequest(request), {95 onNone: () =>96 Promise.resolve(14 unmodified lines111 },112 });113 }114 154- /** A watcher spoke: it is sent whatever it has not been sent yet. */115 override webSocketMessage(socket: WebSocket): Promise<void> {116 return this.#watched((room) => room.heard(socket));117 }118 159- /** A watcher went away: its end closes too. */119 override webSocketClose(120 socket: WebSocket,121 code: number,122 reason: string4 unmodified linesmodified:apps/platform/src/project-shell.ts-34 removed
1-/**2- * One project's Durable Object, without the host: the project service over3- * its own SQLite, behind the encoded call boundary. Host-free, so Node tests4- * run it over sqlite-node and memory ports; `project-do.ts` gives it the5- * DO's storage and the stage's ports.6- *7- * The shell holds no project logic (ADR 0012): `@repo/project`'s service8- * hydrates, transitions, persists and settles. The shell decodes each call9- * (the DO trusts only what the Worker sends), refuses a contract call10- * before `initProject` with `UnknownProject`, runs the method, and answers11- * its `Exit` encoded, so a refusal stays a refusal and never becomes a12- * defect at the boundary.13- */1 import { EvidenceStore } from "@repo/checks/evidence-store";2 import { projectService } from "@repo/project/project";3 import type { ProjectApi, ProjectPorts } from "@repo/project/project";4 import { ProjectStore } from "@repo/project/project-store";15 unmodified lines20 21 import { CallRequest, ProjectCalls } from "./project-calls.ts";22 import type { ArgsOf, ExitEncoded, ProjectMethod } from "./project-calls.ts";23 37-/** One project's DO without its host: what `project-do.ts` runs each call and alarm on. */24 export interface ProjectShell {39- /** One call on the project: its `Exit`, encoded by the method's schemas. */25 readonly call: (26 request: typeof CallRequest.Encoded27 ) => Effect.Effect<ExitEncoded>;43- /** The DO's alarm fired: the project's deadlines and retries run. */28 readonly alarm: () => Effect.Effect<void>;29 }30 47-/**48- * The service's methods as one table, each over its own arguments: what a49- * call indexed by a method name runs. A method may read lane logs50- * (`evidence`), so each runs with the stage's `EvidenceStore`.51- */31 type Methods = {32 readonly [M in ProjectMethod]: (33 ...args: Readonly<ArgsOf<M>>34 ) => Effect.Effect<2 unmodified lines37 EvidenceStore38 >;39 };40 62-/** The DO has no name, and its storage holds no project to take one from. */41 const nameless = Effect.die(42 "the Project DO has no name: the Worker reaches it by `idFromName`"43 );44 45 export const projectShell = (input: {68- /** The DO's name, when the Worker made its id with `idFromName`. */46 readonly name: ProjectName | undefined;70- /** SQL over the DO's own storage; sqlite-node in tests. */47 readonly sql: Layer.Layer<SqlClient>;72- /**73- * Every port the service runs on but its store, and where lane logs are74- * kept, which `evidence` reads.75- */48 readonly ports: Layer.Layer<49 Exclude<ProjectPorts, ProjectStore> | EvidenceStore50 >;51 }): Effect.Effect<ProjectShell, never, Scope.Scope> =>7 unmodified lines59 );60 61 const store = Context.get(context, ProjectStore);62 91- /** A method's run, with the stage's lane logs to read. */63 const withEvidence = Effect.provideService(64 EvidenceStore,65 Context.get(context, EvidenceStore)66 );67 68 const made = yield* Ref.make(false);69 const built = yield* SynchronizedRef.make(Option.none<Methods>());70 100- /** Whether `initProject` has made the project; once it has, it stays made. */71 const isMade = Effect.gen(function* () {72 if (yield* Ref.get(made)) {73 return true;74 }6 unmodified lines81 82 return Option.isSome(project);83 });84 115- /** The project's name: the DO's, or the one its storage holds. */85 const nameOf = Effect.gen(function* () {86 if (input.name !== undefined) {87 return Option.some(input.name);88 }2 unmodified lines91 92 return Option.map(project, (row) => row.project);93 });94 126- /** The project's one service, built on first use: one lock per project. */95 const service = SynchronizedRef.modifyEffect(built, (current) =>96 Option.match(current, {97 onNone: () =>98 Effect.gen(function* () {12 unmodified lines111 onSome: (api) => Effect.succeed([api, current] as const),112 })113 );114 147- /** One call on `method`, its request as the Worker encoded it. */115 const serve = <M extends ProjectMethod>(116 method: M,117 request: typeof CallRequest.Encoded & { readonly method: M }118 ) =>26 unmodified lines145 146 return {147 alarm: () =>148 Effect.gen(function* () {182- // A DO no project was made in has nothing to wake for.149 if (yield* isMade) {150 yield* Effect.flatMap(service, (api) =>151 withEvidence(api.onAlarm())152 );9 unmodified linesmodified:apps/platform/src/rate-limits.ts-11 removed
1-/**2- * The `RateLimits` port: how often one person may claim and propose across3- * the platform, whatever project they call. It sits4- * in front of the projects' own caps: a call past it reaches no project.5- * A flag on an ask is a proposal, so it spends the proposal limit.6- *7- * Adapters: `WorkerRateLimits` over the Worker's rate-limit bindings, and8- * `MemoryRateLimits` for tests (both in `adapters/rate-limits.ts`).9- */1 import type { Handle } from "@repo/protocol/ids";2 import type { CapReached } from "@repo/protocol/refusal";3 import { Context } from "effect";4 import type { Effect } from "effect";5 15-/** What a rate limit counts: claims, proposals (flags among them), or drafts. */6 export type Limited = "claim" | "proposal" | "draft";7 8 export class RateLimits extends Context.Service<9 RateLimits,10 {21- /** Spends one of `handle`'s `kind`; past the limit, `CapReached`. */11 readonly check: (12 kind: Limited,13 handle: Handle14 ) => Effect.Effect<void, CapReached>;2 unmodified linesmodified:apps/platform/src/raw.ts+3 added-9 removed
1-/**2- * A project's raw bytes: `GET /<project>/raw/<rev>/<path…>`, from its3- * canonical repo only, under a sandboxing CSP and `nosniff` so no file runs4- * as script on this origin. The answer is `@repo/project/code/raw`'s, the5- * one the web's dev world serves too. The revision and the path are read6- * from the request's own URL, still encoded, and decoded there once: the7- * router's parameter has `%2F` decoded already, which would cut a tag's8- * name in two.9- */1+// The revision and path are read from the request's own URL, still encoded: the2+// router's parameter has `%2F` decoded already, which would cut a tag's name in two.3+// Served under a sandboxing CSP and `nosniff` so no file runs as script on this origin.4 import type { RepoHost } from "@repo/artifacts/repo-host";5 import { rawFor } from "@repo/project/code/raw";6 import type { Projects } from "@repo/project/projects";7 import type { ProjectName } from "@repo/protocol/ids";7 unmodified linesmodified:apps/platform/src/releases.ts+5 added-88 removed
1-/**2- * The CLI's releases, served by the platform itself: anyone,3- * with no account and no token, runs `curl -fsSL <origin>/install.sh | sh`.4- * The release script (`scripts/release.ts`) uploads each release into the5- * stage's `RELEASES` bucket beside6- * `releases/manifest.json`, which says what each version holds; nothing7- * about a release lives anywhere else.8- */1 import { Brand } from "@repo/brand";2 import type { Layer } from "effect";3 import {4 Array,7 unmodified lines12 } from "effect";13 import type { HttpServerRequest } from "effect/http";14 import { HttpRouter, HttpServerResponse } from "effect/http";15 24-/** One stored file: its bytes, whole or as a stream, and how many there are. */16 export interface ReleaseFile {17 readonly body: ReadableStream | Uint8Array;18 readonly size: number;19 }20 30-/**31- * Where releases are kept: the stage's `RELEASES` bucket32- * (`releases/binding.ts`), or memory (`releases/memory.ts`). Read-only:33- * the release script uploads.34- */21 export class ReleaseStore extends Context.Service<22 ReleaseStore,23 {38- /** The file kept under `key`, if any. */24 readonly get: (key: string) => Effect.Effect<Option.Option<ReleaseFile>>;25 }26 >()("platform/ReleaseStore") {}27 43-/** A sha256 digest, as `sha256sum` prints it: 64 lowercase hex digits. */28 const Sha256 = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/u));29 46-/**47- * A version as the release script numbers releases: semver, with an optional48- * pre-release, and so never `latest`, a `/` or a `..`.30+// Never `latest`, a `/` or a `..`.49- */31 const VERSION =32 /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;33 53-/** A file name inside a version's folder: never a `/`, and never a leading dot. */34 const FILE_NAME = /^[0-9A-Za-z][0-9A-Za-z._-]*$/u;35 56-/**57- * Every key of a record matches `pattern`. Checked whole: a record with a58- * refined key would drop a bad entry without a word.59- */36+// Checked whole: a record with a refined key would drop a bad entry silently.37 const keysMatch = (pattern: RegExp, what: string) =>38 Schema.makeFilter((record: Readonly<Record<string, unknown>>) =>39 Object.keys(record).every((key) => pattern.test(key))40 ? true41 : `every key is ${what}`42 );43 67-/** One file of a release: its size and its digest. */44 const Asset = Schema.Struct({45 bytes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),46 sha256: Sha256,47 });48 49 type Asset = typeof Asset.Type;50 75-/** What one version holds, by file name. */51 const Release = Schema.Struct({52 assets: Schema.Record(Schema.String, Asset).check(53 keysMatch(FILE_NAME, "a file name")54 ),55 });56 57 type Release = typeof Release.Type;58 84-/**85- * `releases/manifest.json`, as the release script's `releaseManifest` writes86- * it: every version released, by version, and which one is latest. Decoded at87- * the boundary (principle 2), so a version or a file name from it never leaves88- * `releases/<version>/`.89- */59 export const ReleaseManifest = Schema.Struct({60 latest: Schema.String.check(Schema.isPattern(VERSION)),61 versions: Schema.Record(Schema.String, Release).check(62 keysMatch(VERSION, "a version")5 unmodified lines68 );69 70 export type ReleaseManifest = typeof ReleaseManifest.Type;71 103-/**104- * What a release is built for (the release script's targets, without Bun's `bun-`105- * prefix). A binary is named for the slug and its target, and nothing else106- * is served as one.107- */72 const releaseTargets = ["linux-x64", "darwin-arm64"] as const;73 110-/** Where the manifest is kept, and served; every release file is under `releases/`. */74 const MANIFEST_KEY = "releases/manifest.json";75 76 const MANIFEST_PATH = `/${MANIFEST_KEY}`;77 115-/** Each version's checksum file, made from its manifest entry. */78 const CHECKSUMS = "SHA256SUMS";79 118-/**119- * Every file served under a version: each binary, and the checksums. Each120- * is a route of its own, so any other name is not found before anything is121- * read, and a git path such as `/releases/info/refs` (a project named122- * `releases`) still reaches the gateway.123- */80+// Each file is a route of its own, so any other name is not found before anything is81+// read, and a git path such as `/releases/info/refs` still reaches the gateway.82 const servedFiles: readonly string[] = [83 ...releaseTargets.map((target) => `${Brand.slug}-${target}`),84 CHECKSUMS,85 ];86 129-/** The version segment that names whichever release is newest. */87 const LATEST = "latest";88 132-/** How long a versioned file may be kept: it never changes. */89 const FOREVER = "public, max-age=31536000, immutable";90 135-/** How long a reply that changes with the next release may be kept. */91 const BRIEFLY = "public, max-age=300";92 138-/** Neither a reply about a missing or broken release nor a 405 is kept. */93 const NO_STORE = "no-store";94 95 const notFound = HttpServerResponse.empty({96 headers: { "cache-control": NO_STORE },4 unmodified lines101 headers: { "cache-control": NO_STORE },102 status: 503,103 });104 151-/** Releases are only read here: the release script uploads them with Wrangler. */105 const readOnly = HttpServerResponse.empty({106 headers: { allow: "GET, HEAD", "cache-control": NO_STORE },107 status: 405,108 });109 157-/** Nothing has been released: there is no manifest. */110 class NoReleases extends Data.TaggedError("NoReleases") {}111 160-/** The manifest could not be read, or did not decode. */112 class ManifestUnusable extends Data.TaggedError("ManifestUnusable") {}113 114 const decodeManifest = Schema.decodeEffect(115 Schema.fromJsonString(ReleaseManifest)116 );117 167-/** A stored file's bytes as text. */118 const textOf = ({ body }: ReleaseFile) =>119 Effect.tryPromise({120 catch: () => new ManifestUnusable(),121 try: () => new Response(body).text(),122 });123 174-/** The manifest, decoded at the boundary (principle 2), and its text as stored. */124 const manifestIn = (store: ReleaseStore["Service"]) =>125 Effect.gen(function* () {126 const stored = yield* store.get(MANIFEST_KEY);127 9 unmodified lines137 138 return { manifest, text };139 });140 192-/** A stored file as a reply, with `headers`. */141 const fileReply = (142 file: ReleaseFile,143 contentType: string,144 headers: Readonly<Record<string, string>>3 unmodified lines148 contentType,149 headers,150 });151 204-/** `/install.sh`: the latest release's install script. */152 const installScript = (store: ReleaseStore["Service"]) =>153 Effect.gen(function* () {154 const { manifest } = yield* manifestIn(store);155 7 unmodified lines163 }),164 });165 });166 220-/**221- * Whether an `If-None-Match` header names the entity tag `tag`: as `*`, or222- * in its list, strong or weak (RFC 9110 §13.1.2 compares weakly).223- */167+// RFC 9110 §13.1.2: `If-None-Match` compares weakly.168 const holds = (header: string | undefined, tag: string) =>169 header !== undefined &&170 header171 .split(",")172 .map((each) => each.trim())173 .some((each) => each === "*" || each.replace(/^W\//u, "") === tag);174 231-/**232- * A version's checksum file, made from its manifest entry: one line per233- * file, as `sha256sum` prints it, and none for a `SHA256SUMS` the manifest234- * lists, since this file is never that one.235- */175 const checksumsOf = (assets: Release["assets"]) =>176 Array.sortWith(177 Object.entries(assets).filter(([name]) => name !== CHECKSUMS),178 ([name]) => name,1 unmodified line180 )181 .map(([name, { sha256 }]) => `${sha256} ${name}\n`)182 .join("");183 245-/**246- * A binary of one version, kept forever and tagged with the digest its247- * manifest lists, or 304 to a client that already holds those bytes.248- */184 const binaryReply = (185 store: ReleaseStore["Service"],186 request: HttpServerRequest.HttpServerRequest,187 key: string,14 unmodified lines202 fileReply(binary, "application/octet-stream", headers),203 });204 });205 271-/**272- * `/releases/:version/<asset>`: a binary or the checksum file of a version273- * the manifest lists, or a short-lived redirect from `latest` to the newest274- * one.275- */206 const versioned = (207 store: ReleaseStore["Service"],208 request: HttpServerRequest.HttpServerRequest,209 asset: string12 unmodified lines222 }223 224 const { assets } = release.value;225 296- // The checksums are made for every listed version; a binary is served297- // only where the version lists it.226 const listed =227 asset === CHECKSUMS ? Option.none() : Record.get(assets, asset);228 229 if (asset !== CHECKSUMS && Option.isNone(listed)) {18 unmodified lines248 binaryReply(store, request, `releases/${named}/${asset}`, file),249 });250 });251 324-/** `/releases/manifest.json`: the manifest as stored, once it decodes. */252 const manifestReply = (store: ReleaseStore["Service"]) =>253 Effect.map(manifestIn(store), ({ text }) =>254 HttpServerResponse.text(text, {255 contentType: "application/json",256 headers: { "cache-control": BRIEFLY },257 })258 );259 333-/**334- * `reply` for GET and HEAD (the router serves HEAD as GET, without the335- * body), and 405 for any other method; a release that failed to load is336- * not found when there is none yet, and unavailable when its manifest is337- * broken.338- */260 const download = <R>(261 reply: (262 request: HttpServerRequest.HttpServerRequest263 ) => Effect.Effect<14 unmodified lines278 })279 );280 });281 361-/**362- * GET and HEAD `/install.sh`, `/releases/manifest.json` and363- * `/releases/:version/<asset>` for each served file.364- */282 export const releaseRoutes: Layer.Layer<283 never,284 never,285 HttpRouter.HttpRouter | ReleaseStore25 unmodified linesmodified:apps/platform/src/repo-names.ts-5 removed
1-/**2- * What a repo's name says it is, from `@repo/project/repo-names`, where3- * the project service lists its forks by it too: the gateway, the handlers4- * and OnPush read names from here.5- */1 export {2 claimForkName,3 repoKind,4 RepoKind,2 unmodified linesmodified:apps/platform/src/router-build.ts+8 added-34 removed
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- * Only the build's own fiber is run to its end here: a fiber the build forks17- * (a layer built beside others) that outlasts its turn and yields is18- * refused as if it had awaited. Both real compositions are built in19- * `test/router-build.test.ts`, so such a build fails `verify`, never a20- * deploy.21- */1+// effect's `HttpRouter.toWebHandler` has every request await one layer build. On2+// Workers a request whose client leaves is cancelled without resuming its fibers, so3+// a build that awaited a request's I/O would hang every later request for the4+// isolate's life. Here the build runs synchronously, and a layer that awaits a5+// promise or a timer while built throws where the handler is made.6 import {7 Cause,8 Context,9 Data,5 unmodified lines15 } from "effect";16 import type { HttpServerRequest } from "effect/http";17 import { HttpEffect, HttpRouter } from "effect/http";18 35-/** A router's build awaited a promise or a timer; nothing was served. */19 export class RouterBuildAwaited extends Data.TaggedError("RouterBuildAwaited")<{20 readonly message: string;21 }> {}22 40-/** What a request needs beyond itself: the services `R`'s routes require of it. */23 type RequestNeeds<A, R> = Exclude<24 | HttpRouter.Request.Only<"Requires", R>25 | HttpRouter.Request.Only<"GlobalRequires", R>,26 A | Scope.Scope | HttpServerRequest.HttpServerRequest27 >;28 47-/**48- * `appLayer`'s routes as a fetch handler, its layer built now; a request49- * that needs services of its own (`RequestNeeds`) is given them as its50- * context. `dispose` closes what the build opened.51- */29 export const buildHandler = <30 A,31 E,32 R extends18 unmodified lines51 E52 >;53 /* oxlint-enable typescript/no-unsafe-type-assertion */54 78- // `runSyncExit` runs its fiber on a scheduler of its own, which yields79- // through microtasks and would ride along in any context a layer captures80- // while it is built (`authenticated` verifies every credential in the81- // one it captured). The build runs on the scheduler a fiber has by default82- // instead; `runSyncExit` still drains what it schedules before it returns.55+ // `runSyncExit`'s own scheduler would ride along in any context a layer captures56+ // while built, so the build runs on the default one; `runSyncExit` still drains what57+ // it schedules before it returns.58 const built = Effect.runSyncExit(59 Layer.buildWithScope(routed, scope).pipe(60 Effect.provideService(61 Scheduler.Scheduler,28 unmodified lines90 Context.get(context, HttpRouter.HttpRouter).asHttpEffect()91 ),92 });93 119- /** One request, given `context` beside it: what `R`'s routes require of it. */94 const handler = (95 request: Request,96 context?: Context.Context<RequestNeeds<A, R>>97 ): Promise<Response> => serveRequest(request, context);6 unmodified linesmodified:apps/platform/src/sessions.ts-7 removed
1 import type { Person } from "@repo/protocol/principal";2 import { Context } from "effect";3 import type { Effect, Option } from "effect";4 5-/**6- * Turns a bearer credential into the person it names, if it names anyone.7- * The platform has one: every source of tokens (sign-in, the operator,8- * `SESSION_TOKENS`) is a `Sessions` of its own, joined by9- * `sessions/first-of.ts`. A credential never names anyone at all: calling10- * as anyone is having none.11- */5 export class Sessions extends Context.Service<6 Sessions,7 {8 readonly verify: (token: string) => Effect.Effect<Option.Option<Person>>;2 unmodified linesmodified:apps/platform/src/surfaces.ts+10 added-137 removed
42 unmodified lines43 import { Sessions } from "./sessions.ts";44 import { isFramed } from "./watch.ts";45 import { agentSkillRoutes } from "./well-known.ts";46 47-/** What `/` says of the host: the web app's URL and the drafter's model. */47 export { HostInfo } from "./host-info.ts";48 50-/** Which stage this Worker serves: `/health` says so. */49 export class Stage extends Context.Service<Stage, { readonly name: string }>()(50 "platform/Stage"51 ) {}52 55-/**56- * What the surfaces need from the platform: the contracts' handlers,57- * sessions, what git's paths need, the CLI's releases, the front page and58- * the repos the projects' skills and raw files are read from, the stage,59- * and what `/` says of the host.60- */53 export type Services =54 | Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>55 | Sessions56 | GitServices2 unmodified lines59 | RepoHost60 | Stage61 | HostInfo;62 71-/**72- * git's smart-HTTP paths: `/<address>(.git)/info/refs` and the two services,73- * where an address is a project's name in one to three segments, a fork's74- * parts on the last (ADR 0032).75- */63 const GIT_PATH =64 /^\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+){0,2}\/(?:info\/refs|git-upload-pack|git-receive-pack)$/u;65 79-/**80- * Where an OAuth client learns how to get a credential: these two81- * documents, with the path-suffixed forms RFC 8414 and RFC 9728 allow.82- */66 const DISCOVERY_PATH =67 /^\/\.well-known\/oauth-(?:protected-resource|authorization-server)(?:\/.*)?$/u;68 86-/**87- * Sign-in's own endpoints: `/authorize`, `/signup`,88- * `/token` and `/oauth/*`.89- */69 const SIGN_IN_PATH = /^\/(?:authorize|signup|token|oauth(?:\/.*)?)$/u;70 92-/**93- * A project's raw files, `/<project>/raw/<rev>/<path…>`, the project's name94- * in one to three segments: no git path, whose segment after the name is95- * `info` or a git service, ever matches it.96- */71+// No git path, whose segment after the name is `info` or a git service, ever matches.72 const RAW_PATH = /^\/[a-z0-9._-]+(?:\/[a-z0-9._-]+){0,2}\/raw\/.+$/u;73 99-/**100- * The CLI's install script and releases (`releases.ts`):101- * `/install.sh`, `/releases/manifest.json` and `/releases/:version/:asset`.102- */74 const RELEASE_PATH =75 /^\/(?:install\.sh|releases\/(?:manifest\.json|[^/]+\/[^/]+))$/u;76 106-/**107- * The projects' contribute skills and their index108- * (`well-known.ts`), public as every landed tree is.109- */77 const SKILLS_PATH = /^\/\.well-known\/agent-skills\/.+$/u;78 112-/**113- * Paths no credential is asked for and none is checked on, so none answers114- * 401: `/health`; git's, whose gateway decides who may read and push (and115- * answers an unknown credential with its own 401); the paths that tell a116- * client how to sign in, or sign it in, which may carry a stale token or an117- * OAuth client's own credential; the CLI's downloads, which anyone may118- * fetch, with whatever credential an installer happens to carry; the119- * projects' skills, which an agent fetches the same way; the host's own120- * page, `/`; and a project's raw files, which a README's images name.121- */79+// No credential is asked for or checked on these, so none answers 401: git's gateway80+// answers an unknown credential itself, and the rest may carry a stale token or an81+// OAuth client's own credential.82 const isExempt = (path: string) =>83 path === "/" ||84 path === "/health" ||85 RAW_PATH.test(path) ||2 unmodified lines88 SIGN_IN_PATH.test(path) ||89 RELEASE_PATH.test(path) ||90 SKILLS_PATH.test(path);91 132-/** Where the platform describes itself as an OAuth protected resource. */92 const PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";93 135-/** The platform's origin, as the request reached it. */94 const originOf = (request: HttpServerRequest.HttpServerRequest) =>95 URL.parse(request.originalUrl)?.origin ??96 Option.match(HttpServerRequest.toURL(request), {97 onNone: () => "http://localhost",98 onSome: ({ origin }) => origin,99 });100 143-/**144- * The platform as an OAuth protected resource (RFC 9728): a bearer token145- * in the `Authorization` header, from the platform's own authorization146- * server.147- */101 export const protectedResourceMetadata = (origin: string) => ({102 authorization_servers: [origin] as const,103 bearer_methods_supported: ["header"] as const,104 resource: origin,105 });106 154-/**155- * A 401 for `request`: it asks for a bearer token and names where to learn156- * how to get one (RFC 9728 §5.1, which MCP's authorization requires). Its157- * `error` is `invalid_token` only for a bearer token the platform does not158- * know; a request with no credential, or one of another scheme, gets no159- * error code (RFC 6750 §3.1).160- */107+// RFC 9728 §5.1, which MCP's authorization requires. `invalid_token` only for a108+// bearer token the platform does not know (RFC 6750 §3.1).109 const unauthorized = (110 request: HttpServerRequest.HttpServerRequest,111 error?: "invalid_token"112 ) => {7 unmodified lines120 status: 401,121 });122 };123 176-/**177- * The bearer credential the request was let in with, and the person it178- * names; none when it carried none, and on an exempt path. Set once per179- * request, before any surface sees it, and read by the contracts' server180- * side, so a token is verified once per request.181- */124 const Caller = Context.Reference<125 Option.Option<{ readonly person: Person; readonly token: string }>126 >("platform/Caller", { defaultValue: Option.none });127 186-/**187- * Who is calling, decided once per request, before any surface sees it: a188- * credential the platform does not know is a 401 on every path but the189- * exempt ones; a known one becomes the request's `Caller`. A request with190- * no credential goes on as anyone: each contract decides whether anyone may191- * call it, and MCP asks for one (`signedInOnly`).192- */128 const identifyCaller = HttpRouter.middleware(129 Effect.gen(function* () {130 const sessions = yield* Sessions;131 30 unmodified lines162 }),163 { global: true }164 );165 231-/**232- * The routes it is given answer only a request let in with a credential;233- * any other gets a 401 naming where to learn how to sign in. On the route,234- * not on a path, so it holds however the router matched the path.235- */166 const signedInOnly = HttpRouter.middleware((httpEffect) =>167 Effect.gen(function* () {168 if (Option.isSome(yield* Caller)) {169 return yield* httpEffect;2 unmodified lines172 return unauthorized(yield* HttpServerRequest.HttpServerRequest);173 })174 ).layer;175 246-/**247- * Server side: protocol's `Authenticated` rule (anyone only on a `public`248- * contract), over the `Caller` the request was let in with rather than a249- * second verification. A call that names a credential other than the one250- * its request was let in with, such as one an RPC message adds to its own251- * headers, runs as nobody.252- */176+// A call naming a credential other than the one its request was let in with (one an177+// RPC message adds to its own headers) runs as nobody.178 const asCaller = authenticated((credential) =>179 Caller.useSync(180 Option.flatMap(({ person, token }) =>181 token === credential ? Option.some(person) : Option.none()182 )183 )184 );185 261-/**262- * Client side, for calls made while serving an HTTP request: the call carries263- * that request's credential.264- */186 const forwardCredential = RpcMiddleware.layerClient(187 Authenticated,188 ({ next, request }) =>189 Effect.gen(function* () {19 unmodified lines209 );210 211 const projection = toToolkit(surfaced("mcp"), Effect.service(Client));212 292-/**293- * The platform's skill as the prompt `contribute`, made when the server294- * starts from agent-kit's command list, the one the CLI's prompt and the295- * web's `llms.txt` read, so they say the same. Made from the skill's parts,296- * not its `SKILL.md`, whose hash is a promise the router's build may not297- * await (`router-build.ts`).298- */213+// Made from the skill's parts, not its `SKILL.md`, whose hash is a promise the214+// router's build may not await.215 const contribute = skillPrompt(216 platformSkillParts({ commands: commandDocs(Contracts) })217 );218 303-/**304- * The MCP-surfaced contracts as tools at `/mcp`, beside each ask's brief305- * and the projects as resources and the skill as a prompt, for a signed-in306- * caller only (harnesses using MCP have tokens), each call307- * made as that caller through one `Client`.308- */219 const mcp = Layer.mergeAll(220 McpServer.toolkit(projection.toolkit).pipe(221 Layer.provideMerge(projection.layer)222 ),11 unmodified lines234 }).pipe(Layer.provide(signedInOnly))235 )236 );237 328-/** The contracts' server over HTTP in one serialization, as one handler. */238 const rpcIn = (serialization: Layer.Layer<RpcSerialization.RpcSerialization>) =>239 RpcServer.toHttpEffect(Contracts).pipe(Effect.provide(serialization));240 332-/**333- * The contracts over HTTP at `/rpc`, for the CLI, the web and anything else334- * remote: a public read as anyone, every other contract as the caller. A335- * call posted as JSON is answered in one JSON body when it ends; one posted336- * as NDJSON is answered framed, each message as it is ready, so a stream337- * (`watch`) reaches its caller as it happens.338- */241 const rpc = HttpRouter.use((router) =>242 Effect.gen(function* () {243 const whole = yield* rpcIn(RpcSerialization.layerJson);244 const framed = yield* rpcIn(RpcSerialization.layerNdjson);3 unmodified lines248 );249 })250 ).pipe(Layer.provide(asCaller));251 350-/** `/health`: the Worker is up, and which stage it serves. */252 const health = HttpRouter.use((router) =>253 Effect.gen(function* () {254 const { name } = yield* Stage;255 4 unmodified lines260 );261 })262 );263 363-/** A route that answers with a web `Response` from `respond`, given the web request. */264 const fromWeb =265 <R>(respond: (web: Request) => Effect.Effect<Response, never, R>) =>266 (request: HttpServerRequest.HttpServerRequest) =>267 HttpServerRequest.toWeb(request).pipe(1 unmodified line269 Effect.map(HttpServerResponse.fromWeb),270 Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 400 }))271 );272 373-/** `/`: what this host serves, for a browser and for an agent (`home.ts`). */273 const home = HttpRouter.use((router) =>274 Effect.gen(function* () {275 const services = Context.make(FrontPage, yield* FrontPage).pipe(276 Context.add(HostInfo, yield* HostInfo),277 Context.add(Projects, yield* Projects),379- // A `Context.Reference`: without it each `/` reads every project.278 Context.add(StandingPostures, yield* StandingPostures)279 );280 281 yield* router.add(5 unmodified lines287 );288 289 const decodeProject = Schema.decodeUnknownOption(ProjectName);290 393-/**394- * A project's address in the router's words: one to three segments, each395- * a parameter, joined back by `addressOf` (ADR 0032).396- */291 const ADDRESSES = ["/:a", "/:a/:b", "/:a/:b/:c"] as const;292 399-/** The address a route's parameters spell, with its segments joined. */293 const addressOf = (params: Readonly<Record<string, string | undefined>>) =>294 [params.a, params.b, params.c]295 .filter((segment) => segment !== undefined)296 .join("/");5 unmodified lines302 `${address}/git-upload-pack` as const,303 `${address}/git-receive-pack` as const,304 ]);305 413-/** `/<project>/raw/<rev>/<path…>`: a project's raw files (`raw.ts`). */306 const raw = HttpRouter.use((router) =>307 Effect.gen(function* () {416- // The isolate's code cache and the code store, as the `/rpc` code417- // reads have them: `Context.Reference`s, so without them every raw read418- // goes to Artifacts.308 const services = Context.make(RepoHost, yield* RepoHost).pipe(309 Context.add(Projects, yield* Projects),310 Context.add(CodeCache, yield* CodeCache),311 Context.add(CodeStore, yield* CodeStore)17 unmodified lines329 }330 })331 );332 444-/**445- * The protected-resource document (RFC 9728), answered to anyone: where a446- * client learns that the platform is its own authorization server. The447- * authorization server's document is the sign-in provider's, which answers448- * its path before the surfaces see it (`auth/provider.ts`).449- */333 const discovery = HttpRouter.use((router) =>334 router.add("GET", PROTECTED_RESOURCE_PATH, (request) =>335 Effect.succeed(336 HttpServerResponse.jsonUnsafe(2 unmodified lines339 )340 )341 );342 460-/** A git request, as the gateway answers it; 404 for a path it does not serve. */343 const toGateway = (request: HttpServerRequest.HttpServerRequest) =>344 HttpServerRequest.toWeb(request).pipe(345 Effect.flatMap((web) =>346 Option.match(serveGit(web), {3 unmodified lines350 ),351 Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 400 }))352 );353 472-/**473- * git's smart-HTTP paths, each handed to the gateway with the services it474- * needs, taken once when the router is built: the layer repos too, which475- * a cartridge may have plugged in over their default (`LayerGate`).476- */354 const git = HttpRouter.use((router) =>355 Effect.gen(function* () {356 const services = Context.make(Sessions, yield* Sessions).pipe(357 Context.add(Projects, yield* Projects),8 unmodified lines366 }367 })368 );369 493-/**494- * The platform's fetch handler over `services`, its router built now,495- * before any request, awaiting nothing (`router-build.ts`).496- */370 export const serve = <E>(services: Layer.Layer<Services, E>) =>371 buildHandler(372 Layer.mergeAll(373 home,11 unmodified linesmodified:apps/platform/src/watch.ts+6 added-108 removed
1-/**2- * `watch` live: a project's events, replayed from a3- * sequence number and then heard as they are committed.4- *5- * The Project DO keeps the newest 500 events (`keptEvents`) and one6- * hibernating WebSocket per watcher (`watchRoom`): it accepts a socket7- * opened at `/watch?since=n`, sends it every kept event after `n`, and after8- * each call and alarm (the settle step that follows the store's commit,9- * ADR 0012) sends every socket what it has not been sent yet. Where each10- * socket stands lives in its attachment, so it survives hibernation; the11- * number it opened from is its tag, read when the attachment is missing.12- *13- * The Worker's `watch` handler (`watchHandler`) relays that socket to the14- * caller over `/rpc`, frame by frame, for as long as the caller stays, and15- * opens it again from the last number it relayed when it is lost, so a16- * watcher hears each event once, in order. Where no socket can be opened17- * (no `PROJECT` namespace, as in process, or a DO that does not upgrade),18- * it follows the project's event log by asking for what is new each19- * second instead: the stream stays the same.20- *21- * A live tail needs a framed transport: over `/rpc` with JSON the whole22- * answer is sent when the call ends, so there `watch` replays what is kept23- * and ends, as it always has.24- */1+// A socket's position lives in its attachment, which survives hibernation; its tag2+// holds the number it opened from, for when the attachment is lost.3 import type { ProjectApi } from "@repo/project/project";4 import { keptEvents } from "@repo/project/project-store";5 import { Projects } from "@repo/project/projects";6 import { NoneOrMore } from "@repo/protocol/domain/common";21 unmodified lines28 import { decodeReply, encodeCall } from "./project-calls.ts";29 import type { CallRequest, ExitEncoded } from "./project-calls.ts";30 import type { ProjectShell } from "./project-shell.ts";31 54-/** How many events `watch` reads from a project's log at a time. */32 const EVENT_PAGE = 100;33 57-/** How long a watcher with no socket waits before it asks the log for what is new. */34 const POLL = Duration.seconds(1);35 60-/** How long the relay waits before it opens a lost socket again. */36 const RECONNECT = Duration.seconds(1);37 63-/** The tag every watch socket a Project DO accepts carries. */38 export const WATCH_TAG = "watch";39 66-/** Where the Worker opens a project's watch socket on its DO. */40 export const WATCH_PATH = "/watch";41 69-/** How the tag that keeps the number a socket opened from begins. */42 const SINCE = "since:";43 72-/** One frame on a watch socket: an event and its place in the project's sequence. */44 export const WatchFrame = Schema.Struct({45 event: ProjectEvent,46 seq: Schema.Int,47 });5 unmodified lines53 const encodeFrame = Schema.encodeEffect(FrameText);54 55 const decodeFrame = Schema.decodeEffect(FrameText);56 86-/** A sequence number as a URL or a tag carries it. */57 const SinceText = Schema.FiniteFromString.pipe(Schema.decodeTo(NoneOrMore));58 59 const decodeSince = Schema.decodeUnknownOption(SinceText);60 91-/**92- * Whether an HTTP request was posted framed (NDJSON), so its answer is93- * sent message by message as it is ready and a stream can stay open.94- */61 export const isFramed = (headers: Headers.Headers) =>62 Option.exists(Headers.get(headers, "content-type"), (type) =>63 type.startsWith(RpcSerialization.ndjson.contentType)64 );65 100-/**101- * Whether the call being served came over a framed `/rpc`, as the HTTP102- * request that carried it says; false for a call that came from no103- * request. Never the call's own headers: the RPC server lays them over the104- * request's, so a call posted as JSON could claim to be framed, and a live105- * `watch` on a buffered answer would never be sent.106- */66+// Never the call's own headers: the RPC server lays them over the request's, so a67+// call posted as JSON could claim to be framed.68 export const servedFramed = Effect.map(69 Effect.serviceOption(HttpServerRequest.HttpServerRequest),70 Option.exists((request) => isFramed(request.headers))71 );72 112-// --- The Project DO's side ---------------------------------------------------113-114-/** What the watch room uses of a Project DO's state: the hibernating sockets it accepts and finds again. */73 export type SocketState = Pick<74 DurableObjectState,75 "acceptWebSocket" | "getTags" | "getWebSockets"76 >;77 120-/** Where a watch socket stands: the last number it was sent. */78 const Position = Schema.Struct({ seq: NoneOrMore });79 80 const decodePosition = Schema.decodeUnknownOption(Position);81 125-/** The number a socket opened from, as its tag keeps it. */82 const openedFrom = (state: SocketState, socket: WebSocket) =>83 Option.flatMap(84 Option.fromUndefinedOr(85 state.getTags(socket).find((tag) => tag.startsWith(SINCE))86 ),87 (tag) => decodeSince(tag.slice(SINCE.length))88 );89 134-/**135- * The number a watch request opens from: `since` on `/watch`, a whole136- * number, with the WebSocket upgrade; none for any other request.137- */90 export const watchRequest = (request: Request): Option.Option<number> => {91 const url = new URL(request.url);92 93 return url.pathname === WATCH_PATH &&1 unmodified line95 ? decodeSince(url.searchParams.get("since") ?? "0")96 : Option.none();97 };98 147-/**148- * Sends `socket` each of `frames` in order, moving its attachment on with149- * each; stops at the first it cannot send.150- */99 const send = (socket: WebSocket, frames: readonly WatchFrame[]) =>100 Effect.forEach(101 frames,102 (frame) =>7 unmodified lines110 }),111 { discard: true }112 ).pipe(Effect.ignore);113 166-/**167- * A Project DO's shell with its watchers. Each call and alarm runs on the168- * shell as before, then settles the sockets: each is sent the kept events169- * after where it stands, in order, and its attachment moves to the last.170- * A socket that can no longer be sent to is left as it stands; the runtime171- * drops it once it has closed.172- */114 export const watchRoom = (state: SocketState, shell: ProjectShell) => {174- /** The kept events after `seq`, oldest first. */115 const eventsAfter = (seq: number) =>116 encodeCall("events", [seq, keptEvents]).pipe(117 Effect.flatMap((request) => shell.call(request)),118 Effect.flatMap((reply) => decodeReply("events", reply))119 );120 181- /** Where `socket` stands; none for a socket that is not a watcher's. */121 const positionOf = (socket: WebSocket) =>122 Option.orElse(123 Option.map(124 decodePosition(socket.deserializeAttachment()),1 unmodified line126 ),127 () => openedFrom(state, socket)128 );129 191- /** Sends each of `sockets` the kept events after where it stands. */130 const catchUp = (sockets: readonly WebSocket[]) =>131 Effect.gen(function* () {132 const standing = sockets.flatMap((socket) =>133 Option.match(positionOf(socket), {20 unmodified lines154 { discard: true }155 );156 });157 220- /**221- * Every watcher, caught up: the settle step after a commit. The commit222- * stands whatever happens here, so a settle that fails is logged and the223- * call still answers what it did; the next settle sends what this one224- * could not.225- */158+ // The commit stands whatever happens here: a failed settle is logged, and the next159+ // settle sends what this one could not.160 const settle = Effect.suspend(() =>161 catchUp(state.getWebSockets(WATCH_TAG))162 ).pipe(163 Effect.catchCause((cause) =>1 unmodified line165 )166 );167 168 return {235- /** A new watcher's socket, from `since`: accepted to hibernate, then sent every kept event after it. */169 admit: (socket: WebSocket, since: number) =>170 Effect.suspend(() => {171 state.acceptWebSocket(socket, [WATCH_TAG, `${SINCE}${since}`]);172 socket.serializeAttachment({ seq: since });2 unmodified lines175 }),176 alarm: () => Effect.andThen(shell.alarm(), settle),177 call: (request: typeof CallRequest.Encoded): Effect.Effect<ExitEncoded> =>178 Effect.tap(shell.call(request), () => settle),246- /** A watcher spoke: it is sent whatever it has not been sent yet. */179 heard: (socket: WebSocket) => catchUp([socket]),180 };181 };182 251-/** Close codes a socket may not send itself: they only report how a close happened. */183 const reportOnly: ReadonlySet<number> = new Set([1005, 1006, 1015]);184 254-/** A watcher closed its socket: the DO closes its end with the same code, if it may send it. */185 export const closeEnd = (socket: WebSocket, code: number, reason: string) =>186 Effect.try(() => {187 socket.close(reportOnly.has(code) ? 1000 : code, reason);188 }).pipe(Effect.ignore);189 260-// --- The Worker's side --------------------------------------------------------261-262-/** A project DO's answer to a watch upgrade, as far as the relay reads it. */190 interface Upgraded {191 readonly webSocket: WebSocket | null;192 }193 267-/** The `PROJECT` namespace as the relay reaches it: a stub's fetch opens the DO's watch socket. */194 export interface WatchNamespace {195 readonly idFromName: (name: string) => DurableObjectId;196 readonly get: (id: DurableObjectId) => {197 readonly fetch: (request: Request) => Promise<Upgraded>;198 };199 }200 275-/**276- * Where the relay opens a project's watch socket: the Worker's `PROJECT`277- * namespace. None by default, as in process, where `watch` follows the278- * project's event log instead.279- */201 export const ProjectSockets = Context.Reference<Option.Option<WatchNamespace>>(202 "platform/ProjectSockets",203 { defaultValue: Option.none }204 );205 285-/** The DO would not open a watch socket. */206 class SocketRefused extends Data.TaggedError("SocketRefused")<{207 readonly cause: unknown;208 }> {}209 290-/** An open watch socket failed. */210 class SocketLost extends Data.TaggedError("SocketLost")<{211 readonly reason: string;212 }> {}213 295-/**296- * One watch socket on `project`'s DO from `since`: each frame it carries,297- * decoded, until it closes. The socket is closed when the stream ends.298- */214 const socketFrames = (215 namespace: WatchNamespace,216 project: ProjectName,217 since: number42 unmodified lines260 })261 )262 );263 }).pipe(349- // The callback runs beside the stream: its own failure ends the stream through the queue.264 Effect.catchTag("SocketRefused", (refused) => Queue.fail(queue, refused))265 )266 ).pipe(Stream.mapEffect((text) => Effect.orDie(decodeFrame(text))));267 354-/**355- * The project's events after `since`, a page at a time, then what is new356- * each `POLL`, for as long as the stream runs.357- */268 const polled = (api: ProjectApi, since: number) =>269 Stream.paginate({ after: since, caughtUp: false }, ({ after, caughtUp }) =>270 Effect.gen(function* () {271 if (caughtUp) {11 unmodified lines283 ] as const;284 })285 );286 377-/** The project's kept events after `since`, a page at a time, then the end. */287 const replayed = (api: ProjectApi, since: number) =>288 Stream.paginate(since, (after) =>289 Effect.map(api.events(after, EVENT_PAGE), (rows) => [290 rows,2 unmodified lines293 : Option.fromUndefinedOr(rows.at(-1)?.seq),294 ])295 );296 388-/**389- * The DO's watch socket, relayed: every frame after the last one relayed,390- * once, in order. A socket lost is opened again from the last number391- * relayed; a DO that will not open one is followed by its log instead.392- */297 const relayed = (298 namespace: WatchNamespace,299 api: ProjectApi,300 project: ProjectName,19 unmodified lines320 );321 })322 );323 420-/**421- * The `watch` contract's handler: `project`'s events after `since` (from422- * the start when none, or when it is less than none). Over a framed423- * transport they keep coming until the caller goes away; over a buffered424- * one the stream ends after the kept events.425- */324 export const watchHandler = (325 payload: { readonly project: ProjectName; readonly since?: number },326 transport: { readonly live: boolean }327 ): Stream.Stream<ProjectEvent, UnknownProject, Projects> =>15 unmodified linesmodified:apps/platform/src/well-known.ts+1 added-64 removed
1-/**2- * The projects' contribute skills where agents look for skills:3- * `/.well-known/agent-skills/index.json`, in the Agent Skills discovery shape4- * (`wellKnownSkills`), lists every project whose landed tree holds5- * `.agents/skills/<key>-contribute/SKILL.md` (the project's key), with the6- * SHA-256 of the file's bytes, and7- * `/.well-known/agent-skills/<key>-contribute/SKILL.md`8- * serves that file as it landed. Nothing is generated here: the platform serves9- * what landed (a follow-up landing lands the regenerated skill). The web host10- * forwards these paths unchanged, and the index's URLs are path-absolute, so11- * they work on either host.12- *13- * Projects come from the front page (`listProjects` reads the same), each14- * read at its landed SHA as its own record says it (`ProjectApi.head`: its15- * last landing, or its initializer's first push); for a project whose16- * record names none, at its repo's refs: the mirror ref the platform moves17- * after each of its own landings, or `main`.18- *19- * What a landed commit holds never changes, so each project's skill (or20- * that it has none) is kept by its landed SHA, in the isolate's code cache21- * and in the code store (`<repo>/skill/v<SKILL_VERSION>/<sha>`): a request22- * costs one record read per project, and a file read only for a project23- * whose main moved.24- */1 import { describedIn } from "@repo/agent-kit/generated-file";2 import {3 contributeDescription,4 contributeSkillName,25 unmodified lines30 Schema,31 } from "effect";32 import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";33 58-/** Where the index and the skills are served. */34 const ROOT = "/.well-known/agent-skills";35 36 const INDEX = `${ROOT}/index.json`;37 63-/** The suffix every contribute skill's name ends in (`contributeSkillName`). */38 const CONTRIBUTE = "-contribute";39 66-/** How many projects are read at once while the index is made. */40 const FAN_OUT = 8;41 69-/** A minute: the index changes only when a landing changes a skill. */42 const BRIEFLY = "public, max-age=60";43 44 const notFound = () =>45 new Response(null, { headers: { "cache-control": "no-store" }, status: 404 });46 75-/** Where a project's skill is served, path-absolute. */47 const skillUrl = (project: ProjectName) =>48 `${ROOT}/${contributeSkillName(project)}/SKILL.md`;49 50 const mainRef = RefName.make("refs/heads/main");51 81-/** UTF-8 that round-trips byte for byte, so the digest is the file's. */52+// UTF-8 that round-trips byte for byte, so the digest is the file's.53 const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });54 84-/** The bytes as text, unless they are not UTF-8. */55 const textOf = (bytes: Uint8Array) =>56 Option.liftThrowable(() => utf8.decode(bytes))();57 88-/** The kept skill's version, in its key: it moves when what is kept changes. */58 const SKILL_VERSION = 1;59 91-/** A project's skill at a landed commit as the store keeps it: its text, or none. */60 const KeptSkill = Schema.fromJsonString(61 Schema.Struct({ content: Schema.optionalKey(Schema.String) })62 );63 64 const decodeKept = Schema.decodeOption(KeptSkill);65 66 const encodeKept = Schema.encodeEffect(KeptSkill);67 100-/**101- * Where `project`'s main landed: as its record says, or, for a project whose102- * record names none (or that the platform never made), at its repo's refs.103- */68 const landedOf = (69 project: ProjectName70 ): Effect.Effect<Option.Option<CommitSha>, never, Projects | RepoHost> =>71 Effect.gen(function* () {18 unmodified lines90 Option.fromUndefinedOr(refs.get(mainRef))91 );92 }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeedNone));93 130-/** `project`'s skill file at `landed`, read from its repo: none when it has none. */94 const skillAt = (project: ProjectName, landed: CommitSha) =>95 Effect.gen(function* () {96 const host = yield* RepoHost;97 const [path] = contributeSkillPaths(project);6 unmodified lines104 105 return Option.flatMap(bytes, textOf);106 }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeedNone));107 145-/**146- * `project`'s skill at `landed`: the isolate's cache first, then the code147- * store, then its repo, whose answer is kept in both. A store that fails is148- * a miss.149- */108 const keptSkillAt = (project: ProjectName, landed: CommitSha) =>109 Effect.gen(function* () {110 const cache = yield* CodeCache;111 const store = yield* CodeStore;26 unmodified lines138 })139 );140 });141 184-/**185- * A project's contribute skill as it landed: none for a project never186- * made, one with no landing, or one whose landed tree has no such file.187- */142 const landedSkill = (143 project: ProjectName144 ): Effect.Effect<Option.Option<string>, never, Projects | RepoHost> =>145 Effect.flatMap(landedOf(project), (landed) =>4 unmodified lines150 );151 152 const decodeKey = Schema.decodeUnknownOption(ProjectKey);153 200-/** The index: every listed project's landed skill, by name. */154 const index = Effect.gen(function* () {155 const listed = yield* FrontPage.use((frontPage) => frontPage.projects());156 157 const projects = Arr.sort(24 unmodified lines182 headers: { "cache-control": BRIEFLY, "content-type": "application/json" },183 });184 });185 233-/** The project whose skill `name` names: `<key>-contribute`. */186 const projectNamed = (name: string) =>187 name.endsWith(CONTRIBUTE)188 ? Option.flatMap(decodeKey(name.slice(0, -CONTRIBUTE.length)), nameOfKey)189 : Option.none();190 239-/** One project's skill file, as it landed. */191 const skillFile = (project: ProjectName) =>192 Effect.map(193 landedSkill(project),194 Option.match({7 unmodified lines202 }),203 })204 );205 255-/**256- * `/.well-known/agent-skills/*`: the index, or one project's skill; 404257- * for any other path under it, read from the request's own path, however258- * the router matched it.259- */206 export const agentSkills = (207 request: Request208 ): Effect.Effect<Response, never, FrontPage | Projects | RepoHost> => {209 const { pathname } = new URL(request.url);19 unmodified lines229 230 return skillFile(project.value);231 };232 287-/** The skills are only read here; anything but GET and HEAD is refused. */233 const readOnly = HttpServerResponse.empty({234 headers: { allow: "GET, HEAD", "cache-control": "no-store" },235 status: 405,236 });237 293-/**294- * `/.well-known/agent-skills/*` on the platform's router, for anyone: GET295- * and HEAD (the router serves HEAD as GET, without the body) through296- * `agentSkills`, with the front page, the projects, the repos and the297- * code reads' cache and store taken once when the router is built (the298- * last two are `Context.Reference`s: without them every request reads299- * every file).300- */238 export const agentSkillRoutes: Layer.Layer<239 never,240 never,241 HttpRouter.HttpRouter | FrontPage | Projects | RepoHost22 unmodified linesmodified:apps/platform/src/worker.ts+2 added-10 removed
9 unmodified lines10 export { Answer } from "./workflows/answer.ts";11 12 export { OnPush } from "./workflows/on-push.ts";13 14-// Built once per isolate, at module load, touching no binding: the env is15-// decoded once for the fetch handler, and both the platform's services and16-// sign-in's are made from what it decoded to; an env that fails to decode17-// fails them both, on use. Both routers are built here, before any request,18-// and their builds await nothing (`router-build.ts` refuses one that does),19-// so no request ever waits on a build another request started. (Each20-// Project DO and Workflow decodes the same env the same way, for its own21-// ports.)14+// Built at module load, touching no binding. Both routers' builds await nothing, so15+// no request ever waits on a build another request started.16 const config = Effect.runSyncExit(decodeEnv(env));17 18 const platform = serve(Layer.unwrap(Effect.map(config, platformOf)));19 26-// OAuth and sign-in answer their own paths and hand the rest to the27-// platform.20 const { handler } = oauthProvider(21 Layer.unwrap(Effect.map(config, signInServices)),22 (request) => platform.handler(request)23 );2 unmodified linesmodified:apps/platform/test/visibility/admission.test.ts-53 removed
1-/**2- * Admission of held-back checks over the platform's Node world:3- * a maintainer's push to datekit's maintainers layer,4- * through the gateway, starts an admission run of the `Answer`5- * Workflow (tagged `Admission`); its steps ask the project for the plan,6- * run each changed area's checks on main three times and on the known-bad7- * tree the layer's manifest names, and hand the area bits back. An8- * admitted push moves the layer's landed SHA under a new commitment, and9- * a claim opened afterwards is pinned to it; a refused one leaves the10- * suite that was there pinned.11- *12- * The world is the core loop's (`world.ts`) with the cartridge's gateway13- * (`LayerGateLive`) and project state (`ProjectVisibilityLive`) plugged in14- * over a private namespace of its own; admissions are queued instead of15- * started, and the test runs each over the Worker's ports with the steps16- * kept in memory, as the `Answer` Workflow runs one over the engine's. The17- * DO's rules read datekit's visibility config from its `visibility.ts`.18- * The Checker answers lane jobs from a script, and held-back jobs with area19- * bits: green on main, red on the known-bad tree.20- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import type { RepoHost } from "@repo/artifacts/repo-host";4 import { Brand } from "@repo/brand";35 unmodified lines40 const maintainers = LayerName.make("maintainers");41 42 const layerRepo = RepoName.make(`${keyOf(project)}--${maintainers}`);43 64-/** The people: datekit's maker, who decides it and keeps its layer, and two contributors. */44 const tokens = {45 bram: "bram-admission-token-0123456789abcdef",46 "ines-v": "ines-v-admission-token-0123456789abcdef",47 okonkwo: "okonkwo-admission-token-0123456789abcdef",48 } as const;49 50 const sdk = `${Brand.cliPackage}/rules`;51 73-/** datekit as ines-v first pushes it, its visibility config with it. */52 const start = {53 [`${Brand.configDir}/project.ts`]: [54 `import { kinds, project } from "${sdk}";`,55 ``,3 unmodified lines59 `});`,60 ``,61 ].join("\n"),62 [`${Brand.configDir}/vouched.td`]: "bram\nines-v\nokonkwo\n",85- // Admission on: three runs green on main, red on one known-bad tree.63 [`${Brand.configDir}/visibility.ts`]: [64 `import { flows, layer, sealedChecks, visibility } from "${sdk}";`,65 ``,66 `export default visibility({`,17 unmodified lines84 'export const svg = (title: string) => title.replaceAll("<", "<");\n',85 "src/parser/week.ts": "export const week = (iso: string) => 1;\n",86 };87 111-/** A held-back check, by path: its area and its source. */88 const checkFile = (area: string, name: string, body: string) =>89 [90 `checks/held-back/${area}/${name}.test.ts`,91 `import { it } from "bun:test";\n\nit(${JSON.stringify(body)}, () => {});\n`,6 unmodified lines98 const isoWeek = checkFile("parser", "iso-week", "reads week dates");99 100 const ordinal = checkFile("parser", "iso-week", "reads ordinal dates");101 126-/** The layer's files: its checks, and the manifest naming each with its clause and `knownBad`. */102 const layerTree = (103 checks: readonly (readonly [string, string])[],104 knownBad: readonly CommitSha[]105 ) => ({13 unmodified lines119 layer: maintainers,120 })}\n`,121 });122 148-/** The public file the known-bad commit breaks: export without its escaping. */123 const unescaped = "src/export/svg.ts";124 125 const redThenGreen = LaneName.make("redThenGreen");126 153-/** An ask on datekit, red first: its file and its check. */127 const askFiles = (ask: AskId) =>128 Array.make(129 {130 content: [13 unmodified lines144 path: RepoPath.make(`test/${ask}.test.ts`),145 }146 );147 175-/**176- * The world: datekit made and landed by ines-v with its visibility config,177- * the cartridge plugged in, the Checker scripted, and every admission the178- * project starts queued for the test.179- */148 const admissionWorld = Effect.gen(function* () {149 const jobs: CheckJob[] = [];150 const script = new Map<string, readonly LaneResult[]>();151 const queued: AdmissionParams[] = [];152 const stores: RepoHost["Service"][] = [];153 const captured: Context.Context<WorkerPorts>[] = [];186- // How many runs on main each area had, and which of them come back red.154 const mainRuns = new Map<string, number>();155 const redOnMain = new Set<string>();156 190- /** The area bits of a held-back job: red on the known-bad tree, green on main unless told otherwise. */157 const bitsOf = (part: HeldBackPart): readonly HeldBackResult[] =>158 part.areas.map((area) => {159 const total = part.runs.filter((run) => run.area === area).length;160 const knownBad = part.files.some(({ path }) => path === unescaped);85 unmodified lines246 const ports = yield* Effect.fromNullishOr(captured[0]);247 const ines = yield* world.person("ines-v");248 const bram = yield* world.person("bram");249 284- // ines-v makes datekit and lands its first tree, visibility config and all.250 const made = yield* ines.rpc.initProject({ project });251 const home = yield* ines.git.clone(made.remote);252 253 yield* ines.git.commit(home, "Start datekit", start);254 yield* ines.git.ok(home, "push", "--quiet", "origin", "HEAD:main");255 291- /** One admission, run over the Worker's ports and `steps`, as the Workflow runs it. */256 const admit = (params: AdmissionParams, steps: Layer.Layer<StepRunner>) =>257 admissionSteps(params).pipe(258 Effect.provide(Layer.merge(Layer.succeedContext(ports), steps))259 );260 297- /** Opens `ask`, red first on main, as ines-v. */261 const openAsk = (ask: AskId) =>262 Effect.gen(function* () {263 const files = askFiles(ask);264 42 unmodified lines307 308 const layerUrl = `${world.origin}/${project}--maintainers.git`;309 const outside = yield* fs.makeTempDirectoryScoped();310 348- // The known-bad commit, on a branch of its own in the layer: the349- // public file it breaks, at main's path.311 const bad = `${outside}/known-bad`;312 313 yield* ines.git.ok(314 outside,14 unmodified lines329 layerUrl,330 "HEAD:refs/heads/known-bad"331 );332 372- // The suite: two export checks and one parser check, each citing a373- // clause, and the known-bad commit named in the manifest.333 const suite = `${outside}/suite`;334 335 yield* ines.git.ok(336 outside,10 unmodified lines347 );348 349 yield* ines.git.ok(suite, "push", "--quiet", layerUrl, "HEAD:main");350 392- // The push started one admission, of its head, against main as it stands.351 const started = [...queued];352 353 const main = CommitSha.make(354 (yield* ines.git.ok(42 unmodified lines397 );398 399 const rootOf = (area: string) => roots.get(AreaName.make(area));400 443- // What the Checker was given: each area's checks on main, three444- // times, and on main with the known-bad file laid over it; no445- // public lane, no layer repo named.401 const ran = jobs.map((job) => ({402 areas: job.heldBack?.areas,403 at: job.at,404 files: job.heldBack?.files.map(({ path }) => path),3 unmodified lines408 409 const exportFiles = [csvQuote[0], svgTitle[0]];410 411 expect({457- // In any order: the runs go to the Checker four at a time.412 ran: Array.sort(413 ran.map(({ areas, files }) => JSON.stringify([areas, files])),414 Order.String415 ),37 unmodified lines453 }),454 ],455 });456 503- // A claim opened now is pinned to the admitted suite.457 const firstAsk = AskId.make("keep-titles");458 459 yield* openAsk(firstAsk);460 1 unmodified line462 ask: firstAsk,463 project,464 });465 513- // The parser check rewritten; this time it is red on its second run on main.466 const second = yield* ines.git.commit(467 suite,468 "Read ordinal dates",469 layerTree([svgTitle, csvQuote, ordinal], [knownBad])470 );471 472 const jobsBefore = jobs.length;473 522- // The parser's fifth run on main: the second of this push's three.474 redOnMain.add("parser on main #5");475 476 yield* ines.git.ok(suite, "push", "--quiet", layerUrl, "HEAD:main");477 yield* admit(11 unmodified lines489 });490 491 const after = yield* world.rpc("anonymous").ledger({ project });492 542- // The first admission run again, over its own steps: it reads543- // back what it recorded and changes nothing; run afresh, it finds544- // nothing left to admit.493 yield* admit(494 AdmissionParams.make({ head: first, layer: maintainers, project }),495 steps496 );16 unmodified lines513 bramsSuite: true,514 inesSuite: bramsClaim.suite,515 queued: [first, second],516 replayed: ledger.entries.length,569- // Only the rewritten area runs again.517 secondRuns: [["parser"], ["parser"], ["parser"], ["parser"]],518 });519 }).pipe(Effect.provide(NodeServices.layer)),520 60_0002 unmodified linesmodified:apps/platform/test/visibility/env-values.test.ts-34 removed
1-/**2- * Write-only values over the platform's surfaces: the handler the3- * Worker serves, its Project DOs in process on SQLite, the platform's ports4- * in memory, and the visibility cartridge's env as the Worker composes it5- * (the real parser and the WebCrypto vault) under the fake env's test6- * `MASTER_KEY`. A decider sets datekit's token over `/rpc` with their7- * token; anyone reads the env shape over `/rpc` and sees who set it and8- * when. The value is in no response body, no log line and no event, and9- * the row the DO keeps is sealed. These tests live in the cartridge and go10- * with it.11- */1 import { SqliteClient } from "@effect/sql-sqlite-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Fetch } from "@repo/artifacts/fetch";4 import { RefName, RepoHost } from "@repo/artifacts/repo-host";59 unmodified lines64 const repo = RepoName.make(keyOf(project));65 66 const token = EnvKey.make("SENTRY_AUTH_TOKEN");67 79-/** What ines-v sets: a token-shaped value of 24 characters. */68 const value = "sntrys_eyJpYXQiOjE3MjA5X";69 82-/** Each person's platform token, as `SESSION_TOKENS` lists them. */70 const tokens = {71 bram: "bram-env-values-token-0123456789abcdef",72 "ines-v": "ines-env-values-token-0123456789abcdef",73 } as const;74 88-/** datekit's `.env.schema` cut to its header, one public item and its one sensitive item. */75 const datekitSchema = [76 "# @currentEnv=$APP_ENV",77 "# @defaultRequired=infer @defaultSensitive=false",78 "# ---",7 unmodified lines86 "SENTRY_AUTH_TOKEN=",87 "",88 ].join("\n");89 104-/** A `RulesEvaluator` that evaluates nothing: at any commit, the scenario's policy. */90 const rules = Layer.effect(91 RulesEvaluator,92 Effect.gen(function* () {93 const finishers = yield* Finishers;10 unmodified lines104 });105 })106 ).pipe(Layer.provide(FinishersFromChecks));107 123-/** Every line logged, with its annotations and cause, as text. */108 const keeper = (logged: string[]) =>109 Logger.make(({ cause, fiber, message }) => {110 logged.push(111 [3 unmodified lines115 ].join(" ")116 );117 });118 135-/** What the world kept: every response body and log line, and each DO's SQLite. */119 interface Kept {120 readonly bodies: string[];121 readonly logged: string[];122 readonly databases: Map<string, Context.Context<SqlClient>>;123 }124 142-/**143- * The platform's handler over its ports, the env cartridge composed with144- * the real parser and the fake env's master key, its Project DOs in145- * process; datekit made by ines-v and its first commit landed.146- */125 const world = (kept: Kept) =>126 Effect.gen(function* () {149- // The stage's env as the Worker decodes it, with the people's tokens.127 const env = {128 ...fakeEnv(),129 SESSION_TOKENS: JSON.stringify(130 Object.fromEntries(54 unmodified lines185 );186 187 yield* Effect.addFinalizer(() => Effect.promise(dispose));188 212- // The handler logs through the keeper too, as the Worker's would.189 const logging = yield* Layer.build(190 Logger.layer([keeper(kept.logged)], { mergeWithExisting: true })191 );192 217- // ines-v makes datekit and pushes its first commit, its env schema in it.193 const ines = Person.make({ handle: Handle.make("ines-v") });194 const api = yield* Context.get(ports, Projects).create(project);195 const client = yield* gitClient(memoryFs());196 19 unmodified lines216 .pipe(Effect.orDie);217 218 yield* api.recordFirstPush(ines, first);219 245- // Every request reaches the handler as a fetch would send it, and246- // every response body is kept as it went out.220 const context = yield* Effect.context();221 222 const fetch: typeof globalThis.fetch = (input, init) =>223 Effect.runPromiseWith(context)(9 unmodified lines233 return response;234 })235 );236 264- /** A client of the contracts over `/rpc`, as `who` (a bearer) or as anyone. */237 return (who?: keyof typeof tokens) =>238 RpcClient.make(Contracts).pipe(239 Effect.provide(240 RpcClient.layerProtocolHttp({10 unmodified lines251 )252 );253 }).pipe(Effect.orDie);254 283-/** The project's rows and events as its DO's SQLite keeps them. */255 const storedIn = (kept: Kept) =>256 Effect.gen(function* () {257 const sql = yield* Effect.orDie(258 Effect.fromNullishOr(kept.databases.get(project))10 unmodified lines269 )270 );271 });272 302-/**303- * bram (no decider) tries to set datekit's token, then ines-v sets it, both304- * over `/rpc` with their tokens; then anyone reads the env shape. Every305- * response body, log line and stored row and event is kept.306- */273 const settingTheToken = (kept: Kept) =>274 Effect.gen(function* () {275 const clientAs = yield* world(kept);276 const ines = yield* clientAs("ines-v");97 unmodified linesmodified:apps/platform/test/visibility/held-back.fixtures.ts-54 removed
1-/**2- * datekit with a maintainers layer whose sealed suite has areas `export`3- * (two checks) and `parser` (one), over the Answer Workflow's world4- * (`../workflows/answer.fixtures.ts`): the project service sees fakes of5- * the two visibility ports (the cartridge's own are tested on their own),6- * the Checker answers held-back jobs from a script of failing areas, the7- * layer's repo lives in a `LayerRepos` of its own, and the cartridge's8- * landing guards (`src/visibility/held-back.ts`) are plugged in over them.9- *10- * The fakes keep to the ports' contracts: the visibility port pins every11- * claim to one suite, reads the suite's files for its job, counts failed12- * held-back runs per claim (the third is `AttemptsExhausted`) and gives13- * the trailer's value when every area passed; the env port keeps a value14- * `setEnv` stored, and scans with the leak scanner.15- */1 import { RefName, RepoHost } from "@repo/artifacts/repo-host";2 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";4 import { CheckRunner } from "@repo/checks/check-runner";50 unmodified lines55 export const exportArea = AreaName.make("export");56 57 export const parserArea = AreaName.make("parser");58 74-/** One sealed check, as the layer holds it. */59 interface SealedFile {60 readonly area: AreaName;61 readonly path: RepoPath;62 readonly content: string;63 }64 81-/** The suite: two checks in `export`, one in `parser`. */65 export const sealedFiles: readonly SealedFile[] = [66 {67 area: exportArea,68 content:12 unmodified lines81 path: RepoPath.make("checks/held-back/parser/week.test.ts"),82 },83 ];84 102-/** The layer commit the suite is pinned at. */85 export const layerAt = CommitSha.make("e".repeat(40));86 105-/** The suite's root, as 612 publishes it. */87 export const suiteRoot = SuiteRoot.make(`sha256:${"3f".repeat(32)}`);88 108-/** The run block's `test` with each sealed check's path filled. */89 const testCommand = (path: RepoPath) => `bun test ${path}`;90 91 const encoder = new TextEncoder();92 113-/** The job `heldBackJob` gives for every pinned claim. */93 export const heldBackJob: HeldBackJob = {94 areas: [exportArea, parserArea],95 at: layerAt,96 files: sealedFiles.map(({ area, content, path }) => ({8 unmodified lines105 })),106 suite: suiteRoot,107 };108 130-/** How many failed held-back runs a claim may have before its area is spent. */109 const ATTEMPTS = 3;110 111 const isoWeek = "2026-W41";112 135-/** When a spent area opens again: the fake's week ends on its Monday. */113 export const resetsAt = DateTime.makeUnsafe("2026-10-12T00:00:00Z");114 115 const attemptsOn = (116 rows: readonly AttemptRow[],8 unmodified lines125 row.area === area126 )127 .reduce((sum, row) => sum + row.count, 0);128 152-// ------------------------------------------------------------------ the fakes153-154-/** What a test changes in the fakes as it goes, and reads back. */129 export class Sealed extends Context.Service<130 Sealed,131 {158- /** Whether the Checker cannot run the next held-back jobs at all. */132 readonly blocked: Ref.Ref<boolean>;160- /** The areas whose held-back checks fail in the next held-back jobs. */133 readonly failing: Ref.Ref<ReadonlySet<AreaName>>;162- /** Every held-back job the Checker was given, in order. */134 readonly jobs: Ref.Ref<readonly CheckJob[]>;164- /** The layers' path set (its files), as stage 1 and the landing guards read it. */135 readonly layerPaths: Ref.Ref<ReadonlySet<RepoPath>>;166- /** How often the visibility port judged a held-back run. */136 readonly judged: Effect.Effect<number>;137 }138 >()("test/Sealed") {}139 171-/**172- * The visibility port over the test's handle: one layer, `maintainers`,173- * read and written by the deciders (alice); every claim pinned to174- * `suiteRoot`; the suite's job; failed runs counted per claim in175- * `attempts` rows, the third one spent.176- */140 const visibilityOver = (141 sealed: Sealed["Service"],142 judged: { count: number }143 ): VisibilityPort => ({62 unmodified lines206 ? new Set([maintainers])207 : new Set(),208 });209 247-/** What the fake env keeps of a value: the value itself, which only a fake may. */210 const KeptValue = Schema.Struct({ fake: Schema.String });211 250-/**251- * The env port: a decider's value kept as it was given (only a fake keeps252- * a value it could read back), and the leak scanner over every kept value.253- */212 const envPort: EnvPort = {213 ...noEnv,214 scan: (scanned, snapshot) =>215 Effect.sync(() => {28 unmodified lines244 },245 }),246 };247 290-/** The two ports' fakes, and the test's handle on them. */248 const fakes = Layer.effectContext(249 Effect.gen(function* () {250 const judged = { count: 0 };251 13 unmodified lines265 );266 })267 );268 312-/** One area's bits in a held-back job: one check fails in each failing area. */269 const bitsOf = (270 job: HeldBackJob,271 failing: ReadonlySet<AreaName>272 ): readonly HeldBackResult[] =>7 unmodified lines280 total,281 };282 });283 328-/**329- * The world's Checker, with held-back jobs answered from the failing areas330- * and recorded; every other job goes to the scripted one.331- */284 const sealedChecker = Layer.effect(285 CheckRunner,286 Effect.gen(function* () {287 const inner = yield* CheckRunner;24 unmodified lines312 );313 314 const mainRef = RefName.make("refs/heads/main");315 364-/** The layer's repo, holding the suite on `main`, in a private host of its own. */316 const layerRepos = Layer.effect(317 LayerRepos,318 Effect.gen(function* () {319 const host = yield* RepoHost;16 unmodified lines336 return LayerRepos.of(host);337 })338 ).pipe(Layer.provide(Layer.fresh(RepoHostMemory)));339 389-/**390- * The Answer Workflow's world with the visibility cartridge's parts391- * plugged in over it: the fakes, the layer's repo, the sealed Checker and392- * the cartridge's landing guards.393- */340 export const sealedWorld = (given: Policy) =>341 Layer.mergeAll(sealedChecker, LandingGuardsLive).pipe(342 Layer.provideMerge(worldWith(given)),343 Layer.provideMerge(layerRepos),2 unmodified linesmodified:apps/platform/test/visibility/held-back.test.ts-50 removed
1-/**2- * The `Answer` Workflow judged by the sealed suite its claim was pinned to:3- * its held-back step, the landing4- * guards before any check, and the scans that keep a stored value out of5- * what leaves a run, over the Answer Workflow's world with the visibility6- * cartridge's parts plugged in (`held-back.fixtures.ts`).7- *8- * A stored value in an added file is quarantined as a refusal that names9- * nothing (`VerifierBlocked`) until the project service can open the10- * `SecretInTree` decision that should hold it for the deciders.11- */1 import { describe, expect, it } from "@effect/vitest";2 import { ObjectId, RepoHost, RepoNotFound } from "@repo/artifacts/repo-host";3 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4 import { CheckAt, CheckRunner, shaOf } from "@repo/checks/check-runner";89 unmodified lines94 sealedWorld,95 suiteRoot,96 } from "./held-back.fixtures.ts";97 109-/** The program run for `answer` over a fresh step record. */98 const run = (answer: Admitted) =>99 Effect.flatMap(memoSteps(), (steps) =>100 runAnswer({ project, requestId: answer.requestId }).pipe(101 Effect.provide(steps)102 )103 );104 117-/** Every public lane on `at` passes: the ask's check and every project lane. */105 const allGreen = (at: CheckAt) =>106 Effect.andThen(107 scriptProjectLanes(at, { result: "passed" }),108 Checker.use((script) => script.script(at, askLane, [{ result: "passed" }]))109 );110 124-/** The held-back checks of `areas` fail from now on, one check in each. */111 const failing = (...areas: readonly (typeof exportArea)[]) =>112 Sealed.use(({ failing: next }) => Ref.set(next, new Set(areas)));113 114 const decodeVerdict = Schema.decodeUnknownEffect(115 Schema.fromJsonString(Verdict)116 );117 132-/** The verdict note on `commit` in `at`, read as plain git finds it. */118 const noteIn = (at: RepoName, commit: CommitSha) =>119 Effect.gen(function* () {120 const host = yield* RepoHost;121 const tip = (yield* host.refs(at).pipe(Effect.orDie)).get(notesRef);24 unmodified lines146 yield* decodeVerdict(new TextDecoder().decode(blob)).pipe(Effect.orDie)147 );148 });149 165-/** The verdict note on `head` in bob's fork. */150 const noteOn = (head: CommitSha) => noteIn(bobFork, head);151 168-/**169- * bob's next answer on the same claim: `files` pushed on his fork's last170- * head, and submitted; its merged tree's public lanes all pass.171- */152 const answerAgain = (answer: Admitted, files: Files) =>153 Effect.gen(function* () {154 const head = yield* Pusher.use((each) =>155 each.push(bobFork, Option.some(answer.head), files)91 unmodified lines247 );248 249 expect(outcomes).toStrictEqual([outcomes[0], outcomes[0], outcomes[0]]);250 expect(yield* Sealed.use(({ judged }) => judged)).toBe(1);271- // The next answer on the claim is its second failure, not its third.251 expect(yield* run(second)).toStrictEqual(252 Outcome.cases.Refused.make({253 refusals: [254 new HeldBackFailed({ area: exportArea, suite: suiteRoot }),174 unmodified lines429 repo: bobFork,430 suite: suiteRoot,431 },432 ]);454- // No layer repo, route or token: only the files, read by the platform.433 expect(JSON.stringify(jobs)).not.toContain(maintainers);434 }).pipe(Effect.provide(sealedWorld(policy)))435 );436 });437 460-/** A file in the ask's territory holding a sealed check's bytes, blob for blob. */438 const copied = RepoPath.make("packages/parser/src/copied.ts");439 440 const copiedContent = sealedFiles[0]?.content ?? "";441 465-/** Every Checker job on the merged tree `at`. */442 const jobsOn = (at: CheckAt) =>443 Checker.use(({ jobs }) =>444 Effect.map(jobs, (all) => all.filter((job) => shaOf(job.at) === shaOf(at)))445 );446 447 const encoder = new TextEncoder();448 473-/** The git id of a blob holding `text`. */449 const blobIdOf = (text: string) =>450 Effect.map(451 Effect.promise(() =>452 crypto.subtle.digest(8 unmodified lines461 .join("")462 )463 );464 490-/**491- * The world's host, with each blob read from bob's fork going through492- * `read` (given the read the host would make), as the Workflow sees it.493- */465 const forkReads = (466 read: (467 id: ObjectId,468 given: Effect.Effect<Option.Option<Uint8Array>, RepoNotFound>196 unmodified lines665 }).pipe(Effect.provide(sealedWorld(policy)))666 );667 });668 698-/** datekit's `SENTRY_AUTH_TOKEN`, as a decider stores it. */669 const sentry = EnvKey.make("SENTRY_AUTH_TOKEN");670 671 const token = "sntrys_0a1b2c3d4e5f6a7b8c9d";672 703-/** alice stores datekit's Sentry token: a write-only value. */673 const stored = (answer: Admitted) =>674 answer.api675 .setEnv(alice, { key: sentry, value: Redacted.make(token) })676 .pipe(Effect.orDie);677 709-/**710- * Everything the answerer reads of their answer, as text: its status, its711- * verdict, the note on its head, and the project's events.712- */678 const answererReads = (answer: Admitted) =>679 Effect.gen(function* () {680 const status = yield* answer.api.status(bob);681 const verdict = yield* verdictOf(answer.api);34 unmodified lines716 717 const outcome = yield* run(answer);718 const read = yield* answererReads(answer);719 755- // Until the project can open the deciders' `SecretInTree` decision756- // (and the answer waits, `AwaitingDecision`), a refusal naming nothing.720 expect(outcome).toStrictEqual(721 Outcome.cases.Refused.make({ refusals: [new VerifierBlocked({})] })722 );723 expect(yield* jobsOn(answer.merged)).toStrictEqual([]);69 unmodified lines793 sealedWorld({794 ...policy,795 run: {796 ...policy.run,834- // A decider's slip: the value in a lane's command, which every verdict quotes.797 checks: {798 ...policy.run.checks,799 [LaneName.make("unit")]: Command.make(800 `SENTRY_AUTH_TOKEN=${token} bun run test`5 unmodified lines806 )807 );808 });809 848-/** A fork the adapter clones from, in a store of its own. */810 const sandboxFork = RepoName.make("alice__datekit--parse-iso--bob");811 851-/** A held-back job, as the held-back step sends it: the suite alone. */812 const sealedJob: CheckJob = {813 at: CheckAt.cases.Tree.make({ tree: TreeSha.make("5".repeat(40)) }),814 heldBack: heldBackJob,815 lanes: [],3 unmodified lines819 repo: sandboxFork,820 run: policy.run,821 };822 863-/** The bits a sandbox that ran `job`'s suite reports when every check passed. */823 const allPassed: readonly HeldBackResult[] = [824 { area: exportArea, passed: 2, suite: suiteRoot, total: 2 },825 { area: parserArea, passed: 1, suite: suiteRoot, total: 1 },826 ];827 869-/**870- * `CheckRunnerSandbox` over a sandbox that answers every job with871- * `heldBack` as its area bits, and keeps each wire it was sent, encoded.872- */828 const overSandbox = (heldBack: readonly HeldBackResult[]) =>829 Effect.gen(function* () {830 const sent: (typeof CheckWire.Encoded)[] = [];831 80 unmodified lines912 const wrong: readonly {913 readonly job: CheckJob;914 readonly bits: readonly HeldBackResult[];915 }[] = [961- // An area left out.916 { bits: allPassed.slice(0, 1), job: sealedJob },963- // Another suite's bits.917 {918 bits: allPassed.map((each) => ({ ...each, suite: otherSuite })),919 job: sealedJob,920 },968- // More checks passed than the area has.921 {922 bits: allPassed.map((each) => ({923 ...each,924 passed: each.total + 1,925 })),926 job: sealedJob,927 },976- // A count that is not the area's.928 {929 bits: allPassed.map((each) => ({ ...each, total: each.total + 1 })),930 job: sealedJob,931 },981- // Bits for a job that sent no suite.932 { bits: allPassed, job: Struct.omit(sealedJob, ["heldBack"]) },933 ];934 935 const outcomes = yield* Effect.forEach(wrong, ({ bits, job }) =>13 unmodified linesmodified:apps/platform/test/visibility/layer-gateway.test.ts-64 removed
1-/**2- * A project's layer repos through the platform's own fetch handler, with3- * real git: the maintainers clone their layer4- * and push to it, a contributor is turned away with one line git prints,5- * every read is logged with who and which commit, and a push to a public6- * fork cannot carry a layer's path, without telling a contributor which of7- * their paths collided.8- *9- * The world is the core loop's (`world.ts`) with the cartridge's gateway side10- * plugged into the Worker (`LayerGateLive`), its public repos and the private11- * namespace's each a store of bare repos behind `git http-backend`. Each12- * Project DO runs on a stand-in for the cartridge's `ProjectVisibility`:13- * datekit declares one layer, `maintainers`, which its deciders ines-v and14- * okonkwo read and push to, holding one sealed check; it writes down every read15- * and every layer push the DO hears.16- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { RefName, RepoName } from "@repo/artifacts/repo-host";4 import type { RepoHost } from "@repo/artifacts/repo-host";43 unmodified lines48 const project = ProjectName.make("ines-v/datekit");49 50 const maintainers = LayerName.make("maintainers");51 68-/** The layer's repo, in the private namespace. */52 const layerRepo = RepoName.make(`${keyOf(project)}--${maintainers}`);53 71-/** The sealed check the layer holds. */54 const sealed = "checks/held-back/export/escape.test.ts";55 56 const mainRef = "refs/heads/main";57 76-/** The people: two deciders who maintain the layer, and a contributor. */58 const tokens = {59 bram: "bram-layer-gateway-token-0123456789abcdef",60 "ines-v": "ines-v-layer-gateway-token-0123456789abcdef",61 okonkwo: "okonkwo-layer-gateway-token-0123456789abcdef",62 } as const;63 83-/** The layer's readers and writers: datekit's deciders. */64 const keepers: ReadonlySet<string> = new Set(["ines-v", "okonkwo"]);65 66 const keeps = (who: Principal) =>67 Principal.guards.Person(who) && keepers.has(who.handle);68 89-/** What the stand-in for the visibility port heard from the DO. */69 interface Heard {91- /** Each time the DO was asked how far someone reaches into a layer. */70 readonly asks: LayerName[];71 readonly reads: {72 readonly handle: Handle;73 readonly layer: LayerName;5 unmodified lines79 readonly pusher: Handle;80 }[];81 }82 105-/**106- * The cartridge's `ProjectVisibility`, as far as the gateway reaches it:107- * datekit's one layer, its keepers' access, its one path, and every read and108- * layer push written down.109- */83 const visibilityHeard = (heard: Heard): VisibilityPort => ({84 ...noVisibility,85 access: (who, layer) => {86 heard.asks.push(layer);8 unmodified lines95 heard.pushes.push({ head, layer, pusher });96 97 return noPlan;98 }),126- // The layer's row, as the visibility port writes it once the config lands:127- // stage 1 names exact paths only to someone who reads every layer kept.99 onPolicy: () =>100 Effect.succeed({101 effects: [],102 writes: { layers: [{ name: maintainers, repo: layerRepo }] },5 unmodified lines108 return {};109 },110 });111 141-/** The private namespace's store, writing down every token secret it mints. */112 const minting = (113 host: RepoHost["Service"],114 minted: string[]115 ): RepoHost["Service"] => ({7 unmodified lines123 });124 125 const sdk = `${Brand.cliPackage}/rules`;126 157-/** datekit as ines-v first pushes it. */127 const start = {128 [`${Brand.configDir}/project.ts`]: [129 `import { kinds, project } from "${sdk}";`,130 ``,8 unmodified lines139 "package.json": '{ "name": "ines-v/datekit", "private": true }\n',140 "src/export.ts": "export const toIso = (date: Date) => date.toISOString();\n",141 };142 174-/** An ask whose territory holds both the code and its checks. */143 const askFiles = (ask: AskId) =>144 Array.make(145 {146 content: [21 unmodified lines168 path: RepoPath.make(`test/${ask}.test.ts`),169 }170 );171 204-/** The lines git printed from the server, less the padding git adds. */172 const remoteLines = (stderr: string) =>173 stderr174 .split("\n")175 .filter((line) => line.startsWith("remote: "))176 .map((line) => line.trimEnd());177 211-/** What `protocol/render` says of `refusals`, as git prints it. */178 const rendered = (refusals: Parameters<typeof explain>[0]) =>179 explain(refusals).map((line) => `remote: ${line}`);180 215-/** The answer both pushes carry: a fix, and a copy of the layer's sealed check. */181 const escaping = {182 [sealed]: "it('escapes', () => {});\n",183 "src/fix.ts": "export const fix = true;\n",184 };185 221-/**222- * The world, with datekit landed by ines-v and its maintainers layer's223- * repo in the private namespace holding the sealed check: the people, what224- * the stand-in port heard, every token the private store minted, and every225- * git run a test keeps for the leak check.226- */186 const layerWorld = Effect.gen(function* () {187 const fs = yield* FileSystem.FileSystem;188 const heard: Heard = { asks: [], pushes: [], reads: [] };189 const minted: string[] = [];21 unmodified lines211 const layers = yield* Effect.fromNullishOr(stores[0]);212 const ines = yield* world.person("ines-v");213 const bram = yield* world.person("bram");214 256- /** git, kept for the check that no token reached anyone. */215 const kept = <R>(ran: Effect.Effect<Ran, never, R>) =>216 Effect.tap(ran, (output) =>217 Effect.sync(() => {218 outputs.push(output);219 })220 );221 264- // ines-v makes datekit and lands its first tree.222 const made = yield* ines.rpc.initProject({ project });223 const home = yield* ines.git.clone(made.remote);224 225 yield* ines.git.commit(home, "Start datekit", start);226 yield* kept(ines.git.push(home));227 271- // The layer's repo in the private namespace, holding its sealed check,272- // pushed there as the cartridge's provisioning would leave it.228 yield* layers.create(layerRepo);229 230 const seed = yield* fs.makeTempDirectoryScoped();231 42 unmodified lines274 } = yield* layerWorld;275 276 const layerUrl = `${world.origin}/${project}--maintainers.git`;277 323- // Asked with no credential, the layer asks for one; a name that is324- // no declared layer is no repo at all.278 const ask = (repo: string, token?: string) =>279 world.fetch(280 new Request(281 `${world.origin}/${repo}.git/info/refs?service=git-upload-pack`,14 unmodified lines296 `${project}--secrets`,297 tokens.bram298 );299 347- // A keeper's request asks the project once: whether the layer is348- // declared and how far she reaches, in one answer.300 const asksBefore = heard.asks.length;301 const keeper = yield* ask(`${project}--maintainers`, tokens["ines-v"]);302 303 expect({13 unmodified lines317 undeclared: 404,318 undeclaredSignedIn: 404,319 });320 370- // ines-v clones the layer and gets its files; her read is logged371- // once, with the commit she read. bram is told why he can't; with372- // no credential at all, git is asked for one.321 const outside = yield* fs.makeTempDirectoryScoped();322 const clone = `${outside}/ines-v`;323 324 const inesClone = yield* kept(41 unmodified lines366 ],367 readsAfterRefusals: readsAfterClone,368 });369 422- // ines-v pushes a new sealed check: the layer's main moves, and the423- // project hears the head. bram's push is turned away.370 const next = yield* ines.git.commit(clone, "Seal a second check", {371 "checks/held-back/export/offset.test.ts":372 "it('offsets', () => {});\n",373 });36 unmodified lines410 { head: next, layer: maintainers, pusher: Handle.make("ines-v") },411 ],412 });413 468- // Two asks, red first, so bram and ines-v each hold a claim.414 const asks = [415 AskId.make("keep-offset"),416 AskId.make("keep-zone"),417 ] as const;23 unmodified lines441 ask: second,442 project,443 });444 500- // bram's fork push carries the layer's path: he reads no layer, so501- // he hears every path he added, and his fork keeps the commit.445 const bramsWork = yield* bram.git.clone(bramsClaim.remote);446 447 const bramsHead = yield* bram.git.commit(448 bramsWork,2 unmodified lines451 );452 453 const bramsAnswer = yield* kept(bram.git.push(bramsWork));454 512- // ines-v reads the layer, so she hears only the path that collides.455 const inesWork = yield* ines.git.clone(inesClaim.remote);456 457 yield* ines.git.commit(inesWork, "Fix, and copy", escaping);458 26 unmodified lines485 ]),486 },487 });488 547- // The layer's tokens stayed with the platform: the private store548- // minted some, and none reached git's output or a log line.489 const logged = yield* world.logged;490 491 const said = [492 ...outputs.flatMap(({ stderr, stdout }) => [stderr, stdout]),17 unmodified lines510 const { heard, ines, layered, remote, seed, world } = yield* layerWorld;511 const layerUrl = `${world.origin}/${project}--maintainers.git`;512 513 // Forty more branches: a clone that wants them all sends git's574- // request gzipped (above 1 KiB).514 const branches = Array.makeBy(40, (n) => `refs/heads/area-${n}`);515 516 yield* ines.git.ok(517 seed,60 unmodified lines578 expect(gate === noLayers).toBeFalsy();579 })580 );581 643- // Found live: the gate's upstream was memoized with the public644- // namespace's, so every layer clone on a stage answered "no repo".582 it.effect(583 "the stage's layer gate asks the private namespace for a layer repo, never the public one",584 () =>585 Effect.gen(function* () {8 unmodified lines594 })595 )596 ).pipe(Effect.provide(workerPorts(config)), Effect.exit);597 661- // Both fake bindings refuse every call, each naming itself.598 expect(Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "").toContain(599 "a test touched ARTIFACTS_PRIVATE."600 );601 })2 unmodified linesmodified:apps/platform/test/visibility/ledger-mcp.test.ts-21 removed
1-/**2- * The public ledger over MCP (`ledger.get` is the `ledger` contract's tool):3- * over the platform's Node world (the core loop's world) with the visibility4- * cartridge's project state composed into every Project DO, a `tools/call` of5- * `ledger` for datekit returns the ledger as structured content, the same6- * ledger the RPC `ledger` gives, and both are the cartridge's.7- *8- * datekit's config folder here has no `visibility.ts`, so its ledger is the9- * Open one, the same as the neutral port's: the test watches the10- * cartridge's port answer.11- */1 import { describe, expect, it } from "@effect/vitest";2 import { Fetch } from "@repo/artifacts/fetch";3 import { RepoHost } from "@repo/artifacts/repo-host";4 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";13 unmodified lines18 import { coreLoopWorld } from "../world.ts";19 20 const project = ProjectName.make("dora/datekit");21 33-/** datekit as dora first pushes it: one source file and the config folder. */22 const start = {23 [`${Brand.configDir}/project.ts`]: [24 `import { kinds, project } from "${Brand.cliPackage}/rules";`,25 ``,6 unmodified lines32 "package.json": '{ "name": "dora/datekit", "private": true }\n',33 "src/week.ts": "export const week = (iso: string) => 0;\n",34 };35 48-/** A `Fetch` that nothing here may call. */36 const noFetch = Layer.succeed(Fetch, untouchable<Fetch["Service"]>("Fetch"));37 51-/** The cartridge's project state for the world's stage, over a private namespace of its own. */38 const stateOfStage = Layer.unwrap(39 Effect.gen(function* () {40 const host = yield* Effect.provide(41 Effect.service(RepoHost),10 unmodified lines52 return stateLive(config).pipe(Layer.provide(noFetch));53 })54 );55 70-/**71- * That state as the Worker plugs it into each Project DO, watched: each72- * project the cartridge's port is asked the ledger of joins `asked`.73- */56 const cartridge = (asked: ProjectName[]) =>57 Layer.effect(58 ProjectVisibility,59 Effect.gen(function* () {13 unmodified lines73 ).pipe(Layer.provide(stateOfStage));74 75 const version = "2026-07-28";76 95-/** A stateless 2026-07-28 `tools/call` over MCP's HTTP transport, as the operator. */77 const ledgerCall = new Request(`${origin}/mcp`, {78 body: JSON.stringify({79 id: 1,80 jsonrpc: "2.0",21 unmodified lines102 },103 method: "POST",104 });105 125-/** A tools/call reply: whether it failed, and its structured content. */106 const Reply = Schema.fromJsonString(107 Schema.Struct({108 result: Schema.Struct({109 isError: Schema.Boolean,1 unmodified line111 }),112 })113 );114 135-/** The last JSON-RPC message in a reply, which is plain JSON or an event stream. */115 const replyOf = (response: Response) =>116 Effect.promise(() => response.text()).pipe(117 Effect.map((text) =>118 response.headers.get("content-type")?.includes("text/event-stream") ===55 unmodified linesmodified:apps/platform/test/visibility/live.test.ts-9 removed
1-/**2- * The visibility cartridge as the platform plugs it in: over the3- * stage's ports, built from the decoded env without touching a binding, and4- * reaching the private namespace through `ARTIFACTS_PRIVATE` alone. These5- * tests live in the cartridge and go with it.6- */1 import { describe, expect, it } from "@effect/vitest";2 import { Fetch } from "@repo/artifacts/fetch";3 import { RepoHost } from "@repo/artifacts/repo-host";4 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";7 unmodified lines12 import { workerPorts } from "../../src/ports.ts";13 import { layerRepos } from "../../src/visibility/layer-repos.ts";14 import { fakeEnv } from "../fake-env.ts";15 22-/** Where each fake binding says its repos' git lives. */16 const remoteBase = "https://artifacts.test";17 25-/** A repo host of its own, empty. */18 const freshHost = Effect.provide(Effect.service(RepoHost), RepoHostMemory);19 28-/** A `Fetch` that nothing here may call. */20 const noFetch = Layer.succeed(Fetch, untouchable<Fetch["Service"]>("Fetch"));21 22 describe("the visibility cartridge, plugged in", () => {23 it.effect(43 unmodified linesmodified:apps/platform/test/visibility/posture-listing.test.ts-13 removed
1-/**2- * The project list's posture over the platform's Node world (the core3- * loop's world) with the visibility cartridge's project state composed4- * into every Project DO, as `ledger-mcp.test.ts` composes it. datekit's5- * first push carries a `visibility.ts` that declares sealed checks: a first6- * config stands at once and writes no `PostureChanged` row, so the7- * projection still lists datekit as `open`, the row D1 holds on demo. The8- * list reads datekit's posture from datekit's own ledger, so the badge and9- * the ledger say the same.10- */1 import { describe, expect, it } from "@effect/vitest";2 import { Fetch } from "@repo/artifacts/fetch";3 import { RepoHost } from "@repo/artifacts/repo-host";4 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";12 unmodified lines17 const project = ProjectName.make("dora/datekit");18 19 const sdk = `${Brand.cliPackage}/rules`;20 31-/** datekit as dora first pushes it, its visibility config declaring sealed checks. */21 const start = {22 [`${Brand.configDir}/project.ts`]: [23 `import { kinds, project } from "${sdk}";`,24 ``,24 unmodified lines49 "package.json": '{ "name": "dora/datekit", "private": true }\n',50 "src/parse.ts": "export const parse = (iso: string) => 0;\n",51 };52 64-/** A `Fetch` that nothing here may call. */53 const noFetch = Layer.succeed(Fetch, untouchable<Fetch["Service"]>("Fetch"));54 67-/** The cartridge's project state for the world's stage, over a private namespace of its own. */55 const cartridge = Layer.unwrap(56 Effect.gen(function* () {57 const host = yield* Effect.provide(58 Effect.service(RepoHost),46 unmodified linesmodified:apps/platform/test/visibility/serve-cartridge-world.ts+2 added-56 removed
1-/**2- * The core loop's world (`../world.ts`) with the visibility cartridge3- * plugged in as the Worker plugs it, as a process of its own that keeps4- * what it served: `bun apps/platform/test/visibility/serve-cartridge-world.ts`5- * prints one JSON line, `{"origin":"http://127.0.0.1:<port>","kept":"http://127.0.0.1:<port>"}`,6- * once it serves, and serves until its stdin ends (the process that started7- * it closed it, or died).8- *9- * - `origin` is the platform's fetch handler, as `../serve-world.ts` serves10- * it; every body it answers with JSON or an event stream (the contracts'11- * at `/rpc`, MCP's at `/mcp`) is kept as it went out.12- * - `kept` is a test's window on the world: `POST /settle` carries every13- * queued answer run (`world.settle`), and `GET /kept?project=<name>`14- * answers, as JSON, every body kept, every line logged (the handler's and15- * each Project DO's, with their annotations), every job the Checker was16- * given, and the project's Durable Object store as its rows encode: its17- * `env_values` and ledger rows and its event log.18- *19- * The cartridge is the Worker's (`../../src/visibility/live.ts`) for the20- * world's stage, over the fake env's test `MASTER_KEY`, with the world's21- * second store of bare repos as the private namespace; each Project DO22- * gets its project state and its env. The Checker keeps each job and fails23- * every lane the same way, so an ask's check is red first and an answer's24- * checks run (and fail): what a job carries is what a test reads. Beside25- * dora, alice and bob, the people in `WORLD_SESSIONS` (a JSON object from26- * token to handle, as `SESSION_TOKENS` is) may call.27- *28- * A process, not an import: apps never import apps, and the CLI's29- * end-to-end `env set` test runs it. It lives in the cartridge30- * and goes with it. The Worker's modules import `cloudflare:workers`, which31- * `../world-process.ts` serves from the shim before this file loads them,32- * as it does for `../serve-world.ts`.33- */1+// Run as a process: prints `{"origin":…,"kept":…}` once it serves, and serves until2+// its stdin ends.3 import { NodeRuntime, NodeServices } from "@effect/platform-node";4 import type { RepoHost } from "@repo/artifacts/repo-host";5 import { CheckJob, CheckRunner } from "@repo/checks/check-runner";6 import type { CheckRun } from "@repo/checks/check-runner";17 unmodified lines24 25 import { shimWorkers, worldSessions } from "../world-process.ts";26 import type { PlugIn } from "../world.ts";27 59-/**60- * The Checker: each job kept as it came, and every lane failed the same61- * way, a count lane printing nothing.62- */28 const keepingChecker = (jobs: CheckJob[]): Layer.Layer<CheckRunner> =>29 Layer.succeed(30 CheckRunner,31 CheckRunner.of({21 unmodified lines53 }),54 })55 );56 92-/**93- * Each job as the Checker got it, encoded by its fields alone: without94- * `CheckJob`'s rule that only landed code carries values, so a job that95- * breaks the rule still shows, values and all, for a test to refuse.96- */57 const encodeJobs = Schema.encodeEffect(58 Schema.Array(Schema.Struct(CheckJob.fields))59 );60 4 unmodified lines65 ledger: Schema.Array(LedgerRow),66 })67 );68 109-/**110- * Whether a response is a contract's or a tool's reply: JSON, or an MCP111- * event stream. Git's packs and adverts are not, and neither is NDJSON,112- * which only a framed `watch` gets and which never ends while it follows.113- */69 const isReply = (response: Response) => {70 const type = response.headers.get("content-type") ?? "";71 72 return (25 unmodified lines98 import("../../src/visibility/env.ts"),99 ])100 );101 147- /** The world's stage config, the second store standing in for the private namespace. */102 const configOver = (aside: RepoHost["Service"]) =>103 decodeEnv(withPrivateNamespace(fakeEnv(), aside)).pipe(Effect.orDie);104 151- /**152- * The cartridge as the Worker plugs it: whole over the Worker's ports, and153- * the project service's part of it (its visibility state and its env)154- * over each Project DO's, which reach no other DO.155- */105 const plugIn = (aside: RepoHost["Service"]): PlugIn => ({106 project: Layer.unwrap(107 Effect.map(configOver(aside), (config) =>108 Layer.mergeAll(stateLive(config), envLive(config))3 unmodified lines112 });113 114 const jobs: CheckJob[] = [];115 const bodies: string[] = [];167- // What the Project DOs and everything else in this process logged.116 const lines: string[] = [];117 170- // Each line as its message and its annotations, both JSON.118 const keeper = Logger.make(({ fiber, message }) => {119 const annotations = fiber.getRef(References.CurrentLogAnnotations);120 121 lines.push(`${JSON.stringify(message)} ${JSON.stringify(annotations)}`);16 unmodified lines138 return response;139 })140 );141 195- /** What the world kept, for `project`'s store. */142 const keptFor = (project: ProjectName) =>143 Effect.gen(function* () {144 const logged = yield* world.logged;145 const stored = yield* world.stored(project);55 unmodified linesmodified:apps/platform/test/visibility/state.test.ts-13 removed
1-/**2- * The cartridge's project state as the platform provides it: salts3- * from WebCrypto's randomness, 32 fresh bytes each, and admissions started4- * as runs of the `Answer` Workflow, one instance per project, layer and5- * head, so a start the outbox runs again finds the first run.6- */1 import { describe, expect, it } from "@effect/vitest";2 import { AdmissionStarts, SaltSource } from "@repo/project/visibility/state";3 import { CommitSha, LayerName, ProjectName } from "@repo/protocol/ids";4 import { Cause, Effect, Exit, Schema } from "effect";27 unmodified lines32 const head = CommitSha.make("a".repeat(40));33 34 const later = CommitSha.make("b".repeat(40));35 42-/**43- * The `Answer` Workflow's binding, in memory: `create` refuses an id it44- * holds, as Workflows do, and `get` finds only the ids it holds. With45- * `down`, both refuse everything.46- */36 const workflowOf = (down = false) => {37 const created: { readonly id: string; readonly params: unknown }[] = [];38 39 const workflow: AdmissionWorkflow = {16 unmodified lines56 };57 58 const decodeParams = Schema.decodeUnknownSync(AdmissionParams);59 71-/** The admission of `at` to datekit's maintainers layer. */60 const admissionOf = (at: CommitSha) =>61 AdmissionParams.make({ head: at, layer: maintainers, project: datekit });62 63 const start = (input: { readonly head: CommitSha }) =>11 unmodified lines75 yield* start({ head });76 yield* start({ head });77 yield* start({ head: later });78 91- // What each instance was created with, read back as the Workflow reads it.79 expect(80 created.map(({ id, params: given }) => ({81 id,82 params: decodeParams(given),25 unmodified linesmodified:apps/platform/test/workflows/answer.fixtures.ts-87 removed
1-/**2- * One project with one answer admitted and waiting for its Answer Workflow,3- * over in-process adapters: `RepoHostMemory`, the isomorphic-git `Lander`4- * over it (recorded, and able to answer `RepoBusy`), a `CheckRunner`5- * scripted per (tree or commit, lane), a `RulesEvaluator` that returns the6- * scenario's policy, `ProjectsMemory`, `EvidenceStoreMemory`, and an7- * `AnswerRuns` that only records which runs the project started: the test8- * runs the Workflow's program itself.9- *10- * The Lander is the isomorphic-git one, not the scripted `/memory` one,11- * because the project reads real commits on the way to an admitted answer12- * (the ask's files composed onto main, the answer's diff for the gate), and13- * a re-merge after main moved must produce a real tree.14- */1 import { RefName, RepoHost } from "@repo/artifacts/repo-host";2 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";4 import { CheckAt, CheckRunner, shaOf } from "@repo/checks/check-runner";45 unmodified lines50 withVouches(["bob"]),51 withAsk({ id: "parse-iso", territory: "packages/parser" })52 );53 68-/**69- * The scenario's policy, with a `unit` lane beside its cheap `lint` and70- * `types` lanes: the checks stage runs the ask's own check and `unit`.71- */54 export const policy: Policy = Schema.decodeSync(Policy)({55 ...Schema.encodeSync(Policy)(scenario.policy),56 run: {57 checks: {24 unmodified lines82 const ask: Ask = Option.getOrThrow(83 Array.findFirst(policy.asks, ({ id }) => id === parseIso)84 );85 104-/** The lane the ask's own check reports as. */86 export const askLane = LaneName.make("redThenGreen");87 107-/** Where the ask's check lives: red on main, green once answered. */88 export const checkPath = CheckSpec.guards.RedThenGreen(ask.check)89 ? ask.check.path90 : RepoPath.make("packages/parser/test/parse-iso.test.ts");91 112-/** The file the answer changes. */92 export const parsePath = RepoPath.make("packages/parser/src/parse.ts");93 115-/** A file the answer leaves alone. */94 export const lexPath = RepoPath.make("packages/lexer/src/lex.ts");95 118-/** The project as alice first pushes it. */96 const start: Files = [97 ["package.json", '{ "name": "datekit", "workspaces": ["packages/*"] }\n'],98 [lexPath, "export const lex = (s) => s.split(' ');\n"],99 [parsePath, "export const parse = (s) => ({});\n"],100 ];101 125-/** The ask's own files: its file in the config folder, and its check. */102 const askFiles = Array.make(103 { content: `export default "${parseIso}";\n`, path: ask.file },104 {105 content: [8 unmodified lines114 path: checkPath,115 }116 );117 142-/** Main once the ask opened: alice's files and the ask's. */118 export const openedFiles: Files = [119 ...start,120 ...askFiles.map(({ content, path }) => [path, content] as const),121 ];122 148-/** `files` with `path` holding `content`, added or replaced. */123 export const changed = (files: Files, path: string, content: string): Files => [124 ...files.filter(([each]) => each !== path),125 [path, content],126 ];127 154-/** Bob's answer: main once the ask opened, with `parse` fixed. */128 export const fixed = changed(129 openedFiles,130 parsePath,131 "export const parse = (s) => ({ year: 2026 });\n"132 );133 161-// ------------------------------------------------------------------ checker162-163-/** One scripted run of a lane: how it ends, and its failure's signature. */134 export interface ScriptedRun {135 readonly result: LaneOutcome;166- /** What the failing test said, as `checks.classify` writes a signature. */136 readonly signature?: string;137 }138 170-/** The scripted Checker's script, and every job it was given. */139 export class Checker extends Context.Service<140 Checker,141 {142 readonly script: (4 unmodified lines147 readonly jobs: Effect.Effect<readonly CheckJob[]>;148 }149 >()("test/Checker") {}150 183-/** Where a lane's script lives: `<tree or commit sha>:<lane>`. */151 const keyOf = (at: CheckAt, lane: LaneName) => `${shaOf(at)}:${lane}`;152 186-/**187- * `CheckRunner` scripted per (tree or commit, lane), as `CheckRunnerMemory`188- * is, with each failure's signature too: each key serves its runs in order,189- * then the last again. A job with a lane nobody scripted is190- * `VerifierBlocked`, as a Checker that cannot run is.191- */153 const checker = Layer.effectContext(154 Effect.gen(function* () {155 const scripts = yield* Ref.make<156 ReadonlyMap<string, readonly ScriptedRun[]>72 unmodified lines229 );230 })231 );232 272-// ------------------------------------------------------------------- lander273-274-/** What the Lander was asked, and a way to make its next lands busy. */233 export class LanderCalls extends Context.Service<234 LanderCalls,235 {278- /** Every job the project and the program gave the Lander, in order. */236 readonly jobs: Effect.Effect<readonly LanderJob[]>;280- /** The next `count` lands find the repo busy, and push nothing. */237 readonly busyFor: (count: number) => Effect.Effect<void>;282- /** The merge a test scripts the checks for, unrecorded. */238 readonly preview: (job: MergeJob) => Effect.Effect<CheckAt>;239 }240 >()("test/LanderCalls") {}241 287-/** The isomorphic-git Lander, recorded, whose lands a test can make busy. */242 const lander = Layer.effectContext(243 Effect.gen(function* () {244 const inner = yield* Lander;245 const jobs = yield* Ref.make<readonly LanderJob[]>([]);32 unmodified lines278 );279 })280 ).pipe(Layer.provide(LanderIsogit));281 328-// ------------------------------------------------------------- the project329-330-/**331- * A `RulesEvaluator` that evaluates nothing: at any commit it returns332- * `given`, holding the asks whose files the commit's config folder has, and333- * the judge closure `checks` derives.334- */282 const rulesOf = (given: Policy) =>283 Layer.effect(284 RulesEvaluator,285 Effect.gen(function* () {11 unmodified lines297 });298 })299 ).pipe(Layer.provide(FinishersFromChecks));300 354-/** Which answer runs the project started: the program runs them in the test. */301 export class Started extends Context.Service<302 Started,303 { readonly ids: Effect.Effect<readonly RequestId[]> }304 >()("test/Started") {}5 unmodified lines310 }).pipe(Context.add(Started, { ids: Ref.get(ids) }))311 )312 );313 368-/** One `advanceAnswer` call the project took, as the program made it. */314 export interface Advance {315 readonly command: LandingCommand;316 readonly report: AnswerReport | undefined;317 }318 374-/** Every `advanceAnswer` call made through `Projects`, in order. */319 export class DoCalls extends Context.Service<320 DoCalls,321 { readonly advances: Effect.Effect<readonly Advance[]> }322 >()("test/DoCalls") {}323 380-/** `ProjectsMemory`, with every `advanceAnswer` through it recorded. */324 const projects = Layer.effectContext(325 Effect.gen(function* () {326 const inner = yield* Projects;327 const advances = yield* Ref.make<readonly Advance[]>([]);13 unmodified lines341 }).pipe(Context.add(DoCalls, { advances: Ref.get(advances) }));342 })343 ).pipe(Layer.provide(ProjectsMemory));344 402-/** Commits made the way git would make them, pushed to a repo's `main`. */345 export class Pusher extends Context.Service<346 Pusher,347 {348 readonly push: (28 unmodified lines377 });378 })379 );380 439-/**440- * Every port the program runs on, and what the test reads back, with the441- * project's rules evaluating to `given`; fresh per build.442- */381 export const worldWith = (given: Policy) =>382 Layer.mergeAll(projects, pusher).pipe(383 Layer.provideMerge(384 Layer.mergeAll(8 unmodified lines393 Layer.provideMerge(lander),394 Layer.provideMerge(RepoHostMemory)395 );396 459-/** The world over the scenario's policy. */397 export const world = worldWith(policy);398 462-/** The scenario's policy, with answers to a `fix` ask landing only once a decider finishes them. */399 export const finishRequired: Policy = {400 ...policy,401 kinds: policy.kinds.map((kind) =>402 kind.name === "fix" ? { ...kind, finish: "required" } : kind403 ),404 };405 470-/** Where canonical `main` stands now. */406 export const mainTip = Effect.gen(function* () {407 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);408 409 return LandedSha.make(410 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))411 );412 });413 479-/** Every lane but the ask's, scripted the same on `at`. */414 export const scriptProjectLanes = (at: CheckAt, run: ScriptedRun) =>415 Checker.use((script) =>416 Effect.forEach(417 Object.keys(policy.run.checks),1 unmodified line419 { discard: true }420 )421 );422 489-/** One answer admitted: its project, its request, where it was made and checked. */423 export interface Admitted {424 readonly api: ProjectApi;425 readonly requestId: RequestId;493- /** The main the answer was made on: the ask's opening landing. */426 readonly opened: LandedSha;427 readonly head: CommitSha;496- /** The tree the answer merges onto `opened` as. */428 readonly merged: CheckAt;429 }430 500-/**501- * The project made, its ask opened red first, bob's claim, his push of502- * `files` to his fork and his answer admitted: its run started, and no step503- * of it run yet. The checks on the merged tree are left to the test.504- */431 export const admitted = (files: Files = fixed) =>432 Effect.gen(function* () {433 yield* advanceTo("2026-10-07T12:00:00Z");434 58 unmodified lines493 requestId: receipt.requestId,494 } satisfies Admitted;495 });496 571-/** Main moved by a push the platform did not make: `files` on top of `from`. */497 export const mainMoved = (from: LandedSha, files: Files) =>498 Effect.map(499 Pusher.use((each) => each.push(repo, Option.some(from), files)),500 (sha) => LandedSha.make(sha)501 );502 578-/** The verdict the project keeps on bob's answer. */503 export const verdictOf = (api: ProjectApi) =>504 Effect.map(api.verdict(bob, { ask: parseIso }), ({ verdict }) =>505 Option.fromUndefinedOr(verdict)506 ).pipe(Effect.orDie);507 584-// -------------------------------------------------------------------- steps585-586-/** Every step the program asked for, by name, in order, and each one's retries. */508 export class StepLog extends Context.Service<509 StepLog,510 {511 readonly names: Effect.Effect<readonly string[]>;512 readonly retries: Effect.Effect<ReadonlyMap<string, StepRetry>>;513 }514 >()("test/StepLog") {}515 595-/** More steps than any run of the scenario asks for: past it, the program ran away. */516 const runaway = 64;517 598-/**599- * `inner`'s steps, each name the program asks for recorded, replays600- * included. With `twice`, a step that runs runs its effect twice and keeps601- * the second value, as an engine does when it retries a step whose first602- * run took effect before its record was written. A program that asks for603- * more than `runaway` steps dies there, so a test fails rather than hangs.604- */518 export const logged = (519 inner: Layer.Layer<StepRunner>,520 options: { readonly twice?: boolean } = {}521 ) =>44 unmodified linesmodified:apps/platform/test/workflows/answer.test.tsnot shown
Its text is not shown, modified.
modified:apps/platform/test/workflows/draft.test.tsnot shown
Its text is not shown, modified.
modified:apps/platform/test/workflows/on-push.test.tsnot shown
Its text is not shown, modified.
modified:apps/platform/test/accounts.test.ts-7 removed
17 unmodified lines18 19 const find = (handle: string) =>20 Accounts.use((accounts) => accounts.find(Handle.make(handle)));21 22-/**23- * What every `Accounts` adapter must do, written against the port: `/memory`24- * and the D1 adapter (over sqlite-node, with the migration D1 applies) run25- * it on every `verify`.26- */22 const describeAccounts = (adapter: string, layer: Layer.Layer<Accounts>) => {23 describe(`Accounts over ${adapter}`, () => {24 it.effect("finds an account by its handle, in any case", () =>25 Effect.gen(function* () {71 unmodified lines97 };98 99 describeAccounts("memory", Layer.fresh(AccountsMemory.layer));100 106-/** The accounts table, as `wrangler d1 migrations apply` makes it. */101 const migrated = Layer.effectDiscard(102 Effect.gen(function* () {103 const fs = yield* FileSystem.FileSystem;104 6 unmodified lines111 yield* sql.unsafe(ddl);112 })113 ).pipe(Layer.orDie, Layer.provide(NodeServices.layer));114 121-/** A fresh in-memory database, migrated, each time the layer is built. */115 const database = migrated.pipe(116 Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),117 Layer.orDie118 );2 unmodified linesmodified:apps/platform/test/answer-runs.test.ts+2 added-6 removed
1-/**2- * The instance ids the `Answer` Workflow's runs take. The engine refuses an3- * id past 100 characters, and starting an id that exists changes nothing, so4- * two runs that must both happen need two ids however long their names are.5- */1+// The engine refuses an instance id past 100 characters, and starting an id that2+// exists changes nothing.3 import { describe, expect, it } from "@effect/vitest";4 import { CommitSha, LayerName, ProjectName } from "@repo/protocol/ids";5 6 import { AdmissionParams, admissionId } from "../src/answer-runs.ts";7 11-/** What the engine takes as an instance id. */8 const INSTANCE_ID = /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/u;9 10 describe("an admission's instance", () => {11 it("is the project, layer and head, whole, when they fit", () => {34 unmodified linesmodified:apps/platform/test/auth.test.ts-15 removed
38 unmodified lines39 const metadataUrl = `${origin}/.well-known/oauth-protected-resource`;40 41 const isPerson = Schema.is(Person);42 43-/**44- * The platform before any project exists, except that `listAsks` and45- * `status` answer, each noting who called it in `seen`.46- */43 const noting = (seen: Ref.Ref<readonly Principal[]>) => {44 const note = Effect.flatMap(Effect.service(CurrentPrincipal), (principal) =>45 Ref.update(seen, (principals) => [...principals, principal])46 );16 unmodified lines63 )64 );65 };66 71-/** Sessions that count every token they are asked to verify. */67 const counting = Effect.gen(function* () {68 const verified = yield* Ref.make(0);69 70 const inner = MemorySessions.service({ [aliceToken]: alice });11 unmodified lines82 83 return { layer, verified };84 });85 91-/** The challenge a 401 carries, and its status. */86 const challengeOf = (response: Response) => ({87 challenge: response.headers.get("www-authenticate"),88 status: response.status,89 });47 unmodified lines137 expect(responses.map(({ status }) => status)).not.toContain(401);138 })139 );140 147- // The gateway answers git's paths itself: an unknown credential there is148- // its 401, with git's Basic challenge, never this one.141 it.effect(142 "leaves git's paths to the gateway, whatever credential they carry",143 () =>144 Effect.gen(function* () {116 unmodified lines261 });262 })263 );264 273- // RFC 6750 §3.1: a credential of another scheme is not an invalid bearer274- // token, so the challenge carries no error code.265 it.effect(266 "turns away an RPC call whose credential is not a bearer token, with no error code",267 () =>268 Effect.gen(function* () {16 unmodified lines285 });286 })287 );288 299- // The router matches `/mcp` however its path is spelled, so the 401 must300- // hold wherever the router sends a request to MCP.289 it.effect("asks for a credential however MCP's path is spelled", () =>290 Effect.gen(function* () {291 const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));292 35 unmodified lines328 })329 )330 );331 344- // An RPC message may carry headers of its own (here, alice's token,345- // encoded as the wire carries it); only the HTTP request's346- // credential says who is calling.332 const message = `{"_tag":"Request","id":"1","tag":"status","payload":{},"headers":[["authorization","Bearer ${aliceToken}"]]}`;333 334 const status = (headers: Readonly<Record<string, string>>) =>335 fetch(149 unmodified linesmodified:apps/platform/test/bindings.test.ts+2 added-47 removed
1-/**2- * The binding fence: what each Worker's code reads from its env and what its3- * `wrangler.jsonc` declares are one set, at the top level and in every4- * stage, since Wrangler does not inherit bindings into an environment. A5- * binding added or removed on one side only fails here; one removed from6- * `wrangler.jsonc` and regenerated (`bun run types`) also fails `typecheck`7- * where the code reads it.8- */1 import { NodeServices } from "@effect/platform-node";2 import type { D1Client } from "@effect/sql-d1";3 import { describe, expect, expectTypeOf, it } from "@effect/vitest";4 import type { RepoHostBinding } from "@repo/artifacts/repo-host/binding";25 unmodified lines30 PlatformVars,31 } from "../src/platform.ts";32 import type { PlatformConfig } from "../src/platform.ts";33 42-/** The offset just past the string literal that opens at `start`. */34 const stringEnd = (text: string, start: number) => {35 let at = start + 1;36 37 while (at < text.length && text[at] !== '"') {2 unmodified lines40 41 return at + 1;42 };43 53-/** Where the token that opens at `at` ends: a string literal, a comment, or one character. */44 const tokenEnd = (text: string, at: number) => {45 if (text[at] === '"') {46 return stringEnd(text, at);47 }12 unmodified lines60 61 return at + 1;62 };63 74-/** `text` cut into its tokens, so nothing below looks inside a string. */64 const tokensOf = (text: string) => {65 const tokens: string[] = [];66 let at = 0;67 9 unmodified lines77 78 const isComment = (token: string) =>79 token.startsWith("//") || token.startsWith("/*");80 92-/** Whether the next token after `tokens[index]` that is not whitespace closes a bracket. */81 const closesAfter = (tokens: readonly string[], index: number) => {82 const next = tokens.find((token, at) => at > index && token.trim() !== "");83 84 return next === "]" || next === "}";85 };86 99-/**100- * `text` (JSONC, as `wrangler.jsonc` is written) as JSON: its comments101- * dropped first, then each comma that only a closing bracket follows, so a102- * comment between the two hides nothing; every string is kept whole.103- */87 const fromJsonc = (text: string) => {88 const tokens = tokensOf(text).filter((token) => !isComment(token));89 90 return tokens4 unmodified lines95 const Bound = Schema.Array(Schema.Struct({ binding: Schema.String }));96 97 const Named = Schema.Array(Schema.Struct({ name: Schema.String }));98 116-/**117- * The keys of a block that declare bindings, each with how it names them.118- * A key that is neither here nor in `NOT_BINDINGS` fails the test: whoever119- * adds it says which it is.120- */99 const BindingKinds = Schema.Struct({100 ai: Schema.optionalKey(Schema.Struct({ binding: Schema.String })),101 artifacts: Schema.optionalKey(Bound),102 d1_databases: Schema.optionalKey(Bound),5 unmodified lines108 worker_loaders: Schema.optionalKey(Bound),109 workflows: Schema.optionalKey(Bound),110 });111 134-/** The keys a block may carry that declare no binding. */112 const NOT_BINDINGS: ReadonlySet<string> = new Set([113 "$schema",114 "compatibility_date",115 "compatibility_flags",11 unmodified lines127 "vars",128 "workers_dev",129 ]);130 154-/** One block: the top level, or a stage's. */131 const Block = Schema.Struct({132 ...BindingKinds.fields,133 secrets: Schema.optionalKey(134 Schema.Struct({ required: Schema.Array(Schema.String) })135 ),136 vars: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),137 });138 163-/** A config as data: its blocks are read one key at a time. */139 const Raw = Schema.Record(Schema.String, Schema.Unknown);140 166-/** A config's text, JSONC as `wrangler.jsonc` is written, as data. */141 const readJsonc = (text: string) =>142 Schema.decodeEffect(Schema.fromJsonString(Raw))(fromJsonc(text));143 170-/** The stages' blocks, by name. */144 const Staged = Schema.Struct({145 env: Schema.optionalKey(Schema.Record(Schema.String, Raw)),146 });147 1 unmodified line149 150 const sorted = (names: Iterable<string>) =>151 Array.sort(Array.fromIterable(names), Order.String);152 180-/** What one block declares: its bindings, vars and required secrets, each sorted, and any key this test does not know. */153 const declaredIn = (raw: typeof Raw.Type) =>154 Effect.map(decodeBlock(raw), (block) => ({155 bindings: sorted([156 ...(block.ai === undefined ? [] : [block.ai.binding]),13 unmodified lines170 ),171 vars: sorted(Object.keys(block.vars ?? {})),172 }));173 202-/** A file of this repo, by its path from `apps/platform`. */174 const fileText = (path: string) =>175 Effect.flatMap(FileSystem.FileSystem, (fs) =>176 fs.readFileString(new URL(`../${path}`, import.meta.url).pathname)177 );178 208-/** What the `wrangler.jsonc` at `path` declares, by block: `top` and each stage. */179 const wranglerOf = (path: string) =>180 Effect.gen(function* () {181 const raw = yield* Effect.flatMap(fileText(path), readJsonc);182 9 unmodified lines192 193 return { stages: Object.fromEntries(stages), top };194 });195 226-/** A struct's keys, sorted; `required` leaves out its optional ones. */196 const keysOf = (197 fields: Readonly<Record<string, Schema.Top>>,198 only: "all" | "required" = "all"199 ) =>4 unmodified lines204 )205 .map(([key]) => key)206 );207 239-/**240- * The bindings the sandbox's code reads from its env: the members of the241- * `Env` its generated types give it (`bun run types` in `apps/sandbox`).242- */208 const sandboxEnvKeys = Effect.map(209 fileText("../sandbox/worker-configuration.d.ts"),210 (text) =>211 sorted(5 unmodified lines217 ].flatMap(({ groups }) => (groups?.key === undefined ? [] : [groups.key]))218 )219 );220 256-/** The draft limit as a stage's block declares it, under its own namespace id. */221 const draftLimit = (id: string) => ({222 name: "DRAFT_LIMIT",223 namespace_id: id,224 simple: { limit: 2, period: 60 },46 unmodified lines271 });272 }).pipe(Effect.provide(NodeServices.layer))273 );274 311- // The drafter's model and the web's address are stage vars, and drafts312- // are rate-limited apart from proposals, two a minute per person.275 it.effect(276 "set the drafter's model, the web's address and the draft limit in every stage",277 () =>278 Effect.gen(function* () {58 unmodified lines337 });338 }).pipe(Effect.provide(NodeServices.layer))339 );340 379- // Code history persists in a bucket of its own per stage, named for its380- // job, never another job's bucket.341 it.effect("keep code history in each block's own code-cache bucket", () =>342 Effect.gen(function* () {343 const raw = yield* Effect.flatMap(fileText("wrangler.jsonc"), readJsonc);344 33 unmodified lines378 >379 >();380 });381 422- // Principle 7: this Worker binds the private namespace deliberately;423- // the web's `test/env.test-d.ts` holds that no public-serving Worker does.382 it("hold the private namespace, decoded as the public one is", () => {383 expectTypeOf<Env>().toHaveProperty("ARTIFACTS_PRIVATE");384 expectTypeOf<PlatformConfig["ARTIFACTS_PRIVATE"]>().toEqualTypeOf<385 Env["ARTIFACTS_PRIVATE"]41 unmodified lines427 >();428 });429 430 it("type the sandbox service binding by the entrypoint the platform calls", () => {473- // The generated `Env` types `SANDBOX` as a plain `Fetcher` (an app's474- // types may not name another app's entrypoint), so the env's decode475- // declares the entrypoint's methods on it (`SandboxBinding`). Should476- // `Env` ever carry them, or turn `any`, the first line fails: drop the477- // declaration, or find what made the binding untyped.431+ // If the generated `Env` ever types `SANDBOX`'s methods, or turns `any`, this fails:432+ // drop the `SandboxBinding` declaration, or find what made the binding untyped.433 expectTypeOf<Env["SANDBOX"]>().not.toExtend<SandboxBinding>();434 expectTypeOf<PlatformConfig["SANDBOX"]>().toExtend<Env["SANDBOX"]>();435 expectTypeOf<PlatformConfig["SANDBOX"]>().toExtend<436 Parameters<typeof CheckRunnerSandbox>[0]30 unmodified linesmodified:apps/platform/test/code-reads.test.ts-13 removed
1-/**2- * The code reads over `/rpc`, as anyone not signed in calls them: datekit's3- * refs, a folder, a file, the log and a commit's changes, read from its4- * canonical repo only. No code read's payload names a repo, so a caller5- * cannot point one at a fork: an extra `repo` key is dropped or refused,6- * and the canonical repo is read either way.7- */1 import { describe, expect, it } from "@effect/vitest";2 import { Contracts } from "@repo/protocol/contracts";3 import { RepoName, RepoPath } from "@repo/protocol/ids";4 import { advanceTo } from "@repo/testkit/clock";11 unmodified lines16 );17 18 const { project } = datekit;19 27-/** The platform over datekit's world, seeded: made, pushed to, its ask open. */20 const platform = Effect.gen(function* () {21 yield* advanceTo("2026-10-07T12:00:00Z");22 23 const world = yield* Layer.build(worldOf([datekit]));10 unmodified lines34 )35 );36 });37 46-/** The contracts that read a project's code. */38 const codeReads = [39 "listRefs",40 "readTree",41 "listPaths",2 unmodified lines44 "showCommit",45 "why",46 ];47 57-/** Every field of a payload, nested ones included: its name and its type's AST. */48 const fieldsIn = (49 ast: SchemaAST.AST50 ): readonly (readonly [string, SchemaAST.AST])[] => {51 if (SchemaAST.isObjects(ast)) {58 unmodified lines110 () =>111 Effect.gen(function* () {112 const { handler } = yield* platform;113 124- // The wire's request, written as a client would send it, with a125- // `repo` beside the project that no contract has.114 const payload = JSON.stringify({115 project,116 repo: "alice__datekit--me--alice",117 });33 unmodified lines151 152 expect(153 rpcs.flatMap(([tag, rpc]) => (rpc === undefined ? [tag] : []))154 ).toStrictEqual([]);167- // The check sees a branded field: `readFile`'s path is a `RepoPath`.155 expect(156 fields.some(157 ([tag, name, type]) =>158 tag === "readFile" && name === "path" && type === RepoPath.ast9 unmodified linesmodified:apps/platform/test/core-loop.test.ts-47 removed
1-/**2- * The product's core loop as a decider and two contributors live it,3- * through the platform's own fetch handler4- * with real git: a project made and first pushed, two asks opened red5- * first, claimed, an answer refused out of scope and then landed with its6- * credit, a second answer refused on a stale base, and a replayed request7- * that lands nothing new. Every step goes through a surface: git's output,8- * or a contract over `/rpc`.9- */1 import { describe, expect, it } from "@effect/vitest";2 import type { RepoHost } from "@repo/artifacts/repo-host";3 import { Brand } from "@repo/brand";4 import { CheckAt } from "@repo/checks/check-runner";32 unmodified lines37 const parseIso = AskId.make("parse-iso");38 39 const parseMonth = AskId.make("parse-month");40 50-/** The lane an ask's `redThenGreen` check runs in. */41 const redThenGreen = LaneName.make("redThenGreen");42 43 const mainRef = "refs/heads/main";44 55-/** Where the config folder's sdk is imported from, as a maintainer writes it. */45 const sdk = `${Brand.cliPackage}/rules`;46 47 const readme = "datekit: dates, parsed\n";48 60-/** The project as dora first pushes it: one source file, the config folder, the vouches. */49 const start = {50 [`${Brand.configDir}/project.ts`]: [51 `import { kinds, project } from "${sdk}";`,52 ``,9 unmodified lines62 "src/parse.ts":63 "export const parse = (iso: string) => ({ month: 0, year: 0 });\n",64 };65 78-/** An ask's own files: its file in the config folder, and its check, which asserts. */66 const askFiles = (ask: AskId, want: string, assertion: string) =>67 Array.make(68 {69 content: [33 unmodified lines103 "parse reads the month of an ISO date",104 'expect(parse("2026-10-07").month).toBe(10);'105 );106 120-/** alice's answer to parse-iso: the year, read. */107 const yearRead =108 "export const parse = (iso: string) => ({ month: 0, year: Number(iso.slice(0, 4)) });\n";109 124-/** bob's answer to parse-month, on the same line: the month, read. */110 const monthRead =111 "export const parse = (iso: string) => ({ month: Number(iso.slice(5, 7)), year: 0 });\n";112 128-/**129- * The lines git printed from the server's side band, less the spaces git130- * pads them with to clear a progress line.131- */113 const remoteLines = (stderr: string) =>114 stderr115 .split("\n")116 .filter((line) => line.startsWith("remote: "))117 .map((line) => line.trimEnd());118 138-/** What `protocol/render` says of `refusals`, as git prints it. */119 const rendered = (refusals: Parameters<typeof explain>[0]) =>120 explain(refusals).map((line) => `remote: ${line}`);121 142-/** A person in a trailer: their handle and the address the platform gives them. */122 const credited = (handle: string) =>123 `${handle} <${handle}@users.${Brand.domain}>`;124 125 describe("the core loop, through the platform's fetch handler with real git", () => {8 unmodified lines134 const doraGit = world.git("dora");135 const aliceGit = world.git("alice");136 const bobGit = world.git("bob");137 159- // 1. dora makes the project; her first push lands the first tree,160- // and a second push straight to main is a direct push.138 const made = yield* dora.initProject({ project });139 const home = yield* doraGit.clone(made.remote);140 const first = yield* doraGit.commit(home, "Start datekit", start);141 const firstPush = yield* doraGit.push(home);35 unmodified lines177 first: { exitCode: 0, remote: [] },178 remote: `${world.origin}/${project}.git`,179 });180 204- // 2. dora opens two asks over the same file; each check fails205- // twice on main the same way, and each lands as a platform commit206- // dora asked, the first on her first push.181 yield* world.script(182 CheckAt.cases.Commit.make({183 commit: yield* world.composed(project, isoFiles),184 }),32 unmodified lines217 "--name-only",218 iso.landed219 ),220 main: yield* doraGit.ok(home, "rev-parse", "origin/main"),247- // parse-month's parent, then parse-iso's.221 parents: yield* doraGit.ok(222 home,223 "log",224 "-2",14 unmodified lines239 parents: [iso.landed, first].join("\n"),240 trailer: credited("dora"),241 });242 270- // 3. alice claims parse-iso, so bob's claim on it is AskFull; bob271- // claims parse-month instead.243 const { claim } = yield* alice.claim({ ask: parseIso, project });244 const full = yield* Effect.flip(bob.claim({ ask: parseIso, project }));245 const { claim: bobs } = yield* bob.claim({ ask: parseMonth, project });246 276- // 4. alice's first try reaches outside the ask's territory: git277- // prints OutOfScope, and her fork keeps the commit.247 const work = yield* aliceGit.clone(claim.remote);248 249 const wide = yield* aliceGit.commit(work, "Read the year, and say so", {250 "README.md": "datekit: dates, parsed, years first\n",3 unmodified lines254 const refused = yield* aliceGit.push(work);255 256 expect({257 base: claim.base,289- // The run block is the config folder's, as `/bun` evaluated it.258 checkCommand: claim.checkCommand,259 fork: yield* aliceGit.ok(work, "ls-remote", "origin", mainRef),260 full,261 refused: {16 unmodified lines278 },279 remote: `${world.origin}/${project}--parse-iso--alice.git`,280 });281 314- // 5. She puts the readme back and pushes again, through a harness315- // that names itself in her credential helper's username: the answer316- // is being checked, then merged, checked green and landed, and the317- // landing discloses the harness (never as its author or a credit).282 const fix = yield* aliceGit.commit(work, "Leave the readme alone", {283 "README.md": readme,284 });285 4 unmodified lines290 291 const offered = yield* harnessGit.push(work);292 const tree = yield* aliceGit.ok(work, "rev-parse", `${fix}^{tree}`);293 330- // main has not moved since alice claimed, so the merged tree is331- // her head's, and her check passes on it.294 yield* world.script(295 CheckAt.cases.Tree.make({ tree: TreeSha.make(tree) }),296 redThenGreen,297 ["passed"]96 unmodified lines394 trailers: `${credited("dora")}\n${credited("alice")}`,395 verdict: [[redThenGreen, "passed"]],396 });397 436- // 6. bob answered parse-month on the main he claimed at, in the437- // line alice's answer changed: his run ends refused, StaleBase,438- // naming alice's landing as the one that moved the file.398 const bobsWork = yield* bobGit.clone(bobs.remote);399 400 const stale = yield* bobGit.commit(bobsWork, "Read the month", {401 "src/parse.ts": monthRead,4 unmodified lines406 yield* world.settle();407 408 const bobsAnswers = (yield* bob.status({ project })).answers;409 451- // 7. alice offers her landed head again: the same receipt comes452- // back, and nothing new lands.410 const receipt = { ask: parseIso, base: claim.base, head: fix, project };411 412 const replayed = yield* alice.submitAnswer({413 ...receipt,74 unmodified lines488 },489 want: "parse reads the day of an ISO date",490 };491 535- // The rounds the Project DOs start run in process, on the Worker's536- // ports and the memory drafter, once the world hands them over.492 const ready = yield* Deferred.make<Context.Context<InlinePorts>>();493 const drafter = yield* Layer.build(DrafterMemory([drafted]));494 495 const world = yield* coreLoopWorld({18 unmodified lines514 515 yield* doraGit.commit(home, "Start datekit", start);516 yield* doraGit.push(home);517 563- // The drafted files fail on main twice the same way.518 yield* world.script(519 CheckAt.cases.Commit.make({520 commit: yield* world.composed(project, draftedFiles(drafted)),521 }),55 unmodified lines577 "--format=%(trailers:only)",578 "origin/main"579 ))580 .split("\n")627- // Who it credits and which agents it discloses: every `-by` trailer.581 .filter((line) => /^[A-Za-z-]+-by: /u.test(line)),582 }).toStrictEqual({583 asks: [{ ask: drafted.id, claimed: false }],584 draft: "Ready",15 unmodified linesmodified:apps/platform/test/credential.test.ts-1 removed
5 unmodified lines6 const token = "alice-token-0123456789abcdef01234567";7 8 const authorized = (authorization: string) => new Headers({ authorization });9 10-/** What git sends for `https://<user>:<password>@host/…`: base64 of `user:password`. */10 const basic = (user: string, password: string) =>11 `Basic ${btoa(`${user}:${password}`)}`;12 13 describe("the credential a request carries", () => {41 unmodified linesmodified:apps/platform/test/do-projects.test.ts-7 removed
53 unmodified lines54 const requestId = RequestId.make("req-none0001");55 56 const layer = LayerName.make("maintainers");57 58-/** A call's `Exit` as JSON, by its method's own schemas: equal when the outcomes are. */58 const settled = <A, E, R>(59 method: ProjectMethod,60 effect: Effect.Effect<A, E, R>61 ) =>3 unmodified lines65 ),66 Effect.orDie67 );68 70-/** Every `ProjectApi` method once, on a project made and not yet pushed to. */69 const everyMethod = (api: ProjectApi) =>70 Effect.all({71 admissionPlan: settled(72 "admissionPlan",135 unmodified lines208 api.vouch(bob, { handle: carol.handle, verdict: "vouch" })209 ),210 });211 214-/**215- * What `Projects` answers: for a name never made, for the project once made216- * (made again, and every method on it), and for another name.217- */212 const script = Effect.gen(function* () {213 const projects = yield* Projects;214 const before = yield* outcomeOf(projects.get(project));215 const made = yield* projects.create(project);58 unmodified lines274 expect(Object.keys(throughDo.each).toSorted()).toStrictEqual(275 projectMethods.toSorted()276 );277 expect(throughDo).toStrictEqual(inProcess);284- // Only a step reported for an answer request that never was dies.278 expect(died).toStrictEqual(["advanceAnswer"]);279 })280 );281 });modified:apps/platform/test/env.test-d.ts-7 removed
1-/**2- * Principle 7's type fence, the positive side: the platform Worker's3- * generated `Env` (from `wrangler.jsonc`, by `bun run types`) holds both4- * Artifacts namespaces, the public one and the private one the layers live5- * in, deliberately. The web's `test/env.test-d.ts` is the negative side:6- * a Worker that serves public pages holds neither.7- */1 import { describe, expectTypeOf, it } from "vitest";2 3 describe("the platform Worker's Env", () => {4 it("holds the public namespace and the private one", () => {11 unmodified linesmodified:apps/platform/test/evidence.test.ts-32 removed
1-/**2- * A failing lane's log, kept and read through the platform: the3- * Answer Workflow keeps the log of alice's failing `unit` lane in the4- * stage's evidence bucket (an R2 fake here, through `EvidenceStoreR2`, as5- * the Worker composes it), her refusal names only where it is kept, and6- * `evidence` over `/rpc` gives it to her and to dora, the project's7- * decider, and to nobody else. The world is the core loop's (`world.ts`):8- * the platform's own fetch handler with real git.9- */1 import { describe, expect, expectTypeOf, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { CheckAt } from "@repo/checks/check-runner";4 import { EvidenceStore } from "@repo/checks/evidence-store";34 unmodified lines39 const unit = LaneName.make("unit");40 41 const sdk = `${Brand.cliPackage}/rules`;42 52-/** The project as dora first pushes it: its run block has a `unit` lane. */43 const start = {44 [`${Brand.configDir}/project.ts`]: [45 `import { kinds, project } from "${sdk}";`,46 ``,37 unmodified lines84 path: RepoPath.make(`test/${parseIso}.test.ts`),85 }86 );87 98-/**99- * The log the platform keeps of a `unit` lane the Checker failed: what the100- * run said of the lane, since a scripted run has no output of its own.101- */88 const unitLog = [89 "unit: failed in 1 ms",90 "$ run unit",91 "unit: scripted failure",92 ].join("\n");93 108-/** One object as the fake bucket keeps it. */94 interface Kept {95 readonly text: string;96 readonly customMetadata: Readonly<Record<string, string>>;97 }98 114-/** The stage's evidence bucket in memory, in the shape of the Worker's `EVIDENCE` binding. */99 const fakeBucket = () => {100 const objects = new Map<string, Kept>();101 102 const bucket: EvidenceBucket = {13 unmodified lines116 117 return { bucket, objects };118 };119 136-/**137- * dora makes datekit and opens parse-iso; alice claims it and answers in138- * scope, and on the merged tree her ask's check passes and `unit` fails,139- * while `unit` passes on main: the answer is refused `ChecksFailed`.140- */120 const refused = Effect.gen(function* () {121 const { bucket, objects } = fakeBucket();122 const world = yield* coreLoopWorld({ evidence: EvidenceStoreR2(bucket) });123 const dora = world.rpc("dora");53 unmodified lines177 178 return { aliceGit, logRef, objects, pushed, verdict, work, world };179 });180 202-/** How a read ended, success or refusal, as JSON. */181 const json = <A, E>(read: Effect.Effect<A, E>) =>182 Effect.map(Effect.exit(read), (exit) => JSON.stringify(exit));183 206-/** Everything `who` can read over `/rpc` besides `evidence`, as JSON. */184 const everythingElse = (185 world: Effect.Success<typeof refused>["world"],186 who: Someone | "anonymous"187 ) =>78 unmodified lines266 267 const asked = (who: Someone | "anonymous", payload = ref) =>268 Effect.exit(world.rpc(who).evidence(payload));269 293- // A name pointing at another project: a real one bob makes, and one294- // nobody made, both read as that project unknown.270 yield* world271 .rpc("bob")272 .initProject({ project: ProjectName.make("bob/burrow") });273 299- // A log's name carries its project's key (ADR 0032).274 const elsewhere = (other: string) => ({275 project,276 ref: logRef.replace(277 `${keyOf(project)}/`,33 unmodified lines311 new UnknownProject({ project: ProjectName.make("alice/ghost") })312 ),313 });314 341- // A log over 256 KiB comes back as its last 256 KiB.315 const long = `${"x".repeat(300 * 1024)}\n${unitLog}`;316 const kept = objects.get(logRef);317 318 if (kept !== undefined) {16 unmodified lines335 () =>336 Effect.gen(function* () {337 const { aliceGit, pushed, work, world } = yield* refused;338 366- // Read first: the refused answer is still alice's latest.339 const read = [340 ...(yield* everythingElse(world, "alice")),341 ...(yield* everythingElse(world, "bob")),342 ...(yield* everythingElse(world, "dora")),343 ...(yield* everythingElse(world, "anonymous")),344 ];345 374- // Then alice tries again: this push's remote: lines are printed375- // while the refused answer's log is kept, unlike her first push's.346 yield* aliceGit.commit(work, "Read the year, trimmed", {347 "src/parse.ts":348 "export const parse = (iso: string) => ({ month: 0, year: Number(iso.slice(0, 4).trim()) });\n",349 });350 351 const again = yield* aliceGit.push(work);352 383- // The log whole, as JSON escapes it, and its one line no other384- // record of the run holds: the failure's signature.353 const needles = [354 unitLog,355 JSON.stringify(unitLog).slice(1, -1),356 "unit: scripted failure",17 unmodified linesmodified:apps/platform/test/fake-env.ts-42 removed
7 unmodified lines8 import type { ProjectStub } from "../src/adapters/do-projects.ts";9 import { CallRequest, ProjectCalls } from "../src/project-calls.ts";10 import type { ExitEncoded, ProjectMethod } from "../src/project-calls.ts";11 12-/**13- * A `FRONT_PAGE` database where every query reads no rows, each recorded in14- * `prepared`: what a call that lists projects (`listProjects`, or `status`15- * without a project) reads from D1.16- */12 export const emptyFrontPage = (prepared: string[] = []) =>13 untouchable<D1Database>("FRONT_PAGE", {14 prepare: (query) => {15 prepared.push(query);19 unmodified lines35 });36 },37 });38 44-/** The operator's token in every fake env: long enough to decode. */39 export const operatorToken = "operator-token-0123456789abcdef0123";40 47-/** Sign-in's cookie key and pepper in every fake env. */41 export const cookieKey = "cookie-key-0123456789abcdef0123456789";42 43 export const passwordPepper = "pepper-0123456789abcdef0123456789abcdef";44 52-/**53- * The master key in every fake env: 64 hex characters, the 256-bit key54- * that wraps write-only values. A test value, never a stage's.55- */45 export const masterKey = "0123456789abcdef".repeat(4);46 58-/** One call a fake Project DO was sent: the DO's name, the method, and who called. */47 export interface ProjectCallSeen {48 readonly project: string;49 readonly method: ProjectMethod;50 readonly caller: CallRequest["caller"];51 }52 65-/** What each fake `PROJECT` namespace was sent, in order, by the namespace. */53 const seenBy = new WeakMap<Env["PROJECT"], ProjectCallSeen[]>();54 68-/** Every call a `fakeProjects` namespace's DOs were sent, in order. */55 export const callsTo = (56 namespace: Env["PROJECT"]57 ): readonly ProjectCallSeen[] => seenBy.get(namespace) ?? [];58 59 const decodeCall = Schema.decodeUnknownSync(CallRequest);60 75-/** `exit`, encoded as `method`'s DO answers it. */61 const replyOf = (method: ProjectMethod, exit: Exit.Exit<unknown, unknown>) =>62 Schema.encodeUnknownSync(ProjectCalls[method].exit)(exit);63 79-/**80- * What a fake Project DO answers. A project in `made` reads as one with no81- * asks and nobody's claims or answers; any other method there is a defect.82- * Any other name holds no project: a contract call answers `UnknownProject`83- * (as the Project DO's shell does before `initProject`); the rest are defects.84- */64 const answer = (65 made: ReadonlySet<string>,66 project: string,67 method: ProjectMethod21 unmodified lines89 90 return replyOf(method, Exit.die(`the fake DO does not serve ${method}`));91 };92 114-/**115- * The `PROJECT` namespace as the Worker reaches it, in memory: each name is116- * a DO (`idFromName`), and each call is decoded as the real DO decodes it,117- * noted for `callsTo`, and answered by `answer`. Anything else read from it118- * throws, as an untouched binding does.119- */93 export const fakeProjects = (made: readonly string[] = []): Env["PROJECT"] => {94 const known = new Set(made);95 const seen: ProjectCallSeen[] = [];96 20 unmodified lines117 118 return namespace;119 };120 148-/**149- * The platform Worker's env at stage `local`, as `wrangler.jsonc` declares150- * it: every var and every required secret set, every binding a fake that151- * throws if touched, so a test proves what building the platform touches.152- * `PROJECT` is the exception: its DOs hold no project and answer calls on153- * one with `UnknownProject`, each noted (`callsTo`). The optional secrets154- * are absent.155- */121 export const fakeEnv = (): Env => ({122 AI: untouchable("AI"),123 ANSWER: untouchable("ANSWER"),124 ARTIFACTS: untouchable("ARTIFACTS"),21 unmodified lines146 SIGN_IN_LIMIT: untouchable("SIGN_IN_LIMIT"),147 STAGE: "local",148 });149 185-/**186- * `env` whose private namespace is `host`, a store of bare repos a test187- * keeps (the Node world's second store): the visibility cartridge's layer188- * repos, through the binding the cartridge reads. Remotes are the store's189- * own, so git reaches the store's server.190- */150 export const withPrivateNamespace = (env: Env, host: HostLike): Env => ({151 ...env,152 ARTIFACTS_PRIVATE: fakeArtifactsBinding(host),153 });154 196-/** `env` without `key`, as a Worker missing that binding, var or secret sees it. */155 export const without = (env: Env, key: keyof Env): Env => {156 const rest = { ...env };157 158 Reflect.deleteProperty(rest, key);3 unmodified linesmodified:apps/platform/test/front-page.test.ts+1 added-35 removed
1-/**2- * The project list and a person's credits as the platform serves them, over3- * a Node platform world: the platform's fetch handler composed as the4- * Worker composes it (`platformOn`), on the ports `workerPorts` gives it,5- * each a Node adapter. The front page and its projection are the D16- * cartridge (`FrontPageD1`, `ProjectionD1`) over sqlite-node with the7- * platform's D1 migrations applied from their files; each project is a8- * project service in memory (`ProjectsMemory`) whose outbox feeds that9- * projection; the Lander is the `/isogit` one over `RepoHostMemory`; and the10- * Checker fails every lane on a commit of main (an ask's check, red first)11- * and passes every lane on an answer's merged tree. The world's `Projects`12- * counts every call, so a test shows which reads never reach a project.13- */1 import { NodeServices } from "@effect/platform-node";2 import { SqliteClient } from "@effect/sql-sqlite-node";3 import { describe, expect, it } from "@effect/vitest";4 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";35 unmodified lines40 import { fakeEnv } from "./fake-env.ts";41 import { seeded } from "./handlers.fixtures.ts";42 import { rpcClient } from "./harness.ts";43 57-/** datekit: alice decides and asks; bob is vouched for. */44 const datekit = aProject({ people: ["bob"] }).pipe(45 withVouches(["bob"]),46 withAsk({ id: "parse-iso", territory: "packages/parser" }),47 withAsk({ id: "trim-input", territory: "packages/trim" })8 unmodified lines56 const alice = Handle.make("alice");57 58 const noon = "2026-10-07T12:00:00Z";59 74-/**75- * The platform's D1 database: every migration in its own folder, in76- * file-name order as `wrangler d1 migrations apply` runs them, statement by77- * statement. Comment lines go before the split: a comment may hold a `;`78- * (`0002_accounts.sql`'s does).79- */60+// Comment lines go before the split: a comment may hold a `;`.61 const migrated = Layer.effectDiscard(62 Effect.gen(function* () {63 const fs = yield* FileSystem.FileSystem;64 const path = yield* Path.Path;28 unmodified lines93 Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),94 Layer.orDie95 );96 116-/**117- * An ask's check fails on a commit of main, every time the same way, and118- * every lane passes on an answer's merged tree.119- */97 const redOnMainGreenOnAnswers = Layer.succeed(98 CheckRunner,99 CheckRunner.of({100 run: ({ at: where, lanes }) => {15 unmodified lines116 },117 })118 );119 143-/** At any commit, datekit's policy, holding the asks whose files the commit has. */120 const rules = Layer.effect(121 RulesEvaluator,122 Effect.gen(function* () {123 const finishers = yield* Finishers;11 unmodified lines135 });136 })137 ).pipe(Layer.provide(FinishersFromChecks));138 163-/** The world a front-page test drives. */139 interface FrontPageWorld {165- /** Every call the platform made to a project through `Projects`, in order. */140 readonly calls: Effect.Effect<readonly string[]>;167- /** Forgets the calls made so far. */141 readonly forget: Effect.Effect<void>;169- /** A client of the contracts over HTTP at `/rpc`, as anyone. */142 readonly anyone: Client["Service"];171- /** bob's answer to `parse-iso` landed, as his claim, push and submission make it. */143 readonly landAnswer: Effect.Effect<void>;173- /** quietkit made and first pushed, and nothing else: no ask, no policy evaluated. */144 readonly makeQuiet: Effect.Effect<void>;145 }146 147 const frontPageWorld: Effect.Effect<FrontPageWorld, never, Scope.Scope> =148 Effect.gen(function* () {179- // Every port but `Projects`, built once: the Worker's and each project's.149 const base = yield* Layer.build(150 Layer.mergeAll(151 AlarmsMemory,152 AnswerRunsInline,136 unmodified lines289 credits: [290 { area: "parser", count: 1, project, role: "Signed-off-by" },291 ],292 },324- // The list's one read: datekit's posture, from its ledger.293 calls: [`get ${project}`],294 listed: {295 projects: [296 { landedAt: at(noon), openAsks: 1, posture: "open", project },2 unmodified lines299 });300 301 yield* world.forget;302 335- // The posture read is kept in D1 beside the projection: the next336- // list asks no project.303 expect(yield* world.anyone.listProjects({})).toStrictEqual(listed);304 expect(yield* world.calls).toStrictEqual([]);305 }).pipe(Effect.scoped)306 );1 unmodified linemodified:apps/platform/test/gateway-owner.test.ts-14 removed
1-/**2- * The gateway reads a project's address as the web does (ADR 0032): the3- * full name, `<owner>/<name>` or `<host>/<account>/<name>`, with a fork's4- * parts after it, and the key a project kept from before owners. Each5- * reaches the repo the project's key names in the store; an address no6- * project can have reaches none.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Fetch } from "@repo/artifacts/fetch";4 import { ProjectName } from "@repo/protocol/ids";5 unmodified lines10 import { gatewayWorld, tokens } from "./gateway.fixtures.ts";11 12 const scenario = aProject({ name: ProjectName.make("oscabriel/datekit") });13 21-/** Bare repos in the store, by the names the platform keeps them under. */14 const STORED = ["datekit", "click", "datekit--fix-week--alice"] as const;15 24-/** A world whose store holds `STORED`, each an empty bare repo. */16 const withStored = Effect.gen(function* () {17 const world = yield* gatewayWorld([scenario]);18 19 yield* Effect.forEach(4 unmodified lines24 25 return world;26 });27 37-/**38- * The status of a clone's first request at `address`, as alice: a fork is39- * read only by its claimant, so the gateway asks anyone else to sign in40- * before it looks the repo up.41- */28 const statusAt = (origin: string, address: string) =>29 Fetch.use(({ fetch }) =>30 fetch(31 new Request(58 unmodified linesmodified:apps/platform/test/gateway.fixtures.ts-58 removed
1-/**2- * The platform's git endpoint as `gateway.test.ts` drives it: `serveGit`3- * served on a local port, in front of bare repos on disk, the way4- * `packages/git/test/world.ts` serves the gateway. Behind it run the real5- * pieces production runs, over local stand-ins: `UpstreamRepoHost`6- * over `RepoHostLocal` and the Worker's `fetch` (`WorkerFetch`), reaching7- * real `git http-backend` on a second port, and `Projects` over its memory8- * adapter with a testkit scenario's policy.9- *10- * The world also writes down what a test checks beyond git's own output:11- * every request the upstream got (method, path, credential), every token12- * the store minted, and every answer run started.13- */1 import { NodeHttpServer, NodeServices } from "@effect/platform-node";2 import { RepoHost } from "@repo/artifacts/repo-host";3 import { RepoHostLocal } from "@repo/artifacts/repo-host/local";4 import { CheckAt } from "@repo/checks/check-runner";43 unmodified lines48 import { WorkerFetch } from "../src/adapters/fetch.ts";49 import { serveGit } from "../src/git.ts";50 import { MemorySessions } from "../src/sessions/memory.ts";51 65-/** A platform token for each person, as the credential helper would hand git one. */52 export const tokens = {53 alice: "alice-platform-token-0123456789abcdef",54 bob: "bob-platform-token-0123456789abcdefghi",55 } as const;1 unmodified line57 export const alice = Person.make({ handle: Handle.make("alice") });58 59 export const bob = Person.make({ handle: Handle.make("bob") });60 75-/** One exchange the upstream served: what was asked, and with which credential. */61 export interface Served {62 readonly method: string;63 readonly path: string;64 readonly authorization: Option.Option<string>;65 }66 82-/** What a test reads back besides git's output. */67 export interface Seen {84- /** Every exchange the upstream served, in order. */68 readonly upstream: Ref.Ref<readonly Served[]>;86- /** Every token secret the store minted. */69 readonly minted: Ref.Ref<readonly string[]>;88- /** Every answer run started, by request id. */70 readonly started: Ref.Ref<readonly RequestId[]>;71 }72 92-/** Writes the files, commits them all, and returns the commit's id. */73 export const commit = (74 cwd: string,75 message: string,76 files: Readonly<Record<string, string>>18 unmodified lines95 96 return CommitSha.make(yield* gitOk(cwd, "rev-parse", "HEAD"));97 });98 119-/**120- * git's arguments for sending `token` as the password of Basic auth on every121- * request, as git does once the credential helper answered.122- */99 export const as = (token: string) => [100 "-c",101 `http.extraHeader=Authorization: Basic ${btoa(`x:${token}`)}`,102 ];103 128-/** Serves `app` on a local port for as long as the scope lasts, and returns its origin. */104 const listen = <E, R>(105 app: Effect.Effect<106 HttpServerResponse.HttpServerResponse,107 E,16 unmodified lines124 125 return `http://127.0.0.1:${address.port}`;126 });127 153-/**154- * `git http-backend` over the bare repos in `root`, as Artifacts stands155- * behind the gateway: it takes whatever credential it is sent, and writes156- * each exchange down.157- */128 const upstreamApp = (root: string, seen: Seen["upstream"]) =>129 Effect.gen(function* () {130 const request = yield* HttpServerRequest.HttpServerRequest;131 const web = yield* HttpServerRequest.toWeb(request);12 unmodified lines144 yield* Effect.scoped(httpBackend(root)(web))145 );146 });147 178-/** The platform's git endpoint: `serveGit`, and a 404 for any other path. */148 const gatewayApp = Effect.gen(function* () {149 const request = yield* HttpServerRequest.HttpServerRequest;150 const web = yield* HttpServerRequest.toWeb(request);151 5 unmodified lines157 158 return HttpServerResponse.fromWeb(response);159 });160 192-/** `RepoHostLocal`, writing down every token secret it mints. */161 const mintingHost = (minted: Seen["minted"]) =>162 Layer.effect(163 RepoHost,164 Effect.gen(function* () {8 unmodified lines173 });174 })175 );176 209-/**210- * The policy `project`'s scenario holds; a project with none gets the first211- * scenario's, with no asks.212- */177 const policyOf = (178 scenarios: readonly Scenario[],179 project: ProjectName180 ): Option.Option<Policy> =>7 unmodified lines188 asks: [],189 }))190 );191 228-/**229- * A `RulesEvaluator` that evaluates nothing: at any commit it returns the230- * policy its project's scenario holds, and the judge closure `checks`231- * derives.232- */192 const rulesOf = (scenarios: readonly Scenario[]) =>193 Layer.effect(194 RulesEvaluator,195 Effect.gen(function* () {14 unmodified lines210 });211 })212 ).pipe(Layer.provide(FinishersFromChecks));213 255-/** The lane an ask's `redThenGreen` check runs in. */214 const checkLane = LaneName.make("redThenGreen");215 258-/** One scripted run of the ask's check, failing. */216 const failedOnce: LaneResult = {217 command: "bun test",218 durationMs: 1,219 lane: checkLane,220 result: "failed",221 };222 266-/** An ask's own files: its file in the config folder, and its check, which asserts. */223 const askFiles = (ask: Ask) =>224 Array.make(225 { content: `export default "${ask.id}";\n`, path: ask.file },226 {11 unmodified lines238 : RepoPath.make(`test/${ask.id}.test.ts`),239 }240 );241 286-/** Answer runs that only write down that they started: no push here lands. */242 const startedRuns = (started: Seen["started"]) =>243 Layer.succeed(244 AnswerRuns,245 AnswerRuns.of({246 start: (requestId) => Ref.update(started, (all) => [...all, requestId]),247 })248 );249 295-/**296- * The world: bare repos under a temporary folder, `git http-backend` over297- * them on one port, and the platform's git endpoint on another, whose298- * services are built here once. Projects follow `scenarios`; alice made299- * every one of them.300- */250 export const gatewayWorld = (scenarios: readonly Scenario[]) =>251 Effect.gen(function* () {252 const fs = yield* FileSystem.FileSystem;253 const root = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);52 unmodified lines306 const repoHost = Context.get(services, RepoHost);307 308 const origin = yield* listen(gatewayApp, services);309 361- /**362- * `decider` opens `ask` (one of the scenario's) on main: the Checker363- * fails its check twice the same way on the composed commit.364- */310 const openAsk = (311 api: ProjectApi,312 main: LandedSha,313 ask: Ask,20 unmodified lines334 host: repoHost,335 openAsk,336 origin,337 projects: Context.get(services, Projects),393- /** Where the store keeps each repo: `<repos>/<name>.git`. */338 repos,339 root,340 seen,397- /** A repo's URL at the gateway. */398- /** A repo's URL at the gateway: a project by its name, a fork by its address. */341 urlOf: (repo: string) =>342 `${origin}/${343 repo.includes("/")344 ? repo4 unmodified linesmodified:apps/platform/test/gateway.test.ts-29 removed
42 unmodified lines43 } from "./gateway.fixtures.ts";44 45 const datekit = ProjectName.make("alice/datekit");46 47-/** The ref the platform keeps a fork's verdict notes under. */47 const notesRef = `refs/notes/${Brand.slug}`;48 49 const parseIso = AskId.make("parse-iso");50 52-/** A project made empty, awaiting its first push. */51 const fresh = ProjectName.make("alice/fresh");52 53 const scenario = aProject({ name: datekit, people: ["bob"] }).pipe(54 withAsk({ id: parseIso, territory: "packages/parser" }),55 withVouches(["bob"])56 );57 60-/** One of the scenario's asks, by id. */58 const askOf = (id: AskId) =>59 Option.getOrThrow(60 Array.findFirst(scenario.policy.asks, (ask) => ask.id === id)61 );62 66-/**67- * The world, with `datekit` made by alice: its first commit (two files) put68- * straight into its repo and recorded as its landed SHA, then `parse-iso`69- * (over `packages/parser`) opened on it red first, which lands as main.70- */63 const withDatekit = Effect.gen(function* () {64 const world = yield* gatewayWorld([scenario]);65 const seed = `${world.root}/seed`;66 const api = yield* world.projects.create(datekit).pipe(Effect.orDie);23 unmodified lines90 91 return { ...world, api, first, landed, seed };92 });93 102-/**103- * The lines git printed from the server's side band, less the spaces git pads104- * them with to clear a progress line.105- */94 const remoteLines = (stderr: string) =>95 stderr96 .split("\n")97 .filter((line) => line.startsWith("remote: "))98 .map((line) => line.trimEnd());99 112-/** What git says of a push custody turned away as a direct push of `ref`. */100 const refusedAs = (ref: string) => ({101 exitCode: 1,102 remote: explain([new DirectPush({ ref })]).map((line) => `remote: ${line}`),103 });104 118-/**119- * A GET of `url`, with `authorization` if given, through the Worker's fetch:120- * its status, and whether it asks for Basic.121- */105 const request = (url: string, authorization?: string) =>106 Fetch.use(({ fetch }) =>107 fetch(108 new Request(url, {119 unmodified lines228 }).toStrictEqual({ again: true, bob: true, first: 0, main: first });229 expect(230 yield* gitOk(`${repos}/${keyOf(fresh)}.git`, "rev-parse", "main")231 ).toBe(first);249- // The first push became the landed SHA: no other commit can now.232 expect(233 yield* Effect.flip(api.recordFirstPush(alice, second))234 ).toStrictEqual(new DirectPush({ ref: "refs/heads/main" }));235 }).pipe(Effect.provide(NodeServices.layer)),178 unmodified lines414 answers.map((answer) => [answer.requestId, answer.head])415 ).toStrictEqual([[requestId, fix]]);416 expect(yield* Ref.get(seen.started)).toStrictEqual([requestId]);417 436- // The platform's tokens reached the upstream, and only they did:437- // never the person's, and never back to git.418 const minted = yield* Ref.get(seen.minted);419 420 const credentials = new Set(421 minted.map((secret) => `Basic ${btoa(`x:${secret}`)}`)90 unmodified lines512 urlOf(claim.fork),513 clone514 );515 536- // The platform's own verdict note, written straight to the fork as537- // `RepoHost.push` writes it, never through the gateway.516 yield* gitOk(clone, "notes", `--ref=${Brand.slug}`, "add", "-m", "{}");517 yield* gitOk(clone, "push", "--quiet", forkRepo, notesRef);518 519 const noted = yield* gitOk(forkRepo, "rev-parse", notesRef);71 unmodified lines591 Effect.gen(function* () {592 const { api, origin } = yield* withDatekit;593 const { claim } = yield* api.claim(alice, parseIso).pipe(Effect.orDie);594 617- // A fork by its repo's name, a project by its address.595 const refs = (repo: string) =>596 `${origin}/${597 repo.includes("/")598 ? repo37 unmodified lines636 ]);637 });638 });639 663-/** A person no project here names, who decides nothing. */640 const carol = Person.make({ handle: Handle.make("carol") });641 642 const mainRef = RefName.make("refs/heads/main");643 668-/** A push moving `ref` from `from` to a commit made up for the test. */644 const moving = (ref: RefName, from: Option.Option<CommitSha>): Command => ({645 from,646 ref,647 to: Option.some(CommitSha.make("c".repeat(40))),648 });649 675-/** What custody says of `commands` pushed by `pusher` to `repo`, before and after the upstream. */650 const judged = (651 projects: Projects["Service"],652 pusher: Person,653 repo: string,654 commands: Array.NonEmptyReadonlyArray<Command>655 ) =>656 Effect.gen(function* () {683- // A project by its name, or a fork by its repo's name.657 const name = Option.getOrElse(repoNameOfAddress(repo), () =>658 RepoName.make(repo)659 );660 52 unmodified lines713 expect(yield* judged(projects, alice, claim.fork, push)).toStrictEqual({714 admitted: [],715 reviewed: [],716 });744- // No answer run started: neither the decider's nor the claimant's.717 expect(yield* Ref.get(seen.started)).toStrictEqual([]);718 expect(719 (yield* judged(projects, carol, claim.fork, push)).admitted720 ).toStrictEqual([NotClaimed.of(parseIso)]);73 unmodified lines794 );795 796 yield* api.initProject(alice, {}).pipe(Effect.orDie);797 826- // bob first: alice's push, once reviewed, is the project's first.798 const byBob = yield* judged(projects, bob, fresh, first);799 const byAlice = yield* judged(projects, alice, fresh, first);800 801 const unmade = yield* judged(36 unmodified linesmodified:apps/platform/test/generated.test.ts-35 removed
1-/**2- * The project's contribute skill kept current on the platform: a3- * landing that changes what the generated files say is followed by the4- * platform's own landing of only those files, regenerated with5- * `@repo/agent-kit` as the platform's Project DOs do it6- * (`workflows/generated.ts`), credited `Decided-by` the decider whose7- * landing changed the config. Node world, memory adapters: `RepoHostMemory`,8- * the isomorphic-git `Lander` over it, a scripted Checker, `ProjectsMemory`,9- * and a rules evaluator whose run block is the config folder's `run.json`.10- */1 import { describe, expect, it } from "@effect/vitest";2 import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";3 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";58 unmodified lines63 checks: { lint: "bun run lint", unit: "bun run test" },64 test: "bun test {path}",65 };66 77-/** What alice pushes first: a package, the run block, and notes of the project's own. */67 const start: Files = [68 ["package.json", '{ "name": "alice/datekit" }\n'],69 ["src/parse.ts", "export const parse = (s) => ({});\n"],70 [runFile, `${JSON.stringify(lintOnly)}\n`],1 unmodified line72 ];73 74 const decodeRun = Schema.decodeEffect(Schema.fromJsonString(RunBlock));75 87-/**88- * The scenario's policy at any commit, with the run block its config89- * folder's `run.json` states, or lint alone when it states none.90- */76 const rules = Layer.succeed(77 RulesEvaluator,78 RulesEvaluator.of({79 call: () => Effect.succeed(false),6 unmodified lines86 ),87 })88 );89 105-/** What the Checker answers: every lane passes on any tree the test names. */90 class Passing extends Context.Service<91 Passing,92 {93 readonly on: (at: CheckAt, lanes: readonly string[]) => Effect.Effect<void>;30 unmodified lines124 );125 })126 );127 144-/**145- * What goes wrong with the next follow-up's land, once: nothing, a busy146- * repo before anything is pushed, or a push that went through and whose147- * answer was lost on the way back (a Lander call that timed out after it).148- */128 type Mishap = "none" | "busy" | "lost";129 130 class Mishaps extends Context.Service<131 Mishaps,132 { readonly next: (mishap: Mishap) => Effect.Effect<void> }133 >()("test/Mishaps") {}134 156-/** The isomorphic-git Lander, with the next follow-up's mishap played on its land. */135 const mishapLander = Layer.effectContext(136 Effect.gen(function* () {137 const real = Context.get(yield* Layer.build(LanderIsogit), Lander);138 const next = yield* Ref.make<Mishap>("none");18 unmodified lines157 );158 })159 );160 183-/** Commits made the way git would make them, pushed to a repo's `main`. */161 class Pusher extends Context.Service<162 Pusher,163 {164 readonly push: (28 unmodified lines193 });194 })195 );196 220-/**221- * The project's ports, the generator only among the Project's own, as a222- * Project DO's shell gives them: the calls the test makes run without it.223- */197 const world = Layer.mergeAll(198 ProjectsMemory.pipe(Layer.provide(ProjectSkillGenerator)),199 pusher200 ).pipe(3 unmodified lines204 Layer.provideMerge(Layer.merge(mishapLander, checker)),205 Layer.provideMerge(RepoHostMemory)206 );207 235-/** Where canonical `main` stands. */208 const mainTip = Effect.gen(function* () {209 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);210 211 return LandedSha.make(7 unmodified lines219 .readCommit(repo, sha)220 .pipe(Effect.orDie, Effect.flatMap(Effect.fromOption))221 ).pipe(Effect.orDie);222 251-/** A file's text at a commit of the canonical repo. */223 const textAt = (sha: CommitSha, path: string) =>224 Effect.flatMap(RepoHost, (host) =>225 host226 .readFile(repo, Revision.Commit({ sha }), RepoPath.make(path))2 unmodified lines229 Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes)))230 )231 );232 262-/** What one commit changed against its first parent, by path. */233 const changedBy = (sha: CommitSha) =>234 Effect.gen(function* () {235 const commit = yield* commitAt(sha);236 const parent = yield* commitAt(commit.parents[0] ?? sha);6 unmodified lines243 244 return changes.map(({ path }) => path).toSorted();245 });246 277-/** The platform's follow-up at `sha`: its parent, what it changed, who it credits and names. */247 const followUpAt = (sha: CommitSha) =>248 Effect.gen(function* () {249 const commit = yield* commitAt(sha);250 8 unmodified lines259 subject: commit.message.split("\n")[0],260 };261 });262 294-/** Every file of the tree at `sha` the test knows of, as a commit on it would carry them. */263 const filesAt = (sha: CommitSha, run: typeof RunBlock.Encoded) =>264 Effect.gen(function* () {265 const generated = yield* Effect.forEach(generatedPaths, (path) =>266 Effect.map(8 unmodified lines275 ...generated,276 ] satisfies Files;277 });278 311-/** The project made, and alice's first push to it recorded. */279 const firstPushed = Effect.gen(function* () {280 yield* advanceTo("2026-10-07T12:00:00Z");281 282 const api = yield* Projects.use((each) => each.create(project)).pipe(10 unmodified lines293 294 return { api, first };295 });296 330-/** alice's own change from her working fork, `files` on top of `base`, made ready to land. */297 const aliceLands = (base: LandedSha, files: Files, requestId: string) =>298 Effect.gen(function* () {299 const api = yield* Projects.use((each) => each.get(project)).pipe(300 Effect.orDie57 unmodified lines358 expect(yield* textAt(tip, skill)).toStrictEqual(359 yield* textAt(tip, claudeSkill)360 );361 396- // The same first push recorded again is still the project's first push.362 expect(363 yield* Effect.exit(api.recordFirstPush(alice, first))364 ).toStrictEqual(Exit.succeed({ landed: first }));365 expect(yield* mainTip).toBe(tip);138 unmodified linesmodified:apps/platform/test/google.fixtures.ts-55 removed
1-/**2- * A fake Google for sign-in tests, behind the `Fetch` port: its discovery3- * document, its token endpoint and its keys (JWKS), signing ID tokens with4- * an RSA key the test made. A test plays Google's consent screen with5- * `consent`: it reads the authorization request the platform sent the6- * browser to, and answers with the callback URL Google would send it back7- * to, its code bound to the request's PKCE challenge and nonce.8- *9- * `googleWorld` is the sign-in Worker as `worker.ts` builds it, over the10- * fake env (Google's client set, unless a test says not), accounts and11- * links in memory and the fake Google, with a browser that keeps cookies.12- */1 import { Fetch } from "@repo/artifacts/fetch";2 import { untouchable } from "@repo/testkit/untouchable";3 import { Clock, Effect, Layer, Option, Ref, Schema } from "effect";4 import { vi } from "vitest";9 unmodified lines14 import { oauthProvider, signInSettings } from "../src/auth/provider.ts";15 import { decodeEnv } from "../src/platform.ts";16 import { fakeEnv } from "./fake-env.ts";17 30-/** The Google OAuth client every Google test signs in with (H4 makes the real one). */18 export const clientId = "419-test.apps.googleusercontent.com";19 20 export const clientSecret = "GOCSPX-a-test-client-secret";21 22 export const tokenEndpoint = "https://oauth2.googleapis.com/token";23 24 export const jwksUri = "https://www.googleapis.com/oauth2/v3/certs";25 39-/** Google's two optional keys in the Worker's env (`.env.schema`). */26 export type GoogleKey = "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET";27 42-/** The Worker's env with Google's keys, which the generated `Env` leaves out (optional secrets). */28 export type GoogleEnv = Env & Readonly<Partial<Record<GoogleKey, string>>>;29 45-/** The fake env with the named halves of Google's client set (both by default). */30 export const googleEnv = (31 keys: readonly GoogleKey[] = ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"]32 ): GoogleEnv => {33 const halves = {18 unmodified lines52 53 const isJwk = (key: ArrayBuffer | JsonWebKey): key is JsonWebKey =>54 !(key instanceof ArrayBuffer);55 72-/** A fresh RS256 key pair, its public half as a JWK under `kid`. */56 const keyPair = (kid: string) =>57 Effect.gen(function* () {58 const pair = yield* Effect.promise(() =>59 crypto.subtle.generateKey(26 unmodified lines86 });87 88 export type KeyPair = Effect.Success<ReturnType<typeof keyPair>>;89 107-/**108- * The ID token claims a test may change, beside the subject. An `azp` set109- * to `undefined` leaves the claim out (JSON drops it).110- */90 export interface Claims {91 readonly aud?: string | readonly string[];92 readonly azp?: string | undefined;93 readonly exp?: number;94 readonly iss?: string;95 readonly nonce?: string;96 }97 119-/**120- * How Google answers one code: the person (`sub`), and anything a test121- * changes about the ID token: its claims, the key it is signed with, or the122- * `kid` its header names.123- */98 export interface Consent {99 readonly claims?: Claims;100 readonly kid?: string;101 readonly signWith?: KeyPair;102 readonly sub: string;103 }104 131-/** What the platform asked Google for, as Google's consent screen reads it. */105 const AuthorizationRequest = Schema.Struct({106 client_id: Schema.String,107 code_challenge: Schema.String,108 code_challenge_method: Schema.Literal("S256"),6 unmodified lines115 116 const decodeAuthorizationRequest =117 Schema.decodeUnknownSync(AuthorizationRequest);118 146-/** The code exchange the platform posts to the token endpoint. */119 const CodeExchange = Schema.Struct({120 client_id: Schema.String,121 client_secret: Schema.String,122 code: Schema.String,8 unmodified lines131 readonly consent: Consent;132 readonly request: typeof AuthorizationRequest.Type;133 }134 163-/** The S256 challenge of `verifier`. */135 const s256 = (verifier: string) =>136 Effect.promise(() => crypto.subtle.digest("SHA-256", utf8(verifier))).pipe(137 Effect.map((digest) => base64Url(new Uint8Array(digest)))138 );139 169-/** A fake Google for one test, and what it was asked. */140 export const fakeGoogle = Effect.gen(function* () {141 const signing = yield* keyPair("google-key-1");142 143 const published = yield* Ref.make<readonly KeyPair[]>([signing]);3 unmodified lines147 const fetched = yield* Ref.make<readonly string[]>([]);148 149 const exchanges = yield* Ref.make<readonly string[]>([]);150 181- /** An ID token for `grant`, signed as `grant.consent` says. */151 const idToken = (grant: Grant) =>152 Effect.gen(function* () {153 const now = Math.floor((yield* Clock.currentTimeMillis) / 1000);154 32 unmodified lines187 188 return `${header}.${claims}.${base64Url(new Uint8Array(signature))}`;189 });190 222- /** Google's token endpoint: the code, its client and its PKCE verifier, or `invalid_grant`. */191 const token = (request: Request) =>192 Effect.gen(function* () {193 const form = Object.fromEntries(194 new URLSearchParams(yield* Effect.promise(() => request.text()))74 unmodified lines269 return new Response("not found", { status: 404 });270 }),271 });272 305- /**306- * Google's consent screen: the person `consent.sub` signs in for the307- * authorization request at `location`, and Google sends the browser back308- * to its redirect URI with a code and the request's `state`.309- */273 const consent = (location: string, given: Consent) =>274 Effect.gen(function* () {275 const request = decodeAuthorizationRequest(276 Object.fromEntries(new URL(location).searchParams)12 unmodified lines289 290 return back;291 });292 330- /** Google starts signing with a new key, and publishes it beside the old one. */293 const rotate = (kid: string) =>294 Effect.gen(function* () {295 const next = yield* keyPair(kid);296 1 unmodified line298 299 return next;300 });301 340- /** How many times a URL was fetched. */302 const timesFetched = (url: string) =>303 Ref.get(fetched).pipe(304 Effect.map((all) => all.filter((each) => each === url).length)305 );9 unmodified lines315 });316 317 export type FakeGoogle = Effect.Success<typeof fakeGoogle>;318 358-/** Where a request comes from, as a browser decides which cookies go with it. */319 export type Site = "cross-site" | "same-site";320 321 interface Kept {322 readonly strict: boolean;323 readonly value: string;324 }325 366-/**367- * A browser for `handler`: it keeps the cookies responses set (dropping one368- * set with `Max-Age=0`) and sends them back, except that a `SameSite=Strict`369- * cookie stays home on a request from another site, as Google's redirect370- * back to the callback is.371- */326 const browserFor = (handler: (request: Request) => Promise<Response>) => {327 const jar = new Map<string, Kept>();328 329 const send = (request: Request, from: Site = "same-site") =>38 unmodified lines368 send,369 };370 };371 418-/** A Worker's context the provider is handed and never needs. */372 const context = untouchable<ExecutionContext>("ExecutionContext");373 421-/** What the rest of the platform answers: only the auth routes are sign-in's. */374 const platformFetch = (request: Request) =>375 Promise.resolve(376 new Response(`platform: ${new URL(request.url).pathname}`, { status: 418 })377 );378 427-/**428- * The sign-in Worker with Google's client set (or not, `google: false`), and429- * `COOKIE_KEY` as the fake env has it unless a test names another. The430- * global `fetch` answers the CLI's client metadata document from the Worker431- * itself, as the public internet does on Cloudflare; Google is reached only432- * through the `Fetch` port.433- */379 export const googleWorld = (380 options: { readonly cookieKey?: string; readonly google?: boolean } = {}381 ) =>382 Effect.gen(function* () {57 unmodified linesmodified:apps/platform/test/google.test.ts-43 removed
51 unmodified lines52 origin,53 tokenRequest,54 } from "./oauth.fixtures.ts";55 56-/** Alice's password, for the accounts signed up with one. */56 const alicePassword = "correct horse battery";57 58 describe("the Worker's env, for Google sign-in", () => {59 it.effect(44 unmodified lines104 105 const handleOf = (subject: string) =>106 Identities.use((identities) => identities.handleOf("google", subject));107 109-/**110- * What every `Identities` adapter must do, written against the port:111- * `/memory` and the D1 adapter (over sqlite-node, with the migration D1112- * applies) run it on every `verify`.113- */108 const describeIdentities = (109 adapter: string,110 layer: Layer.Layer<Identities>111 ) => {86 unmodified lines198 };199 200 describeIdentities("memory", Layer.fresh(IdentitiesMemory.layer));201 208-/** The identities table, as `wrangler d1 migrations apply` makes it. */202 const migrated = Layer.effectDiscard(203 Effect.gen(function* () {204 const fs = yield* FileSystem.FileSystem;205 6 unmodified lines212 yield* sql.unsafe(ddl);213 })214 ).pipe(Layer.orDie, Layer.provide(NodeServices.layer));215 223-/** A fresh in-memory database, migrated, each time the layer is built. */216 const database = migrated.pipe(217 Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),218 Layer.orDie219 );2 unmodified lines222 "D1 (sqlite-node)",223 IdentitiesD1.pipe(Layer.provide(database))224 );225 234-/** RFC 7636 appendix B's verifier and its S256 challenge. */226 const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";227 228 const challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";229 31 unmodified lines261 ]);262 });263 });264 274-/** The request `googleAuthorizeUrl` would send the browser to, built by hand. */265 const authorizationRequest = new URL(266 `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({267 client_id: clientId,268 code_challenge: challenge,5 unmodified lines274 state: "sealed-state",275 }).toString()}`276 ).toString();277 288-/**289- * The person Google names for one consent, as `googleSubject` confirms it290- * (with the verifier and nonce the platform kept, unless a test changes them).291- */278 const subjectOf = (279 google: FakeGoogle,280 consent: Consent,281 kept: { readonly codeVerifier?: string; readonly nonce?: string } = {}10 unmodified lines292 redirectUri: callbackUri,293 });294 });295 310-/** Runs `body` with one fake Google and one isolate's kept keys. */296 const withGoogle = <A, E>(297 body: (google: FakeGoogle) => Effect.Effect<A, E, Fetch | GoogleKeys>298 ) =>299 Effect.gen(function* () {141 unmodified lines441 )442 );443 });444 460-/** A page's text, beside the response it came in. */445 interface Page {446 readonly html: string;447 readonly response: Response;448 }2 unmodified lines451 Effect.promise(() => response.text()).pipe(452 Effect.map((html): Page => ({ html, response }))453 );454 471-/** The browser asks the sign-in Worker for `path` (or a full request). */455 const visit = (world: GoogleWorld, path: Request | string, from?: Site) =>456 world.browser.send(457 path instanceof Request ? path : new Request(new URL(path, origin)),458 from459 );460 478-/** Opens the CLI's sign-in page, as a browser would. */461 const openSignIn = (world: GoogleWorld) =>462 visit(world, new Request(authorizeUrl())).pipe(Effect.flatMap(read));463 482-/** Where the sign-in page's "Continue with Google" goes, if it offers it. */464 const googleLinkIn = (page: Page) =>465 Option.fromNullishOr(466 /<a href="(?<href>\/oauth\/google\/start\?[^"]*)"/u.exec(page.html)?.groups467 ?.href468 ).pipe(Option.map((href) => href.replaceAll("&", "&")));469 489-/** "Continue with Google" from a fresh sign-in page: the Worker's answer, unread. */470 const continueWithGoogle = (world: GoogleWorld) =>471 Effect.gen(function* () {472 const page = yield* openSignIn(world);473 3 unmodified lines477 478 return yield* visit(world, href);479 });480 501-/** Where a response redirects to, parsed. */481 const locationOf = (response: Response) =>482 Option.fromNullishOr(response.headers.get("location")).pipe(483 Option.flatMap((location) => Option.fromNullishOr(URL.parse(location)))484 );485 507-/**508- * A request to `src/worker.ts`'s own handler, on the shim's fake env (no509- * Google client): a GET, or an empty form post to a POST-only path (a GET510- * there answers 404 with Google on too).511- */486 const sendToWorker = (method: "GET" | "POST", path: string) =>487 Effect.promise(() =>488 Promise.resolve(489 worker.fetch(71 unmodified lines561 562 expect(Option.isSome(googleLinkIn(page))).toBeTruthy();563 expect(page.html).toContain("Continue with Google");564 expect(page.html).toContain('formaction="/oauth/google/link"');591- // "Sign in and link Google" posts, then goes on to Google: a browser592- // holds that redirect to `form-action`.565 expect(page.response.headers.get("content-security-policy")).toContain(566 "https://accounts.google.com"567 );568 })62 unmodified lines631 })632 );633 });634 663-/** A browser's form post to `path`; the browser adds its cookies. */635 const formPost = (path: string, fields: Readonly<Record<string, string>>) =>636 new Request(new URL(path, origin), {637 body: new URLSearchParams(fields),638 headers: {2 unmodified lines641 },642 method: "POST",643 });644 674-/** The form `page` carries; the test dies if it carries none. */645 const formIn = (page: Page) =>646 Effect.fromOption(formOf(page.response, page.html, "kept")).pipe(647 Effect.orDie648 );649 680-/**681- * Google's consent for the authorization request `response` redirects to:682- * `consent.sub` signs in at Google, and Google sends the browser back to683- * the callback, from its own site. The callback's answer, read.684- */650 const backFromGoogle = (651 world: GoogleWorld,652 response: Response,653 consent: Consent9 unmodified lines663 Effect.flatMap(read)664 );665 });666 702-/** Chooses `handle` on the pick-a-handle page; the response, unread. */667 const chooseHandle = (world: GoogleWorld, page: Page, handle: string) =>668 Effect.gen(function* () {669 const form = yield* formIn(page);670 6 unmodified lines677 })678 );679 });680 717-/** What `/token` answers, as far as a client reads it. */681 const AccessToken = Schema.fromJsonString(682 Schema.Struct({ access_token: Schema.String })683 );684 722-/** The props of the token a code in `response`'s redirect is traded for. */685 const propsFor = (world: GoogleWorld, response: Response) =>686 Effect.gen(function* () {687 const code = yield* Effect.fromOption(codeOf(response)).pipe(Effect.orDie);688 89 unmodified lines778 const form = yield* formIn(page);779 780 const first = yield* chooseHandle(world, page, "carol");781 820- // The second click left before the first answer cleared the CSRF821- // cookie, so it still carries it; the jar is empty by now, so the822- // browser adds nothing over it.782 const second = new Request(783 formPost("/oauth/google/handle", {784 csrf: form.csrf,785 handle: "carol",205 unmodified lines991 })992 );993 });994 1036-/** Alice's account, signed up with a password. */995 const withAlice = (world: GoogleWorld) =>996 Effect.gen(function* () {997 yield* world.accounts.create(998 Handle.make("alice"),3 unmodified lines1002 )1003 );1004 });1005 1048-/** "Sign in and link Google" from a fresh sign-in page; the response, unread. */1006 const signInAndLink = (world: GoogleWorld, handle: string, password: string) =>1007 Effect.gen(function* () {1008 const form = yield* formIn(yield* openSignIn(world));1009 135 unmodified linesmodified:apps/platform/test/handlers.fixtures.ts-33 removed
1-/**2- * The world the contracts' handlers run over in tests: `ProjectsMemory`3- * over memory adapters (the isomorphic-git Lander on `RepoHostMemory`, a4- * Checker that fails every lane by an assertion, a rules evaluator that5- * returns each scenario's policy), a seeded `FrontPageMemory`, and memory6- * rate limits. `seeded` makes a scenario's project the way its initializer7- * would: made, its first commit pushed, and each of its asks opened red8- * first. Callers reach the handlers through the in-process RPC client, each9- * as the person `as` names.10- */1 import { RefName, RepoHost } from "@repo/artifacts/repo-host";2 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";4 import { CheckRunner } from "@repo/checks/check-runner";25 unmodified lines30 import { MemoryRateLimits } from "../src/adapters/rate-limits.ts";31 32 const mainRef = RefName.make("refs/heads/main");33 44-/** A library of four small packages, as each project's first commit holds it. */34 const start = (name: string): Files => [35 [36 "package.json",37 `{ "name": "${name.slice(name.lastIndexOf("/") + 1)}", "workspaces": ["packages/*"] }\n`,6 unmodified lines44 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],45 ["packages/trim/src/trim.ts", "export const trim = (s) => s;\n"],46 ];47 59-/** An ask's own files: its file in the config folder, and its check. */48 const askFiles = ({ check, file, id, territory }: Ask) =>49 Array.make(50 { content: `export default "${id}";\n`, path: file },51 {11 unmodified lines63 : RepoPath.make(`test/${id}.test.ts`),64 }65 );66 79-/**80- * A Checker before any answer: every lane fails by the same assertion each81- * time, so every ask a test opens is red first on main.82- */67 const allRed = Layer.succeed(68 CheckRunner,69 CheckRunner.of({70 run: ({ lanes }) =>13 unmodified lines84 }),85 })86 );87 104-/**105- * A `RulesEvaluator` that evaluates nothing: for a project it returns its106- * scenario's policy, holding the asks whose files the commit's config folder107- * has, and the judge closure `checks` derives.108- */88 const rulesOf = (scenarios: readonly Scenario[]) =>89 Layer.effect(90 RulesEvaluator,91 Effect.gen(function* () {20 unmodified lines112 });113 })114 ).pipe(Layer.provide(FinishersFromChecks));115 137-/** What the world is made of besides its scenarios' projects. */116 export interface WorldOptions {139- /** What the front page reads back; nothing by default. */117 readonly frontPage?: FrontPageSeed;141- /** Claims and proposals each person may make; 100 of each by default. */118 readonly limits?: {119 readonly claim: number;120 readonly draft?: number;121 readonly proposal: number;1 unmodified line123 }124 125 const noFrontPage: FrontPageSeed = { credits: [], entries: [], projects: [] };126 151-/**152- * The ports the handlers run on, `RepoHost` beside them for `seeded`, fresh153- * for each test.154- */127 export const worldOf = (128 scenarios: readonly Scenario[],129 options: WorldOptions = {}130 ) =>16 unmodified lines147 }),148 EvidenceStoreMemory149 ).pipe(Layer.provideMerge(RepoHostMemory));150 179-/**180- * The scenario's project as its initializer makes it: made, its first181- * commit pushed to `main`, then each of its asks opened, red first.182- */151 export const seeded = (scenario: Scenario) =>152 Effect.gen(function* () {153 const host = yield* RepoHost;154 const api = yield* (yield* Projects).create(scenario.project);17 unmodified lines172 { discard: true }173 );174 }).pipe(Effect.orDie);175 208-/** A client of the contracts in process, each call made as `handle`. */176 export const as = (handle: string) =>177 RpcTest.makeClient(Contracts).pipe(178 Effect.provide(asPerson(Handle.make(handle)))179 );modified:apps/platform/test/handlers.test.ts-27 removed
56 unmodified lines57 import type { WorldOptions } from "./handlers.fixtures.ts";58 59 const people = ["bob", "carol"];60 61-/** datekit: alice decides; bob and carol are vouched for. */61 const datekit = aProject({ people }).pipe(62 withVouches(people),63 withAsk({ id: "parse-iso", territory: "packages/parser" }),64 withAsk({ id: "trim-input", territory: "packages/trim" })65 );66 68-/** burrow: alice decides here too; one ask of its own. */67 const burrow = aProject({ name: "alice/burrow", people }).pipe(68 withVouches(people),69 withAsk({ id: "lex-tokens", territory: "packages/lexer" })70 );5 unmodified lines76 const lexTokens = AskId.make("lex-tokens");77 78 const nowhere = ProjectName.make("alice/nowhere");79 82-/**83- * Both projects as the projection lists them, and one it lists that the84- * platform never made, which a call across projects passes over.85- */80 const listed: FrontPageSeed["projects"] = [81 { openAsks: 2, posture: "open", project: datekit.project },82 { openAsks: 1, posture: "open", project: burrow.project },83 { openAsks: 0, posture: "open", project: nowhere },84 ];85 92-/** The handlers over both projects' world. */86 const platform = (options: WorldOptions = {}) =>87 Handlers.pipe(Layer.provideMerge(worldOf([datekit, burrow], options)));88 96-/** Both projects made, at the scenarios' noon. */89 const made = Effect.gen(function* () {90 yield* advanceTo("2026-10-07T12:00:00Z");91 yield* seeded(datekit);92 yield* seeded(burrow);93 });94 103-/** A call made while serving an HTTP request that reached the platform at `url`. */95 const reachedAt =96 (url: string) =>97 <A, E, R>(call: Effect.Effect<A, E, R>) =>98 Effect.provideService(1 unmodified line100 HttpServerRequest.HttpServerRequest,101 HttpServerRequest.fromWeb(new Request(url, { method: "POST" }))102 );103 113-/** The open decision on `proposal` among a Today's; none fails the test. */104 const decisionOn = (105 decisions: readonly Decision[],106 proposal: Pick<Proposal, "id">107 ) =>61 unmodified lines169 const later = yield* Stream.runCollect(170 bob.watch({ project: datekit.project, since: 1 })171 );172 183- // The adoption lands first; then each ask's opening lands, so each184- // is heard opened, then landed.173 expect(all.map(({ _tag }) => _tag)).toStrictEqual([174 "Landed",175 "AskOpened",176 "Landed",13 unmodified lines190 191 const api = yield* (yield* Projects).get(datekit.project);192 const bobs = Person.make({ handle: Handle.make("bob") });193 206- // 60 claims, each released: 120 events after datekit's adoption207- // landed and its two asks opened, each heard opened and landed.194 yield* Effect.forEach(195 Array.range(1, 60),196 () =>197 Effect.andThen(91 unmodified lines289 const past = yield* Effect.flip(290 alice.claim({ ask: trimInput, project: datekit.project })291 );292 307- // alice's refused claim never reached datekit, so trim-input is free.293 const bobs = yield* bob.claim({294 ask: trimInput,295 project: datekit.project,296 });96 unmodified lines393 const alice = yield* as("alice");394 const bob = yield* as("bob");395 const carol = yield* as("carol");396 412- // bob is new in both projects; datekit's second proposal opens413- // before burrow's, so it expires first.397 yield* bob.claim({ ask: parseIso, project: datekit.project });398 yield* bob.claim({ ask: lexTokens, project: burrow.project });399 400 const declined = yield* bob.proposeAsk({37 unmodified lines438 newcomers: today.newcomers,439 overflow: today.overflow,440 unattended: today.unattended,441 }).toStrictEqual({459- // Five decisions a day in each project; one spent in datekit.442 budget: { finishes: 0, total: 10, used: 1 },443 decider: "alice",444 decisions: [445 { openedAt: "2026-10-07T12:05:00.000Z", project: "alice/datekit" },87 unmodified lines533 it.effect(534 "come from the front-page projection, and a project the platform never made keeps its listed posture",535 () =>536 Effect.gen(function* () {555- // No project is made: only the projection answers, so each listed556- // posture is the projection's own fallback.537 const bob = yield* as("bob");538 539 expect(yield* bob.listProjects({})).toStrictEqual({540 projects: listed,19 unmodified lines560 }).pipe(Effect.provide(platform({ frontPage: projection })))561 );562 });563 584-/** A server side that takes every call as nobody signed in. */564 const anonymous = Layer.succeed(Authenticated, (effect) =>565 Effect.provideService(effect, CurrentPrincipal, Anonymous.make({}))566 );567 31 unmodified lines599 project,600 })601 );602 624- // The project declares no env item, so none takes a value: a625- // decider hears the key is unknown, anyone else that deciders set.603 const setPaymentsKey = {604 key: EnvKey.make("PAYMENTS_KEY"),605 project,606 value: Redacted.make("not-a-real-value-0123456789abcdef"),185 unmodified lines792 }).pipe(Effect.provide(platform()))793 );794 });795 819-/**820- * A rate-limit binding that admits `allowed` calls per key, and keeps every821- * key it was asked about, in order.822- */796 const fakeLimit = (allowed: number) => {797 const keys: string[] = [];798 799 const binding: RateLimit = {129 unmodified linesmodified:apps/platform/test/harness.ts-33 removed
15 unmodified lines16 import { ReleaseStore } from "../src/releases.ts";17 import { HostInfo, serve, Stage } from "../src/surfaces.ts";18 import type { Services } from "../src/surfaces.ts";19 20-/** Where every test request goes: the platform as `served` answers it. */20 export const origin = "http://localhost";21 22 // MCP's 2026-07-28 protocol is stateless: each request names its version and23 // client in `_meta` and repeats its method and target in headers.4 unmodified lines28 "io.modelcontextprotocol/clientInfo": { name: "test", version: "0.0.0" },29 "io.modelcontextprotocol/protocolVersion": version,30 };31 33-/** What an MCP request carries: a tool call names its tool and its arguments. */32 interface Params {33 readonly arguments?: Readonly<Record<string, string>>;34 readonly name?: string;35 }36 39-/** One MCP request over the HTTP transport, as `token`'s bearer if given. */37 const mcpRequest = (method: string, params: Params, token?: string) => {38 const headers = new Headers({39 accept: "application/json, text/event-stream",40 "content-type": "application/json",20 unmodified lines61 method: "POST",62 });63 };64 68-/** A tools/call over MCP's HTTP transport, as `token`'s bearer if given. */65 export const toolCall = (66 name: string,67 args: Readonly<Record<string, string>>,68 token?: string69 ) => mcpRequest("tools/call", { arguments: args, name }, token);70 75-/** A tools/list over MCP's HTTP transport, as `token`'s bearer. */71 export const toolList = (token: string) => mcpRequest("tools/list", {}, token);72 78-/** A tools/call result whose one content block is JSON text. */73 const ToolResult = Schema.Struct({74 content: Schema.Tuple([75 Schema.Struct({76 text: Schema.fromJsonString(Schema.Unknown),4 unmodified lines81 });82 83 const Reply = Schema.fromJsonString(Schema.Struct({ result: ToolResult }));84 91-/** The last JSON-RPC message in a reply, which is plain JSON or an event stream. */85 const lastMessage = (response: Response) =>86 Effect.promise(() => response.text()).pipe(87 Effect.map((text) =>88 response.headers.get("content-type")?.includes("text/event-stream") ===13 unmodified lines102 }),103 })104 );105 113-/** The names of the tools a tools/list reply lists, in its order. */106 export const toolNames = (response: Response) =>107 lastMessage(response).pipe(108 Effect.flatMap(Schema.decodeEffect(Listed)),109 Effect.map(({ result }) => result.tools.map(({ name }) => name))110 );111 120-/** A tool call's outcome: whether it failed, and its JSON. */112 export const toolResult = (response: Response) =>113 lastMessage(response).pipe(114 Effect.flatMap(Schema.decodeEffect(Reply)),115 Effect.map(({ result }) => ({1 unmodified line117 json: result.content[0].text,118 }))119 );120 130-/** A port method a surfaces test never calls: a call is the test's defect. */121 const unused = (port: string) => () =>122 Effect.die(`a surfaces test called ${port}, which it never sets up`);123 134-/**135- * What a surfaces test may leave out: git's ports and the release store,136- * unused (no test here pushes, and only the releases test downloads), a137- * front page that lists no project and the repos behind it, unused (so the138- * skills index is empty), the stage, `local`, and a host with no web app139- * whose drafter is `test-model`.140- */124 const defaults = Layer.mergeAll(125 Layer.succeed(126 Projects,127 Projects.of({ create: unused("Projects"), get: unused("Projects") })8 unmodified lines136 HostInfo.of({ draftModel: "test-model", webUrl: Option.none() })137 )138 );139 157-/**158- * The contracts before any project exists, served by the platform's own159- * handlers: a call that names a project finds none (`UnknownProject`), the160- * front page lists nothing, nobody is near a rate limit, no lane has161- * left a log, and no repo is read.162- */140 export const noProjects = Handlers.pipe(141 Layer.provide([142 Layer.succeed(143 Projects,8 unmodified lines152 Layer.succeed(RepoHost, untouchable<RepoHost["Service"]>("RepoHost")),153 ])154 );155 179-/**180- * The platform's fetch handler over `services`, disposed with the scope: as181- * an Effect, and as the plain function a fetch client calls.182- */156 export const served = Effect.fnUntraced(function* <E>(157 services: Layer.Layer<158 Exclude<159 Services,17 unmodified lines177 handler,178 };179 });180 208-/**209- * A client of the contracts over HTTP at `/rpc`, as the CLI makes one: its210- * requests go to `handler`, each with `token` as its HTTP bearer, which the211- * RPC server reads into every call's headers. Without a token it calls as212- * anyone, as the web does before sign-in.213- */181 export const rpcClient = (182 handler: (request: Request) => Promise<Response>,183 token?: string184 ) => {19 unmodified linesmodified:apps/platform/test/home.test.ts-18 removed
1-/**2- * The platform's `/`: what this host serves, built from the request's3- * origin, the projects the front page lists and the host's own facts. A4- * browser gets HTML; an agent asking for Markdown or plain text gets the5- * text the web serves at `/llms.txt`. Open to a stale credential, as every6- * public path is.7- */1 import { describe, expect, it } from "@effect/vitest";2 import { commandDocs } from "@repo/agent-kit/command-doc";3 import { frontLlms } from "@repo/agent-kit/host-doc";4 import { Brand } from "@repo/brand";26 unmodified lines31 project: ProjectName.make("alice/burrow"),32 },33 ];34 42-/**43- * The platform's projects where datekit's ledger stands sealed: its first44- * config declared sealed checks, which writes no `PostureChanged` row, so45- * the projection still lists it `open`. burrow was never made here.46- */35 const datekitSealed = Layer.succeed(36 Projects,37 Projects.of({38 create: () => Effect.die("the home page makes no project"),8 unmodified lines47 : Effect.fail(new UnknownProject({ project })),48 })49 );50 63-/** The platform's projects before any is made: each listed one keeps its listed posture. */51 const noneMade = Layer.succeed(52 Projects,53 Projects.of({54 create: () => Effect.die("the home page makes no project"),55 get: (project) => Effect.fail(new UnknownProject({ project })),56 })57 );58 72-/**73- * The platform listing `listed`, on a host whose web app is `web`, with74- * `made` for its projects.75- */59 const platform = (60 listed: readonly ProjectListing[],61 web: Option.Option<string> = Option.some(webUrl),62 made: Layer.Layer<Projects> = noneMade10 unmodified lines73 )74 )75 );76 94-/** `/` as `headers` ask for it: its status, type and text. */77 const home = (78 listed: readonly ProjectListing[],79 init: RequestInit = {},80 web?: Option.Option<string>,271 unmodified linesmodified:apps/platform/test/mcp.test.ts+1 added-59 removed
1-/**2- * The platform's MCP surface beside its tools, through its fetch3- * handler composed as the Worker's is (the core loop's world), once dora has made4- * datekit and opened fix-week: an ask's brief is a resource, the projects5- * are one, the platform's skill is the prompt `contribute`, the capped code6- * reads browse datekit for an agent without git, and every tool whose7- * contract can refuse returns its refusal as typed JSON. Requests are8- * MCP's stateless 2026-07-28 ones, built as `harness.ts` builds a tool call.9- */1 import { describe, expect, it, layer } from "@effect/vitest";2 import { commandDocs } from "@repo/agent-kit/command-doc";3 import { readManaged } from "@repo/agent-kit/generated-file";4 import { platformSkill } from "@repo/agent-kit/platform";51 unmodified lines56 const project = ProjectName.make("dora/datekit");57 58 const fixWeek = AskId.make("fix-week");59 69-/** An ask datekit never opened, and a project nobody made. */60 const nope = AskId.make("no-such-ask");61 62 const nowhere = ProjectName.make("alice/nowhere");63 74-/** The lane an ask's `redThenGreen` check runs in. */64 const redThenGreen = LaneName.make("redThenGreen");65 77-/** Where the config folder's sdk is imported from, as a maintainer writes it. */66 const sdk = `${Brand.cliPackage}/rules`;67 80-/** The project as dora first pushes it: one source file, the config folder, the vouches. */68 const start = {69 [`${Brand.configDir}/project.ts`]: [70 `import { kinds, project } from "${sdk}";`,71 ``,10 unmodified lines82 };83 84 const want = "week reads the ISO week of a date";85 99-/** fix-week's own files: its file in the config folder, and its check, which asserts. */86 const askFiles = Array.make(87 {88 content: [89 `import { kinds, territory } from "${sdk}";`,20 unmodified lines110 path: RepoPath.make(`test/${fixWeek}.test.ts`),111 }112 );113 128-/** The core loop's world once dora has made datekit, pushed it, and opened fix-week. */114 class Seeded extends Context.Service<Seeded, CoreLoopWorld>()("test/Seeded") {}115 116 const seeded = Layer.effect(117 Seeded,21 unmodified lines139 return world;140 }).pipe(Effect.orDie)141 );142 158-// --- MCP over HTTP, stateless ------------------------------------------------159-143 const version = "2026-07-28";144 145 const meta = {146 "io.modelcontextprotocol/clientCapabilities": {},147 "io.modelcontextprotocol/clientInfo": { name: "test", version: "0.0.0" },148 "io.modelcontextprotocol/protocolVersion": version,149 };150 168-/** The param the `mcp-name` header repeats, for the methods that route by one. */151 const routedBy = new Map([152 ["prompts/get", "name"],153 ["resources/read", "uri"],154 ["tools/call", "name"],155 ]);156 175-/** One MCP request over the HTTP transport, as `token`'s bearer if given. */157 const mcpRequest = (158 method: string,159 params: Readonly<Record<string, Schema.Json>>,160 token?: string27 unmodified lines188 method: "POST",189 });190 };191 211-/** A JSON-RPC reply: a result, or an error's message. */192 const Reply = Schema.fromJsonString(193 Schema.Struct({194 error: Schema.optionalKey(Schema.Struct({ message: Schema.String })),195 result: Schema.optionalKey(Schema.Unknown),196 })197 );198 219-/** The last JSON-RPC message in a reply, which is plain JSON or an event stream. */199 const replyOf = (response: Response) =>200 Effect.promise(() => response.text()).pipe(201 Effect.map((text) =>202 response.headers.get("content-type")?.includes("text/event-stream") ===6 unmodified lines209 ),210 Effect.flatMap(Schema.decodeEffect(Reply))211 );212 234-/** The result of an MCP call as `token`, decoded with `schema`. */213 const resultOf = <S extends Schema.Top>(214 fetch: (request: Request) => Effect.Effect<Response>,215 schema: S,216 method: string,8 unmodified lines225 return Schema.decodeUnknownEffect(schema)(result);226 })227 );228 251-/** The error message of an MCP call that fails, as `token`. */229 const errorOf = (230 fetch: (request: Request) => Effect.Effect<Response>,231 method: string,232 params: Readonly<Record<string, Schema.Json>>,62 unmodified lines295 })296 ),297 });298 322-/** A tools/call result: whether it failed, and its one content block's JSON. */299 const ToolResult = Schema.Struct({300 content: Schema.Tuple([301 Schema.Struct({302 text: Schema.fromJsonString(Schema.Unknown),2 unmodified lines305 ]),306 isError: Schema.Boolean,307 });308 333-/** A tools/call result whose one content block is plain text, not JSON. */309 const ToolText = Schema.Struct({310 content: Schema.Tuple([311 Schema.Struct({ text: Schema.String, type: Schema.Literal("text") }),312 ]),313 isError: Schema.Boolean,314 });315 341-/** A tools/call result that answered: whether it failed, and its structured content. */316 const Answered = Schema.Struct({317 isError: Schema.Boolean,318 structuredContent: Schema.Unknown,319 });320 347-/** Where an ask's brief is read: `<scheme>ask/<project>/<ask>`. */321 const briefUri = (of: ProjectName, ask: AskId) =>322 `${Brand.urlScheme}ask/${keyOf(of)}/${ask}`;323 351-/**352- * The platform's skill body, from agent-kit's command list: the contracts'353- * commands and the hand-written ones.354- */324 const skillBody = platformSkill({ commands: commandDocs(Contracts) }).pipe(325 Effect.map(([file]) =>326 Option.match(327 Option.flatMap(Option.fromNullishOr(file), ({ content }) =>3 unmodified lines331 )332 )333 );334 366-// --- Each refusing tool, refused --------------------------------------------367-368-/** A contract's own error union, without the `Unauthenticated` its middleware adds. */335 type OwnError<R> =336 R extends Rpc.Rpc<337 infer _Tag,338 infer _Payload,4 unmodified lines343 >344 ? Error["Type"]345 : never;346 381-/** The tags of the contracts whose own error union is not empty. */347 type Refusing<R> = R extends Rpc.Any348 ? [OwnError<R>] extends [never]349 ? never350 : R["_tag"]351 : never;352 388-/** A call a contract refuses in the seeded world, and the refusal it gives. */353 interface Provoked<Tag extends string> {354 readonly args: Rpc.Payload<Rpc.ExtractTag<Contract, Tag>>;355 readonly refusal: OwnError<Rpc.ExtractTag<Contract, Tag>>;356 }5 unmodified lines362 const requestId = RequestId.make("mcp-refused-0001");363 364 const decision = DecisionId.make("dec-000001");365 402-/** A tag datekit never made. */366 const untagged = "v9.9.9";367 405-/**406- * Every contract MCP serves that can refuse, one call it refuses as the407- * operator (who neither made datekit nor claims anything in it), and the408- * refusal it gives.409- */368 const provoked = {369 claim: {370 args: { ask: nope, project },371 refusal: new UnknownAsk({ ask: nope }),110 unmodified lines482 } satisfies {483 readonly [Tag in Refusing<ContractOn<"mcp">>]: Provoked<Tag>;484 };485 528-/** The contracts MCP serves whose error union is not empty, in the group's order. */486 const refusingOnMcp = [...Contracts.requests.values()].filter(487 (rpc) =>488 Context.get(rpc.annotations, Surfaces).includes("mcp") &&489 !SchemaAST.isNever(rpc.errorSchema.ast)3 unmodified lines493 string,494 { readonly args: unknown; readonly refusal: Refusal }495 >(Object.entries(provoked));496 540-// --- The tests ----------------------------------------------------------------541-497 layer(seeded, { excludeTestServices: true, timeout: "120 seconds" })(498 "the platform's MCP surface, once datekit has fix-week open",499 (test) => {500 test.effect("lists the ask brief as a resource template", () =>178 unmodified lines679 expect(statuses).toStrictEqual([401, 401, 401]);680 })681 );682 728- // A connector with no shell browses the canonical repo through these.683 test.effect("reads a file at main as structured content", () =>684 Effect.gen(function* () {685 const world = yield* Seeded;686 const { landed } = yield* world.rpc("anonymous").listRefs({ project });41 unmodified lines728 })729 )(result.structuredContent);730 731 expect(result.isError).toBeFalsy();778- // Folders first, then by name: fix-week added `test/`.732 expect(listing.entries).toStrictEqual([733 { name: Brand.configDir, type: "tree" },734 { name: "src", type: "tree" },735 { name: "test", type: "tree" },35 unmodified lines771 ).toStrictEqual(new UnknownPath({ commit, path: missing }));772 })773 );774 822- // At most 100 commits a page reach a transcript.775 test.effect(776 "refuses a log page of more than 100 commits by its input",777 () =>778 Effect.gen(function* () {40 unmodified lines819 });820 821 const [{ text }] = result.content;822 871- // Before decoding: a call that wrongly succeeded fails here, by872- // this assertion, rather than as a decode error.823+ // Before decoding, so a call that wrongly succeeded fails here, not as a decode error.824 expect(result.isError, `${tag} was not refused`).toBeTruthy();825 826 const refusal = yield* Schema.decodeUnknownEffect(rpc.errorSchema)(827 text9 unmodified lines837 );838 }839 );840 890-// --- As the caller --------------------------------------------------------------891-841 const sessions = MemorySessions.layer({842 "alice-token": Handle.make("alice"),843 "bob-token": Handle.make("bob"),844 });845 897-/** Who a contract is called as, in a word. */846 const callerName = CurrentPrincipal.useSync((principal) =>847 Principal.match(principal, {848 Anonymous: () => "anyone",849 Person: ({ handle }) => handle,850 })851 );852 905-/** fix-week as `showAsk` returns it. */853 const askWire = {854 askedBy: "dora",855 blockedBy: [],856 brief: { want },11 unmodified lines868 state: "open",869 territory: { module: ".", paths: ["src/week.ts"] },870 } as const;871 925-/**926- * A platform with datekit alone, whose `showAsk` and `listAsks` say who927- * called them: the brief names the caller, and so does the one open ask's928- * want.929- */872 const naming = Layer.mergeAll(873 noProjects,874 Contracts.toLayerHandler("showAsk", () =>875 Effect.map(callerName, (who) => ({90 unmodified linesmodified:apps/platform/test/notes.test.ts-48 removed
71 unmodified lines72 const main = RefName.make("refs/heads/main");73 74 const unit = LaneName.make("unit");75 76-/** The verdict the checks gave on `head`: refused, its `unit` lane red. */76 const refusedOn = (head: CommitSha) =>77 Verdict.make({78 ask: AskId.make("fix-week"),79 at: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),24 unmodified lines104 tree: TreeSha.make("3".repeat(40)),105 verifier: "platform",106 });107 109-/** A later verdict on `head`: its checks passed, and it landed. */108 const landedOn = (head: CommitSha) =>109 Verdict.make({110 ...refusedOn(head),111 at: DateTime.makeUnsafe("2026-10-07T12:20:00Z"),12 unmodified lines124 });125 126 const encoded = Schema.encodeEffect(Verdict);127 130-/** A note's text read back as a verdict, encoded again, to compare with what was written. */128 const asVerdict = (note: Option.Option<string>) =>129 Effect.option(130 Schema.decodeEffect(Schema.fromJsonString(Verdict))(131 Option.getOrElse(note, () => "")132 ).pipe(Effect.flatMap(encoded))133 );134 138-/** Real `git http-backend` over the bare repos in `root`, on a local port: its origin. */135 const served = (root: string) =>136 Effect.gen(function* () {137 const node = yield* Effect.context<NodeServices.NodeServices>();138 19 unmodified lines158 ? `http://127.0.0.1:${address.port}`159 : yield* Effect.die("the test server listens on a socket, not a port");160 });161 166-/** What a test of the notes works with: the store, and a folder for clones. */162 interface DiskWorld {163 readonly host: RepoHost["Service"];164 readonly work: string;165 }166 172-/**173- * Bare repos on local disk (`RepoHost` `/local`), served by real `git174- * http-backend`, as the core loop's world serves them: what the platform writes175- * through the port, git reads from the remote.176- */167 const diskWorld: Effect.Effect<168 DiskWorld,169 never,170 NodeServices.NodeServices | Scope.Scope10 unmodified lines181 182 return { host: Context.get(hosts, RepoHost), work };183 });184 195-/**196- * The fork, made with two commits on its main, each an answer's head: the197- * answerer pushed `first`, then `second` on top of it.198- */185 const forkWithTwoHeads = (host: RepoHost["Service"]) =>186 Effect.gen(function* () {187 const client = yield* gitClient(memoryFs());188 17 unmodified lines206 207 return { first, second };208 });209 224-/** `verdict` written as the note on `head` in the fork, through the disk's store. */210 const write = (disk: DiskWorld, head: CommitSha, verdict: Verdict) =>211 writeVerdictNote({ fork, head, verdict }).pipe(212 Effect.provideService(RepoHost, disk.host)213 );214 230-/**231- * The disk's store, whose first `stale` listings of a repo's refs show no232- * notes ref, as a listing made just before another write moved it would;233- * every push it takes is counted.234- */215 const movedUnder = (disk: DiskWorld, stale: number) =>216 Effect.gen(function* () {217 const listings = yield* Ref.make(0);218 const pushes = yield* Ref.make(0);18 unmodified lines237 238 return { host, pushes: Ref.get(pushes) };239 });240 261-/**262- * The disk's store, whose pushes go over git smart HTTP to the repo's263- * remote, as `RepoHost` `/binding` pushes to Artifacts: the push sends264- * every object its source holds that the remote's refs do not reach.265- */241 const overSmartHttp = (disk: DiskWorld) =>242 RepoHost.of({243 ...disk.host,244 push: (name, source, updates) =>6 unmodified lines251 }).pipe(Effect.provide(WorkerFetch))252 ),253 });254 280-/** The disk's store, keeping the updates of every push it takes, in order. */255 const recordingPushes = (disk: DiskWorld) =>256 Effect.map(Ref.make<readonly (readonly RefUpdate[])[]>([]), (pushed) => ({257 host: RepoHost.of({258 ...disk.host,5 unmodified lines264 }),265 pushed: Ref.get(pushed),266 }));267 294-/** Where the fork's notes ref stands, through the port. */268 const notesTip = (host: RepoHost["Service"]) =>269 Effect.map(host.refs(fork).pipe(Effect.orDie), (refs) =>270 Option.fromNullishOr(refs.get(notesRef))271 );272 300-/**301- * A clone of the fork in `work/<name>`, made the first time, then the302- * answerer's read with nothing but git: fetch the notes ref and show the303- * note on `head`. `None` when git shows none.304- */273 const noteInClone = (disk: DiskWorld, name: string, head: CommitSha) =>274 Effect.gen(function* () {275 const fs = yield* FileSystem.FileSystem;276 const clone = `${disk.work}/${name}`;224 unmodified lines501 30_000502 );503 });504 537-/**538- * The note on `head` in bob's fork, read through the port as plain git539- * finds it: the notes ref's tip, that commit's parents, and the note's text.540- */505 const noteOnBobsFork = (head: CommitSha) =>506 Effect.gen(function* () {507 const host = yield* RepoHost;508 const tip = (yield* host.refs(bobFork).pipe(Effect.orDie)).get(notesRef);25 unmodified lines534 tip,535 });536 });537 574-/**575- * The world's store, each push to the fork's notes ref counted; with576- * `refuse`, every such push fails as a store that lost the fork would; with577- * `busy`, that many first ones find the fork busy with another push.578- */538 const countingNotes = (539 options: { readonly busy?: number; readonly refuse?: boolean } = {}540 ) =>541 Effect.gen(function* () {21 unmodified lines563 564 return { counted, pushes: Ref.get(pushes) };565 });566 608-/** Steps over a fresh in-memory record, as a new run of the Workflow instance has. */567 const freshSteps = Effect.flatMap(memoSteps(), (memo) =>568 Layer.build(logged(memo))569 );570 613-/** Every lane on the merged tree green but `unit`, which fails in the file the answer changed. */571 const unitFails = (answer: Admitted) =>572 Effect.gen(function* () {573 yield* scriptProjectLanes(answer.merged, { result: "passed" });574 yield* Checker.use((script) =>13 unmodified lines588 ])589 );590 });591 635-/** Every lane on the merged tree green. */592 const allGreen = (answer: Admitted) =>593 Effect.andThen(594 scriptProjectLanes(answer.merged, { result: "passed" }),595 Checker.use((script) =>596 script.script(answer.merged, askLane, [{ result: "passed" }])597 )598 );599 644-/** The answer's run, over `steps`, its store `host`. */600 const runOver = (601 answer: Admitted,602 steps: Context.Context<StepRunner | StepLog>,603 host: RepoHost["Service"]2 unmodified lines606 Effect.provide(steps),607 Effect.provideService(RepoHost, host)608 );609 655-/** The note `noted` holds, as a verdict encoded again. */610 const noteIn = (611 noted: Option.Option<{ readonly note: Option.Option<string> }>612 ) => asVerdict(Option.flatMap(noted, ({ note }) => note));613 35 unmodified lines649 const steps = yield* freshSteps;650 const outcome = yield* runOver(answer, steps, counted);651 const noted = yield* noteOnBobsFork(answer.head);652 699- // The engine replays the run from its records, the note's step too.653 expect(yield* runOver(answer, steps, counted)).toStrictEqual(outcome);654 expect(yield* pushes).toBe(1);655 expect(656 (yield* StepLog.use(({ names }) => names).pipe(657 Effect.provide(steps)658 )).filter((name) => name.startsWith("notes:"))659 ).toStrictEqual(["notes:Refused", "notes:Refused"]);660 708- // A restarted run starts over a fresh record of steps.661 const restarted = yield* runOver(answer, yield* freshSteps, counted);662 663 expect({664 noted: yield* noteOnBobsFork(answer.head),78 unmodified linesmodified:apps/platform/test/oauth.fixtures.ts-27 removed
1-/**2- * A platform Worker for sign-in tests: the OAuth provider over an in-memory3- * `OAUTH_KV`, accounts and sign-in attempts in their `/memory` adapters,4- * and a stand-in for the rest of the platform. The provider fetches a5- * client's metadata document through the global `fetch`; here the Worker6- * itself answers it, as the public internet does on Cloudflare.7- */1 import { Fetch } from "@repo/artifacts/fetch";2 import { untouchable } from "@repo/testkit/untouchable";3 import { Clock, Effect, Layer, Option, Schema } from "effect";4 import { vi } from "vitest";12 unmodified lines17 export const origin = "https://platform.test";18 19 export const cliClient = cliClientId(origin);20 28-/** RFC 7636 appendix B's verifier and its S256 challenge. */21 export const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";22 23 export const challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";24 25 export const port = 43_123;26 27 export const redirectUri = `http://127.0.0.1:${port}/callback`;28 37-/** A person a named session holds, in the world's `SESSION_TOKENS`. */29 export const namedPerson = "carol";30 40-/** The fake env with one named session, as the demo's stages run. */31 const worldEnv = () => ({32 ...fakeEnv(),33 SESSION_TOKENS: JSON.stringify({34 "carol-token-0123456789abcdef01234567": namedPerson,35 }),36 });37 48-/** A Worker's context the provider is handed and never needs. */38 const context = untouchable<ExecutionContext>("ExecutionContext");39 51-/** What the rest of the platform answers: only the auth routes are the provider's. */40 const platformFetch = (request: Request) =>41 Promise.resolve(42 new Response(`platform: ${new URL(request.url).pathname}`, { status: 418 })43 );44 57-/** A stored access token record, kept whole while its expiry is moved. */45 const decodeTokenRecord = Schema.decodeUnknownEffect(46 Schema.Record(Schema.String, Schema.Unknown)47 );48 62-/**63- * The sign-in Worker, its store and its accounts, for one test. The global64- * `fetch` and the compatibility flag CIMD needs are stubbed for the test's65- * length.66- */49 export const signInWorld = Effect.gen(function* () {50 const config = yield* decodeEnv(worldEnv()).pipe(Effect.orDie);51 52 const accounts = yield* Effect.provide(2 unmodified lines55 );56 57 const store = OAuthStoreMemory.make();58 77- // Google sign-in is off here (no Google client), so it reaches neither78- // its links nor Google.59 const services = Layer.mergeAll(60 Layer.succeed(Accounts, accounts),61 Layer.succeed(OAuthStore, store),62 IdentitiesMemory.layer,22 unmodified lines85 );86 87 const fetch = (request: Request) => Effect.promise(() => send(request));88 109- /** Every access token in the store, made to have expired a second ago. */89 const expireTokens = Effect.gen(function* () {90 const { keys } = yield* Effect.promise(() =>91 store.list({ prefix: "token:" })92 );19 unmodified lines112 });113 114 export type World = Effect.Success<typeof signInWorld>;115 137-/** The hidden fields and the CSRF cookie a sign-in page hands the browser. */116 export interface SignInForm {117 readonly cookie: string;118 readonly csrf: string;119 readonly request: string;4 unmodified lines124 new RegExp(`name="${name}" value="(?<value>[^"]*)"`, "u").exec(html)?.groups125 ?.value126 );127 150-/** The form a page carries, read as a browser would; `cookie` is the one it already holds. */128 export const formOf = (129 response: Response,130 html: string,131 cookie?: string10 unmodified lines142 csrf: field(html, "csrf"),143 request: field(html, "request"),144 });145 169-/** The code a response sends the CLI's loopback, if it redirects there with one. */146 export const codeOf = (response: Response) =>147 Option.fromNullishOr(response.headers.get("location")).pipe(148 Option.flatMap((location) => Option.fromNullishOr(URL.parse(location))),149 Option.filter((url) => url.origin === new URL(redirectUri).origin),150 Option.flatMap((url) => Option.fromNullishOr(url.searchParams.get("code")))151 );152 177-/** The authorization request the CLI opens in a browser. */153 export const authorizeUrl = (state = "state-1", redirect = redirectUri) => {154 const url = new URL("/authorize", origin);155 156 for (const [name, value] of Object.entries({9 unmodified lines166 167 return url;168 };169 195-/** A browser's form post: the fields, the CSRF cookie and the client's address. */170 export const post = (171 path: string,172 fields: Readonly<Record<string, string>>,173 cookie: string,9 unmodified lines183 method: "POST",184 redirect: "manual",185 });186 213-/** The token request the CLI makes with its code and verifier. */187 export const tokenRequest = (code: string, codeVerifier = verifier) =>188 new Request(new URL("/token", origin), {189 body: new URLSearchParams({190 client_id: cliClient,8 unmodified linesmodified:apps/platform/test/oauth.test.ts-12 removed
136 unmodified lines137 state: "state-1",138 },139 };140 141-/** `sealed` with one character of its payload changed. */141 const tampered = (sealed: string) =>142 `${sealed.startsWith("A") ? "B" : "A"}${sealed.slice(1)}`;143 144 describe("a sign-in in progress, sealed into the form", () => {55 unmodified lines200 });201 });202 });203 205-/** A token the fake provider knows, its props, and when it expires (seconds). */204 const issued = (205 props: Readonly<Record<string, string>>,206 expiresAt: number207 ) => ({78 unmodified lines286 }).pipe(Effect.provide(SignInAttemptsMemory.layer))287 );288 });289 292-/** A page's text, beside the response it came in. */290 const read = (response: Response) =>291 Effect.promise(() => response.text()).pipe(292 Effect.map((html) => ({ html, response }))293 );2 unmodified lines296 readonly html: string;297 readonly response: Response;298 }299 303-/** Opens the CLI's sign-in page, as a browser would. */300 const openSignIn = (world: World, state = "state-1") =>301 world.fetch(new Request(authorizeUrl(state))).pipe(Effect.flatMap(read));302 307-/** The form `page` carries; the test dies if it carries none. */303 const formIn = (page: Page, cookie?: string) =>304 Effect.fromOption(formOf(page.response, page.html, cookie)).pipe(305 Effect.orDie306 );307 313-/** Signs up as `handle` from the CLI's sign-in page; the response, unread. */308 const signUp = (world: World, handle: string, secret: string) =>309 Effect.gen(function* () {310 const signInForm = yield* formIn(yield* openSignIn(world));311 18 unmodified lines330 )331 );332 });333 340-/** Signs in as `handle` from a fresh sign-in page; the response, unread. */334 const signIn = (335 world: World,336 handle: string,337 secret: string,16 unmodified lines354 access_token: Schema.String,355 token_type: Schema.String,356 });357 365-/** A code from `response`'s redirect; the test dies without one. */358 const codeIn = (response: Response) =>359 Effect.fromOption(codeOf(response)).pipe(Effect.orDie);360 369-/** An access token for `handle`, by the CLI's whole PKCE flow. */361 const accessTokenFor = (world: World, handle: string, secret: string) =>362 Effect.gen(function* () {363 const code = yield* signIn(world, handle, secret).pipe(364 Effect.flatMap(codeIn)66 unmodified lines431 const world = yield* signInWorld;432 433 const page = yield* openSignIn(world);434 444- // The code goes to the CLI's loopback after the form posts: a445- // browser holds that redirect to `form-action` too.435 expect([436 page.response.status,437 page.response.headers.get("content-type"),438 page.response.headers.get("content-security-policy"),31 unmodified lines470 })471 );472 });473 485-/** A request to `src/worker.ts`'s own handler, on the shim's fake env. */474 const sendToWorker = (path: string) =>475 Effect.promise(() =>476 Promise.resolve(477 worker.fetch(363 unmodified linesmodified:apps/platform/test/pages.test.ts-29 removed
1-/**2- * The platform's own HTML pages (sign-in, which is an MCP client's3- * consent, sign-up, Google's handle page, the problem page, and `/`) load4- * nothing, so each carries its look in one inline `<style>`. This reads5- * that style the way a browser would for each colour scheme and holds its6- * literal colours to WCAG's contrast floors in both: text and links at7- * 4.5:1, input borders at 3:1. The formulas are WCAG 2.2's own (relative8- * luminance over sRGB), written here.9- */1 import { describe, expect, it } from "@effect/vitest";2 import { FrontPageMemory } from "@repo/project/front-page/memory";3 import { Projects } from "@repo/project/projects";4 import { ProjectName } from "@repo/protocol/ids";9 unmodified lines14 import type { Asker, PendingForm } from "../src/auth/pages.ts";15 import { homeResponse } from "../src/home.ts";16 import { HostInfo } from "../src/host-info.ts";17 27-// --- The pages, from stand-in inputs ------------------------------------------28-18 const claude: Asker = {19 clientDomain: "claude.ai",20 clientName: "Claude",21 redirectHost: "claude.ai",71 unmodified lines93 "This sign-in page expired or was not opened here. Start signing in again from your app."94 ),95 } as const;96 108-/** The pages with a form: each input's border must be seen. */97 const FORMS = new Set(["Google's handle page", "sign-in", "sign-up"]);98 111-// --- Reading a style as a browser would ---------------------------------------112-99 interface Rule {100 readonly selectors: readonly string[];101 readonly declarations: ReadonlyMap<string, string>;116- /** Whether it sits in the dark scheme's media query. */102 readonly dark: boolean;103 }104 120-/** The one inline style of a page. */105 const styleOf = (html: string) => {106 const styles = [...html.matchAll(/<style>(?<css>.*?)<\/style>/gsu)];107 108 expect(styles).toHaveLength(1);109 110 return styles[0]?.groups?.css ?? "";111 };112 129-/** How a brace moves the depth of a rule. */113 const DEPTH: ReadonlyMap<string, number> = new Map([114 ["{", 1],115 ["}", -1],116 ]);117 118 const DARK = /^@media\s*\(\s*prefers-color-scheme\s*:\s*dark\s*\)$/u;119 137-/** Every rule of `css`, a dark-scheme media query's marked dark. */120 const rulesOf = (css: string, dark = false): readonly Rule[] => {121 const rules: Rule[] = [];122 const text = css.replaceAll(/\/\*.*?\*\//gsu, "");123 let at = 0;42 unmodified lines166 };167 168 type Scheme = "dark" | "light";169 188-/** A property's value as the scheme sets it, with whether the dark query set any of it. */170 interface Resolved {171 readonly value: string | undefined;172 readonly fromDark: boolean;173 }174 194-/** `property` on `selector` in `scheme`: the last rule that sets it wins, and `var()` resolves on `:root`. */175 const resolve = (176 rules: readonly Rule[],177 scheme: Scheme,178 selector: string,23 unmodified lines202 value: inner.value,203 };204 };205 226-/** `#rgb` or `#rrggbb` as its three channels, 0–255. */206 const channelsOf = (hex: string) => {207 const digits = /^#(?<body>[\da-f]{3}|[\da-f]{6})$/iu.exec(hex)?.groups?.body;208 209 expect(digits, `${hex} is a literal hex colour`).toBeDefined();7 unmodified lines217 Number.parseInt(full.slice(start, start + 2), 16)218 );219 };220 242-/** WCAG 2.2's relative luminance of an sRGB colour. */221 const luminanceOf = (hex: string) => {222 const [r = 0, g = 0, b = 0] = channelsOf(hex).map((channel) => {223 const unit = channel / 255;224 2 unmodified lines227 228 return 0.2126 * r + 0.7152 * g + 0.0722 * b;229 };230 253-/** WCAG 2.2's contrast ratio of two colours. */231 const contrast = (one: string, other: string) => {232 const [light, dark] = [luminanceOf(one), luminanceOf(other)].toSorted(233 (a, b) => b - a234 );235 236 return ((light ?? 0) + 0.05) / ((dark ?? 0) + 0.05);237 };238 262-/** A colour the scheme sets: fails the test when it sets none. */239 const colour = (240 rules: readonly Rule[],241 scheme: Scheme,242 selector: string,5 unmodified lines248 249 return value ?? "";250 };251 276-// --- The checks -----------------------------------------------------------------277-278-/** Every floor, in one scheme, on one page's style. */252 const holdsTheFloors = (253 rules: readonly Rule[],254 scheme: Scheme,255 hasForm: boolean75 unmodified lines331 it.effect("lets the keyboard reach a block that scrolls sideways", () =>332 Effect.gen(function* () {333 const html = yield* page.html;334 362- // A command wider than a phone scrolls in its box: Tab reaches the363- // box, so a keyboard can scroll it.335 expect(html.match(/<pre\b[^>]*>/gu) ?? []).toStrictEqual(336 (html.match(/<pre\b[^>]*>/gu) ?? []).map(() => '<pre tabindex="0">')337 );338 })71 unmodified linesmodified:apps/platform/test/platform.test.ts-7 removed
12 unmodified lines13 import { rpcClient, served, toolCall } from "./harness.ts";14 15 const project = ProjectName.make("alice/datekit");16 17-/** What building the platform from `env` failed with. */17 const failureOf = (env: Env) => Effect.flip(Layer.build(platform(env)));18 19 describe("the platform Worker's env", () => {20 it.effect("lets the operator's token call the contracts", () =>8 unmodified lines29 30 expect(yield* operator.listProjects({})).toStrictEqual({31 projects: [],32 });34- // The projects come from the front page's projection in D1.33 expect(prepared).toHaveLength(1);34 })35 );36 30 unmodified lines67 expect(failure).toStrictEqual(new InvalidEnv({ keys: ["ARTIFACTS"] }));68 })69 );70 73- // Layer repos live in a namespace of their own, which only74- // this Worker binds.71 it.effect("fails to start without the private namespace", () =>72 Effect.gen(function* () {73 const failure = yield* failureOf(without(fakeEnv(), "ARTIFACTS_PRIVATE"));74 34 unmodified lines109 Effect.gen(function* () {110 const { MASTER_KEY } = yield* decodeEnv(fakeEnv());111 112 expect(Redacted.isRedacted(MASTER_KEY)).toBeTruthy();117- // A redacted value prints as its `toString`, never as the value.113 expect(JSON.stringify({ MASTER_KEY })).toBe(114 '{"MASTER_KEY":"<redacted>"}'115 );116 expect(Redacted.value(MASTER_KEY)).toBe(masterKey);100 unmodified lines217 it.effect("hands git's paths to the gateway, outside the 401 gate", () =>218 Effect.gen(function* () {219 const { fetch } = yield* served(platform(fakeEnv()));220 226- // A name the platform never makes: the gateway answers227- // before any port, and nobody is asked to sign in.221 const response = yield* fetch(222 new Request(223 "http://localhost/alice/datekit--layer--alice.git/info/refs?service=git-upload-pack"224 )6 unmodified linesmodified:apps/platform/test/posture-listing.test.ts-14 removed
1-/**2- * `listProjects` as the platform's handlers answer it: the projection lists3- * each project, and each listed project's posture is the one its own4- * ledger stands at now, so the badge and the ledger say the same. The5- * projection here lists datekit as `open`, the row D1 holds for a project6- * whose first config declared sealed checks (that config writes no7- * `PostureChanged` row); datekit's ledger stands sealed. A project the8- * platform never made keeps the posture the projection listed.9- */1 import { describe, expect, it } from "@effect/vitest";2 import { RepoHost } from "@repo/artifacts/repo-host";3 import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";4 import { FrontPageMemory } from "@repo/project/front-page/memory";18 unmodified lines23 const datekit = ProjectName.make("alice/datekit");24 25 const ghost = ProjectName.make("alice/ghost");26 36-/**37- * datekit's project, whose only answered read is the posture its ledger38- * shows, standing sealed; each read counted in `reads`.39- */27 const datekitApi = (reads: Ref.Ref<number>) =>28 untouchable<ProjectApi>("ProjectApi", {29 standing: () =>30 Effect.as(4 unmodified lines35 }36 ),37 });38 52-/** The handlers over projects whose datekit counts its reads in `reads`. */39 const platformCounting = (reads: Ref.Ref<number>) =>40 Handlers.pipe(41 Layer.provide([42 Layer.succeed(78 unmodified linesmodified:apps/platform/test/project-do.fixtures.ts-55 removed
1-/**2- * One project's world for the Project DO's tests: the ports a Project DO3- * runs on, over memory adapters, with the DO's own `Alarms` and4- * `AnswerRuns` adapters over fakes of its storage and the `Answer`5- * Workflow binding, and shells over sqlite-node. The tests drive projects6- * only through the encoded boundary (`encodeCall` → shell → `decodeReply`).7- *8- * The world is the shape of `packages/project/test/world.ts`: the scripted9- * Checker, the rules evaluator that returns the scenario's policy, and10- * pushes made as an answerer's git would make them.11- */1 import { NodeServices } from "@effect/platform-node";2 import { SqliteClient } from "@effect/sql-sqlite-node";3 import { RefName, RepoHost } from "@repo/artifacts/repo-host";4 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";76 unmodified lines81 export const anyone = Anonymous.make({});82 83 export const redThenGreen = LaneName.make("redThenGreen");84 96-/** The project as alice first pushes it. */85 const start: Files = [86 ["package.json", '{ "name": "datekit", "workspaces": ["packages/*"] }\n'],87 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],88 ];89 102-/** `parse-iso`'s own files: its file in the config folder, and its check. */90 export const askFiles = () => {91 const ask = Option.getOrThrow(92 Array.findFirst(scenario.policy.asks, ({ id }) => id === parseIso)93 );16 unmodified lines110 }111 );112 };113 127-/** Main once `parse-iso` opened, with its parser fixed: an answer in its territory. */114 export const fixedFiles: Files = [115 ...start.filter(([path]) => path !== "packages/parser/src/parse.ts"),116 ...askFiles().map(({ content, path }) => [path, content] as const),117 [1 unmodified line119 "export const parse = (s) => ({ year: 2026 });\n",120 ],121 ];122 137-/** The fork a claim of `parse-iso` pushes to. */123 export const forkOf = (who: Person) =>124 RepoName.make(`${keyOf(project)}--${parseIso}--${who.handle}`);125 141-/** What the Checker answers, by `(tree or commit, lane)`; the test adds to it. */126 export class CheckScript extends Context.Service<127 CheckScript,128 {129 readonly script: (3 unmodified lines133 ) => Effect.Effect<void>;134 }135 >()("test/CheckScript") {}136 153-/** Commits made the way an answerer's git would make them, pushed to a repo's `main`. */137 export class Pusher extends Context.Service<138 Pusher,139 {140 readonly push: (4 unmodified lines145 ) => Effect.Effect<CommitSha>;146 }147 >()("test/Pusher") {}148 166-/** Every alarm the DO's storage was asked to set, in epoch milliseconds, in order. */149 export class SetAlarms extends Context.Service<150 SetAlarms,151 { readonly all: Effect.Effect<readonly number[]> }152 >()("test/SetAlarms") {}153 172-/** How an `Answer` Workflow instance stands, as its `status()` reports it. */154 export type InstanceState = Awaited<155 ReturnType<Awaited<ReturnType<AnswerWorkflow["get"]>>["status"]>156 >["status"];157 177-/**178- * Every `Answer` Workflow instance made, in order, how many creates were179- * tried, and every restart asked for; `end` moves an instance to a state180- * the engine would (its run completed, errored or was terminated).181- */158 export class Instances extends Context.Service<159 Instances,160 {161 readonly end: (id: string, state: InstanceState) => Effect.Effect<void>;7 unmodified lines169 readonly tries: Effect.Effect<number>;170 }171 >()("test/Instances") {}172 197-/** At any commit, the scenario's policy, holding the asks whose files the commit has. */173 const rules = Layer.effect(174 RulesEvaluator,175 Effect.gen(function* () {176 const finishers = yield* Finishers;63 unmodified lines240 });241 })242 );243 269-/** The DO's storage, as far as its alarm goes: it keeps every time it is set to. */244 const alarms = Layer.unwrap(245 Effect.sync(() => {246 const set: number[] = [];247 11 unmodified lines259 );260 })261 );262 289-/**290- * The `Answer` Workflow binding: an instance per id, made once. Like the291- * real one, `create` refuses an id it has, `get` finds it, an instance runs292- * once made, and `restart` runs it again from its first step.293- */263 export const answerWorkflow = () => {264 const made = new Map<string, typeof AnswerParams.Encoded>();265 const states = new Map<string, InstanceState>();266 const tries: string[] = [];52 unmodified lines319 );320 })321 );322 354-/**355- * Every port a Project DO's shell takes, over memory adapters and the DO's356- * own `Alarms` and `AnswerRuns` adapters, and what the tests read back.357- * Fresh each time it is built.358- */323 export const world = Layer.mergeAll(324 alarms,325 answers,326 checker,8 unmodified lines335 );336 337 export type World = Layer.Success<typeof world>;338 375-/** A new SQLite file, removed with its folder when the test ends. */339 export const databaseFile = FileSystem.FileSystem.pipe(340 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "project-do-" })),341 Effect.map((folder) => `${folder}/project.sqlite`),342 Effect.orDie,343 Effect.provide(NodeServices.layer)344 );345 383-/**384- * A Project DO's shell over the SQLite at `filename`, on the world's ports,385- * named `name` as `idFromName` names a DO; `Option.none()` for a DO whose id386- * carries no name.387- */346 export const shellOver = (347 filename: string,348 name: Option.Option<ProjectName> = Option.some(project)349 ) =>6 unmodified lines356 sql: SqliteClient.layer({ filename }).pipe(Layer.orDie),357 });358 });359 402-/** One method called on a project, as its own types. */360 export type Call = <M extends ProjectMethod>(361 method: M,362 args: ArgsOf<M>363 ) => Effect.Effect<SuccessOf<M>, ErrorOf<M>>;364 408-/** Calls on a project through its DO's boundary: encoded, answered by `shell`, decoded. */365 export const through =366 (shell: ProjectShell): Call =>367 (method, args) =>368 encodeCall(method, args).pipe(369 Effect.flatMap((request) => shell.call(request)),370 Effect.flatMap((reply) => decodeReply(method, reply))371 );372 417-/**418- * The project made by alice, her first push recorded, and `parse-iso`419- * opened: its check fails twice the same way on main with its files.420- */373 export const opening = (call: Call) =>374 Effect.gen(function* () {375 yield* call("initProject", [alice, {}]);376 17 unmodified lines394 395 return yield* call("openAsk", [alice, { ask: parseIso, files }]);396 });397 446-/** Where `main` of `repo` stands now. */398 export const tipOf = (name: RepoName) =>399 Effect.gen(function* () {400 const refs = yield* (yield* RepoHost).refs(name).pipe(Effect.orDie);401 1 unmodified line403 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))404 );405 });406 456-/** What a call came to: its value, its typed refusal, or `died`. */407 export const outcomeOf = <A, E, R>(effect: Effect.Effect<A, E, R>) =>408 Effect.map(409 Effect.exit(effect),410 Exit.match({5 unmodified lines416 onSuccess: (value) => ({ value }),417 })418 );419 470-/**471- * The `PROJECT` namespace in process: a name is one DO, and its stub runs a472- * shell of its own, over a SQLite of its own, on the world's ports and the473- * test's clock. `names` lists the DOs made, in order.474- */420 export const namespaceOf = inProcessNamespace((name) =>421 shellOver(":memory:", Option.some(name))422 );modified:apps/platform/test/project-do.test.ts-3 removed
119 unmodified lines120 expect(replay).toStrictEqual(receipt);121 expect(yield* Instances.use(({ made }) => made)).toStrictEqual(122 startedOnce123 );124- // The replay never reached the Workflow: one start, not a second the binding refused.124 expect(yield* Instances.use(({ tries }) => tries)).toBe(1);125 }).pipe(Effect.provide(world))126 );127 32 unmodified lines160 }).pipe(Effect.provide(world))161 );162 });163 165-/** A Workflow binding that is down: it neither makes nor finds an instance. */164 const refused = () => Promise.reject(new Error("Workflows are down"));165 166 describe("the Answer Workflow as AnswerRuns", () => {169- /** A queue the Workflow adapter never touches: the instance reaches the DO itself. */167 const queue = untouchable<AnswerQueue>("AnswerQueue");168 169 it.effect("makes one instance for a request started twice", () =>170 Effect.gen(function* () {97 unmodified linesmodified:apps/platform/test/project-namespace.ts-9 removed
1-/**2- * The `PROJECT` namespace in process, for tests that reach Project DOs3- * through `DoProjects` without a Worker: a name is one DO, whose shell4- * `shellFor` makes on the first call that names it and every later call5- * reuses, and its stub's `call` runs on the context the namespace was made6- * in, so each shell lives in that scope.7- */1 import { nameOfKey, ProjectKey } from "@repo/protocol/ids";2 import type { ProjectName } from "@repo/protocol/ids";3 import { untouchable } from "@repo/testkit/untouchable";4 import { Effect, Option, SynchronizedRef } from "effect";5 6 import type { ProjectNamespace } from "../src/adapters/do-projects.ts";7 import type { ProjectShell } from "../src/project-shell.ts";8 16-/** The namespace over `shellFor`'s shells, and the names of the DOs made so far, in order. */9 export const inProcessNamespace = <R>(10 shellFor: (name: ProjectName) => Effect.Effect<ProjectShell, never, R>11 ) =>12 Effect.gen(function* () {2 unmodified lines15 const shells = yield* SynchronizedRef.make<16 ReadonlyMap<string, ProjectShell>17 >(new Map());18 27- /** The DO named `name`: made on its first call, the same one after. */19 const shellOf = (name: string) =>20 SynchronizedRef.modifyEffect(shells, (all) =>21 Option.match(Option.fromUndefinedOr(all.get(name)), {22 onNone: () =>30 unmodified linesmodified:apps/platform/test/ratchet-loop.test.ts-70 removed
1-/**2- * Ratchets and lint-to-zero asks as a decider and two contributors live3- * them, through the platform's own fetch handler with real git:4- * a project that declares a `no-explicit-any`5- * ratchet opens a lint-to-zero ask red first by its count, an answer that6- * drives the count to zero lands and lowers the baseline with no one asked,7- * an answer elsewhere that raises the count is refused `Weakened`, and a8- * reasoned escape waits for a decider, who lets it land or not.9- *10- * The Checker is scripted: each lane's result, and for a count lane the11- * linter's JSON it prints, in oxlint's own shape (`oxlintReport`), per12- * commit or tree.13- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { CheckAt } from "@repo/checks/check-runner";4 import { Verdict } from "@repo/protocol/domain/answer";25 unmodified lines30 const decodeRaw = AskId.make("decode-raw");31 32 const ratchet = RatchetName.make("no-explicit-any");33 47-/** The lane the ratchet's count runs in, named for the ratchet. */34 const ratchetLane = LaneName.make(ratchet);35 50-/** The lane a `lintToZero` ask's check runs in. */36 const lintToZero = LaneName.make("lintToZero");37 53-/** The lane a `redThenGreen` ask's check runs in. */38 const redThenGreen = LaneName.make("redThenGreen");39 56-/** The project's lint, which prints JSON. */40 const lint = "oxlint --format json";41 42 const rule = "typescript/no-explicit-any";43 61-/** Where the config folder's sdk is imported from, as a maintainer writes it. */44 const sdk = `${Brand.cliPackage}/rules`;45 46 const parsePath = "packages/parser/src/parse.ts";47 48 const formatPath = "packages/format/src/format.ts";49 50 const codecPath = "packages/parser/src/codec.ts";51 70-/** Three explicit `any`s in parser, two in format: what main starts with. */52 const anyParse =53 "export const parse = (s: any): any => ({ year: Number(s as any) });\n";54 55 const anyFormat = "export const format = (d: any, f: any) => String(d);\n";56 76-/** The project as dora first pushes it: two packages, the config folder, the vouches. */57 const start = {58 [`${Brand.configDir}/project.ts`]: [59 `import { check, kinds, project } from "${sdk}";`,60 ``,14 unmodified lines75 [formatPath]: anyFormat,76 [parsePath]: anyParse,77 };78 99-/** The lint-to-zero ask's one file: no explicit `any` left in parser. */79 const lintFiles = Array.make({80 content: [81 `import { kinds, territory } from "${sdk}";`,82 ``,7 unmodified lines90 ].join("\n"),91 path: RepoPath.make(`${Brand.configDir}/asks/${noAnyInParser}.ask.ts`),92 });93 115-/** A `fix` ask's files in `module`: its file, and its check, which asserts on `subject`. */94 const fixFiles = (95 ask: AskId,96 module: string,97 want: string,45 unmodified lines143 is: '"2026"',144 name: "decode",145 });146 169-/** One `typescript/no-explicit-any` finding, as oxlint 1.87 prints it. */147 const anyAt = (filename: string, line: number) => ({148 code: "typescript(no-explicit-any)",149 filename,150 help: "Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.",2 unmodified lines153 severity: "error",154 url: "https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-explicit-any.html",155 });156 180-/** What `oxlint --format json` prints for these findings. */157 const oxlintReport = (158 findings: readonly (readonly [path: string, line: number])[]159 ) =>160 JSON.stringify({16 unmodified lines177 [formatPath, 1],178 [formatPath, 1],179 ] as const;180 205-/** The lines git printed from the server's side band, less git's padding. */181 const remoteLines = (stderr: string) =>182 stderr183 .split("\n")184 .filter((line) => line.startsWith("remote: "))185 .map((line) => line.trimEnd());186 212-/** A person in a trailer: their handle and the address the platform gives them. */187 const credited = (handle: string) =>188 `${handle} <${handle}@users.${Brand.domain}>`;189 216-/** A baseline as the tests read it: `[ratchet, territory, count]`. */190 type Baseline = readonly [ratchet: string, territory: string, count: number];191 219-/** Each baseline, in name order. */192 const baselines = (world: CoreLoopWorld) =>193 Effect.map(world.ratchets(project), (rows) =>194 Array.sort(195 rows.map(({ count, ratchet: name, territory }): Baseline => [6 unmodified lines202 )203 )204 );205 234-/** The tree of `head` in a work tree: where an answer whose base is main is checked. */206 const treeOf = (git: GitClient, work: string, head: CommitSha) =>207 Effect.map(git.ok(work, "rev-parse", `${head}^{tree}`), (tree) =>208 CheckAt.cases.Tree.make({ tree: TreeSha.make(tree) })209 );210 240-/** The verdict note on `head` in the clone at `work`, read with plain git. */211 const noteOn = (git: GitClient, work: string, head: CommitSha) =>212 Effect.gen(function* () {213 const ref = `refs/notes/${Brand.slug}`;214 11 unmodified lines226 shown227 ).pipe(Effect.orDie);228 });229 260-/** `as`'s answer, pushed: it claims `ask`, clones its fork and commits `files`. */230 const answer = (231 world: CoreLoopWorld,232 as: Someone,233 git: GitClient,11 unmodified lines245 246 return { claim, head, pushed, tree, work };247 });248 280-/** The merged tree's lanes, scripted: the ratchet's count, and the ask's own check. */249 const scriptAnswer = (250 world: CoreLoopWorld,251 tree: CheckAt,252 input: {11 unmodified lines264 yield* world.script(tree, input.askLane, [input.askResult]);265 yield* world.print(tree, input.askLane, report);266 });267 300-/**301- * Steps 1 to 3: the project, its asks opened red first, alice's answer to302- * the lint-to-zero ask landed (pushed with a harness's audit username), and303- * bob's answer in format refused for what the merged tree counts in parser.304- */268 const ratchetStory = (world: CoreLoopWorld) =>269 Effect.gen(function* () {270 const dora = world.rpc("dora");271 const doraGit = world.git("dora");272 310- // dora makes the project and pushes its first tree.273 yield* dora.initProject({ project });274 275 const home = yield* doraGit.clone(`${world.origin}/${project}.git`);276 277 yield* doraGit.commit(home, "Start burrow", start);278 yield* doraGit.push(home);279 318- // 1. The lint-to-zero ask: twice on main the rule counts 3 in parser.280 const composedLint = CheckAt.cases.Commit.make({281 commit: yield* world.composed(project, lintFiles),282 });283 7 unmodified lines291 });292 293 const afterOpening = yield* baselines(world);294 334- // Two `fix` asks to answer later, each red first by its check.295 for (const [ask, files] of [296 [formatIso, isoFiles],297 [decodeRaw, rawFiles],298 ] as const) {6 unmodified lines305 );306 yield* dora.openAsk({ ask, files, project });307 }308 349- // 2. alice drives the count in parser to zero, through a harness that350- // names itself in her credential helper's username. format still has351- // its two, so the lint exits 1; the ask's check is its count in parser.309 const harnessGit = yield* world.gitWithUsername(310 "alice",311 "audit;harness=pi&model=kimi-k3"312 );19 unmodified lines332 const pushLog = (yield* world.logged).filter(({ annotations }) =>333 annotations.has("harness")334 );335 379- // 3. bob answers format-iso in format; the lint of his merged tree380- // counts one in parser again, over the baseline of zero.336 const bobGit = world.git("bob");337 338 const widened = yield* answer(world, "bob", bobGit, {339 ask: formatIso,23 unmodified lines363 widened,364 };365 });366 412-/**413- * Step 4: alice answers decode-raw with a reasoned escape in parser, which414- * hides its `any` from the lint and raises parser's escapes; dora takes415- * the `Waiver` on Today with `choice`.416- */367 const escapeStory = (world: CoreLoopWorld, choice: Choice) =>368 Effect.gen(function* () {369 const aliceGit = world.git("alice");370 41 unmodified lines412 waiver,413 };414 });415 466-/**467- * alice answers decode-raw with an `any` the lint counts in parser and a468- * reasoned escape beside it, which explains the raise; dora accepts each469- * decision on Today, in turn.470- */416 const raiseStory = (world: CoreLoopWorld) =>417 Effect.gen(function* () {418 const raised = yield* answer(world, "alice", world.git("alice"), {419 ask: decodeRaw,30 unmodified lines450 subjects: today.decisions.map(({ subject }) => subject),451 };452 });453 509-/**510- * alice answers decode-raw with a raise and a reasoned escape; dora accepts511- * the `Waiver` and declines the `RaiseRatchet`, so the answer is refused.512- * alice pushes again on the same claim: the same escape on the same line,513- * and no raise.514- */454 const againStory = (world: CoreLoopWorld) =>455 Effect.gen(function* () {456 const aliceGit = world.git("alice");457 const escape = "// @ts-expect-error -- the codec boundary erases types";51 unmodified lines509 today: (yield* dora.today({ project })).decisions,510 };511 });512 574-/**575- * alice's reasoned escape waits on a `Waiver` while bob's clean answer to576- * format-iso lands; dora then accepts it, alice's land finds main moved,577- * and her answer is merged and checked again on the new main.578- */513 const movedStory = (world: CoreLoopWorld, widened: { readonly work: string }) =>514 Effect.gen(function* () {515 const aliceGit = world.git("alice");516 const bobGit = world.git("bob");15 unmodified lines532 findings: formatOnly,533 });534 yield* world.settle();535 602- // bob's answer, typed this time, lands while alice's waits.536 const typed = yield* bobGit.commit(widened.work, "Type format", {537 [formatPath]:538 "export const format = (d: Date) => d.toISOString().slice(0, 10);\n",539 });5 unmodified lines545 findings: [],546 });547 yield* world.settle();548 616- // alice's answer merged onto the new main, as the Lander will merge it.549 yield* aliceGit.ok(550 escaped.work,551 "fetch",552 "--quiet",80 unmodified lines633 landed: ["Landed"],634 opened: "LintToZero",635 });636 705- // 5. The harness's username is logged with the push, as audit706- // metadata; the push is alice's, by her token.637 expect(638 seen.pushLog.map(({ annotations }) => ({639 harness: annotations.get("harness"),640 model: annotations.get("model"),192 unmodified linesmodified:apps/platform/test/raw.test.ts-12 removed
1-/**2- * A project's raw files through the platform's fetch handler:3- * `GET /<project>/raw/<rev>/<path…>` answers the bytes with their headers4- * to anyone, a stale bearer token or not; a path that climbs out is a5- * 404; and git's own paths beside it still reach git.6- */1 import { describe, expect, it } from "@effect/vitest";2 import { RefName, RepoHost } from "@repo/artifacts/repo-host";3 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";4 import { CodeCacheLive } from "@repo/project/code/cache";15 unmodified lines20 const { project } = datekit;21 22 const readme = "# datekit\n\nDates, parsed.\n";23 30-/**31- * The platform over a world where datekit was made and its first commit,32- * a README and a manifest, pushed to main; and that commit's id. With33- * `reads`, the platform has the isolate's code cache, as `ports.ts` gives34- * it, and each tree its repo host is asked for is counted there.35- */24 const platformWith = (reads: Option.Option<Ref.Ref<number>>) =>25 Effect.gen(function* () {26 yield* advanceTo("2026-10-07T12:00:00Z");27 200 unmodified linesmodified:apps/platform/test/releases.test.ts+3 added-30 removed
9 unmodified lines10 import { MemorySessions } from "../src/sessions/memory.ts";11 import { fakeEnv } from "./fake-env.ts";12 import { noProjects, origin, served, toolCall, toolList } from "./harness.ts";13 14-/** The two binaries a release carries, named as the platform names them. */14 const linux = `${Brand.slug}-linux-x64`;15 16 const darwin = `${Brand.slug}-darwin-arm64`;17 11 unmodified lines29 30 const oldLinuxSha =31 "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf";32 34-/** The manifest the release script writes: two releases, the newer one latest. */33 const manifest = {34 latest: "0.1.0",35 versions: {36 "0.0.9": { assets: { [linux]: { bytes: 5, sha256: oldLinuxSha } } },5 unmodified lines42 },43 },44 };45 48-/** An install script that says which release it installs. */46 const script = (version: string) =>47 `#!/bin/sh\nset -eu\necho "installing ${Brand.cli} ${version}"\n`;48 52-/** The bucket as 715 leaves it, and one file outside `releases/`. */49 const files = {50 "releases/0.0.9/install.sh": script("0.0.9"),51 [`releases/0.0.9/${linux}`]: oldLinuxBytes,52 "releases/0.1.0/install.sh": script("0.1.0"),4 unmodified lines57 };58 59 const sessions = MemorySessions.layer({ "alice-token": Handle.make("alice") });60 65-/**66- * The platform's fetch handler with the release store in memory holding67- * `stored`: `send` takes a path and request options, `fetch` a request, and68- * `reads` lists every key the store was asked for.69- */61 const releasesServed = (62 stored: Readonly<Record<string, string | Uint8Array>>63 ) =>64 Effect.gen(function* () {10 unmodified lines75 fetch(new Request(`${origin}${path}`, init)),76 };77 });78 88-/** A response's body as text. */79 const textOf = (response: Response) => Effect.promise(() => response.text());80 91-/** What a reply says besides its body. */81 const headersOf = (reply: Response) => ({82 cache: reply.headers.get("cache-control"),83 etag: reply.headers.get("etag"),84 length: reply.headers.get("content-length"),1 unmodified line86 status: reply.status,87 type: reply.headers.get("content-type"),88 });89 101-/** A response's body as bytes. */90 const bytesOf = (response: Response) =>91 Effect.map(92 Effect.promise(() => response.arrayBuffer()),93 (buffer) => new Uint8Array(buffer)149 unmodified lines243 it.effect(244 "makes a version's checksums from its manifest, even when the manifest lists an uploaded SHA256SUMS",245 () =>246 Effect.gen(function* () {259- // The release may list the SHA256SUMS it uploaded among a version's files:260- // the served file is still made from the manifest, without a line261- // for itself, and the uploaded copy is never read.247 const listingSums = {248 ...manifest,249 versions: {250 ...manifest.versions,35 unmodified lines286 Effect.gen(function* () {287 const { reads, send } = yield* releasesServed(files);288 289 const paths = [305- // A version never released, and one released without this binary.290 `/releases/9.9.9/${linux}`,291 `/releases/0.0.9/${darwin}`,308- // Names that are not a binary or the checksums.292 `/releases/0.1.0/${Brand.slug}-windows-x64`,293 "/releases/0.1.0/install.sh",294 "/releases/latest/manifest.json",312- // `..` and an encoded `/` in a segment.295 "/releases/0.1.0/..%2F..%2Fsecrets%2Foperator",296 "/releases/..%2F..%2Fsecrets/operator",297 `/releases/..%2F..%2Fsecrets%2Foperator%23/${linux}`,298 `/releases/0.1.0%2F..%2F..%2Fsecrets/${linux}`,87 unmodified lines386 headers: { authorization: "Basic c3RhbGU6dG9rZW4=" },387 }),388 ];389 408- // Beside the releases, a stale token is still refused, and MCP409- // still asks for one.390 const others = [391 yield* send("/install.sh.asc", stale),392 yield* send("/releases", stale),393 yield* send("/releases/0.1.0", stale),65 unmodified lines459 });460 })461 );462 483- // `releases` is a name no project may take (the web forwards484- // `/releases/*` here), so git's paths under it reach the gateway and find485- // no repo; a project's own push still asks for a credential. The releases'486- // own 404 has no body, so the text says the gateway answered.463+ // `releases` is a name no project may take, so git's paths under it reach the gateway464+ // and find no repo. The releases' own 404 has no body, so the text says the gateway465+ // answered.466 it.effect(467 "leaves git's paths to the gateway, which knows no repo named releases",468 () =>469 Effect.gen(function* () {2 unmodified lines472 const reserved = yield* send(473 "/releases/info/refs?service=git-receive-pack"474 );475 497- // A push with no credential: the gateway asks git for one.476 const push = yield* send("/datekit/info/refs?service=git-receive-pack");477 478 expect({479 push: {9 unmodified lines489 })490 );491 });492 515-/**516- * `RELEASES` as R2 answers `get`, over `stored`: each object reads only its517- * body and size; anything else read from the bucket or an object throws.518- */493 const bucketOf = (stored: Readonly<Record<string, string | Uint8Array>>) =>494 untouchable<R2Bucket>("RELEASES", {495 get: (key: string) =>496 Promise.resolve(59 unmodified lines556 })557 );558 });559 586-/** A manifest whose one release holds one file, `name`, as given. */560 const holding = (561 name: string,562 asset: { readonly bytes: number | string; readonly sha256: string }563 ) => ({59 unmodified linesmodified:apps/platform/test/repo-names.test.ts-6 removed
12 unmodified lines13 const parseIso = AskId.make("parse-iso");14 15 const kinds: readonly (readonly [string, RepoKind])[] = [16 ["alice__datekit", RepoKind.Canonical({ project: datekit })],17- // A project made before owners keeps its flat key (ADR 0032).17 [18 "datekit",19 RepoKind.Canonical({ project: ProjectName.make("oscabriel/datekit") }),20 ],21 [22 "alice__date-kit",23 RepoKind.Canonical({ project: ProjectName.make("alice/date-kit") }),24 ],26- // A bare key no project has names nothing.25 ["date-kit", RepoKind.Unknown()],26 [27 "alice__datekit--parse-iso--bob",28 RepoKind.ClaimFork({5 unmodified lines34 [35 "alice__datekit--me--alice",36 RepoKind.WorkingFork({ handle: Handle.make("alice"), project: datekit }),37 ],40- // `layer` is no ask's name; a layer's repo is the visibility cartridge's.38 ["alice__datekit--layer--alice", RepoKind.Unknown()],39 ["alice__datekit--maintainers", RepoKind.Unknown()],43- // A stray `--` splits a name into parts no repo has.40 ["alice__datekit--parse-iso--bob--extra", RepoKind.Unknown()],41 ["alice__datekit----bob", RepoKind.Unknown()],42 ["alice__datekit---parse-iso--bob", RepoKind.Unknown()],43 ["alice__datekit--parse-iso--", RepoKind.Unknown()],44 ["--datekit", RepoKind.Unknown()],49- // The platform spells every handle in a name in lowercase.45 ["alice__datekit--parse-iso--Bob", RepoKind.Unknown()],51- // Not a project's name at all.46 ["Datekit", RepoKind.Unknown()],47 ["datekit.git", RepoKind.Unknown()],48 ];49 27 unmodified linesmodified:apps/platform/test/router-build.test.ts-23 removed
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- */1 import { describe, expect, it } from "@effect/vitest";2 import { untouchable } from "@repo/testkit/untouchable";3 import { env } from "cloudflare:workers";4 import { Effect, Layer, Scheduler, Schema } from "effect";5 unmodified lines10 import { serve } from "../src/surfaces.ts";11 import { callsTo, fakeEnv } from "./fake-env.ts";12 import { origin } from "./harness.ts";13 23-/** A Worker's context, which nothing here needs. */14 const context = untouchable<ExecutionContext>("ExecutionContext");15 26-/** One route, `GET /ping`, answering `pong`. */16 const ping = HttpRouter.use((router) =>17 router.add("GET", "/ping", Effect.succeed(HttpServerResponse.text("pong")))18 );19 31-/** `ping`, beside a layer that counts each time it is built. */20 const counted = () => {21 const builds: number[] = [];22 23 const layer = Layer.merge(3 unmodified lines27 28 return { builds, layer };29 };30 43-/** `ping`, beside a layer that awaits a promise while it is built. */31 const awaiting = Layer.merge(32 ping,33 Layer.effectDiscard(Effect.promise(() => Promise.resolve()))34 );35 49-/**50- * `GET /scheduler`, answering the execution mode of the scheduler its51- * effect runs on, in the context its layer captured while it was built (as52- * `authenticated` does for each credential it verifies).53- */36 const capturing = Layer.unwrap(37 Effect.map(Effect.context(), (built) =>38 HttpRouter.use((router) =>39 router.add(58 unmodified lines98 })99 );100 });101 120-/** What `/health` answers. */102 const Health = Schema.fromJsonString(103 Schema.Struct({ ok: Schema.Boolean, stage: Schema.String })104 );105 3 unmodified lines109 () =>110 Effect.gen(function* () {111 const before = callsTo(env.PROJECT).length;112 132- // Loading runs `serve` and `oauthProvider`, each of which throws if133- // its build awaited anything: a module that loads has both built.113 const worker = yield* Effect.promise(() => import("../src/worker.ts"));114 115 expect(Object.keys(worker.default)).toStrictEqual(["fetch"]);116 expect(callsTo(env.PROJECT)).toHaveLength(before);7 unmodified lines124 const shim = fakeEnv();125 126 const config = yield* decodeEnv(shim).pipe(Effect.orDie);127 149- // As `worker.ts` composes them: each would throw here if its build150- // awaited anything, and `fakeEnv`'s bindings throw when touched.128 const platform = serve(platformOf(config));129 130 const { handler } = oauthProvider(signInServices(config), (request) =>131 platform.handler(request)22 unmodified linesmodified:apps/platform/test/sandbox-adapters.test.ts-34 removed
80 unmodified lines81 lane,82 result: "failed",83 };84 85-/** One lane on an answer's merged tree, cloned from the claim's fork. */85 const checkJob: CheckJob = {86 at: CheckAt.cases.Tree.make({ tree }),87 lanes: [{ command: "bun test", lane }],88 placeholders: [],35 unmodified lines124 const merged = { changes: [{ path, status: "modified" as const }], tree };125 126 const stale = new StaleBase({ base, conflicts: [path], main });127 129-/** What the memory Lander inside the fake sandbox answers, unless a test says otherwise. */128 const landerScript: LanderScript = {129 bundle: [Result.succeed(bundle)],130 compose: [Result.succeed({ commit: composed, tree })],131 land: [Result.succeed({ pending: [], sha: landed })],132 merge: [Result.succeed(merged)],133 };134 137-/** One token a job minted, as the store gave it out. */135 interface Minted {136 readonly repo: RepoName;137 readonly scope: TokenScope;138 readonly ttlMs: number;139 readonly id: string;140 readonly secret: string;141 }142 146-/**147- * The memory store with the canonical repo and a claim's fork, recording148- * every token it mints and every revoke it is asked for; with `failRevoke`,149- * every revoke dies after it is recorded, its error echoing the token's150- * secret.151- */143 const recordingRepoHost = (failRevoke: boolean) =>144 Effect.gen(function* () {145 const store = yield* RepoHost;146 const minted: Minted[] = [];34 unmodified lines181 182 return { host, minted, revoked };183 }).pipe(Effect.provide(RepoHostMemory));184 194-/** Every wire the fake sandbox decoded, by method. */185 interface Seen {186 readonly bundleRules: (typeof BundleWire.Type)[];187 readonly check: (typeof CheckWire.Type)[];188 readonly compose: (typeof ComposeWire.Type)[];189 readonly land: (typeof LandWire.Type)[];190 readonly merge: (typeof MergeWire.Type)[];191 }192 203-/**204- * The sandbox Worker's entrypoint as the service binding reaches it, in205- * memory: each method decodes its wire with its schema, runs the memory206- * `CheckRunner` or `Lander` it was built over, and encodes the `Exit`. It207- * keeps every wire it decoded, by method.208- */193 const fakeSandbox = Effect.gen(function* () {194 const run = yield* FiberSet.makeRuntimePromise<CheckRunner | Lander>();195 196 const seen: Seen = {3 unmodified lines200 land: [],201 merge: [],202 };203 220- /** Decodes a wire into `into`, runs its job, and encodes the outcome. */204 const answer =205 <W, WI, A, E, X>(206 wire: Schema.Codec<W, WI>,207 exit: Schema.Codec<Exit.Exit<A, E>, X>,35 unmodified lines243 });244 245 interface WorldOptions {246 readonly script?: LanderScript;264- /** The binding the adapters get, made from the fake's. */247 readonly binding?: (sandbox: SandboxBinding) => SandboxBinding;248 readonly failRevoke?: boolean;249 }250 269-/**270- * Both adapters over a fake sandbox and a recording store, and what the271- * fake and the store saw.272- */251 const world = (options: WorldOptions = {}) =>252 Effect.gen(function* () {253 const { host, minted, revoked } = yield* recordingRepoHost(254 options.failRevoke ?? false25 unmodified lines280 281 return { host, lander, minted, revoked, runner, seen: fake.seen };282 });283 306-/** One log line, as the structured logger renders it. */284 type Line = ReturnType<typeof Logger.formatStructured.log>;285 309-/** Runs `body` with every log line it writes kept: its exit, and the lines. */286 const withLogs = <A, E>(body: Effect.Effect<A, E>) =>287 Effect.gen(function* () {288 const lines: Line[] = [];289 9 unmodified lines299 300 return { exit, lines };301 });302 327-/** Which repo each token was minted on, with which scope. */303 const mintsOf = (minted: readonly Minted[]) =>304 minted.map(({ repo, scope }) => ({ repo, scope }));305 331-/** A wire remote, with its token in the clear for comparing. */306 const opened = (remote: {307 readonly token: Redacted.Redacted;308 readonly url: string;309 }) => ({2 unmodified lines312 });313 314 type World = Effect.Success<ReturnType<typeof world>>;315 342-/** Every operation of both adapters once, a land for each rebuild that reads a fork or not. */316 const everyJob = ({317 lander,318 runner,319 }: World): readonly Effect.Effect<7 unmodified lines327 lander.compose(composeJob),328 lander.bundleRules(bundleJob),329 ];330 358-/** By token id, so revokes in any order compare. */331 const byId = <T extends { readonly id: string }>(tokens: readonly T[]) =>332 tokens.toSorted((a, b) => a.id.localeCompare(b.id));333 362-/**363- * The sandbox Worker's default entrypoint, by its shape in364- * `apps/sandbox/src/worker.ts` (an app may not import another app).365- */334 interface SandboxEntrypoint extends WorkerEntrypoint<Env> {335 readonly check: (336 wire: typeof CheckWire.Encoded337 ) => Promise<typeof CheckExit.Encoded>;166 unmodified lines504 })505 );506 });507 540-/** A way the sandbox's `merge` can fail to answer with an `Exit`, each echoing a token it was sent. */508 interface Breakage {509 readonly name: string;510 readonly failure: string;511 readonly merge: SandboxBinding["merge"];31 unmodified lines543 name: "dies on the far side",544 },545 ];546 580-/** Every secret in `minted` that `text` contains. */547 const leaked = (text: string, minted: readonly Minted[]) =>548 minted.flatMap(({ secret }) => (text.includes(secret) ? [secret] : []));549 550 describe("a sandbox job that fails", () => {162 unmodified linesmodified:apps/platform/test/serve-world.ts+5 added-68 removed
1-/**2- * The core loop's world (`world.ts`) as a process of its own:3- * `bun apps/platform/test/serve-world.ts` serves the platform's fetch4- * handler on a local port, composed as the Worker composes it, and prints5- * one JSON line, `{"origin":"http://127.0.0.1:<port>"}`, once it serves. It6- * serves until its stdin ends (the process that started it closed it, or7- * died) or it is told to stop.8- *9- * Three things differ from the world a test builds in process:10- *11- * - The Checker runs each lane for real, under `sh -c`, in a clone of the12- * commit or tree it is given (`CheckRunnerLocal`), so an ask's check is13- * red first, or not, by what it really does.14- * - Beside dora, alice and bob, the people in `WORLD_SESSIONS` (a JSON15- * object from token to handle, as `SESSION_TOKENS` is) may call.16- * - Every answer run a push queues is carried a moment later, for as long17- * as the world serves, as the `Answer` Workflow carries it on a stage:18- * an answer pushed over git lands with nobody calling `settle` (smoke's19- * `--loop` runs against this world).20- * - Every cartridge the platform plugs in (`cartridges.ts`) is plugged in21- * here too, as `ports.ts` plugs them into the Worker, for a stage whose22- * private namespace is the world's second store of bare repos: so a23- * project that declares a layer gets its repo there, and its maintainers24- * clone and push it through the gateway. The `Answer` Workflow25- * the cartridge starts an admission on keeps the instance and runs26- * nothing: the world carries no Workflow.27- * - A proposal made with a draft is drafted in process as it is made28- * (`@repo/drafting`'s inline runs, over the Worker's ports), by the29- * memory drafter scripted with the canned draft, whose test fails on any30- * `src/parse.ts` without a `parseOrdinal`: so smoke's `--loop --draft`31- * sees a draft go red first and open on accept with no model.32- *33- * The seed's `--world node` runs it (`scripts/lib/seed.ts`) and34- * reaches it over HTTP and git, as it reaches a stage. A process, not an35- * import: apps never import apps, and no file outside the platform imports36- * its test world. The Worker's modules import `cloudflare:workers`, which37- * `world-process.ts` serves from the shim before this file loads them.38- */1+// Run as a process (`bun apps/platform/test/serve-world.ts`), not imported: apps never2+// import apps. Prints `{"origin":"http://127.0.0.1:<port>"}` once it serves, and3+// serves until its stdin ends.4 import { NodeRuntime, NodeServices } from "@effect/platform-node";5 import type { RepoHost } from "@repo/artifacts/repo-host";6 import { CheckRunner, shaOf } from "@repo/checks/check-runner";7 import type { CheckAt } from "@repo/checks/check-runner";25 unmodified lines33 import { fakeEnv, withPrivateNamespace } from "./fake-env.ts";34 import { shimWorkers, worldSessions } from "./world-process.ts";35 import type { PlugIn } from "./world.ts";36 72-/**73- * A clone of the bare repo at `bare`, its work tree set to `at`, removed74- * when the job ends. The clone shares the repo's objects, so a composed or75- * merged commit is there whatever ref holds it.76- */37 const checkoutIn = (bare: string) => (at: CheckAt) =>38 Effect.gen(function* () {39 const fs = yield* FileSystem.FileSystem;40 20 unmodified lines61 62 return read.exitCode === 0 ? tree : yield* new VerifierBlocked({});63 }).pipe(Effect.provide(NodeServices.layer));64 105-/** The Checker over the world's bare repos: each job's lanes, for real, in a clone of its repo. */65 const localChecker = (repos: string): Layer.Layer<CheckRunner> =>66 Layer.succeed(67 CheckRunner,68 CheckRunner.of({7 unmodified lines76 ),77 })78 );79 121-/**122- * The `Answer` Workflow, as far as an admission's start reaches it: the123- * instance is made, or found, and kept; nothing runs it.124- */80 const keptAdmissions = untouchable<Env["ANSWER"]>("ANSWER", {81 create: (options) =>82 Promise.resolve(83 untouchable<WorkflowInstance>("an admission", {3 unmodified lines87 get: (id) =>88 Promise.resolve(untouchable<WorkflowInstance>("an admission", { id })),89 });90 136-/**137- * Every cartridge in `plugged`, for one stage's config, merged. Typed as138- * `ports.ts` types them, so a platform whose `cartridges.ts` names none (a139- * cartridge deleted) still typechecks here.140- */91+// Typed as `ports.ts` types them, so a platform whose `cartridges.ts` names none92+// still typechecks here.93 const pluggedFor =94 (plugged: typeof Cartridges) =>95 (config: PlatformConfig): Layer.Layer<never, never, WorkerPorts> => {96 const each: readonly Cartridge[] = Object.values(plugged);3 unmodified lines100 ...each.map((cartridge) => cartridge(config))101 );102 };103 152-/**153- * Every cartridge in `plugged`, over the world's ports, for a stage whose154- * private namespace is `aside`: over the Worker's ports as they are, and155- * over each Project DO's, which reach no `Projects` (only the gateway's156- * side asks it, and a DO serves no git).157- */104 const cartridgesOver =105 (106 plugged: typeof Cartridges,107 decode: typeof decodeEnv17 unmodified lines125 worker: all,126 };127 };128 183-/**184- * `plugIn` with draft runs in process beside it: each Project DO starts its185- * rounds inline, on the Worker's ports (which the Worker's side hands over186- * once built) and `drafter`.187- */129 const withDrafts = (130 plugIn: PlugIn,131 ready: Deferred.Deferred<Context.Context<InlinePorts>>,132 drafter: Context.Context<Drafter>11 unmodified lines144 )145 ),146 });147 207-/** How long after the last round the world carries queued answer runs again. */148 const CARRY_EVERY = Duration.millis(250);149 150 const serve = Effect.gen(function* () {151 yield* shimWorkers;19 unmodified lines171 plugIn: (aside) => withDrafts(plugged(aside), ready, drafter),172 sessions,173 });174 235- // The Answer Workflow's stand-in: the queued runs, carried every236- // `CARRY_EVERY` while the world serves. A run that dies is logged, and237- // the next round carries on.175 yield* world.settle().pipe(176 Effect.catchCause((cause) =>177 Effect.logWarning("the world's answer runs failed", cause)178 ),15 unmodified linesmodified:apps/platform/test/step.test.ts-8 removed
10 unmodified lines11 } from "../src/workflows/step.ts";12 13 const sha = LandedSha.make("a".repeat(40));14 15-/** A value whose encoded form differs from it: a date and an option. */15 const Landing = Schema.Struct({16 at: Schema.DateTimeUtcFromString,17 sha: Schema.OptionFromOptionalKey(LandedSha),18 });2 unmodified lines21 at: DateTime.makeUnsafe("2026-10-08T12:00:00Z"),22 sha: Option.some(sha),23 };24 26-/**27- * A Workflow's steps as the engine runs them, in memory: a step's first run28- * records what its body returns under its name; a replay returns the29- * record without running it. It keeps every retry config it was given.30- */25 const fakeWorkflowStep = () => {26 const recorded = new Map<string, Promise<Schema.Json>>();27 const retries: WorkflowStepRetries[] = [];28 10 unmodified lines39 return kept;40 },41 };42 49- /** What the engine recorded for `name`; `null` if it ran no such step. */43 const record = (name: string) =>44 Effect.promise(() => recorded.get(name) ?? Promise.resolve(null));45 46 return { record, retries, steps };47 };48 56-/** A step that counts its runs and lands. */49 const counted = (runs: Ref.Ref<number>) =>50 Effect.as(51 Ref.update(runs, (n) => n + 1),52 landing113 unmodified linesmodified:apps/platform/test/surfaces.test.ts-5 removed
32 unmodified lines33 const project = ProjectName.make("alice/datekit");34 35 const requestId = RequestId.make("answer-0001");36 37-/** An answer, as a client offers it. */37 const args = { ask, base, head, project, requestId };38 40-/** What the platform answers when it takes the answer in. */39 const receipt = {40 ...args,41 outcome: Outcome.cases.Checking.make({ stage: "merge" }),42 };2 unmodified lines45 "alice-token": Handle.make("alice"),46 "bob-token": Handle.make("bob"),47 });48 51-/** The platform where only `holder` holds the ask's claim. */49 const claimHeldBy = (holder: string) =>50 Layer.mergeAll(51 noProjects,52 Contracts.toLayerHandler("submitAnswer", (payload) =>32 unmodified lines85 expect(asBob.json).toHaveProperty("_tag", "NotClaimed");86 })87 );88 92- // A stream has no tool form, and a write-only value must never pass93- // through an agent's transcript.89 it.effect("lists the MCP-surfaced contracts only: no watch, no setEnv", () =>90 Effect.gen(function* () {91 const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));92 77 unmodified linesmodified:apps/platform/test/w9-contracts.test.ts-10 removed
1-/**2- * The code browser's, the people page's and drafting's contracts and3- * routes, wired end to end through the platform's fetch handler: the4- * policy read answers, the code reads reach the façade (`why` here; the5- * others are `code-reads.test.ts`'), a draft needs a person, and `/` and a6- * project's raw files have their routes, open to a stale credential as7- * every public path is (a raw file at no revision is a 404).8- */1 import { describe, expect, it } from "@effect/vitest";2 import { AskId, ProposalId, RepoPath } from "@repo/protocol/ids";3 import { Unauthenticated } from "@repo/protocol/principal";4 import { advanceTo } from "@repo/testkit/clock";13 unmodified lines18 const { project } = datekit;19 20 const sessions = MemorySessions.layer({});21 30-/** The platform over datekit's world, seeded: made, pushed to, its ask open. */22 const platform = Effect.gen(function* () {23 yield* advanceTo("2026-10-07T12:00:00Z");24 25 const world = yield* Layer.build(worldOf([datekit]));15 unmodified lines41 42 const read = yield* anyone.projectPolicy({ project });43 const { policy } = read;44 54- // It evaluated, so there is nothing to say why not.45 expect(Object.keys(read)).toStrictEqual(["policy"]);46 expect(policy?.source).toBe("config");47 expect(policy?.deciders).toStrictEqual(datekit.policy.deciders);48 expect(Object.keys(policy ?? {})).not.toContain("visibility");111 unmodified linesmodified:apps/platform/test/watch.test.ts-69 removed
1-/**2- * `watch` live. Over the Node platform world, a3- * watcher that speaks the framed `/rpc` (NDJSON) hears a project's kept4- * events in order and then each one as it is committed, until it goes5- * away; a watcher from a sequence number hears only what came after.6- *7- * Underneath, the Project DO's watch room (the hibernation API, over a fake8- * `DurableObjectState` that records the sockets it accepts, and a real9- * shell over sqlite-node) keeps the newest 500 events for a socket opened10- * from 0 and sends every socket what a call or an alarm committed, after11- * the commit.12- */1 import { describe, expect, expectTypeOf, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { CheckAt } from "@repo/checks/check-runner";4 import { Contracts } from "@repo/protocol/contracts";57 unmodified lines62 const parseIso = AskId.make("parse-iso");63 64 const redThenGreen = LaneName.make("redThenGreen");65 78-/** Where the config folder's sdk is imported from, as a maintainer writes it. */66 const sdk = `${Brand.cliPackage}/rules`;67 81-/** The project as dora first pushes it. */68 const start = {69 [`${Brand.configDir}/project.ts`]: [70 `import { kinds, project } from "${sdk}";`,71 ``,9 unmodified lines81 "src/parse.ts":82 "export const parse = (iso: string) => ({ month: 0, year: 0 });\n",83 };84 99-/** `parse-iso`'s own files: its file in the config folder, and its check. */85 const isoFiles = Array.make(86 {87 content: [88 `import { kinds, territory } from "${sdk}";`,20 unmodified lines109 path: RepoPath.make(`test/${parseIso}.test.ts`),110 }111 );112 128-/** alice's answer to parse-iso: the year, read. */113 const yearRead =114 "export const parse = (iso: string) => ({ month: 0, year: Number(iso.slice(0, 4)) });\n";115 132-/** How long a live event may take to reach a watcher. */116 const LIVE = "5 seconds";117 135-/**136- * Anyone's client of the contracts over the framed `/rpc`: each call137- * posted as NDJSON, and its answer read message by message as it comes.138- */118 const framedClient = (world: CoreLoopWorld) =>119 RpcClient.make(Contracts).pipe(120 Effect.provide(121 RpcClient.layerProtocolHttp({ url: `${world.origin}/rpc` }).pipe(1 unmodified line123 )124 )125 );126 148-/**149- * `events` heard for as long as the test lasts: what has come so far, in150- * the order it came. A stream that fails stops the hearing; what it heard151- * stays.152- */127 const hearing = <E, R>(events: Stream.Stream<ProjectEvent, E, R>) =>128 Effect.gen(function* () {129 const heard = yield* Ref.make<readonly ProjectEvent[]>([]);130 5 unmodified lines136 137 return heard;138 });139 166-/** A watcher of `project` from `since` over `client`. */140 const watcher = (client: Client["Service"], since: number) =>141 hearing(client.watch({ project, since }));142 170-/** What `heard` holds once `done` says so, or once `LIVE` has passed. */143 const heardUntil = (144 heard: Ref.Ref<readonly ProjectEvent[]>,145 done: (events: readonly ProjectEvent[]) => boolean146 ) =>2 unmodified lines149 Effect.timeoutOption(LIVE),150 Effect.andThen(Ref.get(heard))151 );152 181-/** Each event's tag and sequence number: what a watcher heard, in brief. */153 const brief = (events: readonly ProjectEvent[]) =>154 events.map(({ _tag, seq }) => `${seq} ${_tag}`);155 185-/** Whether `events` run on from `since` with no number skipped or repeated. */156 const unbroken = (events: readonly ProjectEvent[], since: number) =>157 events.every(({ seq }, index) => seq === since + index + 1);158 189-/** Whether `event` is an answer's landing, not an ask's opening. */159 const answered = (event: ProjectEvent) =>160 ProjectEvent.guards.Landed(event) && event.landing.ask !== undefined;161 193-/** The project made, first pushed, and `parse-iso` opened red first by dora. */162 const datekitOpened = (world: CoreLoopWorld) =>163 Effect.gen(function* () {164 const dora = world.rpc("dora");165 const doraGit = world.git("dora");24 unmodified lines190 const framed = yield* framedClient(world);191 192 yield* datekitOpened(world);193 226- // Over JSON, `watch` still replays and ends: a buffered answer227- // cannot carry a live tail. It is what the replay should be.194 const kept = yield* Stream.runCollect(195 reader.watch({ project, since: 0 })196 );197 3 unmodified lines201 first,202 (events) => events.length >= kept.length203 );204 239- // alice claims: the watcher hears it without asking again.205 const { claim } = yield* world206 .rpc("alice")207 .claim({ ask: parseIso, project });208 2 unmodified lines211 );212 213 const claimedAt = claimed.findLast(ProjectEvent.guards.Claimed);214 250- // Her answer lands.215 const aliceGit = world.git("alice");216 const work = yield* aliceGit.clone(claim.remote);217 218 const fix = yield* aliceGit.commit(work, "Read the year", {13 unmodified lines232 );233 234 yield* world.settle();235 272- // Her answer's landing: the opening's was heard in the replay.236 const landedAt = (yield* heardUntil(first, (events) =>237 events.some(answered)238 ))239 .filter(ProjectEvent.guards.Landed)6 unmodified lines246 project,247 sha: LandedSha.make(landedAt.landing.sha),248 })).landing;249 287- // A second watcher from the claim's number hears only what came after.250 const since = claimedAt?.seq ?? 0;251 252 const after = yield* Stream.runCollect(253 reader.watch({ project, since })33 unmodified lines287 replayed: ["1 Landed", "2 AskOpened", "3 Landed"],288 resumed: ["5 Pushed", "6 Judged", "7 Landed", "8 AskClosed"],289 unbroken: { first: true, second: true },290 });329- // Over JSON, the same events replay and end.291 expect({ after: brief(after), kept: brief(kept) }).toStrictEqual({292 after: brief(resumed),293 kept: brief(replayed.slice(0, kept.length)),294 });23 unmodified lines318 const kept = yield* Stream.runCollect(319 reader.watch({ project, since: 0 })320 );321 361- // The RPC server puts a call's own headers after the HTTP362- // request's, so only the request itself says how it was framed.322 const claimingFramed = yield* Stream.runCollect(323 reader.watch(324 { project, since: 0 },325 {9 unmodified lines335 60_000336 );337 });338 380-/**381- * A Project DO's state as far as its watch sockets go: it records every382- * socket it accepts with its tags, and finds the ones still open again.383- */339 const fakeState = () => {340 const accepted: { readonly socket: WebSocket; readonly tags: string[] }[] =341 [];342 14 unmodified lines357 };358 359 return {360 accepted,406- /** The watcher went away: the runtime no longer lists its socket. */361 close: (socket: WebSocket) => {362 closed.add(socket);363 },364 state,1 unmodified line366 };367 368 const decodeFrame = Schema.decodeEffect(Schema.fromJsonString(WatchFrame));369 416-/** What the room keeps on a socket: where it stands, or nothing once hibernation lost it. */370 type Attachment = { readonly seq: number } | null;371 419-/** The DO's end of a watcher's socket: every frame it was sent, decoded, in order. */372 const doSocket = () => {373 const sent: string[] = [];374 let attachment: Attachment = null;375 376 const socket = untouchable<WebSocket>("WebSocket", {377 deserializeAttachment: () => attachment,426- // The room sends text frames only.378 send: (message: string) => {379 sent.push(message);380 },381 serializeAttachment: (value: Attachment) => {6 unmodified lines388 socket,389 };390 };391 441-/** Each frame's number and its event's tag. */392 const framed = (frames: readonly WatchFrame[]) =>393 frames.map(({ event, seq }) => `${seq} ${event._tag}`);394 395 const noon = "2026-10-07T12:00:00Z";8 unmodified lines404 const { accepted, state } = fakeState();405 const room = watchRoom(state, yield* shellOver(":memory:"));406 const call = through(room);407 458- // The adoption lands, parse-iso opens and its opening lands (3459- // events), then 300 claims, each released (600).408 yield* opening(call);409 yield* Effect.forEach(410 Array.range(1, 300),411 () =>139 unmodified lines551 552 const watched = doSocket();553 554 yield* room.admit(watched.socket, 3);607- // Hibernation woke it without its attachment.555 watched.socket.serializeAttachment(null);556 557 yield* call("claim", [bob, doParseIso]);558 1 unmodified line560 }).pipe(Effect.provide(doWorld))561 );562 });563 617-/**618- * A watcher's socket as `WebSocketPair` makes it: the Worker's end hears619- * what the DO's end sends (held until it listens, as the runtime holds it620- * until `accept`), and either end's close reaches the other. `gone` is told621- * when the socket closes, as the runtime stops listing it.622- */564 const socketPair = (gone: (socket: WebSocket) => void) => {565 const events = new EventTarget<WebSocketEventMap>();566 const held: string[] = [];567 let listening = false;10 unmodified lines578 gone(server);579 events.dispatchEvent(new Event("close"));580 },581 deserializeAttachment: () => attachment,641- // The room sends text frames only.582 send: (message: string) => {583 if (!open) {584 throw new Error("the socket is closed");585 }30 unmodified lines616 617 return { client, server };618 };619 680-/**681- * The `PROJECT` namespace over one project's watch room, as the Worker682- * reaches it: `call` runs on the room, so its watchers are settled after683- * each, and `fetch` opens a watch socket on it, or none when `refuses`.684- * `opened` lists the number each socket was opened from, in order;685- * `server` is the DO's end of the newest.686- */620 const roomNamespace = (refuses = false) =>621 Effect.gen(function* () {622 const run = yield* FiberSet.makeRuntimePromise();623 const sockets = fakeState();33 unmodified lines657 server: Effect.sync(() => servers.at(-1)),658 };659 });660 728-/** `watch` live from `since` on the room's project, through the Worker's handler and the namespace. */661 const relayedFrom = (namespace: ProjectNamespace & WatchNamespace, since = 0) =>662 watchHandler({ project: doProject, since }, { live: true }).pipe(663 Stream.provideService(ProjectSockets, Option.some(namespace)),664 Stream.provide(DoProjects(namespace))45 unmodified lines710 const heard = yield* hearing(relayedFrom(namespace));711 712 yield* heardUntil(heard, (events) => events.length >= 4);713 782- // The DO restarts: its end of the socket closes.714 (yield* server)?.close(1012, "restarting");715 716 yield* heardUntil(heard, () => false).pipe(717 Effect.repeat({72 unmodified linesmodified:apps/platform/test/well-known.test.ts-23 removed
1-/**2- * The projects' contribute skills, found where agents look for skills:3- * `/.well-known/agent-skills/index.json` lists each4- * project whose landed tree holds `.agents/skills/<project>-contribute/SKILL.md`,5- * with the SHA-256 of that file's bytes, and each listed URL serves the file6- * as it landed. Anyone may read them, with no credential or a stale one.7- * Through the platform's fetch handler over the Node world, with real git;8- * and `agentSkills` itself over memory adapters, for a `main` that moved9- * past the landed mirror, and for skills kept by each project's landed10- * commit, so the index reads a file only for a project whose main moved.11- */1 import { describe, expect, it } from "@effect/vitest";2 import { RefName, RepoHost } from "@repo/artifacts/repo-host";3 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";14 unmodified lines19 const datekit = ProjectName.make("dora/datekit");20 21 const burrow = ProjectName.make("dora/burrow");22 34-/** Listed by the front page, but never made. */23 const ghost = ProjectName.make("alice/ghost");24 25 const skillPath = ".agents/skills/dora__datekit-contribute/SKILL.md";26 7 unmodified lines34 "Claim an ask, change only its territory, and push.",35 "",36 ].join("\n");37 50-/** `sha256sum` of `skill`, worked out apart from the platform. */38 const skillDigest =39 "sha256:07b4246a86d79a7a0d0975e5e0b32f6f12b10a8e2cd5fad3188722e26b841f52";40 41 const Index = Schema.fromJsonString(16 unmodified lines58 posture: "open" as const,59 project,60 });61 75-/** What a reply says: its status, its type and its body. */62 const read = (response: Response) =>63 Effect.map(64 Effect.promise(() => response.text()),65 (body) => ({18 unmodified lines84 85 const dora = world.rpc("dora");86 const doraGit = world.git("dora");87 102- // datekit lands its skill with its first push; burrow lands none.88 for (const [project, files] of [89 [datekit, { [skillPath]: skill, "README.md": "datekit\n" }],90 [burrow, { "README.md": "burrow\n" }],91 ] as const) {42 unmodified lines134 contentType: "text/markdown; charset=utf-8",135 status: 200,136 });137 153- // A credential the platform does not know is no reason to refuse.138 expect(139 (yield* get("/.well-known/agent-skills/index.json", {140 authorization: "Bearer a-token-the-platform-never-issued-0123",141 })).status21 unmodified lines163 60_000164 );165 });166 183-/** What `agentSkills` itself answers for a path. */167 const at = (path: string) =>168 Effect.flatMap(169 agentSkills(new Request(`https://platform.test${path}`)),170 read171 );172 190-/** Projects the platform never made: each skill is read at its repo's refs. */173 const noneMade = Layer.succeed(174 Projects,175 Projects.of({176 create: () => Effect.die("the skills make no project"),9 unmodified lines186 const host = yield* RepoHost;187 const client = yield* gitClient(memoryFs());188 const repo = RepoName.make(keyOf(datekit));189 208- // The mirror holds the last landing; main has moved on without one,209- // as between a landing's two pushes, or after a stray push.190 const landing = yield* client.commit("Land", [[skillPath, skill]]);191 192 const unlanded = yield* client.commit(193 "Not landed",46 unmodified lines240 )241 );242 });243 264-/** The memory store, each file read and each refs read counted. */244 const countedHost = (counts: Ref.Ref<{ files: number; refs: number }>) =>245 Layer.effect(246 RepoHost,247 Effect.gen(function* () {14 unmodified lines262 });263 })264 ).pipe(Layer.provide(RepoHostMemory));265 287-/** Projects whose record says each one's main landed where `landed` holds. */266 const landedWhere = (landed: Ref.Ref<ReadonlyMap<ProjectName, LandedSha>>) =>267 Layer.succeed(268 Projects,269 Projects.of({65 unmodified lines335 ),336 ({ skills }) => skills.map(({ description }) => description)337 );338 361- /** What one request read: files and refs, since the last. */339 const reads = Effect.flatMap(340 Ref.getAndSet(counts, { files: 0, refs: 0 }),341 Effect.succeed342 );45 unmodified linesmodified:apps/platform/test/worker-init.test.ts-48 removed
1-/**2- * The Worker as Cloudflare starts it, in Node: `src/worker.ts` imported3- * through the `cloudflare:workers` shim, whose env is `fakeEnv()` (every4- * binding a fake that throws if touched; `PROJECT` a namespace of DOs that5- * hold no project). Then the ports `workerPorts` composes from a decoded6- * env, each over a fake of the binding it is built on.7- */1 import { describe, expect, it } from "@effect/vitest";2 import { Fetch } from "@repo/artifacts/fetch";3 import { RepoHost } from "@repo/artifacts/repo-host";4 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";40 unmodified lines45 origin as signInOrigin,46 tokenRequest,47 } from "./oauth.fixtures.ts";48 56-/**57- * What the shim's `PROJECT` was sent while `src/worker.ts` loaded, read58- * before any test runs: importing the module built its handler, and any59- * other binding it read would have thrown there.60- */49 const sentWhileLoading = [...callsTo(env.PROJECT)];50 63-/** A Worker's context, which nothing here needs. */51 const context = untouchable<ExecutionContext>("ExecutionContext");52 66-/** The Worker module's own fetch, as Cloudflare calls it, with the shim's env. */53 const workerFetch = (request: Request) =>54 Promise.resolve(worker.fetch(request, env, context));55 56 const nowhere = ProjectName.make("alice/nowhere");3 unmodified lines60 const canonical = RepoName.make("alice__datekit");61 62 const landed = LandedSha.make("7".repeat(40));63 78-/** A land of a commit the answer already made, onto canonical `main`. */64 const landJob: LandJob = {65 author: Handle.make("alice"),66 main: LandedSha.make("4".repeat(40)),67 message: "Fix the parser\n\nRequest-Id: request-0001\n",3 unmodified lines71 tree: TreeSha.make("5".repeat(40)),72 verdict: Option.none(),73 };74 90-/** Where the fake Artifacts binding says each repo's git lives. */75 const artifactsBase = "https://artifacts.test";76 93-/**94- * The global `fetch`, for the test's length, as a stub that notes each URL95- * it is asked for and answers 503: the Worker's `Fetch` port goes through96- * it, so nothing here reaches a network.97- */77 const fetchedUrls = Effect.acquireRelease(78 Effect.sync(() => {79 const urls: string[] = [];80 7 unmodified lines88 }),89 () => Effect.sync(() => vi.unstubAllGlobals())90 );91 113-/**114- * The sandbox Worker's entrypoint as the `SANDBOX` binding reaches it: a115- * land answers `landed`, and each land's request id is noted; anything116- * else read from it throws.117- */92 const fakeSandbox = () => {93 const lands: string[] = [];94 95 const sandbox = untouchable<Env["SANDBOX"] & SandboxBinding>("SANDBOX", {8 unmodified lines104 105 return { lands, sandbox };106 };107 134-/**135- * One land through the ports `workerPorts` composes for `LANDER_ADAPTER`,136- * over a fake Artifacts binding that holds the canonical repo and a fake137- * sandbox: what the land came to, which lands the sandbox was sent, and138- * which URLs the Worker fetched.139- */108 const landThrough = (adapter: "container" | "isogit") =>109 Effect.gen(function* () {110 const urls = yield* fetchedUrls;111 21 unmodified lines133 134 return { fetched: [...urls], lands: [...lands], outcome };135 });136 169-/** What `/health` answers. */137 const Health = Schema.fromJsonString(138 Schema.Struct({ ok: Schema.Boolean, stage: Schema.String })139 );140 174-/** A response's body, decoded by `schema`; one that won't decode is the test's defect. */141 const bodyOf =142 <A>(schema: Schema.Codec<A, string>) =>143 (response: Response) =>144 Effect.promise(() => response.text()).pipe(122 unmodified lines267 })268 );269 });270 305-/** A sign-in page's text, beside its response. */271 const pageOf = (response: Response) =>272 Effect.map(273 Effect.promise(() => response.text()),274 (html) => ({ html, response })275 );276 312-/** What `/token` answers, as far as a client reads it. */277 const AccessToken = Schema.fromJsonString(278 Schema.Struct({ access_token: Schema.String })279 );280 317-/** The sign-in form `page` carries; the test dies if it carries none. */281 const formIn = (282 page: { readonly html: string; readonly response: Response },283 cookie?: string284 ) => Effect.orDie(Effect.fromOption(formOf(page.response, page.html, cookie)));285 323-/**324- * The platform as `worker.ts` puts it together, OAuth and sign-in in front,325- * over the fake env with its `OAUTH_KV` in memory and a Project DO for326- * datekit (accounts in memory too), and an access token for a new account327- * `handle`, by the CLI's PKCE flow: sign up from the sign-in page, then328- * trade the code for a token. The global `fetch` answers the client329- * metadata document from the Worker itself, as the public internet does on330- * Cloudflare.331- */286 const signedUp = (handle: string, password: string) =>287 Effect.gen(function* () {288 const store = OAuthStoreMemory.make();289 10 unmodified lines300 const { dispose, handler } = oauthProvider(301 Layer.mergeAll(302 AccountsMemory.layer,303 Layer.succeed(OAuthStore, store),350- // No Google client in the fake env: Google sign-in touches neither.304 IdentitiesMemory.layer,305 Layer.succeed(Fetch, untouchable<Fetch["Service"]>("Fetch")),306 SignInAttemptsMemory.layer,307 signInSettings(config)97 unmodified lines405 "alice",406 "correct horse battery"407 );408 456- // The same user and grant, another secret: the provider knows no such token.409 const forged = [...accessToken.split(":").slice(0, 2), "forged"].join(410 ":"411 );412 17 unmodified linesmodified:apps/platform/test/workers-shim.ts-7 removed
1-/**2- * `cloudflare:workers` for tests in Node. `vitest.config.ts` aliases the3- * module here, so the Worker's modules load outside workerd: config4- * aliasing, not module mocking. Each class keeps what its constructor is5- * given and does nothing else; `env` is a fake whose bindings throw when6- * touched (`fake-env.ts`).7- */1 import { fakeEnv } from "./fake-env.ts";2 3 export class DurableObject<E = Env> {4 readonly ctx: DurableObjectState;32 unmodified linesmodified:apps/platform/test/world-process.tsnot shown
Its text is not shown, modified.
modified:apps/platform/test/world.tsnot shown
Its text is not shown, modified.
modified:apps/platform/vitest.config.tsnot shown
Its text is not shown, modified.