Skip to content
Myr

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

6 files+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 */7import { NodeServices } from "@effect/platform-node";8import { describe, expect, it } from "@effect/vitest";9import {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";21import { ChildProcess, ChildProcessSpawner } from "effect/process";2223import { ReleaseManifest } from "../../../apps/platform/src/releases.ts";24import { NoStage, UnknownStage } from "../../../infra/stages.ts";25import {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";45import { Brand } from "../../brand/src/index.ts";46import { repoRoot } from "./root.ts";4748/** What the test reads of a package manifest. */49const 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);6364const runtime = { "@effect/platform-bun": "4.0.1", effect: "4.0.1" };6566describe("the npm package's manifest", () => {67 const manifest = publishManifest(Brand, {68 dependencies: runtime,69 version: "0.1.0",70 });7172 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 });8889 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 });99100 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 });110111 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 });128129 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});138139/** The top of a tsdown build, as rolldown writes it, with prose that only looks like imports. */140const 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");153154describe("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 });161162 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;169170 const read = (file: string) =>171 fs172 .readFileString(path.join(root, file))173 .pipe(Effect.flatMap(Schema.decodeEffect(PackageJson)));174175 const cli = yield* read("apps/cli/package.json");176 const workspace = yield* read("package.json");177178 const pinned = pinnedDependencies({179 catalog: workspace.workspaces?.catalog ?? {},180 declared: cli.dependencies ?? {},181 imported: importedPackages(built),182 });183184 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 );199200 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 });211212 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});222223describe("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 });227228 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 });239240 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 });252253 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 });291292 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 });303304 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 });312313 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 });327328 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 });350351 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 });362363 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 });384385 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});406407/** A digest, as `sha256sum` prints one. */408const digest = (fill: string) => fill.repeat(64);409410const 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};424425const 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};430431describe("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 });441442 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 );450451 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 });459460 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});480481/** A file's digest as `sha256sum` prints it. */482const 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 );491492const origin = "https://platform-demo.example.workers.dev";493494const base = `${origin}/releases/0.1.0`;495496describe("the install script", () => {497 const script = installScript({498 baseUrl: base,499 brand: Brand,500 version: "0.1.0",501 });502503 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 });516517 /**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");530531 yield* Effect.forEach([served, tools, home], (folder) =>532 fs.makeDirectory(folder, { recursive: true })533 );534535 yield* Effect.forEach(Object.entries(files), ([name, content]) =>536 fs.writeFileString(path.join(served, name), content)537 );538539 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 );554555 yield* fs.chmod(path.join(tools, "curl"), 0o755);556 yield* fs.writeFileString(path.join(dir, "install.sh"), script);557558 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 );569570 const [stderr, exitCode] = yield* Effect.all(571 [Stream.mkString(Stream.decodeText(child.stderr)), child.exitCode],572 { concurrency: "unbounded" }573 );574575 const bin = path.join(home, ".local", "bin");576577 const installed = (yield* fs.exists(bin))578 ? Arr.sort(yield* fs.readDirectory(bin), Order.String)579 : [];580581 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));590591 /** 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 );598599 /** `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 );609610 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 });618619 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 );630631 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 });637638 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});646647describe("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 });658659 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 });675676 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 */9import type { Brand } from "@repo/brand";1011/** `value` as one single-quoted shell word. */12const quoted = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;1314/**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 */23export 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`;3132 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
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 */24import { Brand } from "@repo/brand";25import { Contracts } from "@repo/protocol/contracts";26import {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";39import { ChildProcess, ChildProcessSpawner } from "effect/process";4041import { resources } from "../../../infra/stages.ts";42import type { Stage } from "../../../infra/stages.ts";43import { commandDocs } from "../../../packages/agent-kit/src/command-doc.ts";44import { platformSkill } from "../../../packages/agent-kit/src/platform.ts";45import {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";61import type { ReleaseAsset, ReleaseStep } from "../release.ts";62import { packageReadme } from "./readme.ts";6364/** A step could not finish; nothing after it ran. */65export 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}7374/** Where a release reads and writes, from the repo root. */75export 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}8687export 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");9192 return {93 cli,94 dist: path.join(cli, "dist"),95 npm: path.join(release, "npm"),96 release,97 root,98 };99 });100101/** One release: its version, and the origin its install script fetches from. */102export 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}109110/** The command a person runs from the repo root to publish the staged package. */111export const publishCommand = (layout: Layout, path: Path.Path) =>112 `npm publish ${path.relative(layout.root, layout.npm)} --access public`;113114const failed = (step: ReleaseStep, reason: string) =>115 new ReleaseFailed({ reason, step });116117/** Runs `command` in `cwd` with this terminal's output; any exit but 0 fails `step`. */118const 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 );142143/** What the release reads of a package manifest. */144const 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);159160const 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 );165166/** The files of the build the npm package ships: `dist/*.js` and `dist/*.d.ts`. */167const 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);172173 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 );181182 return Arr.sort(files, Order.String);183 });184185/** `manifest`: the npm package, staged afresh from the build. */186const stagePackage = (layout: Layout, release: Release) =>187 Effect.gen(function* () {188 const fs = yield* FileSystem.FileSystem;189 const path = yield* Path.Path;190191 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 );201202 yield* fs.remove(layout.npm, { force: true, recursive: true });203 yield* fs.makeDirectory(path.join(layout.npm, "dist"), { recursive: true });204205 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 );213214 const cli = yield* readPackage(215 "manifest",216 path.join(layout.cli, "package.json")217 );218219 const workspace = yield* readPackage(220 "manifest",221 path.join(layout.root, "package.json")222 );223224 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 );241242 const manifest = publishManifest(Brand, {243 dependencies,244 version: release.version,245 });246247 yield* fs.writeFileString(248 path.join(layout.npm, "package.json"),249 `${JSON.stringify(manifest, undefined, 2)}\n`250 );251252 yield* fs.writeFileString(253 path.join(layout.npm, "README.md"),254 packageReadme({ brand: Brand, version: release.version })255 );256257 yield* fs.copyFile(258 path.join(layout.root, "LICENSE"),259 path.join(layout.npm, "LICENSE")260 );261262 return manifest;263 });264265/** `copySkills`: the platform's skill, as the platform and the CLI's MCP prompt serve it. */266const 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) });271272 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 });281282/** `compile`: each target's binary, as the release folder and the platform name it. */283const collectBinaries = (layout: Layout) =>284 Effect.gen(function* () {285 const fs = yield* FileSystem.FileSystem;286 const path = yield* Path.Path;287288 yield* fs.makeDirectory(layout.release, { recursive: true });289290 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 );298299 const released = path.join(layout.release, binaryName(Brand, target));300301 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 );311312 yield* fs.copyFile(built, released);313 yield* fs.chmod(released, 0o755);314315 return released;316 })317 );318 });319320/** The files a release serves under its version: each binary, and the install script. */321const releasedFiles = [322 ...targets.map((target) => binaryName(Brand, target)),323 "install.sh",324];325326/** A file's sha256, as `sha256sum` prints it, and its size. */327const 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);333334 return {335 bytes: bytes.length,336 sha256: [...digest]337 .map((byte) => byte.toString(16).padStart(2, "0"))338 .join(""),339 } satisfies ReleaseAsset;340 });341342/** Each released file in the release folder, by name. */343const 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)));352353/** `checksums`: `SHA256SUMS` beside the files it lists. */354const 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);359360 yield* fs.writeFileString(361 path.join(layout.release, "SHA256SUMS"),362 checksumsFile(assets)363 );364 });365366/** How the bucket keeps each file: the platform sets its own reply headers. */367const contentTypes = new Map([368 ["install.sh", "text/x-shellscript; charset=utf-8"],369 ["manifest.json", "application/json"],370]);371372/** A binary is bytes; the install script and the manifest are text. */373const contentTypeOf = (file: string) =>374 contentTypes.get(file) ?? "application/octet-stream";375376/** Wrangler's own bin, pinned in `apps/platform`, as bootstrap runs it. */377const wranglerOf = (layout: Layout, path: Path.Path) =>378 path.join(379 layout.root,380 "apps",381 "platform",382 "node_modules",383 ".bin",384 "wrangler"385 );386387/**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 */392const wrangler = (layout: Layout, cwd: string, args: readonly string[]) =>393 Effect.gen(function* () {394 const path = yield* Path.Path;395 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;396397 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 );407408 const [output, exitCode] = yield* Effect.all(409 [Stream.mkString(Stream.decodeText(child.all)), child.exitCode],410 { concurrency: "unbounded" }411 );412413 return { exitCode: Number(exitCode), output };414 }).pipe(415 Effect.scoped,416 Effect.mapError(({ message }) =>417 failed("upload", `wrangler didn't run: ${message}`)418 )419 );420421/** What Wrangler prints when a bucket holds no object under a key. */422const NO_SUCH_KEY = "The specified key does not exist";423424/** The manifest the stage's bucket holds, if it holds one. */425const 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");430431 const got = yield* wrangler(layout, scratch, [432 "r2",433 "object",434 "get",435 `${bucket}/${MANIFEST_KEY}`,436 "--remote",437 "--file",438 file,439 ]);440441 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 }449450 const text = yield* fs.readFileString(file);451452 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 });465466/** `upload`: the version's files into the stage's own bucket, and the manifest last. */467const upload = (layout: Layout, release: Release) =>468 Effect.gen(function* () {469 const fs = yield* FileSystem.FileSystem;470 const path = yield* Path.Path;471472 const stage = yield* Effect.fromOption(release.stage).pipe(473 Effect.mapError(() => failed("upload", "an upload names its --stage"))474 );475476 const bucket = resources(stage).releases;477478 const scratch = yield* fs.makeTempDirectoryScoped({479 prefix: "release-715-",480 });481482 const previous = yield* previousManifest(layout, bucket, scratch);483 const assets = yield* assetsIn(layout);484485 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)));492493 const manifest = releaseManifest({494 assets,495 previous: Option.getOrUndefined(previous),496 version: release.version,497 });498499 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 );505506 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 );530531 yield* Console.log(` uploaded ${bucket}/${key}`);532 }533534 return manifest;535 }).pipe(Effect.scoped);536537/** The paths the staged package's manifest names that it lacks. */538export const missingFromPackage = (layout: Layout, version: string) =>539 Effect.gen(function* () {540 const fs = yield* FileSystem.FileSystem;541 const path = yield* Path.Path;542543 const manifest = publishManifest(Brand, { dependencies: {}, version });544545 return yield* Effect.filter(namedFiles(manifest), (file) =>546 Effect.map(fs.exists(path.join(layout.npm, file)), (exists) => !exists)547 );548 });549550/**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 */555export const publishable = (layout: Layout, release: Release) =>556 Effect.gen(function* () {557 const path = yield* Path.Path;558559 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 );569570 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 });578579/** `publish`: `npm publish` of the staged package, once it is `publishable`. */580const 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 );590591/** `installScript`: the install script for this version, fetching from the release's origin. */592const writeInstallScript = (layout: Layout, release: Release) =>593 Effect.gen(function* () {594 const fs = yield* FileSystem.FileSystem;595 const path = yield* Path.Path;596597 yield* fs.makeDirectory(layout.release, { recursive: true });598599 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 );607608 yield* fs.chmod(path.join(layout.release, "install.sh"), 0o755);609 });610611/** One step, run. */612export 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 */6import type { Brand } from "@repo/brand";7import { detectHarness } from "@repo/protocol/audit";8import { Array as Arr, Option, Order, Predicate, Result, Schema } from "effect";910import { ReleaseManifest } from "../../apps/platform/src/releases.ts";11import { declaredStage, NoStage, UnknownStage } from "../../infra/stages.ts";12import { installScriptFor } from "./release/install-script.ts";1314// --- What a release builds for -----------------------------------------------1516/** The machines a release builds a binary for, as Bun names them. */17export type Target = "bun-linux-x64" | "bun-darwin-arm64";1819export const targets: readonly Target[] = ["bun-linux-x64", "bun-darwin-arm64"];2021/** A target as 416's build and the platform name it, without Bun's prefix: `linux-x64`. */22export const machineOf = (target: Target) => target.replace(/^bun-/u, "");2324/** A target's binary, as the release folder and the platform name it: `<slug>-linux-x64`. */25export const binaryName = (brand: typeof Brand, target: Target) =>26 `${brand.slug}-${machineOf(target)}`;2728// --- The npm package's dependencies ------------------------------------------2930/**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 */39const STATEMENT =40 /^(?:import|export)\b[^;"'`]*?\bfrom\s*["'](?<from>[^"']+)["']|^import\s*["'](?<bare>[^"']+)["']/gmu;4142/** The package a bare specifier names: `@scope/name` or `name`, without a subpath. */43const packageOf = (specifier: string) =>44 specifier45 .split("/")46 .slice(0, specifier.startsWith("@") ? 2 : 1)47 .join("/");4849/** Whether `specifier` names a package, not a file or a runtime built-in. */50const isPackage = (specifier: string) => !/^(?:\.|\/|node:)/u.test(specifier);5152/**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 */57export 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 ?? "";6263 return isPackage(specifier) ? [packageOf(specifier)] : [];64 })65 ),66 Order.String67 );6869/**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 */73const PI_HOST = "@earendil-works/pi-coding-agent";7475/**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 */80export class Unpinned extends Schema.TaggedError<Unpinned>()("Unpinned", {81 packages: Schema.Array(Schema.String),82}) {}8384/** The version a declared specifier pins, with `catalog:` read from the catalog. */85const pinOf = (86 specifier: string | undefined,87 catalogued: string | undefined88) => {89 const version = specifier === "catalog:" ? catalogued : specifier;9091 return version === undefined || /^(?:workspace|catalog):/u.test(version)92 ? undefined93 : version;94};9596/**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 */103export 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 );119120 const unpinned = pins.flatMap(([name, version]) =>121 version === undefined ? [name] : []122 );123124 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};134135// --- The npm package's manifest ----------------------------------------------136137/** The command line, under Node or Bun: 416's npm build. */138const BIN = "./dist/bin.js";139140/** A library entry: its code, and the types tsgo declared for it. */141interface LibraryEntry {142 readonly types: string;143 readonly default: string;144}145146/** The npm package's manifest, as `npm publish` reads it. */147export 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}168169/** A library entry of 416's build, by the name it is published under. */170const 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 });176177/**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 */186export 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});212213/** A path in the package, as the manifest writes it, from the package's root. */214const fromRoot = (file: string) =>215 file.replace(/^\.\//u, "").replace(/\/$/u, "");216217/**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 */223export 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 );238239// --- The plan ----------------------------------------------------------------240241/** One step of a release, in the order a release runs them. */242export type ReleaseStep =243 | "tsdown"244 | "manifest"245 | "copySkills"246 | "compile"247 | "installScript"248 | "checksums"249 | "upload"250 | "publish";251252/** `npm publish` runs only when a person runs the release (H2). */253export class PublishNeedsAPerson extends Schema.TaggedError<PublishNeedsAPerson>()(254 "PublishNeedsAPerson",255 { markers: Schema.Array(Schema.String) }256) {}257258/**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 */263export 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 );272273/** What a build makes: 416's build, then the package and the binaries beside it. */274const BUILD: readonly ReleaseStep[] = [275 "tsdown",276 "manifest",277 "copySkills",278 "compile",279];280281/** What a build or an upload ends with: the install script for its origin, and the digests. */282const RELEASE_FILES: readonly ReleaseStep[] = ["installScript", "checksums"];283284/** What `bun run release` was asked to do, and the env it runs in. */285export 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}292293/**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 */301const stepsOf = (302 flags: ReleaseFlags303): Result.Result<readonly ReleaseStep[], NoStage | UnknownStage> => {304 if (flags.stage === undefined && flags.upload) {305 return Result.fail(new NoStage());306 }307308 if (flags.stage !== undefined && Option.isNone(declaredStage(flags.stage))) {309 return Result.fail(new UnknownStage({ stage: flags.stage }));310 }311312 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};319320/**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 */325export const releasePlan = (326 flags: ReleaseFlags327): Result.Result<328 readonly ReleaseStep[],329 PublishNeedsAPerson | NoStage | UnknownStage330> => {331 const markers = flags.publish ? agentMarkers(flags.env) : [];332333 return markers.length > 0334 ? Result.fail(new PublishNeedsAPerson({ markers }))335 : stepsOf(flags);336};337338/** One run of `bun run release`: the steps it runs, and who it hands the publish to. */339export 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}344345/**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 */352export const releaseRun = (353 flags: ReleaseFlags354): Result.Result<ReleaseRun, NoStage | UnknownStage> => {355 const handOver = flags.publish ? agentMarkers(flags.env) : [];356357 return Result.map(358 stepsOf({ ...flags, publish: flags.publish && handOver.length === 0 }),359 (steps) => ({ handOver, steps })360 );361};362363// --- The version -------------------------------------------------------------364365/**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 */369export 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}379380/**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 */384const served = (version: string) =>385 Option.isSome(386 Schema.decodeOption(ReleaseManifest)({387 latest: version,388 versions: { [version]: { assets: {} } },389 })390 );391392/**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 */396const UNRELEASED = "0.0.0";397398/**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 */402export 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 }412413 return served(input.version)414 ? Result.succeed(input.version)415 : Result.fail(new VersionNeeded({ given: input.version }));416};417418// --- The platform's release storage ------------------------------------------419420/** One file of a release, as the manifest lists it. */421export interface ReleaseAsset {422 readonly sha256: string;423 readonly bytes: number;424}425426export { ReleaseManifest } from "../../apps/platform/src/releases.ts";427428/**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 */434export 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});445446/**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 */451export 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}459460/** Two releases hold the same files, by name, size and digest. */461const 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 );470471/**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 */475export 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];481482 return released === undefined || sameAssets(released.assets, input.assets)483 ? Result.void484 : Result.fail(new VersionReleased({ version: input.version }));485};486487/** Where the manifest is kept: every release file is under `releases/`. */488export const MANIFEST_KEY = "releases/manifest.json";489490/** Files by name, sorted (`Order.String`), as both sides list them. */491const byName = <A>(record: Readonly<Record<string, A>>) =>492 Arr.sortWith(Object.entries(record), ([name]) => name, Order.String);493494/**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 */499export const checksumsFile = (500 assets: Readonly<Record<string, ReleaseAsset>>501): string =>502 byName(assets)503 .map(([name, { sha256 }]) => `${sha256} ${name}\n`)504 .join("");505506/**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 */511export 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];521522// --- The install script ------------------------------------------------------523524/**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 */530export 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