Merge build/616-cli-env-set: `<cli> env set` stores a real write-only value end to end, and `env shape` shows who set it
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents c6defde, 36d8c2b · Browse files · 4 files·+1305 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+1305 added−15 removed
- tests:+1290 added−15 removed
- other:+15 added−0 removed
Provenance
- Commit
89eb59d- Tree
610a680- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
c6defde- Parent 2
36d8c2b
4 files changed+1305 added−15 removed
added:apps/cli/test/local/env-set-live.test.ts+938 added
1+/**2+ * `<cli> env set` end to end (W6 616; spec §6.7's done-when for env): the3+ * CLI's real `env set`, `env shape` and `ledger` commands, over its remote4+ * client as the stored profile, against the platform's Node world with the5+ * visibility cartridge composed under the fake env's test `MASTER_KEY`6+ * (`apps/platform/test/visibility/serve-cartridge-world.ts`, a process of7+ * its own: apps never import apps).8+ *9+ * ines-v makes datekit and first pushes it with its committed `.env.schema`10+ * and config folder, which names her its decider and vouches for bram. She11+ * pipes a token into `env set`; bram, not a decider, tries the same; she12+ * tries a public item and a short value. Then she opens an ask, bram13+ * answers it, and the world's Checker runs the answer's checks. The value14+ * shows nowhere: not in what the CLI printed or logged, not in any `/rpc`15+ * or `/mcp` body the world sent, any line it logged or printed, the16+ * Project DO's event log or ledger, or any job the Checker was given; the17+ * DO's `env_values` row holds it sealed. What the world kept, it gives18+ * through its `kept` window, once every step has run.19+ */20+import { NodeServices } from "@effect/platform-node";21+import { expect, layer } from "@effect/vitest";22+import { Brand } from "@repo/brand";23+import { CheckJob } from "@repo/checks/check-runner";24+import { Client } from "@repo/protocol/contracts";25+import { EnvSchemaView } from "@repo/protocol/domain/env";26+import { Ledger, LedgerEntry } from "@repo/protocol/domain/visibility";27+import { Envelope } from "@repo/protocol/envelope";28+import {29+ AskId,30+ EnvKey,31+ Handle,32+ ProjectName,33+ RepoPath,34+} from "@repo/protocol/ids";35+import {36+ NotDecider,37+ NotSensitive,38+ ValueTooShort,39+} from "@repo/protocol/refusal";40+import { explain } from "@repo/protocol/render";41+import { git, gitOk, spawn } from "@repo/testkit/git";42+import {43+ Array,44+ Cause,45+ Context,46+ DateTime,47+ Deferred,48+ Effect,49+ Exit,50+ FileSystem,51+ Layer,52+ Logger,53+ Option,54+ Path,55+ Redacted,56+ Ref,57+ References,58+ Runtime,59+ Schema,60+ Stdio,61+ Stream,62+ Terminal,63+} from "effect";64+import { CliOutput } from "effect/cli";65+import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";66+import { TestConsole } from "effect/testing";67+68+import { Credentials } from "../../src/credentials.ts";69+import { program } from "../../src/main.ts";70+import { OutputLive } from "../../src/output.ts";71+import { policyFor } from "../../src/policy.ts";72+import { RemoteClient } from "../../src/remote.ts";73+74+/** The world, from the repo root: the platform's Node world, cartridge composed. */75+const WORLD = "apps/platform/test/visibility/serve-cartridge-world.ts";76+77+const project = ProjectName.make("datekit");78+79+const token = EnvKey.make("SENTRY_AUTH_TOKEN");80+81+/** What ines-v pipes in: a token of 24 characters, then the newline `echo` adds. */82+const value = "sk_test_0123456789abcdef";83+84+/** A value of 8 characters, under the 12 a value needs. */85+const short = "tooshort";86+87+/** The ask ines-v opens and bram answers: one of datekit's own. */88+const ask = AskId.make("parse-iso-week");89+90+interface Person {91+ readonly handle: Handle;92+ /** Their platform token, as the world's sessions list it. */93+ readonly token: string;94+}95+96+const ines: Person = {97+ handle: Handle.make("ines-v"),98+ token: "ines-v-env-set-live-token-0123456789abcdef",99+};100+101+const bram: Person = {102+ handle: Handle.make("bram"),103+ token: "bram-env-set-live-token-0123456789abcdefgh",104+};105+106+/** Whether datekit's first commit carries a tracked file: the library before anyone asked. */107+const seeded = (file: string) =>108+ [109+ ".env.schema",110+ `${Brand.configDir}/project.ts`,111+ `${Brand.configDir}/vouched.td`,112+ "package.json",113+ "tsconfig.json",114+ ].includes(file) ||115+ /^src\/[^/]+\.ts$/u.test(file) ||116+ /^test\/[^/]+\.test\.ts$/u.test(file);117+118+/** The ask's file and the check it names, as datekit commits them. */119+const askFiles = [120+ `${Brand.configDir}/asks/${ask}.ask.ts`,121+ `test/asks/${ask}.test.ts`,122+] as const;123+124+// --------------------------------------------------------------- the world125+126+const Serving = Schema.fromJsonString(127+ Schema.Struct({ kept: Schema.String, origin: Schema.String })128+);129+130+const decodeServing = Schema.decodeUnknownOption(Serving);131+132+/** Where the world serves: the platform, and the test's window on what it kept. */133+interface Served {134+ readonly origin: string;135+ readonly kept: string;136+ /** Everything the world's process printed so far, stdout and stderr. */137+ readonly printed: Effect.Effect<string>;138+}139+140+/**141+ * The world served by a process of its own for as long as the scope142+ * lasts, with ines-v and bram among its sessions. Both of its streams are143+ * kept to the end, so it never blocks on a full pipe and every line it144+ * printed can be searched.145+ */146+const servedWorld = (root: string) =>147+ Effect.gen(function* () {148+ const child = yield* spawn("bun", [WORLD], {149+ cwd: root,150+ env: {151+ WORLD_SESSIONS: JSON.stringify({152+ [ines.token]: ines.handle,153+ [bram.token]: bram.handle,154+ }),155+ },156+ });157+158+ const printed = yield* Ref.make("");159+ const serving = yield* Deferred.make<typeof Serving.Type>();160+161+ const keep = (text: string) => Ref.update(printed, (all) => all + text);162+163+ yield* Stream.decodeText(child.stderr).pipe(164+ Stream.runForEach(keep),165+ Effect.ignore,166+ Effect.forkScoped167+ );168+169+ yield* Stream.splitLines(Stream.decodeText(child.stdout)).pipe(170+ Stream.runForEach((line) =>171+ Effect.andThen(172+ keep(`${line}\n`),173+ Option.match(decodeServing(line), {174+ onNone: () => Effect.void,175+ onSome: (where) => Deferred.succeed(serving, where),176+ })177+ )178+ ),179+ Effect.ignore,180+ Effect.forkScoped181+ );182+183+ const ended = child.exitCode.pipe(184+ Effect.ignore,185+ Effect.andThen(Ref.get(printed)),186+ Effect.flatMap((said) =>187+ Effect.die(`the world ended before it served: ${said}`)188+ )189+ );190+191+ const where = yield* Effect.raceFirst(Deferred.await(serving), ended).pipe(192+ Effect.timeout("60 seconds"),193+ Effect.orDie194+ );195+196+ return { ...where, printed: Ref.get(printed) } satisfies Served;197+ });198+199+/** What the world's `kept` window gives: each part as the world encoded it. */200+const Kept = Schema.fromJsonString(201+ Schema.Struct({202+ bodies: Schema.Array(Schema.String),203+ jobs: Schema.Array(Schema.Unknown),204+ logged: Schema.Array(Schema.String),205+ store: Schema.NullOr(206+ Schema.Struct({207+ envValues: Schema.Array(208+ Schema.Struct({209+ key: Schema.String,210+ sealed: Schema.Record(Schema.String, Schema.Unknown),211+ setAt: Schema.String,212+ setBy: Schema.String,213+ })214+ ),215+ events: Schema.Array(Schema.Unknown),216+ ledger: Schema.Array(Schema.Unknown),217+ })218+ ),219+ })220+);221+222+/** What the world kept for datekit. */223+const keptBy = (world: Served) =>224+ Effect.gen(function* () {225+ const http = yield* HttpClient.HttpClient;226+ const response = yield* http.get(`${world.kept}/kept?project=${project}`);227+228+ return yield* Schema.decodeEffect(Kept)(yield* response.text);229+ }).pipe(Effect.orDie);230+231+/** Carries every answer run the world has queued. */232+const settle = (world: Served) =>233+ Effect.gen(function* () {234+ const http = yield* HttpClient.HttpClient;235+ const response = yield* http.post(`${world.kept}/settle`);236+237+ return response.status === 204238+ ? yield* Effect.void239+ : yield* Effect.die(`the world did not settle: ${response.status}`);240+ }).pipe(Effect.orDie);241+242+// MCP's 2026-07-28 protocol is stateless: each request names its version243+// and client in `_meta` and repeats its method in a header.244+const mcpVersion = "2026-07-28";245+246+const Listed = Schema.fromJsonString(247+ Schema.Struct({248+ result: Schema.Struct({249+ tools: Schema.Array(Schema.Struct({ name: Schema.String })),250+ }),251+ })252+);253+254+/** The names of the tools the world's `/mcp` lists to `as`. */255+const toolsListed = (world: Served, as: Person) =>256+ Effect.gen(function* () {257+ const http = yield* HttpClient.HttpClient;258+259+ const request = HttpClientRequest.post(`${world.origin}/mcp`).pipe(260+ HttpClientRequest.setHeaders({261+ accept: "application/json, text/event-stream",262+ "mcp-method": "tools/list",263+ "mcp-protocol-version": mcpVersion,264+ }),265+ HttpClientRequest.bearerToken(as.token),266+ HttpClientRequest.bodyText(267+ JSON.stringify({268+ id: 1,269+ jsonrpc: "2.0",270+ method: "tools/list",271+ params: {272+ _meta: {273+ "io.modelcontextprotocol/clientCapabilities": {},274+ "io.modelcontextprotocol/clientInfo": {275+ name: "test",276+ version: "0.0.0",277+ },278+ "io.modelcontextprotocol/protocolVersion": mcpVersion,279+ },280+ },281+ }),282+ "application/json"283+ )284+ );285+286+ const response = yield* http.execute(request);287+ const text = yield* response.text;288+289+ // The reply is plain JSON or an event stream; its last message answers.290+ const last =291+ response.headers["content-type"]?.includes("text/event-stream") === true292+ ? (text293+ .split("\n")294+ .findLast((line) => line.startsWith("data: "))295+ ?.slice("data: ".length) ?? "")296+ : text;297+298+ const { result } = yield* Schema.decodeEffect(Listed)(last);299+300+ return result.tools.map(({ name }) => name);301+ }).pipe(Effect.orDie);302+303+// ----------------------------------------------------------------- people304+305+/** Credentials holding `as`'s profile on the world, as `login` would have stored it. */306+const signedIn = (world: Served, as: Person) =>307+ Layer.succeed(Credentials)({308+ current: Effect.succeedSome({309+ handle: as.handle,310+ token: Redacted.make(as.token),311+ url: world.origin,312+ }),313+ forHost: () => Effect.succeedNone,314+ put: () => Effect.die("the test stores no profile"),315+ remove: () => Effect.die("the test removes no profile"),316+ });317+318+/** The CLI's own client of the contracts, as `as`, for the steps the test sets up. */319+const clientOf = (world: Served, as: Person) =>320+ Effect.map(321+ Layer.build(RemoteClient.pipe(Layer.provide(signedIn(world, as)))),322+ (built) => Context.get(built, Client)323+ );324+325+/**326+ * `as`'s git: every command through a credential helper that gives their327+ * handle and token, as the CLI's helper gives git a stored profile's.328+ */329+const gitOf = (helpers: string, as: Person) =>330+ Effect.gen(function* () {331+ const fs = yield* FileSystem.FileSystem;332+ const helper = `${helpers}/${as.handle}`;333+334+ yield* fs.writeFileString(335+ helper,336+ [337+ "#!/bin/sh",338+ 'test "$1" = get || exit 0',339+ `echo username=${as.handle}`,340+ `echo password=${as.token}`,341+ "",342+ ].join("\n")343+ );344+345+ yield* fs.chmod(helper, 0o700);346+347+ const helped = ["-c", `credential.helper=${helper}`];348+349+ return {350+ ok: (cwd: string, ...args: string[]) => gitOk(cwd, ...helped, ...args),351+ run: (cwd: string, ...args: string[]) => git(cwd, ...helped, ...args),352+ };353+ });354+355+// -------------------------------------------------------------- the CLI356+357+/** What one run of the CLI did: its exit code, and what it printed and logged, by line. */358+interface Ran {359+ readonly code: number;360+ readonly out: readonly string[];361+ readonly err: readonly string[];362+ readonly logged: readonly string[];363+}364+365+/** A terminal that fails any prompt: nothing here may prompt. */366+const noPrompts = Layer.succeed(Terminal.Terminal)(367+ Terminal.make({368+ columns: Effect.succeed(80),369+ display: () => Effect.die("the CLI prompted"),370+ readInput: Effect.die("the CLI prompted"),371+ readLine: Effect.die("the CLI prompted"),372+ rows: Effect.succeed(24),373+ })374+);375+376+/** How the process would exit, by the runtime's own rule. */377+const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>378+ Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));379+380+/** Each line of what a stream got, however it was written. */381+const linesOf = (chunks: readonly unknown[]) =>382+ chunks.flatMap((chunk) => String(chunk).split("\n"));383+384+/**385+ * `<cli> <args>` as `as`, a person at a terminal whose stdin is `stdin`386+ * piped in: the real command tree and output, the real remote client over387+ * HTTP to the world, and their stored profile.388+ */389+const cli = (390+ world: Served,391+ as: Person,392+ args: readonly string[],393+ stdin = ""394+): Effect.Effect<Ran> =>395+ Effect.suspend(() => {396+ const logged: string[] = [];397+ const policy = policyFor({ env: {}, isTTY: true });398+ const credentials = signedIn(world, as);399+400+ return Effect.gen(function* () {401+ const exit = yield* Effect.exit(program(args));402+403+ return {404+ code: exitCodeOf(exit),405+ err: linesOf(yield* TestConsole.errorLines),406+ logged,407+ out: linesOf(yield* TestConsole.logLines),408+ };409+ }).pipe(410+ Effect.provideService(References.MinimumLogLevel, "All"),411+ Effect.provide(412+ Layer.mergeAll(413+ NodeServices.layer,414+ TestConsole.layer,415+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),416+ RemoteClient.pipe(Layer.provide(credentials)),417+ credentials,418+ policy,419+ OutputLive.pipe(Layer.provide(policy)),420+ noPrompts,421+ Logger.layer([422+ Logger.make((options) => {423+ logged.push(Logger.formatSimple.log(options));424+ }),425+ ]),426+ // Last, so it stands in for the host's stdio.427+ Stdio.layerTest({428+ stdin: Stream.make(new TextEncoder().encode(stdin)),429+ stdinIsTerminal: Effect.succeed(false),430+ })431+ )432+ )433+ );434+ });435+436+// ------------------------------------------------------------ the scenario437+438+/** Everything the scenario did and the world kept, read by each test below. */439+class Scenario extends Context.Service<440+ Scenario,441+ {442+ /** ines-v's `env set` of the token, its refusals, and bram's. */443+ readonly set: Ran;444+ readonly byBram: Ran;445+ readonly publicItem: Ran;446+ readonly tooShort: Ran;447+ /** `env shape --json` and `ledger --json` once the token was set. */448+ readonly envView: Ran;449+ readonly ledger: Ran;450+ /** bram's push of his answer, as git printed it. */451+ readonly answered: { readonly exitCode: number; readonly stderr: string };452+ /** The jobs the Checker was given for the answer: those made while the world settled. */453+ readonly answerJobs: readonly CheckJob[];454+ /** The tools `/mcp` lists to ines-v. */455+ readonly tools: readonly string[];456+ readonly kept: typeof Kept.Type;457+ /** All the world's process printed, stdout and stderr. */458+ readonly printed: string;459+ }460+>()("test/EnvSetLiveScenario") {}461+462+/**463+ * The jobs as the world encoded them: by `CheckJob`'s fields alone, so a464+ * job of unlanded code that carries values decodes, and a test refuses it.465+ */466+const decodeJobs = Schema.decodeUnknownEffect(467+ Schema.Array(Schema.Struct(CheckJob.fields))468+);469+470+/**471+ * The scenario, run once: datekit made and first pushed by ines-v, the472+ * token set and the refusals met through the CLI, then an ask opened by473+ * ines-v and answered by bram, the answer's checks run, and what the world474+ * kept read back.475+ */476+const ScenarioOnce = Layer.effect(477+ Scenario,478+ Effect.gen(function* () {479+ const fs = yield* FileSystem.FileSystem;480+ const path = yield* Path.Path;481+482+ const root = yield* path.fromFileUrl(483+ new URL("../../../../", import.meta.url)484+ );485+486+ const example = path.join(root, "examples", "datekit");487+ const home = yield* fs.makeTempDirectoryScoped({ prefix: "env-set-live-" });488+ const world = yield* servedWorld(root);489+ const helpers = path.join(home, "helpers");490+491+ yield* fs.makeDirectory(helpers);492+493+ const inesGit = yield* gitOf(helpers, ines);494+ const bramGit = yield* gitOf(helpers, bram);495+ const asInes = yield* clientOf(world, ines);496+ const asBram = yield* clientOf(world, bram);497+498+ // ines-v makes datekit and first pushes the library as committed, its499+ // `.env.schema` and its config folder in it.500+ const made = yield* asInes.initProject({ project });501+ const start = path.join(home, "start");502+503+ const tracked = yield* gitOk(example, "ls-files", "--full-name", ".");504+ const prefix = "examples/datekit/";505+506+ yield* fs.makeDirectory(start);507+508+ for (const file of tracked509+ .split("\n")510+ .map((line) => line.slice(prefix.length))) {511+ if (seeded(file)) {512+ yield* fs.makeDirectory(path.dirname(path.join(start, file)), {513+ recursive: true,514+ });515+ yield* fs.copyFile(path.join(example, file), path.join(start, file));516+ }517+ }518+519+ yield* gitOk(start, "init", "--quiet", "--initial-branch=main");520+ yield* gitOk(start, "add", "--all");521+ yield* gitOk(start, "commit", "--quiet", "--message", "Start datekit");522+ yield* inesGit.ok(start, "push", "--quiet", made.remote, "HEAD:main");523+524+ // The token, piped in as `printf '%s\n' "$TOKEN" |` gives it; then bram,525+ // a public item and a short value.526+ const setting = (key: string) => [527+ "env",528+ "set",529+ key,530+ "--project",531+ project,532+ "--yes",533+ ];534+535+ const set = yield* cli(world, ines, setting(token), `${value}\n`);536+ const byBram = yield* cli(world, bram, setting(token), `${value}\n`);537+538+ const publicItem = yield* cli(539+ world,540+ ines,541+ setting("APP_ENV"),542+ `${value}\n`543+ );544+545+ const tooShort = yield* cli(world, ines, setting(token), `${short}\n`);546+547+ const envView = yield* cli(world, ines, [548+ "env",549+ "shape",550+ "--project",551+ project,552+ "--json",553+ ]);554+555+ const ledger = yield* cli(world, ines, [556+ "ledger",557+ "--project",558+ project,559+ "--json",560+ ]);561+562+ // ines-v opens one of datekit's asks (red first on the world's563+ // Checker); bram claims it and pushes an answer to his claim's fork.564+ const files = yield* Effect.forEach(askFiles, (file) =>565+ Effect.map(fs.readFileString(path.join(example, file)), (content) => ({566+ content,567+ path: RepoPath.make(file),568+ }))569+ );570+571+ yield* asInes.openAsk({572+ ask,573+ files: Array.isReadonlyArrayNonEmpty(files)574+ ? files575+ : yield* Effect.die("the ask has no files"),576+ project,577+ });578+579+ const { claim } = yield* asBram.claim({ ask, project });580+ const work = path.join(home, "work");581+582+ yield* bramGit.ok(home, "clone", "--quiet", claim.remote, work);583+584+ const parse = path.join(work, "src", "parse.ts");585+586+ yield* fs.writeFileString(587+ parse,588+ `${yield* fs.readFileString(parse)}// Week dates next.\n`589+ );590+591+ yield* gitOk(592+ work,593+ "commit",594+ "--quiet",595+ "--all",596+ "--message",597+ "Read week dates"598+ );599+600+ const answered = yield* bramGit.run(work, "push", "origin", "HEAD:main");601+ const before = (yield* keptBy(world)).jobs.length;602+603+ yield* settle(world);604+605+ // Last, what MCP lists, then everything the world kept and printed.606+ const tools = yield* toolsListed(world, ines);607+ const kept = yield* keptBy(world);608+609+ return {610+ answerJobs: yield* decodeJobs(kept.jobs.slice(before)),611+ answered,612+ byBram,613+ envView,614+ kept,615+ ledger,616+ printed: yield* world.printed,617+ publicItem,618+ set,619+ tooShort,620+ tools,621+ };622+ }).pipe(Effect.orDie)623+).pipe(Layer.provide([NodeServices.layer, FetchHttpClient.layer]));624+625+// ------------------------------------------------------------------ tests626+627+const decodeEnvelope = <A extends Schema.Top>(data: A) =>628+ Schema.decodeUnknownEffect(Schema.fromJsonString(Envelope(data)));629+630+/** What a `--json` run printed: its one envelope's data, as encoded, if it was not refused. */631+const dataOf = (ran: Ran) =>632+ Effect.map(633+ decodeEnvelope(Schema.Unknown)(ran.out.join("\n")).pipe(Effect.orDie),634+ (printed) => (printed.ok ? printed.data : undefined)635+ );636+637+/** A run's lines, less the empty ones a trailing newline leaves. */638+const filled = (lines: readonly string[]) =>639+ lines.filter((line) => line.length > 0);640+641+/** Everything a run printed or logged, as one text. */642+const allOf = (ran: Ran) => [...ran.out, ...ran.err, ...ran.logged].join("\n");643+644+/**645+ * The value base64-encoded from `shift` bytes into a longer text, less the646+ * characters it shares there with its neighbours: what any base64 text647+ * holding the value at that alignment contains.648+ */649+const base64At = (shift: number) => {650+ const encoded = btoa(`${"\0".repeat(shift)}${value}`);651+652+ return encoded.slice(653+ shift === 0 ? 0 : 4,654+ (shift + value.length) % 3 === 0 ? encoded.length : encoded.length - 4655+ );656+};657+658+/**659+ * The value, and what base64 or base64url leaves of it wherever it starts660+ * inside an encoded text.661+ */662+const forms = [663+ value,664+ ...[0, 1, 2]665+ .map(base64At)666+ .flatMap((form) => [form, form.replaceAll("+", "-").replaceAll("/", "_")]),667+];668+669+/** Whether a text holds the value in any form. */670+const holds = (text: string) => forms.some((form) => text.includes(form));671+672+/** When the token was set, as the CLI printed it. */673+const setAtOf = (set: Ran) =>674+ / at (?<at>\S+Z)\. /u.exec(filled(set.out)[0] ?? "")?.groups?.at;675+676+/** A ledger's entries as encoded: each one's fields, whatever they are. */677+const Entries = Schema.Struct({678+ entries: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)),679+});680+681+/** The token's item in the env shape `env shape --json` printed, if it lists one. */682+const tokenItem = (envView: Ran) =>683+ Effect.map(684+ decodeEnvelope(EnvSchemaView)(envView.out.join("\n")).pipe(Effect.orDie),685+ (printed) =>686+ printed.ok687+ ? printed.data.items.find(({ key }) => key === token)688+ : undefined689+ );690+691+/** What unlanded code sees in place of the token: its key, made a placeholder. */692+const placeholder = `__${token}_PLACEHOLDER__`;693+694+layer(ScenarioOnce, { excludeTestServices: true, timeout: "240 seconds" })(695+ `${Brand.cli} env set against the platform's Node world, the visibility cartridge composed`,696+ (it) => {697+ it.effect(698+ "stores ines-v's piped token and prints one line naming the key, ines-v and a time",699+ () =>700+ Effect.gen(function* () {701+ const { set } = yield* Scenario;702+703+ expect({704+ code: set.code,705+ err: filled(set.err),706+ out: filled(set.out),707+ }).toStrictEqual({708+ code: 0,709+ err: [],710+ out: [711+ expect.stringMatching(712+ /^SENTRY_AUTH_TOKEN on datekit was set by ines-v at \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\. Nobody can read it back\.$/u713+ ),714+ ],715+ });716+ })717+ );718+719+ it.effect(720+ "shows who set the token and when in env shape and in the ledger, and nothing more of it",721+ () =>722+ Effect.gen(function* () {723+ const { envView, ledger, set } = yield* Scenario;724+ const item = yield* tokenItem(envView);725+ const at = setAtOf(set) ?? "never";726+727+ const data = yield* dataOf(ledger);728+ const { entries } = yield* Schema.decodeUnknownEffect(Ledger)(data);729+ const encoded = yield* Schema.decodeUnknownEffect(Entries)(data);730+731+ expect({732+ code: envView.code,733+ sensitive: item?.sensitive,734+ setAt: item?.value && DateTime.formatIso(item.value.setAt),735+ setBy: item?.value?.setBy,736+ }).toStrictEqual({737+ code: 0,738+ sensitive: true,739+ setAt: at,740+ setBy: "ines-v",741+ });742+ expect(entries).toStrictEqual([743+ LedgerEntry.cases.ValueSet.make({744+ at: DateTime.makeUnsafe(at),745+ by: ines.handle,746+ key: token,747+ seq: 1,748+ }),749+ ]);750+ // The entry is who, which key and when, numbered: no field holds more.751+ expect(752+ encoded.entries.map((entry) => Object.keys(entry).toSorted())753+ ).toStrictEqual([["_tag", "at", "by", "key", "seq"]]);754+ })755+ );756+757+ it.effect(758+ "leaves the value in no output, response body, log line, event, ledger entry or job, and the DO's row holds it sealed",759+ () =>760+ Effect.gen(function* () {761+ const scenario = yield* Scenario;762+ const { kept, printed, set } = scenario;763+764+ const runs = [765+ scenario.set,766+ scenario.byBram,767+ scenario.publicItem,768+ scenario.tooShort,769+ scenario.envView,770+ scenario.ledger,771+ ];772+773+ // Counts, so a failure never prints what it found.774+ expect({775+ bodies: kept.bodies.filter(holds).length,776+ cli: runs.filter((ran) => holds(allOf(ran))).length,777+ envValues: holds(JSON.stringify(kept.store?.envValues ?? null)),778+ events: holds(JSON.stringify(kept.store?.events ?? null)),779+ jobs: holds(JSON.stringify(kept.jobs)),780+ ledger: holds(JSON.stringify(kept.store?.ledger ?? null)),781+ logged: kept.logged.filter(holds).length,782+ printed: holds(printed),783+ }).toStrictEqual({784+ bodies: 0,785+ cli: 0,786+ envValues: false,787+ events: false,788+ jobs: false,789+ ledger: false,790+ logged: 0,791+ printed: false,792+ });793+794+ // What was searched holds what happened: the set's reply, its795+ // log line, its sealed row and its ledger event.796+ const reply = JSON.stringify({797+ key: token,798+ setAt: setAtOf(set),799+ setBy: "ines-v",800+ });801+802+ expect({803+ event: JSON.stringify(kept.store?.events ?? null).includes(804+ '"entry":{"_tag":"ValueSet"'805+ ),806+ logged: kept.logged.filter((line) =>807+ line.includes('"a write-only value was set"')808+ ),809+ printed: printed.includes("a write-only value was set"),810+ replies: kept.bodies.filter((body) => body.includes(reply)).length,811+ rows: kept.store?.envValues.map(812+ ({ key, sealed, setAt, setBy }) => ({813+ key,814+ sealed: Object.keys(sealed).length > 0,815+ setAt,816+ setBy,817+ })818+ ),819+ }).toStrictEqual({820+ event: true,821+ logged: [822+ `["a write-only value was set"] {"by":"ines-v","key":"${token}"}`,823+ ],824+ printed: true,825+ replies: 1,826+ rows: [827+ {828+ key: token,829+ sealed: true,830+ setAt: setAtOf(set),831+ setBy: "ines-v",832+ },833+ ],834+ });835+ })836+ );837+838+ it.effect(839+ "refuses bram, no decider, with NotDecider printed once and exit 1",840+ () =>841+ Effect.gen(function* () {842+ const { byBram } = yield* Scenario;843+844+ expect({845+ code: byBram.code,846+ err: filled(byBram.err),847+ out: filled(byBram.out),848+ }).toStrictEqual({849+ code: 1,850+ err: explain([new NotDecider({})]),851+ out: [],852+ });853+ })854+ );855+856+ it.effect(857+ "refuses a public item NotSensitive, and a short value ValueTooShort that tells neither the value nor its length",858+ () =>859+ Effect.gen(function* () {860+ const { publicItem, tooShort } = yield* Scenario;861+862+ expect({863+ publicItem: {864+ code: publicItem.code,865+ err: filled(publicItem.err),866+ out: filled(publicItem.out),867+ },868+ tooShort: {869+ code: tooShort.code,870+ err: filled(tooShort.err),871+ out: filled(tooShort.out),872+ },873+ }).toStrictEqual({874+ publicItem: {875+ code: 1,876+ err: explain([new NotSensitive({ key: EnvKey.make("APP_ENV") })]),877+ out: [],878+ },879+ tooShort: {880+ code: 1,881+ err: explain([ValueTooShort.of(token, 12)]),882+ out: [],883+ },884+ });885+ expect(allOf(tooShort)).not.toContain(short);886+ expect(allOf(tooShort)).not.toContain(String(short.length));887+ })888+ );889+890+ it.effect(891+ "gives the answer's checks the token's placeholder, and no value",892+ () =>893+ Effect.gen(function* () {894+ const { answerJobs, answered } = yield* Scenario;895+896+ expect(answered.exitCode).toBe(0);897+ expect(answered.stderr).toContain(`remote: checking ${ask} at `);898+ expect(answerJobs.map(({ repo }) => repo)).toContain(899+ `${project}--${ask}--${bram.handle}`900+ );901+ expect(902+ answerJobs.map((job) => ({903+ landed: job.landed ?? false,904+ placeholders: job.placeholders,905+ proxies: job.proxies,906+ values: job.values?.length ?? 0,907+ }))908+ ).toStrictEqual(909+ answerJobs.map(() => ({910+ landed: false,911+ placeholders: [{ key: token, placeholder }],912+ proxies: [913+ {914+ block: false,915+ host: "sentry.io",916+ key: token,917+ path: "/api/**",918+ placeholder,919+ },920+ ],921+ values: 0,922+ }))923+ );924+ })925+ );926+927+ it.effect(928+ "serves no setEnv tool over /mcp, where it serves the env shape's",929+ () =>930+ Effect.gen(function* () {931+ const { tools } = yield* Scenario;932+933+ expect(tools).toContain("envShape");934+ expect(tools).not.toContain("setEnv");935+ })936+ );937+ }938+);added:apps/platform/test/visibility/serve-cartridge-world.ts+307 added
1+/**2+ * The core loop's world (`../world.ts`) with the visibility cartridge3+ * plugged in as the Worker plugs it, as a process of its own that keeps4+ * what it served: `bun apps/platform/test/visibility/serve-cartridge-world.ts`5+ * prints one JSON line, `{"origin":"http://127.0.0.1:<port>","kept":"http://127.0.0.1:<port>"}`,6+ * once it serves, and serves until its stdin ends (the process that started7+ * it closed it, or died).8+ *9+ * - `origin` is the platform's fetch handler, as `../serve-world.ts` serves10+ * it; every body it answers with JSON or an event stream (the contracts'11+ * at `/rpc`, MCP's at `/mcp`) is kept as it went out.12+ * - `kept` is a test's window on the world: `POST /settle` carries every13+ * queued answer run (`world.settle`), and `GET /kept?project=<name>`14+ * answers, as JSON, every body kept, every line logged (the handler's and15+ * each Project DO's, with their annotations), every job the Checker was16+ * given, and the project's Durable Object store as its rows encode: its17+ * `env_values` and ledger rows and its event log.18+ *19+ * The cartridge is the Worker's (`../../src/visibility/live.ts`) for the20+ * world's stage, over the fake env's test `MASTER_KEY`, with the world's21+ * second store of bare repos as the private namespace; each Project DO22+ * gets its project state and its env. The Checker keeps each job and fails23+ * every lane the same way, so an ask's check is red first and an answer's24+ * checks run (and fail): what a job carries is what a test reads. Beside25+ * dora, alice and bob, the people in `WORLD_SESSIONS` (a JSON object from26+ * token to handle, as `SESSION_TOKENS` is) may call.27+ *28+ * A process, not an import: apps never import apps, and the CLI's29+ * end-to-end `env set` test (W6 616) runs it. It lives in the cartridge30+ * and goes with it. The Worker's modules import `cloudflare:workers`, which31+ * this file serves from `../workers-shim.ts` through Bun's runtime plugins32+ * before it loads them, as `../serve-world.ts` does.33+ */34+import { NodeRuntime, NodeServices } from "@effect/platform-node";35+import type { RepoHost } from "@repo/artifacts/repo-host";36+import { CheckJob, CheckRunner } from "@repo/checks/check-runner";37+import type { CheckRun } from "@repo/checks/check-runner";38+import {39+ EnvValueRow,40+ EventRow,41+ LedgerRow,42+} from "@repo/project/project-store/rows";43+import { ProjectName } from "@repo/protocol/ids";44+import { fakeArtifactsBinding } from "@repo/testkit/fake-artifacts-binding";45+import {46+ Config,47+ Console,48+ Effect,49+ Layer,50+ Logger,51+ Option,52+ References,53+ Schema,54+ Stdio,55+ Stream,56+} from "effect";57+58+import * as shim from "../workers-shim.ts";59+import type { PlugIn } from "../world.ts";60+61+/** Bun's runtime plugins, as far as this file uses them (the platform has no Bun types). */62+interface BunPlugins {63+ readonly plugin: (plugin: {64+ readonly name: string;65+ readonly setup: (build: {66+ readonly module: (67+ specifier: string,68+ load: () => {69+ readonly exports: typeof shim;70+ readonly loader: "object";71+ }72+ ) => void;73+ }) => void;74+ }) => void;75+}76+77+declare const Bun: BunPlugins;78+79+/** `cloudflare:workers` served from the shim, for every module loaded after. */80+const shimWorkers = Effect.sync(() => {81+ Bun.plugin({82+ name: "cloudflare-workers-shim",83+ setup: (build) => {84+ build.module("cloudflare:workers", () => ({85+ exports: { ...shim },86+ loader: "object",87+ }));88+ },89+ });90+});91+92+/** Where the private namespace's stand-in says its repos are. */93+const PRIVATE_REMOTES = "https://artifacts.private.test";94+95+/**96+ * The Checker: each job kept as it came, and every lane failed the same97+ * way, a count lane printing nothing.98+ */99+const keepingChecker = (jobs: CheckJob[]): Layer.Layer<CheckRunner> =>100+ Layer.succeed(101+ CheckRunner,102+ CheckRunner.of({103+ run: (job) =>104+ Effect.sync((): CheckRun => {105+ jobs.push(job);106+107+ return {108+ durationMs: job.lanes.length,109+ evidence: job.lanes.map(({ lane }) => ({110+ lane,111+ signature: `${lane}: failed`,112+ })),113+ heldBack: [],114+ lanes: job.lanes.map(({ command, lane }) => ({115+ command,116+ durationMs: 1,117+ lane,118+ result: "failed",119+ })),120+ outputs: job.lanes121+ .filter(({ output }) => output === "stdout")122+ .map(({ lane }) => ({ lane, stdout: "" })),123+ };124+ }),125+ })126+ );127+128+const decodeSessions = Schema.decodeUnknownEffect(129+ Schema.fromJsonString(Schema.Record(Schema.String, Schema.String))130+);131+132+/**133+ * Each job as the Checker got it, encoded by its fields alone: without134+ * `CheckJob`'s rule that only landed code carries values, so a job that135+ * breaks the rule still shows, values and all, for a test to refuse.136+ */137+const encodeJobs = Schema.encodeEffect(138+ Schema.Array(Schema.Struct(CheckJob.fields))139+);140+141+const encodeStore = Schema.encodeEffect(142+ Schema.Struct({143+ envValues: Schema.Array(EnvValueRow),144+ events: Schema.Array(EventRow),145+ ledger: Schema.Array(LedgerRow),146+ })147+);148+149+/**150+ * Whether a response is a contract's or a tool's reply: JSON, or an MCP151+ * event stream. Git's packs and adverts are not, and neither is NDJSON,152+ * which only a framed `watch` gets and which never ends while it follows.153+ */154+const isReply = (response: Response) => {155+ const type = response.headers.get("content-type") ?? "";156+157+ return (158+ (type.includes("json") && !type.includes("ndjson")) ||159+ type.includes("text/event-stream")160+ );161+};162+163+const serve = Effect.gen(function* () {164+ yield* shimWorkers;165+166+ const raw = yield* Config.String("WORLD_SESSIONS").pipe(167+ Config.withDefault("{}")168+ );169+170+ const sessions = yield* decodeSessions(raw).pipe(171+ Effect.catch(() =>172+ Effect.die("WORLD_SESSIONS is not a JSON object from token to handle")173+ )174+ );175+176+ // Loaded after the shim: each reaches `cloudflare:workers`.177+ const [178+ { coreLoopWorld, listen },179+ { fakeEnv },180+ { decodeEnv },181+ { live },182+ { stateLive },183+ { envLive },184+ ] = yield* Effect.promise(() =>185+ Promise.all([186+ import("../world.ts"),187+ import("../fake-env.ts"),188+ import("../../src/platform.ts"),189+ import("../../src/visibility/live.ts"),190+ import("../../src/visibility/state.ts"),191+ import("../../src/visibility/env.ts"),192+ ])193+ );194+195+ /** The world's stage config, the second store standing in for the private namespace. */196+ const configOver = (aside: RepoHost["Service"]) =>197+ decodeEnv({198+ ...fakeEnv(),199+ ARTIFACTS_PRIVATE: fakeArtifactsBinding(aside, {200+ remoteBase: PRIVATE_REMOTES,201+ }),202+ }).pipe(Effect.orDie);203+204+ /**205+ * The cartridge as the Worker plugs it: whole over the Worker's ports, and206+ * the project service's part of it (its visibility state and its env)207+ * over each Project DO's, which reach no other DO.208+ */209+ const plugIn = (aside: RepoHost["Service"]): PlugIn => ({210+ project: Layer.unwrap(211+ Effect.map(configOver(aside), (config) =>212+ Layer.mergeAll(stateLive(config), envLive(config))213+ )214+ ),215+ worker: Layer.unwrap(Effect.map(configOver(aside), live)),216+ });217+218+ const jobs: CheckJob[] = [];219+ const bodies: string[] = [];220+ // What the Project DOs and everything else in this process logged.221+ const lines: string[] = [];222+223+ // Each line as its message and its annotations, both JSON.224+ const keeper = Logger.make(({ fiber, message }) => {225+ const annotations = fiber.getRef(References.CurrentLogAnnotations);226+227+ lines.push(`${JSON.stringify(message)} ${JSON.stringify(annotations)}`);228+ });229+230+ const world = yield* coreLoopWorld({231+ checker: () => keepingChecker(jobs),232+ plugIn,233+ sessions,234+ }).pipe(Effect.provide(Logger.layer([keeper], { mergeWithExisting: true })));235+236+ const origin = yield* listen((request) =>237+ Effect.gen(function* () {238+ const response = yield* world.fetch(request);239+240+ if (isReply(response)) {241+ bodies.push(yield* Effect.promise(() => response.clone().text()));242+ }243+244+ return response;245+ })246+ );247+248+ /** What the world kept, for `project`'s store. */249+ const keptFor = (project: ProjectName) =>250+ Effect.gen(function* () {251+ const logged = yield* world.logged;252+ const stored = yield* world.stored(project);253+254+ return {255+ bodies,256+ jobs: yield* encodeJobs(jobs),257+ logged: [258+ ...logged.map(259+ ({ annotations, message }) =>260+ `${JSON.stringify(message)} ${JSON.stringify(Object.fromEntries(annotations))}`261+ ),262+ ...lines,263+ ],264+ store: Option.isSome(stored)265+ ? yield* encodeStore({266+ envValues: stored.value.rows.envValues,267+ events: stored.value.events,268+ ledger: stored.value.rows.ledger,269+ })270+ : null,271+ };272+ }).pipe(Effect.orDie);273+274+ const kept = yield* listen((request) =>275+ Effect.gen(function* () {276+ const url = new URL(request.url);277+278+ if (request.method === "POST" && url.pathname === "/settle") {279+ yield* world.settle();280+281+ return new Response(null, { status: 204 });282+ }283+284+ const project = url.searchParams.get("project");285+286+ if (287+ request.method === "GET" &&288+ url.pathname === "/kept" &&289+ project !== null290+ ) {291+ return Response.json(yield* keptFor(ProjectName.make(project)));292+ }293+294+ return new Response(null, { status: 404 });295+ })296+ );297+298+ yield* Console.log(JSON.stringify({ kept, origin }));299+300+ const stdio = yield* Stdio.Stdio;301+302+ yield* Stream.runDrain(stdio.stdin);303+});304+305+NodeRuntime.runMain(306+ serve.pipe(Effect.scoped, Effect.provide(NodeServices.layer))307+);modified:apps/platform/test/world.ts+45 added-15 removed
29 unmodified lines30 * the private namespace's stand-in, for W6's layer repos.31 *32 * Every log line the Worker's handler writes is kept beside its usual33 * printing, with its annotations (`logged`), and each Project DO's SQLite34- * stays reachable (`ratchets` reads its `ratchets` rows through the store).34+ * stays reachable through the store (`ratchets` reads its `ratchets` rows,35+ * `stored` all its rows and its event log).36 */37 import { NodeHttpServer, NodeServices } from "@effect/platform-node";38 import { SqliteClient } from "@effect/sql-sqlite-node";39 import { RefName, RepoHost } from "@repo/artifacts/repo-host";10 unmodified lines50 import { Lander } from "@repo/project/lander";51 import { LanderIsogit } from "@repo/project/lander/isogit";52 import { FinishersFromChecks } from "@repo/project/project";53 import { ProjectStore } from "@repo/project/project-store";54+import type { ProjectSnapshot } from "@repo/project/project-store";53-import type { RatchetRow } from "@repo/project/project-store/rows";55+import type { EventRow, RatchetRow } from "@repo/project/project-store/rows";56 import { ProjectStoreSqlite } from "@repo/project/project-store/sqlite";57 import { ProjectionMemory } from "@repo/project/projection/memory";58 import type { Projects } from "@repo/project/projects";59 import { Contracts } from "@repo/protocol/contracts";119 unmodified lines179 /** A project's ratchet baselines, as its Durable Object's store keeps them. */180 readonly ratchets: (181 project: ProjectName182 ) => Effect.Effect<readonly RatchetRow[]>;183+ /**184+ * A project's rows and its whole event log, as its Durable Object's store185+ * keeps them; none before anyone called it.186+ */187+ readonly stored: (project: ProjectName) => Effect.Effect<188+ Option.Option<{189+ readonly rows: ProjectSnapshot;190+ readonly events: readonly EventRow[];191+ }>192+ >;193 /** A client of the contracts over HTTP at `/rpc`, as that person (or as anyone). */194 readonly rpc: (as: Someone | "anonymous") => Client["Service"];195 /**196 * Someone `sessions` names, by handle: their git, whose credential helper32 unmodified lines229 * Serves `handle` on a local port for as long as the scope lasts, each230 * request as Node's server hands it over made a plain `Request`, and returns231 * its origin.232 */221-const listen = (handle: (request: Request) => Effect.Effect<Response>) =>233+export const listen = (handle: (request: Request) => Effect.Effect<Response>) =>234 Effect.gen(function* () {235 const app = Effect.gen(function* () {236 const request = yield* HttpServerRequest.HttpServerRequest;237 const web = yield* HttpServerRequest.toWeb(request);166 unmodified lines404 405 // Each DO's database, kept so a test can read its rows back.406 const databases = new Map<string, Context.Context<SqlClient>>();407 408+ /** `read` over a project's DO store; none before anyone called the DO. */409+ const readStore = <A>(410+ project: ProjectName,411+ read: (store: ProjectStore["Service"]) => Effect.Effect<A>412+ ): Effect.Effect<Option.Option<A>> =>413+ Option.match(Option.fromUndefinedOr(databases.get(project)), {414+ onNone: () => Effect.succeedNone,415+ onSome: (sql) =>416+ ProjectStore.use(read).pipe(417+ Effect.asSome,418+ Effect.provide(419+ ProjectStoreSqlite.pipe(Layer.provide(Layer.succeedContext(sql)))420+ )421+ ),422+ });423+424 // The `PROJECT` namespace in process: a name is one DO, made on its425 // first call, a shell over a database of its own, living in the world's426 // scope.427 const { namespace } = yield* inProcessNamespace((name) =>252 unmodified lines680 Effect.sync(() => {681 printed.set(scriptKey(at, lane), stdout);682 }),683 ratchets: (project) =>656- Option.match(Option.fromUndefinedOr(databases.get(project)), {657- onNone: () => Effect.succeed([]),658- onSome: (sql) =>659- ProjectStore.use((store) => store.load()).pipe(660- Effect.map(({ ratchets }) => ratchets),661- Effect.provide(662- ProjectStoreSqlite.pipe(663- Layer.provide(Layer.succeedContext(sql))664- )665- )666- ),667- }),684+ Effect.map(685+ readStore(project, (store) => store.load()),686+ Option.match({687+ onNone: () => [],688+ onSome: ({ ratchets }) => ratchets,689+ })690+ ),691 rpc: (as) => clients[as],692 script: (at, lane, results) =>693 Effect.sync(() => {694 script.set(6 unmodified lines701 }))702 );703 }),704 settle: () => carry(0),705+ stored: (project) =>706+ readStore(project, (store) =>707+ Effect.all({708+ events: store.eventsSince(0, Number.MAX_SAFE_INTEGER),709+ rows: store.load(),710+ })711+ ),712 };713 });modified:turbo.json+15 added
41 unmodified lines42434445464748495051525354555657585960616263643 unmodified lines41 unmodified lines "!$TURBO_ROOT$/examples/*/.env*" ], "outputs": [] }, "@repo/cli#test": { "dependsOn": ["types", "^types"], "env": ["UPDATE_GOLDEN"], "inputs": [ "$TURBO_DEFAULT$", "$TURBO_ROOT$/apps/platform/src/**", "$TURBO_ROOT$/apps/platform/test/**", "$TURBO_ROOT$/packages/*/src/**", "$TURBO_ROOT$/examples/datekit/**", "!$TURBO_ROOT$/examples/datekit/.env", "!$TURBO_ROOT$/examples/datekit/.env.local", "!$TURBO_ROOT$/examples/datekit/.env.*.local" ], "outputs": [] }, "@repo/config#test": { "cache": false, "dependsOn": ["types", "^types"], "outputs": []3 unmodified lines