Trim comments in apps/sandbox
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parent aba93c8 · Browse files · 29 files·+88 added−1090 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
29 files+88 added−1090 removed
- tests:+7 added−230 removed
- other:+81 added−860 removed
Provenance
- Commit
123905f- Tree
642443b- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
aba93c8
29 files changed+88 added−1090 removed
modified:apps/sandbox/src/box/sdk.ts+1 added-17 removed
12345612345613141516171878910111213141527161718199 unmodified lines29303132453334353611 unmodified lines48495051655253545535 unmodified lines919293941091109596979819 unmodified lines/** * `Box` over a Durable Object's own container (`ctx.container`), as the * Sandbox SDK 1.0 runs one: the Durable Object starts the container and runs * commands through the Container API (`exec`, then `output`); the SDK's * `Files` writes files through the `sandbox-shim` every image carries. */import { Files } from "@cloudflare/sandbox";import { Duration, Effect, Layer } from "effect";
import { Box, BoxFailed } from "../box.ts";import type { ExecOptions } from "../box.ts";
/** * Which image the container runs, whether it may reach the internet, and * its instance size (the runtime's default, `lite`, when absent: a * Durable Object's container takes its size when it starts, not from * `wrangler.jsonc`). *//** `instance` is set at start, not from `wrangler.jsonc`; absent means `lite`. */export interface ContainerStart { readonly image: string; readonly enableInternet: boolean; readonly instance?: ContainerStartupOptions["instance"];}
const text = new TextDecoder();
/** The container, started on first use if it is not running yet. */const started = (container: Container, start: ContainerStart) => Effect.sync(() => { if (!container.running) { container.start(9 unmodified lines
return container; });
/** The Container API's options for one command; `signal` stops it. */const execOptions = (options: ExecOptions, signal: AbortSignal) => { const exec: ContainerExecOptions = { signal };
if (options.cwd !== undefined) {11 unmodified lines (operation: BoxFailed["operation"]) => (cause: unknown): BoxFailed => new BoxFailed({ operation, reason: String(cause) });
/** One command, run to its end, its output read as text. */const run = ( container: Container, argv: readonly string[], options: ExecOptions35 unmodified lines exec: (argv, options = {}) => Effect.flatMap(started(container, start), (running) => { const command = run(running, argv, options);
// Interrupting the command stops it: its signal while it starts, // a kill once it runs. return options.timeoutMs === undefined ? command : Effect.timeoutOrElse(command, { duration: Duration.millis(options.timeoutMs),19 unmodified linesmodified:apps/sandbox/src/checker/logs/worker.ts-7 removed
123456123411567814 unmodified lines/** * `CheckLogs` as the sandbox Worker's own logs: each phase's log as one log * line, its tail only, annotated with its phase and name. The check's wire * carries no logs yet, so this is where they go until the * platform stores them through `EvidenceStore`. */import { Effect, Layer } from "effect";
import { CheckLogs } from "../logs.ts";
/** The most of a log the Worker's own logs keep: its last 8 KiB. */const TAIL = 8 * 1024;
export const WorkerCheckLogs = { layer: Layer.succeed(14 unmodified linesmodified:apps/sandbox/src/checker/env.ts+3 added-39 removed
1-/**2- * A check job's env part, as the Checker applies it: which3- * `@proxy` hosts go to the env gateway, with which rules, and which values4- * the gateway may swap in. Pure: the Checker opens the route once egress is5- * off (`run.ts`), and the Durable Object reserves its hosts before the6- * catch-all intercept (`sdk.ts`).7- *8- * Only HTTPS is intercepted: Cloudflare adds a credential only to HTTPS9- * requests, since the outbound handler fetches with the scheme the container10- * used, and varlock injects only over verified TLS. A rule's host that is11- * not one is left out, with its reason.12- */1+// Only HTTPS is intercepted: the outbound handler fetches with the scheme the2+// container used, and varlock injects only over verified TLS.3 import type { CheckJob, EnvProxy } from "@repo/checks/check-runner";4 import { Array, Option, Result } from "effect";5 6 import { CLONE_HOST } from "./network.ts";7 import type { EnvRoute, EnvSwap } from "./network.ts";8 19-/** A rule's host the Checker does not intercept, and why. */9 export interface Skipped {10 readonly host: string;11 readonly reason: string;12 }13 25-/** The job's env route, if it has one, and every host it leaves out. */14 export interface EnvPlan {15 readonly route: Option.Option<EnvRoute>;16 readonly skipped: readonly Skipped[];17 }18 19 const HTTPS = "https://";20 33-/**34- * The most proxy hosts the container intercepts: its intercept table holds35- * 64 hostname targets, and the clone route and the catch-all take two36- * (`sdk.ts`); a few stay spare. Hosts past it are left out, with a reason.37- */21+/** The intercept table holds 64 hosts; the clone route and catch-all take two, a few stay spare. */22 const MAX_PROXY_HOSTS = 60;23 24 const TOO_MANY = `the container intercepts at most ${MAX_PROXY_HOSTS} proxy hosts beside the clone route and the catch-all`;25 42-/**43- * The host the container's HTTPS intercept takes for a rule's `host`, as44- * the schema writes it: a bare host or glob (`sentry.io`, `*.example.com`,45- * `api.example.com:8443`), or one with `https://` before it, which is46- * dropped. Any other scheme, `*` (the catch-all, which the egress gateway47- * holds), and the clone route's host are none.48- */26 const interceptHost = (host: string): Result.Result<string, string> => {27 const written = host.trim().toLowerCase();28 29 if (written.startsWith("http://")) {20 unmodified lines50 51 return Result.succeed(bare);52 };53 77-/**78- * The values a landed job's gateway may swap in: each one whose key a rule79- * that is not `block` names, with that rule's placeholder, the one the80- * gateway swaps out of a request and scrubs back into a response. None in81- * any other job.82- */54 const swapsOf = (55 job: CheckJob,56 rules: readonly EnvProxy[]57 ): readonly EnvSwap[] => {11 unmodified lines69 : [{ key, placeholder: rule.placeholder, value }];70 });71 };72 102-/**103- * The job's env route: its rules whose host is intercepted, each with the104- * host the intercept takes; the hosts, each once; and the values a landed105- * job's gateway may swap in. None when no host is left, or when the job has106- * a sealed suite: sealed checks run with the network off, and a107- * run with sealed files beside it has no landed value to swap anyway.108- */73 export const envPlanOf = (job: CheckJob): EnvPlan => {74 if (job.heldBack !== undefined) {75 return {76 route: Option.none(),35 unmodified linesmodified:apps/sandbox/src/checker/logs.ts-12 removed
123456789123134516678910111224131415/** * Where a check's raw output goes: to the platform's side, never into the * result an answerer reads (a `LaneResult` names a log by * its `logRef`, and the platform writes it through `EvidenceStore`). * * The check's wire carries no logs yet, so the Worker's * adapter (`logs/worker.ts`) writes each one to the Worker's own logs, its * tail only; tests record them (`test/fake-box.ts`). */import { Context } from "effect";import type { Effect } from "effect";
/** One phase's output: the clone's, setup's, or one lane's. */export interface PhaseLog { readonly phase: "clone" | "setup" | "lane"; /** The lane's name, or the phase's own. */ readonly name: string; readonly text: string;}
export class CheckLogs extends Context.Service< CheckLogs, { /** Hands over every log the check wrote, once, when it ends. */ readonly report: (logs: readonly PhaseLog[]) => Effect.Effect<void>; }>()("sandbox/CheckLogs") {}modified:apps/sandbox/src/checker/network.ts+4 added-64 removed
1-/**2- * The Checker's network: which hosts its container may reach, and the one3- * route its clone takes. The container starts with the internet off, so a4- * request leaves it only through an outbound entrypoint of this Worker5- * (`outbound.ts`): the clone route adds the job's read token on the Worker's6- * side and closes once setup starts, and every other host is refused unless7- * the current allow-list names it. Adapters: `checker/sdk.ts` over the container's outbound intercepts;8- * tests record the calls (`test/fake-box.ts`).9- */1 import type { EnvProxy } from "@repo/checks/check-runner";2 import type { EnvKey } from "@repo/protocol/ids";3 import { Context } from "effect";4 import type { Effect, Redacted } from "effect";5 15-/**16- * The hosts setup may reach on every project, beyond the run block's17- * `setupEgress`: the public package registries and nothing else. The checks18- * themselves reach none of them.19- */6 export const REGISTRIES = [21- // npm's registry: npm, pnpm and Bun install from it by default, and22- // corepack downloads pnpm from it.7 "registry.npmjs.org",24- // Yarn 1's registry, a mirror of npm's that `yarn install` uses.8 "registry.yarnpkg.com",26- // Yarn 2+'s home: corepack downloads Yarn itself from it.9 "repo.yarnpkg.com",28- // PyPI's index (the simple API pip and uv read).10 "pypi.org",30- // PyPI's package files, which the index links to.11 "files.pythonhosted.org",32- // crates.io's API, which redirects a crate download to the static host.12 "crates.io",34- // crates.io's sparse index, which cargo reads by default.13 "index.crates.io",36- // crates.io's crate files.14 "static.crates.io",38- // The Go module proxy, where `go mod download` fetches modules.15 "proxy.golang.org",40- // The Go checksum database, which verifies what the proxy served.16 "sum.golang.org",17 ] as const;18 44-/**45- * Whether `allow` lets a request to `hostname` out: an exact name, or a46- * `*.example.com` entry for any host under it (not the apex itself).47- */19+/** `*.example.com` matches any host under it, not the apex itself. */20 export const allows = (allow: readonly string[], hostname: string): boolean => {21 const host = hostname.toLowerCase();22 23 return allow.some((entry) =>2 unmodified lines26 : host === entry.toLowerCase()27 );28 };29 58-/**59- * The host the container clones from. It names nothing real: the container60- * reaches it only because the clone route intercepts it, so the container61- * learns no remote's host and holds no token for one.62- */30+/** Names nothing real, so the container learns no remote's host or token. */31 export const CLONE_HOST = "repo.checker.internal";32 65-/**66- * The URL the container clones `remote` from: the clone host, with the67- * remote's path and nothing else (no user, no token, no query).68- */33 export const cloneUrlOf = (remote: string): string =>34 `https://${CLONE_HOST}${new URL(remote).pathname}`;35 72-/**73- * Where the container's clone goes: requests to `host` reach the clone74- * gateway, which sends them on to `remote` with `token` added. The container75- * sees `host` and never the token.76- */36 export interface CloneRoute {37 readonly host: string;38 readonly remote: string;39 readonly token: Redacted.Redacted;40 }41 83-/** A value the env gateway may swap in, with the placeholder it stands for. */42 export interface EnvSwap {43 readonly key: EnvKey;44 readonly placeholder: string;45 readonly value: Redacted.Redacted;46 }47 90-/**91- * Where a job's `@proxy` hosts go: each of `hosts` to the env92- * gateway, which lets out only the requests `rules` allow and swaps a93- * placeholder for its value only when `values` holds it, which only a job of94- * landed code fills. Every host is HTTPS and named once.95- */48+/** `values` is filled only for a job of landed code. */49 export interface EnvRoute {50 readonly hosts: readonly string[];51 readonly rules: readonly EnvProxy[];52 readonly values: readonly EnvSwap[];1 unmodified line54 55 export class Network extends Context.Service<56 Network,57 {105- /**106- * Routes the clone's host to the clone gateway for this job's remote,107- * until the first `allow`.108- */58 readonly routeClone: (route: CloneRoute) => Effect.Effect<void>;110- /**111- * Lets out requests to `hosts` and refuses every other, the clone host112- * included: the clone is done before setup starts, so its route closes113- * here. `[]` turns the network off.114- */59+ /** Closes the clone route too. `[]` turns the network off. */60 readonly allow: (hosts: readonly string[]) => Effect.Effect<void>;116- /**117- * Routes each of `route.hosts` to the env gateway for the rest of the118- * job, in place of the egress gateway; every other host stays as119- * `allow` left it.120- */61 readonly routeEnv: (route: EnvRoute) => Effect.Effect<void>;62 }63 >()("sandbox/Network") {}modified:apps/sandbox/src/checker/run.ts+16 added-164 removed
1-/**2- * One check job, phase by phase, in one container that holds no credential:3- *4- * 1. clone: the job's tree, through the clone route, whose gateway adds the5- * read token outside the container;6- * 2. the plan from `@repo/checks/phases`, keyed by the lockfiles just cloned:7- * setup (or a snapshot of an earlier one) with egress to the registries8- * and the run block's `setupEgress` only, the snapshot, egress off, the9- * sealed suite's files when the job has one, the lanes and then each10- * sealed check, the report.11- *12- * The container is destroyed however the job ends, and its logs are handed13- * to `CheckLogs` before that; the result carries none (a count lane's14- * stdout, in `outputs`, is a result, not a log). A job the Checker15- * cannot run to the end (a clone or a setup that fails, a sealed file it16- * cannot write) is `VerifierBlocked`: the gate's trouble, never the17- * answer's. A lane that fails or runs out of time is that lane's result.18- *19- * A sealed suite is written only after the20- * snapshot and with egress off, so no snapshot and no request carries it21- * out, and it reports one result per area (`@repo/checks/held-back-filter`).22- * From its first write on, nothing a command prints leaves the Checker: the23- * sealed checks' output is dropped, and so is that of the public lanes24- * that run beside the sealed files (a `bun test` with no path finds them25- * too), which report only how they ended.26- */1+// A sealed suite is written only after the snapshot and with egress off. From2+// its first write on, nothing a command prints leaves the Checker, the public3+// lanes' output included (a `bun test` with no path finds the sealed files).4 import { CheckAt, evidenceFrom } from "@repo/checks/check-runner";5 import type {6 CheckRun,7 EnvPlaceholder,28 unmodified lines36 REGISTRIES,37 } from "./network.ts";38 import { Snapshots } from "./snapshots.ts";39 63-/** Where the job's tree is checked out, and every command runs. */40 export const REPO = "/workspace/repo";41 66-/**67- * The CA the container's outbound intercepts present: every HTTPS request68- * leaves through one, so every TLS client trusts this CA alone.69- */42+/** Every HTTPS request leaves through an intercept, so TLS clients trust its CA alone. */43 const CA = "/etc/cloudflare/certs/cloudflare-containers-ca.crt";44 45 const TRUST = {46 CARGO_HTTP_CAINFO: CA,4 unmodified lines51 REQUESTS_CA_BUNDLE: CA,52 SSL_CERT_FILE: CA,53 };54 82-/**83- * The project's own bins first, as `npm run` puts them (an84- * ASSUMPTION), then the image's.85- */55+/** The project's own bins first, as `npm run` puts them. */56 const PATH = [57 `${REPO}/node_modules/.bin`,58 "/usr/local/sbin",59 "/usr/local/bin",2 unmodified lines62 "/sbin",63 "/bin",64 ].join(":");65 96-/**97- * The whole environment every command sees: fixed, so two runs of one tree98- * see the same one, and holding nothing secret.99- */66+/** Fixed, so two runs of one tree see the same env. */67 const ENV = {68 ...TRUST,69 CI: "1",70 // corepack fetches pnpm or Yarn during setup without asking first.6 unmodified lines77 NO_COLOR: "1",78 PATH,79 };80 114-/**115- * The env every command of the project runs with (setup, the lanes, each116- * sealed check): each write-only value's placeholder (a process117- * env beats any resolver, so an unchanged `.env.schema` still loads), under118- * the Checker's own env, which no item's key displaces (an item named119- * `PATH` or `NODE_EXTRA_CA_CERTS` keeps the Checker's). Never a value.120- */81+/** Placeholders, never values; no item's key displaces the Checker's own env. */82 const commandEnv = (placeholders: readonly EnvPlaceholder[]) => ({83 ...Object.fromEntries(84 placeholders.map(({ key, placeholder }) => [key, placeholder])85 ),86 ...ENV,87 });88 128-/** The identity of the commit a checked tree is checked out as. */89 const GIT_ENV = {90 ...ENV,91 GIT_AUTHOR_DATE: "2026-10-06T12:00:00Z",92 GIT_AUTHOR_EMAIL: "checker@example.com",2 unmodified lines95 GIT_COMMITTER_EMAIL: "checker@example.com",96 GIT_COMMITTER_NAME: "Checker",97 };98 139-/** The files whose contents decide what setup installs. */99 const LOCKFILES = [100 "bun.lock",101 "bun.lockb",102 "package-lock.json",9 unmodified lines112 ];113 114 const CLONE_LIMIT = Duration.minutes(5);115 157-/** Making room for the sealed files is quick; it never waits on the network. */116 const ROOM_LIMIT = Duration.minutes(1);117 118 const SETUP_LIMIT = Duration.minutes(15);119 162-/**163- * A lane with no time limit of its own gets ten minutes, as `/local` gives;164- * so does each sealed check.165- */120 const LANE_LIMIT = Duration.minutes(10);121 122 const timedOut: RunExit = { code: -1, stderr: "", stdout: "", timedOut: true };123 170-/** Hosts a failed setup's output names: in URLs and in resolver errors. */124 const HOSTS_IN_OUTPUT = [125 /\bhttps?:\/\/(?<host>[a-z0-9.-]+)/giu,126 /\bgetaddrinfo \w+ (?<host>[a-z0-9.-]+)/giu,127 /\bresolve host:? (?<host>[a-z0-9.-]+)/giu,128 ];129 177-/** The hosts `text` names that `allowed` does not let out. */130 const refusedIn = (text: string, allowed: readonly string[]) => [131 ...new Set(132 HOSTS_IN_OUTPUT.flatMap((pattern) =>133 [...text.matchAll(pattern)].flatMap(24 unmodified lines158 Effect.annotateLogs(annotations),159 Effect.andThen(Effect.fail(new VerifierBlocked({})))160 );161 210-/**211- * A lane's run, as the lane's result, what it leaves for comparison, and,212- * for a count lane that ran to its end, what it printed.213- */162 interface LaneRan {163 readonly result: LaneResult;164 readonly evidence: Option.Option<LaneEvidence>;165 readonly output: Option.Option<LaneOutput>;166 }167 220-/** Every phase's log so far, handed to `CheckLogs` when the check ends. */168 type Kept = Ref.Ref<readonly PhaseLog[]>;169 223-/** Adds `log`'s text to the log of its phase and name, starting it if new. */170 const keep = (kept: Kept, log: PhaseLog) =>171 Ref.update(kept, (logs) =>172 logs.some(({ name, phase }) => phase === log.phase && name === log.name)173 ? logs.map((each) =>3 unmodified lines177 )178 : [...logs, log]179 );180 235-/** Where a command's output goes: into its phase's log, or nowhere. */181 type Recorder = (text: string) => Effect.Effect<void>;182 238-/** Into the log of `log`'s phase and name. */183 const keeping =184 (kept: Kept, log: Omit<PhaseLog, "text">): Recorder =>185 (text) =>186 keep(kept, { ...log, text });187 244-/** Nowhere: the command ran beside the sealed files. */188 const dropping: Recorder = () => Effect.void;189 247-/**248- * One command, to its end or `limit` (none when it ran out of time), its249- * output handed to `record`. At the limit the Checker stops waiting for250- * it; the process itself ends only when the container is destroyed (the251- * `Box` adapter aborts an `exec` that is still starting, not one already252- * running).253- */190+/** None when it ran out of time. */191 const exec = (192 record: Recorder,193 argv: readonly [string, ...string[]],194 options: ExecOptions,13 unmodified lines208 )209 )210 );211 275-/** One git command of the checkout, which must succeed: its output. */212 const git = (kept: Kept, ...args: readonly string[]) =>213 exec(214 keeping(kept, { name: "clone", phase: "clone" }),215 ["git", ...args],19 unmodified lines235 })236 )237 );238 303-/**304- * The job's tree as the work tree's HEAD, fetched from `url` (the clone305- * host, which holds no token) into an empty repo or the one a snapshot306- * brought back. `clean` keeps what setup installed (ignored files) and drops307- * anything else the tree does not hold.308- */239+/** `clean` keeps ignored files, which setup installed. */240 const checkout = (kept: Kept, url: string, at: CheckAt) =>241 Effect.gen(function* () {242 const fetch = (refspec: string) =>243 git(26 unmodified lines270 yield* git(kept, "-C", REPO, "checkout", "-q", "--force", "--detach", head);271 yield* git(kept, "-C", REPO, "clean", "-q", "-ffd");272 });273 343-/** What the phases share for one job. */274 interface Job {275 readonly wire: CheckWire;276 readonly kept: Kept;347- /** The env the project's commands run with: placeholders, never values. */277 readonly env: Readonly<Record<string, string>>;349- /** The URL the container clones from: the clone host, no token. */278 readonly url: string;351- /** Whether setup was skipped for a snapshot of an earlier one. */279 readonly restored: Ref.Ref<boolean>;353- /** Whether the work tree holds sealed files yet: from then on, no output is kept. */280 readonly sealed: Ref.Ref<boolean>;355- /** How each sealed check ended, in the job's order. */281 readonly exits: Ref.Ref<readonly HeldBackExit[]>;282 }283 284 /** A snapshot is its project's own: two projects with one lockfile never share one. */285 const snapshotKeyOf = ({ wire }: Job, key: string) =>286 `${wire.job.project}:${key}`;287 363-/**364- * Setup, or the snapshot of an earlier one: with a snapshot under `key`, the365- * container restarts from it and the job's tree is checked out again;366- * without one, `command` runs with egress to the registries and `egress`367- * only. A setup that fails is `VerifierBlocked`, and a host it was refused is368- * named in setup's log and in the log line.369- */288 const setup = (289 job: Job,290 command: string,291 egress: readonly string[],59 unmodified lines351 phase: "setup",352 });353 });354 437-/**438- * Keeps what setup installed for the next check of this project and439- * lockfile. Only a check of a commit in the project's own repo keeps one440- * (main, or main with a decider's ask files): an answer's tree may change441- * what setup does, so a check of one only ever restores. A snapshot that442- * fails to save leaves this check as it was.443- */355+/** Only the project's own commits save one: an answer's tree may change what setup does. */356 const snapshot = (job: Job, key: string) =>357 Effect.gen(function* () {358 const snapshots = yield* Snapshots;359 const { at, project, repo } = job.wire.job;21 unmodified lines381 )382 );383 });384 473-/**474- * One lane, to its end or its time limit, as its result: how it ended,475- * classified (`checks.classifyRun`), never an error. A lane that runs out of476- * time, or that the container would not run, never ran to an end. A count477- * lane (`output: "stdout"`) that did hands back its stdout, which its count478- * is read from; any other lane's output stays in its log. A lane that runs479- * beside the sealed files keeps neither, nor its failure's signature: what480- * it printed may name or quote them.481- */385+/** A lane beside the sealed files keeps no output or failure signature: it may quote them. */386 const runLane = (job: Job, { command, lane }: PlannedLane) =>387 Effect.gen(function* () {388 const own = job.wire.job.lanes.find((each) => each.lane === lane);389 const beside = yield* Ref.get(job.sealed);50 unmodified lines440 })441 );442 });443 540-/**541- * Whether a sealed file's path stays inside the checked tree: relative,542- * with no empty, `.` or `..` segment.543- */444 const inTree = (path: string) =>445 !path.startsWith("/") &&446 path447 .split("/")448 .every((segment) => segment !== "" && segment !== "." && segment !== "..");449 550-/**551- * The shell script `roomFor` runs. Its arguments are folders, shallowest552- * first, then `--`, then files. A folder's place is cleared of anything553- * that is not a folder (a file, a link, a link to a folder) and the folder554- * made; a file's place is cleared of whatever stands there. Every path is555- * absolute, so none reads as `--`.556- */450+/** Arguments: folders, shallowest first, then `--`, then files; all absolute, so none reads as `--`. */451 const ROOM = [452 'while [ "$1" != -- ]; do',453 ' if [ -L "$1" ] || { [ -e "$1" ] && [ ! -d "$1" ]; }; then',454 ' rm -f -- "$1" || exit 1',4 unmodified lines459 "shift",460 'rm -rf -- "$@"',461 ].join("\n");462 569-/** Every folder `path` sits in under `root`, shallowest first. */463 const foldersAbove = (root: string, path: string) => {464 const folders = path.split("/").slice(0, -1);465 466 return folders.map(467 (_, depth) => `${root}/${folders.slice(0, depth + 1).join("/")}`468 );469 };470 578-/**579- * The command that makes room under `root` for the sealed files at `paths`580- * (relative, inside the tree): each folder they sit in, made, and each581- * file's own place, empty. The answer's tree decides what stands there; a582- * file where a sealed folder goes, a folder where a sealed file goes, or a583- * link would fail the write, and a `VerifierBlocked` spends no attempt, so584- * it would tell the answer, for free, that a sealed path is there. What585- * the tree holds anywhere else stays, folders on the way included.586- */471+/** A failed write would tell the answer, for free, that a sealed path is there. */472 export const roomFor = (473 root: string,474 paths: readonly string[]475 ): readonly [string, ...string[]] => [9 unmodified lines485 /** The sealed files are not all in the work tree: nothing logged says which. */486 const unwritten = () =>487 blocked("the sealed files were not written", { phase: "WriteHeldBack" });488 604-/**605- * The sealed suite's files, written into the work tree after the snapshot606- * and with egress off (the plan's order), from the bytes the job carried:607- * the Checker holds no route to the layer. `Files.writeFile` makes no608- * folder, so room is made first (`roomFor`), whatever the answer's tree609- * holds there. A file that would land outside the tree, or that the610- * container cannot write, is `VerifierBlocked`; nothing logged names a611- * path, and no reason the container gave is logged, since it may name one.612- */489+/** No reason the container gave is logged, since it may name a sealed path. */490 const writeHeldBack = (job: Job, { files }: HeldBackPart) =>491 Effect.gen(function* () {492 if (!files.every(({ path }) => inTree(path))) {493 return yield* blocked("a sealed file's path leaves the checked tree", {28 unmodified lines522 { discard: true }523 );524 });525 649-/**650- * One sealed check, to its end or the lane time limit: how it ended, and651- * nothing it printed. A check that runs out of time, or that the container652- * fails to run, did not pass, and says no more than a failure would: a653- * different answer would be one more bit about the suite, and one an654- * answer could ask for without spending an attempt.655- */526+/** A timeout reads as a plain failure: anything else is one more bit about the suite. */527 const runSealed = (job: Job, { area, command }: HeldBackCheck) =>528 exec(529 dropping,530 ["sh", "-c", command],14 unmodified lines545 Effect.succeed<HeldBackExit>({ area, code: -1, timedOut: false })546 )547 );548 678-/**679- * Routes the job's `@proxy` hosts to the env gateway (`checker/env.ts`),680- * logging each host it leaves out with the reason. A host comes from the681- * project's own `.env.schema`, which is public; no value is logged.682- */549 const openEnvRoute = (wire: CheckWire) =>550 Effect.gen(function* () {551 const network = yield* Network;552 const { route, skipped } = envPlanOf(wire.job);11 unmodified lines564 yield* network.routeEnv(route.value);565 }566 });567 702-/** The phases, from the clone to the last lane, with the logs kept as they go. */568 const phases = (wire: CheckWire, run: RunBlock, kept: Kept) =>569 Effect.gen(function* () {570 const network = yield* Network;571 const { clone } = wire;572 708- // The job's sealed suite, if it has one.573 const heldBack = Option.fromNullishOr(wire.job.heldBack);574 575 const job: Job = {576 env: commandEnv(wire.job.placeholders),24 unmodified lines601 placeholders: wire.job.placeholders.map(({ key }) => key),602 run,603 });604 741- // Setup looks its snapshot up under the key the plan's `Snapshot` keeps742- // it under.605 const key = plan.find(Phase.$is("Snapshot"))?.key ?? lockfileHash;606 607 const ran = yield* Effect.forEach(plan, (phase) =>608 Effect.logInfo("checker phase").pipe(609 Effect.annotateLogs({ phase: phase._tag }),610 Effect.andThen(611 Phase.$match(phase, {750- // Off for every host but the env gateway's, which open here751- // (the plan's "leaving only the platform's handlers").612+ // Off for every host but the env gateway's, which open here.613 EgressOff: () =>614 Effect.as(615 Effect.andThen(network.allow([]), openEnvRoute(wire)),616 []617 ),618 Report: () => Effect.succeed([]),758- // The public lanes, then each sealed check, all with egress off.619 Run: ({ lanes }) =>620 Effect.tap(621 Effect.forEach(lanes, (lane) => runLane(job, lane)),622 () =>8 unmodified lines631 ),632 Setup: ({ command, egress }) =>633 Effect.as(setup(job, command, egress, key), []),634 Snapshot: (saved) => Effect.as(snapshot(job, saved.key), []),775- // The plan has this phase only for a job with a sealed suite.635 WriteHeldBack: () =>636 Option.match(heldBack, {637 onNone: () => Effect.succeed([]),638 onSome: (part) => Effect.as(writeHeldBack(job, part), []),13 unmodified lines652 ran: ran.flat(),653 };654 });655 797-/**798- * One check job in one container: the phases, then the logs handed to799- * `CheckLogs` and the container destroyed, however the phases ended. The800- * result carries each lane's result and evidence, never a log, a count801- * lane's stdout (`outputs`), which the platform reads its count from, and802- * one result per sealed area.803- */656 export const check = (657 wire: CheckWire658 ): Effect.Effect<659 CheckRun,26 unmodified linesmodified:apps/sandbox/src/checker/sdk.ts+8 added-64 removed
1-/**2- * `Network` and `Snapshots` over a Durable Object's own container, as the3- * Container API runs one (`ctx.container`; Sandbox SDK 1.0 leaves both to4- * it):5- *6- * - the network is the container's outbound intercepts. The container starts7- * with the internet off, so a request leaves only through an intercept:8- * the clone host goes to `CloneGateway`, each `@proxy` host of the job to9- * `EgressGateway` until egress is off and to `EnvGateway` after, and every10- * other host, HTTPS (`*`) and HTTP, to `EgressGateway`, whose props say11- * what it lets out. A host is registered ahead of the catch-all, which12- * takes every host registered after it (the Sandbox SDK's13- * `DirectoryBackup.intercept`), so the job's `@proxy` hosts are reserved14- * when the layer is built. Registering a target again replaces its handler15- * in place, which is how the allow-list changes, how the clone route16- * closes once setup starts, how egress goes off, and how the env route17- * opens.18- * - a snapshot is a Container snapshot (public beta) of the whole root19- * filesystem, its id kept in an index the project's checks share; a20- * restore starts the container again from it, so the intercepts are21- * registered again too (they last only as long as one container).22- */1+// The catch-all intercept takes every host registered after it, so the job's2+// `@proxy` hosts are reserved when the layer is built. Registering a target3+// again replaces its handler in place. Intercepts last one container, so a4+// restore registers them again.5 import {6 Context,7 Effect,8 Layer,9 unmodified lines18 import { Network } from "./network.ts";19 import type { CloneRoute, EnvRoute } from "./network.ts";20 import { Snapshots } from "./snapshots.ts";21 40-/**41- * The outbound entrypoints' loopbacks: `ctx.exports` holds one per export of42- * the Worker's main module.43- */22 export interface Gateways {23 readonly CloneGateway: (options: { readonly props: CloneProps }) => Fetcher;24 readonly EgressGateway: (options: { readonly props: EgressProps }) => Fetcher;25 readonly EnvGateway: (options: {26 readonly props: EnvGatewayProps;27 }) => Fetcher;28 }29 52-/** Whether `ctx.exports` holds every gateway: `worker.ts` must export them. */30 export const hasGateways = (31 exports: Cloudflare.Exports32 ): exports is Cloudflare.Exports & Gateways =>33 Predicate.hasProperty(exports, "CloneGateway") &&2 unmodified lines36 Predicate.isFunction(exports.EgressGateway) &&37 Predicate.hasProperty(exports, "EnvGateway") &&38 Predicate.isFunction(exports.EnvGateway);39 63-/** Where snapshot ids are kept, by key, for every check of one project. */40 export interface SnapshotIndex {41 readonly find: (key: string) => Promise<string | null>;42 readonly keep: (key: string, id: string) => Promise<void>;43 readonly forget: (key: string) => Promise<void>;44 }45 70-/** What the container's intercepts say now. */46 interface Routes {47 readonly clone: Option.Option<CloneRoute>;48 readonly allow: readonly string[];74- /**75- * The clone is done: the first `allow` closes its route, so setup and the76- * lanes reach the clone host only as a host they are refused.77- */49 readonly cloned: boolean;79- /**80- * The job's `@proxy` hosts, registered ahead of the catch-all from the81- * first install on: to the egress gateway, like any other host, until82- * the env route opens.83- */50 readonly proxied: readonly string[];85- /** The env route, once open: its hosts go to the env gateway. */51 readonly env: Option.Option<EnvRoute>;52 }53 89-/** The name every setup snapshot carries; its index key tells them apart. */54 const SNAPSHOT_NAME = "check-setup";55 92-/** What a restored container runs while commands run beside it. */56 const IDLE = ["sleep", "infinity"];57 58 const failed = (reason: string) => (cause: unknown) =>59 new BoxFailed({ operation: "exec", reason: `${reason}: ${String(cause)}` });60 98-/**99- * One intercept registered. One that will not register leaves the network100- * other than the job needs, so it ends the job (a defect), never a lane's run.101- */61+/** A failed registration is a defect: the network would not be what the job needs. */62 const intercept = (register: () => Promise<void>) => Effect.promise(register);63 104-/**105- * The env gateway's props for `route`: plain data on the Worker's side,106- * the values opened from their redaction only here.107- */64+/** The values leave their redaction only here, on the Worker's side. */65 const envProps = ({ rules, values }: EnvRoute): EnvGatewayProps => ({66 rules,67 values: values.map(({ key, placeholder, value }) => ({68 key,1 unmodified line70 value: Redacted.value(value),71 })),72 });73 117-/** The hosts the env route has opened, and the gateway they go to. */74 interface Opened {75 readonly hosts: readonly string[];76 readonly to: Fetcher;77 }78 123-/**124- * Points the container's intercepts where `routes` says: the clone host to125- * the clone gateway (or, once the clone is done, to the egress gateway, which126- * refuses it), each `@proxy` host to the env gateway once its route is open127- * (to the egress gateway until then), and every other host, HTTPS and HTTP,128- * to an egress gateway allowing `allow`, in that order.129- */79+/** Registration order matters: named hosts before the catch-all. */80 const install = (81 container: Container,82 gateways: Gateways,83 { allow, clone, cloned, env, proxied }: Routes42 unmodified lines126 yield* intercept(() => container.interceptOutboundHttps("*", egress));127 yield* intercept(() => container.interceptAllOutboundHttp(egress));128 });129 180-/** The restored container answers a command, or the snapshot is gone. */130 const probe = (container: Container) =>131 Effect.tryPromise({132 catch: failed("the restored container did not answer"),133 try: () => container.exec(["true"]),13 unmodified lines147 })148 )149 );150 202-/** How the Checker's container runs: the hosts its env route may open, and its size. */151 export interface CheckerStart {204- /**205- * Every host the job's env route may open (`checker/env.ts`): a host206- * first registered after the catch-all would never be reached.207- */152+ /** A host first registered after the catch-all would never be reached. */153 readonly proxied: readonly string[];209- /** The instance a restore starts on: the one the job's `Box` starts. */154 readonly instance: NonNullable<ContainerStartupOptions["instance"]>;155 }156 157 export const SdkChecker = {105 unmodified linesmodified:apps/sandbox/src/checker/snapshots.ts+1 added-15 removed
12345678912345678189202122232410111213/** * What setup installed, kept for the next check of the same project with the * same lockfile, so setup runs once per lockfile rather than once per check. * A snapshot is taken right after setup and never later: held-back files are * written only after it (`@repo/checks/phases`). * * Adapters: `checker/sdk.ts` over Container snapshots; tests keep the keys in * memory (`test/fake-box.ts`). */import { Context } from "effect";import type { Effect } from "effect";
import type { BoxFailed } from "../box.ts";
export class Snapshots extends Context.Service< Snapshots, { /** Keeps the container's files under `key`, replacing any kept there. */ readonly save: (key: string) => Effect.Effect<void, BoxFailed>; /** * Puts back the files kept under `key`, if any: `false` when there are * none, and the container is untouched. After a restore the workspace is * the snapshot's, so the caller checks its own tree out again. */ /** After a restore the workspace is the snapshot's: check the tree out again. */ readonly restore: (key: string) => Effect.Effect<boolean, BoxFailed>; }>()("sandbox/Snapshots") {}modified:apps/sandbox/src/lander/run.ts+11 added-120 removed
1-/**2- * The Lander's jobs, run through the `Box` port: each runs `script.ts`'s3- * git steps in the container and reads what git printed. A step that4- * reaches a remote gets that remote's token as an `http.extraHeader`5- * through `GIT_CONFIG_*` env, never in its URL or on its command line. A6- * step that fails blocks the job with `VerifierBlocked`, which carries no7- * text (principle 3): git's stderr goes beside it, as a log annotation,8- * trimmed and with every token taken out.9- */1+// A remote's token reaches git as an `http.extraHeader` through `GIT_CONFIG_*`2+// env, never in a URL or on a command line. git's stderr is logged with every3+// token taken out, never put in the refusal.4 import { Brand } from "@repo/brand";5 import { notesRef } from "@repo/git/notes";6 import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";7 import type { GitIdentity } from "@repo/git/trailers";69 unmodified lines77 writeTree,78 } from "./script.ts";79 import type { GitStep, RemoteName, Signature } from "./script.ts";80 87-/** Where the Lander's container keeps things, and finds its tools. */81 export interface LanderLayout {89- /** The folder its repos and scratch files live in. */82 readonly work: string;91- /**92- * The image's copy of the sdk, which a config folder's imports of the sdk93- * resolve to: its entry module, the packages its own imports resolve in94- * (`effect` among them), and a file naming its version.95- */83 readonly sdk: {84 readonly entry: string;85 readonly modules: string;86 readonly version: string;87 };101- /** Where commands are looked up. */88 readonly path: string;89 }90 105-/** The land image's layout (`images/land.Dockerfile`); tests point it at a temp folder. */91 export const Layout = Context.Reference<LanderLayout>("sandbox/lander/Layout", {92 defaultValue: () => ({93 path: "/usr/local/bin:/usr/bin:/bin",94 sdk: {4 unmodified lines99 work: "/workspace",100 }),101 });102 118-/** The tokens a job carries, by the remote each opens. */103 type Tokens = Partial<Record<RemoteName, Redacted.Redacted>>;104 105 // The modes git stores a file's bytes under, plain or executable: a file a106 // composed file may replace, and a file a bundle may read.6 unmodified lines113 const REMOTE_MS = 120_000;114 115 const LOCAL_MS = 30_000;116 133-/** `text` with every token taken out, and only its end kept. */117 const scrubbed = (text: string, tokens: Tokens) => {118 let kept = text;119 120 for (const token of Object.values(tokens)) {6 unmodified lines127 128 return kept.trim().slice(-STDERR_KEPT);129 };130 148-/** git's subcommand in a step, for logs: the first argument after its options. */131 const subcommandOf = (step: GitStep) =>132 step.argv.find(133 (argument, index) =>134 index > 0 && !argument.startsWith("-") && step.argv[index - 1] !== "-c"135 ) ?? "git";136 155-/**156- * The job is blocked at `step` (a git subcommand, or the Box operation); what157- * went wrong goes to the log, token-free, never into the refusal.158- */137 const blockedBy = (step: string, why: string, tokens: Tokens) =>138 Effect.logWarning("a Lander step failed").pipe(139 Effect.annotateLogs({ step, why: scrubbed(why, tokens) }),140 Effect.andThen(Effect.fail(new VerifierBlocked({})))141 );142 165-/** Everything a command printed, for a log: its exit, then stdout and stderr. */143 const printed = (ran: Executed) =>144 `exit ${ran.exitCode}: ${ran.stdout}\n${ran.stderr}`;145 169-/** git's env for every step: no config but the step's own, no prompt, English. */146 const baseEnv = (layout: LanderLayout) => ({147 GIT_CONFIG_GLOBAL: "/dev/null",148 GIT_CONFIG_NOSYSTEM: "1",149 GIT_TERMINAL_PROMPT: "0",1 unmodified line151 LC_ALL: "C",152 PATH: layout.path,153 });154 179-/** The header that carries a remote's token, as git reads config from env. */155 const header = (token: Redacted.Redacted) => ({156 GIT_CONFIG_COUNT: "1",157 GIT_CONFIG_KEY_0: "http.extraHeader",158 GIT_CONFIG_VALUE_0: `Authorization: Bearer ${Redacted.value(token)}`,159 });160 186-/** How one job runs its steps, and how it says one blocked it. */161 interface Steps {188- /**189- * Runs a step in the work folder, with the token of the remote it reaches.190- * A step expected to succeed that does not blocks the job; the others hand191- * back what git printed for the caller to read.192- */162+ /** A step expected to succeed that does not blocks the job. */163 readonly run: (step: GitStep) => Effect.Effect<Executed, VerifierBlocked>;194- /** Blocks the job at `step`, logging `why` with the job's tokens taken out. */164 readonly blocked: (165 step: GitStep,166 why: string167 ) => Effect.Effect<never, VerifierBlocked>;168 }169 201-/** The steps of one job, which carries `tokens`. */170 const runner = (tokens: Tokens) => {171 const blocked = (step: GitStep, why: string) =>172 blockedBy(subcommandOf(step), why, tokens);173 46 unmodified lines220 );221 222 const signed = (who: GitIdentity, at: number): Signature => ({ ...who, at });223 256-/** A scratch file the job writes, in the work folder. */224 const scratch = (name: string) =>225 Effect.map(Layout, ({ work }) => `${work}/scratch/${name}`);226 260-/**261- * The Lander's copy of the job's repo, and the scratch folders its files go262- * in, made if they are missing.263- */227 const prepared = (job: Job) =>228 Effect.gen(function* () {229 const { work } = yield* Layout;230 231 yield* job.run(folders([`${work}/scratch/compose`]));232 yield* job.run(initCopy(job.repo));233 });234 272-/** `text` written to `file` in the container; a file it would not take blocks the job. */235 const writtenAt = (file: string, text: string) =>236 Box.use((box) => box.writeFile(file, new TextEncoder().encode(text))).pipe(237 Effect.catchTag("BoxFailed", ({ reason }) =>238 blockedBy("writeFile", reason, {})239 )240 );241 280-/** Writes `text` to a scratch file for git to read: a message, a note. */242 const written = (name: string, text: string) =>243 Effect.gen(function* () {244 const file = yield* scratch(name);245 1 unmodified line247 248 return file;249 });250 290-/** What one job runs its steps with: its canonical repo, that repo's URL, and its steps. */251 interface Job extends Steps {252 readonly repo: RepoName;253 readonly url: string;254 }255 296-/** `rev` in the Lander's copy, if it names something there. */256 const resolved = ({ repo, run }: Job, rev: string) =>257 Effect.map(run(revParse(repo, rev)), ({ exitCode, stdout }) =>258 exitCode === 0 ? Option.some(stdout.trim()) : Option.none()259 );260 302-/** `rev`'s id in the Lander's copy, which a step before made sure is there. */261 const idOf = (job: Job, rev: string) =>262 resolved(job, rev).pipe(263 Effect.flatMap(264 Option.match({3 unmodified lines268 })269 )270 );271 314-/** A commit of `tree` on `parents`, written to the copy: its id. */272 const committed = (273 job: Job,274 commit: {275 readonly tree: string;18 unmodified lines294 295 return CommitSha.make(ran.stdout.trim());296 });297 341-/**342- * The merged tree as a commit on `main` and the head, pushed to the fork's343- * `mergeRef(tree)`, where a Checker's fetch of the fork's refs finds it.344- * It is dated at the epoch, so merging the same sides again345- * makes the same commit, and pushing it again changes nothing.346- */298+/** Dated at the epoch, so merging the same sides again makes the same commit. */299 const keptForChecks = (300 job: Job,301 sides: {302 readonly head: CommitSha;26 unmodified lines329 ? commit330 : yield* job.blocked(push, printed(ran));331 });332 381-/**382- * The answer's head merged onto canonical `main` with its base as the merge383- * base: the merged tree and the answer's changes, or `StaleBase` with the384- * paths that conflict. Nothing is pushed.385- */333 export const merge = (wire: typeof MergeWire.Type) =>334 Effect.gen(function* () {335 const { job } = wire;336 34 unmodified lines371 372 return { changes, tree: merged.tree };373 });374 428-/** A path's folders and file name; one that cannot name a file is a defect upstream. */375 const placed = ({ path }: { readonly path: string }) =>376 path.split("/").every((segment) => !["", ".", "..", ".git"].includes(segment))377 ? Effect.void378 : Effect.die(`${path} cannot name a file in a repo`);379 434-/**435- * `main` with `files` added, written to the copy: the new root. A file436- * keeps the mode of the file it replaces; a path where a folder, a symlink437- * or a submodule stands blocks the job.438- */380+/** A file keeps the mode of the file it replaces. */381 const composed = (382 job: Job,383 main: string,384 files: readonly { readonly path: string; readonly content: string }[]43 unmodified lines428 (yield* job.run(writeTree(job.repo, index))).stdout.trim()429 );430 });431 490-/** The tree a land rebuilds, written to the copy where it is new. */432 const rebuilt = (433 job: Job,434 wire: typeof LandWire.Type435 ): Effect.Effect<TreeSha, StaleBase | VerifierBlocked, Box> =>30 unmodified lines466 }),467 }468 );469 529-/** The mirror of canonical `main` (ADR 0005). */470 const landedRef = `${Brand.refsPrefix}landed`;471 532-/** Where the copy keeps canonical's notes ref. */472 const notesCopyOf = notesRef.replace("refs/notes/", `${notesCopy}/`);473 474 const encodeNote = Schema.encodeEffect(Schema.fromJsonString(Verdict));475 537-/** Whether the notes commit `notes` (in the copy) holds a note on `landing`. */476 const holdsNote = (job: Job, notes: string, landing: CommitSha) =>477 Effect.map(478 job.run(objectType(job.repo, `${notes}:${landing}`)),479 ({ exitCode }) => exitCode === 0480 );481 544-/**545- * The verdict written as the landing's note, unless it is there already:546- * the content `@repo/git/notes`' `noteCommit` writes (one JSON blob named by547- * the landing, fanout-free, the platform's commit on the earlier notes),548- * pushed alone. It gives the notes commit that holds the note.549- */482 const note = (job: Job, landing: CommitSha, verdict: Verdict, at: number) =>483 Effect.gen(function* () {484 const parent = yield* resolved(job, notesCopyOf);485 37 unmodified lines523 ? commit524 : yield* job.blocked(step, printed(ran));525 });526 595-/** A piece of bookkeeping a landing may leave pending. */527 type Bookkeeping = (typeof Landed.Type)["pending"][number];528 598-/** One piece of bookkeeping: `None` once written, its name when it was not. */529 const attempt = <A, E, R>(item: Bookkeeping, write: Effect.Effect<A, E, R>) =>530 write.pipe(531 Effect.as(Option.none<Bookkeeping>()),532 Effect.catchCause((cause) =>3 unmodified lines536 )537 )538 );539 610-/**611- * What follows a landing on `main`, each in its own push: the612- * mirror ref, while the landing is still main's tip (a later landing's own613- * mirror supersedes it), then the verdict note. Neither fails the landing;614- * what was not written comes back pending, and landing the same job again615- * writes it.616- */540+/** Neither fails the landing: what was not written comes back pending, and landing again writes it. */541 const settle = (542 job: Job,543 wire: typeof LandWire.Type,544 landing: CommitSha,31 unmodified lines576 const requestIdOf = (text: string) =>577 parseTrailers(text).find(({ key }) => key.toLowerCase() === "request-id")578 ?.value;579 656-/** The base a stale land names: the answer's own, or the main it was built on. */580 const baseOf = (wire: typeof LandWire.Type) =>581 Rebuild.match(wire.job.rebuild, {582 Compose: () => wire.job.main,583 Existing: () => wire.job.main,584 Merge: ({ base }) => base,585 });586 664-/**665- * A land that found `main` at `tip`, not where the job left it: an earlier666- * land of the same request (a child of the job's `main` carrying its667- * `Request-Id`, within 16 first parents of the tip) gets its missing668- * bookkeeping written; anything else is `StaleBase`.669- */587+/** An earlier land of the same `Request-Id` gets its missing bookkeeping written; anything else is `StaleBase`. */588 const moved = (job: Job, wire: typeof LandWire.Type, tip: string) =>589 Effect.gen(function* () {590 const history = readLog(591 (yield* job.run(firstParents(job.repo, tip, LOOKBACK))).stdout18 unmodified lines610 main: CommitSha.make(tip),611 });612 });613 696-/**697- * One commit on canonical `main` whose parent is the job's `main` and whose698- * tree is the job's `tree`, rebuilt here; the answerer its author and the699- * platform its committer. It is pushed without force, so a `main` that700- * moved refuses it; then the mirror ref and the verdict note, each alone.701- */614+/** Pushed without force, so a `main` that moved refuses it. */615 export const land = (wire: typeof LandWire.Type) =>616 Effect.gen(function* () {617 const { job: landing } = wire;618 61 unmodified lines680 681 return yield* job.blocked(script.main, printed(ran));682 });683 771-// What a composed commit says: the platform made it, for a check, off main.684 const COMPOSE_MESSAGE = "Compose files onto main for a check\n";685 774-/**775- * `main` with a decider's files added, committed by the platform on `main`776- * and pushed to `${Brand.refsPrefix}compose/<tree>`, where a Checker fetches777- * it by id. `main` never moves. Composed before onto the same `main`, it is778- * the commit already there.779- */686 export const compose = (wire: typeof ComposeWire.Type) =>687 Effect.gen(function* () {688 const job: Job = {689 ...(yield* runner({ main: wire.main.token })),49 unmodified lines739 740 return { commit, tree };741 });742 837-/** Whether `rev` names a commit in the Lander's copy. */743 const hasCommit = (job: Job, rev: string) =>744 Effect.map(745 job.run(objectType(job.repo, `${rev}^{commit}`)),746 ({ exitCode }) => exitCode === 0747 );748 844-/** `commit` in the Lander's copy, fetched by its id if fetching main did not bring it. */749 const present = (job: Job, commit: string) =>750 Effect.gen(function* () {751 if (!(yield* hasCommit(job, commit))) {752 yield* job.run(fetchCommit(job.repo, job.url, commit));6 unmodified lines759 `canonical has no commit ${commit}`760 );761 });762 859-/**860- * The entries of a config folder bundled by bun in the work folder: the861- * folder's files checked out from the copy (no repo config, no hooks; files862- * only, never a symlink), the sdk's two names pointed at the image's copy863- * and its packages beside it, then bun's output read back, each entry at its864- * own path and each shared chunk at the path bun gave it.865- */763+/** Files only, never a symlink, and no repo config or hooks. */764 const built = (765 job: Job,766 files: readonly {767 readonly path: string;44 unmodified lines812 )813 );814 });815 918-/**919- * The config folder at `at`, for the rules evaluator: its project module,920- * visibility module and ask files each bundled by bun into plain ES modules921- * with the sdk and `effect` inlined (shared code in chunks beside them), its922- * other files (`policy.json`, the vouch file) as committed, and the version923- * of the sdk the image carries. A folder that is missing gives no modules:924- * the project runs on the defaults. Nothing in the folder runs here.925- */816+/** Nothing in the folder runs here. A missing folder gives no modules: the defaults apply. */817 export const bundleRules = (wire: typeof BundleWire.Type) =>818 Effect.gen(function* () {819 const { sdk } = yield* Layout;820 46 unmodified linesmodified:apps/sandbox/src/lander/script.ts+13 added-144 removed
1-/**2- * The Lander's git, as data: each step is one git command, the remote it3- * reaches (whose token `run.ts` hands git in its env, never on its command4- * line), and how its exit reads. Pure, so the script is read and tested5- * without a container; `run.ts` runs it through the `Box` port and reads6- * what git printed with the parsers below.7- *8- * Every step runs git with hooks pointed at `/dev/null`, no credential9- * helper, no redirects and no automatic maintenance, in a bare repo: the10- * Lander checks nothing out and runs nothing from the trees it handles.11- * Nothing here pushes with force, `--force-with-lease` or `--atomic` to12- * `main`: a landing is a plain push, which git refuses when13- * `main` moved, and only a compose ref, never `main`, moves by a lease. A14- * merge pushes one ref, to the answer's fork alone: the merged commit, for15- * the Checker to fetch.16- */1+// The Lander checks nothing out and runs nothing from the trees it handles.2+// Nothing pushes `main` with force, a lease or `--atomic`: a landing is a3+// plain push, which git refuses when `main` moved.4 import { Brand } from "@repo/brand";5 import type { LandJob, Merged, MergeJob } from "@repo/project/lander/wire";6 import { BlobSha, CommitSha, RepoPath, TreeSha } from "@repo/protocol/ids";7 import type { RepoName } from "@repo/protocol/ids";1 unmodified line9 import type { Types } from "effect";10 11 import type { Executed } from "../box.ts";12 26-/** Which of a job's remotes a step reaches. */13 export type RemoteName = "main" | "fork";14 29-/** How a step's exit reads. */15 export type Expect =31- /** Exit 0, or the job is blocked. */16 | "ok"17 /** `merge-tree`: 0 is a clean merge, 1 a merge with conflicts. */18 | "merge"35- /** A push: what git printed says whether the ref moved, and why not. */19 | "push"20 /** A question: a non-zero exit means "no". */21 | "probe";22 40-/** One command: git, or a tool beside it in the image (`mkdir`, `bun`, `cat`). */23 export interface GitStep {24 readonly argv: Array.NonEmptyReadonlyArray<string>;43- /** Env git needs for this step alone: identities, an index file. Never a token. */25+ /** Never a token. */26 readonly env?: Readonly<Record<string, string>>;45- /** The remote this step reaches; git gets its token as a header, through env. */27 readonly remote?: RemoteName;28 readonly expect: Expect;29 }30 50-/** Where canonical `main` is kept in the Lander's copy. */31 export const mainCopy = "refs/lander/main";32 53-/** Where a fork's branches are kept in the Lander's copy. */33 export const forkCopy = (fork: RepoName) => `refs/lander/forks/${fork}`;34 56-/** Where canonical's notes refs are kept in the Lander's copy. */35 export const notesCopy = "refs/lander/notes";36 59-/** Where a compose ref already on canonical is kept in the Lander's copy. */37 export const composeCopy = "refs/lander/compose";38 62-/** The canonical branch a landing moves. */39 export const mainRef = "refs/heads/main";40 65-/**66- * Where a merged commit waits, in the answer's fork, for a Checker to fetch67- * its tree: named by the tree, so a ref an answerer rewrote cannot change68- * what is checked (at worst the Checker finds no such tree).69- */41+/** Named by the tree, so a ref an answerer rewrote cannot change what is checked. */42 export const mergeRef = (tree: string) => `${Brand.refsPrefix}merge/${tree}`;43 44 // Each git command: no hooks, no helper that could see a token, no redirect45 // a header could follow, and nothing running in the background.9 unmodified lines55 "-c",56 "maintenance.auto=false",57 ] as const;58 87-/**88- * The Lander's copy of a canonical repo, relative to its work folder: one89- * bare repo per project, kept between jobs so a fetch brings only what is90- * new. It is never shallow, so a push from it sends no `shallow` lines,91- * which Artifacts' receive-pack does not advertise.92- */59+/** Never shallow: Artifacts' receive-pack does not advertise `shallow`. */60 export const copyOf = (repo: RepoName) => `repos/${repo}.git`;61 62 const git = (63 repo: RepoName,6 unmodified lines70 ];71 72 const fetch = ["fetch", "--quiet", "--no-tags", "--no-write-fetch-head"];73 107-/**108- * The folders a job writes in, made if they are missing: the container's109- * file writes, like the Sandbox SDK's, make no folder on their own.110- */74+/** The container's file writes make no folder on their own. */75 export const folders = (76 paths: Array.NonEmptyReadonlyArray<string>77 ): GitStep => ({ argv: ["mkdir", "-p", "--", ...paths], expect: "ok" });78 115-/** A folder and everything in it gone, if it was there. */79 export const removeFolder = (folder: string): GitStep => ({80 argv: ["rm", "-rf", "--", folder],81 expect: "ok",82 });83 121-/** The Lander's copy of `repo`, made if it is missing; making it again changes nothing. */84 export const initCopy = (repo: RepoName): GitStep => ({85 argv: ["git", ...safety, "init", "--quiet", "--bare", copyOf(repo)],86 expect: "ok",87 });88 127-/**128- * Canonical `main` fetched into the copy, with its notes refs when a landing129- * needs them (`--prune` drops a notes ref canonical no longer has).130- */89 export const fetchMain = (90 repo: RepoName,91 url: string,92 options: { readonly notes?: boolean } = {}9 unmodified lines102 expect: "ok",103 remote: "main",104 });105 148-/** Every branch of the answer's fork, fetched into the copy. */106 export const fetchFork = (107 repo: RepoName,108 fork: RepoName,109 url: string2 unmodified lines112 expect: "ok",113 remote: "fork",114 });115 159-/**160- * The answer's head merged onto `main` with its own base as the merge base,161- * by `git merge-tree --write-tree` (git 2.40 or later): no worktree, no162- * checkout. It prints the merged tree, then each conflicting path.163- */116+/** `merge-tree --write-tree` needs git 2.40 or later. */117 export const mergeTree = (118 repo: RepoName,119 sides: { readonly base: string; readonly main: string; readonly head: string }120 ): GitStep => ({10 unmodified lines131 ),132 expect: "merge",133 });134 182-/** What changed from `from` to `to`, path by path, with blob ids. */135 export const diffTree = (136 repo: RepoName,137 from: string,138 to: string1 unmodified line140 argv: git(repo, "diff-tree", "-r", "-z", "--no-renames", from, to),141 expect: "ok",142 });143 192-/** A merge as git runs it, in order. */144 export interface MergeScript {194- /** Canonical `main` and every branch of the fork, into the Lander's copy. */145 readonly fetch: readonly GitStep[];146 readonly merge: GitStep;147 /** The answer's changes against its own base, not main's. */148 readonly changes: GitStep;149 }150 201-/** A merge's fetches and merge; it writes nothing to canonical. */151 export const mergeScript = (152 job: typeof MergeJob.Type,153 remotes: { readonly main: string; readonly fork: string }154 ): MergeScript => ({5 unmodified lines160 ],161 merge: mergeTree(job.repo, job),162 });163 215-/**216- * One push of one ref, from the copy. `lease` makes it a compare-and-swap on217- * a ref that may move to a commit that does not descend from it: only ever218- * a compose ref.219- */164+/** `lease` is only ever for a compose ref, never `main`. */165 export const pushRef = (166 repo: RepoName,167 url: string,168 update: {169 readonly to: string;170 readonly ref: string;171 readonly lease?: string;227- /** The remote it reaches: canonical, unless it is the fork. */172 readonly remote?: RemoteName;173 }174 ): GitStep => ({175 argv: git(10 unmodified lines186 expect: "push",187 remote: update.remote ?? "main",188 });189 246-/** The two pushes of a landing. */190 export interface LandScript {248- /** The landing onto canonical `main`. */191 readonly main: GitStep;250- /** The mirror ref onto the landing, once `main` moved. */192 readonly mirror: GitStep;193 }194 254-/**255- * The two pushes of a landing, in order and each alone: `landing` onto256- * canonical `main`, a plain push that git refuses when `main` is no longer257- * the landing's parent; then, once it moved, the mirror ref (ADR 0005).258- */195 export const landScript = (196 job: Pick<typeof LandJob.Type, "repo">,197 url: string,198 landing: CommitSha,2 unmodified lines201 main: pushRef(job.repo, url, { ref: mainRef, to: landing }),202 mirror: pushRef(job.repo, url, { ref: mirror, to: landing }),203 });204 269-/** One git identity at one moment, as git's env spells it. */205 export interface Signature {206 readonly name: string;207 readonly email: string;208 /** Seconds since the epoch, in UTC. */209 readonly at: number;210 }211 277-/** A commit of `tree` on `parents`, with its message from a file, as its people sign it. */212 export const commitTree = (213 repo: RepoName,214 commit: {215 readonly tree: string;21 unmodified lines237 },238 expect: "ok",239 });240 307-/** Whether `rev` names an object in the copy; it prints the object's type. */241 export const objectType = (repo: RepoName, rev: string): GitStep => ({242 argv: git(repo, "cat-file", "-t", rev),243 expect: "probe",244 });245 313-/** One revision's id in the copy. */246 export const revParse = (repo: RepoName, rev: string): GitStep => ({247 argv: git(repo, "rev-parse", "--verify", "--quiet", rev),248 expect: "probe",249 });3 unmodified lines253 argv: git(repo, "hash-object", "-w", "--no-filters", "--", file),254 expect: "ok",255 });256 325-/** An index file loaded with `tree`, or emptied when there is none. */257 export const readTree = (258 repo: RepoName,259 index: string,260 tree?: string2 unmodified lines263 env: { GIT_INDEX_FILE: index },264 expect: "ok",265 });266 336-/** Blobs placed in an index file at their paths, with their modes. */267 export const updateIndex = (268 repo: RepoName,269 index: string,270 entries: readonly {14 unmodified lines285 env: { GIT_INDEX_FILE: index },286 expect: "ok",287 });288 359-/** The tree an index file holds, written to the copy. */289 export const writeTree = (repo: RepoName, index: string): GitStep => ({290 argv: git(repo, "write-tree"),291 env: { GIT_INDEX_FILE: index },292 expect: "ok",293 });294 366-/**367- * An index file's files written under `folder`, symlinks as plain files368- * holding their target, so nothing written points outside it.369- */295+/** Symlinks as plain files holding their target, so nothing written points outside. */296 export const checkoutIndex = (297 repo: RepoName,298 index: string,299 folder: string12 unmodified lines312 env: { GIT_INDEX_FILE: index },313 expect: "ok",314 });315 390-/** The modes and ids of `paths` in `tree`, those that are there. */316 export const lsTree = (317 repo: RepoName,318 tree: string,319 paths: readonly string[]1 unmodified line321 argv: git(repo, "ls-tree", "-z", "--full-tree", tree, "--", ...paths),322 expect: "ok",323 });324 400-/** Every file under `folder` in `tree`, at any depth, with its mode and id. */325 export const filesUnder = (326 repo: RepoName,327 tree: string,328 folder: string1 unmodified line330 argv: git(repo, "ls-tree", "-r", "-z", "--full-tree", tree, "--", folder),331 expect: "ok",332 });333 410-/** A blob's bytes, printed. */334 export const catBlob = (repo: RepoName, blob: string): GitStep => ({335 argv: git(repo, "cat-file", "blob", blob),336 expect: "ok",337 });338 416-/** One commit fetched from canonical by its id, into the copy's objects. */339 export const fetchCommit = (340 repo: RepoName,341 url: string,342 commit: string2 unmodified lines345 expect: "ok",346 remote: "main",347 });348 427-/** The commits from `tip` back along first parents, at most `count`. */349 export const firstParents = (350 repo: RepoName,351 tip: string,352 count: number9 unmodified lines362 ),363 expect: "ok",364 });365 445-/** A ref's id on a remote, if it has the ref. */366 export const lsRemote = (367 repo: RepoName,368 url: string,369 ref: string2 unmodified lines372 expect: "ok",373 remote: "main",374 });375 456-/** A ref fetched from canonical into `into` in the copy. */376 export const fetchRef = (377 repo: RepoName,378 url: string,379 ref: string,3 unmodified lines383 expect: "ok",384 remote: "main",385 });386 468-// --------------------------------------------------------------- bundling469-470-// A module that runs: what the rules evaluator imports, and what a bundle inlines.387 const SCRIPT = /\.[cm]?[jt]sx?$/u;388 473-// An ask file, as `@repo/rules` finds one: `<id>.ask.ts`, or its JavaScript.389 const ASK_FILE = /\.ask\.[cm]?[jt]s$/u;390 476-/**477- * The config folder's project module, which a bundle names whether or not478- * the folder has one (`ConfigBundle.entry`).479- */391 export const configEntry = `${Brand.configDir}/project.ts`;392 482-/** Whether a file in the config folder is code, which a bundle carries only inlined. */393 export const isScript = (path: string) => SCRIPT.test(path);394 485-/** The config folder's visibility module: its layers and held-back checks. */395 const visibilityEntry = `${Brand.configDir}/visibility.ts`;396 488-/**489- * The modules the rules evaluator imports, each bundled on its own: the490- * project module, the visibility module and every ask file. Other code in491- * the folder (helpers, an ask's check) is inlined where an entry imports492- * it, or left out.493- */397 export const bundleEntries = (paths: readonly string[]) =>398 paths.filter(399 (path) =>400 path === configEntry ||401 path === visibilityEntry ||402 (path.startsWith(`${Brand.configDir}/asks/`) && ASK_FILE.test(path))403 );404 502-/** Where bun writes an entry's bundle: its path, as JavaScript. */405 export const bundledAs = (entry: string) => entry.replace(/\.[^./]*$/u, ".js");406 505-/**506- * How the config folder's imports resolve: both names of the sdk (its507- * workspace name and the published `<cli package>/rules`) to the image's508- * copy. Anything else bare resolves in the packages beside that copy, so509- * `effect` is the sdk's own.510- */407+/** Bare imports resolve beside the sdk's copy, so `effect` is the sdk's own. */408 export const resolution = (sdk: string) =>409 `${JSON.stringify(410 {411 compilerOptions: {3 unmodified lines415 null,416 2417 )}\n`;418 522-/** A symlink at `link` to `target`. */419 export const symlink = (target: string, link: string): GitStep => ({420 argv: ["ln", "-s", "--", target, link],421 expect: "ok",422 });423 528-/**529- * The entries bundled by bun, for a browser-like runtime as ES modules:530- * code the entries share goes to chunks in the config folder, and every531- * import resolves as `tsconfig` (written by `resolution`) says. Macros are532- * off, so no code in the folder runs while it is bundled.533- */424+/** Macros are off, so no code in the folder runs while it is bundled. */425 export const bundle = (input: {426 readonly root: string;427 readonly out: string;428 readonly tsconfig: string;15 unmodified lines444 ],445 expect: "ok",446 });447 557-/** Every file under `folder`, by its path from there. */448 export const listFiles = (folder: string): GitStep => ({449 argv: ["find", folder, "-type", "f", "-printf", "%P\\0"],450 expect: "ok",451 });452 563-/** One file's bytes, printed. */453 export const readFile = (file: string): GitStep => ({454 argv: ["cat", "--", file],455 expect: "ok",456 });457 569-// ------------------------------------------------------------------ reading570-458 const fields = (text: string) => text.split("\0").filter((part) => part !== "");459 573-/** What `merge-tree` printed: the merged tree, and the paths that conflict, sorted. */460 export const readMerge = (stdout: string) => {461 const [tree = "", ...conflicts] = fields(stdout);462 463 return {3 unmodified lines467 tree: TreeSha.make(tree.trim()),468 };469 };470 585-/** A change's status, as a merge reports it. */471 type Status = (typeof Merged.Type)["changes"][number]["status"];472 473 /** A raw diff's status letter as a change's status; a type change is a modification. */474 const statusOf = (letter: string): Status | undefined => {19 unmodified lines494 495 // An object id of zeros: no object, on the side of a change that has none.496 const NO_OBJECT = /^0+$/u;497 613-// A raw diff line's head: both modes, both blob ids, and the status letter.498 const RAW =499 /^:\d+ \d+ (?<before>[0-9a-f]+) (?<after>[0-9a-f]+) (?<letter>[A-Z])/u;500 617-/** One change as a merge reports it. */501 type Changed = (typeof Merged.Type)["changes"][number];502 620-/**621- * What `diff-tree -r -z --no-renames` printed, as changes in path order: a622- * file that changed type is modified, and a submodule's pointer counts as a623- * file, as `@repo/git/tree-diff` reads them.624- */503+/** A submodule's pointer counts as a file, as `@repo/git/tree-diff` reads them. */504 export const readChanges = (stdout: string) =>505 Array.chunksOf(fields(stdout), 2).flatMap(([meta, path = ""]) => {506 const raw = RAW.exec(meta)?.groups;507 const status = statusOf(raw?.letter ?? "");17 unmodified lines525 526 return [change];527 });528 650-/** One commit as `firstParents` prints it. */529 export interface Logged {530 readonly sha: CommitSha;531 readonly parents: readonly CommitSha[];532 readonly message: string;533 }534 657-/** What `firstParents` printed. */535 export const readLog = (stdout: string): readonly Logged[] =>536 fields(stdout).map((record) => {537 const newline = record.indexOf("\n");538 const head = newline === -1 ? record : record.slice(0, newline);5 unmodified lines544 sha: CommitSha.make(sha),545 };546 });547 671-/** What `lsTree` printed: each path's mode and id. */548 export const readEntries = (stdout: string) =>549 new Map(550 fields(stdout).map((line) => {551 const tab = line.indexOf("\t");2 unmodified lines554 return [line.slice(tab + 1), { mode, sha }] as const;555 })556 );557 682-/** What `listFiles` printed: each file's path. */558 export const readFiles = (stdout: string) => fields(stdout);559 685-/** What `lsRemote` printed: the ref's id, when the remote has it. */560 export const readRemoteRef = (stdout: string) => {561 const [line = ""] = stdout.split("\n");562 const [sha = ""] = line.split("\t");563 564 return sha === "" ? undefined : CommitSha.make(sha);565 };566 693-/** How a push came out. */567 export type Pushed =695- /** The ref now points where the push said, or already did. */568 | "moved"697- /** The ref was not where the push expected: someone else moved it first. */569 | "stale"570 /** Artifacts was busy with another push to the repo; retryable. */571 | "busy"701- /** Anything else. */572 | "failed";573 574 // git's words for a push the ref's current value refused: a client-side575 // fast-forward check (`fetch first`, `non-fast-forward`, `stale info` for a6 unmodified lines582 583 // A porcelain line: the flag, `from:to`, and the summary.584 const PORCELAIN = /^(?<flag>.)\t(?<refs>[^\t]*)\t(?<summary>.*)$/u;585 716-/** How the push of `ref` came out, from what git printed with `--porcelain`. */586 export const readPush = (ran: Executed, ref: string): Pushed => {587 if (`${ran.stdout}\n${ran.stderr}`.includes(BUSY)) {588 return "busy";589 }18 unmodified linesmodified:apps/sandbox/src/box.ts-10 removed
1-/**2- * The `Box` port: the one container a Checker or a Lander Durable Object3- * runs its commands in. Both run through it, so their scripts are tested in4- * Node over local processes and run in a container in the5- * Worker (`box/sdk.ts`).6- */1 import { Context, Schema } from "effect";2 import type { Array, Effect } from "effect";3 10-/** The container would not run a command, take a file or answer at all. */4 export class BoxFailed extends Schema.TaggedError<BoxFailed>()("BoxFailed", {5 operation: Schema.Literals(["exec", "writeFile"]),6 reason: Schema.String,7 }) {}8 16-/** How one command runs: where, with what env, and for how long at most. */9 export interface ExecOptions {10 readonly cwd?: string;11 readonly env?: Readonly<Record<string, string>>;12 readonly timeoutMs?: number;13 }14 23-/** What one command left: its exit code and its output, as text. */15 export interface Executed {16 readonly exitCode: number;17 readonly stdout: string;18 readonly stderr: string;10 unmodified lines29 readonly writeFile: (30 path: string,31 bytes: Uint8Array32 ) => Effect.Effect<void, BoxFailed>;42- /** Stops the container and drops everything in it. */33 readonly destroy: () => Effect.Effect<void>;34 }35 >()("sandbox/Box") {}modified:apps/sandbox/src/checker.ts+5 added-37 removed
1-/**2- * The Checker: one container per check job, holding no credential, where an3- * answer's lanes run. Each job gets a Durable Object of4- * its own (a unique id), whose container is destroyed when the job ends; the5- * phases are `checker/run.ts`. The class name is frozen.6- *7- * One more Checker per project, named `snapshots:<project>`, never starts a8- * container: it keeps the ids of that project's setup snapshots, which every9- * check of the project shares.10- */1+// Each check job gets a Checker of its own (a unique id). A Checker named2+// `snapshots:<project>` never starts a container: it only keeps that3+// project's snapshot ids.4 import type { CheckRun } from "@repo/checks/check-runner";5 import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";6 import { keyOf } from "@repo/protocol/ids";7 import { VerifierBlocked } from "@repo/protocol/refusal";6 unmodified lines14 import { blocked, check } from "./checker/run.ts";15 import { hasGateways, SdkChecker } from "./checker/sdk.ts";16 import { answerJob } from "./job.ts";17 25-/** The run block's image a check runs in when it names none. */18 const DEFAULT_IMAGE = "checker:default";19 28-/** That image's name in `wrangler.jsonc`, built from `images/check.Dockerfile`. */20 const CHECK_IMAGE = "check";21 31-/**32- * The Checker's container size: two vCPUs and 8 GiB. oxlint with JS33- * plugins (burrow's lint lane) reserves about 6 GiB of address space per34- * thread for its fixed-size allocators (4 GiB aligned on 2 GiB), and Linux35- * refuses one reservation larger than the machine's memory: on the36- * runtime's default (`lite`, 256 MiB) the lane aborted on main and on every37- * answer, so each answer was `VerifierBlocked` (dev-oscabriel, 2026-10-08).38- * `standard-2`'s 6 GiB leaves no room for one. A restore from a snapshot39- * starts on it too.40- */22+/** oxlint's JS plugins reserve about 6 GiB of address space per thread; smaller sizes abort. */23 export const checkInstance = "standard-3";24 43-/** The Checker's Durable Object, which owns its container. */25 export class Checker extends DurableObject<Env> {45- /** Runs one check job in this object's container, its outcome encoded. */26 check(wire: typeof CheckWire.Encoded): Promise<typeof CheckExit.Encoded> {27 return answerJob(CheckWire, CheckExit, (job) => this.#checked(job))(wire);28 }29 50- /** The snapshot id kept under `key`, on a project's snapshot index. */30 snapshotOf(key: string): string | null {31 return this.ctx.storage.kv.get<string>(key) ?? null;32 }33 66 unmodified lines100 );101 }102 }103 125-/**126- * What the Checker needs of the sandbox's env: a new Checker for each job,127- * and each project's snapshot index (a Checker that never starts a128- * container). `Env` has both; they are written out so the Checker reads them129- * as the plain promises Workers RPC returns, and a test stands Checkers in130- * without its stub types.131- */104+/** Written out so the Checker reads plain RPC promises and a test needs no stub types. */105 export interface Checkers {106 readonly CHECKER: {107 readonly newUniqueId: () => DurableObjectId;108 readonly get: (id: DurableObjectId) => {8 unmodified lines117 };118 };119 }120 148-/**149- * One check job from the platform, run in a Checker of its own, its outcome150- * encoded. A Checker that cannot be reached at all is `VerifierBlocked`, as151- * the job would have been.152- */121 export const runCheck = (122 env: Checkers,123 wire: typeof CheckWire.Encoded124 ): Promise<typeof CheckExit.Encoded> =>15 unmodified linesmodified:apps/sandbox/src/env-gateway.ts+5 added-63 removed
1-/**2- * The env gateway: the outbound entrypoint each `@proxy` host's3- * HTTPS requests reach from the Checker's container4- * (`interceptOutboundHttps(host, EnvGateway)`, `checker/sdk.ts`), as in5- * Cloudflare's "call an authenticated API from a sandbox": the credential6- * stays on the Worker's side, and the entrypoint lets out only the requests7- * it allows.8- *9- * Its props are one job's rules and, for a job of landed code alone, the10- * values the platform opened for it (never in the container, and gone with11- * the job). A request that matches no rule, matches a `block` rule, is not12- * HTTPS, or matches two rules that would put two values in one placeholder,13- * is answered 403 and sent nowhere. One it allows goes on as the container14- * sent it, its headers' placeholders swapped for values where the gateway15- * holds them, with no header added; for an unlanded job it holds none, so16- * the placeholder goes on unchanged. The answer comes back with every value17- * the gateway holds scrubbed back to its placeholder, from the headers and18- * from an uncompressed text body (varlock's proxy does the same, VD proxy19- * l.145). A compressed or binary body comes back as it is.20- */1+// Values stay on the Worker's side: placeholders are swapped in on the way2+// out, and values scrubbed back to placeholders on the way in (headers and3+// uncompressed text bodies only, as varlock's proxy does).4 import type { EnvProxy } from "@repo/checks/check-runner";5 import type { EnvKey } from "@repo/protocol/ids";6 import { WorkerEntrypoint } from "cloudflare:workers";7 import { Effect, Option, Order, Result, Stream } from "effect";8 9 import { forward, refused, resent } from "./outbound.ts";10 28-/** A value the gateway may swap in, with the placeholder the process sees for it. */11 export interface EnvSwapProps {12 readonly key: EnvKey;13 readonly placeholder: string;14 readonly value: string;15 }16 35-/** One job's env route, as the gateway gets it: plain data, on the Worker's side. */17 export interface EnvGatewayProps {18 readonly rules: readonly EnvProxy[];19 /** Empty unless the job runs landed code. */20 readonly values: readonly EnvSwapProps[];17 unmodified lines38 )}$`,39 "u"40 ).test(path);41 61-/** A rule's methods, written as one or a list (`GET, POST`); none allows any. */42 const methodMatches = (methods: string, method: string) =>43 methods44 .split(",")45 .map((each) => each.trim().toUpperCase())3 unmodified lines49 hostMatches(rule.host, url.host) &&50 (rule.path === undefined || pathMatches(rule.path, url.pathname)) &&51 (rule.method === undefined || methodMatches(rule.method, method));52 73-/**74- * Text and what replaces it: a placeholder and its value on the way out, a75- * value and its placeholder on the way back.76- */53 type Swap = readonly [from: string, to: string];54 79-/**80- * Whether `request` goes on, and with which swaps: the placeholder of each81- * rule it matches, for the value the gateway holds for that rule's key.82- * Refused, with the reason, when it is not HTTPS, matches no rule, matches83- * a `block` rule (which wins over any other), or matches two rules whose84- * one placeholder stands for two keys (the gateway would not know which85- * value goes).86- */55 const swapsFor = (56 props: EnvGatewayProps,57 request: Request58 ): Result.Result<readonly Swap[], string> => {44 unmodified lines103 Order.flip(Order.Number),104 ([from]: Swap) => from.length105 );106 139-/**140- * `text` with every `[from, to]` pair's `from` replaced by its `to`, the141- * longest first: a `DATABASE_URL` that holds a `DB_PASSWORD` goes whole,142- * not as the rest of the URL around the password's placeholder.143- */107 const replaced = (text: string, pairs: readonly Swap[]) => {108 let done = text;109 110 for (const [from, to] of pairs.toSorted(longestFirst)) {2 unmodified lines113 114 return done;115 };116 154-/** A copy of `headers` with each value's text replaced through `pairs`. */117 const headersReplaced = (headers: Headers, pairs: readonly Swap[]) => {118 const copy = new Headers();119 120 for (const [name, value] of headers) {2 unmodified lines123 124 return copy;125 };126 165-/** The request that goes on: the container's, its headers swapped. */127 const sent = (request: Request, swaps: readonly Swap[]) =>128 resent(request.url, request, headersReplaced(request.headers, swaps));129 169-/** A body the gateway can read as text and scrub: text-like, and not compressed. */130 const scrubbable = (headers: Headers) => {131 const type = headers.get("content-type")?.toLowerCase() ?? "";132 const encoding = headers.get("content-encoding")?.trim().toLowerCase() ?? "";133 5 unmodified lines139 ))140 );141 };142 183-/**184- * The length of the longest end of `text` that begins one of `values` but185- * is not all of it: held back until the next chunk says whether the value186- * completes there.187- */143+/** How much of `text`'s end may begin a value: held back for the next chunk. */144 const carried = (text: string, values: readonly string[]) =>145 Math.max(146 0,147 ...values.flatMap((value) =>3 unmodified lines151 )152 )153 );154 199-/**200- * A text body with every value replaced by its placeholder, chunk by201- * chunk, carrying across a chunk's end any text that may begin a value.202- */155 const scrubbedBody = (156 body: ReadableStream<unknown>,157 scrubs: readonly Swap[]158 ) => {28 unmodified lines187 Stream.toReadableStream()188 );189 };190 239-/**240- * The answer as the container gets it: every value the gateway holds241- * scrubbed back to its placeholder, in the headers and in a text body it242- * can read, of any length (streamed, so nothing is buffered whole). A243- * scrubbed body's length may change, so its `content-length` goes.244- */191+/** A scrubbed body's length may change, so its `content-length` goes. */192 const scrubbed = (response: Response, props: EnvGatewayProps): Response => {193 if (props.values.length === 0) {194 return response;195 }21 unmodified lines217 { headers, status: response.status, statusText: response.statusText }218 );219 };220 274-/** What the gateway answers one request from the container with. */221 const answer = (props: EnvGatewayProps, request: Request) =>222 Result.match(swapsFor(props, request), {223 onFailure: (reason) => Effect.succeed(refused(`${reason}\n`)),224 onSuccess: (swaps) =>2 unmodified lines227 (response) => scrubbed(response, props)228 ),229 });230 285-/**286- * The env gateway: one job's `@proxy` hosts reach it, and its props say287- * what it lets out and what it swaps in.288- */231 export class EnvGateway extends WorkerEntrypoint<Env, EnvGatewayProps> {232 override fetch(request: Request): Promise<Response> {233 return Effect.runPromise(answer(this.ctx.props, request));234 }1 unmodified linemodified:apps/sandbox/src/job.ts-12 removed
1-/**2- * How the sandbox answers one job from the platform: decode its wire, run3- * it, and send back its `Exit` encoded as JSON (principle 2: both sides of4- * the service binding decode with the same schemas). A wire that does not5- * decode, or an outcome that does not encode, is a defect: the platform6- * encoded the job with the same schema.7- */1 import { Effect, Schema } from "effect";2 import type { Exit } from "effect";3 4 export const answerJob =13 unmodified lines18 )19 )20 );21 29-/**30- * A job whose side of the sandbox is not built yet: `VerifierBlocked`, the31- * gate's trouble and never the answer's, with `not built` in a log32- * annotation, since a refusal carries no free text (principle 3).33- */22 export const notBuilt = <E>(job: string, blocked: E) =>23 Effect.logWarning("sandbox job not built").pipe(24 Effect.annotateLogs({ job, reason: "not built" }),25 Effect.andThen(Effect.fail(blocked))1 unmodified linemodified:apps/sandbox/src/lander.ts+6 added-39 removed
1-/**2- * The Lander: the trusted container that merges answers, composes ask files,3- * lands checked trees on canonical `main` with a non-force push, and bundles4- * the config folder. It runs no answer's code: only git, and5- * bun's bundler with macros off. The class name is frozen.6- *7- * One Lander Durable Object per project, named by the project's canonical8- * repo, owns one container and runs one job at a time in it: its jobs share9- * the container's copy of the repo and its scratch files, and a project's10- * landings stay serial here as they are in the Project DO's queue.11- */1+// The trusted container: it runs no answer's code, only git and bun's bundler2+// with macros off. One per project, one job at a time, so landings stay serial.3 import {4 BundleExit,5 BundleWire,6 ComposeExit,11 unmodified lines18 import { SdkBox } from "./box/sdk.ts";19 import { answerJob } from "./job.ts";20 import { bundleRules, compose, land, merge } from "./lander/run.ts";21 31-/** The image the Lander's container runs: `images.land` in `wrangler.jsonc`. */22 export const landImage = "land";23 34-/**35- * The Lander's four jobs as the service binding carries them: each decoded,36- * run in `box` while it holds `turn` (one job at a time), and its `Exit`37- * encoded as JSON.38- */24 export const landerJobs = (25 box: Layer.Layer<Box>,26 turn: Semaphore.Semaphore27 ) => {11 unmodified lines39 merge: answerJob(MergeWire, MergeExit, (wire) => inBox(merge(wire))),40 };41 };42 58-/**59- * The Lander's container size: a whole vCPU. On the runtime's default60- * (`lite`, 1/16 vCPU) one landing took 32 s and a config bundle 20 s on61- * dev-oscabriel, against a target of 5 s.62- */43+/** On the default `lite` (1/16 vCPU) one landing took 32 s. */44 export const landInstance = "standard-2";45 65-/**66- * The Lander's Durable Object, which owns its container: started on its67- * first job from the `land` image on `landInstance`, with internet on,68- * since git reaches Artifacts over HTTPS with the tokens each job carries.69- */46+/** Internet on: git reaches Artifacts over HTTPS with each job's tokens. */47 export class Lander extends DurableObject<Env> {48 readonly #jobs: ReturnType<typeof landerJobs>;49 50 constructor(ctx: DurableObjectState, env: Env) {35 unmodified lines86 return this.#jobs.bundleRules(wire);87 }88 }89 113-/** The Lander's jobs as its Durable Object takes them over RPC. */90 export type LanderJobs = Pick<91 Lander,92 "bundleRules" | "compose" | "land" | "merge"93 >;94 119-/**120- * The one binding the jobs reach: the Lander namespace, by what it gives.121- * The Worker's `Env` is one; so is a test's fake. (The generated `Env` names122- * the class through an `import()` the type-aware linter does not follow, so123- * it would read a stub straight from `Env` as `any`.)124- */95+// The generated `Env` names the class through an `import()` the type-aware96+// linter does not follow, so a stub read straight from `Env` would be `any`.97 export interface Landers {98 readonly LANDER: { readonly getByName: (name: string) => LanderJobs };99 }100 129-/** The project's Lander: one per canonical repo, so one container per project. */101 const landerOf = (102 env: Landers,103 wire: { readonly job: { readonly repo: string } }104 ) => env.LANDER.getByName(wire.job.repo);105 135-/** An answer's head merged onto canonical `main`, in the project's Lander. */106 export const runMerge = (107 env: Landers,108 wire: typeof MergeWire.Encoded109 ): Promise<typeof MergeExit.Encoded> => landerOf(env, wire).merge(wire);110 141-/** A checked tree landed on canonical `main`, in the project's Lander. */111 export const runLand = (112 env: Landers,113 wire: typeof LandWire.Encoded114 ): Promise<typeof LandExit.Encoded> => landerOf(env, wire).land(wire);115 147-/** A decider's files composed onto canonical `main`, on a compose ref. */116 export const runCompose = (117 env: Landers,118 wire: typeof ComposeWire.Encoded119 ): Promise<typeof ComposeExit.Encoded> => landerOf(env, wire).compose(wire);120 153-/** The config folder at a landed commit, bundled for the rules evaluator. */121 export const runBundleRules = (122 env: Landers,123 wire: typeof BundleWire.Encoded124 ): Promise<typeof BundleExit.Encoded> => landerOf(env, wire).bundleRules(wire);modified:apps/sandbox/src/outbound.ts+5 added-39 removed
1-/**2- * The Checker container's only ways out, as outbound entrypoints of this Worker3- * (the outbound handler is the credential boundary). The container starts with4- * the internet off; its Durable Object routes the clone's host to5- * `CloneGateway` and every other host to `EgressGateway` (`checker/sdk.ts`),6- * each told what it may do through its props, which the container never sees.7- *8- * Both are reached through `ctx.exports`, which holds one loopback per export9- * of the Worker's main module, so `worker.ts` must export them.10- */1+// The Checker container's only ways out: the outbound handler is the2+// credential boundary, and the container never sees a gateway's props.3 import { WorkerEntrypoint } from "cloudflare:workers";4 import { Option } from "effect";5 6 import { allows, CLONE_HOST } from "./checker/network.ts";7 16-/** One job's remote and the read token the platform minted for it alone. */8 export interface CloneProps {9 readonly remote: string;10 readonly token: string;11 }12 22-/** The hosts the container may reach right now; `[]` is none. */13 export interface EgressProps {14 readonly allow: readonly string[];15 }16 27-/** A 403 whose plain-text body says why; `text` ends with its own newline. */17 export const refused = (text: string) =>18 new Response(text, {19 headers: { "content-type": "text/plain; charset=utf-8" },20 status: 403,21 });22 34-/**35- * Sends a request on to the internet. Redirects come back to the container,36- * so the request that follows one goes through a gateway too.37- */23+/** Redirects go back to the container, so a followed one passes a gateway too. */24 export const forward = (request: Request): Promise<Response> =>25 // @effect-diagnostics-next-line globalFetch:off -- an outbound entrypoint is the Worker's own network edge: workerd hands it a Request and takes back a Response, and its only way to the internet is the runtime's fetch; sandbox code may not use effect/http.26 fetch(request, { redirect: "manual" });27 42-/**43- * `request` as a new request to `url` with `headers`: its method, and its44- * body streamed through as it comes.45- */28 export const resent = (url: string, request: Request, headers: Headers) => {29 // Node sends a streamed body only with `duplex: "half"`; the Workers types30 // lack the key, and workerd ignores it.31 const init = {5 unmodified lines37 38 return new Request(url, init);39 };40 59-/**60- * The request the clone gateway sends for one from the container: a read of61- * the job's repo (`git-upload-pack`, as a clone or fetch makes) at the clone62- * host, exactly as git asks for one, sent to the remote with the token63- * added. Anything else, a push or a query git never sends included, is none.64- */41+/** Only `git-upload-pack` reads of the job's repo pass; a push or any other query does not. */42 const cloneRequestFor = (43 request: Request,44 props: CloneProps45 ): Option.Option<Request> => {21 unmodified lines67 resent(`${remote.origin}${url.pathname}${url.search}`, request, headers)68 );69 };70 94-/**95- * The clone's way out: the container clones the job's repo from the clone96- * host with no credential, and this entrypoint sends each read on to the97- * repo's real remote with `Authorization: Bearer <token>` (as the Artifacts98- * probes sent it, and as it works live). The token lives99- * in its props, on the Worker's side.100- */71+/** The container clones with no credential; the token is added here, on the Worker's side. */72 export class CloneGateway extends WorkerEntrypoint<Env, CloneProps> {73 override fetch(request: Request): Promise<Response> {74 return Option.match(cloneRequestFor(request, this.ctx.props), {75 onNone: () =>4 unmodified lines80 });81 }82 }83 113-/**114- * Every other way out: a request to a host its props allow goes on as it115- * is, and any other is refused with a 403 that names the host, so a setup116- * that fails on one says which.117- */84 export class EgressGateway extends WorkerEntrypoint<Env, EgressProps> {85 override fetch(request: Request): Promise<Response> {86 const { hostname } = new URL(request.url);87 9 unmodified linesmodified:apps/sandbox/src/worker.ts+1 added-10 removed
1-/**2- * The sandbox Worker. Its default entrypoint is reached only through the3- * platform's `SANDBOX` service binding: each method takes a job's wire,4- * encoded, and returns the job's `Exit`, encoded as JSON, so both sides5- * decode with the schemas in `@repo/checks/check-runner/wire` and6- * `@repo/project/lander/wire`.7- */1 import type { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";2 import type {3 BundleExit,4 BundleWire,12 unmodified lines17 export { Checker } from "./checker.ts";18 19 export { Lander } from "./lander.ts";20 28-// The Checker's container reaches out only through these, and its Durable29-// Object finds them in `ctx.exports`, which holds a loopback for each export30-// of this module alone (outbound.ts, env-gateway.ts).21+// `ctx.exports` holds a loopback only for the main module's exports.22 export { CloneGateway, EgressGateway } from "./outbound.ts";23 24 export { EnvGateway } from "./env-gateway.ts";25 25 unmodified linesmodified:apps/sandbox/test/box-sdk.test.ts-6 removed
14 unmodified lines15 16 return buffer;17 };18 19-/**20- * A Durable Object's container as the Container API shows it: it records21- * what starts it and each command it runs, and every command prints22- * `git version 2.47.3`.23- */19 const fakeContainer = (running: boolean) => {20 const started: ContainerStartupOptions[] = [];21 const commands: { argv: string[]; options: ContainerExecOptions }[] = [];22 24 unmodified lines47 };48 49 const start = { enableInternet: false, image: "check" };50 56-/** A running container whose one command never ends until it is killed. */51 const hungContainer = () => {52 const killed: (number | undefined)[] = [];53 54 const container = untouchable<Container>("container", {90 unmodified linesmodified:apps/sandbox/test/checker.test.ts+1 added-32 removed
81 unmodified lines82 call.argv[0] === "sh" &&83 call.argv[1] === "-c" &&84 call.argv[2] === command;85 86-/** How many times setup's command ran. */86 const setups = (calls: readonly Call[]) =>87 calls.filter((call) => isShell(call, SETUP)).length;88 90-/**91- * The recording as phases, each run of calls for one phase read as one:92- * the clone's route and git commands, setup's snapshot lookup, network and93- * command, the snapshot, egress off, the lanes, the report, the destroy.94- */89 const phaseOf = Match.type<Call>().pipe(90 Match.discriminatorsExhaustive("kind")({91 allow: ({ hosts }): readonly string[] =>92 hosts.length === 0 ? ["egressOff"] : ["setup"],61 unmodified lines154 })155 )156 );157 164- // Setup ran while egress allowed the registries and the run block's165- // own setup host, and nothing else.158 const setupAt = fake.calls.findIndex((call) => isShell(call, SETUP));159 160 const egress = fake.calls161 .slice(0, setupAt)3 unmodified lines165 hosts: [...REGISTRIES, "npm.pkg.github.com"],166 kind: "allow",167 });168 177- // The lanes ran in the job's order, after egress went off.169 expect(170 fake.calls.flatMap((call) =>171 call.kind === "exec" && call.argv[0] === "sh" ? [call.argv[2]] : []172 )79 unmodified lines252 : []253 )254 ).toStrictEqual(["evil.example"]);255 265- // Nothing ran after setup, nothing was kept, and the box is gone.256 expect(phasesOf(fake.calls)).toStrictEqual([257 "clone",258 "setup",259 "report",41 unmodified lines301 signature:302 "week > parses ISO weeks: AssertionError: expected 52 to be 53",303 },304 ]);315- // No raw log travels in the result.305 expect(JSON.stringify(ran)).not.toContain("Cannot find module");306 })307 );308 45 unmodified lines354 expect(ran.outputs).toStrictEqual([355 { lane: "no-explicit-any", stdout: printed },356 ]);357 369- // The outcome crosses the binding with it.358 const crossed = yield* Schema.encodeEffect(CheckExit)(359 Exit.succeed(ran)360 ).pipe(Effect.flatMap(Schema.decodeEffect(CheckExit)));361 42 unmodified lines404 call.kind === "restore" ? [call.hit] : []405 )406 ).toStrictEqual([true]);407 420- // The restored workspace is checked out at this job's tree again421- // before any lane runs.408 const restoredAt = second.calls.findIndex(409 (call) => call.kind === "restore"410 );411 103 unmodified lines515 })516 );517 });518 533-/** The requests the Worker sends on, in place of the network, until the scope ends. */519 const outboundRecorded = Effect.acquireRelease(520 Effect.sync(() => {521 const sent: Request[] = [];522 180 unmodified lines703 })704 );705 });706 722-/**723- * The sandbox's `CHECKER` namespace: each unique id gets a Checker over its724- * own fake container, and `snapshots:<project>` names an index kept in725- * `index`.726- */707 const checkerWorld = (options: {708 readonly withGateways: boolean;729- /** Whether each Checker's container is running before its job; it is unless false. */709 readonly running?: boolean;710 }) => {711 const boxes: ReturnType<typeof fakeContainer>[] = [];712 const index = new Map<string, string>();713 const named: string[] = [];714 736- /** A project's snapshot index, as Workers RPC hands one back. */715 const indexStub = untouchable<DurableObjectStub<Checker>>("index", {716 forgetSnapshot: (key) => {717 index.delete(key);718 16 unmodified lines735 736 return indexStub;737 };738 761- // A Checker reaches only its project's snapshot index through the env.739 const env: Env = {740 CHECKER: untouchable<Env["CHECKER"]>("CHECKER", { getByName: indexNamed }),741 LANDER: untouchable("LANDER"),742 };29 unmodified lines772 773 const encodedWire = () =>774 Schema.encodeEffect(CheckWire)(wireFor()).pipe(Effect.orDie);775 799-/**800- * Two jobs of one project through `runCheck`, one after the other, each in801- * a container that runs before it starts unless `running` is false.802- */776 const twoJobsIn = ({ running = true } = {}) =>777 Effect.gen(function* () {778 const world = checkerWorld({ running, withGateways: true });779 const wire = yield* encodedWire();50 unmodified lines830 expect(intercepts(boxes[0]?.calls ?? [])).toStrictEqual([831 `${CLONE_HOST} → clone ${REMOTE} ${TOKEN}`,832 "* → egress []",833 "http:* → egress []",861- // Setup reaches the registries and its own hosts, not the repo.834 `${CLONE_HOST} → egress [${setupHosts}]`,835 `* → egress [${setupHosts}]`,836 `http:* → egress [${setupHosts}]`,837 `${CLONE_HOST} → egress []`,43 unmodified lines881 Effect.gen(function* () {882 const { boxes } = yield* twoJobsIn({ running: false });883 884 // oxlint with JS plugins reserves 6 GiB of address space per913- // thread, which Linux refuses on a smaller instance: on the914- // runtime's default (`lite`, 256 MiB) burrow's lint lane aborted915- // on main and on every answer, so each answer was VerifierBlocked916- // (dev-oscabriel, 2026-10-08).885+ // thread, which Linux refuses on a smaller instance.886 const starts = boxes.flatMap(({ calls }) =>887 calls.flatMap((call) => (call.kind === "start" ? [call] : []))888 );889 28 unmodified linesmodified:apps/sandbox/test/env-injection.test.ts-21 removed
1-/**2- * The Checker's env: every `@sensitive` item reaches3- * the container as its placeholder, and a `@proxy` host's requests go4- * through the env gateway, which swaps the placeholder for the value only in5- * a run of landed code. Over the fake `Box` (`fake-box.ts`), and the gateway6- * itself with a fake upstream.7- */1 import { describe, expect, it } from "@effect/vitest";2 import { CheckAt } from "@repo/checks/check-runner";3 import type { CheckJob } from "@repo/checks/check-runner";4 import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";36 unmodified lines41 const SENTRY = EnvKey.make("SENTRY_AUTH_TOKEN");42 43 const PLACEHOLDER = "__SENTRY_AUTH_TOKEN_PLACEHOLDER__";44 52-/** The write-only value a landed run's gateway swaps in: never in the container. */45 const VALUE = "sntrys_5f0c1d2e3b4a69788796a5b4c3d2e1f0";46 47 const sentryRule = {48 block: false,19 unmodified lines68 ...env,69 },70 });71 80-/** The env `sh -c <command>` ran with, for each run of `command`. */72 const envsOf = (calls: readonly Call[], command: string) =>73 calls.flatMap((call) =>74 call.kind === "exec" && call.argv[0] === "sh" && call.argv[2] === command75 ? [call.options.env ?? {}]76 : []77 );78 88-/** One job through the Checker over the fakes: what they saw. */79 const checked = (wire: CheckWire) =>80 Effect.gen(function* () {81 const fake = fakeChecker();82 3 unmodified lines86 87 return { calls: fake.calls, outcome };88 });89 100-/** A job of landed code, carrying the value its gateway swaps in. */90 const landedJob = () =>91 jobWith({92 landed: true,93 values: [{ key: SENTRY, value: Redacted.make(VALUE) }],134 unmodified lines228 })229 );230 });231 243-/**244- * What the gateway sends on, in place of the network, until the scope245- * ends: each request, read, and the response `answer` gives for it.246- */232 const upstream = (answer: (request: Request) => Response) =>233 Effect.acquireRelease(234 Effect.sync(() => {235 const sent: Request[] = [];8 unmodified lines244 }),245 () => Effect.sync(() => vi.unstubAllGlobals())246 );247 263-/** A gateway for one job: its rules, and the values only a landed job's carries. */248 const gatewayFor = (props: Partial<EnvGatewayProps> = {}) =>249 new EnvGateway(250 untouchable<ExecutionContext<EnvGatewayProps>>("ctx", {251 props: { rules: [sentryRule], values: [], ...props },12 unmodified lines264 },265 method: "POST",266 });267 284-/** What reached the upstream: method, URL, every header, and the body. */268 const readSent = (request: Request) =>269 Effect.promise(() => request.text()).pipe(270 Effect.map((body) => ({271 body,212 unmodified lines484 })485 );486 });487 505-/**506- * One job through a Checker Durable Object over a fake container (the507- * Container API as `fake-box.ts` records it): the calls it made.508- */488 const inContainer = (wire: CheckWire) =>489 Effect.gen(function* () {490 const box = fakeContainer();491 179 unmodified linesmodified:apps/sandbox/test/fake-box.ts+1 added-35 removed
1-/**2- * The Checker's capabilities as fakes that record every call, in order, in3- * one list: the container (`Box`), its network, its snapshots, where its logs4- * go, and the Worker's own log lines. A test scripts what each command prints5- * and reads back what the Checker did, phase by phase.6- */1 import { untouchable } from "@repo/testkit/untouchable";2 import { Effect, Layer, Logger, Redacted, References } from "effect";3 4 import { Box } from "../src/box.ts";4 unmodified lines9 import { Snapshots } from "../src/checker/snapshots.ts";10 import type { EnvGatewayProps } from "../src/env-gateway.ts";11 import type { CloneProps, EgressProps } from "../src/outbound.ts";12 19-/** What the container could reach at one moment. */13 export type Reach = "clone route" | readonly string[];14 22-/** One thing the Checker did, as the fakes saw it. */15 export type Call =16 | {17 readonly kind: "exec";18 readonly argv: readonly string[];19 readonly options: ExecOptions;28- /**29- * What the network let out as the command started: the clone route30- * alone before the first `allow`, then the hosts that `allow` named.31- */20 readonly network: Reach;21 }22 | { readonly kind: "writeFile"; readonly path: string; readonly text: string }23 | { readonly kind: "destroy" }19 unmodified lines43 readonly message: string;44 readonly annotations: Readonly<Record<string, string>>;45 };46 59-/** What a command left, for a script. */47 export const exited = (48 exitCode: number,49 output: { readonly stdout?: string; readonly stderr?: string } = {}50 ): Effect.Effect<Executed, BoxFailed> =>3 unmodified lines54 stdout: output.stdout ?? "",55 });56 57 export interface FakeOptions {71- /**72- * What `sh -c <command>` does, by command (setup and lanes). A command not73- * listed exits 0 and prints nothing.74- */58+ /** A command not listed exits 0 and prints nothing. */59 readonly commands?: ReadonlyMap<string, Effect.Effect<Executed, BoxFailed>>;76- /** What `git ls-tree` prints: the lockfiles at the checked-out tree. */60 readonly lockfiles?: string;78- /** Snapshot keys kept so far, shared by the jobs a test runs. */61 readonly snapshots?: Set<string>;80- /** What writing a file does, by path; every write succeeds when absent. */62 readonly writeFile?: (path: string) => Effect.Effect<void, BoxFailed>;63 }64 84-/** A lockfile listing, as `git ls-tree HEAD -- <names>` prints one. */65 export const LOCKFILES =66 "100644 blob 8f2c1d0e9b7a6c5d4e3f2a1b0c9d8e7f6a5b4c3d\tbun.lock\n";67 88-/** The command `sh -c <command>` runs, or none for any other argv. */68 const shellCommandOf = (argv: readonly string[]) =>69 argv[0] === "sh" && argv[1] === "-c" ? argv[2] : undefined;70 92-/** The fakes for one job, and the list their calls go to. */71 export const fakeChecker = (options: FakeOptions = {}) => {72 const calls: Call[] = [];73 const kept = options.snapshots ?? new Set<string>();74 let reach: Reach = "clone route";108 unmodified lines183 ])184 ),185 kind: "log",186 level: logLevel,209- // A log line's message is its arguments, one string here.187 message: String(message),188 });189 }),190 ]);3 unmodified lines194 layer: Layer.mergeAll(box, network, snapshots, logs, logger),195 };196 };197 221-/** One thing done to a Durable Object's container, as the Container API saw it. */198 export type ContainerCall =199 | {200 readonly kind: "exec";201 readonly argv: readonly string[];2 unmodified lines204 | { readonly kind: "intercept"; readonly target: string; readonly to: string }205 | {206 readonly kind: "start";207 readonly from: string;232- /** The instance size the start named, when it named one. */208 readonly instance?: ContainerStartupOptions["instance"];209 }210 | { readonly kind: "snapshot" }211 | { readonly kind: "destroy" };6 unmodified lines218 219 return buffer;220 };221 247-/**248- * A container as the Container API shows a Durable Object one, running249- * unless `running` says otherwise (a stopped one is started before each250- * command): it records each call, prints a lockfile listing for `git251- * ls-tree`, and exits 0 with no output for every other command. Its252- * outbound intercepts record which gateway, with which props, took each253- * target.254- */222 export const fakeContainer = ({ running = true } = {}) => {223 const calls: ContainerCall[] = [];224 const gateways = new Map<Fetcher, string>();225 62 unmodified lines288 );289 },290 });291 325- /** The loopbacks `ctx.exports` holds for the Worker's outbound gateways. */292 const exports = {293 CloneGateway: ({ props }: { readonly props: CloneProps }) =>294 gateway(`clone ${props.remote} ${props.token}`),295 EgressGateway: ({ props }: { readonly props: EgressProps }) =>10 unmodified linesmodified:apps/sandbox/test/fake-env.ts-4 removed
1 import { untouchable } from "@repo/testkit/untouchable";2 3-/**4- * The sandbox Worker's env, as `wrangler.jsonc` declares it: each binding a5- * fake that throws if touched, so a test proves what a call touches.6- */3 export const fakeEnv = (): Env => ({4 CHECKER: untouchable("CHECKER"),5 LANDER: untouchable("LANDER"),6 });modified:apps/sandbox/test/held-back.test.ts+1 added-23 removed
56 unmodified lines57 const exportArea = AreaName.make("export");58 59 const parser = AreaName.make("parser");60 61-/**62- * The maintainers' sealed suite: two areas, three files. Each file names63- * its own test and carries a canary, so a leak of either is searchable.64- */61+/** Each file carries a canary, so a leak is searchable. */62 const SEALED = [63 {64 area: exportArea,65 path: "checks/held-back/export/round-trip.test.ts",18 unmodified lines84 }));85 86 const weekFile = SEALED.at(-1);87 91-/** What the parser's sealed check prints as it fails. */88 const PARSER_STDOUT = `(fail) parser > ${weekFile?.test}\n`;89 90 const PARSER_STDERR =91 "AssertionError: expected Week(54) to be undefined at week-54.test.ts:3\n";35 unmodified lines127 run,128 },129 });130 135-/** The fake, with the parser's sealed check failing. */131 const parserFails = (options: FakeOptions = {}) =>132 fakeChecker({133 commands: new Map([134 [7 unmodified lines142 const sealedCommands: ReadonlySet<string> = new Set(143 SEALED.map(({ command }) => command)144 );145 151-/**152- * Whether `call` writes the sealed files or readies their place: a file153- * written, or a command that names a path in the work tree (no lane or154- * sealed check does; each runs in it).155- */146 const writesSealed = (call: Call) =>147 call.kind === "writeFile" ||148 (call.kind === "exec" && call.argv.some((arg) => arg.startsWith(`${REPO}/`)));149 1 unmodified line151 call.kind === "exec" && call.argv[0] === "sh" && call.argv[1] === "-c"152 ? Option.fromUndefinedOr(call.argv[2])153 : Option.none();154 165-/** The recording as phases, each run of calls for one phase read as one. */155 const phaseOf = Match.type<Call>().pipe(156 Match.discriminatorsExhaustive("kind")({157 allow: ({ hosts }): readonly string[] =>158 hosts.length === 0 ? ["egressOff"] : ["setup"],33 unmodified lines192 calls193 .flatMap(phaseOf)194 .filter((phase, at, all) => at === 0 || all[at - 1] !== phase);195 207-/** Everything about the suite that must never leave the Checker. */196 const SECRETS = [197 ...SEALED.flatMap(({ path, test, text }) => [198 path,199 path.split("/").at(-1) ?? path,5 unmodified lines205 PARSER_STDERR.trim(),206 "Week(54)",207 ];208 221-/** The secrets `text` holds. */209 const leakedIn = (text: string) =>210 SECRETS.filter((secret) => text.includes(secret));211 225-/** What leaves the Checker besides its result: the logs it hands over and its log lines. */212 const leftBy = (calls: readonly Call[]) =>213 JSON.stringify(214 calls.filter((call) => call.kind === "report" || call.kind === "log")215 );216 231-/** One job with the sealed suite, the parser's check failing: what the fakes saw, and the outcome. */217 const sealedJob = Effect.gen(function* () {218 const fake = parserFails();219 220 const outcome = yield* Effect.exit(9 unmodified lines230 });231 232 const LINT_COUNT = "oxlint --format json";233 249-/** Public lanes that print what they found: `unit`, and a count lane. */234 const printing = () =>235 fakeChecker({236 commands: new Map([237 [UNIT, printedBeside],238 [LINT_COUNT, printedBeside],239 ]),240 });241 258-/** The job's wire with a count lane after `unit`. */242 const withCountLane = (sealed: Option.Option<HeldBackPart>): CheckWire => {243 const base = wireFor(sealed);244 245 return {11 unmodified lines257 },258 };259 };260 278-/** The outcome as it crosses the service binding, as JSON. */261 const serialized = (outcome: Exit.Exit<CheckRun, VerifierBlocked>) =>262 Schema.encodeEffect(CheckExit)(outcome).pipe(263 Effect.map((encoded) => JSON.stringify(encoded))264 );17 unmodified lines282 "report",283 "destroy",284 ]);285 304- // The order is the plan's, the sealed checks running in its `Run`.286 expect(287 phasesOf(calls)288 .slice(1, -1)289 .filter((phase) => phase !== "runHeldBack")8 unmodified lines298 ({ _tag }) => `${_tag.charAt(0).toLowerCase()}${_tag.slice(1)}`299 )300 );301 321- // Setup reached the registries and its own host, nothing else.302 expect(303 calls.find(304 (call) =>305 call.kind === "exec" && Option.contains(shellOf(call), SETUP)111 unmodified lines417 const ran = yield* check(withCountLane(Option.some(heldBack))).pipe(418 Effect.provide(fake.layer)419 );420 441- // Only how each lane ended leaves.421 expect(422 ran.lanes.map(({ lane, result }) => ({ lane, result }))423 ).toStrictEqual([424 { lane: "unit", result: "failed" },226 unmodified lines651 )652 );653 654 it("takes the held-back job the platform reads from the layer as it is", () => {676- // `ProjectApi.heldBackJob`'s job is the `CheckJob`'s held-back part.655 expectTypeOf<HeldBackJob>().toEqualTypeOf<HeldBackPart>();656 });657 658 it.effect(31 unmodified linesmodified:apps/sandbox/test/lander.fixtures.ts+1 added-39 removed
44 unmodified lines45 46 /** The token every remote carries: no command line, result or log may show it. */47 export const secret = "art_v1_0123456789abcdef0123456789abcdef01234567";48 49-/** A path in this repo, from the sandbox's test folder. */49 export const inRepo = (path: string) =>50 new URL(`../../../${path}`, import.meta.url).pathname;51 53-/**54- * The sdk a config folder's imports resolve to: this repo's own, where the55- * image keeps its copy under `/opt/sdk` (its entry, and the packages its own56- * imports resolve in).57- */52 export const sdk = {53 entry: inRepo("packages/sdk/src/index.ts"),54 modules: inRepo("packages/sdk/node_modules"),55 };56 63-/** What a file holds after a commit, or `null` for a file the commit deletes. */57 export type Files = Readonly<Record<string, string | null>>;58 66-/** The message of a landing that credits dora as asker and bob as answerer. */59 export const message = formatLanding({60 assisted: [],61 credits: [62 { handle: dora, role: "Asked-by" },23 unmodified lines86 tree: input.tree,87 verifier: "platform",88 });89 98-/** Every ref of a bare repo, with what it points at. */90 const refsOf = (repo: string) =>91 gitOk(repo, "for-each-ref", "--format=%(refname) %(objectname)");92 102-/** What a bare repo holds: its refs, and how many objects. */93 const stateOf = (repo: string) =>94 Effect.all({95 objects: gitOk(repo, "count-objects", "-v"),96 refs: refsOf(repo),97 });98 109-/** One revision's id in a bare repo, or `None` when it has none. */99 const revision = (repo: string, rev: string) =>100 Effect.map(101 git(repo, "rev-parse", "--verify", "--quiet", rev),102 ({ exitCode, stdout }) =>103 exitCode === 0 ? Option.some(stdout.trim()) : Option.none()104 );105 117-/** A repo's remote as a job carries it: its URL, and a token for it. */106 const remote = (url: string) => ({ token: Redacted.make(secret), url });107 120-/**121- * Two bare repos on disk, canonical and the claim's fork, and a working122- * clone the test makes commits in and pushes from, as people would. The123- * Lander under test works in its own folder (`layout.work`) and reaches the124- * repos only through the remotes it is handed.125- */108 export const world = Effect.gen(function* () {109 const fs = yield* FileSystem.FileSystem;110 const path = yield* Path.Path;111 const root = yield* fs.makeTempDirectoryScoped({ prefix: "lander-" });6 unmodified lines118 yield* gitOk(root, "init", "--quiet", "--bare", "-b", "main", forkDir);119 yield* gitOk(root, "init", "--quiet", "-b", "main", clone);120 yield* fs.makeDirectory(work);121 140- /** A commit of `files` over `parent` (or over nothing), made in the clone. */122 const commit = (123 parent: CommitSha | undefined,124 files: Files,125 subject: string19 unmodified lines145 146 return CommitSha.make(yield* gitOk(clone, "rev-parse", "HEAD"));147 });148 168- /** Sets `ref` in the bare repo `repo` to `sha`, as a person's push would. */149 const push = (repo: string, sha: CommitSha, ref = "refs/heads/main") =>150 gitOk(clone, "push", "--quiet", "--force", repo, `${sha}:${ref}`);151 172- /** A blob's id at `file` in `at`, read in the clone. */152 const blobAt = (at: CommitSha, file: string) =>153 Effect.map(gitOk(clone, "rev-parse", `${at}:${file}`), (blob) =>154 BlobSha.make(blob)155 );156 178- /** The tree git's own merge of `theirs` into `ours` makes, in the clone. */157 const mergedTree = (ours: CommitSha, theirs: CommitSha) =>158 Effect.gen(function* () {159 yield* gitOk(clone, "checkout", "--quiet", "--detach", ours);160 yield* gitOk(clone, "merge", "--quiet", "--no-edit", theirs);73 unmodified lines234 235 return { base, clash, head, main: LandedSha.make(main) };236 });237 260-/** The mirror ref a landing moves, after main. */238 export const landedRefName = `${Brand.refsPrefix}landed`;239 263-/**264- * The Lander's container, as local processes working in `work`: the sdk is265- * this repo's, and the file naming its version (which the image writes when266- * it is built) is written beside `work`.267- */240 export const layout = (work: string) =>241 Layer.effect(242 Layout,243 Effect.gen(function* () {10 unmodified lines254 };255 }).pipe(Effect.orDie)256 ).pipe(Layer.provide(NodeServices.layer));257 286-/** The Lander's container over local processes, its `Box` changed by `wrap` when a test needs to. */258 export const box = (259 work: string,260 wrap: (inner: Box["Service"]) => Box["Service"] = (inner) => inner261 ) =>3 unmodified lines265 );266 267 export const TestServices = NodeServices.layer;268 298-/** A file's path in the config folder. */269 export const config = (file: string) => `${Brand.configDir}/${file}`;270 301-/**302- * A config folder as maintainers write one: the project module (importing303- * the sdk by its published name, and a helper beside it), an ask file304- * (importing the sdk by its workspace name), the ask's check, which imports305- * a test runner the Lander never has, the visibility module, and the vouch306- * file.307- */271+/** The ask's check imports a test runner the Lander never has. */272 export const configFolder = {273 [config("asks/parse-iso.ask.ts")]: [274 'import { kinds, territory } from "@repo/sdk";',275 "",37 unmodified lines313 ].join("\n"),314 [config("vouched.td")]: "dora\nbob\n",315 } satisfies Files;316 353-/** datekit's first commit with `files` beside its code, on canonical `main`. */317 export const startedWith = (repos: World, files: Files) =>318 Effect.gen(function* () {319 const at = yield* repos.commit(undefined, { ...start, ...files }, "Start");320 1 unmodified line322 323 return LandedSha.make(at);324 });325 363-/** A bundle of datekit's config folder at `at`. */326 export const bundleWire = (repos: World, at: LandedSha) => ({327 job: { at, repo: project },328 main: repos.remote(repos.canonical),329 });modified:apps/sandbox/test/lander.test.ts+3 added-50 removed
48 unmodified lines49 world,50 } from "./lander.fixtures.ts";51 import type { Files, World } from "./lander.fixtures.ts";52 53-/** The merge of bob's answer at `head` onto datekit's `main`. */53 const mergeWire = (54 repos: World,55 job: {56 readonly base: CommitSha;5 unmodified lines62 job: { ...job, fork, repo: project },63 main: repos.remote(repos.canonical),64 });65 67-/** A land of bob's answer, merged again from `head`, onto datekit's `main`. */66 const landWire = (67 repos: World,68 job: {69 readonly base: CommitSha;15 unmodified lines85 },86 main: repos.remote(repos.canonical),87 });88 91-/** A commit in a bare repo as git shows it: who made it, on what, and its message. */89 const commitIn = (repo: string, sha: string) =>90 Effect.gen(function* () {91 const shown = yield* gitOk(92 repo,16 unmodified lines109 });110 111 const decodeNote = Schema.decodeEffect(Schema.fromJsonString(Verdict));112 116-/** Whether a command is the push that moves canonical `main`. */113 const pushesMain = (argv: readonly string[]) =>114 argv.includes("push") && argv.at(-1)?.endsWith(":refs/heads/main") === true;115 120-/**121- * The Lander's container, where `first` runs just before git pushes `main`:122- * someone else moving main between the Lander's fetch and its push.123- */116 const beforeMainIsPushed =117 (first: Effect.Effect<void>) =>118 (inner: Box["Service"]): Box["Service"] => ({119 ...inner,2 unmodified lines122 ? Effect.andThen(first, inner.exec(argv, options))123 : inner.exec(argv, options),124 });125 134-/** Someone else's commit on canonical `main`, as a push that moves it would leave it. */126 const movedBy = (repos: World, parent: CommitSha) =>127 Effect.gen(function* () {128 const other = yield* repos.commit(129 parent,5 unmodified lines135 136 return other;137 });138 148-/** One command the Lander handed its container: what it ran, and with what env. */139 interface Handed {140 readonly argv: readonly string[];141 readonly env: Readonly<Record<string, string>>;142 }143 154-/** The Lander's container, keeping every command it is handed in `handed`. */144 const recording =145 (handed: Handed[]) =>146 (inner: Box["Service"]): Box["Service"] => ({147 ...inner,3 unmodified lines151 inner.exec(argv, options)152 ),153 });154 166-/**167- * The Lander's container, where the push of the mirror ref is rejected, as168- * a receive-pack that refuses one ref would.169- */155 const mirrorRefused = (inner: Box["Service"]): Box["Service"] => ({156 ...inner,157 exec: (argv, options) =>158 argv.at(-1)?.endsWith(`:${landedRefName}`) === true4 unmodified lines163 })164 : inner.exec(argv, options),165 });166 182-/**183- * The Lander's container, where Artifacts is busy with another push to the184- * repo when the Lander pushes `main`: one side-band error packet and no185- * report, as a probe of Artifacts recorded it.186- */167+/** A busy Artifacts answers one side-band error packet and no report. */168 const busyOnMain = (inner: Box["Service"]): Box["Service"] => ({169 ...inner,170 exec: (argv, options) =>171 pushesMain(argv)5 unmodified lines177 })178 : inner.exec(argv, options),179 });180 200-/**201- * The Lander's container, where the remote refuses the push of `main` for a202- * reason of its own, and its message repeats the token it was sent.203- */181 const mainDeclined = (inner: Box["Service"]): Box["Service"] => ({182 ...inner,183 exec: (argv, options) =>184 pushesMain(argv)4 unmodified lines189 })190 : inner.exec(argv, options),191 });192 216-/**217- * The Lander's container, where a command that reaches a remote fails and218- * prints everything git was handed, its header too: a git whose trace shows219- * the credential it sent.220- */193 const tracing = (inner: Box["Service"]): Box["Service"] => ({194 ...inner,195 exec: (argv, options = {}) =>196 options.env?.GIT_CONFIG_VALUE_0 === undefined4 unmodified lines201 stdout: "",202 }),203 });204 233-/** A logger keeping every line, with its annotations, as JSON. */205 const keeping = (lines: string[]) =>206 Logger.layer([207 Logger.make((options) => {208 lines.push(JSON.stringify(Logger.formatStructured.log(options)));209 }),210 ]);211 241-/** A module's default export, as `import()` of a file gives it. */212 interface Imported {213 readonly default: unknown;214 }215 246-/**247- * `modules` written under a temp folder at their paths, and the one at248- * `file` imported: how the rules evaluator's `/bun` adapter reads a bundle.249- */216 const importedFrom = (217 modules: Readonly<Record<string, string>>,218 file: string219 ) =>13 unmodified lines233 234 return yield* Effect.promise((): Promise<Imported> => import(target));235 });236 271-// Both names a config folder imports the sdk by.237 const SDK_NAMES = [`"${Brand.cliPackage}/rules"`, '"@repo/sdk"'];238 274-/** A file's source with its imports of the sdk pointed at this repo's. */239 const pointedAtSdk = (source: string) => {240 let pointed = source;241 242 for (const name of SDK_NAMES) {2 unmodified lines245 246 return pointed;247 };248 285-/** The config folder as committed, its imports of the sdk pointed at this repo's. */249 const asCommitted = (files: Files) =>250 Object.fromEntries(251 Object.entries(files).flatMap(([file, source]) =>252 source === null ? [] : [[file, pointedAtSdk(source)] as const]253 )254 );255 293-/** A definition as data: what JSON keeps of it, as the evaluator reads it back. */256 const dataOf = ({ default: definition }: Imported) =>257 JSON.stringify(definition);258 297-/** What `admit` hears about a person who wants to claim (the sdk's `ClaimantFacts`). */259 interface Claimant {260 readonly handle: string;261 readonly kind: string;262 readonly record: number;263 readonly territory: string;264 readonly vouched: boolean;265 }266 306-// Where the sdk keeps a definition's function-valued rules.267 const FUNCTIONS = Symbol.for("@repo/sdk/Functions");268 309-/** A function-valued `admit` rule, as the sdk keeps one. */269 type Admit = (facts: Claimant) => boolean;270 271 const isAdmit = (rule: unknown): rule is Admit => Predicate.isFunction(rule);272 314-/** The project's `admit` rule, where the sdk keeps it, called with `facts`. */273 const admits = ({ default: definition }: Imported, facts: Claimant) => {274 const functions = Predicate.hasProperty(definition, FUNCTIONS)275 ? definition[FUNCTIONS]276 : undefined;623 unmodified lines900 );901 });902 });903 946-/** The root manifest's catalog: the versions every workspace shares. */904 const RootManifest = Schema.fromJsonString(905 Schema.Struct({906 workspaces: Schema.Struct({907 catalog: Schema.Struct({ effect: Schema.String }),21 unmodified lines929 ).toBe(manifest.workspaces.catalog.effect);930 }).pipe(Effect.provide(TestServices))931 );932 976- // Live on dev-oscabriel: the land image ended on debian's own977- // `bash`, which exits at once with no stdin, so the container stopped and978- // the first `exec` of every job was killed (exit 137).933+ // A bare `bash` entrypoint exits at once with no stdin, which stops the934+ // container and kills the first `exec` of every job (exit 137).935 it.effect.each(["check", "land"])(936 "keeps the %s container up until its Durable Object destroys it, since every command runs through exec",937 (image) =>938 Effect.gen(function* () {94 unmodified lines1033 ).toStrictEqual([]);1034 });1035 });1036 1081-/** A merge whose remotes no command in these tests reaches. */1037 const idleMerge = {1038 fork: {1039 token: Redacted.make(secret),1040 url: "https://artifacts.invalid/datekit--parse-iso--bob.git",146 unmodified lines1187 yield* Effect.promise(() => lander.merge(wire))1188 );1189 1190 expect(merged).toStrictEqual(Exit.fail(new VerifierBlocked({})));1236- // A whole vCPU (live on dev-oscabriel: on the default `lite`,1237- // 1/16 vCPU, one landing took 32 s and a config bundle 20 s).1191 expect(started).toStrictEqual([1192 { enableInternet: true, image: "land-image", instance: "standard-2" },1193 ]);1194 })2 unmodified linesmodified:apps/sandbox/test/local-box.ts-8 removed
11 unmodified lines12 (operation: BoxFailed["operation"]) =>13 (cause: { readonly message: string }) =>14 new BoxFailed({ operation, reason: cause.message });15 16-/**17- * `Box` over local processes, for tests: the Lander's git script runs here18- * as it runs in its container, against bare repos on disk. A command gets19- * only the env it is given (no variable of this machine's leaks in, so a20- * command that needs `PATH` is handed one), no stdin, and its time limit.21- * A file is written as the Sandbox SDK's `Files` writes one: into a folder22- * that must already be there.23- */16 export const LocalBox: Layer.Layer<Box> = Layer.effect(17 Box,18 Effect.gen(function* () {19 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;47 unmodified linesmodified:apps/sandbox/test/smoke.test.ts-5 removed
21 unmodified lines22 token: Redacted.make(`token-for-${name}`),23 url: `https://artifacts.invalid/${name}.git`,24 });25 26-/** The sandbox's entrypoint as the platform's service binding reaches it. */26 const sandbox = new Sandbox(untouchable("ctx"), fakeEnv());27 29-/** A stub's outcome: a typed failure, not a defect. */28 const failureOf = Exit.findErrorOption;29 30 describe("the sandbox Worker's main module", () => {33- // Live on dev-oscabriel: `ctx.exports` holds a loopback only for an34- // export of the main module, and every check was blocked with "worker.ts35- // does not export the outbound gateways".31 it("exports the Checker's outbound gateways, so ctx.exports holds them", () => {32 expect({33 CloneGateway: ExportedClone,34 EgressGateway: ExportedEgress,32 unmodified linesmodified:apps/sandbox/test/workers-shim.ts-7 removed
1-/**2- * `cloudflare:workers` for tests in Node. `vitest.config.ts` aliases the3- * module here, for this Worker's modules and the Sandbox SDK's: 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;21 unmodified linesmodified:apps/sandbox/vitest.config.ts+2 added-4 removed
1 import { preset } from "@repo/config/vitest";2 import { defineConfig, mergeConfig } from "vitest/config";3 4-// Worker modules import `cloudflare:workers`, which only workerd serves; in5-// Node it resolves to a shim. The Sandbox SDK imports it too, so vitest6-// bundles the SDK (`inline`) for the alias to reach it. An alias resolves to7-// a file, not a folder.4+// `cloudflare:workers` only exists in workerd; the SDK is inlined so the5+// alias reaches its import too.6 export default mergeConfig(7 preset,8 defineConfig({9 resolve: {8 unmodified lines