Merge branch 'build/715-release'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents c38b722, 981905b · Browse files · 6 files·+2308 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+2308 added−14 removed
- tests:+693 added−0 removed
- other:+1615 added−14 removed
Provenance
- Commit
918a2c1- Tree
736bd37- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
c38b722- Parent 2
981905b
6 files changed+2308 added−14 removed
added:packages/config/test/release.test.ts+693 added
1+/**2+ * The release (issue 715): the CLI's npm package says what it is from3+ * `Brand` alone, a release builds for exactly two machines, only a person4+ * publishes, and what goes to the platform's own release storage is what5+ * the platform decodes and serves (issue 420).6+ */7+import { NodeServices } from "@effect/platform-node";8+import { describe, expect, it } from "@effect/vitest";9+import {10+ Array as Arr,11+ Crypto,12+ Effect,13+ FileSystem,14+ Option,15+ Order,16+ Path,17+ Result,18+ Schema,19+ Stream,20+} from "effect";21+import { ChildProcess, ChildProcessSpawner } from "effect/process";22+23+import { ReleaseManifest } from "../../../apps/platform/src/releases.ts";24+import { NoStage, UnknownStage } from "../../../infra/stages.ts";25+import {26+ agentMarkers,27+ checksumsFile,28+ importedPackages,29+ installScript,30+ namedFiles,31+ pinnedDependencies,32+ publishManifest,33+ PublishNeedsAPerson,34+ releaseManifest,35+ releasePlan,36+ releaseRun,37+ releaseVersion,38+ targets,39+ Unpinned,40+ unreleased,41+ uploads,42+ VersionNeeded,43+ VersionReleased,44+} from "../../../scripts/lib/release.ts";45+import { Brand } from "../../brand/src/index.ts";46+import { repoRoot } from "./root.ts";47+48+/** What the test reads of a package manifest. */49+const PackageJson = Schema.fromJsonString(50+ Schema.Struct({51+ dependencies: Schema.optionalKey(52+ Schema.Record(Schema.String, Schema.String)53+ ),54+ workspaces: Schema.optionalKey(55+ Schema.Struct({56+ catalog: Schema.optionalKey(57+ Schema.Record(Schema.String, Schema.String)58+ ),59+ })60+ ),61+ })62+);63+64+const runtime = { "@effect/platform-bun": "4.0.1", effect: "4.0.1" };65+66+describe("the npm package's manifest", () => {67+ const manifest = publishManifest(Brand, {68+ dependencies: runtime,69+ version: "0.1.0",70+ });71+72+ it("is the brand's CLI package, with both names as bins", () => {73+ expect({74+ bin: manifest.bin,75+ license: manifest.license,76+ name: manifest.name,77+ version: manifest.version,78+ }).toStrictEqual({79+ bin: {80+ [Brand.cli]: "./dist/bin.js",81+ [Brand.gitCredentialHelper]: "./dist/bin.js",82+ },83+ license: "MIT",84+ name: Brand.cliPackage,85+ version: "0.1.0",86+ });87+ });88+89+ it("exports the command line, the sdk a config folder imports, and its types", () => {90+ expect(manifest.exports).toStrictEqual({91+ ".": "./dist/bin.js",92+ "./protocol": {93+ default: "./dist/protocol.js",94+ types: "./dist/protocol.d.ts",95+ },96+ "./rules": { default: "./dist/rules.js", types: "./dist/rules.d.ts" },97+ });98+ });99+100+ it("lists each library entry's types first and its code last, the order Node and TypeScript match conditions in", () => {101+ expect(102+ [manifest.exports["./rules"], manifest.exports["./protocol"]].map(103+ (entry) => Object.keys(entry ?? {})104+ )105+ ).toStrictEqual([106+ ["types", "default"],107+ ["types", "default"],108+ ]);109+ });110+111+ it("is a pi package whose host is an optional peer, never a dependency", () => {112+ expect({113+ dependencies: manifest.dependencies,114+ keywords: manifest.keywords.includes("pi-package"),115+ peerDependencies: manifest.peerDependencies,116+ peerDependenciesMeta: manifest.peerDependenciesMeta,117+ pi: manifest.pi,118+ }).toStrictEqual({119+ dependencies: runtime,120+ keywords: true,121+ peerDependencies: { "@earendil-works/pi-coding-agent": "*" },122+ peerDependenciesMeta: {123+ "@earendil-works/pi-coding-agent": { optional: true },124+ },125+ pi: { extensions: ["./dist/pi.js"], skills: ["./skills"] },126+ });127+ });128+129+ it("ships the build, the platform's skill, a README and the licence", () => {130+ expect(manifest.files).toStrictEqual([131+ "dist/",132+ "skills/",133+ "README.md",134+ "LICENSE",135+ ]);136+ });137+});138+139+/** The top of a tsdown build, as rolldown writes it, with prose that only looks like imports. */140+const built = [141+ "#!/usr/bin/env node",142+ 'import { createRequire } from "node:module";',143+ 'import { BunRuntime, BunServices } from "@effect/platform-bun";',144+ 'import { Effect, Schema } from "effect";',145+ 'import { Command, Flag } from "effect/cli";',146+ 'import "./chunk-a1.js";',147+ "/**",148+ ' * `import("x")` and `require("x")`, and `… from "y"`.',149+ " */",150+ 'const source = `import { project } from "some-sdk/rules";`;',151+ "",152+].join("\n");153+154+describe("the npm package's dependencies", () => {155+ it("are the packages the build imports, by package name", () => {156+ expect(importedPackages(built)).toStrictEqual([157+ "@effect/platform-bun",158+ "effect",159+ ]);160+ });161+162+ it.live(163+ "are pinned from the CLI's own manifest and the catalog, with no workspace package",164+ () =>165+ Effect.gen(function* () {166+ const fs = yield* FileSystem.FileSystem;167+ const path = yield* Path.Path;168+ const root = yield* repoRoot;169+170+ const read = (file: string) =>171+ fs172+ .readFileString(path.join(root, file))173+ .pipe(Effect.flatMap(Schema.decodeEffect(PackageJson)));174+175+ const cli = yield* read("apps/cli/package.json");176+ const workspace = yield* read("package.json");177+178+ const pinned = pinnedDependencies({179+ catalog: workspace.workspaces?.catalog ?? {},180+ declared: cli.dependencies ?? {},181+ imported: importedPackages(built),182+ });183+184+ expect(185+ Result.map(pinned, (dependencies) => ({186+ exact: Object.values(dependencies).every((version) =>187+ /^\d+\.\d+\.\d+$/u.test(version)188+ ),189+ names: Object.keys(dependencies),190+ }))191+ ).toStrictEqual(192+ Result.succeed({193+ exact: true,194+ names: ["@effect/platform-bun", "effect"],195+ })196+ );197+ }).pipe(Effect.provide(NodeServices.layer))198+ );199+200+ it("refuses a package the build imports that the CLI doesn't declare, or one from the workspace", () => {201+ expect(202+ pinnedDependencies({203+ catalog: { effect: "4.0.1" },204+ declared: { "@repo/brand": "workspace:*", effect: "catalog:" },205+ imported: ["@repo/brand", "effect", "yaml"],206+ })207+ ).toStrictEqual(208+ Result.fail(new Unpinned({ packages: ["@repo/brand", "yaml"] }))209+ );210+ });211+212+ it("leave out pi, which the pi adapter imports from its host, never from a dependency", () => {213+ expect(214+ pinnedDependencies({215+ catalog: { effect: "4.0.1" },216+ declared: { effect: "catalog:" },217+ imported: ["@earendil-works/pi-coding-agent", "effect"],218+ })219+ ).toStrictEqual(Result.succeed({ effect: "4.0.1" }));220+ });221+});222+223+describe("a release's plan", () => {224+ it("builds for exactly linux-x64 and darwin-arm64", () => {225+ expect(targets).toStrictEqual(["bun-linux-x64", "bun-darwin-arm64"]);226+ });227+228+ it("reads an agent from any harness's marker in the env, and nothing else", () => {229+ expect({230+ agent: agentMarkers({231+ AI_AGENT: "",232+ CLAUDECODE: "1",233+ HOME: "/home/someone",234+ PI_SESSION_ID: "s1",235+ }),236+ person: agentMarkers({ HOME: "/home/someone", PATH: "/usr/bin" }),237+ }).toStrictEqual({ agent: ["CLAUDECODE", "PI_SESSION_ID"], person: [] });238+ });239+240+ it("refuses to publish under an agent, naming what marked it", () => {241+ expect(242+ releasePlan({243+ build: false,244+ env: { CLAUDECODE: "1" },245+ publish: true,246+ upload: false,247+ })248+ ).toStrictEqual(249+ Result.fail(new PublishNeedsAPerson({ markers: ["CLAUDECODE"] }))250+ );251+ });252+253+ it("under an agent, still runs every other step it was asked for, and hands only the publish to a person", () => {254+ expect({255+ agent: releaseRun({256+ build: true,257+ env: { CLAUDECODE: "1" },258+ publish: true,259+ stage: "demo",260+ upload: true,261+ }),262+ alone: releaseRun({263+ build: false,264+ env: { CLAUDECODE: "1" },265+ publish: true,266+ upload: false,267+ }),268+ person: releaseRun({269+ build: false,270+ env: {},271+ publish: true,272+ upload: false,273+ }),274+ }).toStrictEqual({275+ agent: Result.succeed({276+ handOver: ["CLAUDECODE"],277+ steps: [278+ "tsdown",279+ "manifest",280+ "copySkills",281+ "compile",282+ "installScript",283+ "checksums",284+ "upload",285+ ],286+ }),287+ alone: Result.succeed({ handOver: ["CLAUDECODE"], steps: [] }),288+ person: Result.succeed({ handOver: [], steps: ["publish"] }),289+ });290+ });291+292+ it("refuses an unknown stage under an agent too, before it hands anything over", () => {293+ expect(294+ releaseRun({295+ build: false,296+ env: { CLAUDECODE: "1" },297+ publish: true,298+ stage: "prod",299+ upload: true,300+ })301+ ).toStrictEqual(Result.fail(new UnknownStage({ stage: "prod" })));302+ });303+304+ it("publishes last when a person runs it", () => {305+ expect(306+ Result.map(307+ releasePlan({ build: false, env: {}, publish: true, upload: false }),308+ Arr.last309+ )310+ ).toStrictEqual(Result.succeed(Option.some("publish")));311+ });312+313+ it("builds the package and the binaries, and writes the install script and checksums", () => {314+ expect(315+ releasePlan({ build: true, env: {}, publish: false, upload: false })316+ ).toStrictEqual(317+ Result.succeed([318+ "tsdown",319+ "manifest",320+ "copySkills",321+ "compile",322+ "installScript",323+ "checksums",324+ ])325+ );326+ });327+328+ it("uploads to a stage's own release storage after the checksums", () => {329+ expect(330+ releasePlan({331+ build: true,332+ env: {},333+ publish: true,334+ stage: "demo",335+ upload: true,336+ })337+ ).toStrictEqual(338+ Result.succeed([339+ "tsdown",340+ "manifest",341+ "copySkills",342+ "compile",343+ "installScript",344+ "checksums",345+ "upload",346+ "publish",347+ ])348+ );349+ });350+351+ it("uploads what was built, for the stage's own origin", () => {352+ expect(353+ releasePlan({354+ build: false,355+ env: { CLAUDECODE: "1" },356+ publish: false,357+ stage: "dev-oscabriel",358+ upload: true,359+ })360+ ).toStrictEqual(Result.succeed(["installScript", "checksums", "upload"]));361+ });362+363+ it("names its version when it uploads or publishes, and only a version the platform serves", () => {364+ expect({365+ build: releaseVersion({ publish: false, upload: false }),366+ named: releaseVersion({367+ publish: true,368+ upload: true,369+ version: "0.2.0-rc.1",370+ }),371+ unnamed: releaseVersion({ publish: false, upload: true }),372+ wrong: releaseVersion({373+ publish: false,374+ upload: true,375+ version: "latest",376+ }),377+ }).toStrictEqual({378+ build: Result.succeed("0.0.0"),379+ named: Result.succeed("0.2.0-rc.1"),380+ unnamed: Result.fail(new VersionNeeded({})),381+ wrong: Result.fail(new VersionNeeded({ given: "latest" })),382+ });383+ });384+385+ it("refuses an upload to a stage the repo doesn't declare, or to none", () => {386+ expect({387+ none: releasePlan({388+ build: false,389+ env: {},390+ publish: false,391+ upload: true,392+ }),393+ unknown: releasePlan({394+ build: false,395+ env: {},396+ publish: false,397+ stage: "prod",398+ upload: true,399+ }),400+ }).toStrictEqual({401+ none: Result.fail(new NoStage()),402+ unknown: Result.fail(new UnknownStage({ stage: "prod" })),403+ });404+ });405+});406+407+/** A digest, as `sha256sum` prints one. */408+const digest = (fill: string) => fill.repeat(64);409+410+const first = {411+ latest: "0.1.0",412+ versions: {413+ "0.1.0": {414+ assets: {415+ [`${Brand.slug}-darwin-arm64`]: {416+ bytes: 62_722_290,417+ sha256: digest("a"),418+ },419+ [`${Brand.slug}-linux-x64`]: { bytes: 81_806_816, sha256: digest("b") },420+ },421+ },422+ },423+};424+425+const second = {426+ "install.sh": { bytes: 2048, sha256: digest("c") },427+ [`${Brand.slug}-darwin-arm64`]: { bytes: 62_800_000, sha256: digest("d") },428+ [`${Brand.slug}-linux-x64`]: { bytes: 81_900_000, sha256: digest("e") },429+};430+431+describe("the release manifest", () => {432+ it.effect(433+ "keeps every earlier version, makes the new one latest, and is what the platform decodes",434+ () =>435+ Effect.gen(function* () {436+ const manifest = releaseManifest({437+ assets: second,438+ previous: first,439+ version: "0.2.0",440+ });441+442+ expect(443+ yield* Schema.decodeEffect(ReleaseManifest)(manifest)444+ ).toStrictEqual({445+ latest: "0.2.0",446+ versions: { ...first.versions, "0.2.0": { assets: second } },447+ });448+ })449+ );450+451+ it("starts the list with the first release", () => {452+ expect(453+ releaseManifest({ assets: second, previous: undefined, version: "0.1.0" })454+ ).toStrictEqual({455+ latest: "0.1.0",456+ versions: { "0.1.0": { assets: second } },457+ });458+ });459+460+ it("refuses to release a version again with other bytes, since its files are cached for good", () => {461+ expect({462+ again: unreleased({463+ assets: first.versions["0.1.0"].assets,464+ previous: first,465+ version: "0.1.0",466+ }),467+ changed: unreleased({468+ assets: second,469+ previous: first,470+ version: "0.1.0",471+ }),472+ next: unreleased({ assets: second, previous: first, version: "0.2.0" }),473+ }).toStrictEqual({474+ again: Result.void,475+ changed: Result.fail(new VersionReleased({ version: "0.1.0" })),476+ next: Result.void,477+ });478+ });479+});480+481+/** A file's digest as `sha256sum` prints it. */482+const sha256 = (content: string) =>483+ Effect.flatMap(Crypto.Crypto, (crypto) =>484+ crypto.digest("SHA-256", new TextEncoder().encode(content))485+ ).pipe(486+ Effect.map((bytes) =>487+ [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("")488+ ),489+ Effect.provide(NodeServices.layer)490+ );491+492+const origin = "https://platform-demo.example.workers.dev";493+494+const base = `${origin}/releases/0.1.0`;495+496+describe("the install script", () => {497+ const script = installScript({498+ baseUrl: base,499+ brand: Brand,500+ version: "0.1.0",501+ });502+503+ it("fetches the release and its checksums from the platform, and never from GitHub", () => {504+ expect({505+ base: script.includes(`'${base}'`),506+ checksums: script.includes('"$base/SHA256SUMS"'),507+ github: /github/iu.test(script),508+ posix: script.startsWith("#!/bin/sh\n"),509+ }).toStrictEqual({510+ base: true,511+ checksums: true,512+ github: false,513+ posix: true,514+ });515+ });516+517+ /**518+ * A machine to install on: a `curl` that serves `files` for the release's519+ * URLs and fails any other, a home folder, and `sh` to run the script.520+ */521+ const install = (files: Readonly<Record<string, string>>) =>522+ Effect.gen(function* () {523+ const fs = yield* FileSystem.FileSystem;524+ const path = yield* Path.Path;525+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;526+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "install-715-" });527+ const served = path.join(dir, "served");528+ const tools = path.join(dir, "tools");529+ const home = path.join(dir, "home");530+531+ yield* Effect.forEach([served, tools, home], (folder) =>532+ fs.makeDirectory(folder, { recursive: true })533+ );534+535+ yield* Effect.forEach(Object.entries(files), ([name, content]) =>536+ fs.writeFileString(path.join(served, name), content)537+ );538+539+ yield* fs.writeFileString(540+ path.join(tools, "curl"),541+ [542+ "#!/bin/sh",543+ 'out=""; url=""',544+ "while [ $# -gt 0 ]; do",545+ ' case "$1" in -o) out="$2"; shift 2 ;; -*) shift ;; *) url="$1"; shift ;; esac',546+ "done",547+ 'case "$url" in "$RELEASE_BASE"/*) ;; *) exit 22 ;; esac',548+ 'name="$(basename "$url")"',549+ '[ -f "$SERVED/$name" ] || exit 22',550+ 'cp "$SERVED/$name" "$out"',551+ "",552+ ].join("\n")553+ );554+555+ yield* fs.chmod(path.join(tools, "curl"), 0o755);556+ yield* fs.writeFileString(path.join(dir, "install.sh"), script);557+558+ const child = yield* spawner.spawn(559+ ChildProcess.make("sh", [path.join(dir, "install.sh")], {560+ env: {561+ HOME: home,562+ PATH: `${tools}:/usr/bin:/bin`,563+ RELEASE_BASE: base,564+ SERVED: served,565+ },566+ extendEnv: false,567+ })568+ );569+570+ const [stderr, exitCode] = yield* Effect.all(571+ [Stream.mkString(Stream.decodeText(child.stderr)), child.exitCode],572+ { concurrency: "unbounded" }573+ );574+575+ const bin = path.join(home, ".local", "bin");576+577+ const installed = (yield* fs.exists(bin))578+ ? Arr.sort(yield* fs.readDirectory(bin), Order.String)579+ : [];580+581+ return {582+ exitCode: Number(exitCode),583+ helper: installed.includes(Brand.gitCredentialHelper)584+ ? yield* fs.readLink(path.join(bin, Brand.gitCredentialHelper))585+ : "",586+ installed,587+ stderr,588+ };589+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));590+591+ /** A binary for each machine a release builds for, as a tiny script. */592+ const binaries = Object.fromEntries(593+ ["linux-x64", "darwin-arm64"].map((target) => [594+ `${Brand.slug}-${target}`,595+ `#!/bin/sh\necho ${target}\n`,596+ ])597+ );598+599+ /** `SHA256SUMS` for the binaries, each digest as `digestOf` gives it. */600+ const sums = <E, R>(601+ digestOf: (content: string) => Effect.Effect<string, E, R>602+ ) =>603+ Effect.map(604+ Effect.forEach(Object.entries(binaries), ([name, content]) =>605+ Effect.map(digestOf(content), (sum) => `${sum} ${name}\n`)606+ ),607+ (lines) => lines.join("")608+ );609+610+ it.live(611+ "installs the binary that matches SHA256SUMS, with git's credential helper beside it",612+ () =>613+ Effect.gen(function* () {614+ const ran = yield* install({615+ ...binaries,616+ SHA256SUMS: yield* sums(sha256),617+ });618+619+ expect({ ...ran, stderr: ran.stderr.trim() }).toStrictEqual({620+ exitCode: 0,621+ helper: Brand.cli,622+ installed: Arr.sort(623+ [Brand.cli, Brand.gitCredentialHelper],624+ Order.String625+ ),626+ stderr: "",627+ });628+ })629+ );630+631+ it.live("installs nothing when the download doesn't match SHA256SUMS", () =>632+ Effect.gen(function* () {633+ const ran = yield* install({634+ ...binaries,635+ SHA256SUMS: yield* sums(() => Effect.succeed(digest("0"))),636+ });637+638+ expect({639+ exitCode: ran.exitCode,640+ installed: ran.installed,641+ said: ran.stderr.includes("does not match SHA256SUMS"),642+ }).toStrictEqual({ exitCode: 1, installed: [], said: true });643+ })644+ );645+});646+647+describe("what a release hands the platform", () => {648+ it("lists each file's digest as sha256sum does, sorted by name", () => {649+ expect(checksumsFile(second)).toStrictEqual(650+ [651+ `${digest("c")} install.sh`,652+ `${digest("d")} ${Brand.slug}-darwin-arm64`,653+ `${digest("e")} ${Brand.slug}-linux-x64`,654+ "",655+ ].join("\n")656+ );657+ });658+659+ it("uploads every file of the version first and the manifest last, so it never names a missing file", () => {660+ expect(661+ uploads({ files: Object.keys(second), version: "0.2.0" })662+ ).toStrictEqual([663+ { file: "install.sh", key: "releases/0.2.0/install.sh" },664+ {665+ file: `${Brand.slug}-darwin-arm64`,666+ key: `releases/0.2.0/${Brand.slug}-darwin-arm64`,667+ },668+ {669+ file: `${Brand.slug}-linux-x64`,670+ key: `releases/0.2.0/${Brand.slug}-linux-x64`,671+ },672+ { file: "manifest.json", key: "releases/manifest.json" },673+ ]);674+ });675+676+ it("names every file the npm package's manifest points at, so a package missing one is never published", () => {677+ expect(678+ namedFiles(679+ publishManifest(Brand, { dependencies: runtime, version: "0.1.0" })680+ )681+ ).toStrictEqual([682+ "LICENSE",683+ "README.md",684+ "dist/bin.js",685+ "dist/pi.js",686+ "dist/protocol.d.ts",687+ "dist/protocol.js",688+ "dist/rules.d.ts",689+ "dist/rules.js",690+ "skills",691+ ]);692+ });693+});added:scripts/lib/release/install-script.ts+113 added
1+/**2+ * The install script the platform serves at `<origin>/install.sh` (issue3+ * 420), as the release writes it for one version and one origin (issue4+ * 715): `curl -fsSL <origin>/install.sh | sh`. POSIX `sh`, so it runs on5+ * Linux and macOS as they come. It downloads the binary for the machine6+ * from the platform, checks it against the release's `SHA256SUMS` from the7+ * same place, and installs nothing unless the two agree.8+ */9+import type { Brand } from "@repo/brand";10+11+/** `value` as one single-quoted shell word. */12+const quoted = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;13+14+/**15+ * The script for `version`, whose files are at `baseUrl`: the stage's16+ * public origin and `/releases/<version>`, where the platform serves17+ * `<slug>-<target>` and `SHA256SUMS`. `machines` are the targets a release18+ * builds, without Bun's `bun-` prefix (`linux-x64`). It installs the19+ * binary as `<dir>/<cli>` and links `<dir>/git-credential-<slug>` to it (the20+ * one binary is git's credential helper when started by that name); `<dir>`21+ * is `$<SLUG>_INSTALL_DIR`, or `~/.local/bin`.22+ */23+export const installScriptFor = (input: {24+ readonly brand: typeof Brand;25+ readonly version: string;26+ readonly baseUrl: string;27+ readonly machines: readonly string[];28+}): string => {29+ const { brand, machines } = input;30+ const installDir = `${brand.slug.toUpperCase()}_INSTALL_DIR`;31+32+ return [33+ "#!/bin/sh",34+ `# Installs ${brand.cli} ${input.version}, the ${brand.name} command line, from`,35+ `# ${input.baseUrl}.`,36+ "#",37+ "# It downloads the binary for this machine, checks it against the",38+ "# release's SHA256SUMS, and installs it as <dir>/" +39+ `${brand.cli}, with <dir>/${brand.gitCredentialHelper}`,40+ `# beside it (git's credential helper). <dir> is $${installDir},`,41+ "# or ~/.local/bin. Nothing is installed unless the checksum matches.",42+ "set -eu",43+ "",44+ `base=${quoted(input.baseUrl)}`,45+ `version=${quoted(input.version)}`,46+ `slug=${quoted(brand.slug)}`,47+ `name=${quoted(brand.cli)}`,48+ `helper=${quoted(brand.gitCredentialHelper)}`,49+ `dir="\${${installDir}:-$HOME/.local/bin}"`,50+ "",51+ "fail() {",52+ ' echo "$name install: $*" >&2',53+ " exit 1",54+ "}",55+ "",56+ 'case "$(uname -s)" in',57+ " Linux) os=linux ;;",58+ " Darwin) os=darwin ;;",59+ ' *) os="$(uname -s)" ;;',60+ "esac",61+ "",62+ 'case "$(uname -m)" in',63+ " x86_64 | amd64) arch=x64 ;;",64+ " arm64 | aarch64) arch=arm64 ;;",65+ ' *) arch="$(uname -m)" ;;',66+ "esac",67+ "",68+ 'case "$os-$arch" in',69+ ` ${machines.join(" | ")}) asset="$slug-$os-$arch" ;;`,70+ ` *) fail "no build for $os-$arch; $version is built for ${machines.join(" and ")}" ;;`,71+ "esac",72+ "",73+ "if command -v curl >/dev/null 2>&1; then",74+ ' fetch() { curl -fsSL "$1" -o "$2"; }',75+ "elif command -v wget >/dev/null 2>&1; then",76+ ' fetch() { wget -q -O "$2" "$1"; }',77+ "else",78+ ' fail "needs curl or wget to download $version"',79+ "fi",80+ "",81+ "if command -v sha256sum >/dev/null 2>&1; then",82+ " digest() { sha256sum \"$1\" | cut -d ' ' -f 1; }",83+ "elif command -v shasum >/dev/null 2>&1; then",84+ " digest() { shasum -a 256 \"$1\" | cut -d ' ' -f 1; }",85+ "else",86+ ' fail "needs sha256sum or shasum to check the download"',87+ "fi",88+ "",89+ 'tmp="$(mktemp -d)"',90+ "trap 'rm -rf \"$tmp\"' EXIT",91+ "trap 'exit 1' HUP INT TERM",92+ "",93+ 'fetch "$base/$asset" "$tmp/$asset" || fail "could not download $base/$asset"',94+ 'fetch "$base/SHA256SUMS" "$tmp/SHA256SUMS" || fail "could not download $base/SHA256SUMS"',95+ "",96+ 'expected="$(awk -v asset="$asset" \'$2 == asset { print $1 }\' "$tmp/SHA256SUMS")"',97+ '[ -n "$expected" ] || fail "SHA256SUMS lists no $asset; nothing was installed"',98+ 'actual="$(digest "$tmp/$asset")"',99+ '[ "$actual" = "$expected" ] || fail "$asset does not match SHA256SUMS (expected $expected, got $actual); nothing was installed"',100+ "",101+ 'mkdir -p "$dir"',102+ 'chmod 755 "$tmp/$asset"',103+ 'mv -f "$tmp/$asset" "$dir/$name"',104+ 'ln -sf "$name" "$dir/$helper"',105+ "",106+ 'echo "installed $name $version as $dir/$name, with $helper beside it"',107+ 'case ":$PATH:" in',108+ ' *":$dir:"*) ;;',109+ ' *) echo "add $dir to your PATH to run $name" ;;',110+ "esac",111+ "",112+ ].join("\n");113+};added:scripts/lib/release/readme.ts+62 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162/** * The npm package's own README (issue 715): how to install the CLI, start * it and use its sdk, every name from `Brand`. The repo's README is about * the platform; this one is what npm and pi show for the package. */import type { Brand } from "@repo/brand";
const fence = (lines: readonly string[]) => ["```sh", ...lines, "```"];
/** The package's README for `version`. */export const packageReadme = (input: { readonly brand: typeof Brand; readonly version: string;}): string => { const { brand } = input;
return [ `# ${brand.cliPackage}`, "", `The ${brand.name} command line, ${input.version}. ${brand.name} is a git platform where a change lands only by passing a typed gate: a project states each change it wants as an ask, and you answer one with a commit pushed to your claim's fork.`, "", "## Install", "", "With Node or Bun:", "", ...fence([`npm install --global ${brand.cliPackage}`]), "", `Or as one file that needs neither, from the platform you use (Linux x64 and macOS on Apple silicon; the script checks the download against the release's SHA256SUMS):`, "", ...fence(["curl -fsSL <platform>/install.sh | sh"]), "", `Either way you get \`${brand.cli}\`, and \`${brand.gitCredentialHelper}\`, the credential helper git calls for the platform.`, "", "## Start", "", ...fence([ `${brand.cli} login --url <platform>`, `${brand.cli} asks # list the open asks you could take`, `${brand.cli} claim <ask> # take one; you get a fork to push your answer to`, `${brand.cli} check # run the gate's checks locally before you push`, ]), "", `\`${brand.cli} --help\` lists every command; \`${brand.cli} mcp\` serves them as MCP tools over stdio.`, "", "## pi", "", `The package is a pi package: \`pi install npm:${brand.cliPackage}\` gives every pi session the brief of the claim it works on, a guard on the files the gate judges with, and the verdict before it stops. The platform's skill ships in \`skills/${brand.slug}/\`.`, "", "## A project's config folder", "", `A maintainer's \`${brand.configDir}/\` imports the sdk from \`${brand.cliPackage}/rules\`, and the types of its data from \`${brand.cliPackage}/protocol\`:`, "", "```ts", `import { project } from "${brand.cliPackage}/rules";`, "```", "", "## Licence", "", "MIT", "", ].join("\n");};added:scripts/lib/release/steps.ts+630 added
1+/**2+ * What each step of a release does on this machine (issue 715), over the3+ * plan `scripts/lib/release.ts` makes:4+ *5+ * - `tsdown`: 416's `bun run build` in `apps/cli`, with both targets6+ * (`dist/`, and `dist/bin/<target>/` per target);7+ * - `manifest`: the npm package, staged in `apps/cli/release/npm/`: the8+ * build's `dist/*.js` and `*.d.ts`, the generated `package.json`, its9+ * README and the repo's licence;10+ * - `copySkills`: the platform's skill (`@repo/agent-kit`'s11+ * `platformSkill` over `commandDocs(Contracts)`) into its `skills/`;12+ * - `compile`: each target's binary, copied to `apps/cli/release/<slug>-<target>`;13+ * - `installScript` and `checksums`: `apps/cli/release/install.sh` and14+ * `SHA256SUMS`;15+ * - `upload`: the version's files into the stage's `releases-<stage>`16+ * bucket with Wrangler's own login, then `releases/manifest.json` last;17+ * - `publish`: `npm publish` of the staged package, which the plan allows18+ * only when a person runs it (H2).19+ *20+ * The package is staged beside the binaries rather than in `dist/`: its21+ * manifest names `./dist/…` and `./skills` from the package's root, and22+ * `dist/bin/` holds the binaries, which npm must not ship.23+ */24+import { Brand } from "@repo/brand";25+import { Contracts } from "@repo/protocol/contracts";26+import {27+ Array as Arr,28+ Console,29+ Crypto,30+ Effect,31+ FileSystem,32+ Match,33+ Option,34+ Order,35+ Path,36+ Schema,37+ Stream,38+} from "effect";39+import { ChildProcess, ChildProcessSpawner } from "effect/process";40+41+import { resources } from "../../../infra/stages.ts";42+import type { Stage } from "../../../infra/stages.ts";43+import { commandDocs } from "../../../packages/agent-kit/src/command-doc.ts";44+import { platformSkill } from "../../../packages/agent-kit/src/platform.ts";45+import {46+ binaryName,47+ checksumsFile,48+ importedPackages,49+ installScript,50+ machineOf,51+ MANIFEST_KEY,52+ namedFiles,53+ pinnedDependencies,54+ publishManifest,55+ ReleaseManifest,56+ releaseManifest,57+ targets,58+ unreleased,59+ uploads,60+} from "../release.ts";61+import type { ReleaseAsset, ReleaseStep } from "../release.ts";62+import { packageReadme } from "./readme.ts";63+64+/** A step could not finish; nothing after it ran. */65+export class ReleaseFailed extends Schema.TaggedError<ReleaseFailed>()(66+ "ReleaseFailed",67+ { reason: Schema.String, step: Schema.String }68+) {69+ override get message() {70+ return `${this.step}: ${this.reason}`;71+ }72+}73+74+/** Where a release reads and writes, from the repo root. */75+export interface Layout {76+ readonly root: string;77+ /** `apps/cli`, where 416's build runs. */78+ readonly cli: string;79+ /** `apps/cli/dist`, 416's build. */80+ readonly dist: string;81+ /** `apps/cli/release`: the binaries, the install script and the checksums. */82+ readonly release: string;83+ /** `apps/cli/release/npm`: the npm package, as `npm publish` takes it. */84+ readonly npm: string;85+}86+87+export const layoutOf = (root: string) =>88+ Effect.map(Path.Path, (path): Layout => {89+ const cli = path.join(root, "apps", "cli");90+ const release = path.join(cli, "release");91+92+ return {93+ cli,94+ dist: path.join(cli, "dist"),95+ npm: path.join(release, "npm"),96+ release,97+ root,98+ };99+ });100+101+/** One release: its version, and the origin its install script fetches from. */102+export interface Release {103+ readonly version: string;104+ /** The platform's public origin, without a trailing `/`. */105+ readonly origin: string;106+ /** The stage an upload goes to. */107+ readonly stage: Option.Option<Stage>;108+}109+110+/** The command a person runs from the repo root to publish the staged package. */111+export const publishCommand = (layout: Layout, path: Path.Path) =>112+ `npm publish ${path.relative(layout.root, layout.npm)} --access public`;113+114+const failed = (step: ReleaseStep, reason: string) =>115+ new ReleaseFailed({ reason, step });116+117+/** Runs `command` in `cwd` with this terminal's output; any exit but 0 fails `step`. */118+const run = (119+ step: ReleaseStep,120+ command: string,121+ args: readonly string[],122+ cwd: string123+) =>124+ Effect.flatMap(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>125+ spawner.exitCode(126+ ChildProcess.make(command, args, {127+ cwd,128+ stderr: "inherit",129+ stdin: "inherit",130+ stdout: "inherit",131+ })132+ )133+ ).pipe(134+ Effect.mapError(({ message }) => failed(step, message)),135+ Effect.filterOrFail(136+ (exitCode) => exitCode === 0,137+ (exitCode) =>138+ failed(step, `${command} ${args.join(" ")} exited ${exitCode}`)139+ ),140+ Effect.asVoid141+ );142+143+/** What the release reads of a package manifest. */144+const PackageJson = Schema.fromJsonString(145+ Schema.Struct({146+ dependencies: Schema.optionalKey(147+ Schema.Record(Schema.String, Schema.String)148+ ),149+ version: Schema.optionalKey(Schema.String),150+ workspaces: Schema.optionalKey(151+ Schema.Struct({152+ catalog: Schema.optionalKey(153+ Schema.Record(Schema.String, Schema.String)154+ ),155+ })156+ ),157+ })158+);159+160+const readPackage = (step: ReleaseStep, file: string) =>161+ Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(file)).pipe(162+ Effect.flatMap(Schema.decodeEffect(PackageJson)),163+ Effect.mapError(({ message }) => failed(step, `${file}: ${message}`))164+ );165+166+/** The files of the build the npm package ships: `dist/*.js` and `dist/*.d.ts`. */167+const builtFiles = (layout: Layout) =>168+ Effect.gen(function* () {169+ const fs = yield* FileSystem.FileSystem;170+ const path = yield* Path.Path;171+ const names = yield* fs.readDirectory(layout.dist);172+173+ const files = yield* Effect.filter(174+ names.filter((name) => /\.(?:js|d\.ts)$/u.test(name)),175+ (name) =>176+ Effect.map(177+ fs.stat(path.join(layout.dist, name)),178+ ({ type }) => type === "File"179+ )180+ );181+182+ return Arr.sort(files, Order.String);183+ });184+185+/** `manifest`: the npm package, staged afresh from the build. */186+const stagePackage = (layout: Layout, release: Release) =>187+ Effect.gen(function* () {188+ const fs = yield* FileSystem.FileSystem;189+ const path = yield* Path.Path;190+191+ const files = yield* builtFiles(layout).pipe(192+ Effect.filterOrFail(193+ (names) => names.includes("bin.js"),194+ () =>195+ failed(196+ "manifest",197+ "apps/cli/dist has no bin.js: build first (--build)"198+ )199+ )200+ );201+202+ yield* fs.remove(layout.npm, { force: true, recursive: true });203+ yield* fs.makeDirectory(path.join(layout.npm, "dist"), { recursive: true });204+205+ const sources = yield* Effect.forEach(files, (name) =>206+ fs207+ .copyFile(208+ path.join(layout.dist, name),209+ path.join(layout.npm, "dist", name)210+ )211+ .pipe(Effect.andThen(fs.readFileString(path.join(layout.dist, name))))212+ );213+214+ const cli = yield* readPackage(215+ "manifest",216+ path.join(layout.cli, "package.json")217+ );218+219+ const workspace = yield* readPackage(220+ "manifest",221+ path.join(layout.root, "package.json")222+ );223+224+ const dependencies = yield* Effect.fromResult(225+ pinnedDependencies({226+ catalog: workspace.workspaces?.catalog ?? {},227+ declared: cli.dependencies ?? {},228+ imported: Arr.sort(229+ Arr.dedupe(sources.flatMap(importedPackages)),230+ Order.String231+ ),232+ })233+ ).pipe(234+ Effect.mapError(({ packages }) =>235+ failed(236+ "manifest",237+ `the build imports ${packages.join(", ")}, which apps/cli/package.json doesn't pin`238+ )239+ )240+ );241+242+ const manifest = publishManifest(Brand, {243+ dependencies,244+ version: release.version,245+ });246+247+ yield* fs.writeFileString(248+ path.join(layout.npm, "package.json"),249+ `${JSON.stringify(manifest, undefined, 2)}\n`250+ );251+252+ yield* fs.writeFileString(253+ path.join(layout.npm, "README.md"),254+ packageReadme({ brand: Brand, version: release.version })255+ );256+257+ yield* fs.copyFile(258+ path.join(layout.root, "LICENSE"),259+ path.join(layout.npm, "LICENSE")260+ );261+262+ return manifest;263+ });264+265+/** `copySkills`: the platform's skill, as the platform and the CLI's MCP prompt serve it. */266+const writeSkills = (layout: Layout) =>267+ Effect.gen(function* () {268+ const fs = yield* FileSystem.FileSystem;269+ const path = yield* Path.Path;270+ const skills = yield* platformSkill({ commands: commandDocs(Contracts) });271+272+ yield* Effect.forEach(skills, ({ content, path: file }) =>273+ Effect.andThen(274+ fs.makeDirectory(path.dirname(path.join(layout.npm, file)), {275+ recursive: true,276+ }),277+ fs.writeFileString(path.join(layout.npm, file), content)278+ )279+ );280+ });281+282+/** `compile`: each target's binary, as the release folder and the platform name it. */283+const collectBinaries = (layout: Layout) =>284+ Effect.gen(function* () {285+ const fs = yield* FileSystem.FileSystem;286+ const path = yield* Path.Path;287+288+ yield* fs.makeDirectory(layout.release, { recursive: true });289+290+ return yield* Effect.forEach(targets, (target) =>291+ Effect.gen(function* () {292+ const built = path.join(293+ layout.dist,294+ "bin",295+ machineOf(target),296+ Brand.cli297+ );298+299+ const released = path.join(layout.release, binaryName(Brand, target));300+301+ yield* fs.exists(built).pipe(302+ Effect.filterOrFail(303+ (exists) => exists,304+ () =>305+ failed(306+ "compile",307+ `${path.relative(layout.root, built)} is missing: build first (--build)`308+ )309+ )310+ );311+312+ yield* fs.copyFile(built, released);313+ yield* fs.chmod(released, 0o755);314+315+ return released;316+ })317+ );318+ });319+320+/** The files a release serves under its version: each binary, and the install script. */321+const releasedFiles = [322+ ...targets.map((target) => binaryName(Brand, target)),323+ "install.sh",324+];325+326+/** A file's sha256, as `sha256sum` prints it, and its size. */327+const assetOf = (file: string) =>328+ Effect.gen(function* () {329+ const fs = yield* FileSystem.FileSystem;330+ const crypto = yield* Crypto.Crypto;331+ const bytes = yield* fs.readFile(file);332+ const digest = yield* crypto.digest("SHA-256", bytes);333+334+ return {335+ bytes: bytes.length,336+ sha256: [...digest]337+ .map((byte) => byte.toString(16).padStart(2, "0"))338+ .join(""),339+ } satisfies ReleaseAsset;340+ });341+342+/** Each released file in the release folder, by name. */343+const assetsIn = (layout: Layout) =>344+ Effect.flatMap(Path.Path, (path) =>345+ Effect.forEach(releasedFiles, (name) =>346+ Effect.map(347+ assetOf(path.join(layout.release, name)),348+ (asset) => [name, asset] as const349+ )350+ )351+ ).pipe(Effect.map((entries) => Object.fromEntries(entries)));352+353+/** `checksums`: `SHA256SUMS` beside the files it lists. */354+const writeChecksums = (layout: Layout) =>355+ Effect.gen(function* () {356+ const fs = yield* FileSystem.FileSystem;357+ const path = yield* Path.Path;358+ const assets = yield* assetsIn(layout);359+360+ yield* fs.writeFileString(361+ path.join(layout.release, "SHA256SUMS"),362+ checksumsFile(assets)363+ );364+ });365+366+/** How the bucket keeps each file: the platform sets its own reply headers. */367+const contentTypes = new Map([368+ ["install.sh", "text/x-shellscript; charset=utf-8"],369+ ["manifest.json", "application/json"],370+]);371+372+/** A binary is bytes; the install script and the manifest are text. */373+const contentTypeOf = (file: string) =>374+ contentTypes.get(file) ?? "application/octet-stream";375+376+/** Wrangler's own bin, pinned in `apps/platform`, as bootstrap runs it. */377+const wranglerOf = (layout: Layout, path: Path.Path) =>378+ path.join(379+ layout.root,380+ "apps",381+ "platform",382+ "node_modules",383+ ".bin",384+ "wrangler"385+ );386+387+/**388+ * Runs Wrangler in `cwd` with its own login (never the read-mostly infra389+ * token; `infra/.env.schema`), and gives its exit code and everything it390+ * printed.391+ */392+const wrangler = (layout: Layout, cwd: string, args: readonly string[]) =>393+ Effect.gen(function* () {394+ const path = yield* Path.Path;395+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;396+397+ const child = yield* spawner.spawn(398+ ChildProcess.make(wranglerOf(layout, path), args, {399+ cwd,400+ env: {401+ CLOUDFLARE_API_TOKEN: undefined,402+ WRANGLER_SEND_METRICS: "false",403+ },404+ extendEnv: true,405+ })406+ );407+408+ const [output, exitCode] = yield* Effect.all(409+ [Stream.mkString(Stream.decodeText(child.all)), child.exitCode],410+ { concurrency: "unbounded" }411+ );412+413+ return { exitCode: Number(exitCode), output };414+ }).pipe(415+ Effect.scoped,416+ Effect.mapError(({ message }) =>417+ failed("upload", `wrangler didn't run: ${message}`)418+ )419+ );420+421+/** What Wrangler prints when a bucket holds no object under a key. */422+const NO_SUCH_KEY = "The specified key does not exist";423+424+/** The manifest the stage's bucket holds, if it holds one. */425+const previousManifest = (layout: Layout, bucket: string, scratch: string) =>426+ Effect.gen(function* () {427+ const fs = yield* FileSystem.FileSystem;428+ const path = yield* Path.Path;429+ const file = path.join(scratch, "previous.json");430+431+ const got = yield* wrangler(layout, scratch, [432+ "r2",433+ "object",434+ "get",435+ `${bucket}/${MANIFEST_KEY}`,436+ "--remote",437+ "--file",438+ file,439+ ]);440+441+ if (got.exitCode !== 0) {442+ return got.output.includes(NO_SUCH_KEY)443+ ? Option.none()444+ : yield* failed(445+ "upload",446+ `wrangler r2 object get ${bucket}/${MANIFEST_KEY} failed:\n${got.output.trim()}`447+ );448+ }449+450+ const text = yield* fs.readFileString(file);451+452+ return Option.some(453+ yield* Schema.decodeEffect(Schema.fromJsonString(ReleaseManifest))(454+ text455+ ).pipe(456+ Effect.mapError(({ message }) =>457+ failed(458+ "upload",459+ `${bucket}/${MANIFEST_KEY} doesn't decode, so the platform answers 503 until it is fixed by hand: ${message}`460+ )461+ )462+ )463+ );464+ });465+466+/** `upload`: the version's files into the stage's own bucket, and the manifest last. */467+const upload = (layout: Layout, release: Release) =>468+ Effect.gen(function* () {469+ const fs = yield* FileSystem.FileSystem;470+ const path = yield* Path.Path;471+472+ const stage = yield* Effect.fromOption(release.stage).pipe(473+ Effect.mapError(() => failed("upload", "an upload names its --stage"))474+ );475+476+ const bucket = resources(stage).releases;477+478+ const scratch = yield* fs.makeTempDirectoryScoped({479+ prefix: "release-715-",480+ });481+482+ const previous = yield* previousManifest(layout, bucket, scratch);483+ const assets = yield* assetsIn(layout);484+485+ yield* Effect.fromResult(486+ unreleased({487+ assets,488+ previous: Option.getOrUndefined(previous),489+ version: release.version,490+ })491+ ).pipe(Effect.mapError(({ message }) => failed("upload", message)));492+493+ const manifest = releaseManifest({494+ assets,495+ previous: Option.getOrUndefined(previous),496+ version: release.version,497+ });498+499+ yield* fs.writeFileString(500+ path.join(layout.release, "manifest.json"),501+ `${yield* Schema.encodeEffect(Schema.fromJsonString(ReleaseManifest))(502+ manifest503+ ).pipe(Effect.mapError(({ message }) => failed("upload", message)))}\n`504+ );505+506+ for (const { file, key } of uploads({507+ files: Object.keys(assets),508+ version: release.version,509+ })) {510+ yield* wrangler(layout, scratch, [511+ "r2",512+ "object",513+ "put",514+ `${bucket}/${key}`,515+ "--remote",516+ "--file",517+ path.join(layout.release, file),518+ "--content-type",519+ contentTypeOf(file),520+ ]).pipe(521+ Effect.filterOrFail(522+ ({ exitCode }) => exitCode === 0,523+ ({ output }) =>524+ failed(525+ "upload",526+ `wrangler r2 object put ${bucket}/${key} failed:\n${output.trim()}`527+ )528+ )529+ );530+531+ yield* Console.log(` uploaded ${bucket}/${key}`);532+ }533+534+ return manifest;535+ }).pipe(Effect.scoped);536+537+/** The paths the staged package's manifest names that it lacks. */538+export const missingFromPackage = (layout: Layout, version: string) =>539+ Effect.gen(function* () {540+ const fs = yield* FileSystem.FileSystem;541+ const path = yield* Path.Path;542+543+ const manifest = publishManifest(Brand, { dependencies: {}, version });544+545+ return yield* Effect.filter(namedFiles(manifest), (file) =>546+ Effect.map(fs.exists(path.join(layout.npm, file)), (exists) => !exists)547+ );548+ });549+550+/**551+ * The staged package is whole and of this release's version, so what552+ * `npm publish` ships is what this release built: checked before the553+ * publish runs, and before an agent hands its command to a person (H2).554+ */555+export const publishable = (layout: Layout, release: Release) =>556+ Effect.gen(function* () {557+ const path = yield* Path.Path;558+559+ yield* readPackage("publish", path.join(layout.npm, "package.json")).pipe(560+ Effect.filterOrFail(561+ ({ version }) => version === release.version,562+ ({ version }) =>563+ failed(564+ "publish",565+ `the staged package is ${version ?? "unversioned"}, not ${release.version}: run --build --version ${release.version} first`566+ )567+ )568+ );569+570+ yield* missingFromPackage(layout, release.version).pipe(571+ Effect.filterOrFail(572+ (missing) => missing.length === 0,573+ (missing) =>574+ failed("publish", `the staged package lacks ${missing.join(", ")}`)575+ )576+ );577+ });578+579+/** `publish`: `npm publish` of the staged package, once it is `publishable`. */580+const publish = (layout: Layout, release: Release) =>581+ Effect.andThen(582+ publishable(layout, release),583+ run(584+ "publish",585+ "npm",586+ ["publish", layout.npm, "--access", "public"],587+ layout.root588+ )589+ );590+591+/** `installScript`: the install script for this version, fetching from the release's origin. */592+const writeInstallScript = (layout: Layout, release: Release) =>593+ Effect.gen(function* () {594+ const fs = yield* FileSystem.FileSystem;595+ const path = yield* Path.Path;596+597+ yield* fs.makeDirectory(layout.release, { recursive: true });598+599+ yield* fs.writeFileString(600+ path.join(layout.release, "install.sh"),601+ installScript({602+ baseUrl: `${release.origin}/releases/${release.version}`,603+ brand: Brand,604+ version: release.version,605+ })606+ );607+608+ yield* fs.chmod(path.join(layout.release, "install.sh"), 0o755);609+ });610+611+/** One step, run. */612+export const runStep = (step: ReleaseStep, layout: Layout, release: Release) =>613+ Match.value(step).pipe(614+ Match.when("tsdown", () =>615+ run(616+ "tsdown",617+ "bun",618+ ["run", "build", "--", "--targets", targets.join(",")],619+ layout.cli620+ )621+ ),622+ Match.when("manifest", () => stagePackage(layout, release)),623+ Match.when("copySkills", () => writeSkills(layout)),624+ Match.when("compile", () => collectBinaries(layout)),625+ Match.when("installScript", () => writeInstallScript(layout, release)),626+ Match.when("checksums", () => writeChecksums(layout)),627+ Match.when("upload", () => upload(layout, release)),628+ Match.when("publish", () => publish(layout, release)),629+ Match.exhaustive630+ );added:scripts/lib/release.ts+534 added
1+/**2+ * The release's core (issue 715): what the CLI's npm package says of3+ * itself, which steps a release runs, and what it hands the platform's own4+ * release storage. Pure; `scripts/release.ts` runs it.5+ */6+import type { Brand } from "@repo/brand";7+import { detectHarness } from "@repo/protocol/audit";8+import { Array as Arr, Option, Order, Predicate, Result, Schema } from "effect";9+10+import { ReleaseManifest } from "../../apps/platform/src/releases.ts";11+import { declaredStage, NoStage, UnknownStage } from "../../infra/stages.ts";12+import { installScriptFor } from "./release/install-script.ts";13+14+// --- What a release builds for -----------------------------------------------15+16+/** The machines a release builds a binary for, as Bun names them. */17+export type Target = "bun-linux-x64" | "bun-darwin-arm64";18+19+export const targets: readonly Target[] = ["bun-linux-x64", "bun-darwin-arm64"];20+21+/** A target as 416's build and the platform name it, without Bun's prefix: `linux-x64`. */22+export const machineOf = (target: Target) => target.replace(/^bun-/u, "");23+24+/** A target's binary, as the release folder and the platform name it: `<slug>-linux-x64`. */25+export const binaryName = (brand: typeof Brand, target: Target) =>26+ `${brand.slug}-${machineOf(target)}`;27+28+// --- The npm package's dependencies ------------------------------------------29+30+/**31+ * A module statement as rolldown writes one, at the start of a line: an32+ * `import … from "x"` or `export … from "x"`, over any number of lines, or a33+ * side-effect `import "x"`. Prose and inline strings are not read, but a34+ * template literal's line can start with `import` (`dist/bin.js` holds one:35+ * the rules' `/bun` main imports `./job.json`). Such a line naming a36+ * package is read as an import, which fails the pin loudly (`Unpinned`)37+ * rather than letting an import slip through unpinned.38+ */39+const STATEMENT =40+ /^(?:import|export)\b[^;"'`]*?\bfrom\s*["'](?<from>[^"']+)["']|^import\s*["'](?<bare>[^"']+)["']/gmu;41+42+/** The package a bare specifier names: `@scope/name` or `name`, without a subpath. */43+const packageOf = (specifier: string) =>44+ specifier45+ .split("/")46+ .slice(0, specifier.startsWith("@") ? 2 : 1)47+ .join("/");48+49+/** Whether `specifier` names a package, not a file or a runtime built-in. */50+const isPackage = (specifier: string) => !/^(?:\.|\/|node:)/u.test(specifier);51+52+/**53+ * The packages a built module imports statically, by package name, sorted.54+ * A package tsdown keeps external is imported this way; one reached only by55+ * a dynamic `import()` would not be listed (none is today).56+ */57+export const importedPackages = (source: string): readonly string[] =>58+ Arr.sort(59+ Arr.dedupe(60+ [...source.matchAll(STATEMENT)].flatMap(({ groups }) => {61+ const specifier = groups?.from ?? groups?.bare ?? "";62+63+ return isPackage(specifier) ? [packageOf(specifier)] : [];64+ })65+ ),66+ Order.String67+ );68+69+/**70+ * pi, the harness the package plugs into: a host package, so an optional71+ * peer and never bundled or depended on (ratstack-pi §1.3 "Packages").72+ */73+const PI_HOST = "@earendil-works/pi-coding-agent";74+75+/**76+ * Packages the build imports that can't be pinned for npm: the CLI's77+ * manifest doesn't declare them, they are workspace packages (tsdown inlines78+ * those, so one left is a build fault), or their catalog has no version.79+ */80+export class Unpinned extends Schema.TaggedError<Unpinned>()("Unpinned", {81+ packages: Schema.Array(Schema.String),82+}) {}83+84+/** The version a declared specifier pins, with `catalog:` read from the catalog. */85+const pinOf = (86+ specifier: string | undefined,87+ catalogued: string | undefined88+) => {89+ const version = specifier === "catalog:" ? catalogued : specifier;90+91+ return version === undefined || /^(?:workspace|catalog):/u.test(version)92+ ? undefined93+ : version;94+};95+96+/**97+ * The published package's `dependencies`: each package the build imports,98+ * at the version the CLI's manifest (`declared`) pins, `catalog:` resolved99+ * from the workspace's catalog. pi is left out: the adapter imports it from100+ * the host that loads it, an optional peer. Every other one is pinned, or101+ * none is returned.102+ */103+export const pinnedDependencies = (input: {104+ readonly imported: readonly string[];105+ readonly declared: Readonly<Record<string, string>>;106+ readonly catalog: Readonly<Record<string, string>>;107+}): Result.Result<Readonly<Record<string, string>>, Unpinned> => {108+ const pins = input.imported109+ .filter((name) => name !== PI_HOST)110+ .map(111+ (name) =>112+ [113+ name,114+ name.startsWith("@repo/")115+ ? undefined116+ : pinOf(input.declared[name], input.catalog[name]),117+ ] as const118+ );119+120+ const unpinned = pins.flatMap(([name, version]) =>121+ version === undefined ? [name] : []122+ );123+124+ return unpinned.length > 0125+ ? Result.fail(new Unpinned({ packages: unpinned }))126+ : Result.succeed(127+ Object.fromEntries(128+ pins.flatMap(([name, version]) =>129+ version === undefined ? [] : [[name, version]]130+ )131+ )132+ );133+};134+135+// --- The npm package's manifest ----------------------------------------------136+137+/** The command line, under Node or Bun: 416's npm build. */138+const BIN = "./dist/bin.js";139+140+/** A library entry: its code, and the types tsgo declared for it. */141+interface LibraryEntry {142+ readonly types: string;143+ readonly default: string;144+}145+146+/** The npm package's manifest, as `npm publish` reads it. */147+export interface PublishManifest {148+ readonly bin: Readonly<Record<string, string>>;149+ readonly dependencies: Readonly<Record<string, string>>;150+ readonly description: string;151+ readonly exports: Readonly<Record<string, string | LibraryEntry>>;152+ readonly files: readonly string[];153+ readonly keywords: readonly string[];154+ readonly license: "MIT";155+ readonly name: string;156+ readonly peerDependencies: Readonly<Record<string, string>>;157+ readonly peerDependenciesMeta: Readonly<158+ Record<string, { readonly optional: boolean }>159+ >;160+ readonly pi: {161+ readonly extensions: readonly string[];162+ readonly skills: readonly string[];163+ };164+ readonly publishConfig: { readonly access: "public" };165+ readonly type: "module";166+ readonly version: string;167+}168+169+/** A library entry of 416's build, by the name it is published under. */170+const library = (name: "protocol" | "rules"): LibraryEntry =>171+ // oxlint-disable-next-line sort-keys -- Node matches export conditions in key order and needs "default" last; TypeScript reads "types" only before it172+ ({173+ types: `./dist/${name}.d.ts`,174+ default: `./dist/${name}.js`,175+ });176+177+/**178+ * The npm package's manifest for `version`. Every name comes from `brand`:179+ * the package, and one bin for each name the one entry answers to (as git's180+ * credential helper, it reads its own name; 416's `src/bin.ts`).181+ * `dependencies` are the packages the build imports, pinned182+ * (`pinnedDependencies`). The `pi` key and the `pi-package` keyword make it183+ * a pi package (`pi install npm:<package>`): pi loads the adapter at184+ * `dist/pi.js` (706) and the platform's skill under `skills/`.185+ */186+export const publishManifest = (187+ brand: typeof Brand,188+ input: {189+ readonly version: string;190+ readonly dependencies: Readonly<Record<string, string>>;191+ }192+): PublishManifest => ({193+ bin: { [brand.cli]: BIN, [brand.gitCredentialHelper]: BIN },194+ dependencies: input.dependencies,195+ description: `The ${brand.name} command line: find an ask, claim it, check your answer, and read its verdict; also git's credential helper, and a pi package.`,196+ exports: {197+ ".": BIN,198+ "./protocol": library("protocol"),199+ "./rules": library("rules"),200+ },201+ files: ["dist/", "skills/", "README.md", "LICENSE"],202+ keywords: [brand.slug, "cli", "git", "pi-package"],203+ license: "MIT",204+ name: brand.cliPackage,205+ peerDependencies: { [PI_HOST]: "*" },206+ peerDependenciesMeta: { [PI_HOST]: { optional: true } },207+ pi: { extensions: ["./dist/pi.js"], skills: ["./skills"] },208+ publishConfig: { access: "public" },209+ type: "module",210+ version: input.version,211+});212+213+/** A path in the package, as the manifest writes it, from the package's root. */214+const fromRoot = (file: string) =>215+ file.replace(/^\.\//u, "").replace(/\/$/u, "");216+217+/**218+ * Every path the npm package's manifest points at (its bins, exports, pi's219+ * extension and skills folder, and the README and licence it ships), from220+ * the package's root, sorted: a staged package missing any of them is not221+ * published.222+ */223+export const namedFiles = (manifest: PublishManifest): readonly string[] =>224+ Arr.sort(225+ Arr.dedupe(226+ [227+ ...Object.values(manifest.bin),228+ ...Object.values(manifest.exports).flatMap((entry) =>229+ Predicate.isString(entry) ? [entry] : [entry.default, entry.types]230+ ),231+ ...manifest.pi.extensions,232+ ...manifest.pi.skills,233+ ...manifest.files.filter((file) => !file.endsWith("/")),234+ ].map(fromRoot)235+ ),236+ Order.String237+ );238+239+// --- The plan ----------------------------------------------------------------240+241+/** One step of a release, in the order a release runs them. */242+export type ReleaseStep =243+ | "tsdown"244+ | "manifest"245+ | "copySkills"246+ | "compile"247+ | "installScript"248+ | "checksums"249+ | "upload"250+ | "publish";251+252+/** `npm publish` runs only when a person runs the release (H2). */253+export class PublishNeedsAPerson extends Schema.TaggedError<PublishNeedsAPerson>()(254+ "PublishNeedsAPerson",255+ { markers: Schema.Array(Schema.String) }256+) {}257+258+/**259+ * The env names that say an agent runs this process: each one that alone260+ * makes `@repo/protocol/audit`'s `detectHarness` name a harness (W4 401261+ * keeps that table once; this reads it, never copies it), sorted.262+ */263+export const agentMarkers = (264+ env: Readonly<Record<string, string | undefined>>265+): readonly string[] =>266+ Arr.sort(267+ Object.keys(env).filter(268+ (key) => detectHarness({ [key]: env[key] }).harness !== undefined269+ ),270+ Order.String271+ );272+273+/** What a build makes: 416's build, then the package and the binaries beside it. */274+const BUILD: readonly ReleaseStep[] = [275+ "tsdown",276+ "manifest",277+ "copySkills",278+ "compile",279+];280+281+/** What a build or an upload ends with: the install script for its origin, and the digests. */282+const RELEASE_FILES: readonly ReleaseStep[] = ["installScript", "checksums"];283+284+/** What `bun run release` was asked to do, and the env it runs in. */285+export interface ReleaseFlags {286+ readonly build: boolean;287+ readonly upload: boolean;288+ readonly stage?: string;289+ readonly publish: boolean;290+ readonly env: Readonly<Record<string, string | undefined>>;291+}292+293+/**294+ * The steps `flags` name, in order: `build` (416's build with both295+ * targets, the npm package and the binaries), the install script and the296+ * checksums, `upload` to the stage's own release storage, and `publish`297+ * last. An upload names a stage the repo declares (`dev-oscabriel` or298+ * `demo`); a stage given to a build only says whose origin the install299+ * script fetches from, and is checked the same way.300+ */301+const stepsOf = (302+ flags: ReleaseFlags303+): Result.Result<readonly ReleaseStep[], NoStage | UnknownStage> => {304+ if (flags.stage === undefined && flags.upload) {305+ return Result.fail(new NoStage());306+ }307+308+ if (flags.stage !== undefined && Option.isNone(declaredStage(flags.stage))) {309+ return Result.fail(new UnknownStage({ stage: flags.stage }));310+ }311+312+ return Result.succeed([313+ ...(flags.build ? BUILD : []),314+ ...(flags.build || flags.upload ? RELEASE_FILES : []),315+ ...(flags.upload ? (["upload"] as const) : []),316+ ...(flags.publish ? (["publish"] as const) : []),317+ ]);318+};319+320+/**321+ * The steps a release runs, in order (`stepsOf`). Under any agent's env, a322+ * plan that publishes is refused (H2); `releaseRun` says what the script323+ * then does instead.324+ */325+export const releasePlan = (326+ flags: ReleaseFlags327+): Result.Result<328+ readonly ReleaseStep[],329+ PublishNeedsAPerson | NoStage | UnknownStage330+> => {331+ const markers = flags.publish ? agentMarkers(flags.env) : [];332+333+ return markers.length > 0334+ ? Result.fail(new PublishNeedsAPerson({ markers }))335+ : stepsOf(flags);336+};337+338+/** One run of `bun run release`: the steps it runs, and who it hands the publish to. */339+export interface ReleaseRun {340+ readonly steps: readonly ReleaseStep[];341+ /** The agent markers that refused the publish (H2); none when a person runs it. */342+ readonly handOver: readonly string[];343+}344+345+/**346+ * What the script runs for `flags`. A person's run is the plan. Under an347+ * agent, a run that publishes still runs every other step it names, so a348+ * `--build --publish` builds, and hands the publish to a person in place349+ * of running it: the script checks the staged package and prints the350+ * command (H2), rather than ending well with nothing done.351+ */352+export const releaseRun = (353+ flags: ReleaseFlags354+): Result.Result<ReleaseRun, NoStage | UnknownStage> => {355+ const handOver = flags.publish ? agentMarkers(flags.env) : [];356+357+ return Result.map(358+ stepsOf({ ...flags, publish: flags.publish && handOver.length === 0 }),359+ (steps) => ({ handOver, steps })360+ );361+};362+363+// --- The version -------------------------------------------------------------364+365+/**366+ * An upload or a publish names its `--version`, and it is one the platform367+ * serves: semver, never `latest` (`given` is the one that isn't).368+ */369+export class VersionNeeded extends Schema.TaggedError<VersionNeeded>()(370+ "VersionNeeded",371+ { given: Schema.optionalKey(Schema.String) }372+) {373+ override get message() {374+ return this.given === undefined375+ ? "an upload or a publish names its --version (semver, such as 0.1.0)"376+ : `--version ${this.given} is not a version the platform serves (semver, such as 0.1.0)`;377+ }378+}379+380+/**381+ * Whether the platform serves `version`: its manifest decodes with it as382+ * the latest release (420's schema holds the one rule for a version).383+ */384+const served = (version: string) =>385+ Option.isSome(386+ Schema.decodeOption(ReleaseManifest)({387+ latest: version,388+ versions: { [version]: { assets: {} } },389+ })390+ );391+392+/**393+ * What the CLI reports itself as until a build stamps it (416 #6: `main.ts`394+ * says `0.0.0`), and so what a build that neither uploads nor publishes is.395+ */396+const UNRELEASED = "0.0.0";397+398+/**399+ * The release's version: `version` as given, which an upload or a publish400+ * must name, and which must be one the platform serves.401+ */402+export const releaseVersion = (input: {403+ readonly version?: string;404+ readonly upload: boolean;405+ readonly publish: boolean;406+}): Result.Result<string, VersionNeeded> => {407+ if (input.version === undefined) {408+ return input.upload || input.publish409+ ? Result.fail(new VersionNeeded({}))410+ : Result.succeed(UNRELEASED);411+ }412+413+ return served(input.version)414+ ? Result.succeed(input.version)415+ : Result.fail(new VersionNeeded({ given: input.version }));416+};417+418+// --- The platform's release storage ------------------------------------------419+420+/** One file of a release, as the manifest lists it. */421+export interface ReleaseAsset {422+ readonly sha256: string;423+ readonly bytes: number;424+}425+426+export { ReleaseManifest } from "../../apps/platform/src/releases.ts";427+428+/**429+ * `releases/manifest.json` once `version` is released with `assets`: every430+ * version `previous` lists, kept, and `version`, now latest. It is the shape431+ * the platform decodes and serves from (420's `ReleaseManifest`, the one432+ * schema both sides use).433+ */434+export const releaseManifest = (input: {435+ readonly version: string;436+ readonly previous: ReleaseManifest | undefined;437+ readonly assets: Readonly<Record<string, ReleaseAsset>>;438+}): ReleaseManifest => ({439+ latest: input.version,440+ versions: {441+ ...input.previous?.versions,442+ [input.version]: { assets: input.assets },443+ },444+});445+446+/**447+ * `version` is already released with other bytes. The platform serves a448+ * version's files as immutable, so a client may keep the old ones for good:449+ * a changed release needs a new `--version`.450+ */451+export class VersionReleased extends Schema.TaggedError<VersionReleased>()(452+ "VersionReleased",453+ { version: Schema.String }454+) {455+ override get message() {456+ return `${this.version} is already released with other bytes, and its files are cached for good: release a new --version`;457+ }458+}459+460+/** Two releases hold the same files, by name, size and digest. */461+const sameAssets = (462+ one: Readonly<Record<string, ReleaseAsset>>,463+ other: Readonly<Record<string, ReleaseAsset>>464+) =>465+ Object.keys(one).length === Object.keys(other).length &&466+ Object.entries(one).every(467+ ([name, { bytes, sha256 }]) =>468+ other[name]?.bytes === bytes && other[name]?.sha256 === sha256469+ );470+471+/**472+ * Whether `assets` may be released as `version`: it is new, or it is473+ * released already with exactly these files (an upload run again).474+ */475+export const unreleased = (input: {476+ readonly version: string;477+ readonly previous: ReleaseManifest | undefined;478+ readonly assets: Readonly<Record<string, ReleaseAsset>>;479+}): Result.Result<void, VersionReleased> => {480+ const released = input.previous?.versions[input.version];481+482+ return released === undefined || sameAssets(released.assets, input.assets)483+ ? Result.void484+ : Result.fail(new VersionReleased({ version: input.version }));485+};486+487+/** Where the manifest is kept: every release file is under `releases/`. */488+export const MANIFEST_KEY = "releases/manifest.json";489+490+/** Files by name, sorted (`Order.String`), as both sides list them. */491+const byName = <A>(record: Readonly<Record<string, A>>) =>492+ Arr.sortWith(Object.entries(record), ([name]) => name, Order.String);493+494+/**495+ * `SHA256SUMS`: one `<sha256> <name>` line per file, sorted by name, as496+ * `sha256sum` prints them and as the platform makes the one it serves from497+ * the manifest (issue 420).498+ */499+export const checksumsFile = (500+ assets: Readonly<Record<string, ReleaseAsset>>501+): string =>502+ byName(assets)503+ .map(([name, { sha256 }]) => `${sha256} ${name}\n`)504+ .join("");505+506+/**507+ * What an upload puts where, in order: every file of `version` under508+ * `releases/<version>/`, sorted, and `releases/manifest.json` last, so the509+ * manifest never names a file the bucket lacks (420 #5).510+ */511+export const uploads = (input: {512+ readonly version: string;513+ readonly files: readonly string[];514+}): readonly { readonly file: string; readonly key: string }[] => [515+ ...Arr.sort(input.files, Order.String).map((file) => ({516+ file,517+ key: `releases/${input.version}/${file}`,518+ })),519+ { file: "manifest.json", key: MANIFEST_KEY },520+];521+522+// --- The install script ------------------------------------------------------523+524+/**525+ * `curl -fsSL <origin>/install.sh | sh` for `version`, whose files the526+ * platform serves at `baseUrl` (`<origin>/releases/<version>`, issue 420):527+ * the binary for the machine, checked against `SHA256SUMS` before it is528+ * installed as `brand.cli`, with `brand.gitCredentialHelper` linked to it.529+ */530+export const installScript = (input: {531+ readonly brand: typeof Brand;532+ readonly version: string;533+ readonly baseUrl: string;534+}): string => installScriptFor({ ...input, machines: targets.map(machineOf) });modified:scripts/release.ts+276 added-14 removed
1234234566789101112131415161718192021222324252627892829303132333435363738391112134041424344454647484950515253545556575859606162636465666768697071727374757677787980811718828384202185868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527623277278279280281282283284285/** * release: builds the CLI into a publishable package and two single-file * binaries, which the platform serves from its own bucket (issue 715). Only a * person publishes. * release: builds the CLI into its npm package and two single-file * binaries, uploads a release to a stage's own release storage, and * publishes the package only when a person runs it (issue 715). * * A stub until 715 builds it: it says so in one line and exits 1. * bun run release -- --build [--version <semver>] [--stage <s> | --origin <url>] * bun run release -- --upload --stage dev-oscabriel|demo --version <semver> * bun run release -- --publish --version <semver> * * `--build` runs 416's build with both targets, stages the npm package in * `apps/cli/release/npm/` (its `package.json` generated from `Brand`, the * platform's skill, a README and the licence), copies the binaries to * `apps/cli/release/<slug>-<target>`, and writes `install.sh` and * `SHA256SUMS` beside them. The install script fetches from `--origin`, or * the stage's platform origin, or the local platform (`wrangler dev`). * * `--upload --stage <s>` puts the version's files into the stage's * `releases-<stage>` bucket with Wrangler's own login, and * `releases/manifest.json` last; the platform then serves `<origin>/install.sh` * and `<origin>/releases/…` (issue 420). Nothing goes to GitHub. * * `--publish` runs `npm publish` only when a person runs it: under any * agent's env (`@repo/protocol/audit`'s table) the run still does every * other step it names, checks the staged package as a publish would, prints * the command for a person to run, and exits 0 (H2). The release's core * lives in `lib/release.ts`, its steps in `lib/release/steps.ts`. */import { BunRuntime } from "@effect/platform-bun";import { Console, Effect, Runtime, Schema } from "effect";import { BunRuntime, BunServices } from "@effect/platform-bun";import { Console, Effect, FileSystem, Option, Path, Runtime, Schema, Stdio,} from "effect";
/** The script is not built yet: the line it printed says where it will be. */class NotBuilt extends Schema.TaggedError<NotBuilt>()("NotBuilt", {}) { override readonly [Runtime.errorExitCode] = 1;import { declaredStage, flagValue, platformOrigin, repoRoot, subdomainFile, WorkersDev,} from "../infra/stages.ts";import type { Stage } from "../infra/stages.ts";import { releaseRun, releaseVersion } from "./lib/release.ts";import { layoutOf, missingFromPackage, publishable, publishCommand, ReleaseFailed, runStep,} from "./lib/release/steps.ts";import type { Layout, Release } from "./lib/release/steps.ts";
/** The flags the command takes; any other is a typo, refused. */const FLAGS = new Set([ "--build", "--origin", "--publish", "--stage", "--upload", "--version",]);
const USAGE = "bun run release -- [--build] [--upload --stage <dev-…|demo>] [--publish] [--version <semver>] [--origin <url>]";
/** * The release stopped, and it has said why in one line: what failed and * what to do (a step's failure, a refusal of the flags or the plan). The * runtime then exits 1 without printing it again. */class Reported extends Schema.TaggedError<Reported>()("Reported", {}) { override readonly [Runtime.errorReported] = false;}
const main = Effect.gen(function* () { yield* Console.error("not built: see .scratch/build/issues/715-release.md");/** The local platform, as `wrangler dev` serves it. */const LOCAL_ORIGIN = "http://localhost:8787";
return yield* new NotBuilt();});/** What `bun run release` was asked to do. */interface Options { readonly build: boolean; readonly upload: boolean; readonly publish: boolean; readonly stage?: string; readonly version?: string; readonly origin?: string;}
/** The command's flags, read; an unknown flag or no step at all is refused. */const optionsOf = (argv: readonly string[]) => Effect.gen(function* () { const unknown = argv.filter( (arg) => arg.startsWith("--") && !FLAGS.has(arg.split("=")[0] ?? arg) );
if (unknown.length > 0) { return yield* new ReleaseFailed({ reason: `unknown ${unknown.join(", ")}; usage: ${USAGE}`, step: "flags", }); }
const options: Options = { build: argv.includes("--build"), publish: argv.includes("--publish"), upload: argv.includes("--upload"), ...Option.match(flagValue(argv, "--stage"), { onNone: () => ({}), onSome: (stage) => ({ stage }), }), ...Option.match(flagValue(argv, "--version"), { onNone: () => ({}), onSome: (version) => ({ version }), }), ...Option.match(flagValue(argv, "--origin"), { onNone: () => ({}), onSome: (origin) => ({ origin: origin.replace(/\/+$/u, "") }), }), };
if (!options.build && !options.upload && !options.publish) { return yield* new ReleaseFailed({ reason: `name a step; usage: ${USAGE}`, step: "flags", }); }
return options; });
/** The stage's platform origin, on the workers.dev subdomain bootstrap recorded. */const stageOrigin = (root: string, stage: Stage) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path;
const { subdomain } = yield* fs .readFileString(path.join(root, subdomainFile)) .pipe( Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(WorkersDev))), Effect.mapError( () => new ReleaseFailed({ reason: `${subdomainFile} names no workers.dev subdomain: run bootstrap, or pass --origin`, step: "installScript", }) ) );
return platformOrigin(stage, subdomain); });
/** Sizes of the release folder's files, and the staged package's files, for the record. */const report = (layout: Layout, version: string) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path;
if (!(yield* fs.exists(layout.release))) { return; }
for (const name of (yield* fs.readDirectory(layout.release)).toSorted()) { const info = yield* fs.stat(path.join(layout.release, name));
if (info.type === "File") { yield* Console.log( ` ${path.relative(layout.root, path.join(layout.release, name))} ${Number(info.size).toLocaleString("en-US")} bytes` ); } }
if (yield* fs.exists(layout.npm)) { const files = (yield* fs.readDirectory(layout.npm, { recursive: true, })).toSorted();
yield* Console.log( ` ${path.relative(layout.root, layout.npm)}/: ${files.join(", ")}` );
const missing = yield* missingFromPackage(layout, version);
if (missing.length > 0) { yield* Console.log( ` the package lacks ${missing.join(", ")}, which its manifest names: --publish refuses it until the build makes ${missing.length === 1 ? "that file" : "them"}` ); } } });
/** * Under an agent, the publish is a person's (H2): once the staged package * is whole and of this version, say what they run, and end well, since the * agent has done all it may. */const handOver = ( layout: Layout, release: Release, markers: readonly string[]) => Effect.gen(function* () { const path = yield* Path.Path;
yield* publishable(layout, release);
yield* Console.log( [ `release: an agent runs this (${markers.join(", ")}), so it doesn't publish (H2).`, `A person publishes the staged package (${release.version}), after \`npm login\`, from the repo root:`, "", ` ${publishCommand(layout, path)}`, ].join("\n") ); });
export const main = ( argv: readonly string[], env: Readonly<Record<string, string | undefined>>) => Effect.gen(function* () { const options = yield* optionsOf(argv); const root = yield* repoRoot; const layout = yield* layoutOf(root);
const { handOver: markers, steps } = yield* Effect.fromResult( releaseRun({ ...options, env }) );
const version = yield* Effect.fromResult(releaseVersion(options));
const stage = Option.flatMap( Option.fromNullishOr(options.stage), declaredStage );
const origin = options.origin ?? (yield* Option.match(stage, { onNone: () => Effect.succeed(LOCAL_ORIGIN), onSome: (named) => stageOrigin(root, named), }));
const release: Release = { origin, stage, version };
const planned = [ ...steps, ...(markers.length > 0 ? ["publish (by a person)"] : []), ];
yield* Console.log( `release ${version}: ${planned.join(", ")} (the install script fetches from ${origin})` );
for (const step of steps) { yield* Console.log(`release: ${step}`); yield* runStep(step, layout, release); }
yield* report(layout, version);
if (markers.length > 0) { yield* handOver(layout, release, markers); } }).pipe( Effect.tapError((failure) => Console.error(`release: ${failure.message}`)), Effect.mapError(() => new Reported()) );
if (import.meta.main) {BunRuntime.runMain(main); BunRuntime.runMain( Effect.gen(function* () { const args = yield* (yield* Stdio.Stdio).args;
// The env as this process got it: an agent's harness marks it there. return yield* main(args, process.env); }).pipe(Effect.provide(BunServices.layer)) );}