Skip to content
Myr

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

29 files+88 added−1090 removed

modified:apps/sandbox/src/box/sdk.ts+1 added-17 removed
modified:apps/sandbox/src/checker/logs/worker.ts-7 removed
modified: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.3import type { CheckJob, EnvProxy } from "@repo/checks/check-runner";4import { Array, Option, Result } from "effect";56import { CLONE_HOST } from "./network.ts";7import type { EnvRoute, EnvSwap } from "./network.ts";819/** A rule's host the Checker does not intercept, and why. */9export interface Skipped {10 readonly host: string;11 readonly reason: string;12}1325/** The job's env route, if it has one, and every host it leaves out. */14export interface EnvPlan {15 readonly route: Option.Option<EnvRoute>;16 readonly skipped: readonly Skipped[];17}1819const HTTPS = "https://";2033/**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. */22const MAX_PROXY_HOSTS = 60;2324const TOO_MANY = `the container intercepts at most ${MAX_PROXY_HOSTS} proxy hosts beside the clone route and the catch-all`;2542/**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 */26const interceptHost = (host: string): Result.Result<string, string> => {27 const written = host.trim().toLowerCase();2829 if (written.startsWith("http://")) {
20 unmodified lines
5051 return Result.succeed(bare);52};5377/**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 */54const swapsOf = (55 job: CheckJob,56 rules: readonly EnvProxy[]57): readonly EnvSwap[] => {
11 unmodified lines
69 : [{ key, placeholder: rule.placeholder, value }];70 });71};72102/**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 */73export const envPlanOf = (job: CheckJob): EnvPlan => {74 if (job.heldBack !== undefined) {75 return {76 route: Option.none(),
35 unmodified lines
modified:apps/sandbox/src/checker/logs.ts-12 removed
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 */1import type { EnvProxy } from "@repo/checks/check-runner";2import type { EnvKey } from "@repo/protocol/ids";3import { Context } from "effect";4import type { Effect, Redacted } from "effect";515/**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 */6export 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;1844/**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. */20export const allows = (allow: readonly string[], hostname: string): boolean => {21 const host = hostname.toLowerCase();2223 return allow.some((entry) =>
2 unmodified lines
26 : host === entry.toLowerCase()27 );28};2958/**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. */31export const CLONE_HOST = "repo.checker.internal";3265/**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 */33export const cloneUrlOf = (remote: string): string =>34 `https://${CLONE_HOST}${new URL(remote).pathname}`;3572/**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 */36export interface CloneRoute {37 readonly host: string;38 readonly remote: string;39 readonly token: Redacted.Redacted;40}4183/** A value the env gateway may swap in, with the placeholder it stands for. */42export interface EnvSwap {43 readonly key: EnvKey;44 readonly placeholder: string;45 readonly value: Redacted.Redacted;46}4790/**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. */49export interface EnvRoute {50 readonly hosts: readonly string[];51 readonly rules: readonly EnvProxy[];52 readonly values: readonly EnvSwap[];
1 unmodified line
5455export 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).4import { CheckAt, evidenceFrom } from "@repo/checks/check-runner";5import type {6 CheckRun,7 EnvPlaceholder,
28 unmodified lines
36 REGISTRIES,37} from "./network.ts";38import { Snapshots } from "./snapshots.ts";3963/** Where the job's tree is checked out, and every command runs. */40export const REPO = "/workspace/repo";4166/**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. */43const CA = "/etc/cloudflare/certs/cloudflare-containers-ca.crt";4445const TRUST = {46 CARGO_HTTP_CAINFO: CA,
4 unmodified lines
51 REQUESTS_CA_BUNDLE: CA,52 SSL_CERT_FILE: CA,53};5482/**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. */56const PATH = [57 `${REPO}/node_modules/.bin`,58 "/usr/local/sbin",59 "/usr/local/bin",
2 unmodified lines
62 "/sbin",63 "/bin",64].join(":");6596/**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. */67const ENV = {68 ...TRUST,69 CI: "1",70 // corepack fetches pnpm or Yarn during setup without asking first.
6 unmodified lines
77 NO_COLOR: "1",78 PATH,79};80114/**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. */82const commandEnv = (placeholders: readonly EnvPlaceholder[]) => ({83 ...Object.fromEntries(84 placeholders.map(({ key, placeholder }) => [key, placeholder])85 ),86 ...ENV,87});88128/** The identity of the commit a checked tree is checked out as. */89const GIT_ENV = {90 ...ENV,91 GIT_AUTHOR_DATE: "2026-10-06T12:00:00Z",92 GIT_AUTHOR_EMAIL: "checker@example.com",
2 unmodified lines
95 GIT_COMMITTER_EMAIL: "checker@example.com",96 GIT_COMMITTER_NAME: "Checker",97};98139/** The files whose contents decide what setup installs. */99const LOCKFILES = [100 "bun.lock",101 "bun.lockb",102 "package-lock.json",
9 unmodified lines
112];113114const CLONE_LIMIT = Duration.minutes(5);115157/** Making room for the sealed files is quick; it never waits on the network. */116const ROOM_LIMIT = Duration.minutes(1);117118const SETUP_LIMIT = Duration.minutes(15);119162/**163 * A lane with no time limit of its own gets ten minutes, as `/local` gives;164 * so does each sealed check.165 */120const LANE_LIMIT = Duration.minutes(10);121122const timedOut: RunExit = { code: -1, stderr: "", stdout: "", timedOut: true };123170/** Hosts a failed setup's output names: in URLs and in resolver errors. */124const 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];129177/** The hosts `text` names that `allowed` does not let out. */130const refusedIn = (text: string, allowed: readonly string[]) => [131 ...new Set(132 HOSTS_IN_OUTPUT.flatMap((pattern) =>133 [...text.matchAll(pattern)].flatMap(
24 unmodified lines
158 Effect.annotateLogs(annotations),159 Effect.andThen(Effect.fail(new VerifierBlocked({})))160 );161210/**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 */162interface LaneRan {163 readonly result: LaneResult;164 readonly evidence: Option.Option<LaneEvidence>;165 readonly output: Option.Option<LaneOutput>;166}167220/** Every phase's log so far, handed to `CheckLogs` when the check ends. */168type Kept = Ref.Ref<readonly PhaseLog[]>;169223/** Adds `log`'s text to the log of its phase and name, starting it if new. */170const 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 lines
177 )178 : [...logs, log]179 );180235/** Where a command's output goes: into its phase's log, or nowhere. */181type Recorder = (text: string) => Effect.Effect<void>;182238/** Into the log of `log`'s phase and name. */183const keeping =184 (kept: Kept, log: Omit<PhaseLog, "text">): Recorder =>185 (text) =>186 keep(kept, { ...log, text });187244/** Nowhere: the command ran beside the sealed files. */188const dropping: Recorder = () => Effect.void;189247/**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. */191const exec = (192 record: Recorder,193 argv: readonly [string, ...string[]],194 options: ExecOptions,
13 unmodified lines
208 )209 )210 );211275/** One git command of the checkout, which must succeed: its output. */212const git = (kept: Kept, ...args: readonly string[]) =>213 exec(214 keeping(kept, { name: "clone", phase: "clone" }),215 ["git", ...args],
19 unmodified lines
235 })236 )237 );238303/**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. */240const checkout = (kept: Kept, url: string, at: CheckAt) =>241 Effect.gen(function* () {242 const fetch = (refspec: string) =>243 git(
26 unmodified lines
270 yield* git(kept, "-C", REPO, "checkout", "-q", "--force", "--detach", head);271 yield* git(kept, "-C", REPO, "clean", "-q", "-ffd");272 });273343/** What the phases share for one job. */274interface 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}283284/** A snapshot is its project's own: two projects with one lockfile never share one. */285const snapshotKeyOf = ({ wire }: Job, key: string) =>286 `${wire.job.project}:${key}`;287363/**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 */288const setup = (289 job: Job,290 command: string,291 egress: readonly string[],
59 unmodified lines
351 phase: "setup",352 });353 });354437/**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. */356const snapshot = (job: Job, key: string) =>357 Effect.gen(function* () {358 const snapshots = yield* Snapshots;359 const { at, project, repo } = job.wire.job;
21 unmodified lines
381 )382 );383 });384473/**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. */386const 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 lines
440 })441 );442 });443540/**541 * Whether a sealed file's path stays inside the checked tree: relative,542 * with no empty, `.` or `..` segment.543 */444const inTree = (path: string) =>445 !path.startsWith("/") &&446 path447 .split("/")448 .every((segment) => segment !== "" && segment !== "." && segment !== "..");449550/**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 `--`. */451const ROOM = [452 'while [ "$1" != -- ]; do',453 ' if [ -L "$1" ] || { [ -e "$1" ] && [ ! -d "$1" ]; }; then',454 ' rm -f -- "$1" || exit 1',
4 unmodified lines
459 "shift",460 'rm -rf -- "$@"',461].join("\n");462569/** Every folder `path` sits in under `root`, shallowest first. */463const foldersAbove = (root: string, path: string) => {464 const folders = path.split("/").slice(0, -1);465466 return folders.map(467 (_, depth) => `${root}/${folders.slice(0, depth + 1).join("/")}`468 );469};470578/**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. */472export const roomFor = (473 root: string,474 paths: readonly string[]475): readonly [string, ...string[]] => [
9 unmodified lines
485/** The sealed files are not all in the work tree: nothing logged says which. */486const unwritten = () =>487 blocked("the sealed files were not written", { phase: "WriteHeldBack" });488604/**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. */490const 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 lines
522 { discard: true }523 );524 });525649/**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. */527const runSealed = (job: Job, { area, command }: HeldBackCheck) =>528 exec(529 dropping,530 ["sh", "-c", command],
14 unmodified lines
545 Effect.succeed<HeldBackExit>({ area, code: -1, timedOut: false })546 )547 );548678/**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 */549const openEnvRoute = (wire: CheckWire) =>550 Effect.gen(function* () {551 const network = yield* Network;552 const { route, skipped } = envPlanOf(wire.job);
11 unmodified lines
564 yield* network.routeEnv(route.value);565 }566 });567702/** The phases, from the clone to the last lane, with the logs kept as they go. */568const phases = (wire: CheckWire, run: RunBlock, kept: Kept) =>569 Effect.gen(function* () {570 const network = yield* Network;571 const { clone } = wire;572708 // The job's sealed suite, if it has one.573 const heldBack = Option.fromNullishOr(wire.job.heldBack);574575 const job: Job = {576 env: commandEnv(wire.job.placeholders),
24 unmodified lines
601 placeholders: wire.job.placeholders.map(({ key }) => key),602 run,603 });604741 // 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;606607 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 lines
631 ),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 lines
652 ran: ran.flat(),653 };654 });655797/**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 */656export const check = (657 wire: CheckWire658): Effect.Effect<659 CheckRun,
26 unmodified lines
modified: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.5import {6 Context,7 Effect,8 Layer,
9 unmodified lines
18import { Network } from "./network.ts";19import type { CloneRoute, EnvRoute } from "./network.ts";20import { Snapshots } from "./snapshots.ts";2140/**41 * The outbound entrypoints' loopbacks: `ctx.exports` holds one per export of42 * the Worker's main module.43 */22export 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}2952/** Whether `ctx.exports` holds every gateway: `worker.ts` must export them. */30export const hasGateways = (31 exports: Cloudflare.Exports32): exports is Cloudflare.Exports & Gateways =>33 Predicate.hasProperty(exports, "CloneGateway") &&
2 unmodified lines
36 Predicate.isFunction(exports.EgressGateway) &&37 Predicate.hasProperty(exports, "EnvGateway") &&38 Predicate.isFunction(exports.EnvGateway);3963/** Where snapshot ids are kept, by key, for every check of one project. */40export 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}4570/** What the container's intercepts say now. */46interface 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}5389/** The name every setup snapshot carries; its index key tells them apart. */54const SNAPSHOT_NAME = "check-setup";5592/** What a restored container runs while commands run beside it. */56const IDLE = ["sleep", "infinity"];5758const failed = (reason: string) => (cause: unknown) =>59 new BoxFailed({ operation: "exec", reason: `${reason}: ${String(cause)}` });6098/**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. */62const intercept = (register: () => Promise<void>) => Effect.promise(register);63104/**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. */65const envProps = ({ rules, values }: EnvRoute): EnvGatewayProps => ({66 rules,67 values: values.map(({ key, placeholder, value }) => ({68 key,
1 unmodified line
70 value: Redacted.value(value),71 })),72});73117/** The hosts the env route has opened, and the gateway they go to. */74interface Opened {75 readonly hosts: readonly string[];76 readonly to: Fetcher;77}78123/**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. */80const install = (81 container: Container,82 gateways: Gateways,83 { allow, clone, cloned, env, proxied }: Routes
42 unmodified lines
126 yield* intercept(() => container.interceptOutboundHttps("*", egress));127 yield* intercept(() => container.interceptAllOutboundHttp(egress));128 });129180/** The restored container answers a command, or the snapshot is gone. */130const probe = (container: Container) =>131 Effect.tryPromise({132 catch: failed("the restored container did not answer"),133 try: () => container.exec(["true"]),
13 unmodified lines
147 })148 )149 );150202/** How the Checker's container runs: the hosts its env route may open, and its size. */151export 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}156157export const SdkChecker = {
105 unmodified lines
modified:apps/sandbox/src/checker/snapshots.ts+1 added-15 removed
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.4import { Brand } from "@repo/brand";5import { notesRef } from "@repo/git/notes";6import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";7import type { GitIdentity } from "@repo/git/trailers";
69 unmodified lines
77 writeTree,78} from "./script.ts";79import type { GitStep, RemoteName, Signature } from "./script.ts";8087/** Where the Lander's container keeps things, and finds its tools. */81export 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}90105/** The land image's layout (`images/land.Dockerfile`); tests point it at a temp folder. */91export const Layout = Context.Reference<LanderLayout>("sandbox/lander/Layout", {92 defaultValue: () => ({93 path: "/usr/local/bin:/usr/bin:/bin",94 sdk: {
4 unmodified lines
99 work: "/workspace",100 }),101});102118/** The tokens a job carries, by the remote each opens. */103type Tokens = Partial<Record<RemoteName, Redacted.Redacted>>;104105// 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 lines
113const REMOTE_MS = 120_000;114115const LOCAL_MS = 30_000;116133/** `text` with every token taken out, and only its end kept. */117const scrubbed = (text: string, tokens: Tokens) => {118 let kept = text;119120 for (const token of Object.values(tokens)) {
6 unmodified lines
127128 return kept.trim().slice(-STDERR_KEPT);129};130148/** git's subcommand in a step, for logs: the first argument after its options. */131const subcommandOf = (step: GitStep) =>132 step.argv.find(133 (argument, index) =>134 index > 0 && !argument.startsWith("-") && step.argv[index - 1] !== "-c"135 ) ?? "git";136155/**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 */137const 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 );142165/** Everything a command printed, for a log: its exit, then stdout and stderr. */143const printed = (ran: Executed) =>144 `exit ${ran.exitCode}: ${ran.stdout}\n${ran.stderr}`;145169/** git's env for every step: no config but the step's own, no prompt, English. */146const baseEnv = (layout: LanderLayout) => ({147 GIT_CONFIG_GLOBAL: "/dev/null",148 GIT_CONFIG_NOSYSTEM: "1",149 GIT_TERMINAL_PROMPT: "0",
1 unmodified line
151 LC_ALL: "C",152 PATH: layout.path,153});154179/** The header that carries a remote's token, as git reads config from env. */155const 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});160186/** How one job runs its steps, and how it says one blocked it. */161interface 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}169201/** The steps of one job, which carries `tokens`. */170const runner = (tokens: Tokens) => {171 const blocked = (step: GitStep, why: string) =>172 blockedBy(subcommandOf(step), why, tokens);173
46 unmodified lines
220);221222const signed = (who: GitIdentity, at: number): Signature => ({ ...who, at });223256/** A scratch file the job writes, in the work folder. */224const scratch = (name: string) =>225 Effect.map(Layout, ({ work }) => `${work}/scratch/${name}`);226260/**261 * The Lander's copy of the job's repo, and the scratch folders its files go262 * in, made if they are missing.263 */227const prepared = (job: Job) =>228 Effect.gen(function* () {229 const { work } = yield* Layout;230231 yield* job.run(folders([`${work}/scratch/compose`]));232 yield* job.run(initCopy(job.repo));233 });234272/** `text` written to `file` in the container; a file it would not take blocks the job. */235const 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 );241280/** Writes `text` to a scratch file for git to read: a message, a note. */242const written = (name: string, text: string) =>243 Effect.gen(function* () {244 const file = yield* scratch(name);245
1 unmodified line
247248 return file;249 });250290/** What one job runs its steps with: its canonical repo, that repo's URL, and its steps. */251interface Job extends Steps {252 readonly repo: RepoName;253 readonly url: string;254}255296/** `rev` in the Lander's copy, if it names something there. */256const 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 );260302/** `rev`'s id in the Lander's copy, which a step before made sure is there. */261const idOf = (job: Job, rev: string) =>262 resolved(job, rev).pipe(263 Effect.flatMap(264 Option.match({
3 unmodified lines
268 })269 )270 );271314/** A commit of `tree` on `parents`, written to the copy: its id. */272const committed = (273 job: Job,274 commit: {275 readonly tree: string;
18 unmodified lines
294295 return CommitSha.make(ran.stdout.trim());296 });297341/**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. */299const keptForChecks = (300 job: Job,301 sides: {302 readonly head: CommitSha;
26 unmodified lines
329 ? commit330 : yield* job.blocked(push, printed(ran));331 });332381/**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 */333export const merge = (wire: typeof MergeWire.Type) =>334 Effect.gen(function* () {335 const { job } = wire;336
34 unmodified lines
371372 return { changes, tree: merged.tree };373 });374428/** A path's folders and file name; one that cannot name a file is a defect upstream. */375const 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`);379434/**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. */381const composed = (382 job: Job,383 main: string,384 files: readonly { readonly path: string; readonly content: string }[]
43 unmodified lines
428 (yield* job.run(writeTree(job.repo, index))).stdout.trim()429 );430 });431490/** The tree a land rebuilds, written to the copy where it is new. */432const rebuilt = (433 job: Job,434 wire: typeof LandWire.Type435): Effect.Effect<TreeSha, StaleBase | VerifierBlocked, Box> =>
30 unmodified lines
466 }),467 }468 );469529/** The mirror of canonical `main` (ADR 0005). */470const landedRef = `${Brand.refsPrefix}landed`;471532/** Where the copy keeps canonical's notes ref. */472const notesCopyOf = notesRef.replace("refs/notes/", `${notesCopy}/`);473474const encodeNote = Schema.encodeEffect(Schema.fromJsonString(Verdict));475537/** Whether the notes commit `notes` (in the copy) holds a note on `landing`. */476const holdsNote = (job: Job, notes: string, landing: CommitSha) =>477 Effect.map(478 job.run(objectType(job.repo, `${notes}:${landing}`)),479 ({ exitCode }) => exitCode === 0480 );481544/**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 */482const note = (job: Job, landing: CommitSha, verdict: Verdict, at: number) =>483 Effect.gen(function* () {484 const parent = yield* resolved(job, notesCopyOf);485
37 unmodified lines
523 ? commit524 : yield* job.blocked(step, printed(ran));525 });526595/** A piece of bookkeeping a landing may leave pending. */527type Bookkeeping = (typeof Landed.Type)["pending"][number];528598/** One piece of bookkeeping: `None` once written, its name when it was not. */529const 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 lines
536 )537 )538 );539610/**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. */541const settle = (542 job: Job,543 wire: typeof LandWire.Type,544 landing: CommitSha,
31 unmodified lines
576const requestIdOf = (text: string) =>577 parseTrailers(text).find(({ key }) => key.toLowerCase() === "request-id")578 ?.value;579656/** The base a stale land names: the answer's own, or the main it was built on. */580const 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 });586664/**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`. */588const 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))).stdout
18 unmodified lines
610 main: CommitSha.make(tip),611 });612 });613696/**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. */615export const land = (wire: typeof LandWire.Type) =>616 Effect.gen(function* () {617 const { job: landing } = wire;618
61 unmodified lines
680681 return yield* job.blocked(script.main, printed(ran));682 });683771// What a composed commit says: the platform made it, for a check, off main.684const COMPOSE_MESSAGE = "Compose files onto main for a check\n";685774/**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 */686export const compose = (wire: typeof ComposeWire.Type) =>687 Effect.gen(function* () {688 const job: Job = {689 ...(yield* runner({ main: wire.main.token })),
49 unmodified lines
739740 return { commit, tree };741 });742837/** Whether `rev` names a commit in the Lander's copy. */743const hasCommit = (job: Job, rev: string) =>744 Effect.map(745 job.run(objectType(job.repo, `${rev}^{commit}`)),746 ({ exitCode }) => exitCode === 0747 );748844/** `commit` in the Lander's copy, fetched by its id if fetching main did not bring it. */749const 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 lines
759 `canonical has no commit ${commit}`760 );761 });762859/**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. */764const built = (765 job: Job,766 files: readonly {767 readonly path: string;
44 unmodified lines
812 )813 );814 });815918/**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. */817export const bundleRules = (wire: typeof BundleWire.Type) =>818 Effect.gen(function* () {819 const { sdk } = yield* Layout;820
46 unmodified lines
modified: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.4import { Brand } from "@repo/brand";5import type { LandJob, Merged, MergeJob } from "@repo/project/lander/wire";6import { BlobSha, CommitSha, RepoPath, TreeSha } from "@repo/protocol/ids";7import type { RepoName } from "@repo/protocol/ids";
1 unmodified line
9import type { Types } from "effect";1011import type { Executed } from "../box.ts";1226/** Which of a job's remotes a step reaches. */13export type RemoteName = "main" | "fork";1429/** How a step's exit reads. */15export 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";2240/** One command: git, or a tool beside it in the image (`mkdir`, `bun`, `cat`). */23export 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}3050/** Where canonical `main` is kept in the Lander's copy. */31export const mainCopy = "refs/lander/main";3253/** Where a fork's branches are kept in the Lander's copy. */33export const forkCopy = (fork: RepoName) => `refs/lander/forks/${fork}`;3456/** Where canonical's notes refs are kept in the Lander's copy. */35export const notesCopy = "refs/lander/notes";3659/** Where a compose ref already on canonical is kept in the Lander's copy. */37export const composeCopy = "refs/lander/compose";3862/** The canonical branch a landing moves. */39export const mainRef = "refs/heads/main";4065/**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. */42export const mergeRef = (tree: string) => `${Brand.refsPrefix}merge/${tree}`;4344// 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 lines
55 "-c",56 "maintenance.auto=false",57] as const;5887/**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`. */60export const copyOf = (repo: RepoName) => `repos/${repo}.git`;6162const git = (63 repo: RepoName,
6 unmodified lines
70];7172const fetch = ["fetch", "--quiet", "--no-tags", "--no-write-fetch-head"];73107/**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. */75export const folders = (76 paths: Array.NonEmptyReadonlyArray<string>77): GitStep => ({ argv: ["mkdir", "-p", "--", ...paths], expect: "ok" });78115/** A folder and everything in it gone, if it was there. */79export const removeFolder = (folder: string): GitStep => ({80 argv: ["rm", "-rf", "--", folder],81 expect: "ok",82});83121/** The Lander's copy of `repo`, made if it is missing; making it again changes nothing. */84export const initCopy = (repo: RepoName): GitStep => ({85 argv: ["git", ...safety, "init", "--quiet", "--bare", copyOf(repo)],86 expect: "ok",87});88127/**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 */89export const fetchMain = (90 repo: RepoName,91 url: string,92 options: { readonly notes?: boolean } = {}
9 unmodified lines
102 expect: "ok",103 remote: "main",104});105148/** Every branch of the answer's fork, fetched into the copy. */106export const fetchFork = (107 repo: RepoName,108 fork: RepoName,109 url: string
2 unmodified lines
112 expect: "ok",113 remote: "fork",114});115159/**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. */117export const mergeTree = (118 repo: RepoName,119 sides: { readonly base: string; readonly main: string; readonly head: string }120): GitStep => ({
10 unmodified lines
131 ),132 expect: "merge",133});134182/** What changed from `from` to `to`, path by path, with blob ids. */135export const diffTree = (136 repo: RepoName,137 from: string,138 to: string
1 unmodified line
140 argv: git(repo, "diff-tree", "-r", "-z", "--no-renames", from, to),141 expect: "ok",142});143192/** A merge as git runs it, in order. */144export 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}150201/** A merge's fetches and merge; it writes nothing to canonical. */151export const mergeScript = (152 job: typeof MergeJob.Type,153 remotes: { readonly main: string; readonly fork: string }154): MergeScript => ({
5 unmodified lines
160 ],161 merge: mergeTree(job.repo, job),162});163215/**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`. */165export 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 lines
186 expect: "push",187 remote: update.remote ?? "main",188});189246/** The two pushes of a landing. */190export 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}194254/**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 */195export const landScript = (196 job: Pick<typeof LandJob.Type, "repo">,197 url: string,198 landing: CommitSha,
2 unmodified lines
201 main: pushRef(job.repo, url, { ref: mainRef, to: landing }),202 mirror: pushRef(job.repo, url, { ref: mirror, to: landing }),203});204269/** One git identity at one moment, as git's env spells it. */205export interface Signature {206 readonly name: string;207 readonly email: string;208 /** Seconds since the epoch, in UTC. */209 readonly at: number;210}211277/** A commit of `tree` on `parents`, with its message from a file, as its people sign it. */212export const commitTree = (213 repo: RepoName,214 commit: {215 readonly tree: string;
21 unmodified lines
237 },238 expect: "ok",239});240307/** Whether `rev` names an object in the copy; it prints the object's type. */241export const objectType = (repo: RepoName, rev: string): GitStep => ({242 argv: git(repo, "cat-file", "-t", rev),243 expect: "probe",244});245313/** One revision's id in the copy. */246export const revParse = (repo: RepoName, rev: string): GitStep => ({247 argv: git(repo, "rev-parse", "--verify", "--quiet", rev),248 expect: "probe",249});
3 unmodified lines
253 argv: git(repo, "hash-object", "-w", "--no-filters", "--", file),254 expect: "ok",255});256325/** An index file loaded with `tree`, or emptied when there is none. */257export const readTree = (258 repo: RepoName,259 index: string,260 tree?: string
2 unmodified lines
263 env: { GIT_INDEX_FILE: index },264 expect: "ok",265});266336/** Blobs placed in an index file at their paths, with their modes. */267export const updateIndex = (268 repo: RepoName,269 index: string,270 entries: readonly {
14 unmodified lines
285 env: { GIT_INDEX_FILE: index },286 expect: "ok",287});288359/** The tree an index file holds, written to the copy. */289export const writeTree = (repo: RepoName, index: string): GitStep => ({290 argv: git(repo, "write-tree"),291 env: { GIT_INDEX_FILE: index },292 expect: "ok",293});294366/**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. */296export const checkoutIndex = (297 repo: RepoName,298 index: string,299 folder: string
12 unmodified lines
312 env: { GIT_INDEX_FILE: index },313 expect: "ok",314});315390/** The modes and ids of `paths` in `tree`, those that are there. */316export const lsTree = (317 repo: RepoName,318 tree: string,319 paths: readonly string[]
1 unmodified line
321 argv: git(repo, "ls-tree", "-z", "--full-tree", tree, "--", ...paths),322 expect: "ok",323});324400/** Every file under `folder` in `tree`, at any depth, with its mode and id. */325export const filesUnder = (326 repo: RepoName,327 tree: string,328 folder: string
1 unmodified line
330 argv: git(repo, "ls-tree", "-r", "-z", "--full-tree", tree, "--", folder),331 expect: "ok",332});333410/** A blob's bytes, printed. */334export const catBlob = (repo: RepoName, blob: string): GitStep => ({335 argv: git(repo, "cat-file", "blob", blob),336 expect: "ok",337});338416/** One commit fetched from canonical by its id, into the copy's objects. */339export const fetchCommit = (340 repo: RepoName,341 url: string,342 commit: string
2 unmodified lines
345 expect: "ok",346 remote: "main",347});348427/** The commits from `tip` back along first parents, at most `count`. */349export const firstParents = (350 repo: RepoName,351 tip: string,352 count: number
9 unmodified lines
362 ),363 expect: "ok",364});365445/** A ref's id on a remote, if it has the ref. */366export const lsRemote = (367 repo: RepoName,368 url: string,369 ref: string
2 unmodified lines
372 expect: "ok",373 remote: "main",374});375456/** A ref fetched from canonical into `into` in the copy. */376export const fetchRef = (377 repo: RepoName,378 url: string,379 ref: string,
3 unmodified lines
383 expect: "ok",384 remote: "main",385});386468// --------------------------------------------------------------- bundling469470// A module that runs: what the rules evaluator imports, and what a bundle inlines.387const SCRIPT = /\.[cm]?[jt]sx?$/u;388473// An ask file, as `@repo/rules` finds one: `<id>.ask.ts`, or its JavaScript.389const ASK_FILE = /\.ask\.[cm]?[jt]s$/u;390476/**477 * The config folder's project module, which a bundle names whether or not478 * the folder has one (`ConfigBundle.entry`).479 */391export const configEntry = `${Brand.configDir}/project.ts`;392482/** Whether a file in the config folder is code, which a bundle carries only inlined. */393export const isScript = (path: string) => SCRIPT.test(path);394485/** The config folder's visibility module: its layers and held-back checks. */395const visibilityEntry = `${Brand.configDir}/visibility.ts`;396488/**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 */397export 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 );404502/** Where bun writes an entry's bundle: its path, as JavaScript. */405export const bundledAs = (entry: string) => entry.replace(/\.[^./]*$/u, ".js");406505/**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. */408export const resolution = (sdk: string) =>409 `${JSON.stringify(410 {411 compilerOptions: {
3 unmodified lines
415 null,416 2417 )}\n`;418522/** A symlink at `link` to `target`. */419export const symlink = (target: string, link: string): GitStep => ({420 argv: ["ln", "-s", "--", target, link],421 expect: "ok",422});423528/**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. */425export const bundle = (input: {426 readonly root: string;427 readonly out: string;428 readonly tsconfig: string;
15 unmodified lines
444 ],445 expect: "ok",446});447557/** Every file under `folder`, by its path from there. */448export const listFiles = (folder: string): GitStep => ({449 argv: ["find", folder, "-type", "f", "-printf", "%P\\0"],450 expect: "ok",451});452563/** One file's bytes, printed. */453export const readFile = (file: string): GitStep => ({454 argv: ["cat", "--", file],455 expect: "ok",456});457569// ------------------------------------------------------------------ reading570458const fields = (text: string) => text.split("\0").filter((part) => part !== "");459573/** What `merge-tree` printed: the merged tree, and the paths that conflict, sorted. */460export const readMerge = (stdout: string) => {461 const [tree = "", ...conflicts] = fields(stdout);462463 return {
3 unmodified lines
467 tree: TreeSha.make(tree.trim()),468 };469};470585/** A change's status, as a merge reports it. */471type Status = (typeof Merged.Type)["changes"][number]["status"];472473/** A raw diff's status letter as a change's status; a type change is a modification. */474const statusOf = (letter: string): Status | undefined => {
19 unmodified lines
494495// An object id of zeros: no object, on the side of a change that has none.496const NO_OBJECT = /^0+$/u;497613// A raw diff line's head: both modes, both blob ids, and the status letter.498const RAW =499 /^:\d+ \d+ (?<before>[0-9a-f]+) (?<after>[0-9a-f]+) (?<letter>[A-Z])/u;500617/** One change as a merge reports it. */501type Changed = (typeof Merged.Type)["changes"][number];502620/**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. */504export 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 lines
525526 return [change];527 });528650/** One commit as `firstParents` prints it. */529export interface Logged {530 readonly sha: CommitSha;531 readonly parents: readonly CommitSha[];532 readonly message: string;533}534657/** What `firstParents` printed. */535export 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 lines
544 sha: CommitSha.make(sha),545 };546 });547671/** What `lsTree` printed: each path's mode and id. */548export const readEntries = (stdout: string) =>549 new Map(550 fields(stdout).map((line) => {551 const tab = line.indexOf("\t");
2 unmodified lines
554 return [line.slice(tab + 1), { mode, sha }] as const;555 })556 );557682/** What `listFiles` printed: each file's path. */558export const readFiles = (stdout: string) => fields(stdout);559685/** What `lsRemote` printed: the ref's id, when the remote has it. */560export const readRemoteRef = (stdout: string) => {561 const [line = ""] = stdout.split("\n");562 const [sha = ""] = line.split("\t");563564 return sha === "" ? undefined : CommitSha.make(sha);565};566693/** How a push came out. */567export 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";573574// 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 a
6 unmodified lines
582583// A porcelain line: the flag, `from:to`, and the summary.584const PORCELAIN = /^(?<flag>.)\t(?<refs>[^\t]*)\t(?<summary>.*)$/u;585716/** How the push of `ref` came out, from what git printed with `--porcelain`. */586export const readPush = (ran: Executed, ref: string): Pushed => {587 if (`${ran.stdout}\n${ran.stderr}`.includes(BUSY)) {588 return "busy";589 }
18 unmodified lines
modified: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 */1import { Context, Schema } from "effect";2import type { Array, Effect } from "effect";310/** The container would not run a command, take a file or answer at all. */4export class BoxFailed extends Schema.TaggedError<BoxFailed>()("BoxFailed", {5 operation: Schema.Literals(["exec", "writeFile"]),6 reason: Schema.String,7}) {}816/** How one command runs: where, with what env, and for how long at most. */9export interface ExecOptions {10 readonly cwd?: string;11 readonly env?: Readonly<Record<string, string>>;12 readonly timeoutMs?: number;13}1423/** What one command left: its exit code and its output, as text. */15export interface Executed {16 readonly exitCode: number;17 readonly stdout: string;18 readonly stderr: string;
10 unmodified lines
29 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.4import type { CheckRun } from "@repo/checks/check-runner";5import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";6import { keyOf } from "@repo/protocol/ids";7import { VerifierBlocked } from "@repo/protocol/refusal";
6 unmodified lines
14import { blocked, check } from "./checker/run.ts";15import { hasGateways, SdkChecker } from "./checker/sdk.ts";16import { answerJob } from "./job.ts";1725/** The run block's image a check runs in when it names none. */18const DEFAULT_IMAGE = "checker:default";1928/** That image's name in `wrangler.jsonc`, built from `images/check.Dockerfile`. */20const CHECK_IMAGE = "check";2131/**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. */23export const checkInstance = "standard-3";2443/** The Checker's Durable Object, which owns its container. */25export 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 }2950 /** 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 lines
100 );101 }102}103125/**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. */105export interface Checkers {106 readonly CHECKER: {107 readonly newUniqueId: () => DurableObjectId;108 readonly get: (id: DurableObjectId) => {
8 unmodified lines
117 };118 };119}120148/**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 */121export const runCheck = (122 env: Checkers,123 wire: typeof CheckWire.Encoded124): Promise<typeof CheckExit.Encoded> =>
15 unmodified lines
modified: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).4import type { EnvProxy } from "@repo/checks/check-runner";5import type { EnvKey } from "@repo/protocol/ids";6import { WorkerEntrypoint } from "cloudflare:workers";7import { Effect, Option, Order, Result, Stream } from "effect";89import { forward, refused, resent } from "./outbound.ts";1028/** A value the gateway may swap in, with the placeholder the process sees for it. */11export interface EnvSwapProps {12 readonly key: EnvKey;13 readonly placeholder: string;14 readonly value: string;15}1635/** One job's env route, as the gateway gets it: plain data, on the Worker's side. */17export interface EnvGatewayProps {18 readonly rules: readonly EnvProxy[];19 /** Empty unless the job runs landed code. */20 readonly values: readonly EnvSwapProps[];
17 unmodified lines
38 )}$`,39 "u"40 ).test(path);4161/** A rule's methods, written as one or a list (`GET, POST`); none allows any. */42const methodMatches = (methods: string, method: string) =>43 methods44 .split(",")45 .map((each) => each.trim().toUpperCase())
3 unmodified lines
49 hostMatches(rule.host, url.host) &&50 (rule.path === undefined || pathMatches(rule.path, url.pathname)) &&51 (rule.method === undefined || methodMatches(rule.method, method));5273/**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 */53type Swap = readonly [from: string, to: string];5479/**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 */55const swapsFor = (56 props: EnvGatewayProps,57 request: Request58): Result.Result<readonly Swap[], string> => {
44 unmodified lines
103 Order.flip(Order.Number),104 ([from]: Swap) => from.length105);106139/**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 */107const replaced = (text: string, pairs: readonly Swap[]) => {108 let done = text;109110 for (const [from, to] of pairs.toSorted(longestFirst)) {
2 unmodified lines
113114 return done;115};116154/** A copy of `headers` with each value's text replaced through `pairs`. */117const headersReplaced = (headers: Headers, pairs: readonly Swap[]) => {118 const copy = new Headers();119120 for (const [name, value] of headers) {
2 unmodified lines
123124 return copy;125};126165/** The request that goes on: the container's, its headers swapped. */127const sent = (request: Request, swaps: readonly Swap[]) =>128 resent(request.url, request, headersReplaced(request.headers, swaps));129169/** A body the gateway can read as text and scrub: text-like, and not compressed. */130const scrubbable = (headers: Headers) => {131 const type = headers.get("content-type")?.toLowerCase() ?? "";132 const encoding = headers.get("content-encoding")?.trim().toLowerCase() ?? "";133
5 unmodified lines
139 ))140 );141};142183/**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. */144const carried = (text: string, values: readonly string[]) =>145 Math.max(146 0,147 ...values.flatMap((value) =>
3 unmodified lines
151 )152 )153 );154199/**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 */155const scrubbedBody = (156 body: ReadableStream<unknown>,157 scrubs: readonly Swap[]158) => {
28 unmodified lines
187 Stream.toReadableStream()188 );189};190239/**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. */192const scrubbed = (response: Response, props: EnvGatewayProps): Response => {193 if (props.values.length === 0) {194 return response;195 }
21 unmodified lines
217 { headers, status: response.status, statusText: response.statusText }218 );219};220274/** What the gateway answers one request from the container with. */221const answer = (props: EnvGatewayProps, request: Request) =>222 Result.match(swapsFor(props, request), {223 onFailure: (reason) => Effect.succeed(refused(`${reason}\n`)),224 onSuccess: (swaps) =>
2 unmodified lines
227 (response) => scrubbed(response, props)228 ),229 });230285/**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 */231export 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 line
modified: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 */1import { Effect, Schema } from "effect";2import type { Exit } from "effect";34export const answerJob =
13 unmodified lines
18 )19 )20 );2129/**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 */22export 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 line
modified: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.3import {4 BundleExit,5 BundleWire,6 ComposeExit,
11 unmodified lines
18import { SdkBox } from "./box/sdk.ts";19import { answerJob } from "./job.ts";20import { bundleRules, compose, land, merge } from "./lander/run.ts";2131/** The image the Lander's container runs: `images.land` in `wrangler.jsonc`. */22export const landImage = "land";2334/**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 */24export const landerJobs = (25 box: Layer.Layer<Box>,26 turn: Semaphore.Semaphore27) => {
11 unmodified lines
39 merge: answerJob(MergeWire, MergeExit, (wire) => inBox(merge(wire))),40 };41};4258/**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. */44export const landInstance = "standard-2";4565/**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. */47export class Lander extends DurableObject<Env> {48 readonly #jobs: ReturnType<typeof landerJobs>;4950 constructor(ctx: DurableObjectState, env: Env) {
35 unmodified lines
86 return this.#jobs.bundleRules(wire);87 }88}89113/** The Lander's jobs as its Durable Object takes them over RPC. */90export type LanderJobs = Pick<91 Lander,92 "bundleRules" | "compose" | "land" | "merge"93>;94119/**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`.97export interface Landers {98 readonly LANDER: { readonly getByName: (name: string) => LanderJobs };99}100129/** The project's Lander: one per canonical repo, so one container per project. */101const landerOf = (102 env: Landers,103 wire: { readonly job: { readonly repo: string } }104) => env.LANDER.getByName(wire.job.repo);105135/** An answer's head merged onto canonical `main`, in the project's Lander. */106export const runMerge = (107 env: Landers,108 wire: typeof MergeWire.Encoded109): Promise<typeof MergeExit.Encoded> => landerOf(env, wire).merge(wire);110141/** A checked tree landed on canonical `main`, in the project's Lander. */111export const runLand = (112 env: Landers,113 wire: typeof LandWire.Encoded114): Promise<typeof LandExit.Encoded> => landerOf(env, wire).land(wire);115147/** A decider's files composed onto canonical `main`, on a compose ref. */116export const runCompose = (117 env: Landers,118 wire: typeof ComposeWire.Encoded119): Promise<typeof ComposeExit.Encoded> => landerOf(env, wire).compose(wire);120153/** The config folder at a landed commit, bundled for the rules evaluator. */121export 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.3import { WorkerEntrypoint } from "cloudflare:workers";4import { Option } from "effect";56import { allows, CLONE_HOST } from "./checker/network.ts";716/** One job's remote and the read token the platform minted for it alone. */8export interface CloneProps {9 readonly remote: string;10 readonly token: string;11}1222/** The hosts the container may reach right now; `[]` is none. */13export interface EgressProps {14 readonly allow: readonly string[];15}1627/** A 403 whose plain-text body says why; `text` ends with its own newline. */17export const refused = (text: string) =>18 new Response(text, {19 headers: { "content-type": "text/plain; charset=utf-8" },20 status: 403,21 });2234/**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. */24export 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" });2742/**43 * `request` as a new request to `url` with `headers`: its method, and its44 * body streamed through as it comes.45 */28export 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 lines
3738 return new Request(url, init);39};4059/**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. */42const cloneRequestFor = (43 request: Request,44 props: CloneProps45): Option.Option<Request> => {
21 unmodified lines
67 resent(`${remote.origin}${url.pathname}${url.search}`, request, headers)68 );69};7094/**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. */72export 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 lines
80 });81 }82}83113/**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 */84export class EgressGateway extends WorkerEntrypoint<Env, EgressProps> {85 override fetch(request: Request): Promise<Response> {86 const { hostname } = new URL(request.url);87
9 unmodified lines
modified: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 */1import type { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";2import type {3 BundleExit,4 BundleWire,
12 unmodified lines
17export { Checker } from "./checker.ts";1819export { Lander } from "./lander.ts";2028// 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.22export { CloneGateway, EgressGateway } from "./outbound.ts";2324export { EnvGateway } from "./env-gateway.ts";25
25 unmodified lines
modified:apps/sandbox/test/box-sdk.test.ts-6 removed
14 unmodified lines
1516 return buffer;17};1819/**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 */19const fakeContainer = (running: boolean) => {20 const started: ContainerStartupOptions[] = [];21 const commands: { argv: string[]; options: ContainerExecOptions }[] = [];22
24 unmodified lines
47};4849const start = { enableInternet: false, image: "check" };5056/** A running container whose one command never ends until it is killed. */51const hungContainer = () => {52 const killed: (number | undefined)[] = [];5354 const container = untouchable<Container>("container", {
90 unmodified lines
modified:apps/sandbox/test/checker.test.ts+1 added-32 removed
81 unmodified lines
82 call.argv[0] === "sh" &&83 call.argv[1] === "-c" &&84 call.argv[2] === command;8586/** How many times setup's command ran. */86const setups = (calls: readonly Call[]) =>87 calls.filter((call) => isShell(call, SETUP)).length;8890/**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 */89const phaseOf = Match.type<Call>().pipe(90 Match.discriminatorsExhaustive("kind")({91 allow: ({ hosts }): readonly string[] =>92 hosts.length === 0 ? ["egressOff"] : ["setup"],
61 unmodified lines
154 })155 )156 );157164 // 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));159160 const egress = fake.calls161 .slice(0, setupAt)
3 unmodified lines
165 hosts: [...REGISTRIES, "npm.pkg.github.com"],166 kind: "allow",167 });168177 // 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 lines
252 : []253 )254 ).toStrictEqual(["evil.example"]);255265 // 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 lines
301 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 lines
354 expect(ran.outputs).toStrictEqual([355 { lane: "no-explicit-any", stdout: printed },356 ]);357369 // 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 lines
404 call.kind === "restore" ? [call.hit] : []405 )406 ).toStrictEqual([true]);407420 // 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 lines
515 })516 );517});518533/** The requests the Worker sends on, in place of the network, until the scope ends. */519const outboundRecorded = Effect.acquireRelease(520 Effect.sync(() => {521 const sent: Request[] = [];522
180 unmodified lines
703 })704 );705});706722/**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 */707const 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[] = [];714736 /** 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 lines
735736 return indexStub;737 };738761 // 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 lines
772773const encodedWire = () =>774 Schema.encodeEffect(CheckWire)(wireFor()).pipe(Effect.orDie);775799/**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 */776const twoJobsIn = ({ running = true } = {}) =>777 Effect.gen(function* () {778 const world = checkerWorld({ running, withGateways: true });779 const wire = yield* encodedWire();
50 unmodified lines
830 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 lines
881 Effect.gen(function* () {882 const { boxes } = yield* twoJobsIn({ running: false });883884 // 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 lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { CheckAt } from "@repo/checks/check-runner";3import type { CheckJob } from "@repo/checks/check-runner";4import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";
36 unmodified lines
41const SENTRY = EnvKey.make("SENTRY_AUTH_TOKEN");4243const PLACEHOLDER = "__SENTRY_AUTH_TOKEN_PLACEHOLDER__";4452/** The write-only value a landed run's gateway swaps in: never in the container. */45const VALUE = "sntrys_5f0c1d2e3b4a69788796a5b4c3d2e1f0";4647const sentryRule = {48 block: false,
19 unmodified lines
68 ...env,69 },70});7180/** The env `sh -c <command>` ran with, for each run of `command`. */72const 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 );7888/** One job through the Checker over the fakes: what they saw. */79const checked = (wire: CheckWire) =>80 Effect.gen(function* () {81 const fake = fakeChecker();82
3 unmodified lines
8687 return { calls: fake.calls, outcome };88 });89100/** A job of landed code, carrying the value its gateway swaps in. */90const landedJob = () =>91 jobWith({92 landed: true,93 values: [{ key: SENTRY, value: Redacted.make(VALUE) }],
134 unmodified lines
228 })229 );230});231243/**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 */232const upstream = (answer: (request: Request) => Response) =>233 Effect.acquireRelease(234 Effect.sync(() => {235 const sent: Request[] = [];
8 unmodified lines
244 }),245 () => Effect.sync(() => vi.unstubAllGlobals())246 );247263/** A gateway for one job: its rules, and the values only a landed job's carries. */248const gatewayFor = (props: Partial<EnvGatewayProps> = {}) =>249 new EnvGateway(250 untouchable<ExecutionContext<EnvGatewayProps>>("ctx", {251 props: { rules: [sentryRule], values: [], ...props },
12 unmodified lines
264 },265 method: "POST",266 });267284/** What reached the upstream: method, URL, every header, and the body. */268const readSent = (request: Request) =>269 Effect.promise(() => request.text()).pipe(270 Effect.map((body) => ({271 body,
212 unmodified lines
484 })485 );486});487505/**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 */488const inContainer = (wire: CheckWire) =>489 Effect.gen(function* () {490 const box = fakeContainer();491
179 unmodified lines
modified: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 */1import { untouchable } from "@repo/testkit/untouchable";2import { Effect, Layer, Logger, Redacted, References } from "effect";34import { Box } from "../src/box.ts";
4 unmodified lines
9import { Snapshots } from "../src/checker/snapshots.ts";10import type { EnvGatewayProps } from "../src/env-gateway.ts";11import type { CloneProps, EgressProps } from "../src/outbound.ts";1219/** What the container could reach at one moment. */13export type Reach = "clone route" | readonly string[];1422/** One thing the Checker did, as the fakes saw it. */15export 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 lines
43 readonly message: string;44 readonly annotations: Readonly<Record<string, string>>;45 };4659/** What a command left, for a script. */47export const exited = (48 exitCode: number,49 output: { readonly stdout?: string; readonly stderr?: string } = {}50): Effect.Effect<Executed, BoxFailed> =>
3 unmodified lines
54 stdout: output.stdout ?? "",55 });5657export 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}6484/** A lockfile listing, as `git ls-tree HEAD -- <names>` prints one. */65export const LOCKFILES =66 "100644 blob 8f2c1d0e9b7a6c5d4e3f2a1b0c9d8e7f6a5b4c3d\tbun.lock\n";6788/** The command `sh -c <command>` runs, or none for any other argv. */68const shellCommandOf = (argv: readonly string[]) =>69 argv[0] === "sh" && argv[1] === "-c" ? argv[2] : undefined;7092/** The fakes for one job, and the list their calls go to. */71export const fakeChecker = (options: FakeOptions = {}) => {72 const calls: Call[] = [];73 const kept = options.snapshots ?? new Set<string>();74 let reach: Reach = "clone route";
108 unmodified lines
183 ])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 lines
194 layer: Layer.mergeAll(box, network, snapshots, logs, logger),195 };196};197221/** One thing done to a Durable Object's container, as the Container API saw it. */198export type ContainerCall =199 | {200 readonly kind: "exec";201 readonly argv: readonly string[];
2 unmodified lines
204 | { 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 lines
218219 return buffer;220};221247/**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 */222export const fakeContainer = ({ running = true } = {}) => {223 const calls: ContainerCall[] = [];224 const gateways = new Map<Fetcher, string>();225
62 unmodified lines
288 );289 },290 });291325 /** 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 lines
modified:apps/sandbox/test/fake-env.ts-4 removed
1import { untouchable } from "@repo/testkit/untouchable";23/**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 */3export 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 lines
57const exportArea = AreaName.make("export");5859const parser = AreaName.make("parser");6061/**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. */62const SEALED = [63 {64 area: exportArea,65 path: "checks/held-back/export/round-trip.test.ts",
18 unmodified lines
84}));8586const weekFile = SEALED.at(-1);8791/** What the parser's sealed check prints as it fails. */88const PARSER_STDOUT = `(fail) parser > ${weekFile?.test}\n`;8990const PARSER_STDERR =91 "AssertionError: expected Week(54) to be undefined at week-54.test.ts:3\n";
35 unmodified lines
127 run,128 },129});130135/** The fake, with the parser's sealed check failing. */131const parserFails = (options: FakeOptions = {}) =>132 fakeChecker({133 commands: new Map([134 [
7 unmodified lines
142const sealedCommands: ReadonlySet<string> = new Set(143 SEALED.map(({ command }) => command)144);145151/**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 */146const writesSealed = (call: Call) =>147 call.kind === "writeFile" ||148 (call.kind === "exec" && call.argv.some((arg) => arg.startsWith(`${REPO}/`)));149
1 unmodified line
151 call.kind === "exec" && call.argv[0] === "sh" && call.argv[1] === "-c"152 ? Option.fromUndefinedOr(call.argv[2])153 : Option.none();154165/** The recording as phases, each run of calls for one phase read as one. */155const phaseOf = Match.type<Call>().pipe(156 Match.discriminatorsExhaustive("kind")({157 allow: ({ hosts }): readonly string[] =>158 hosts.length === 0 ? ["egressOff"] : ["setup"],
33 unmodified lines
192 calls193 .flatMap(phaseOf)194 .filter((phase, at, all) => at === 0 || all[at - 1] !== phase);195207/** Everything about the suite that must never leave the Checker. */196const SECRETS = [197 ...SEALED.flatMap(({ path, test, text }) => [198 path,199 path.split("/").at(-1) ?? path,
5 unmodified lines
205 PARSER_STDERR.trim(),206 "Week(54)",207];208221/** The secrets `text` holds. */209const leakedIn = (text: string) =>210 SECRETS.filter((secret) => text.includes(secret));211225/** What leaves the Checker besides its result: the logs it hands over and its log lines. */212const leftBy = (calls: readonly Call[]) =>213 JSON.stringify(214 calls.filter((call) => call.kind === "report" || call.kind === "log")215 );216231/** One job with the sealed suite, the parser's check failing: what the fakes saw, and the outcome. */217const sealedJob = Effect.gen(function* () {218 const fake = parserFails();219220 const outcome = yield* Effect.exit(
9 unmodified lines
230});231232const LINT_COUNT = "oxlint --format json";233249/** Public lanes that print what they found: `unit`, and a count lane. */234const printing = () =>235 fakeChecker({236 commands: new Map([237 [UNIT, printedBeside],238 [LINT_COUNT, printedBeside],239 ]),240 });241258/** The job's wire with a count lane after `unit`. */242const withCountLane = (sealed: Option.Option<HeldBackPart>): CheckWire => {243 const base = wireFor(sealed);244245 return {
11 unmodified lines
257 },258 };259};260278/** The outcome as it crosses the service binding, as JSON. */261const serialized = (outcome: Exit.Exit<CheckRun, VerifierBlocked>) =>262 Schema.encodeEffect(CheckExit)(outcome).pipe(263 Effect.map((encoded) => JSON.stringify(encoded))264 );
17 unmodified lines
282 "report",283 "destroy",284 ]);285304 // 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 lines
298 ({ _tag }) => `${_tag.charAt(0).toLowerCase()}${_tag.slice(1)}`299 )300 );301321 // 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 lines
417 const ran = yield* check(withCountLane(Option.some(heldBack))).pipe(418 Effect.provide(fake.layer)419 );420441 // 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 lines
651 )652 );653654 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 });657658 it.effect(
31 unmodified lines
modified:apps/sandbox/test/lander.fixtures.ts+1 added-39 removed
44 unmodified lines
4546/** The token every remote carries: no command line, result or log may show it. */47export const secret = "art_v1_0123456789abcdef0123456789abcdef01234567";4849/** A path in this repo, from the sandbox's test folder. */49export const inRepo = (path: string) =>50 new URL(`../../../${path}`, import.meta.url).pathname;5153/**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 */52export const sdk = {53 entry: inRepo("packages/sdk/src/index.ts"),54 modules: inRepo("packages/sdk/node_modules"),55};5663/** What a file holds after a commit, or `null` for a file the commit deletes. */57export type Files = Readonly<Record<string, string | null>>;5866/** The message of a landing that credits dora as asker and bob as answerer. */59export const message = formatLanding({60 assisted: [],61 credits: [62 { handle: dora, role: "Asked-by" },
23 unmodified lines
86 tree: input.tree,87 verifier: "platform",88 });8998/** Every ref of a bare repo, with what it points at. */90const refsOf = (repo: string) =>91 gitOk(repo, "for-each-ref", "--format=%(refname) %(objectname)");92102/** What a bare repo holds: its refs, and how many objects. */93const stateOf = (repo: string) =>94 Effect.all({95 objects: gitOk(repo, "count-objects", "-v"),96 refs: refsOf(repo),97 });98109/** One revision's id in a bare repo, or `None` when it has none. */99const 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 );105117/** A repo's remote as a job carries it: its URL, and a token for it. */106const remote = (url: string) => ({ token: Redacted.make(secret), url });107120/**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 */108export 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 lines
118 yield* gitOk(root, "init", "--quiet", "--bare", "-b", "main", forkDir);119 yield* gitOk(root, "init", "--quiet", "-b", "main", clone);120 yield* fs.makeDirectory(work);121140 /** 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: string
19 unmodified lines
145146 return CommitSha.make(yield* gitOk(clone, "rev-parse", "HEAD"));147 });148168 /** 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}`);151172 /** 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 );156178 /** 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 lines
234235 return { base, clash, head, main: LandedSha.make(main) };236 });237260/** The mirror ref a landing moves, after main. */238export const landedRefName = `${Brand.refsPrefix}landed`;239263/**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 */240export const layout = (work: string) =>241 Layer.effect(242 Layout,243 Effect.gen(function* () {
10 unmodified lines
254 };255 }).pipe(Effect.orDie)256 ).pipe(Layer.provide(NodeServices.layer));257286/** The Lander's container over local processes, its `Box` changed by `wrap` when a test needs to. */258export const box = (259 work: string,260 wrap: (inner: Box["Service"]) => Box["Service"] = (inner) => inner261) =>
3 unmodified lines
265 );266267export const TestServices = NodeServices.layer;268298/** A file's path in the config folder. */269export const config = (file: string) => `${Brand.configDir}/${file}`;270301/**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. */272export const configFolder = {273 [config("asks/parse-iso.ask.ts")]: [274 'import { kinds, territory } from "@repo/sdk";',275 "",
37 unmodified lines
313 ].join("\n"),314 [config("vouched.td")]: "dora\nbob\n",315} satisfies Files;316353/** datekit's first commit with `files` beside its code, on canonical `main`. */317export const startedWith = (repos: World, files: Files) =>318 Effect.gen(function* () {319 const at = yield* repos.commit(undefined, { ...start, ...files }, "Start");320
1 unmodified line
322323 return LandedSha.make(at);324 });325363/** A bundle of datekit's config folder at `at`. */326export 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 lines
49 world,50} from "./lander.fixtures.ts";51import type { Files, World } from "./lander.fixtures.ts";5253/** The merge of bob's answer at `head` onto datekit's `main`. */53const mergeWire = (54 repos: World,55 job: {56 readonly base: CommitSha;
5 unmodified lines
62 job: { ...job, fork, repo: project },63 main: repos.remote(repos.canonical),64});6567/** A land of bob's answer, merged again from `head`, onto datekit's `main`. */66const landWire = (67 repos: World,68 job: {69 readonly base: CommitSha;
15 unmodified lines
85 },86 main: repos.remote(repos.canonical),87});8891/** A commit in a bare repo as git shows it: who made it, on what, and its message. */89const commitIn = (repo: string, sha: string) =>90 Effect.gen(function* () {91 const shown = yield* gitOk(92 repo,
16 unmodified lines
109 });110111const decodeNote = Schema.decodeEffect(Schema.fromJsonString(Verdict));112116/** Whether a command is the push that moves canonical `main`. */113const pushesMain = (argv: readonly string[]) =>114 argv.includes("push") && argv.at(-1)?.endsWith(":refs/heads/main") === true;115120/**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 */116const beforeMainIsPushed =117 (first: Effect.Effect<void>) =>118 (inner: Box["Service"]): Box["Service"] => ({119 ...inner,
2 unmodified lines
122 ? Effect.andThen(first, inner.exec(argv, options))123 : inner.exec(argv, options),124 });125134/** Someone else's commit on canonical `main`, as a push that moves it would leave it. */126const movedBy = (repos: World, parent: CommitSha) =>127 Effect.gen(function* () {128 const other = yield* repos.commit(129 parent,
5 unmodified lines
135136 return other;137 });138148/** One command the Lander handed its container: what it ran, and with what env. */139interface Handed {140 readonly argv: readonly string[];141 readonly env: Readonly<Record<string, string>>;142}143154/** The Lander's container, keeping every command it is handed in `handed`. */144const recording =145 (handed: Handed[]) =>146 (inner: Box["Service"]): Box["Service"] => ({147 ...inner,
3 unmodified lines
151 inner.exec(argv, options)152 ),153 });154166/**167 * The Lander's container, where the push of the mirror ref is rejected, as168 * a receive-pack that refuses one ref would.169 */155const mirrorRefused = (inner: Box["Service"]): Box["Service"] => ({156 ...inner,157 exec: (argv, options) =>158 argv.at(-1)?.endsWith(`:${landedRefName}`) === true
4 unmodified lines
163 })164 : inner.exec(argv, options),165});166182/**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. */168const busyOnMain = (inner: Box["Service"]): Box["Service"] => ({169 ...inner,170 exec: (argv, options) =>171 pushesMain(argv)
5 unmodified lines
177 })178 : inner.exec(argv, options),179});180200/**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 */181const mainDeclined = (inner: Box["Service"]): Box["Service"] => ({182 ...inner,183 exec: (argv, options) =>184 pushesMain(argv)
4 unmodified lines
189 })190 : inner.exec(argv, options),191});192216/**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 */193const tracing = (inner: Box["Service"]): Box["Service"] => ({194 ...inner,195 exec: (argv, options = {}) =>196 options.env?.GIT_CONFIG_VALUE_0 === undefined
4 unmodified lines
201 stdout: "",202 }),203});204233/** A logger keeping every line, with its annotations, as JSON. */205const keeping = (lines: string[]) =>206 Logger.layer([207 Logger.make((options) => {208 lines.push(JSON.stringify(Logger.formatStructured.log(options)));209 }),210 ]);211241/** A module's default export, as `import()` of a file gives it. */212interface Imported {213 readonly default: unknown;214}215246/**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 */216const importedFrom = (217 modules: Readonly<Record<string, string>>,218 file: string219) =>
13 unmodified lines
233234 return yield* Effect.promise((): Promise<Imported> => import(target));235 });236271// Both names a config folder imports the sdk by.237const SDK_NAMES = [`"${Brand.cliPackage}/rules"`, '"@repo/sdk"'];238274/** A file's source with its imports of the sdk pointed at this repo's. */239const pointedAtSdk = (source: string) => {240 let pointed = source;241242 for (const name of SDK_NAMES) {
2 unmodified lines
245246 return pointed;247};248285/** The config folder as committed, its imports of the sdk pointed at this repo's. */249const asCommitted = (files: Files) =>250 Object.fromEntries(251 Object.entries(files).flatMap(([file, source]) =>252 source === null ? [] : [[file, pointedAtSdk(source)] as const]253 )254 );255293/** A definition as data: what JSON keeps of it, as the evaluator reads it back. */256const dataOf = ({ default: definition }: Imported) =>257 JSON.stringify(definition);258297/** What `admit` hears about a person who wants to claim (the sdk's `ClaimantFacts`). */259interface Claimant {260 readonly handle: string;261 readonly kind: string;262 readonly record: number;263 readonly territory: string;264 readonly vouched: boolean;265}266306// Where the sdk keeps a definition's function-valued rules.267const FUNCTIONS = Symbol.for("@repo/sdk/Functions");268309/** A function-valued `admit` rule, as the sdk keeps one. */269type Admit = (facts: Claimant) => boolean;270271const isAdmit = (rule: unknown): rule is Admit => Predicate.isFunction(rule);272314/** The project's `admit` rule, where the sdk keeps it, called with `facts`. */273const admits = ({ default: definition }: Imported, facts: Claimant) => {274 const functions = Predicate.hasProperty(definition, FUNCTIONS)275 ? definition[FUNCTIONS]276 : undefined;
623 unmodified lines
900 );901 });902});903946/** The root manifest's catalog: the versions every workspace shares. */904const RootManifest = Schema.fromJsonString(905 Schema.Struct({906 workspaces: Schema.Struct({907 catalog: Schema.Struct({ effect: Schema.String }),
21 unmodified lines
929 ).toBe(manifest.workspaces.catalog.effect);930 }).pipe(Effect.provide(TestServices))931 );932976 // 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 lines
1033 ).toStrictEqual([]);1034 });1035});10361081/** A merge whose remotes no command in these tests reaches. */1037const idleMerge = {1038 fork: {1039 token: Redacted.make(secret),1040 url: "https://artifacts.invalid/datekit--parse-iso--bob.git",
146 unmodified lines
1187 yield* Effect.promise(() => lander.merge(wire))1188 );11891190 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 lines
modified:apps/sandbox/test/local-box.ts-8 removed
11 unmodified lines
12 (operation: BoxFailed["operation"]) =>13 (cause: { readonly message: string }) =>14 new BoxFailed({ operation, reason: cause.message });1516/**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 */16export const LocalBox: Layer.Layer<Box> = Layer.effect(17 Box,18 Effect.gen(function* () {19 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
47 unmodified lines
modified:apps/sandbox/test/smoke.test.ts-5 removed
21 unmodified lines
22 token: Redacted.make(`token-for-${name}`),23 url: `https://artifacts.invalid/${name}.git`,24});2526/** The sandbox's entrypoint as the platform's service binding reaches it. */26const sandbox = new Sandbox(untouchable("ctx"), fakeEnv());2729/** A stub's outcome: a typed failure, not a defect. */28const failureOf = Exit.findErrorOption;2930describe("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 lines
modified: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 */1import { fakeEnv } from "./fake-env.ts";23export class DurableObject<E = Env> {4 readonly ctx: DurableObjectState;
21 unmodified lines
modified:apps/sandbox/vitest.config.ts+2 added-4 removed
1import { preset } from "@repo/config/vitest";2import { defineConfig, mergeConfig } from "vitest/config";34// 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.6export default mergeConfig(7 preset,8 defineConfig({9 resolve: {
8 unmodified lines