A local-first multi-agent app development platform, built on PenguinHarness
refactor(server,hmr): the HMR layer — its registry's two halves named, the layer named, its mechanism a package (#656)
Myriad-Dreamin0dd00ad6e2c7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 116ece4a..a69c57d5 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -99,7 +99,7 @@ jobs:build: "@prismshadow/penguin-core..."tests: pnpm --filter @prismshadow/penguin-core test- shard: server- build: "@prismshadow/penguin-core..."+ build: "@prismshadow/penguin-server..."tests: pnpm --filter @prismshadow/penguin-server test- shard: web-clibuild: "@prismshadow/penguin-core...,@prismshadow/penguin-web..."@@ -160,7 +160,7 @@ jobs:tests: pnpm --filter @prismshadow/penguin-core testsmoke: false- shard: server- build: "@prismshadow/penguin-core..."+ build: "@prismshadow/penguin-server..."tests: pnpm --filter @prismshadow/penguin-server testsmoke: false- shard: rest@@ -202,13 +202,13 @@ jobs:build: "@prismshadow/penguin-core..."tests: pnpm --filter @prismshadow/penguin-core test- shard: server-1- build: "@prismshadow/penguin-core..."+ build: "@prismshadow/penguin-server..."tests: pnpm --filter @prismshadow/penguin-server exec vitest run --shard=1/3- shard: server-2- build: "@prismshadow/penguin-core..."+ build: "@prismshadow/penguin-server..."tests: pnpm --filter @prismshadow/penguin-server exec vitest run --shard=2/3- shard: server-3- build: "@prismshadow/penguin-core..."+ build: "@prismshadow/penguin-server..."tests: pnpm --filter @prismshadow/penguin-server exec vitest run --shard=3/3- shard: restbuild: "@prismshadow/penguin-desktop...,@prismshadow/penguin-cli..."diff --git a/changelog/unreleased/2026-09-07-hmr-layer-and-package.md b/changelog/unreleased/2026-09-07-hmr-layer-and-package.mdnew file mode 100644index 00000000..b853d45b--- /dev/null+++ b/changelog/unreleased/2026-09-07-hmr-layer-and-package.md@@ -0,0 +1,28 @@+# The HMR layer: named, packaged, and reduced to /api/hmr++- **Date:** 2026-09-07+- **Type:** improvement+- **Scope:** `hmr`, `server`, `desktop`, `tooling`, `ci`+- **PR:** [#656](https://github.com/Prism-Shadow/penguin-harness/pull/656)++[中文版](2026-09-07-hmr-layer-and-package.zh.md)++One purpose: make it hard to put product behaviour where only a reinstall can deliver it.++**The layer is named after what it does.** "Runtime" also means "the program that is running", so anything the process did sounded like it belonged to the layer. It is the HMR layer now, in the documentation and in the identifiers. The tree's node names are not renamed.++**The mechanism is `packages/hmr`.** The version store, the atomic `harness.json` commit, the resource registry and the park → boot → swap live in a package that cannot see a platform: the bundle compiled into the program is a constructor argument, and the api a platform exposes is a type parameter. Its README carries the layer's rules; the server keeps its half — the capability contract, the upgrade endpoints, the seam, and the platform itself. CI's server test shards build `@prismshadow/penguin-server...`, so the new package is built before the tests that import it.++**Its HTTP surface is `/api/hmr`.** `/api/auth` and `/api/desktop` are platform route groups now, served through the seam like every other route; the platform's route table no longer carries a list of prefixes to decline, and an unknown path under `/api/auth` answers 404 rather than the cookie gate's 401.++**The platform hands the layer its log.** The layer's request line goes through `log` on the platform's api, resolved per line through the host, instead of a `Log` node looked up by name at boot and held across swaps.++**The upgrade channel is a route the platform declares, with a protocol the mechanism owns.** `/api/hmr` is contributed to the platform's route table like any other group (network gate, then the platform's auth, then admin), and what a push is — its body, its answer — is `packages/hmr`'s `upgradeEndpoint`, reached through the control object any generation can claim. A generation that would not serve the channel is refused before commit (`admitsUpgradeRoute`): the previous one stays, and the installation can never be left with no way to push. The layer reserves nothing above the seam.++**The frozen operations are `hmrMain`, in the package.** Which generation a request goes to (and the wait for an in-flight swap), how a push is applied and what happens when its boot fails, and what the product refreshes once a generation is current — the pushed one, or the previous one re-booted — are `packages/hmr`'s `main.ts`. The server's entry hands it the host, its refresh (the tree it resolves nodes from), and its own start; the seam and the upgrade route drive the control object, never the host. The port is bound before any of that runs, so a client that arrives during startup is answered rather than refused: it gets 503 with `Retry-After`, and a browser gets a page that comes back on its own. The port announcement (`PENGUIN_PORT_FILE`) stays what it always meant — the App is up — by moving to the end of startup, so a reader that waits for it, the desktop shell above all, is never handed a server that only answers "starting".++**A push works the way `git push` does.** A push used to carry every part inline every time — both bundles, the whole web dist, every native asset — base64 inside one gzip JSON body, whether or not the target already held it. The store is content-addressed now (`store/blobs/<first two hex digits>/<sha256>`, each distinct file once, spread over 256 subdirectories so no directory holds thousands of files; blobs a store kept in the flat layout of earlier builds are swept, and the next push uploads what it needs of them again): `POST /api/hmr/assets/probe { hashes }` answers which blobs the target lacks, `PUT /api/hmr/blobs/<sha256>` stores one blob from a raw body if it hashes to the name, and the push body keeps its one shape with every content value — `platform`, `cli`, each `web.files` and `assets.files` entry — allowed to be `{ sha }` instead of inline, resolved from the store before anything boots; a name the store does not hold is refused with the hash, never materialized as a hole. `scripts/deploy.mjs` probes, uploads only the missing blobs, and pushes a body of names, so a push carries only what changed since the last one. A target without the probe answers 404 and gets every part inline, the push it always received. A blob neither the committed version nor a kept assets set records is swept with the old sets.++**A fault is named, never defaulted.** Three places used to answer a broken state with a normal-looking one, which is how a real failure becomes invisible. A `harness.json` that cannot be read is no longer indistinguishable from a root that never pushed: the host says so and boots the packaged platform, and `penguin-hmr` says which of the two it hit rather than always "no CLI pushed here". A generation is admitted to the store only if it answers the upgrade path the way the channel itself would. And when no generation is current at all, the seam answers 503 saying so rather than passing the request to the static tail, which would have returned the SPA shell with a 200 for an API call.++**The registry is the platform's state, and the ids say so.** Every entry reads `platform.<name>`. The registry is in-memory state, so the rename is a hard upgrade: a platform built with it needs a layer built with it, and the other way round.diff --git a/changelog/unreleased/2026-09-07-hmr-layer-and-package.zh.md b/changelog/unreleased/2026-09-07-hmr-layer-and-package.zh.mdnew file mode 100644index 00000000..862324e4--- /dev/null+++ b/changelog/unreleased/2026-09-07-hmr-layer-and-package.zh.md@@ -0,0 +1,28 @@+# HMR 层:定名、成包、只剩 /api/hmr++- **Date:** 2026-09-07+- **Type:** improvement+- **Scope:** `hmr`, `server`, `desktop`, `tooling`, `ci`+- **PR:** [#656](https://github.com/Prism-Shadow/penguin-harness/pull/656)++[English](2026-09-07-hmr-layer-and-package.md)++同一个目的:让「把产品行为放进只能靠重装才能送达的地方」这件事变难。++**这一层按它所做的事命名。** 「runtime」同时也指「正在运行的那个程序」,于是进程做的任何事听起来都像属于这一层。现在它在文档与标识符里都叫 HMR 层。模块树的节点名不改。++**机制就是 `packages/hmr`。** 版本仓库、`harness.json` 的原子提交、资源注册表,以及 park → boot → swap,住在一个看不见 platform 的包里:编译进程序的那份 bundle 是构造函数参数,platform 暴露的 api 是类型参数。它的 README 承载这一层的规矩;server 留下自己的那一半——能力契约、升级端点、接缝,以及 platform 本身。CI 的 server 测试分片改为构建 `@prismshadow/penguin-server...`,新包会先于引用它的测试构建。++**它的 HTTP 面只有 `/api/hmr`。** `/api/auth` 与 `/api/desktop` 现在是平台的路由组,和其他路由一样经接缝提供;平台的路由表不再携带要拒绝的前缀清单,`/api/auth` 下的未知路径答 404 而不是被 cookie 门拦成 401。++**平台把日志交给层。** 层的请求日志行经平台 api 上的 `log` 写出,每行经 host 解析到当前平台,而不是启动时按名字取一个 `Log` 节点、跨 swap 拿着不放。++**升级通道是平台声明的路由,协议归机制。** `/api/hmr` 和其他路由组一样贡献进平台的路由表(先网络门,再平台的鉴权,再 admin),而「一次推送是什么」——body 与应答——是 `packages/hmr` 的 `upgradeEndpoint`,任何一代都能经控制对象认领到。不服务该通道的一代在提交前被拒绝(`admitsUpgradeRoute`):上一代继续,安装永远不会落到无法再推送的地步。层在接缝之上不再保留任何前缀。++**冻结的操作是 `hmrMain`,在包里。** 请求交给哪一代(含等待进行中的 swap)、推送如何落地、启动失败时怎么办、一代成为当前之后产品要刷新什么(新的一代,或失败后重新启动的上一代)——这些都在 `packages/hmr` 的 `main.ts`。server 的入口把 host、自己的刷新(解析节点用的那棵树)和启动交给它;接缝与升级路由只驱动控制对象,不再直接驱动 host。端口在这一切之前就绑定,于是启动期间到达的客户端会得到应答而不是被拒绝:503 带 `Retry-After`,浏览器另外得到一个会自己回来的页面。端口通告(`PENGUIN_PORT_FILE`)挪到启动的最后一步,含义仍与从前一致——App 已经起来——于是等这份通告的读者(首先是桌面外壳)不会拿到一个只会答「正在启动」的服务器。++**推送的做法和 `git push` 一样。** 推送原本每次都把所有部分内联带上——两个 bundle、整个 web dist、全部原生资产,以 base64 塞进一个 gzip JSON body——不管目标是否已经持有。现在存储按内容寻址(`store/blobs/<哈希前两位>/<sha256>`,每份不同内容只存一次,分散在 256 个子目录里,避免单个目录挂上千个文件;早先构建按平铺布局存下的 blob 会被清掉,下一次推送按需重新上传):`POST /api/hmr/assets/probe { hashes }` 回答目标缺哪些 blob,`PUT /api/hmr/blobs/<sha256>` 以原始 body 收一个 blob、哈希对上名字才存,推送 body 形状不变,其中每个内容值——`platform`、`cli`、`web.files` 与 `assets.files` 的每一项——都可以写成 `{ sha }` 而不是内联,升级在任何东西启动之前先从存储解析;指名了存储里没有的 blob 会被拒绝并给出哈希,绝不物化成一个洞。`scripts/deploy.mjs` 先探测、只上传缺失的 blob,再推送一个只有名字的 body,于是一次推送只传上次之后变化的部分。没有探测端点的目标回应 404,收到全部内联内容,和它一直以来收到的推送一样。已提交版本与留存的资产集合都未记录的 blob 随旧集合一起清扫。++**故障要点名,不许拿默认值顶替。** 有三处曾把坏状态答成正常状态,真正的失败因此看不见。读不出来的 `harness.json` 不再等同于「从没推送过」:宿主明说并启动打包平台,`penguin-hmr` 也会区分这两种情况,而不是一律报「这里没有推送过 CLI」。一代要被接纳进存储,必须对升级路径给出通道本身会给的应答。当没有任何一代在运行时,接缝直接答 503 说明原因,而不是把请求交给静态兜底——那会让一次 API 调用拿到 200 和一份 SPA 外壳。++**registry 里的是平台的状态,id 也这么说。** 每个条目都是 `platform.<name>`。registry 是内存状态,改名即硬升级:带此改动的平台需要带此改动的层,反之亦然。diff --git a/packages/cli/src/penguin-hmr.ts b/packages/cli/src/penguin-hmr.tsindex 11046d49..8b09a991 100644--- a/packages/cli/src/penguin-hmr.ts+++ b/packages/cli/src/penguin-hmr.ts@@ -8,11 +8,16 @@ import "./warnings.js";import "dotenv/config";import { pathToFileURL } from "node:url";import { resolveRoot } from "@prismshadow/penguin-core";-import { resolveCliBundlePath } from "@prismshadow/penguin-server/hmr/manifest";+import { readPushedCli } from "@prismshadow/penguin-server/hmr/manifest";export async function loadPushedCli(root: string): Promise<(argv: string[]) => Promise<number>> {- const bundlePath = await resolveCliBundlePath(root);- if (bundlePath === null) throw new Error(`no CLI pushed to ${root}; use \`penguin\` instead`);+ const pushed = await readPushedCli(root);+ // A root that pushed no CLI and a root whose record names one it cannot produce are+ // different problems, and only one of them is fixed by running `penguin` instead.+ if (pushed.kind === "none") throw new Error(`no CLI pushed to ${root}; use \`penguin\` instead`);+ if (pushed.kind === "broken")+ throw new Error(`the CLI pushed to ${root} is unusable: ${pushed.reason}`);+ const bundlePath = pushed.file;// Cache-busted: a re-push writes a new file, but the same path may be reused.const mod = (await import(`${pathToFileURL(bundlePath).href}?v=${Date.now()}`)) as {cli?: (argv: string[]) => Promise<number>;diff --git a/packages/core/src/kernel/upgrade.ts b/packages/core/src/kernel/upgrade.tsindex 45fd7915..735f3952 100644--- a/packages/core/src/kernel/upgrade.ts+++ b/packages/core/src/kernel/upgrade.ts@@ -137,6 +137,12 @@ export async function upgrade<A extends Park, C extends Json>(opts: {impl: Impl<A, C>;iface: Iface<A, C>;resources: Resources;+ /**+ * A last word on a successor that booted: a reason it may not become current, or null.+ * A refusal is a boot failure in every respect — the successor is disposed and the+ * caller gets the parked document to recover the predecessor from.+ */+ admit?: (instance: Instance<A>) => Promise<string | null> | string | null;}): Promise<UpgradeResult<A>> {const parked = opts.current.park();const state: ReconcileState = { dropped: [], missing: [], invalid: [], migrated: false };@@ -164,6 +170,11 @@ export async function upgrade<A extends Park, C extends Json>(opts: {// is what makes a successor never race its predecessor.await (opts.current.api as { drained?: () => Promise<void> | undefined }).drained?.();instance = await boot(opts.impl, opts.iface, doc, opts.resources);+ const refusal = opts.admit === undefined ? null : await opts.admit(instance);+ if (refusal !== null) {+ instance.dispose();+ throw new Error(refusal);+ }} catch (error) {return { status: "failed", error, doc: parked };}diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.tsindex 4112d58f..2d01082e 100644--- a/packages/desktop/src/main.ts+++ b/packages/desktop/src/main.ts@@ -1,7 +1,7 @@/*** Desktop shell main process.*- * RUNTIME LAYER — MECHANISM ONLY (see packages/server/src/hmr/README.md). The+ * HMR LAYER — MECHANISM ONLY (see packages/hmr/README.md). The* shell boots and hosts; it does not implement product behavior. It is also* the least updatable code in the system — a change here reaches users only* through a new installer — so a capability that could instead be delivereddiff --git a/packages/desktop/src/server-process.ts b/packages/desktop/src/server-process.tsindex e26ab2af..f6f454c7 100644--- a/packages/desktop/src/server-process.ts+++ b/packages/desktop/src/server-process.ts@@ -80,7 +80,8 @@ async function waitForHttp(origin: string, exited: () => boolean): Promise<void>if (exited()) throw new Error("The embedded server exited during startup.");try {// Any HTTP answer counts (the root may 302 on the preview host); manual redirect- // keeps the probe from chasing hosts.+ // keeps the probe from chasing hosts. The announcement this follows is made once the+ // App is up, so an answer here is the App's.const res = await fetch(`${origin}/`, {redirect: "manual",signal: AbortSignal.timeout(1000),diff --git a/packages/hmr/README.md b/packages/hmr/README.mdnew file mode 100644index 00000000..7d51edf0--- /dev/null+++ b/packages/hmr/README.md@@ -0,0 +1,123 @@+# @prismshadow/penguin-hmr — the HMR layer's mechanism, and nothing else++This package is the hot-update **mechanism**: the version store, the atomic `harness.json`+commit, the resource registry live objects ride across a swap in, and the park → boot → swap+itself, with the recovery that re-boots the previous version when a boot fails.++It is the heart of the **HMR layer** — the layer that boots, transports and hot-swaps+everything else. The layer's other homes are the server's half of it+(`packages/server/src/hmr/`: the capability contract, the upgrade endpoints, the seam, and the+platform itself), `packages/desktop/`, and core's environment tooling. Read this before+changing any of them.++The layer used to be called "the runtime", and that name is why this file has to keep saying+what belongs here: *runtime* also means "the program that is running", so everything the+process did sounded like it belonged to the layer, and behaviour kept landing here that ships+only by reinstalling every installation. The layer is named after the one thing it does.++## The four layers++| Layer | Lives in | How it ships |+| ------------ | ------------------------------------------------------- | ---------------------------------- |+| **hmr** | `packages/hmr`, `server/src/hmr/`, `packages/desktop/` | Rebuild + redeploy every install |+| **platform** | `packages/server/src/platform.ts` + `app.ts` | One HTTP push, seconds, no restart |+| **workflow** | An agent's own folder | Installed/reloaded per agent |+| **state** | Parked context documents / the resource registry | Rides across swaps, not restarts |++## The rule++**The HMR layer carries mechanism. It must not carry policy. And this package is not to be+changed without asking.**++Not "prefer not to" — asking is the rule. Everything in the layer ships by rebuilding and+redeploying **every installation**, so a change costs weeks of latency for every user, and a+mistake in this package costs the channel through which every other fix arrives. A package that+cannot be hot-updated is the one package a broken hot update has to survive.++Mechanism is the machinery that is the same no matter what the product does: HTTP transport,+SSE channels, the network gate, the park → migrate → boot swap, the resource registry, artifact+storage and the atomic `harness.json` commit. Policy is everything a deployment might reasonably+want to change: business APIs, what an agent sees, what a command does, how a capability+behaves. Policy belongs in the **platform**, which is hot-swappable.++Authentication is policy, and used to be in the layer: a platform naming a member an older+runtime's AuthService lacked was refused at the handshake, so every auth fix waited for a+reinstall. The App builds its own AuthService now; what the layer still publishes is+`runtime:auth-state`, the process-scoped values a push must not forget — state, not a+capability.++The layer's HTTP surface is `/api/hmr/*` — the channel a broken platform is replaced through,+which is why it is never offered to the platform. Every other route is the platform's; the+layer keeps rollback copies of `/api/auth` and `/api/desktop` below its seam only until no+platform that declines them can be rolled back to.++## The registry is the platform's state, not an HMR-layer API++What the resource registry holds is the **platform's**: the config the process started with,+the open database, the channels, the hot host, the auth values, the plugin host's imported+objects, the nodes a test stands in for. The process keeps them there for one reason — a swap+must not lose them — and every id reads `platform.<name>`. The registry is in-memory state:+a platform and the layer it runs on name the same ids, and a rename is a hard upgrade of+both, never an alias.++## The test to apply BEFORE editing HMR-layer code++1. Which layer owns this **behaviour** in the four-layer model?+2. Can a platform push deliver it instead? If yes, it must.+3. If it truly must live here, be able to say why in one sentence — "it is transport,+ security, the kernel, or a one-time primitive the hot layers build on".++**The trap is "fix where the code is."** Much behaviour still physically lives in the layer's+files, so a fix at the fault site lands in the layer almost every time. The fault site is not+the owner: decide the layer first, then choose the edit site.++**The enabler people forget:** platform code executes inside the server process. Anything+achievable in-process is deliverable by a hot push with zero layer change — including effects+that look like the shell's, such as extending `process.env.PATH` so the agent's spawned shells+inherit it. Before touching the layer, ask whether a platform `boot()` could do the same.++Worked examples, all from review: a preload bridge added to the Electron shell so the page could+open DevTools (rejected — the shell already ships Ctrl+Shift+I, and the bridge cost the window's+zero-preload posture); `PATH` injected where the shell forks the server so the agent could find+the `penguin` CLI (rejected — what environment the agent sees is policy, and `boot()` reaches+deployed machines by push); a route added to the shell per new business API (the anti-pattern+the seam exists to prevent). What does justify a layer change: transport and security+mechanism, kernel evolution, and one-time primitives the hot layers build on.++## The route table is not a layer asset++The shell mounts ONE seam (`packages/server/src/hmr/http-seam.ts`) before its own routes: the+running platform gets first refusal on every request and answers `null` for the ones it does+not own, so a pushed platform can add an endpoint, replace one, or serve something else+entirely with no rebuild. Two boundaries keep it safe: `/api/hmr/*` is never offered, and a+platform that throws does not fall through — it claimed the request, and the error surfaces as+a 500. A streaming response rides the seam unchanged; a live socket is what it cannot carry,+so the terminal WebSocket handshake reaches the App through in-process members instead.++## What is deliberately NOT in this package++- **The platform.** `HmrHost` never imports one: the bundle compiled into the program is a+ constructor argument, and the api it exposes is a type parameter. This package cannot name+ a route, a service or a plugin, and that is enforced by it having no way to see one.+- **The capability list.** Which objects a platform may claim, and what each promises, is the+ server's contract (`packages/server/src/hmr/capabilities.ts`) — the registry here holds+ whatever it is handed.+- **The route.** `/api/hmr` is a route group the platform declares and gates+ (`packages/server/src/hmr/routes.ts`: the network gate, who may push); this package owns+ what the route answers, not that it exists.+- **What "a version" contains.** The store keeps bytes and a manifest; that a version is a+ platform plus a cli plus a web bundle is the product's idea, expressed in what the server+ hands over.++## Layout++| File | What it is |+| ---------------- | ----------------------------------------------------------------------- |+| `main.ts` | `hmrMain`: the entry — which generation a request goes to, how a push lands, what a push is (`upgradeEndpoint`), why a generation without the channel is refused (`admitsUpgradeRoute`) |+| `host.ts` | `HmrHost`: store, commit, boot, upgrade, recovery |+| `resources.ts` | `HotResources`: the registry, and its disposal groups |+| `manifest.ts` | `harness.json` — read, write, materialize; importable with no host |+| `ifaces-diff.ts` | What a refused handshake says two generations disagree about |++Internal to this repo (`private`), and inlined into the server's bundle — it is a boundary in+the source tree, not another artifact to publish.diff --git a/packages/hmr/package.json b/packages/hmr/package.jsonnew file mode 100644index 00000000..59cfaaa3--- /dev/null+++ b/packages/hmr/package.json@@ -0,0 +1,41 @@+{+ "name": "@prismshadow/penguin-hmr",+ "version": "0.2.9",+ "private": true,+ "type": "module",+ "description": "The hot-update mechanism: the version store, the atomic commit, the resource registry and the park → boot → swap. Mechanism only.",+ "license": "Apache-2.0",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/Prism-Shadow/penguin-harness.git",+ "directory": "packages/hmr"+ },+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js"+ },+ "./manifest": {+ "types": "./dist/manifest.d.ts",+ "import": "./dist/manifest.js"+ }+ },+ "files": [+ "dist",+ "README.md"+ ],+ "scripts": {+ "typecheck": "tsc --noEmit -p tsconfig.json",+ "test": "vitest run --passWithNoTests",+ "build": "tsup"+ },+ "dependencies": {+ "@prismshadow/penguin-core": "workspace:*"+ },+ "devDependencies": {+ "tsup": "^8.3.0",+ "vitest": "^3.2.6"+ }+}diff --git a/packages/server/src/hmr/host.ts b/packages/hmr/src/host.tssimilarity index 80%rename from packages/server/src/hmr/host.tsrename to packages/hmr/src/host.tsindex a30b3a1a..d540974e 100644--- a/packages/server/src/hmr/host.ts+++ b/packages/hmr/src/host.ts@@ -1,7 +1,7 @@/*** HmrHost: the runtime side of the stop-the-world hot-update protocol.*- * RUNTIME LAYER — MECHANISM ONLY. Nothing here may encode what the product+ * HMR LAYER — MECHANISM ONLY. Nothing here may encode what the product* does; policy belongs in the platform, which ships by HTTP push in seconds* while every line in this file costs a rebuild and a redeploy of every* installation. Before adding anything, read ./README.md — in particular the@@ -70,19 +70,17 @@ import fsp from "node:fs/promises";import path from "node:path";import zlib from "node:zlib";import { pathToFileURL } from "node:url";-import type { Instance, Json, AnyIface, AnyImpl } from "@prismshadow/penguin-core/kernel";+import type { Instance, Json, AnyIface, AnyImpl, Park } from "@prismshadow/penguin-core/kernel";import { boot, initialDoc, upgrade } from "@prismshadow/penguin-core/kernel";import { HotResources } from "./resources.js";import type { Manifest } from "./manifest.js";import { MATERIALIZED } from "./manifest.js";-import type { PlatformApi } from "./platform.js";-import { packagedPlatform } from "./platform.js";/*** The contract every platform bundle must satisfy — packaged or pushed. `context` is the* initial context a fresh boot creates the tree with (see initialDoc): the runtime never* hardcodes a business value of its own, so this is where a business platform's own- * starting state belongs (see platform/platform.ts's packagedPlatform).+ * starting state belongs (the server's hmr/platform.ts calls its own `packagedPlatform`).*/export interface PlatformBundle {id: string;@@ -118,6 +116,13 @@ export interface UpgradeAssets {* manifest. All three travel in the SAME request — there is no partial-target* upgrade.*/+/** One materialized assets directory's own record of what it was built from. */+interface AssetsRecord {+ /** relPath → sha256, the same map the pusher named (or the one derived from inline files). */+ files: Record<string, string>;+}+const ASSETS_RECORD = ".manifest.json";+export interface UpgradeAllTarget {platform: string;cli: string;@@ -153,20 +158,20 @@ export type UpgradeOutcome =*/const STORE_KEEP = 2;-export class HmrHost {+export class HmrHost<Api extends Park = Park> {readonly resources = new HotResources();- private instance: Instance<PlatformApi> | null = null;+ private instance: Instance<Api> | null = null;/*** The bundle behind the RUNNING instance, held as the loaded object rather than a* pointer to re-read: it is what boot-failure recovery re-boots (see recoverPrevious).* A bundle's `id` cannot stand in for this — the packaged export IS what a push- * delivers (hmr/entry.ts re-exports `packagedPlatform` as `hotPlatform`), so every+ * delivers (the server's hmr/entry.ts re-exports its packaged platform as `hotPlatform`), so every* pushed bundle carries the packaged id and comparing ids cannot tell a pushed version* from the compiled-in default. Nor can the manifest: a push whose disk commit failed* (`persisted: false`) is running a version harness.json does not name.*/- private current: PlatformBundle = packagedPlatform;+ private current: PlatformBundle;/** Current version's materialized native assets dir (see assetsDir()). */private assets: string | null = null;private readonly hmrDir: string;@@ -178,11 +183,21 @@ export class HmrHost {* fallback can never run twice and race each other into assigning `this.instance` (a double* boot, or a restored version clobbered by a concurrently-booted packaged default).*/- private initPromise: Promise<Instance<PlatformApi>> | null = null;+ private initPromise: Promise<Instance<Api>> | null = null;/** The freeze, as a queue: everything the HTTP layer gates on chains here. */private opQueue: Promise<unknown> = Promise.resolve();- constructor(private readonly root: string) {+ /**+ * `packaged` is the bundle compiled INTO the program — the starting state, and the+ * fallback a failed restore lands on. Passed in rather than imported: this package is the+ * mechanism, and it must not know what a platform is or what this product's default one+ * contains. The server hands it its own (hmr/platform.ts's `packagedPlatform`).+ */+ constructor(+ private readonly root: string,+ private readonly packaged: PlatformBundle,+ ) {+ this.current = packaged;this.hmrDir = path.join(root, "hmr");this.storeDir = path.join(this.hmrDir, "store");this.manifestPath = path.join(this.hmrDir, "harness.json");@@ -215,24 +230,24 @@ export class HmrHost {* in-flight promise (see `initPromise`) rather than each racing their own* restore()/packaged-boot.*/- ensure(): Promise<Instance<PlatformApi>> {+ ensure(): Promise<Instance<Api>> {if (this.instance !== null) return Promise.resolve(this.instance);this.initPromise ??= this.initialize();return this.initPromise;}/** Runs exactly once per process (guarded by `initPromise` in ensure()). */- private async initialize(): Promise<Instance<PlatformApi>> {+ private async initialize(): Promise<Instance<Api>> {try {await this.restore();if (this.instance === null) {- const bundle = packagedPlatform;+ const bundle = this.packaged;this.instance = (await boot(bundle.impl,bundle.iface,initialDoc(bundle.iface, bundle.context),this.resources,- )) as Instance<PlatformApi>;+ )) as Instance<Api>;this.current = bundle;}return this.instance;@@ -262,11 +277,29 @@ export class HmrHost {* restart always resumes the pushed CODE with a clean slate, never last run's doc.*/private async restore(): Promise<void> {+ // No file is the only silent case: nothing has ever been pushed to this root. A file+ // that cannot be read or parsed is a FAULT — this root does hold a committed version+ // and it is now unreachable — so it is named rather than served as "nothing pushed",+ // which would boot the packaged platform and let the next push overwrite the record+ // with no one ever having been told.+ let raw: string;+ try {+ raw = await fsp.readFile(this.manifestPath, "utf8");+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") {+ this.warn(`harness.json could not be read (${errMsg(err)}); booting the packaged platform`);+ }+ return;+ }let manifest: Manifest;try {- manifest = JSON.parse(await fsp.readFile(this.manifestPath, "utf8")) as Manifest;- } catch {- return; // nothing committed yet+ manifest = JSON.parse(raw) as Manifest;+ } catch (err) {+ this.warn(+ `harness.json is not readable JSON (${errMsg(err)}); booting the packaged platform. ` ++ `The committed version stays on disk but cannot be resumed until a push rewrites the record.`,+ );+ return;}if (manifest.platform === undefined && manifest.web === undefined) {return; // nothing committed yet@@ -311,7 +344,7 @@ export class HmrHost {bundle.iface,initialDoc(bundle.iface, bundle.context),this.resources,- )) as Instance<PlatformApi>;+ )) as Instance<Api>;this.instance = instance;this.current = bundle;this.webMem = webMem;@@ -324,8 +357,11 @@ export class HmrHost {}/** Strictly request-driven; serialized on the op queue (never auto-triggered). */- upgradeAll(target: UpgradeAllTarget): Promise<UpgradeOutcome> {- const run = this.opQueue.then(() => this.doUpgradeAll(target));+ upgradeAll(+ target: UpgradeAllTarget,+ admit?: (instance: Instance<Api>) => Promise<string | null> | string | null,+ ): Promise<UpgradeOutcome> {+ const run = this.opQueue.then(() => this.doUpgradeAll(target, admit));// The queue must survive a failed upgrade: swallow for chaining only.this.opQueue = run.then(() => undefined,@@ -334,7 +370,10 @@ export class HmrHost {return run;}- private async doUpgradeAll(target: UpgradeAllTarget): Promise<UpgradeOutcome> {+ private async doUpgradeAll(+ target: UpgradeAllTarget,+ admit?: (instance: Instance<Api>) => Promise<string | null> | string | null,+ ): Promise<UpgradeOutcome> {const current = await this.ensure();if (typeof target.web["index.html"] !== "string") {@@ -366,6 +405,7 @@ export class HmrHost {impl: bundle.impl,iface: bundle.iface,resources: this.resources,+ ...(admit !== undefined ? { admit: admit as never } : {}),});} catch (err) {this.publishAssets(previousAssets);@@ -402,12 +442,19 @@ export class HmrHost {// as one atomic version — never a platform that's newer (or older) than the// web or cli it's paired with. `result.doc` (the swap's parked+migrated state)// is never written to disk — see the module doc: code persists, state does not.- this.instance = result.instance as Instance<PlatformApi>;+ this.instance = result.instance as Instance<Api>;this.current = bundle;this.webMem = webMem;const digest = filesDigest(target.web);const gz = zlib.gzipSync(Buffer.from(JSON.stringify({ files: target.web })));+ // The parts by the names a pusher gives them (HMR_BLOBS_PATH), whether or not this push+ // named them: what the sweep keeps alive so an unchanged part is never uploaded twice.+ const blobs = [+ sha256(Buffer.from(target.platform, "utf8")),+ sha256(Buffer.from(target.cli, "utf8")),+ ...[...webMem.values()].map(sha256),+ ];const persisted = await this.persistVersion(platformSha,target.cli,@@ -415,6 +462,7 @@ export class HmrHost {digest.slice(0, 16),assetsDir,source,+ blobs,);return {@@ -441,12 +489,7 @@ export class HmrHost {private async recoverPrevious(doc: Json): Promise<void> {try {const bundle = this.current;- this.instance = (await boot(- bundle.impl,- bundle.iface,- doc,- this.resources,- )) as Instance<PlatformApi>;+ this.instance = (await boot(bundle.impl, bundle.iface, doc, this.resources)) as Instance<Api>;// `current` unchanged: the previous version is the running version again.} catch (err) {this.warn(@@ -537,28 +580,80 @@ export class HmrHost {* push interrupted halfway is repaired rather than trusted.*/private async materializeAssets(assets: UpgradeAssets): Promise<string> {- const sha = filesDigest(assets.files).slice(0, 16);+ // Every file goes through the blob store first, so a set is one map of relPath → sha256+ // whether its content arrived in this push or was already here.+ const files: Record<string, string> = {};+ for (const [rel, b64] of Object.entries(assets.files)) {+ if (!isSafeRelPath(rel)) throw new Error(`unsafe path in assets manifest: ${rel}`);+ files[rel] = await this.storeBlob(Buffer.from(b64, "base64"));+ }++ const sha = recordDigest(files).slice(0, 16);const dir = path.join(this.storeDir, "assets", sha);const marker = path.join(dir, MATERIALIZED);if (fs.existsSync(marker)) return dir;const exec = new Set(assets.exec ?? []);- for (const [rel, b64] of Object.entries(assets.files)) {- if (!isSafeRelPath(rel)) throw new Error(`unsafe path in assets manifest: ${rel}`);+ for (const [rel, blob] of Object.entries(files)) {const file = path.join(dir, rel);- const content = Buffer.from(b64, "base64");await fsp.mkdir(path.dirname(file), { recursive: true });- // Repairing an incomplete directory: whatever already matches is left alone, for the- // same reason the whole directory is skipped above.+ // Repairing an incomplete directory: whatever already matches is left alone. The+ // content comes from the blob store, never from the payload — after the first push+ // of a given file the payload does not carry it any more.+ const content = await fsp.readFile(this.blobPath(blob));if (!(await sameFileContent(file, content))) await fsp.writeFile(file, content);// Explicit chmod: writeFile's mode is masked by umask, and ignored outright when// the file already exists (a reused, content-addressed directory).await fsp.chmod(file, exec.has(rel) ? 0o755 : 0o644);}+ const record: AssetsRecord = { files };+ await fsp.writeFile(path.join(dir, ASSETS_RECORD), JSON.stringify(record));await fsp.writeFile(marker, sha);return dir;}+ /**+ * `store/blobs/<first two hex digits>/<sha256>`: one file per distinct content, shared by+ * every assets set, spread over 256 subdirectories — a store holds thousands of blobs, and+ * one directory that size is slow to create in, list and sweep.+ */+ private blobPath(sha: string): string {+ return path.join(this.storeDir, "blobs", sha.slice(0, 2), sha);+ }++ /** Writes a blob under its hash (a no-op when it is already there) and returns the hash. */+ async storeBlob(content: Buffer): Promise<string> {+ const sha = sha256(content);+ const file = this.blobPath(sha);+ if (!fs.existsSync(file)) {+ await fsp.mkdir(path.dirname(file), { recursive: true });+ // Written beside and renamed in: a crash mid-write must not leave a blob whose name+ // promises content it does not have.+ const tmp = `${file}.${process.pid}.tmp`;+ await fsp.writeFile(tmp, content);+ await fsp.rename(tmp, file);+ }+ return sha;+ }++ /** The bytes of a blob the store holds, or null: what a push that names its parts by hash is resolved from. */+ readBlob(sha: string): Buffer | null {+ if (!isBlobName(sha)) return null;+ try {+ return fs.readFileSync(this.blobPath(sha));+ } catch {+ return null;+ }+ }++ /**+ * Which of these blobs the store does NOT hold — what a pusher asks before it sends, so+ * an unchanged native module or plugin never crosses the wire twice.+ */+ missingBlobs(hashes: readonly string[]): string[] {+ return hashes.filter((sha) => !isBlobName(sha) || !fs.existsSync(this.blobPath(sha)));+ }+/** Points the registry at this version's assets (or clears it when a push has none). */private publishAssets(dir: string | null): void {this.assets = dir;@@ -566,7 +661,7 @@ export class HmrHost {/*** Where the current version's native-module assets live, or null when none were- * pushed. A declared member of the hmr capability (see RUNTIME_INTERFACES), read by+ * pushed. A declared member of the hmr capability (see HMR_INTERFACES), read by* the bundle's pty loader — not a registry key: the host is already the claimed* object, so its per-push state belongs on it.*/@@ -595,6 +690,7 @@ export class HmrHost {webSha: string,assetsDir: string | null,source: GitSource | null,+ blobs: string[],): Promise<boolean> {try {// The platform bundle is already in the store: storePlatformBundle put it at its@@ -621,6 +717,7 @@ export class HmrHost {// content-addressed and say nothing about their origin on their own....(source === null ? {} : { source }),pushedAt: new Date().toISOString(),+ blobs,}));return true;} catch (err) {@@ -724,6 +821,44 @@ export class HmrHost {assetsRef,(sha) => fsp.rm(path.join(assetsRoot, sha), { recursive: true, force: true }),);++ // Blobs are shared by every assets set and by the committed version's own parts, so+ // they are collected LAST, against what the sweep above left: a blob neither a+ // remaining set nor the version records is unreachable. A set without a record+ // (materialized before records existed) keeps nothing alive through the blob store+ // because it never read from it, and its own files stay untouched.+ const live = new Set<string>(manifest.blobs ?? []);+ for (const name of await fsp.readdir(assetsRoot).catch(() => [] as string[])) {+ try {+ const record = JSON.parse(+ await fsp.readFile(path.join(assetsRoot, name, ASSETS_RECORD), "utf8"),+ ) as AssetsRecord;+ for (const sha of Object.values(record.files)) live.add(sha);+ } catch {+ // No record, or an unreadable one: nothing to keep alive from here.+ }+ }+ const blobsDir = path.join(this.storeDir, "blobs");+ for (const shard of await fsp.readdir(blobsDir).catch(() => [] as string[])) {+ const shardDir = path.join(blobsDir, shard);+ if (!/^[0-9a-f]{2}$/.test(shard)) {+ // A blob from the flat layout this store used before (or a stray temp file): nothing+ // resolves it any more, so it goes; a push that needs its content uploads it again.+ if (isBlobName(shard) || shard.endsWith(".tmp")) {+ await fsp.rm(shardDir, { force: true }).catch(() => undefined);+ }+ continue;+ }+ const names = await fsp.readdir(shardDir).catch(() => [] as string[]);+ let left = names.length;+ for (const name of names) {+ if ((isBlobName(name) && !live.has(name)) || name.endsWith(".tmp")) {+ await fsp.rm(path.join(shardDir, name), { force: true }).catch(() => undefined);+ left -= 1;+ }+ }+ if (left === 0) await fsp.rmdir(shardDir).catch(() => undefined);+ }}/** Process-exit sweep only; never part of an upgrade. */@@ -738,10 +873,30 @@ function errMsg(err: unknown): string {return err instanceof Error ? err.message : String(err);}+/** A blob is named by the lowercase hex sha256 of its content, nothing else. */+export function isBlobName(name: string): boolean {+ return /^[0-9a-f]{64}$/.test(name);+}++function sha256(content: Buffer): string {+ return crypto.createHash("sha256").update(content).digest("hex");+}+function sha1(content: string): string {return crypto.createHash("sha1").update(content).digest("hex");}+/**+ * The name of a materialized assets directory: a hash over relPath → sha256, so the same+ * files name the same directory whether they arrived inline or by manifest, and a set is+ * never written twice.+ */+function recordDigest(files: Record<string, string>): string {+ const hash = crypto.createHash("sha1");+ for (const rel of Object.keys(files).sort()) hash.update(rel).update("\0").update(files[rel]!);+ return hash.digest("hex");+}+/** Content hash over a web dist manifest: stable across re-pushes of identical content. */function filesDigest(files: Record<string, string>): string {const hash = crypto.createHash("sha1");diff --git a/packages/hmr/src/index.ts b/packages/hmr/src/index.tsnew file mode 100644index 00000000..df12dbea--- /dev/null+++ b/packages/hmr/src/index.ts@@ -0,0 +1,39 @@+/**+ * @prismshadow/penguin-hmr — the hot-update MECHANISM, and nothing else.+ *+ * What a deployment does is not in this package and must never be: see README.md, which+ * states the rule and the reason it is enforced by a package boundary rather than by+ * discipline. The four exports below are the whole mechanism:+ *+ * - {@link hmrMain} — the layer's entry: the frozen operations (which generation a request+ * goes to, how a push is applied, what the product refreshes once one is current).+ * - {@link HmrHost} — the version store, the atomic `harness.json` commit, and the+ * park → boot → swap it drives (with recovery when a boot fails).+ * - {@link HotResources} — the registry live objects ride across a swap in.+ * - the manifest reader/writer — what a committed version is, on disk.+ * - the interface diff — what a handshake reports when two generations disagree.+ */+export {+ hmrMain,+ hmrControl,+ admitsUpgradeRoute,+ parseUpgradeTarget,+ upgradeEndpoint,+ HMR_ROUTE_PREFIX,+ HMR_UPGRADE_PATH,+ HMR_PROBE_PATH,+ HMR_BLOBS_PATH,+ probeEndpoint,+ blobEndpoint,+} from "./main.js";+export type { Hmr, Replace } from "./main.js";+export { HmrHost } from "./host.js";+export type {+ PlatformBundle,+ GitSource,+ UpgradeAssets,+ UpgradeAllTarget,+ UpgradeOutcome,+} from "./host.js";+export { HotResources } from "./resources.js";+export * from "./manifest.js";diff --git a/packages/hmr/src/main.ts b/packages/hmr/src/main.tsnew file mode 100644index 00000000..cc44acc1--- /dev/null+++ b/packages/hmr/src/main.ts@@ -0,0 +1,285 @@+/**+ * The HMR layer's entry: the operations that are FROZEN.+ *+ * Everything that decides how a generation becomes current lives here and in host.ts —+ * how the first one boots, how a push is applied and what happens when its boot fails, when+ * a request may be handed to a generation, and what the layer must refresh once a new one+ * is current. The product hands in three things and drives nothing itself:+ *+ * - `host`: the store and the swap (HmrHost), built over the product's packaged bundle;+ * - `replace`: what the product does with a generation once it is current — point its+ * handles at it, refresh what it derives from a version. Called for the first boot and+ * after every push: the pushed generation when it lands, the previous one re-booted+ * when it does not;+ * - `start`: the product's boot — publish what a generation claims, then the first `ensure`.+ *+ * `start` receives the control object before it runs, so the product's routes and seam can+ * be built over it while the first generation is still coming up.+ */+import zlib from "node:zlib";+import type { Instance, Park } from "@prismshadow/penguin-core/kernel";+import type { HmrHost, UpgradeAllTarget, UpgradeOutcome } from "./host.js";+import { isBlobName } from "./host.js";++/** Where a push arrives. The product declares and contributes the route like any other; the protocol behind it is this file's. */+export const HMR_ROUTE_PREFIX = "/api/hmr";+export const HMR_UPGRADE_PATH = `${HMR_ROUTE_PREFIX}/upgrade`;+/** Names the blobs a pusher holds; answers which of them this store lacks, so the push carries only those. */+export const HMR_PROBE_PATH = `${HMR_ROUTE_PREFIX}/assets/probe`;+/** `PUT ${HMR_BLOBS_PATH}/<sha256>` with the raw bytes: one blob into the store, hashed as it lands. */+export const HMR_BLOBS_PATH = `${HMR_ROUTE_PREFIX}/blobs`;++/** What the product does with a generation once it is current. */+export type Replace<Api extends Park> = (instance: Instance<Api>) => void;++/** The frozen operations, as the product sees them. */+export interface Hmr<Api extends Park> {+ /**+ * The generation requests go to. Waits out an in-flight swap FIRST: the kernel disposes the+ * old tree before the new one has booted, and for that window the host still answers with+ * the old instance — a caller that did not wait would be handed a disposed tree. Throws+ * when no generation can boot at all; the product's own routes are the fallback then, and+ * the upgrade channel stays reachable to push a working one.+ */+ current(): Promise<Instance<Api>>;+ /**+ * THE upgrade, serialized: store the bundles, boot the new generation, swap, commit the+ * version — or put the previous generation back and report why. `replace` runs once the+ * new one is current.+ */+ upgrade(target: UpgradeAllTarget): Promise<UpgradeOutcome>;+ /**+ * The channel's endpoints, framework-free: a Request in, a Response out — what the routes+ * the product declares under HMR_ROUTE_PREFIX answer with. HMR_PROBE_PATH names blobs and+ * answers which ones the store lacks; HMR_BLOBS_PATH takes one blob, raw; HMR_UPGRADE_PATH+ * is the push, each part of it inline or `{ sha }` resolved from the store. Any+ * generation may serve the routes by handing the request here, which is how one without a+ * platform of its own still carries the channel.+ */+ endpoint(+ request: Request,+ onLanded?: (outcome: Extract<UpgradeOutcome, { status: "ok" }>) => void,+ ): Promise<Response>;+}++/** The control object alone, for a product that boots its first generation some other way (tests). */+export function hmrControl<Api extends Park>(host: HmrHost<Api>, replace: Replace<Api>): Hmr<Api> {+ const hmr: Hmr<Api> = {+ endpoint: (request, onLanded) => {+ const { pathname } = new URL(request.url);+ if (pathname === HMR_PROBE_PATH) return probeEndpoint(host, request);+ if (pathname.startsWith(`${HMR_BLOBS_PATH}/`)) return blobEndpoint(host, request);+ return upgradeEndpoint(hmr, request, onLanded, (sha) => host.readBlob(sha));+ },+ current: async () => {+ await host.waitIdle();+ return host.ensure();+ },+ upgrade: async (target) => {+ const outcome = await host.upgradeAll(target, admitsUpgradeRoute);+ // Whatever is current now is a NEW instance — the pushed generation, or the previous+ // one re-booted after the pushed one failed — and the product is told either way. A+ // double fault leaves nothing current: ensure() throws, and the product keeps its last.+ try {+ replace(await host.ensure());+ } catch {+ // No generation is current; the upgrade channel stays reachable to push a good one.+ }+ return outcome;+ },+ };+ return hmr;+}++export async function hmrMain<Api extends Park>(+ host: HmrHost<Api>,+ replace: Replace<Api>,+ start: (hmr: Hmr<Api>) => Promise<void>,+): Promise<Hmr<Api>> {+ const hmr = hmrControl(host, replace);+ await start(hmr);+ replace(await host.ensure());+ return hmr;+}++/**+ * The one thing every generation must serve: the upgrade channel. A platform without it+ * would be committed and restored on every restart with no way to push another — so it is+ * refused before commit, and the previous generation stays. The probe carries no+ * credential: the route's own gate answering (401/403), or the endpoint refusing the+ * probe's shape (400/405), proves the route is there; null, a 404 or anything else does not.+ */+export async function admitsUpgradeRoute<Api extends Park>(+ instance: Instance<Api>,+): Promise<string | null> {+ if (typeof (instance.api as { http?: unknown }).http !== "function") {+ return `the pushed platform serves no HTTP, so no ${HMR_UPGRADE_PATH}`;+ }+ // A credential-less POST reaches the mechanism's endpoint (400, no body) or stops at the+ // platform's gate (401/403) or its router (405). No other answer is one the channel gives,+ // and a path nothing serves is declined outright, which is how the two are told apart.+ const answer = await probe(instance, HMR_UPGRADE_PATH);+ if (["400", "401", "403", "405"].includes(answer)) return null;+ return (+ `the pushed platform serves no ${HMR_UPGRADE_PATH} (answered ${answer}); ` ++ `a push must carry the upgrade channel, or the installation could never be upgraded again`+ );+}++/** One probe, as a comparable string: a status, `none` for a declined path, or the throw. */+async function probe<Api extends Park>(instance: Instance<Api>, path: string): Promise<string> {+ const api = instance.api as {+ http?: (request: Request) => Promise<Response | null> | Response | null;+ };+ try {+ const response = await api.http?.call(+ api,+ new Request(`http://localhost${path}`, { method: "POST" }),+ );+ return response === null || response === undefined ? "none" : String(response.status);+ } catch (err) {+ return `a throw (${err instanceof Error ? err.message : String(err)})`;+ }+}++const json = (status: number, body: unknown): Response =>+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });+const bad = (message: string): Response => json(400, { error: { code: "bad_request", message } });++/**+ * What a push's body is: `gzip(JSON.stringify({ platform, cli, web: { files }, assets?, source? }))`.+ * Every content value — a bundle, a web file, an asset — is either inline (bundles as text,+ * files as base64) or `{ sha }`: a blob put in the store beforehand (HMR_BLOBS_PATH), resolved+ * here through `readBlob`. Throws with the reason when the body is not a push.+ */+export function parseUpgradeTarget(+ contentType: string | null,+ body: Buffer,+ readBlob: (sha: string) => Buffer | null = () => null,+): UpgradeAllTarget {+ const type = (contentType ?? "").split(";")[0]!.trim().toLowerCase();+ if (type !== "application/gzip" && type !== "application/octet-stream") {+ throw new Error(+ "expected a gzip(JSON.stringify({ platform, cli, web })) body " ++ "(Content-Type application/gzip or application/octet-stream)",+ );+ }+ let payload: {+ platform?: unknown;+ cli?: unknown;+ web?: { files?: unknown };+ assets?: { files?: unknown; exec?: string[] };+ source?: { repo: string; revision: string };+ };+ try {+ payload = JSON.parse(zlib.gunzipSync(body).toString("utf8"));+ } catch (err) {+ throw new Error(+ `invalid gzip upgrade payload: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ const content = (what: string, value: unknown, encoding: "utf8" | "base64"): string => {+ if (typeof value === "string") return value;+ const sha = (value as { sha?: unknown } | null)?.sha;+ if (typeof sha !== "string" || !isBlobName(sha)) {+ throw new Error(`payload has no ${what} (content, or { sha } of a blob in the store)`);+ }+ const blob = readBlob(sha);+ if (blob === null) {+ throw new Error(+ `${what} names blob ${sha.slice(0, 12)}, which this store does not hold — put it first (PUT ${HMR_BLOBS_PATH}/<sha256>)`,+ );+ }+ return blob.toString(encoding);+ };+ const files = (what: string, value: unknown): Record<string, string> => {+ if (typeof value !== "object" || value === null) {+ throw new Error(`payload has no ${what} (a { relPath: content } map)`);+ }+ return Object.fromEntries(+ Object.entries(value).map(([rel, v]) => [rel, content(`${what} ${rel}`, v, "base64")]),+ );+ };+ return {+ platform: content("`platform`", payload.platform, "utf8"),+ cli: content("`cli`", payload.cli, "utf8"),+ web: files("`web.files`", payload.web?.files),+ // Optional: a push that needs no real files on disk (no native module, no helper+ // binary) simply omits it.+ ...(payload.assets?.files+ ? {+ assets: {+ files: files("`assets.files`", payload.assets.files),+ ...(payload.assets.exec ? { exec: payload.assets.exec } : {}),+ },+ }+ : {}),+ // Provenance is optional and, unlike the bundles, outlives the request in harness.json —+ // so it is accepted only fully formed. A half-filled or wrong-typed `source` is dropped+ // rather than committed: readers tolerate its absence, and a malformed record on disk+ // would outlive the push that produced it.+ ...(typeof payload.source?.repo === "string" &&+ typeof payload.source.revision === "string" &&+ payload.source.repo.length > 0 &&+ payload.source.revision.length > 0+ ? { source: { repo: payload.source.repo, revision: payload.source.revision } }+ : {}),+ };+}++/**+ * The upgrade endpoint, framework-free: a Request in, a Response out. A malformed push and a+ * push whose generation could not become current both answer 400 with the reason;+ * `blocked` is an outcome, not an error — the body carries the paths for the upper rungs+ * of the upgrade ladder, so clients keep one parsing path. `onLanded` runs for a push that+ * landed: what the product tells its clients (a reload), not what the layer does.+ */+export async function probeEndpoint(+ host: Pick<HmrHost, "missingBlobs">,+ request: Request,+): Promise<Response> {+ const body = (await request.json().catch(() => null)) as { hashes?: unknown } | null;+ const hashes = body?.hashes;+ if (!Array.isArray(hashes) || hashes.some((h) => typeof h !== "string")) {+ return bad("expected { hashes: string[] }");+ }+ if (hashes.length > 50_000) return bad("too many hashes in one probe");+ return json(200, { missing: host.missingBlobs(hashes as string[]) });+}++/** One blob in, raw: `PUT <HMR_BLOBS_PATH>/<sha256>` with the bytes as the body, stored only if they hash to the name. */+export async function blobEndpoint(+ host: Pick<HmrHost, "storeBlob">,+ request: Request,+): Promise<Response> {+ const sha = new URL(request.url).pathname.slice(HMR_BLOBS_PATH.length + 1);+ if (!isBlobName(sha)) return bad("a blob is named by the lowercase hex sha256 of its content");+ const stored = await host.storeBlob(Buffer.from(await request.arrayBuffer()));+ return stored === sha ? json(200, { sha }) : bad(`the body hashes to ${stored}, not ${sha}`);+}++export async function upgradeEndpoint<Api extends Park>(+ hmr: Hmr<Api>,+ request: Request,+ onLanded?: (outcome: Extract<UpgradeOutcome, { status: "ok" }>) => void,+ readBlob?: (sha: string) => Buffer | null,+): Promise<Response> {+ let target: UpgradeAllTarget;+ try {+ target = parseUpgradeTarget(+ request.headers.get("content-type"),+ Buffer.from(await request.arrayBuffer()),+ readBlob,+ );+ } catch (err) {+ return bad(err instanceof Error ? err.message : String(err));+ }+ let outcome: UpgradeOutcome;+ try {+ outcome = await hmr.upgrade(target);+ } catch (err) {+ return bad(err instanceof Error ? err.message : String(err));+ }+ if (outcome.status === "ok") onLanded?.(outcome);+ return json(200, outcome);+}diff --git a/packages/hmr/src/manifest.ts b/packages/hmr/src/manifest.tsnew file mode 100644index 00000000..f684f6be--- /dev/null+++ b/packages/hmr/src/manifest.ts@@ -0,0 +1,208 @@+/**+ * The harness.json shape (`<root>/hmr/harness.json`) and pure readers over it.+ *+ * Split out of host.ts so a reader never needs a running HmrHost: `penguin` is a+ * separate, short-lived process per invocation (see packages/cli/src/index.ts) — it+ * has no host instance to ask, only the data root's own harness.json on disk.+ * `resolveCliBundlePath` is that reader: a plain disk read, no HTTP, no boot, no+ * in-memory state.+ *+ * ONE atomic version, THREE independent artifacts: `platform`, `cli`, and `web` are+ * always written together by HmrHost's single merged upgrade path (see host.ts's+ * persistVersion), but each is content-addressed and stored on its own — a push to+ * POST /api/hmr/upgrade carries `platform` and `cli` as two separate single-file ESM+ * sources, so `cli.bundle` points at its OWN file, a different sha from+ * `platform.bundle`. They are read back together too (see host.ts's restore): a+ * partial record (e.g. `platform` present but `web` or `cli` missing) is never+ * trusted — the whole version is treated as absent instead of partially applied.+ */+import fs from "node:fs";+import fsp from "node:fs/promises";+import path from "node:path";+import type { HarnessInfo } from "@prismshadow/penguin-core";++/**+ * The committed on-disk record: a runtime restart resumes exactly this CODE (platform,+ * cli, web). It carries no STATE — a restart always boots the resumed platform bundle+ * against its own fresh initial context (bundle.context, see host.ts's PlatformBundle),+ * never a document parked from a previous run (see host.ts's module doc for why: a+ * parked doc's live-resource handles die with the process anyway, so resuming one could+ * only ever produce handles that fail to reclaim). Paths are relative to hmrDir+ * (`<root>/hmr`).+ */+/**+ * Written into an assets directory once every file in it is on disk. Its absence marks a+ * directory whose materialization was interrupted; no asset path can collide with it+ * (assets arrive as `node_modules/...` paths).+ */+export const MATERIALIZED = ".materialized";++export interface Manifest {+ platform?: { bundle: string };+ /**+ * The CLI's own bundle pointer — its own independent file (a different sha from+ * `platform.bundle`; the two are separately compiled artifacts), kept as its own+ * field so a reader that only wants "which bundle does the CLI load right now"+ * never has to reach into `platform` at all.+ */+ cli?: { bundle: string };+ /** One gzip(JSON.stringify({ files })) artifact, restored straight into memory. */+ web?: { manifest: string };+ /**+ * Files the pushed platform needs as REAL files on disk, unpacked under this directory+ * (relative to hmrDir). The web artifact stays in memory because it is only ever served+ * as bytes; an asset is something the platform hands to the OS — a native `.node` the+ * loader must resolve by path, a helper binary it execs — so it has to exist on the+ * filesystem, with its exec bit intact.+ */+ assets?: { dir: string };+ /**+ * Provenance of the push that produced this version, exactly as the pushing client sent+ * it (scripts/deploy.mjs fills it from its own checkout). Recorded, never executed or+ * resolved. Absent for a version pushed without it, and for every version committed+ * before the field existed — which is why every reader treats it as optional.+ */+ source?: { repo: string; revision: string };+ /** When this version was committed to the store (ISO 8601). Absent on older records. */+ pushedAt?: string;+ /**+ * The sha256 of each part this version was pushed as (platform, cli, every web file):+ * the blobs the store keeps alive so the next push need not carry an unchanged one.+ * Absent on older records.+ */+ blobs?: string[];+}++/** A string field of an untrusted manifest, or null unless it is a non-empty string. */+function str(value: unknown): string | null {+ return typeof value === "string" && value.length > 0 ? value : null;+}++/**+ * What the store has committed, for version reporting: provenance, commit time, and the+ * three artifact pointers. Null when nothing has ever been pushed to this root.+ *+ * Read defensively rather than cast: harness.json is written only by persistVersion, but a+ * truncated or hand-edited file must degrade a `penguin version` to missing fields, never+ * crash it. A record missing every artifact pointer counts as nothing pushed, and so does an+ * unreadable one — the only reader here that deliberately collapses the two, because its+ * caller is a report with nowhere to put a fault. The host says so at boot instead, and+ * `penguin-hmr` says so through readPushedCli.+ */+export async function readHarnessInfo(root: string): Promise<HarnessInfo | null> {+ const manifest = await readManifest(root);+ if (manifest === null) return null;++ const bundles = {+ platform: str(manifest.platform?.bundle),+ cli: str(manifest.cli?.bundle),+ web: str(manifest.web?.manifest),+ };+ if (bundles.platform === null && bundles.cli === null && bundles.web === null) return null;++ const repo = str(manifest.source?.repo);+ const revision = str(manifest.source?.revision);+ return {+ // Both halves or neither: half a provenance names nothing.+ source: repo !== null && revision !== null ? { repo, revision } : null,+ pushedAt: str(manifest.pushedAt),+ bundles,+ };+}++/**+ * `<root>/hmr/harness.json`, as one of three answers. No file means nothing was ever pushed+ * here; a file that cannot be read or parsed is a fault on a root that DID commit a version,+ * and the two must not arrive as the same value — a reader that acts on "nothing pushed"+ * would quietly ignore a version this root still holds.+ */+type ManifestRead =+ { kind: "none" } | { kind: "manifest"; manifest: Manifest } | { kind: "broken"; reason: string };++async function readManifestFile(root: string): Promise<ManifestRead> {+ const file = path.join(root, "hmr", "harness.json");+ let raw: string;+ try {+ raw = await fsp.readFile(file, "utf8");+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return { kind: "none" };+ return { kind: "broken", reason: `${file} could not be read: ${msg(err)}` };+ }+ try {+ return { kind: "manifest", manifest: JSON.parse(raw) as Manifest };+ } catch (err) {+ return { kind: "broken", reason: `${file} is not readable JSON: ${msg(err)}` };+ }+}++function msg(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++/**+ * Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt. The published+ * `./hmr/manifest` subpath is a contract with installed CLIs, so this keeps its shape;+ * a caller that has to tell the two apart reads it through readPushedCli.+ */+export async function readManifest(root: string): Promise<Manifest | null> {+ const read = await readManifestFile(root);+ return read.kind === "manifest" ? read.manifest : null;+}++/**+ * What this root has for the `penguin-hmr` loader. Three answers, never two: a root that+ * pushed no CLI and a root whose record names one it cannot produce are different+ * situations, and collapsing them tells the caller "nothing pushed" when the truth is+ * "the store lost it".+ */+export type PushedCli =+ /** Nothing has pushed a CLI here: a fresh root, or a record with no `cli` entry. */+ | { kind: "none" }+ /** The committed CLI bundle, absolute. */+ | { kind: "bundle"; file: string }+ /** The record names a CLI this root cannot produce. Says which, so it can be repaired. */+ | { kind: "broken"; reason: string };++/**+ * Reads the committed CLI bundle. Never throws: a malformed record is an answer+ * (`broken`), not an exception, because the caller is a CLI entry point that has to print+ * something useful either way.+ *+ * `cli.bundle` is trusted content, written only by persistVersion, but a reader must never+ * let a malformed or malicious value walk it out of the store via `..` segments — an escape+ * is `broken`, like a file the store no longer holds (pruned, see host.ts's pruneStore).+ */+export async function readPushedCli(root: string): Promise<PushedCli> {+ const read = await readManifestFile(root);+ if (read.kind === "none") return { kind: "none" };+ if (read.kind === "broken") return { kind: "broken", reason: read.reason };+ // No `cli` entry at all is a version that pushed no CLI; an entry that names nothing+ // usable is a record this root cannot act on.+ if (read.manifest.cli === undefined) return { kind: "none" };+ const bundle: unknown = read.manifest.cli.bundle;+ if (typeof bundle !== "string" || bundle.length === 0) {+ return { kind: "broken", reason: "harness.json has a `cli` entry with no bundle path" };+ }+ const hmrDir = path.join(root, "hmr");+ const abs = path.resolve(hmrDir, bundle);+ if (abs !== hmrDir && !abs.startsWith(hmrDir + path.sep)) {+ return {+ kind: "broken",+ reason: `harness.json points \`cli.bundle\` outside ${hmrDir}: ${bundle}`,+ };+ }+ if (!fs.existsSync(abs)) {+ return { kind: "broken", reason: `the committed CLI bundle is missing from the store: ${abs}` };+ }+ return { kind: "bundle", file: abs };+}++/**+ * The committed CLI bundle's path, or null for anything else. The published `./hmr/manifest`+ * subpath is a contract with installed CLIs, so this keeps its shape; readPushedCli is what+ * says WHY there is no path.+ */+export async function resolveCliBundlePath(root: string): Promise<string | null> {+ const cli = await readPushedCli(root);+ return cli.kind === "bundle" ? cli.file : null;+}diff --git a/packages/server/src/hmr/resources.ts b/packages/hmr/src/resources.tssimilarity index 100%rename from packages/server/src/hmr/resources.tsrename to packages/hmr/src/resources.tsdiff --git a/packages/hmr/tsconfig.json b/packages/hmr/tsconfig.jsonnew file mode 100644index 00000000..8cd1715a--- /dev/null+++ b/packages/hmr/tsconfig.json@@ -0,0 +1,7 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "rootDir": "."+ },+ "include": ["src", "test"]+}diff --git a/packages/hmr/tsup.config.ts b/packages/hmr/tsup.config.tsnew file mode 100644index 00000000..56fcc842--- /dev/null+++ b/packages/hmr/tsup.config.ts@@ -0,0 +1,12 @@+import { defineConfig } from "tsup";++export default defineConfig({+ // Two entries: the mechanism, and the harness.json reader on its own — the CLI's thin+ // loader resolves the committed cli bundle through that reader with no host in the process.+ entry: { index: "src/index.ts", manifest: "src/manifest.ts" },+ format: ["esm"],+ target: "node24",+ dts: true,+ clean: true,+ sourcemap: true,+});diff --git a/packages/server/package.json b/packages/server/package.jsonindex 960277fb..0689a1c9 100644--- a/packages/server/package.json+++ b/packages/server/package.json@@ -72,6 +72,7 @@"@hono/node-server": "^2.0.5","@larksuiteoapi/node-sdk": "^1.73.0","@prismshadow/penguin-core": "workspace:*",+ "@prismshadow/penguin-hmr": "workspace:*","@xterm/headless": "^5.5.0","dotenv": "^17.0.0","fflate": "^0.8.3",diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex d4c07db9..09ab9c4c 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -1,20 +1,17 @@/**- * App assembly, both halves of it.+ * The HMR layer's app assembly.*- * The RUNTIME shell — `createRuntimeApp(deps)` — mounts the mechanism surface: the network- * guards, `/api/auth`, `/api/desktop`, `/api/hmr`, the platform seam, and static hosting.- * `bootAppDeps(config)` builds the shell's own core (database, auth, channels, HmrHost),- * publishes its capabilities into the resource registry (see hmr/capabilities.ts), boots the- * platform — which builds the business surface over those capabilities — and returns that- * App's deps, read off the booted instance. Neither app listens on a port: tests inject- * requests via `app.request()`, and the startup entry point is index.ts.+ * `bootAppDeps(config)` builds the process's core (database, channels, HmrHost), publishes+ * it into the resource registry (see hmr/capabilities.ts), boots the platform — which builds+ * the business surface over what it claims there — and returns the boot. `createApp(boot)`+ * mounts the layer's HTTP surface: the network guards, `/api/hmr`, the platform seam, and+ * static hosting. Neither listens on a port: tests inject requests via `app.request()`, and+ * the startup entry point is index.ts.*- * The BUSINESS surface — `buildAppDeps` + `createApp`, at the bottom of this- * file — is what a hot push replaces. Both are called from `platformImpl.create`- * (hmr/platform.ts) at every App creation, over the capabilities claimed from the- * registry, so every business service and route travels with the platform version rather- * than with this build. Swap semantics for anything they hold that is not parked is a- * HARD STOP: approvals deny, runs abort, the scheduler dies with its App.+ * Every other route is the platform's (http/app.ts, `HttpModule`), assembled at every App+ * creation from `platformImpl.create` (hmr/platform.ts), so it travels with the platform+ * version rather than with this build. Swap semantics for anything the platform holds that+ * is not parked is a HARD STOP: approvals deny, runs abort, the scheduler dies with its App.*/import { createHash } from "node:crypto";import zlib from "node:zlib";@@ -30,19 +27,20 @@ import type { ModuleTree } from "@prismshadow/penguin-core/kernel";import type { ServerConfig } from "./config.js";import { applyProxySettings, mergedNoProxy } from "./net/proxy.js";import {- RUNTIME_INTERFACES,- RUNTIME_INTERFACES_RESOURCE_ID,- RUNTIME_AUTH_STATE_RESOURCE_ID,- RUNTIME_CHANNELS_RESOURCE_ID,- RUNTIME_CONFIG_RESOURCE_ID,- RUNTIME_DB_RESOURCE_ID,- RUNTIME_DESKTOP_RESOURCE_ID,- RUNTIME_LIFECYCLE_RESOURCE_ID,- RUNTIME_HMR_RESOURCE_ID,- RUNTIME_OVERRIDES_RESOURCE_ID,+ HMR_INTERFACES,+ HMR_INTERFACES_RESOURCE_ID,+ HMR_AUTH_STATE_RESOURCE_ID,+ HMR_CHANNELS_RESOURCE_ID,+ HMR_CONFIG_RESOURCE_ID,+ HMR_DB_RESOURCE_ID,+ HMR_DESKTOP_RESOURCE_ID,+ HMR_LIFECYCLE_RESOURCE_ID,+ HMR_HOST_RESOURCE_ID,+ HMR_CONTROL_RESOURCE_ID,+ HMR_OVERRIDES_RESOURCE_ID,type Replacements,- RUNTIME_PROXY_RESOURCE_ID,- RuntimeCapabilities,+ HMR_PROXY_RESOURCE_ID,+ HmrCapabilities,ConsoleLog,type Log,type ProxyControl,@@ -59,7 +57,7 @@ import { SessionsRepo } from "./db/repos/sessions.js";import { UiPrefsRepo } from "./db/repos/ui-prefs.js";import { UsersRepo } from "./db/repos/users.js";import type { UserRow } from "./db/repos/users.js";-import { authMiddleware, jsonOnlyWrites } from "./auth/middleware.js";+import { jsonOnlyWrites } from "./auth/middleware.js";import { mintApiToken, storeApiToken } from "./auth/api-token.js";import type { Identity } from "./terminal/identity.js";import { terminalRoutes } from "./terminal/routes.js";@@ -72,7 +70,6 @@ import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";import { ensureInstallId } from "./install-id.js";import { handleError, HttpError, errorBody } from "./http/errors.js";import { attributedProjectId } from "./http/attribution.js";-import { authRoutes } from "./http/routes/auth.js";import { installRoutes } from "./http/routes/install.js";import { ChannelHub } from "./runtime/channel.js";import { ErrorRecorder } from "./runtime/error-recorder.js";@@ -104,7 +101,6 @@ import { TitleGenerator, TitleNotifier } from "./runtime/title-generator.js";import { AdminService } from "./services/admin-service.js";import { DesktopService } from "./services/desktop-service.js";import { LifecycleService } from "./services/lifecycle-service.js";-import { desktopRoutes, desktopTrayRoutes, desktopUpdateRoutes } from "./http/routes/desktop.js";import { AgentConfigService } from "./services/agent-config-service.js";import { MemoryService } from "./services/memory-service.js";import { AgentService } from "./services/agent-service.js";@@ -120,8 +116,10 @@ import { UpdateCheckService } from "./services/update-check-service.js";import { UpdateJobService } from "./services/update-job.js";import { UsageService } from "./services/usage-service.js";import { WorkspaceFilesService } from "./services/workspace-files-service.js";-import { HmrHost } from "./hmr/host.js";-import { hmrRoutes } from "./hmr/routes.js";+import { HmrHost, hmrControl } from "@prismshadow/penguin-hmr";+import type { Hmr } from "@prismshadow/penguin-hmr";+import type { PlatformApi, ServerHmrHost } from "./hmr/platform.js";+import { packagedPlatform } from "./hmr/platform.js";import { platformHttpSeam } from "./hmr/http-seam.js";import {createPreviewTokenSigner,@@ -185,7 +183,9 @@ export interface ServerBoot {config: ServerConfig;db: DatabaseSync;channels: ChannelHub;- hmr: HmrHost;+ hmr: ServerHmrHost;+ /** The frozen operations over `hmr` (packages/hmr's main.ts): the seam and the upgrade route drive it, nothing drives the host directly. */+ control: Hmr<PlatformApi>;desktop: DesktopService | null;/** Process lifecycle: whether a supervisor relaunches this process, and the restart trigger (the "restart to update" step). */lifecycle: LifecycleService;@@ -206,14 +206,26 @@ export async function bootAppDeps(config: ServerConfig,replacements: Replacements = [],plugins?: PluginHost,+ host?: ServerHmrHost,+ control?: Hmr<PlatformApi>,): Promise<ServerBoot> {const db = openDatabase(config.dbPath);const usersRepo = wire(UsersRepo, { db: db });// Hoisted above the services so its registry can be populated before anything boots- // against it.- const hmr = new HmrHost(config.root);+ // against it. index.ts builds both and hands them in (hmrMain owns them there); a test+ // that boots without an entry gets the same pair here.+ const hmr = host ?? new HmrHost<PlatformApi>(config.root, packagedPlatform);+ // The default replace does what index.ts's does: point the boot's tree at the new+ // generation, so what createApp resolves from it is the current generation's.+ let booted: ServerBoot | null = null;+ const ctl =+ control ??+ hmrControl(hmr, (instance) => {+ const next = typeof instance.api.business === "function" ? instance.api.business() : null;+ if (next !== null && booted !== null) booted.tree = next;+ });// Channel idle reclamation must skip active Sessions, but "is this session busy" is a// business question: the App installs the answer itself via setActivityProbe at every@@ -262,21 +274,22 @@ export async function bootAppDeps(console.warn(`[server] could not write the penguin CLI shim: ${shim.reason}`);}- // The capability set buildAppDeps claims (see hmr/capabilities.ts) — every- // entry must be in place before ensure() below performs the first boot. The interface- // descriptor leads: it is what a bundle's handshake reads before trusting any of the rest.- hmr.resources.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);- hmr.resources.register(RUNTIME_CONFIG_RESOURCE_ID, config);- hmr.resources.register(RUNTIME_DB_RESOURCE_ID, db);- hmr.resources.register(RUNTIME_AUTH_STATE_RESOURCE_ID, authState);- hmr.resources.register(RUNTIME_CHANNELS_RESOURCE_ID, channels);- hmr.resources.register(RUNTIME_PROXY_RESOURCE_ID, applyProxySettings);- hmr.resources.register(RUNTIME_HMR_RESOURCE_ID, hmr);- hmr.resources.register(RUNTIME_OVERRIDES_RESOURCE_ID, replacements);+ // What buildAppDeps claims (see hmr/capabilities.ts) — every entry must be in place before+ // ensure() below performs the first boot. The interface descriptor leads: it is what a+ // bundle's handshake reads before trusting any of the rest.+ hmr.resources.register(HMR_INTERFACES_RESOURCE_ID, HMR_INTERFACES);+ hmr.resources.register(HMR_CONFIG_RESOURCE_ID, config);+ hmr.resources.register(HMR_DB_RESOURCE_ID, db);+ hmr.resources.register(HMR_AUTH_STATE_RESOURCE_ID, authState);+ hmr.resources.register(HMR_CHANNELS_RESOURCE_ID, channels);+ hmr.resources.register(HMR_PROXY_RESOURCE_ID, applyProxySettings);+ hmr.resources.register(HMR_HOST_RESOURCE_ID, hmr);+ hmr.resources.register(HMR_CONTROL_RESOURCE_ID, ctl);+ hmr.resources.register(HMR_OVERRIDES_RESOURCE_ID, replacements);const desktop = config.desktopToken !== null ? new DesktopService(config.desktopToken) : null;- hmr.resources.register(RUNTIME_DESKTOP_RESOURCE_ID, desktop);+ hmr.resources.register(HMR_DESKTOP_RESOURCE_ID, desktop);const lifecycle = new LifecycleService(config.supervised);- hmr.resources.register(RUNTIME_LIFECYCLE_RESOURCE_ID, lifecycle);+ hmr.resources.register(HMR_LIFECYCLE_RESOURCE_ID, lifecycle);// The registry sweep only STARTS plugin disposal (its disposers are sync) — the// fallback for exit paths that skip the graceful shutdown. The graceful path awaits// host.dispose() itself, bounded (index.ts); dispose is idempotent, so both may fire.@@ -295,22 +308,57 @@ export async function bootAppDeps(// Callers that outlive swaps (index.ts, the runtime app) may only touch the swap-stable// members: the runtime singletons published above. The tree is THIS generation's and// goes stale at the next push — per-request business dispatch rides the seam.- return { config, db, channels, hmr, desktop, lifecycle, tree };+ booted = { config, db, channels, hmr, control: ctl, desktop, lifecycle, tree };+ return booted;+}++/**+ * The layer's log handle: whichever platform is current writes the line, and the console+ * does before there is one. Resolved per line through the host, so a swap changes where the+ * lines go without the layer holding any generation's object.+ */+export function platformLog(hmr: ServerHmrHost): (line: string) => void {+ return (line) => {+ void hmr+ .ensure()+ .then((instance) => {+ if (typeof instance.api.log === "function") instance.api.log(line);+ else console.log(line);+ })+ .catch(() => console.log(line));+ };}/** Assembles the Hono app (does not listen on a port). */-export function createRuntimeApp(boot: ServerBoot): Hono<AppEnv> {- const { tree } = boot;- const errors = tree.api<Errors>("ObservabilityModule", "Errors");- const log = tree.api<{ line(text: string): void }>("RuntimeModule", "Log");- const settings = tree.api<Settings>("SettingsModule", "Settings");- const access = tree.api<Access>("ProjectsModule", "Access");- const authService = tree.api<Auth>("IdentityModule", "Auth");+export function createApp(boot: ServerBoot): Hono<AppEnv> {+ // Resolved on use, from the CURRENT generation's tree — the entry's replace hook points+ // `boot.tree` at each new one — so a node is never the first generation's for the life+ // of the process. A generation that has no tree to resolve from (a pushed fixture, a+ // bare kernel, a tree mid-dispose) keeps the last one resolved, as a captured node did.+ const current = <T>(resolve: () => T): (() => T) => {+ let last = resolve();+ return () => {+ try {+ last = resolve();+ } catch {+ // The tree is mid-swap or belongs to a generation without one: the last node stands.+ }+ return last;+ };+ };+ const errors = current(() => boot.tree.api<Errors>("ObservabilityModule", "Errors"));+ const log = platformLog(boot.hmr);+ const settings = current(() => boot.tree.api<Settings>("SettingsModule", "Settings"));+ const access = current(() => boot.tree.api<Access>("ProjectsModule", "Access"));+ const authService = current(() => boot.tree.api<Auth>("IdentityModule", "Auth"));const deps = {config: boot.config,desktop: boot.desktop,- authService,+ get authService() {+ return authService();+ },hmr: boot.hmr,+ control: boot.control,channels: boot.channels,};const app = new Hono<AppEnv>();@@ -320,8 +368,8 @@ export function createRuntimeApp(boot: ServerBoot): Hono<AppEnv> {// exceptions are logged with a stack trace and collapsed to 500), and recording// to the DB is just a side-effect layered on top.app.onError((err, c) => {- const projectId = attributedProjectId(c, { access });- errors.record({+ const projectId = attributedProjectId(c, { access: access() });+ errors().record({source: "http",err,...(projectId !== undefined ? { ctx: { projectId } } : {}),@@ -335,7 +383,7 @@ export function createRuntimeApp(boot: ServerBoot): Hono<AppEnv> {const start = performance.now();await next();const ms = Math.round(performance.now() - start);- log.line(`${c.req.method} ${c.req.path} ${c.res.status} ${ms}ms`);+ log(`${c.req.method} ${c.req.path} ${c.res.status} ${ms}ms`);});// Canonical-host guard (loopback binds only): the App is served on one loopback name and@@ -381,7 +429,7 @@ export function createRuntimeApp(boot: ServerBoot): Hono<AppEnv> {// size so the steady state allocates nothing.let capped: { size: number; mw: MiddlewareHandler } | null = null;app.use("/api/*", (c, next) => {- const size = bodyLimitBytes(settings.getAttachmentLimitsMb());+ const size = bodyLimitBytes(settings().getAttachmentLimitsMb());if (capped === null || capped.size !== size) {capped = {size,@@ -403,42 +451,15 @@ export function createRuntimeApp(boot: ServerBoot): Hono<AppEnv> {});app.use("/api/*", jsonOnlyWrites);- // Public routes (no login required).- app.route("/api/auth", authRoutes(deps));- // Desktop shutdown authenticates with the shell's Bearer token, not the cookie- // session, so it mounts outside authMiddleware (and only in desktop mode).- if (deps.desktop) {- app.route("/api/desktop", desktopRoutes(deps));- // The client-update surface is runtime-owned like the rest of /api/desktop (the- // platform declines that whole prefix): it reads the updater snapshot the shell- // pushes over the parentPort this process wires at startup, and forwards- // check/install back. Cookie-authed, unlike the Bearer-token shutdown above, so it- // carries the auth middleware on its own subtree — the routes then gate on- // `sessionVia === "desktop"`, i.e. the shell's own window.- app.use("/api/desktop/update", authMiddleware(deps.authService, deps.config.trustProxy));- app.use("/api/desktop/update/*", authMiddleware(deps.authService, deps.config.trustProxy));- app.route("/api/desktop/update", desktopUpdateRoutes(deps));- // The tray-icon preference rides the same relay and the same shell-window gate: it is- // the Settings › Appearance switch reaching the chrome around the window it runs in.- app.use("/api/desktop/tray", authMiddleware(deps.authService, deps.config.trustProxy));- app.route("/api/desktop/tray", desktopTrayRoutes(deps));- }- // Hot platform APIs run their own gate — the network gate, then the SAME auth middleware- // the routes below use (the boot's local API token as `Authorization: Bearer`, or an admin- // cookie session) with an admin check on top; see hmr/routes.ts. That is why they mount- // above the blanket /api/* middleware rather than under it.- app.route("/api/hmr", hmrRoutes(deps));-- // THE seam: from here down, every route is one the platform may take over by push. Mounted- // after /api/hmr (which stays runtime-owned — see http-seam.ts) and before both the auth- // gate and the built-in routes, so a pushed platform can add endpoints, replace existing- // ones, and decide its own authentication. Declining costs one property read and lands on- // the runtime's own routes below, which is what a platform without an `http` handler does.- app.use("*", platformHttpSeam(deps.hmr));-- // Every protected business route — /api/me through /api/sessions, and /preview — is- // served by the platform through the seam above (see app.ts). What- // follows is the runtime's own tail: static hosting and the SPA fallback.+ // THE seam: every route is one the platform may take over by push — the upgrade channel+ // included, which the platform declares and contributes like any other group+ // (hmr/routes.ts; a generation without it is refused before commit, see packages/hmr's+ // admitsUpgradeRoute). Declining costs one property read and lands on the layer's own+ // tail below, which is what a platform without an `http` handler does.+ app.use("*", platformHttpSeam(deps.control));++ // Every route but /api/hmr is the platform's, served through the seam above. What follows+ // is the layer's own tail: static hosting and the SPA fallback.// Static hosting (production): serves the frontend build output with SPA fallback to// index.html. The source resolves per request — the hot host can point it at adiff --git a/packages/server/src/auth/runtime-state.ts b/packages/server/src/auth/runtime-state.tsindex fc375346..da17e05b 100644--- a/packages/server/src/auth/runtime-state.ts+++ b/packages/server/src/auth/runtime-state.ts@@ -9,7 +9,7 @@* boot — a swap that forgot it would 401 every CLI and every command subprocess still* holding the file's value.*- * That is the state layer of the four-layer model (hmr/README.md): a runtime resource the+ * That is the state layer of the four-layer model (packages/hmr/README.md): a runtime resource the* platform claims, riding across swaps and never across restarts. The holder is deliberately* a plain mutable bag rather than a service — it carries no behaviour to go stale, so a* platform newer than its runtime can still use one an older runtime published.diff --git a/packages/server/src/config.ts b/packages/server/src/config.tsindex 4aa3b932..a404410d 100644--- a/packages/server/src/config.ts+++ b/packages/server/src/config.ts@@ -69,7 +69,7 @@ export interface ServerConfig {*/supervised: boolean;/**- * Port announcement file (PENGUIN_PORT_FILE): after the listener is up, the actual+ * Port announcement file (PENGUIN_PORT_FILE): once the App is up, the actual* bound port is written here — the supervising process's way to learn the port when* it starts the server with PORT=0.*/diff --git a/packages/server/src/hmr/README.md b/packages/server/src/hmr/README.mddeleted file mode 100644index 2f64a55f..00000000--- a/packages/server/src/hmr/README.md+++ /dev/null@@ -1,107 +0,0 @@-# The runtime layer — mechanism only--This directory is the heart of the **runtime**: the layer that boots, transports and hot-swaps-everything else. Read this before changing anything here (or in-`packages/desktop/`, or in core's environment tooling — the other runtime homes).--## The four layers--| Layer | Lives in | How it ships |-| ------------ | ----------------------------------------------- | --------------------------------- |-| **runtime** | `hmr/`, `packages/desktop/`, server transport | Rebuild + redeploy every install |-| **platform** | `packages/server/src/hmr/platform.ts` + `app.ts` | One HTTP push, seconds, no restart|-| **workflow** | An agent's own folder | Installed/reloaded per agent |-| **state** | Parked context documents / runtime resources | Rides across swaps, not restarts |--## The rule--**The runtime carries mechanism. It must not carry policy.**--Mechanism is the machinery that is the same no matter what the product does: HTTP transport,-SSE channels, the network gate, the kernel's park → migrate → boot swap, the resource registry,-artifact storage and the atomic `harness.json` commit.--Authentication is NOT on that list, and used to be. Who may set a password, how long a session-lasts, how logins are throttled — that is policy, and a runtime that owned it made every auth-fix wait for a full reinstall: a platform naming a member an older runtime's AuthService lacked-was refused at the handshake. The App builds its own AuthService now (the `auth` module under src/modules).-What the runtime still publishes is `runtime:auth-state`, the process-scoped values a push must-not forget — the state layer, not a capability.--Policy is everything a deployment might reasonably want to change: business APIs, what an agent-sees, what a command does, how a capability behaves. Policy belongs in the **platform**, which is-hot-swappable.--## Why this matters more than it looks--A runtime change costs a full artifact rebuild and a redeploy of **every installation** — and-until that redeploy lands, the fix does not exist for users. A platform change is one HTTP push-that takes seconds and needs no restart. Every behavior misfiled into the runtime is a fix that-arrives weeks late.--## The test to apply BEFORE editing runtime code--1. Which layer owns this **behavior** in the four-layer model?-2. Can it be delivered by a platform push instead? If yes, it must be.-3. If it truly must live here, be able to say why in one sentence — "it is transport, security,- kernel, or a one-time primitive the hot layers build on".--### The trap: "fix where the code is"--The single most common way this rule gets broken is finding the line that misbehaves and editing-it there. Today most behavior still physically lives in runtime files, so "fix at the fault site"-lands in the runtime almost every time. **The fault site is not the owner.** Decide the layer-first, then choose the edit site — not the reverse.--### The enabler people forget--Platform code executes **inside the server process**. Anything achievable in-process is therefore-deliverable by a hot push, with zero runtime change — including effects that look like they-belong to the shell, e.g. extending `process.env.PATH` so the agent's spawned shells inherit it.-Before touching the runtime, ask whether a platform `boot()` could do the same thing.--## The route table is not a runtime asset--The runtime mounts ONE seam (`http-seam.ts`) before its own routes: the running platform gets-first refusal on every request and answers `null` for the ones it does not own. A pushed-platform can therefore add an endpoint, replace an existing one, or serve something else-entirely — with no rebuild. The RPC dispatch route that used to stand in for this-(`POST /api/hmr/platform/call`) is gone with it: it made *methods* pushable, which is not the-same thing — a method has no path, no verb and no status code, and every client would have had-to speak that envelope instead of the API it already speaks.--Two boundaries keep it safe, and both are load-bearing:--- **`/api/hmr/*` is never offered to the platform.** It is the channel a broken platform gets- replaced through; if a push could claim it, one bad push would lock the installation out for- good.-- **A platform that throws does not fall through.** It claimed the request; running the- runtime's older handler instead would answer with semantics the caller was not promised. The- error surfaces as a 500.--A streaming response rides the seam unchanged — the handler returns a whole `Response` as-soon as the stream exists and keeps writing to it, which is what the platform's SSE endpoints-do. A live **socket** is what the seam cannot carry, there being no `Response` to return for-one, so the terminal WebSocket handshake reaches the App through in-process members instead.-That is a property of the contract, not a layer boundary.--## Worked examples (all real, all from review)--- **Opening DevTools from the web UI** — a preload bridge was added to the Electron shell so the- app could open DevTools. Rejected and reverted: the shell already ships- Ctrl+Shift+I, so the "capability" bought nothing and cost the window's zero-preload security- posture. An app-level convenience is never a reason to grow runtime surface.-- **The agent could not find the `penguin` CLI** — the first fix injected `PATH` when the Electron- shell forked the server. Rejected: "what environment the agent sees" is policy. It belongs in- the platform's `boot()`, where it also reaches already-deployed machines through a normal push.-- **New business APIs** — the HTTP seam offers every request to the booted platform, which- serves the ones it owns. This is the mechanism that keeps business APIs out of the runtime- permanently: a pushed bundle adds, changes or drops endpoints with no route change here.- Adding a route per business API is the anti-pattern it exists to prevent.--## What does legitimately justify a runtime change--Transport and security mechanism, kernel evolution, and one-time primitives the hot layers build-on (for example: making a web push one gzip artifact served from memory, so pushes stop-serializing on per-file disk writes). If a change is none of those, it is probably policy —-put it in the platform.diff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.tsindex a96e9e9f..9eda47b9 100644--- a/packages/server/src/hmr/capabilities.ts+++ b/packages/server/src/hmr/capabilities.ts@@ -14,7 +14,7 @@* back into it and every reader must observe that write).** What a booting platform does when the capabilities are missing or wrong — refuse, or- * run terminals-only for a declared bare kernel — is {@link RuntimeClaim}'s story, below.+ * run terminals-only for a declared bare kernel — is {@link HmrClaim}'s story, below.** There is no reverse direction here: the runtime reaches the current App through the* instance `hmr.ensure()` already returns (in-process api members), never through the@@ -27,7 +27,11 @@ import type { AuthRuntimeState } from "../auth/runtime-state.js";import { newAuthRuntimeState } from "../auth/runtime-state.js";import type { ChannelHub, Channel } from "../runtime/channel.js";import type { ProxySettings } from "../net/proxy.js";-import type { HmrHost } from "./host.js";+import type { HmrHost, Hmr as HmrControlOf } from "@prismshadow/penguin-hmr";+import type { PlatformApi } from "./platform.js";++/** The control object the entry built (hmrMain): `current()` and `upgrade()`. */+export type HmrControlApi = HmrControlOf<PlatformApi>;import type { DesktopService } from "../services/desktop-service.js";import type { LifecycleService } from "../services/lifecycle-service.js";import { Interface, Component, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";@@ -75,7 +79,7 @@ export type MembersOf<T> = readonly (keyof T & string)[];export const PENGUIN_FAMILY = "penguin";/**- * The interfaces the RUNTIME publishes for a platform to claim: per `runtime:*`+ * The interfaces the HMR LAYER publishes for a platform to claim: per `runtime:*`* capability, the members a claimer reaches for. The runtime registers this descriptor* and a bundle checks it — and the live objects behind it — against the copy compiled* into itself, so a mismatch declines the claim at boot instead of surfacing as a@@ -83,7 +87,7 @@ export const PENGUIN_FAMILY = "penguin";** `proxy` is a bare callable: an empty member set means "nothing beyond being there".*/-interface RuntimeInterfaces extends Interfaces {+interface HmrInterfaces extends Interfaces {family: string;config: MembersOf<ServerConfig>;db: MembersOf<DatabaseSync>;@@ -94,7 +98,7 @@ interface RuntimeInterfaces extends Interfaces {lifecycle: MembersOf<LifecycleService>;}-export const RUNTIME_INTERFACES: RuntimeInterfaces = {+export const HMR_INTERFACES: HmrInterfaces = {family: PENGUIN_FAMILY,config: ["root",@@ -115,6 +119,7 @@ export const RUNTIME_INTERFACES: RuntimeInterfaces = {channels: ["get", "peek", "broadcast", "dispose", "setActivityProbe"],proxy: [],hmr: ["resources", "ensure", "resolveWebSource", "assetsDir", "dispose"],+ hmrControl: ["current", "upgrade", "endpoint"],// The replacement seam (Replacements): production publishes [], tests publish the nodes// they stand in for. Presence-only — a list has no members to verify.overrides: [],@@ -122,7 +127,7 @@ export const RUNTIME_INTERFACES: RuntimeInterfaces = {lifecycle: ["supervised", "onRestartRequest", "requestRestart"],};-export const RUNTIME_INTERFACES_RESOURCE_ID = "runtime:interfaces";+export const HMR_INTERFACES_RESOURCE_ID = "platform.interfaces";/** The member set an entry names, or [] when the entry is absent or is the family tag. */function members(descriptor: Interfaces, name: string): readonly string[] | undefined {@@ -167,34 +172,33 @@ export function lacksMembers(value: unknown, need: readonly string[]): string[]return need.filter((m) => (value as Record<string, unknown>)[m] === undefined);}-export const RUNTIME_CONFIG_RESOURCE_ID = "runtime:config";-export const RUNTIME_DB_RESOURCE_ID = "runtime:db";-/**- * Process-scoped auth STATE (auth/runtime-state.ts), not an auth service: authentication is- * business behaviour the platform builds for itself, so it ships by push. Only the values that- * must ride across a swap and die at a restart live here. Claimed optionally — a runtime older- * than this resource simply gives the platform a fresh holder, which costs one reprint of the- * first-login link and nothing else.- */-export const RUNTIME_AUTH_STATE_RESOURCE_ID = "runtime:auth-state";-export const RUNTIME_CHANNELS_RESOURCE_ID = "runtime:channels";-export const RUNTIME_PROXY_RESOURCE_ID = "runtime:proxy-control";-export const RUNTIME_HMR_RESOURCE_ID = "runtime:hmr-host";+// What the layer publishes for the platform to claim: the platform's state, kept by the process+// so a swap does not lose it. Ids are `platform.<name>`, the plugin-id shape.++export const HMR_CONFIG_RESOURCE_ID = "platform.config";+export const HMR_DB_RESOURCE_ID = "platform.db";+export const HMR_CHANNELS_RESOURCE_ID = "platform.channels";+export const HMR_PROXY_RESOURCE_ID = "platform.proxyControl";+export const HMR_HOST_RESOURCE_ID = "platform.host";+/** The frozen operations over the host (packages/hmr's main.ts): what the upgrade route drives. */+export const HMR_CONTROL_RESOURCE_ID = "platform.hmrControl";/*** Desktop mode's one service (one-shot login + shutdown token holder). Registered even- * when null: desktop-ness is the runtime's lifecycle fact, but the business surface- * reads it too (`/api/me` reports desktopMode; single-user mode closes the multi-user- * admin surfaces), so the claim must distinguish "not desktop" from "not published".+ * when null — the platform reads desktop-ness too (`/api/me`, single-user mode), so the+ * claim must distinguish "not desktop" from "not published".*/-export const RUNTIME_DESKTOP_RESOURCE_ID = "runtime:desktop";+export const HMR_DESKTOP_RESOURCE_ID = "platform.desktop";+/** Whether a supervisor relaunches this process, and the restart trigger. Always published. */+export const HMR_LIFECYCLE_RESOURCE_ID = "platform.lifecycle";+/**- * Process lifecycle (services/lifecycle-service.ts): whether a supervisor relaunches this- * process, and the restart trigger. Always published — the platform's restart route needs- * a definite "nobody would relaunch me" to refuse with, not a missing capability.+ * Process-scoped auth values (auth/runtime-state.ts), not an auth service. Claimed+ * optionally: a layer older than the holder gives the platform a fresh one, which costs one+ * reprint of the first-login link.*/-export const RUNTIME_LIFECYCLE_RESOURCE_ID = "runtime:lifecycle";-/** Test-only: the node Replacements published by bootAppDeps for the platform boot to claim. */-export const RUNTIME_OVERRIDES_RESOURCE_ID = "runtime:overrides";+export const HMR_AUTH_STATE_RESOURCE_ID = "platform.authState";+/** Test-only: the node Replacements bootAppDeps leaves for the platform boot to claim. */+export const HMR_OVERRIDES_RESOURCE_ID = "platform.overrides";/*** The {@link Interfaces} descriptor each App leaves for its successor, naming the@@ -204,11 +208,10 @@ export const RUNTIME_OVERRIDES_RESOURCE_ID = "runtime:overrides";* registration order) before it adopts anything. Riding the registry, not the kernel* iface, keeps the swap mechanism untouched and the policy itself hot-pushable.*- * Deliberately colon-free: an ID without a group can never be swept by disposeGroup —- * the declaration must outlive the App that wrote it (its dispose effect does NOT- * release it) to inform the successor.+ * Not in any `<group>:` — disposeGroup never sweeps it: the declaration must outlive the App+ * that wrote it (its dispose effect does NOT release it) to inform the successor.*/-export const RESOURCE_IFACES_RESOURCE_ID = "resource-interfaces";+export const RESOURCE_IFACES_RESOURCE_ID = "platform.resourceInterfaces";/** There is deliberately NO reverse-direction registry entry. The runtime already holds@@ -225,7 +228,7 @@ export const RESOURCE_IFACES_RESOURCE_ID = "resource-interfaces";export type ProxyControl = (settings: ProxySettings) => void;/** Everything buildAppDeps needs, claimed in one place. */-export interface RuntimeCapabilities {+export interface HmrCapabilities {config: ServerConfig;db: DatabaseSync;/** Process-scoped auth values; the AuthService itself is built per App (see buildAppDeps). */@@ -233,6 +236,7 @@ export interface RuntimeCapabilities {channels: ChannelHub;proxyControl: ProxyControl;hmr: HmrHost;+ hmrControl: HmrControlApi;/** Null on a non-desktop server (a real value, not an absent capability). */desktop: DesktopService | null;lifecycle: LifecycleService;@@ -255,49 +259,50 @@ export interface RuntimeCapabilities {* carry what the descriptor promised. Booting a business platform over any of these* would put a new frontend in front of an older runtime's own routes.*/-export type RuntimeClaim =- | { kind: "claimed"; caps: RuntimeCapabilities }+export type HmrClaim =+ | { kind: "claimed"; caps: HmrCapabilities }| { kind: "bare" }| { kind: "refused"; reason: string };-export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {- const offered = resources.claim<Interfaces>(RUNTIME_INTERFACES_RESOURCE_ID);+export function claimHmrCapabilities(resources: Resources): HmrClaim {+ const offered = resources.claim<Interfaces>(HMR_INTERFACES_RESOURCE_ID);if (offered === undefined) {return { kind: "refused", reason: "no interface descriptor published" };}- if (offered.family !== RUNTIME_INTERFACES.family) {+ if (offered.family !== HMR_INTERFACES.family) {return {kind: "refused",- reason: `family '${String(offered.family)}' != '${String(RUNTIME_INTERFACES.family)}'`,+ reason: `family '${String(offered.family)}' != '${String(HMR_INTERFACES.family)}'`,};}// A family-matching descriptor that offers none of the required capabilities IS the// bare-kernel declaration; offering SOME of them is a broken runtime, refused below.- const required = Object.keys(RUNTIME_INTERFACES).filter((name) => name !== "family");+ const required = Object.keys(HMR_INTERFACES).filter((name) => name !== "family");if (required.every((name) => members(offered, name) === undefined)) {return { kind: "bare" };}- const mismatch = interfaceMismatch(offered, RUNTIME_INTERFACES);+ const mismatch = interfaceMismatch(offered, HMR_INTERFACES);if (mismatch !== null) return { kind: "refused", reason: mismatch };- const config = resources.claim<ServerConfig>(RUNTIME_CONFIG_RESOURCE_ID);- const db = resources.claim<DatabaseSync>(RUNTIME_DB_RESOURCE_ID);- const channels = resources.claim<ChannelHub>(RUNTIME_CHANNELS_RESOURCE_ID);- const proxyControl = resources.claim<ProxyControl>(RUNTIME_PROXY_RESOURCE_ID);- const hmr = resources.claim<HmrHost>(RUNTIME_HMR_RESOURCE_ID);- const lifecycle = resources.claim<LifecycleService>(RUNTIME_LIFECYCLE_RESOURCE_ID);- if (!config || !db || !channels || !proxyControl || !hmr || !lifecycle) {+ const config = resources.claim<ServerConfig>(HMR_CONFIG_RESOURCE_ID);+ const db = resources.claim<DatabaseSync>(HMR_DB_RESOURCE_ID);+ const channels = resources.claim<ChannelHub>(HMR_CHANNELS_RESOURCE_ID);+ const proxyControl = resources.claim<ProxyControl>(HMR_PROXY_RESOURCE_ID);+ const hmr = resources.claim<HmrHost>(HMR_HOST_RESOURCE_ID);+ const hmrControl = resources.claim<HmrControlApi>(HMR_CONTROL_RESOURCE_ID);+ const lifecycle = resources.claim<LifecycleService>(HMR_LIFECYCLE_RESOURCE_ID);+ if (!config || !db || !channels || !proxyControl || !hmr || !hmrControl || !lifecycle) {return { kind: "refused", reason: "a declared capability was not actually published" };}// Desktop is nullable by meaning, so it sits outside the all-present check.- const desktop = resources.claim<DesktopService | null>(RUNTIME_DESKTOP_RESOURCE_ID) ?? null;- const replacements = resources.claim<Replacements>(RUNTIME_OVERRIDES_RESOURCE_ID) ?? [];+ const desktop = resources.claim<DesktopService | null>(HMR_DESKTOP_RESOURCE_ID) ?? null;+ const replacements = resources.claim<Replacements>(HMR_OVERRIDES_RESOURCE_ID) ?? [];// Optional by design (see the resource's own note): an older runtime published no such// holder, and a fresh one is a correct, slightly forgetful substitute. A runtime older// than this platform may also publish a holder missing the fields added since; they are// filled IN PLACE, never by copying — the bag is shared with the runtime by identity, and// a copy would strand every write the App makes to it.const authState =- resources.claim<AuthRuntimeState>(RUNTIME_AUTH_STATE_RESOURCE_ID) ?? newAuthRuntimeState();+ resources.claim<AuthRuntimeState>(HMR_AUTH_STATE_RESOURCE_ID) ?? newAuthRuntimeState();authState.firstLoginToken ??= null;authState.apiToken ??= null;// …then the objects themselves. A descriptor is a claim about what is there; this is@@ -309,11 +314,12 @@ export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {["channels", channels],["proxy", proxyControl],["hmr", hmr],+ ["hmrControl", hmrControl],["lifecycle", lifecycle],...(desktop === null ? [] : ([["desktop", desktop]] as Array<[string, unknown]>)),];for (const [name, value] of live) {- const need = RUNTIME_INTERFACES[name];+ const need = HMR_INTERFACES[name];if (!Array.isArray(need)) continue;const lacking = lacksMembers(value, need);if (lacking.length > 0) {@@ -322,7 +328,18 @@ export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {}return {kind: "claimed",- caps: { config, db, authState, channels, proxyControl, hmr, desktop, lifecycle, replacements },+ caps: {+ config,+ db,+ authState,+ channels,+ proxyControl,+ hmr,+ hmrControl,+ desktop,+ lifecycle,+ replacements,+ },};}@@ -375,6 +392,18 @@ export abstract class Hmr extends Interface<{}>() {}export type _HmrCheck = HmrHost extends Hmr ? true : never;+/**+ * The frozen operations (packages/hmr's main.ts), as the platform's routes drive them. The+ * instance and the outcome are host objects to the contract, like `Hmr`'s.+ */+export abstract class HmrControl extends Interface<{+ current(): Promise<Opaque<"PlatformInstance", Awaited<ReturnType<HmrHost["ensure"]>>>>;+ upgrade(+ target: Opaque<"UpgradeAllTarget", Parameters<HmrHost["upgradeAll"]>[0]>,+ ): Promise<Opaque<"UpgradeOutcome", Awaited<ReturnType<HmrHost["upgradeAll"]>>>>;+ endpoint(request: Opaque<"Request", Request>): Promise<Opaque<"Response", Response>>;+}>() {}+export type DesktopApi = Pick<DesktopService,| "verifyToken"@@ -385,6 +414,10 @@ export type DesktopApi = Pick<| "setUpdateStatus"| "onUpdateCommand"| "requestUpdateCommand"+ | "getTrayStatus"+ | "setTrayStatus"+ | "onTrayCommand"+ | "requestTrayCommand">;/** The desktop shell's service, or null when this server is not the shell's child. */@@ -405,7 +438,7 @@ export abstract class Log extends Interface<{/*** Whether a registry resource group inherited from the previous App may be adopted — the- * platform node decides from the resource-interfaces declaration (hmr/platform.ts); a+ * platform node decides from the parked declaration (hmr/platform.ts); a* module that parks handles asks before claiming them back.*/export abstract class ResourceGroups extends Interface<{@@ -435,7 +468,7 @@ export type Replacements = ReadonlyArray<readonly [ModuleClass, object]>;@Module()export class RuntimeConfig {@Provide() config!: Config;- constructor(private readonly caps: RuntimeCapabilities) {}+ constructor(private readonly caps: HmrCapabilities) {}setup() {this.config = this.caps.config;}@@ -443,7 +476,7 @@ export class RuntimeConfig {@Module()export class RuntimeDb {@Provide() db!: Db;- constructor(private readonly caps: RuntimeCapabilities) {}+ constructor(private readonly caps: HmrCapabilities) {}setup() {this.db = this.caps.db;}@@ -451,7 +484,7 @@ export class RuntimeDb {@Module()export class RuntimeChannels {@Provide() channels!: Channels;- constructor(private readonly caps: RuntimeCapabilities) {}+ constructor(private readonly caps: HmrCapabilities) {}setup() {this.channels = this.caps.channels;}@@ -459,7 +492,7 @@ export class RuntimeChannels {@Module()export class RuntimeProxy {@Provide() proxy!: Proxy;- constructor(private readonly caps: RuntimeCapabilities) {}+ constructor(private readonly caps: HmrCapabilities) {}setup() {this.proxy = { apply: this.caps.proxyControl };}@@ -467,15 +500,23 @@ export class RuntimeProxy {@Module()export class RuntimeHmr {@Provide() hmr!: Hmr;- constructor(private readonly caps: RuntimeCapabilities) {}+ constructor(private readonly caps: HmrCapabilities) {}setup() {this.hmr = this.caps.hmr;}}@Module()+export class RuntimeHmrControl {+ @Provide() hmrControl!: HmrControl;+ constructor(private readonly caps: HmrCapabilities) {}+ setup() {+ this.hmrControl = this.caps.hmrControl;+ }+}+@Module()export class RuntimeDesktop {@Provide() desktop!: Desktop;- constructor(private readonly caps: RuntimeCapabilities) {}+ constructor(private readonly caps: HmrCapabilities) {}setup() {const { desktop } = this.caps;this.desktop = { current: () => desktop };@@ -484,7 +525,7 @@ export class RuntimeDesktop {@Module()export class RuntimeLifecycle {@Provide() lifecycle!: Lifecycle;- constructor(private readonly caps: RuntimeCapabilities) {}+ constructor(private readonly caps: HmrCapabilities) {}setup() {this.lifecycle = this.caps.lifecycle;}@@ -492,7 +533,7 @@ export class RuntimeLifecycle {@Module()export class RuntimeAuthState {@Provide() authState!: AuthState;- constructor(private readonly caps: RuntimeCapabilities) {}+ constructor(private readonly caps: HmrCapabilities) {}setup() {this.authState = this.caps.authState;}diff --git a/packages/server/src/hmr/http-seam.ts b/packages/server/src/hmr/http-seam.tsindex 48ea429d..9fc7b59d 100644--- a/packages/server/src/hmr/http-seam.ts+++ b/packages/server/src/hmr/http-seam.ts@@ -14,11 +14,14 @@** Two boundaries make that safe:*- * - **`/api/hmr/*` is never offered.** It is the channel a broken platform is replaced through;- * if a push could claim it, one bad push would lock the installation out permanently.* - **A platform that throws does not fall through.** It claimed the request by throwing rather* than declining, and quietly running the runtime's older handler instead would answer with* different semantics than the caller was promised. The error surfaces as a 500.+ * - **No platform at all is not a decline either.** When no generation is current the request+ * is answered 503, not passed to the static tail: the tail would serve the SPA shell for+ * any path, and an API call would come back 200 with an HTML body that means nothing.+ * (The upgrade channel is the platform's own route, so a box in this state is pushed to+ * through the previous generation's closures — see the host's recovery.)** The contract is one function wide — Request in, whole Response out — and a streaming body* rides it unchanged: the platform's SSE endpoints (`/api/events`, a session's event stream)@@ -28,10 +31,9 @@* (`terminals()`, `attachStream()`) instead.*/import type { MiddlewareHandler } from "hono";-import type { HmrHost } from "./host.js";--/** Prefix the runtime keeps for itself, whatever the platform says. */-const RESERVED_PREFIX = "/api/hmr";+import type { Hmr } from "@prismshadow/penguin-hmr";+import type { PlatformApi } from "./platform.js";+import { noPlatformResponse } from "./starting.js";/*** A platform that wants to serve HTTP exposes this. Optional on purpose: a platform pushed@@ -51,25 +53,19 @@ export interface PlatformHttp {* `hmr.ensure()` returns the already-booted instance after the first call, so this costs a* property read per request once the platform is up.*/-export function platformHttpSeam(hmr: HmrHost): MiddlewareHandler {+export function platformHttpSeam(hmr: Hmr<PlatformApi>): MiddlewareHandler {return async (c, next) => {- if (c.req.path.startsWith(RESERVED_PREFIX)) return next();- // Wait out any in-flight swap FIRST, same as /api/hmr/*'s own gate (routes.ts): the- // kernel's upgrade() disposes the old tree before it awaits the new one's boot, and for- // that whole window `hmr.ensure()` still resolves synchronously to the OLD instance —- // it only reassigns once the swap is done. Without this wait, a request landing in that- // window would be handed to an already-disposed tree instead of observing the freeze as- // latency (see host.ts's module doc: "a client never observes the stop-the-world- // window").- await hmr.waitIdle();+ // Which generation a request goes to — including waiting out an in-flight swap — is the+ // frozen operation `current()` (packages/hmr's main.ts); this seam only hands over.let handler: PlatformHttp["http"];try {- const instance = await hmr.ensure();+ const instance = await hmr.current();handler = (instance.api as PlatformHttp).http?.bind(instance.api);- } catch {- // The platform cannot boot: the runtime's own routes are the fallback, and the- // upgrade channel above is still reachable to push a working one.- return next();+ } catch (err) {+ // Not a decline: there is no generation to decline anything. Answering here rather+ // than falling through keeps "no platform" distinguishable from "the platform does+ // not serve this path", which is a 404 the platform itself gives.+ return noPlatformResponse(err instanceof Error ? err.message : String(err));}if (!handler) return next();diff --git a/packages/server/src/hmr/manifest.ts b/packages/server/src/hmr/manifest.tsindex 070c643d..e7d6dbcf 100644--- a/packages/server/src/hmr/manifest.ts+++ b/packages/server/src/hmr/manifest.ts@@ -1,135 +1,9 @@/**- * The harness.json shape (`<root>/hmr/harness.json`) and pure readers over it.+ * The `harness.json` reader, re-exported so this package's published `./hmr/manifest`+ * subpath keeps working: the CLI's thin loader resolves the committed cli bundle through it+ * with no server in the process, and that entry point is a contract with installed CLIs.*- * Split out of host.ts so a reader never needs a running HmrHost: `penguin` is a- * separate, short-lived process per invocation (see packages/cli/src/index.ts) — it- * has no host instance to ask, only the data root's own harness.json on disk.- * `resolveCliBundlePath` is that reader: a plain disk read, no HTTP, no boot, no- * in-memory state.- *- * ONE atomic version, THREE independent artifacts: `platform`, `cli`, and `web` are- * always written together by HmrHost's single merged upgrade path (see host.ts's- * persistVersion), but each is content-addressed and stored on its own — a push to- * POST /api/hmr/upgrade carries `platform` and `cli` as two separate single-file ESM- * sources, so `cli.bundle` points at its OWN file, a different sha from- * `platform.bundle`. They are read back together too (see host.ts's restore): a- * partial record (e.g. `platform` present but `web` or `cli` missing) is never- * trusted — the whole version is treated as absent instead of partially applied.- */-import fs from "node:fs";-import fsp from "node:fs/promises";-import path from "node:path";-import type { HarnessInfo } from "@prismshadow/penguin-core";--/**- * The committed on-disk record: a runtime restart resumes exactly this CODE (platform,- * cli, web). It carries no STATE — a restart always boots the resumed platform bundle- * against its own fresh initial context (bundle.context, see host.ts's PlatformBundle),- * never a document parked from a previous run (see host.ts's module doc for why: a- * parked doc's live-resource handles die with the process anyway, so resuming one could- * only ever produce handles that fail to reclaim). Paths are relative to hmrDir- * (`<root>/hmr`).- */-/**- * Written into an assets directory once every file in it is on disk. Its absence marks a- * directory whose materialization was interrupted; no asset path can collide with it- * (assets arrive as `node_modules/...` paths).- */-export const MATERIALIZED = ".materialized";--export interface Manifest {- platform?: { bundle: string };- /**- * The CLI's own bundle pointer — its own independent file (a different sha from- * `platform.bundle`; the two are separately compiled artifacts), kept as its own- * field so a reader that only wants "which bundle does the CLI load right now"- * never has to reach into `platform` at all.- */- cli?: { bundle: string };- /** One gzip(JSON.stringify({ files })) artifact, restored straight into memory. */- web?: { manifest: string };- /**- * Files the pushed platform needs as REAL files on disk, unpacked under this directory- * (relative to hmrDir). The web artifact stays in memory because it is only ever served- * as bytes; an asset is something the platform hands to the OS — a native `.node` the- * loader must resolve by path, a helper binary it execs — so it has to exist on the- * filesystem, with its exec bit intact.- */- assets?: { dir: string };- /**- * Provenance of the push that produced this version, exactly as the pushing client sent- * it (scripts/deploy.mjs fills it from its own checkout). Recorded, never executed or- * resolved. Absent for a version pushed without it, and for every version committed- * before the field existed — which is why every reader treats it as optional.- */- source?: { repo: string; revision: string };- /** When this version was committed to the store (ISO 8601). Absent on older records. */- pushedAt?: string;-}--/** A string field of an untrusted manifest, or null unless it is a non-empty string. */-function str(value: unknown): string | null {- return typeof value === "string" && value.length > 0 ? value : null;-}--/**- * What the store has committed, for version reporting: provenance, commit time, and the- * three artifact pointers. Null when nothing has ever been pushed to this root.- *- * Read defensively rather than cast: harness.json is written only by persistVersion, but a- * truncated or hand-edited file must degrade a `penguin version` to missing fields, never- * crash it. A record missing every artifact pointer counts as nothing pushed.- */-export async function readHarnessInfo(root: string): Promise<HarnessInfo | null> {- const manifest = await readManifest(root);- if (manifest === null) return null;-- const bundles = {- platform: str(manifest.platform?.bundle),- cli: str(manifest.cli?.bundle),- web: str(manifest.web?.manifest),- };- if (bundles.platform === null && bundles.cli === null && bundles.web === null) return null;-- const repo = str(manifest.source?.repo);- const revision = str(manifest.source?.revision);- return {- // Both halves or neither: half a provenance names nothing.- source: repo !== null && revision !== null ? { repo, revision } : null,- pushedAt: str(manifest.pushedAt),- bundles,- };-}--/** Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt (nothing committed yet). */-export async function readManifest(root: string): Promise<Manifest | null> {- try {- const raw = await fsp.readFile(path.join(root, "hmr", "harness.json"), "utf8");- return JSON.parse(raw) as Manifest;- } catch {- return null;- }-}--/**- * Resolves the current CLI bundle's absolute path from a data root, or null when- * nothing has been pushed yet: a fresh root, a missing/corrupt manifest, no `cli`- * entry, a `cli.bundle` that isn't a non-empty string (e.g. `{"cli":{}}` — a- * hand-edited or truncated harness.json), a path that resolves outside `<root>/hmr/`- * (defense in depth: `manifest.cli.bundle` is trusted content today, written only by- * this same process's persistVersion, but a reader must never let a malformed or- * malicious manifest value walk it out of the store directory via `..` segments), or- * a referenced file that no longer exists (e.g. pruned from the store — see host.ts's- * pruneStore). A null return means "use the packaged default" to every caller;- * nothing here ever throws for an ordinary unconfigured or malformed root.+ * The reader itself is the hot-update MECHANISM and lives with the rest of it+ * (@prismshadow/penguin-hmr) — see that package's README for what may go in there.*/-export async function resolveCliBundlePath(root: string): Promise<string | null> {- const manifest = await readManifest(root);- const bundle = manifest?.cli?.bundle;- if (typeof bundle !== "string" || bundle.length === 0) return null;- const hmrDir = path.join(root, "hmr");- const abs = path.resolve(hmrDir, bundle);- const withinHmrDir = abs === hmrDir || abs.startsWith(hmrDir + path.sep);- if (!withinHmrDir) return null;- return fs.existsSync(abs) ? abs : null;-}+export * from "@prismshadow/penguin-hmr/manifest";diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.tsindex ae2e298d..8efaf75b 100644--- a/packages/server/src/hmr/platform.ts+++ b/packages/server/src/hmr/platform.ts@@ -13,7 +13,7 @@* instead of a rebuild. Worth remembering when something looks like it must* live in the shell: this code runs INSIDE the server process, so in-process* effects (e.g. extending process.env for the shells agents spawn) are- * deliverable from boot() with no runtime change. See ../hmr/README.md.+ * deliverable from boot() with no runtime change. See packages/hmr/README.md.** This packaged platform carries the WHOLE business surface (see app.ts):* every business service and route is assembled inside create() over the runtime's@@ -39,7 +39,7 @@ import {bootModules,moduleDefOf,} from "@prismshadow/penguin-core/kernel";-import type { PlatformBundle } from "./host.js";+import type { HmrHost, PlatformBundle } from "@prismshadow/penguin-hmr";import { TerminalManager } from "../terminal/manager.js";import type { TerminalSession } from "../terminal/session.js";import { identityFrom } from "../terminal/identity.js";@@ -56,15 +56,25 @@ import { declined, seamHttp } from "./hono-seam.js";import {PENGUIN_FAMILY,RESOURCE_IFACES_RESOURCE_ID,- claimRuntimeCapabilities,+ claimHmrCapabilities,+ Log,} from "./capabilities.js";import type { Interfaces, MembersOf } from "./capabilities.js";import { pluginHostFrom } from "../plugin/host.js";import { migrate } from "../db/migrations.js";import type { Auth } from "../mechanisms/identity.js";+/**+ * This server's hot host: the mechanism (@prismshadow/penguin-hmr) with the api ITS platforms+ * expose. The mechanism is generic on purpose — it cannot name a route or a service — so the+ * product supplies the type here, once, and everything that holds a host uses this alias.+ */+export type ServerHmrHost = HmrHost<PlatformApi>;+export interface PlatformApi extends Park {info(): Json;+ /** The platform's log. The layer writes its request lines through it while there is one. */+ log(line: string): void;/*** The HTTP seam (hmr/http-seam.ts): every request is offered here first, and null* declines it to the runtime's own routes. This is how a business API ships by push@@ -131,7 +141,7 @@ export const PlatformIface = defineIface<PlatformApi, PlatformCtx>({"modules?": { "[string]": "unknown" },}) as never,),- methods: ["park", "info", "http", "terminals", "attachStream"],+ methods: ["park", "info", "http", "terminals", "attachStream", "log"],});/** The node names the two parking modules were keyed by before nodes were named by class. */@@ -217,12 +227,12 @@ const DRAIN_GRACE_MS = 5000;export const platformImpl: Impl<PlatformApi, PlatformCtx> = {async create(ctx, context) {// The claim comes FIRST, before a single registry read is acted on, and "refused" is a- // throw — what each outcome means and why lives on RuntimeClaim (capabilities.ts).+ // throw — what each outcome means and why lives on HmrClaim (capabilities.ts).// The check sits HERE, in the bundle, because the runtime that needs it is by// definition too old to receive it; failing this early costs nothing — doUpgradeAll// rolls the whole upgrade back, and a hot upgrade cannot land what a fresh start// would refuse (bootAppDeps treats a business-less platform as fatal too).- const claim = claimRuntimeCapabilities(ctx.resources);+ const claim = claimHmrCapabilities(ctx.resources);if (claim.kind === "refused") {throw new Error(`this runtime publishes no business capabilities this platform can claim ` +@@ -366,8 +376,10 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {"http",);const http = httpApi !== undefined ? seamHttp(httpApi) : seamHttp(bareApp(terminals, identity));+ const logNode = business?.api<Log>("RuntimeModule", "Log") ?? null;return {+ log: (line) => (logNode !== null ? logNode.line(line) : console.log(line)),park: () => {const modules = tree.park();// The top-level fields are written for every platform that reads them: a barediff --git a/packages/server/src/hmr/routes.ts b/packages/server/src/hmr/routes.tsindex 11532960..0512653a 100644--- a/packages/server/src/hmr/routes.ts+++ b/packages/server/src/hmr/routes.ts@@ -1,51 +1,40 @@/**- * /api/hmr/*: the hot-update surface.+ * /api/hmr/*: the hot-update surface, declared and contributed like every other route group.*- * The gate middleware is the runtime half of the stop-the-world protocol:- * requests arriving during a swap are ENQUEUED on the host's operation queue- * (awaiting waitIdle), never rejected — a client only ever observes latency,- * not the freeze. The routes are runtime code: they orchestrate through the- * platform api, so they survive impl swaps unchanged.+ * What a push IS — its body, the outcome it answers with, what happens when the pushed+ * generation cannot become current — is the mechanism's, in packages/hmr's main.ts+ * (`upgradeEndpoint`). What is here is the product's: the network gate, who may push, and+ * what clients are told when a version lands. The cookie / API-token gate is the platform's+ * usual middleware, applied after the network gate; admin is checked on top.*- * RUNTIME LAYER — MECHANISM ONLY (see ./README.md). A new business API must NOT- * become a route here. It is served by the platform itself, through the HTTP- * seam (../hmr/http-seam.ts) that offers every request to the booted platform- * before the runtime's own routes see it — a real route with its own path,- * verb and status, rather than an RPC envelope clients would have to learn.- *- * What remains here is the upgrade channel and the status it needs, which is- * the one thing the platform is never offered: it is how a broken platform- * gets replaced.+ * Because the group is the platform's, a generation that does not serve it would leave+ * the installation with no way to push another — so a push is refused before commit when+ * its generation does not answer here (`admitsUpgradeRoute`).*/-import zlib from "node:zlib";import { Hono } from "hono";-import type { ServerConfig } from "../config.js";-import type { HmrHost } from "./host.js";-import type { ChannelHub } from "../runtime/channel.js";--/** What the hot-update routes reach: runtime capabilities and the current App's auth. */-export interface HmrRouteDeps {- hmr: HmrHost;- authService: Auth;- config: ServerConfig;- channels: ChannelHub;-}+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import { authMiddleware } from "../auth/middleware.js";import type { AppEnv } from "../auth/middleware.js";-import { HttpError } from "../http/errors.js";import type { Auth } from "../mechanisms/identity.js";+import { HttpError } from "../http/errors.js";+import { Channels, Config, HmrControl } from "./capabilities.js";+import type { ServerConfig } from "../config.js";+import type { ChannelHub } from "../runtime/channel.js";+import type { HmrControlApi } from "./capabilities.js";/** Bind addresses considered safe by default; anything else needs HTTPS. */const LOOPBACK_HOSTS = new Set(["127.0.0.1", "::1", "localhost"]);+export interface HmrRouteDeps {+ control: HmrControlApi;+ /** The platform's auth, applied here after the network gate rather than by the group's `auth: "user"`, so a plaintext public bind is refused before any credential is looked at. */+ auth: Auth;+ config: Pick<ServerConfig, "host" | "trustProxy">;+ channels: Pick<ChannelHub, "broadcast">;+}+export function hmrRoutes(deps: HmrRouteDeps): Hono<AppEnv> {const routes = new Hono<AppEnv>();- const hmr = deps.hmr;- // Mounted BEFORE the global cookie-auth middleware (see app.ts): this gate- // does its own auth (admin cookie only — see the network gate above for the- // other half) rather than relying on the generic middleware being mounted- // later.- const cookieAuth = authMiddleware(deps.authService, deps.config.trustProxy);routes.use("*", async (c, next) => {// Dangerous-network off: hot APIs load and run code, so on a non-loopback@@ -72,134 +61,64 @@ export function hmrRoutes(deps: HmrRouteDeps): Hono<AppEnv> {);}}- const gated = async (): Promise<void> => {- // The upgrade endpoint enqueues internally; everything else waits out- // any in-flight swap here (unobservable freeze: latency, not errors).- if (!c.req.path.endsWith("/upgrade")) await hmr.waitIdle();- await next();- };- // Admin credential required. An earlier per-boot Bearer token published to- // $PENGUIN_HOME/hmr/api.json was removed over the on-disk-plaintext objection- // (readable by any process of the same OS user, agent shells included, and- // admin-equivalent). That objection has since been deliberately reversed as a- // product decision, harness-wide: agents driving their own server through the- // CLI is the feature, and local filesystem access to the data root is defined- // as admin authority (exactly the reset-admin-password rule). The mechanism now- // lives at the general auth layer instead of here: the per-boot local API token- // at <root>/api-token (auth/api-token.ts), which authMiddleware — reused below —- // accepts as `Authorization: Bearer` and authenticates as the admin. A local- // caller may therefore present either that token or an admin cookie session.- return cookieAuth(c, async () => {- if (!c.get("user").isAdmin) {- throw new HttpError(403, "forbidden", "Hot platform APIs are admin-only.");- }- await gated();- });+ await next();});-- /**- * THE ONE upgrade endpoint: platform + cli + web move together, atomically —- * there is no route that updates any of the three alone (see host.ts's module- * doc). Content-Type application/gzip or application/octet-stream; the raw body- * is gzip(JSON.stringify({ platform, cli, web: { files }, source? })):- * - `platform` — the platform's single-file JS ESM source, inline (works over- * HTTP alone, remote runtimes included); it must export `hotPlatform`.- * - `cli` — the CLI's own single-file JS ESM source, inline, a SEPARATE- * artifact from `platform`; the server never imports or runs it, only- * content-addresses it into the store for packages/cli's own loader.- * - `web.files` — a { relPath: base64 } manifest of the built web dist.- * - `source?` — optional provenance (repo + revision), recorded but not run.- * The server boots the platform AND installs the web dist in memory first;- * only once BOTH succeed does it persist the version — platform, cli, and web- * together (one atomic harness.json rename — see host.ts's persistVersion). A- * boot failure or a bad web manifest leaves the previously committed version- * untouched.- */- routes.post("/upgrade", async (c) => {- const contentType = (c.req.header("content-type") ?? "").split(";")[0]!.trim().toLowerCase();- if (contentType !== "application/gzip" && contentType !== "application/octet-stream") {- throw new HttpError(- 400,- "bad_request",- "expected a gzip(JSON.stringify({ platform, cli, web })) body " +- "(Content-Type application/gzip or application/octet-stream)",- );- }- let payload: {- platform?: string;- cli?: string;- web?: { files?: Record<string, string> };- assets?: { files?: Record<string, string>; exec?: string[] };- source?: { repo: string; revision: string };- };- try {- const gz = Buffer.from(await c.req.arrayBuffer());- payload = JSON.parse(zlib.gunzipSync(gz).toString("utf8"));- } catch (err) {- throw new HttpError(- 400,- "bad_request",- `invalid gzip upgrade payload: ${err instanceof Error ? err.message : String(err)}`,- );- }- if (typeof payload.platform !== "string") {- throw new HttpError(400, "bad_request", "payload has no `platform` (string)");- }- if (typeof payload.cli !== "string") {- throw new HttpError(400, "bad_request", "payload has no `cli` (string)");- }- if (typeof payload.web?.files !== "object" || payload.web.files === null) {- throw new HttpError(- 400,- "bad_request",- "payload has no `web.files` (a { relPath: base64 } map)",- );- }- let outcome;- try {- outcome = await hmr.upgradeAll({- platform: payload.platform,- cli: payload.cli,- web: payload.web.files,- // Optional: a push that needs no real files on disk (no native module, no helper- // binary) simply omits it, and older pushers keep working unchanged.- ...(payload.assets?.files- ? {- assets: {- files: payload.assets.files,- ...(payload.assets.exec ? { exec: payload.assets.exec } : {}),- },- }- : {}),- // Provenance is optional and, unlike the bundles, now outlives the request in- // harness.json — so it is accepted only fully formed. A half-filled or- // wrong-typed `source` is dropped rather than committed: readers already- // tolerate its absence, and a malformed record on disk would outlive the push- // that produced it.- ...(typeof payload.source?.repo === "string" &&- typeof payload.source.revision === "string" &&- payload.source.repo.length > 0 &&- payload.source.revision.length > 0- ? { source: { repo: payload.source.repo, revision: payload.source.revision } }- : {}),- });- } catch (err) {- throw new HttpError(400, "bad_request", err instanceof Error ? err.message : String(err));+ // Then the platform's cookie / API-token gate, and admin on top.+ routes.use("*", authMiddleware(deps.auth, deps.config.trustProxy));+ routes.use("*", async (c, next) => {+ if (!c.var.user.isAdmin) {+ throw new HttpError(403, "forbidden", "Hot platform APIs are admin-only.");}- // Live clients (browser tabs AND the desktop window) reload to pick up the- // new web assets once a version actually lands.- if (outcome.status === "ok") {+ await next();+ });++ // What the store lacks of these blobs, so the push that follows carries only those. A+ // pusher that gets a 404 here is talking to a generation older than the probe and sends+ // everything inline, as it always did. The answer is the mechanism's, like the push's.+ routes.post("/assets/probe", (c) => deps.control.endpoint(c.req.raw));+ // One blob, raw, under its sha256; a push then names it instead of carrying it.+ routes.put("/blobs/:sha", (c) => deps.control.endpoint(c.req.raw));++ // THE ONE upgrade endpoint: platform + cli + web move together, atomically — there is no+ // route that updates any of the three alone. The body and the answer are the mechanism's+ // (packages/hmr); live clients (browser tabs AND the desktop window) are told to reload+ // once a version actually lands.+ routes.post("/upgrade", (c) =>+ deps.control.endpoint(c.req.raw, (outcome) =>deps.channels.broadcast("user:",{ type: "web_updated", rev: outcome.web.rev },"server_event",- );- }- // Blocked is a first-class outcome, not an HTTP error: the body carries- // status + the dropped/missing/invalid paths (input for the upper- // upgrade-ladder rungs), so clients keep one parsing path.- return c.json(outcome);- });+ ),+ ),+ );return routes;}++@Component({+ contributes: {+ "HttpModule.routes": [+ // Manifest data is literal (gen-ifaces reads it off the source): the same prefix packages/hmr exports as HMR_ROUTE_PREFIX.+ // `auth: "none"` only in the manifest: the group gates itself, network first, then the+ // platform's own auth middleware — the order the gate's tests pin.+ { id: "HmrRoutes.routes", prefix: "/api/hmr", auth: "none", order: 5 },+ ],+ },+})+export class HmrRoutes {+ @Use() private readonly control!: HmrControl;+ @Use() private readonly auth!: Auth;+ @Use() private readonly config!: Config;+ @Use() private readonly channels!: Channels;+ @Bind("HmrRoutes.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = hmrRoutes({+ // The node's contract keeps the instance and the outcome opaque; the routes speak the real types.+ control: this.control as unknown as HmrControlApi,+ auth: this.auth,+ config: this.config,+ channels: this.channels,+ });+ }+}diff --git a/packages/server/src/hmr/starting.ts b/packages/server/src/hmr/starting.tsnew file mode 100644index 00000000..d8a34bc9--- /dev/null+++ b/packages/server/src/hmr/starting.ts@@ -0,0 +1,24 @@+/**+ * What this process answers when there is no App to answer with: the entry binds the port+ * before `start` has built one, and the seam can find no generation current. Both are 503+ * with the reason. Only the first ends by itself, so only it asks for a retry.+ */++export function startingResponse(): Response {+ return unavailable("penguin-server is starting", true);+}++export function noPlatformResponse(reason: string): Response {+ return unavailable(`penguin-server has no running platform: ${reason}`, false);+}++function unavailable(text: string, retry: boolean): Response {+ return new Response(text, {+ status: 503,+ headers: {+ ...(retry ? { "retry-after": "1" } : {}),+ "cache-control": "no-store",+ "content-type": "text/plain; charset=utf-8",+ },+ });+}diff --git a/packages/server/src/http/app.ts b/packages/server/src/http/app.tsindex 25ab3bde..0b7d50cc 100644--- a/packages/server/src/http/app.ts+++ b/packages/server/src/http/app.ts@@ -32,9 +32,6 @@ export interface HttpSlots {>;}-/** Prefixes the runtime owns; the platform declines them before anything else runs — in particular before the auth gate, which would otherwise 401 an unauthenticated /api/auth/login. */-const RUNTIME_PREFIXES = ["/api/auth", "/api/desktop", "/api/hmr"];-/*** The platform's whole HTTP surface, assembled from `HttpModule.routes` contributions: every* module that serves requests contributes its groups here as data (prefix, auth, order)@@ -102,19 +99,7 @@ export class HttpModule {})).sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));let gated = false;- let declinedRuntime = false;for (const r of routes) {- // The terminal group (order 0) sits before the runtime-prefix decline, so a matched- // terminal route ends the chain first; everything after it declines /api/auth etc.- if (!declinedRuntime && r.order > 0) {- app.use("*", async (c, next) => {- if (RUNTIME_PREFIXES.some((p) => c.req.path === p || c.req.path.startsWith(`${p}/`))) {- return declined();- }- await next();- });- declinedRuntime = true;- }if (r.auth === "user") {// Protected routes: cookie -> auth_session -> user. /api/* is gated once, ahead of// the first protected group. A protected group under another prefix — the machinediff --git a/packages/server/src/http/routes/auth.ts b/packages/server/src/http/routes/auth.tsindex e14215bc..dc176c18 100644--- a/packages/server/src/http/routes/auth.ts+++ b/packages/server/src/http/routes/auth.ts@@ -12,15 +12,17 @@ import type { AuthResponse } from "../../api/types.js";import { SESSION_COOKIE, cookieOptions } from "../../auth/middleware.js";import type { AppEnv } from "../../auth/middleware.js";import { readJson, requireString } from "../validate.js";+import { HttpError } from "../errors.js";import type { ServerConfig } from "../../config.js";-import type { DesktopService } from "../../services/desktop-service.js";import type { Auth } from "../../mechanisms/identity.js";+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";+import { Config, Desktop } from "../../hmr/capabilities.js";+import type { DesktopApi } from "../../hmr/capabilities.js";-/** What this route group reaches — bound by its module (src/modules). */export interface AuthRouteDeps {authService: Auth;config: ServerConfig;- desktop: DesktopService | null;+ desktop: Pick<DesktopApi, "redeemLoginToken"> | null;}export function authRoutes(deps: AuthRouteDeps): Hono<AppEnv> {@@ -81,5 +83,34 @@ export function authRoutes(deps: AuthRouteDeps): Hono<AppEnv> {return c.redirect("/", 302);});+ // The group owns its prefix: an unknown path here is not found, never a 401 from the+ // cookie gate behind it (there is no register endpoint, and a probe learns nothing).+ app.all("/*", () => {+ throw new HttpError(404, "not_found", "Not found.");+ });+return app;}++/**+ * Platform code: who may sign in and how is policy. The HMR layer mounts a copy of these+ * routes below its seam for a platform older than this move, which declines the prefix.+ */+@Component({+ contributes: {+ "HttpModule.routes": [{ id: "AuthRoutes.routes", prefix: "/api/auth", auth: "none", order: 5 }],+ },+})+export class AuthRoutes {+ @Use() private readonly auth!: Auth;+ @Use() private readonly config!: Config;+ @Use() private readonly desktop!: Desktop;+ @Bind("AuthRoutes.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = authRoutes({+ authService: this.auth,+ config: this.config,+ desktop: this.desktop.current(),+ });+ }+}diff --git a/packages/server/src/http/routes/desktop.ts b/packages/server/src/http/routes/desktop.tsindex 3326ec00..ba9a1e97 100644--- a/packages/server/src/http/routes/desktop.ts+++ b/packages/server/src/http/routes/desktop.ts@@ -3,15 +3,16 @@* /api/desktop/update, the tray-icon preference at /api/desktop/tray, plus the shared* desktop-mode guard that turns off multi-user surfaces (see rejectInDesktopMode).*- * The shutdown route is authenticated by the shell's Bearer token, not the cookie- * session (the shell holds no cookie), so it mounts OUTSIDE authMiddleware and only- * when desktop mode is enabled. Responds 202 first, then triggers the graceful- * shutdown a beat later so the response isn't cut off by the closing listener.- * The other two are called by the page instead, so they mount INSIDE authMiddleware- * (see desktopUpdateRoutes and desktopTrayRoutes).+ * Platform code, all of it: what the shell's window may ask of the shell is policy. The+ * shutdown route is authenticated by the shell's Bearer token, not the cookie session (the+ * shell holds no cookie), so its group is unauthenticated and checks the token itself; it+ * answers 202 first, then triggers the graceful shutdown a beat later so the response is not+ * cut off by the closing listener. The update and tray routes are called by the page, so their+ * groups sit behind the cookie gate and are further restricted to the shell's own window.*/import { Hono } from "hono";import type { Context, MiddlewareHandler } from "hono";+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import type {DesktopTrayPatch,DesktopTrayStatusResponse,@@ -19,12 +20,13 @@ import type {} from "../../api/types.js";import { HttpError } from "../errors.js";import type { AppEnv } from "../../auth/middleware.js";+import { Desktop } from "../../hmr/capabilities.js";+import type { DesktopApi } from "../../hmr/capabilities.js";-/** What this route group reaches — bound by its module (src/modules). */+/** The shell's service as the platform sees it; null outside desktop mode. */export interface DesktopRouteDeps {- desktop: DesktopService | null;+ desktop: DesktopApi | null;}-import type { DesktopService } from "../../services/desktop-service.js";/*** Guard for user-management surfaces (admin users, Project members): the desktop app is@@ -74,11 +76,7 @@ export function desktopRoutes(deps: DesktopRouteDeps): Hono {* desktop-mode server must not read the machine's updater state, restart its GUI app, or* reach into the chrome of a window it is not looking at.*/-function shellSessionOf(- deps: DesktopRouteDeps,- c: Context<AppEnv>,- refusal: string,-): DesktopService {+function shellSessionOf(deps: DesktopRouteDeps, c: Context<AppEnv>, refusal: string): DesktopApi {const desktop = deps.desktop;if (!desktop) throw new HttpError(404, "not_found", "Desktop mode is not enabled.");if (c.var.sessionVia !== "desktop") throw new HttpError(403, "desktop_shell_only", refusal);@@ -86,58 +84,48 @@ function shellSessionOf(}/**- * Client-update relay routes (mounted INSIDE authMiddleware at /api/desktop/update, and- * only in desktop mode). Restricted to the shell's own window (`sessionVia === "desktop"`,- * the same two-field rule as the change-password gate, inverted): a browser signed into- * the same desktop-mode server must not read the machine's updater state or restart its- * GUI app. Consent is collected by the page's update modal before each POST: `download`- * fetches only the release the shell has offered, and `install` restarts only into what- * its updater already downloaded and verified.+ * Client-update relay routes. Restricted to the shell's own window (`sessionVia ===+ * "desktop"`, the same two-field rule as the change-password gate, inverted): a browser+ * signed into the same desktop-mode server must not read the machine's updater state or+ * restart its GUI app. Consent is collected by the page's update modal before each POST:+ * `download` fetches only the release the shell has offered, and `install` restarts only+ * into what its updater already downloaded and verified.+ *+ * The relay members are optional on the service: a layer older than the update modal has+ * none, and this platform still runs on it — with no status and a 503 for every command.*/export function desktopUpdateRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();- const requireShellSession = (c: Context<AppEnv>): DesktopService =>+ const requireShellSession = (c: Context<AppEnv>): DesktopApi =>shellSessionOf(deps, c, "Client updates are managed from the desktop app's own window.");- app.get("/", (c) => {- const desktop = requireShellSession(c);- return c.json({ status: desktop.getUpdateStatus() } satisfies DesktopUpdateStatusResponse);- });-- app.post("/check", (c) => {- const desktop = requireShellSession(c);- if (!desktop.requestUpdateCommand("check")) {- throw new HttpError(503, "shell_unreachable", "The desktop shell is not listening.");- }- return c.body(null, 202);- });-- app.post("/download", (c) => {+ const relay = (action: "check" | "download" | "install", c: Context<AppEnv>) => {const desktop = requireShellSession(c);- if (!desktop.requestUpdateCommand("download")) {+ if (!desktop.requestUpdateCommand?.(action)) {throw new HttpError(503, "shell_unreachable", "The desktop shell is not listening.");}return c.body(null, 202);- });+ };- app.post("/install", (c) => {+ app.get("/", (c) => {const desktop = requireShellSession(c);- if (!desktop.requestUpdateCommand("install")) {- throw new HttpError(503, "shell_unreachable", "The desktop shell is not listening.");- }- return c.body(null, 202);+ const status = desktop.getUpdateStatus?.() ?? null;+ return c.json({ status } satisfies DesktopUpdateStatusResponse);});+ app.post("/check", (c) => relay("check", c));+ app.post("/download", (c) => relay("download", c));+ app.post("/install", (c) => relay("install", c));return app;}/**- * The tray-icon preference (mounted INSIDE authMiddleware at /api/desktop/tray, and only- * in desktop mode). GET reads what the shell last pushed — null until that first push,+ * The tray-icon preference. GET reads what the shell last pushed — null until that first push,* which the page reads as on, the shell's own default. PUT relays a patch — the switch, the* page's UI language, or both; the shell applies it, persists it and pushes the new state* straight back, so the answer here is an acknowledgement and the GET is what tells the truth.+ * Like the update relay, the members are optional on a layer older than the tray icon.*/export function desktopTrayRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();@@ -145,7 +133,8 @@ export function desktopTrayRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {app.get("/", (c) => {const desktop = shellSessionOf(deps, c, refusal);- return c.json({ status: desktop.getTrayStatus() } satisfies DesktopTrayStatusResponse);+ const status = desktop.getTrayStatus?.() ?? null;+ return c.json({ status } satisfies DesktopTrayStatusResponse);});app.put("/", async (c) => {@@ -171,7 +160,7 @@ export function desktopTrayRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {if (patch.showTrayIcon === undefined && patch.locale === undefined) {throw new HttpError(400, "empty_tray_patch", "Pass showTrayIcon, locale, or both.");}- if (!desktop.requestTrayCommand(patch)) {+ if (!desktop.requestTrayCommand?.(patch)) {throw new HttpError(503, "shell_unreachable", "The desktop shell is not listening.");}return c.body(null, 202);@@ -179,3 +168,48 @@ export function desktopTrayRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {return app;}++@Component({+ contributes: {+ "HttpModule.routes": [+ { id: "DesktopRoutes.routes", prefix: "/api/desktop", auth: "none", order: 5 },+ ],+ },+})+export class DesktopRoutes {+ @Use() private readonly desktop!: Desktop;+ @Bind("DesktopRoutes.routes") routes!: Hono;+ setup() {+ this.routes = desktopRoutes({ desktop: this.desktop.current() });+ }+}++@Component({+ contributes: {+ "HttpModule.routes": [+ { id: "DesktopUpdateRoutes.routes", prefix: "/api/desktop/update", auth: "user", order: 10 },+ ],+ },+})+export class DesktopUpdateRoutes {+ @Use() private readonly desktop!: Desktop;+ @Bind("DesktopUpdateRoutes.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = desktopUpdateRoutes({ desktop: this.desktop.current() });+ }+}++@Component({+ contributes: {+ "HttpModule.routes": [+ { id: "DesktopTrayRoutes.routes", prefix: "/api/desktop/tray", auth: "user", order: 10 },+ ],+ },+})+export class DesktopTrayRoutes {+ @Use() private readonly desktop!: Desktop;+ @Bind("DesktopTrayRoutes.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = desktopTrayRoutes({ desktop: this.desktop.current() });+ }+}diff --git a/packages/server/src/http/routes/install.ts b/packages/server/src/http/routes/install.tsindex ccefca5b..ced9532a 100644--- a/packages/server/src/http/routes/install.ts+++ b/packages/server/src/http/routes/install.ts@@ -7,7 +7,7 @@* for, a wiped data root, is precisely the case where nobody is. See install-id.ts for why* publishing the id discloses nothing.*- * Mounted in the PLATFORM, above its auth gate (app.ts's createApp). A hot push carries+ * Mounted in the PLATFORM, above its auth gate (http/app.ts's HttpModule). A hot push carries* platform + cli + web dist as one version and never the runtime, so putting the route where* the platform is puts it where the web bundle that calls it is: the two can never arrive on* an installation separately. The data root is still the runtime's — `deps.config.root` comesdiff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex 035d048b..8ec75e12 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -20,7 +20,13 @@ import type { Server as HttpServer } from "node:http";import { config as loadDotenv } from "dotenv";import { serve } from "@hono/node-server";import { SERVER_RESTART_EXIT_CODE } from "@prismshadow/penguin-core";-import { bootAppDeps, createRuntimeApp } from "./app.js";+import { bootAppDeps, createApp } from "./app.js";+import { HmrHost, hmrMain } from "@prismshadow/penguin-hmr";+import type { Hmr } from "@prismshadow/penguin-hmr";+import type { Instance } from "@prismshadow/penguin-core/kernel";+import { packagedPlatform } from "./hmr/platform.js";+import { startingResponse } from "./hmr/starting.js";+import type { PlatformApi, ServerHmrHost } from "./hmr/platform.js";import type { ServerBoot } from "./app.js";import { ADMIN_USER_ID } from "./auth/service.js";import { resolveServerConfig, type ServerConfig } from "./config.js";@@ -48,13 +54,25 @@ async function main(): Promise<void> {server.installProxy();server.readConfig();await server.ensureSoleInstance();- await server.loadPlugins();- await server.buildDeps();- server.applyPersistedProxy();- server.buildApp();- await server.seedAdmin();server.listen();- server.installProcessHandlers();+ // The HMR layer's entry (packages/hmr's main.ts) owns the frozen operations: which+ // generation a request goes to, how a push lands, what happens when one fails. The+ // product hands it the host, what to refresh once a generation is current, and its own+ // start — everything the platform is comes up inside it.+ await hmrMain(+ server.createHost(),+ (instance) => server.replace(instance),+ async (hmr) => {+ await server.loadPlugins();+ await server.buildDeps(hmr);+ server.applyPersistedProxy();+ server.buildApp();+ await server.seedAdmin();+ server.installProcessHandlers();+ await server.printFirstLoginNotice();+ },+ );+ await server.announce();}/**@@ -72,12 +90,17 @@ class PenguinServer {private config!: ServerConfig;/** Assigned by loadPlugins(); published to the platform tree by buildDeps(). */private plugins!: PluginHost;+ /** Assigned by createHost(): the store and the swap, built over the packaged platform. */+ private host!: ServerHmrHost;/** Assigned by buildDeps(); the merged runtime + business view (see app.ts). */private deps!: ServerBoot;/** Assigned by buildApp(). */- private app!: ReturnType<typeof createRuntimeApp>;+ private app!: ReturnType<typeof createApp>;/** Assigned by listen(). */private httpServer!: ReturnType<typeof serve>;+ /** Resolves with the port the OS actually bound, once the listener is up. */+ private bound!: Promise<number>;+ private resolveBound!: (port: number) => void;/** The `::1` companion listener, when one was opened — see openIpv6Loopback(). */private ipv6Loopback: ReturnType<typeof serve> | null = null;@@ -162,8 +185,24 @@ class PenguinServer {* registry is the only way a pushed bundle — compiled standalone — can reach these* plugin objects at all (see plugin/index.ts's pluginHostFrom).*/- async buildDeps(): Promise<void> {- this.deps = await bootAppDeps(this.config, [], this.plugins);+ /** The store and the swap, ahead of everything that boots against them (hmrMain takes it first). */+ createHost(): ServerHmrHost {+ this.host = new HmrHost<PlatformApi>(this.config.root, packagedPlatform);+ return this.host;+ }++ async buildDeps(hmr: Hmr<PlatformApi>): Promise<void> {+ this.deps = await bootAppDeps(this.config, [], this.plugins, this.host, hmr);+ }++ /**+ * What the layer refreshes once a generation is current (hmrMain's replace): the tree it+ * resolves nodes from. Everything read through `deps.tree` — the auth for the socket and+ * the hot-update gate, the settings, the error recorder — is the new generation's from here.+ */+ replace(instance: Instance<PlatformApi>): void {+ const tree = typeof instance.api.business === "function" ? instance.api.business() : null;+ if (tree !== null && this.deps !== undefined) this.deps.tree = tree;}/**@@ -180,9 +219,20 @@ class PenguinServer {});}- /** Assembles the runtime shell's middleware and routes. Nothing is listening yet. */+ /**+ * Assembles the layer's middleware and routes; from here the listening port answers+ * with them. The terminal stream is a WebSocket upgrade, which never reaches the fetch+ * handler — it is bound on each Node listener here, once the platform it asks exists.+ */buildApp(): void {- this.app = createRuntimeApp(this.deps);+ this.app = createApp(this.deps);+ attachTerminalWebSocket(this.httpServer as unknown as HttpServer, this.terminalWebSocketDeps());+ if (this.ipv6Loopback !== null) {+ attachTerminalWebSocket(+ this.ipv6Loopback as unknown as HttpServer,+ this.terminalWebSocketDeps(),+ );+ }}/**@@ -213,15 +263,40 @@ class PenguinServer {}/**- * Opens the HTTP listener. Everything that needs the port the OS actually handed out- * (PORT=0 asks for an ephemeral one) waits for onListening().+ * Opens the HTTP listener. The port is bound before the platform exists: until buildApp()+ * it answers the starting response, so a client that arrives early sees "starting" —+ * and, if it is a browser, comes back on its own — rather than a refused connection.+ * Everything that needs the port the OS actually handed out (PORT=0 asks for an+ * ephemeral one) waits for onListening().*/listen(): void {+ // The listener's callback records this process as the root's server (the lock); the+ // root has to exist for that, and the database that used to create it is now opened+ // later, inside start.+ fs.mkdirSync(this.config.root, { recursive: true });+ this.bound = new Promise((resolve) => {+ this.resolveBound = resolve;+ });this.httpServer = serve(- { fetch: this.app.fetch, hostname: this.config.host, port: this.config.port },+ {+ fetch: (request: Request) => this.app?.fetch(request) ?? startingResponse(),+ hostname: this.config.host,+ port: this.config.port,+ },(info) => this.onListening(info.port),);- attachTerminalWebSocket(this.httpServer as unknown as HttpServer, this.terminalWebSocketDeps());+ }++ /**+ * Announces the port (PENGUIN_PORT_FILE), the last step of startup. The port is bound+ * long before this — a client that arrives early is answered rather than refused — but+ * the announcement means the App is up, because that is what a reader waits for: the+ * desktop shell opens its window on it. Between the bind and here every request gets the+ * starting response instead.+ */+ async announce(): Promise<void> {+ if (this.config.portFile === null) return;+ writePortFile(this.config.portFile, await this.bound);}/**@@ -313,24 +388,28 @@ class PenguinServer {port,startedAt: new Date().toISOString(),});- if (this.config.portFile !== null) writePortFile(this.config.portFile, port);if (this.config.host === "127.0.0.1" || this.config.host === "localhost") {this.openIpv6Loopback(port);}- // Last, so the link is what a console is left showing rather than something scrolled- // past — and here rather than in seedAdmin() because the URL needs the port the OS- // actually handed out, which PORT=0 only settles at this point.- if (this.pendingFirstLoginNotice) {- // Minting here rather than at seed time is what keeps "exists" and "was printed" the- // same thing for a setup session: the modes that decline to print never ask for one.- const link = this.auth().mintFirstLogin();- if (link !== null) {- const token = encodeURIComponent(link);- console.log(- renderFirstLoginNotice(`http://${this.appHost()}:${port}/api/auth/claim?token=${token}`),- );- }- }+ this.resolveBound(port);+ }++ /**+ * The one-time sign-in link, last in the startup sequence so it is what a console is+ * left showing rather than something scrolled past. Minting here rather than at seed+ * time is what keeps "exists" and "was printed" the same thing for a setup session: the+ * modes that decline to print never ask for one. The URL needs the port the OS actually+ * handed out, which PORT=0 only settles once the listener is up.+ */+ async printFirstLoginNotice(): Promise<void> {+ if (!this.pendingFirstLoginNotice) return;+ const port = await this.bound;+ const link = this.auth().mintFirstLogin();+ if (link === null) return;+ const token = encodeURIComponent(link);+ console.log(+ renderFirstLoginNotice(`http://${this.appHost()}:${port}/api/auth/claim?token=${token}`),+ );}/**@@ -360,24 +439,34 @@ class PenguinServer {* every preview URL (same port, counterpart host) would refuse connections.*/private openIpv6Loopback(port: number): void {- const loopback = serve({ fetch: this.app.fetch, hostname: "::1", port });+ const loopback = serve({+ fetch: (request: Request) => this.app?.fetch(request) ?? startingResponse(),+ hostname: "::1",+ port,+ });this.ipv6Loopback = loopback;loopback.on("error", (err: NodeJS.ErrnoException) => {console.warn(`[server] IPv6 loopback listener unavailable (${err.code ?? err.message}); previews via localhost may not resolve.`,);});- // The terminal stream is a WebSocket upgrade, which never reaches the Hono fetch- // handler — it has to be bound on each Node listener, this one included, or the- // terminal only works on whichever address the browser happened to resolve.- attachTerminalWebSocket(loopback as unknown as HttpServer, this.terminalWebSocketDeps());+ // The terminal stream is bound on every listener in buildApp(), this one included, or+ // the terminal only works on whichever address the browser happened to resolve; a+ // loopback opened after buildApp() (never in practice — binding is quick) gets it here.+ if (this.app !== undefined) {+ attachTerminalWebSocket(loopback as unknown as HttpServer, this.terminalWebSocketDeps());+ }}/** Terminal WebSocket wiring, shared by every listener this process opens. */private terminalWebSocketDeps() {+ const auth = () => this.auth();return {hmr: this.deps.hmr,- authService: this.auth(),+ // A getter: the upgrade handler asks per handshake, and gets the current generation's.+ get authService() {+ return auth();+ },log: (line: string) => console.log(line),};}diff --git a/packages/server/src/machines/install-server.ts b/packages/server/src/machines/install-server.tsindex 33f00f39..d7244510 100644--- a/packages/server/src/machines/install-server.ts+++ b/packages/server/src/machines/install-server.ts@@ -1,6 +1,6 @@/*** Installing THIS server's build onto another machine, from inside the server process —- * platform code, so the whole capability travels by hot push (see ../hmr/README.md).+ * platform code, so the whole capability travels by hot push (see packages/hmr/README.md).** Nothing installable is produced here. The far side runs the ordinary release installer* ONLINE, pinned to this server's own base release, so the program tree — launchers, libs,diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex a257e9e9..77bb8d84 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -1,7 +1,7 @@import { Component, Module, moduleDefOf, Use } from "@prismshadow/penguin-core/kernel";import type { ManifestTable, ModuleClass, ModuleDef } from "@prismshadow/penguin-core/kernel";import table from "./ifaces.json" with { type: "json" };-import type { RuntimeCapabilities } from "./hmr/capabilities.js";+import type { HmrCapabilities } from "./hmr/capabilities.js";import {ConfigPaths,ConsoleLog,@@ -12,6 +12,7 @@ import {RuntimeDb,RuntimeDesktop,RuntimeHmr,+ RuntimeHmrControl,RuntimeProxy,RuntimeResourceGroups,SystemClock,@@ -23,6 +24,7 @@ import {Desktop,Lifecycle,Hmr,+ HmrControl,Log,Paths,Proxy,@@ -97,7 +99,10 @@ import { Machines, MachinesModule } from "./machines/service.js";import { ProjectAdminRoutes } from "./http/routes/projects.js";import { AdminRoutes } from "./http/routes/admin.js";import { MeRoutes } from "./http/routes/me.js";+import { AuthRoutes } from "./http/routes/auth.js";+import { DesktopRoutes, DesktopTrayRoutes, DesktopUpdateRoutes } from "./http/routes/desktop.js";import { InstallRoutes } from "./http/routes/install.js";+import { HmrRoutes } from "./hmr/routes.js";import { EventsRoutes } from "./http/routes/events.js";import { PluginRoutes } from "./http/routes/plugins.js";import { TerminalModule } from "./terminal/manager.js";@@ -185,6 +190,7 @@ export class Startup {RuntimeChannels,RuntimeProxy,RuntimeHmr,+ RuntimeHmrControl,RuntimeDesktop,RuntimeAuthState,RuntimeLifecycle,@@ -199,6 +205,7 @@ export class Startup {Channels,Proxy,Hmr,+ HmrControl,Desktop,AuthState,Lifecycle,@@ -219,6 +226,7 @@ export class RuntimeModule {}AdminService,AdminRoutes,MeRoutes,+ AuthRoutes,],exports: [Users, AuthSessions, Auth, Admin, PasswordHasher],})@@ -340,6 +348,10 @@ export class MessagingHubModule {}WebModule,InstallRoutes,VersionRoutes,+ HmrRoutes,+ DesktopRoutes,+ DesktopUpdateRoutes,+ DesktopTrayRoutes,PluginRoutes,],exports: [Http, WebShell, UpdateCheck],@@ -374,7 +386,7 @@ export class PlatformModule {}* plugin modules appended under the root.*/export function platformDef(- caps: RuntimeCapabilities,+ caps: HmrCapabilities,adoptable: (group: string) => boolean,plugins: ModuleDef[] = [],replace: ReadonlyMap<string, ModuleDef> = new Map(),@@ -385,6 +397,7 @@ export function platformDef([RuntimeChannels, new RuntimeChannels(caps)],[RuntimeProxy, new RuntimeProxy(caps)],[RuntimeHmr, new RuntimeHmr(caps)],+ [RuntimeHmrControl, new RuntimeHmrControl(caps)],[RuntimeDesktop, new RuntimeDesktop(caps)],[RuntimeAuthState, new RuntimeAuthState(caps)],[RuntimeLifecycle, new RuntimeLifecycle(caps)],diff --git a/packages/server/src/plugin/host.ts b/packages/server/src/plugin/host.tsindex eab248c7..ba8b6a00 100644--- a/packages/server/src/plugin/host.ts+++ b/packages/server/src/plugin/host.ts@@ -72,8 +72,20 @@ export class PluginHost {dispose(): void {}}-/** Registry key the runtime publishes its loaded host under. */-export const PLUGINS_RESOURCE_ID = "runtime:plugins";+/**+ * Registry key for the loaded plugin host.+ *+ * Nothing about the host is the runtime's business: which plugins a deployment runs is+ * configuration the platform reads, the modules go into the platform's tree, and a platform+ * route writes this very entry when the list changes (http/routes/plugins-installed.ts). It+ * is parked only because the imported objects must survive a swap — a re-import would give+ * the successor different module instances.+ *+ * That the runtime still LOADS it at process start (index.ts) is the misfiling this note+ * exists to flag: it is why a machine whose program is older cannot learn a new loading rule+ * from a push, and had to be restarted to pick up a plugin list.+ */+export const PLUGINS_RESOURCE_ID = "platform.plugins";/*** The host the runtime loaded (see ./loader.ts), or an empty one — the honest readingdiff --git a/packages/server/src/terminal/routes.ts b/packages/server/src/terminal/routes.tsindex d996e041..ce1cf0c2 100644--- a/packages/server/src/terminal/routes.ts+++ b/packages/server/src/terminal/routes.ts@@ -1,7 +1,7 @@/*** Terminal control plane: `/api/terminals`, one route group of the platform's Hono app.*- * Mounted by app.ts's createApp beside the business route groups, so all+ * Mounted by http/app.ts's HttpModule beside the business route groups, so all* platform routes register into ONE app and swap as one unit. This group owns exactly* the six routes below and nothing else under its prefix: unknown paths and methods fall* to the parent app's notFound, which declines to the runtime. The identity gate is@@ -94,7 +94,7 @@ type TerminalEnv = { Variables: { user: IdentifiedUser } };/*** The terminal route group, mounted into the platform's one Hono app beside the business- * groups (see app.ts's createApp). Decline (unknown path/method) and error+ * groups (see http/app.ts's HttpModule). Decline (unknown path/method) and error* shaping belong to the parent app; what stays here is the routes and their identity* gate. `identity` is the runtime's capability; a request it cannot attribute is 401* here rather than falling through, because falling through would hand andiff --git a/packages/server/src/terminal/ws.ts b/packages/server/src/terminal/ws.tsindex 606aca21..f4e6ded6 100644--- a/packages/server/src/terminal/ws.ts+++ b/packages/server/src/terminal/ws.ts@@ -16,7 +16,7 @@ import type { IncomingMessage, Server as HttpServer } from "node:http";import type { Duplex } from "node:stream";import { WebSocketServer } from "ws";import { SESSION_COOKIE } from "../auth/middleware.js";-import type { HmrHost } from "../hmr/host.js";+import type { ServerHmrHost } from "../hmr/platform.js";import type { Auth } from "../mechanisms/identity.js";const STREAM_PATH = /^\/api\/terminals\/([^/]+)\/stream$/;@@ -38,7 +38,7 @@ const BACKPRESSURE_POLL_MS = 250;export interface TerminalWebSocketDeps {/** The booted platform owns the terminals; the runtime asks it per upgrade. */- hmr: HmrHost;+ hmr: ServerHmrHost;authService: Auth;log: (line: string) => void;}diff --git a/packages/server/test/fixtures/platform-http.bundle.mjs b/packages/server/test/fixtures/platform-http.bundle.mjsindex 47a9efa6..ce058a38 100644--- a/packages/server/test/fixtures/platform-http.bundle.mjs+++ b/packages/server/test/fixtures/platform-http.bundle.mjs@@ -2,7 +2,7 @@* Test fixture: a pushed platform that SERVES HTTP.** The point of the seam it exercises: this bundle adds `/api/demo/ping`, replaces the- * runtime's `/api/version`, and tries (and fails) to claim `/api/hmr/platform` — none of which+ * runtime's `/api/version`, and carries the upgrade channel a generation must — none of which* the runtime knows anything about. It arrives as bytes over one HTTP push, with no rebuild.** Standalone on purpose, like the other fixtures: no kernel or arktype imports, only what an@@ -37,7 +37,7 @@ const iface = {};const impl = {- create(_ctx, context) {+ create(ctx, context) {return {park: () => context,info: () => ({ impl: "http-fixture" }),@@ -66,10 +66,11 @@ const impl = {if (url.pathname === "/api/demo/boom") {throw new Error("deliberate platform failure");}- if (url.pathname.startsWith("/api/hmr")) {- // Never reached: the runtime keeps its upgrade channel, so a push cannot lock the- // installation out of being replaced.- return new Response("hijacked", { status: 418 });+ if (url.pathname.startsWith("/api/hmr/")) {+ // The upgrade channel is the platform's to serve; a generation without it is+ // refused before commit (admitsUpgradeRoute). The protocol is the mechanism's,+ // claimed off the registry — that is how this bundle carries it without a platform.+ return ctx.resources.claim("platform.hmrControl").endpoint(request);}return null; // not mine — the runtime's own routes answer},diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.tsindex c8c36f17..5661d113 100644--- a/packages/server/test/helpers.ts+++ b/packages/server/test/helpers.ts@@ -8,11 +8,11 @@ import os from "node:os";import path from "node:path";import type { Hono } from "hono";import type { OmniMessage } from "@prismshadow/penguin-core";-import { bootAppDeps, createRuntimeApp } from "../src/app.js";+import { bootAppDeps, createApp } from "../src/app.js";import type { ServerBoot } from "../src/app.js";import type { ModuleTree, ModuleClass } from "@prismshadow/penguin-core/kernel";import type { DatabaseSync } from "node:sqlite";-import type { HmrHost } from "../src/hmr/host.js";+import type { ServerHmrHost } from "../src/hmr/platform.js";import type { ChannelHub } from "../src/runtime/channel.js";import type { DesktopService } from "../src/services/desktop-service.js";import type { AuthService } from "../src/auth/service.js";@@ -127,7 +127,7 @@ export function testConfig(root: string): ServerConfig {export interface TestDeps {config: ServerConfig;db: DatabaseSync;- hmr: HmrHost;+ hmr: ServerHmrHost;channels: ChannelHub;desktop: DesktopService | null;tree: ModuleTree;@@ -353,7 +353,7 @@ export async function createTestApp(options: TestAppOptions = {}): Promise<TestA// The seed hashes and discards; tests know the password only because the config injects it.// With a null override there is nothing to know, and such tests never password-login.const adminPassword = finalConfig.seedAdminPassword ?? TEST_ADMIN_PASSWORD;- const app = createRuntimeApp(boot);+ const app = createApp(boot);return {app,deps,diff --git a/packages/server/test/hmr-host.test.ts b/packages/server/test/hmr-host.test.tsindex 34b86f7a..0bb2d5d8 100644--- a/packages/server/test/hmr-host.test.ts+++ b/packages/server/test/hmr-host.test.ts@@ -9,10 +9,13 @@ import fs from "node:fs/promises";import fsSync from "node:fs";import path from "node:path";import zlib from "node:zlib";+import { createHash } from "node:crypto";import { afterEach, describe, expect, it, vi } from "vitest";import type { Hono } from "hono";import type { AppEnv } from "../src/auth/middleware.js";-import { HmrHost } from "../src/hmr/host.js";+import { HmrHost } from "@prismshadow/penguin-hmr";+import type { PlatformApi } from "../src/hmr/platform.js";+import { packagedPlatform } from "../src/hmr/platform.js";import { readHarnessInfo } from "../src/hmr/manifest.js";import { apiClient, createTestApp, loginAdmin } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -35,12 +38,14 @@ const iface = {};const SERVED = ${JSON.stringify(paths)};const impl = {- create(_ctx, context) {+ create(ctx, context) {return {park: () => context,info: () => ({ impl: ${JSON.stringify(id)} }),http(request) {const { pathname } = new URL(request.url);+ // The upgrade channel every generation must carry (admitsUpgradeRoute): the mechanism's endpoint, claimed.+ if (pathname.startsWith("/api/hmr/")) return ctx.resources.claim("platform.hmrControl").endpoint(request);if (!SERVED.includes(pathname)) return null;return new Response(JSON.stringify({ servedBy: ${JSON.stringify(id)}, pathname }), {status: 200,@@ -84,12 +89,14 @@ const iface = {migrations: {},};const impl = {- create(_ctx, context) {+ create(ctx, context) {return {park: () => context,info: () => ({ impl: ${JSON.stringify(id)}, n: context.n }),http(request) {const { pathname } = new URL(request.url);+ // The upgrade channel every generation must carry (admitsUpgradeRoute): the mechanism's endpoint, claimed.+ if (pathname.startsWith("/api/hmr/")) return ctx.resources.claim("platform.hmrControl").endpoint(request);if (pathname !== "/api/demo/bump") return null;context.n += 1;return new Response(JSON.stringify({ n: context.n }), {@@ -121,7 +128,7 @@ const iface = {migrations: {},};const impl = {- create(_ctx, context) {+ create(ctx, context) {return { park: () => context, info: () => ({ impl: ${JSON.stringify(id)} }) };},};@@ -186,7 +193,7 @@ describe("HmrHost.ensure(): single-flight first boot", () => {warnings.push(String(chunk));return true;}) as typeof process.stderr.write);- const fresh = new HmrHost(root);+ const fresh = new HmrHost<PlatformApi>(root, packagedPlatform);try {// Restore refused, the host goes on to boot the packaged default — which this bare// host cannot (it publishes no runtime resources). That rejection is the fixture's,@@ -217,7 +224,7 @@ describe("HmrHost.ensure(): single-flight first boot", () => {t = undefined; // already torn down by hand; skip the normal cleanup() (it would rm(root))// A brand-new HmrHost over the SAME root: nothing has called ensure() yet.- const fresh = new HmrHost(root);+ const fresh = new HmrHost<PlatformApi>(root, packagedPlatform);try {const [a, b, c] = await Promise.all([fresh.ensure(), fresh.ensure(), fresh.ensure()]);// Same object: only one restore()/boot ever ran.@@ -282,7 +289,7 @@ describe("HmrHost: code persists across a restart, state does not", () => {t.deps.db.close();t = undefined; // torn down by hand; skip cleanup() (it would rm(root))- const fresh = new HmrHost(root);+ const fresh = new HmrHost<PlatformApi>(root, packagedPlatform);try {const instance = await fresh.ensure();const restored = (instance.api as unknown as { info(): { impl: string; n: number } }).info();@@ -469,6 +476,216 @@ export const hotPlatform = { id: "boom", iface, impl, context: {} };*/const BOOM_PLATFORM_PACKAGED_ID = BOOM_PLATFORM.replace('id: "boom"', 'id: "packaged"');+describe("a push is content-addressed: blobs are put raw, parts are named by hash, unreferenced blobs are collected", () => {+ let t: TestApp | undefined;++ afterEach(async () => {+ if (t) await t.cleanup();+ t = undefined;+ });++ const sha256 = (buf: Buffer) => createHash("sha256").update(buf).digest("hex");+ const PKG = Buffer.from('{"name":"demo-native"}');+ const BIN = Buffer.from("\0binary");+ const README = Buffer.from("# demo\n");++ const payload = (id: string, assets: unknown) => ({+ platform: platformServing([`/api/demo/${id}`], id),+ cli: MINIMAL_CLI,+ web: { files: MINIMAL_WEB },+ assets,+ });+ const push = (app: Hono<AppEnv>, cookie: string, body: unknown) =>+ app.request("/api/hmr/upgrade", {+ method: "POST",+ headers: { cookie, "content-type": "application/gzip" },+ body: zlib.gzipSync(Buffer.from(JSON.stringify(body))),+ });+ const put = (app: Hono<AppEnv>, cookie: string, sha: string, bytes: Buffer) =>+ app.request(`/api/hmr/blobs/${sha}`, {+ method: "PUT",+ headers: { cookie, "content-type": "application/octet-stream" },+ body: bytes,+ });+ const probe = async (app: Hono<AppEnv>, cookie: string, hashes: string[]) =>+ (await (+ await app.request("/api/hmr/assets/probe", {+ method: "POST",+ headers: { cookie, "content-type": "application/json" },+ body: JSON.stringify({ hashes }),+ })+ ).json()) as { missing: string[] };++ it("a blob lands only under the hash of its bytes", async () => {+ t = await createTestApp();+ const cookie = (await loginAdmin(t.app)).cookie;+ const bytes = Buffer.from("\0native");+ const sha = sha256(bytes);+ const wrong = sha256(Buffer.from("other"));++ const refused = await put(t.app, cookie, wrong, bytes);+ expect(refused.status).toBe(400);+ expect(await refused.text()).toContain("hashes to");+ expect((await probe(t.app, cookie, [wrong])).missing).toEqual([wrong]);++ expect(await (await put(t.app, cookie, sha, bytes)).json()).toEqual({ sha });+ expect((await probe(t.app, cookie, [wrong, sha])).missing).toEqual([wrong]);+ expect(+ await fs.readFile(path.join(t.root, "hmr", "store", "blobs", sha.slice(0, 2), sha)),+ ).toEqual(bytes);+ // Not a hash: refused before any byte is read.+ expect((await put(t.app, cookie, "latest", bytes)).status).toBe(400);+ });++ it("a second push names by hash what the first carried inline, and ships only what is new", async () => {+ t = await createTestApp();+ const cookie = (await loginAdmin(t.app)).cookie;++ // Nothing pushed yet: everything is missing.+ const before = await probe(t.app, cookie, [sha256(PKG), sha256(BIN)]);+ expect(before.missing.sort()).toEqual([sha256(PKG), sha256(BIN)].sort());++ // First push, inline (what a pusher without the probe sends): the blobs land in the store.+ const first = await push(+ t.app,+ cookie,+ payload("v1", {+ files: {+ "node_modules/demo-native/package.json": PKG.toString("base64"),+ "node_modules/demo-native/demo.node": BIN.toString("base64"),+ },+ exec: ["node_modules/demo-native/demo.node"],+ }),+ );+ expect(first.status).toBe(200);+ expect(+ (await probe(t.app, cookie, [sha256(PKG), sha256(BIN), sha256(README)])).missing,+ ).toEqual([sha256(README)]);++ // Second push adds one file: it is put, and every file is then named by hash.+ expect((await put(t.app, cookie, sha256(README), README)).status).toBe(200);+ const second = await push(+ t.app,+ cookie,+ payload("v2", {+ files: {+ "node_modules/demo-native/package.json": { sha: sha256(PKG) },+ "node_modules/demo-native/demo.node": { sha: sha256(BIN) },+ "node_modules/demo-native/README.md": { sha: sha256(README) },+ },+ exec: ["node_modules/demo-native/demo.node"],+ }),+ );+ expect(second.status, await second.clone().text()).toBe(200);+ const assetsRoot = path.join(t.root, "hmr", "store", "assets");+ const sets = await fs.readdir(assetsRoot);+ expect(sets).toHaveLength(2);+ const withReadme = sets.find((s) =>+ fsSync.existsSync(path.join(assetsRoot, s, "node_modules/demo-native/README.md")),+ )!;+ expect(+ await fs.readFile(path.join(assetsRoot, withReadme, "node_modules/demo-native/demo.node")),+ ).toEqual(BIN);+ // The exec bit survives a materialization that read from the blob store — a POSIX+ // contract, guarded like the inline-push case above: Windows has no such bit to restore.+ const mode = (+ await fs.stat(path.join(assetsRoot, withReadme, "node_modules/demo-native/demo.node"))+ ).mode;+ if (process.platform !== "win32") expect(mode & 0o111).not.toBe(0);+ });++ it("refuses a name the store does not hold, rather than materializing a hole", async () => {+ t = await createTestApp();+ const cookie = (await loginAdmin(t.app)).cookie;+ const res = await push(+ t.app,+ cookie,+ payload("v1", { files: { "node_modules/demo-native/package.json": { sha: sha256(PKG) } } }),+ );+ expect(res.status).toBe(400);+ expect(await res.text()).toContain("does not hold");+ });++ it("every part may be named by hash: the bundles and the web dist too", async () => {+ t = await createTestApp();+ const cookie = (await loginAdmin(t.app)).cookie;+ const platform = Buffer.from(platformServing(["/api/demo/by-hash"], "by-hash"));+ const cliBytes = Buffer.from(MINIMAL_CLI);+ const index = Buffer.from("<html>by hash</html>");+ const asset = Buffer.from("\0helper");+ const body = {+ platform: { sha: sha256(platform) },+ cli: { sha: sha256(cliBytes) },+ web: { files: { "index.html": { sha: sha256(index) } } },+ assets: { files: { "bin/helper": { sha: sha256(asset) } } },+ };++ // Nothing put yet: the push names what the store does not hold, and says which.+ const early = await push(t.app, cookie, body);+ expect(early.status).toBe(400);+ expect(await early.text()).toMatch(+ new RegExp(`platform.*${sha256(platform).slice(0, 12)}.*put it first`),+ );++ for (const bytes of [platform, cliBytes, index, asset]) {+ expect((await put(t.app, cookie, sha256(bytes), bytes)).status).toBe(200);+ }+ const landed = await push(t.app, cookie, body);+ expect(landed.status, await landed.clone().text()).toBe(200);+ // The generation, the web dist and the asset all came out of the blob store.+ expect((await t.app.request("/api/demo/by-hash")).status).toBe(200);+ expect(await (await t.app.request("/")).text()).toContain("by hash");+ const assetsRoot = path.join(t.root, "hmr", "store", "assets");+ const [set] = await fs.readdir(assetsRoot);+ expect(await fs.readFile(path.join(assetsRoot, set!, "bin", "helper"))).toEqual(asset);+ // Persisted like an inline push: a restart reads the same record.+ await expect(readHarnessInfo(t.root)).resolves.toMatchObject({+ bundles: { cli: expect.stringContaining("store/cli/") },+ });+ // The commit's sweep keeps the parts it was pushed as: the next identical push carries+ // nothing and needs no put. (This was the bug that re-sent every bundle every time.)+ const shas = [platform, cliBytes, index, asset].map(sha256);+ expect((await probe(t.app, cookie, shas)).missing).toEqual([]);+ const again = await push(t.app, cookie, body);+ expect(again.status, await again.clone().text()).toBe(200);+ });++ it("collects blobs no kept assets set records, and keeps the rest", async () => {+ t = await createTestApp();+ const cookie = (await loginAdmin(t.app)).cookie;+ const blobsDir = path.join(t.root, "hmr", "store", "blobs");+ // A blob in the flat layout of an older store: nothing resolves it, so the sweep drops it.+ const legacy = path.join(blobsDir, sha256(Buffer.from("flat")));+ await fs.mkdir(blobsDir, { recursive: true });+ await fs.writeFile(legacy, "flat");+ // Four pushes with four distinct files: the store keeps current + one rollback, so the+ // two oldest sets go, and with them the blobs only they referenced.+ const contents = ["a", "b", "c", "d"].map((x) => Buffer.from(`file ${x}`));+ for (const [i, content] of contents.entries()) {+ const res = await push(+ t.app,+ cookie,+ payload(`v${i}`, { files: { "node_modules/x/f": content.toString("base64") } }),+ );+ expect(res.status).toBe(200);+ }+ // Sharded by the hash's first two hex digits; no shard holds anything but its own blobs.+ const kept: string[] = [];+ for (const shard of await fs.readdir(blobsDir)) {+ expect(shard).toMatch(/^[0-9a-f]{2}$/);+ for (const name of await fs.readdir(path.join(blobsDir, shard))) {+ expect(name.slice(0, 2)).toBe(shard);+ kept.push(name);+ }+ }+ expect(fsSync.existsSync(legacy)).toBe(false);+ expect(kept).toContain(sha256(contents[3]!));+ expect(kept).toContain(sha256(contents[2]!));+ expect(kept).not.toContain(sha256(contents[0]!));+ expect(kept).not.toContain(sha256(contents[1]!));+ });+});+describe("upgrade boot failure: the previous version is re-booted, not left half-dead", () => {let t: TestApp | undefined;@@ -716,7 +933,7 @@ const iface = {migrations: {},};const impl = {- create(_ctx, context) {+ create(ctx, context) {globalThis.__doubleFaultBoots = (globalThis.__doubleFaultBoots ?? 0) + 1;if (globalThis.__doubleFaultBoots > 1) throw new Error("re-boot refused");return {@@ -724,6 +941,8 @@ const impl = {info: () => ({ impl: ${JSON.stringify(id)} }),http(request) {const { pathname } = new URL(request.url);+ // The upgrade channel every generation must carry (admitsUpgradeRoute): the mechanism's endpoint, claimed.+ if (pathname.startsWith("/api/hmr/")) return ctx.resources.claim("platform.hmrControl").endpoint(request);if (pathname !== ${JSON.stringify(path)}) return null;return new Response(JSON.stringify({ servedBy: ${JSON.stringify(id)} }), {status: 200,@@ -784,8 +1003,10 @@ describe("double fault: the upgrade channel survives a failed push whose recoverexpect(JSON.stringify(await bad.json())).toMatch(/failed to boot.*boom/);expect(warnings.join("")).toMatch(/boot-failure recovery failed too/);- // The claim under test: /api/hmr is runtime-owned, so it answers out of the runtime's- // own routes no matter what state the platform tree is in, and a good push repairs the+ // The claim under test: the upgrade channel is the platform's now, but a platform whose+ // recovery failed is left in place, disposed, and its routes still answer out of their+ // closures — the half-dead state this warning names. The channel needs nothing of the+ // stopped App (the control object is the layer's), so a good push repairs the// installation without a restart.const good = await pushPlatform(t.app,@@ -827,7 +1048,7 @@ describe("double fault: the upgrade channel survives a failed push whose recover// A real restart is a fresh process, so the bundle's module state starts over.faultGlobals.__doubleFaultBoots = 0;- const fresh = new HmrHost(root);+ const fresh = new HmrHost<PlatformApi>(root, packagedPlatform);try {const instance = await fresh.ensure();expect((instance.api as unknown as { info(): { impl: string } }).info().impl).toBe("brittle");diff --git a/packages/server/test/hmr-http-seam.test.ts b/packages/server/test/hmr-http-seam.test.tsindex cb76600e..85f3dbfe 100644--- a/packages/server/test/hmr-http-seam.test.ts+++ b/packages/server/test/hmr-http-seam.test.ts@@ -13,8 +13,11 @@ import zlib from "node:zlib";import fs from "node:fs/promises";import { fileURLToPath } from "node:url";import { afterEach, beforeEach, describe, expect, it } from "vitest";-import type { Hono } from "hono";+import { Hono } from "hono";import type { AppEnv } from "../src/auth/middleware.js";+import type { Hmr } from "@prismshadow/penguin-hmr";+import { platformHttpSeam } from "../src/hmr/http-seam.js";+import type { PlatformApi } from "../src/hmr/platform.js";import { apiClient, createTestApp, loginAdmin } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -73,27 +76,36 @@ describe("platform HTTP seam", () => {expect(await (await api.get("/api/version")).json()).toEqual({ version: "from-platform" });});- it("routes the platform declines still reach the runtime's own", async () => {+ it("the layer serves nothing but /api/hmr: what a platform declines is not found", async () => {await pushPlatform(t.app, cookie, bundle);- // The runtime's own routes are the mechanism surface (auth, hmr, desktop, static):- // login still works with a fixture platform in place, because the fixture declines- // /api/auth and the runtime serves it. Business routes are NOT runtime fallbacks —- // /api/me travels with the business platform, which this push replaced.- const login = await loginAdmin(t.app);- expect(login.user.userId).toBe("admin");+ // The fixture declines /api/auth and /api/desktop; there is no copy below the seam to+ // land on. A platform without a route is a platform without it.+ const login = await t.app.request("/api/auth/login", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ userId: "admin", password: "irrelevant" }),+ });+ expect(login.status).toBe(404);+ const shutdown = await t.app.request("/api/desktop/shutdown", { method: "POST" });+ expect(shutdown.status).toBe(404);expect((await api.get("/api/me")).status).toBe(404);});- it("cannot claim the upgrade channel — one bad push must not lock the box out", async () => {- await pushPlatform(t.app, cookie, bundle);- // The fixture answers 418 for anything under /api/hmr; the runtime never offers- // it, so an unrouted path there is the runtime's own 404 rather than the- // platform's 418 — proof the claim was refused, not merely unmatched.- const probe = await api.get("/api/hmr/upgrade");- expect(probe.status).not.toBe(418);- expect(probe.status).toBe(404);- // …and the channel still accepts the next push, which is the property that matters.+ it("a platform without the upgrade channel is refused — one bad push must not lock the box out", async () => {+ // The channel is the platform's to serve, so a generation that hijacks it (or lacks it)+ // would be committed, restored on every restart, and never replaceable. It is refused+ // before commit instead: the push fails, the previous generation keeps serving, and the+ // next good push lands.+ const hijacker = platformServing(["/api/demo/x"], "hijacker").replace(+ 'if (pathname.startsWith("/api/hmr/")) return ctx.resources.claim("platform.hmrControl").endpoint(request);',+ 'if (pathname === "/api/hmr/upgrade") return new Response("hijacked", { status: 418 });',+ );+ const bad = await pushPlatform(t.app, cookie, hijacker);+ expect(bad.status).toBe(400);+ expect(await bad.text()).toMatch(/serves no \/api\/hmr\/upgrade/);+ expect((await api.get("/api/demo/x")).status).toBe(404);expect((await pushPlatform(t.app, cookie, bundle)).status).toBe(200);+ expect((await api.get("/api/demo/ping")).status).toBe(200);});it("a platform that throws answers 500 instead of quietly falling through", async () => {@@ -135,12 +147,14 @@ const iface = {};const SERVED = ${JSON.stringify(paths)};const impl = {- create(_ctx, context) {+ create(ctx, context) {return {park: () => context,info: () => ({ impl: ${JSON.stringify(id)} }),http(request) {const { pathname } = new URL(request.url);+ // The upgrade channel every generation must carry (admitsUpgradeRoute): the mechanism's endpoint, claimed.+ if (pathname.startsWith("/api/hmr/")) return ctx.resources.claim("platform.hmrControl").endpoint(request);if (!SERVED.includes(pathname)) return null;return new Response(JSON.stringify({ servedBy: ${JSON.stringify(id)}, pathname }), {status: 200,@@ -261,13 +275,15 @@ const iface = {migrations: {},};const impl = {- async create(_ctx, context) {+ async create(ctx, context) {await new Promise((resolve) => setTimeout(resolve, ${delayMs}));return {park: () => context,info: () => ({ impl: ${JSON.stringify(id)} }),http(request) {const { pathname } = new URL(request.url);+ // The upgrade channel every generation must carry (admitsUpgradeRoute): the mechanism's endpoint, claimed.+ if (pathname.startsWith("/api/hmr/")) return ctx.resources.claim("platform.hmrControl").endpoint(request);if (pathname !== "/api/demo/version") return null;return new Response(JSON.stringify({ impl: ${JSON.stringify(id)} }), {status: 200,@@ -313,3 +329,28 @@ describe("platform HTTP seam: a request racing an in-flight swap", () => {expect(await raced.json()).toEqual({ impl: "v2" });});});++describe("no generation is current: the seam answers, it does not fall through", () => {+ /** A control object whose current() always throws, as it does when nothing can boot. */+ const dead = {+ current: () => Promise.reject(new Error("the packaged platform failed to boot")),+ upgrade: () => Promise.reject(new Error("not used here")),+ endpoint: () => Promise.reject(new Error("not used here")),+ } as unknown as Hmr<PlatformApi>;++ const app = new Hono();+ app.use("*", platformHttpSeam(dead));+ app.get("/api/anything", (c) => c.json({ from: "the tail" }));++ it("says so instead of letting the static tail answer for it", async () => {+ const res = await app.request("/api/anything");+ expect(res.status).toBe(503);+ expect(await res.text()).toContain("the packaged platform failed to boot");+ });++ it("promises no retry: nothing here ends on its own, unlike the starting window", async () => {+ const res = await app.request("/");+ expect(res.status).toBe(503);+ expect(res.headers.get("retry-after")).toBeNull();+ });+});diff --git a/packages/server/test/hmr-manifest.test.ts b/packages/server/test/hmr-manifest.test.tsindex 889e7a66..0bc27429 100644--- a/packages/server/test/hmr-manifest.test.ts+++ b/packages/server/test/hmr-manifest.test.ts@@ -7,7 +7,7 @@ import fs from "node:fs/promises";import os from "node:os";import path from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { readHarnessInfo, resolveCliBundlePath } from "../src/hmr/manifest.js";+import { readHarnessInfo, readPushedCli, resolveCliBundlePath } from "../src/hmr/manifest.js";async function makeRoot(): Promise<string> {return fs.mkdtemp(path.join(os.tmpdir(), "penguin-hmr-manifest-test-"));@@ -19,71 +19,97 @@ async function writeManifest(root: string, manifest: unknown): Promise<void> {await fs.writeFile(path.join(hmrDir, "harness.json"), JSON.stringify(manifest));}-describe("resolveCliBundlePath", () => {+describe("readPushedCli: nothing pushed and a record it cannot produce are different answers", () => {let root: string | undefined;afterEach(async () => {if (root) await fs.rm(root, { recursive: true, force: true });root = undefined;});- it("returns null (not a throw) for a fresh root with no harness.json at all", async () => {+ it("is `none` for a fresh root with no harness.json at all", async () => {root = await makeRoot();- await expect(resolveCliBundlePath(root)).resolves.toBeNull();+ await expect(readPushedCli(root)).resolves.toEqual({ kind: "none" });});- it("returns null (not a throw) for `cli: {}` — no `bundle` key", async () => {+ it("is `none` for a record with no `cli` entry — nothing pushed a CLI here", async () => {root = await makeRoot();- await writeManifest(root, { cli: {} });- await expect(resolveCliBundlePath(root)).resolves.toBeNull();+ await writeManifest(root, { platform: { bundle: "store/platform/abc.mjs" } });+ await expect(readPushedCli(root)).resolves.toEqual({ kind: "none" });});- it("returns null (not a throw) when `bundle` is not a string", async () => {+ it("is `broken`, naming the file, for a harness.json that will not parse", async () => {root = await makeRoot();- await writeManifest(root, { cli: { bundle: 42 } });- await expect(resolveCliBundlePath(root)).resolves.toBeNull();+ await fs.mkdir(path.join(root, "hmr"), { recursive: true });+ await fs.writeFile(path.join(root, "hmr", "harness.json"), "{ not json");+ const cli = await readPushedCli(root);+ expect(cli.kind).toBe("broken");+ expect(cli.kind === "broken" && cli.reason).toMatch(/harness\.json is not readable JSON/);});- it("returns null (not a throw) when `bundle` is an empty string", async () => {+ it("is `broken` for a `cli` entry with no usable bundle path", async () => {root = await makeRoot();- await writeManifest(root, { cli: { bundle: "" } });- await expect(resolveCliBundlePath(root)).resolves.toBeNull();+ for (const bundle of [42, ""]) {+ await writeManifest(root, { cli: { bundle } });+ expect((await readPushedCli(root)).kind).toBe("broken");+ }+ await writeManifest(root, { cli: {} });+ expect((await readPushedCli(root)).kind).toBe("broken");});- it("returns null for a bundle path that escapes <root>/hmr/ via `..`", async () => {+ it("is `broken` for a bundle path that escapes <root>/hmr/, planted file and all", async () => {root = await makeRoot();- // Plant a real file the escape would otherwise reach, to prove the guard — not the- // file's mere non-existence — is what returns null.+ // A real file the escape would otherwise reach, to prove the guard — not the file's+ // mere non-existence — is what refuses it.await fs.writeFile(path.join(root, "escaped.mjs"), "export const cli = async () => 0;\n");await writeManifest(root, { cli: { bundle: "../escaped.mjs" } });- await expect(resolveCliBundlePath(root)).resolves.toBeNull();+ const cli = await readPushedCli(root);+ expect(cli.kind === "broken" && cli.reason).toMatch(/outside/);});- it("returns null for an absolute bundle path (also an escape attempt)", async () => {+ it("is `broken` for an absolute bundle path (also an escape attempt)", async () => {root = await makeRoot();const outside = path.join(os.tmpdir(), "not-under-hmr.mjs");await fs.writeFile(outside, "export const cli = async () => 0;\n");try {await writeManifest(root, { cli: { bundle: outside } });- await expect(resolveCliBundlePath(root)).resolves.toBeNull();+ expect((await readPushedCli(root)).kind).toBe("broken");} finally {await fs.rm(outside, { force: true });}});- it("resolves a legitimate, in-store bundle path", async () => {+ it("is `broken`, not `none`, when the store lost the file (pruned)", async () => {+ root = await makeRoot();+ await writeManifest(root, { cli: { bundle: "store/cli/nonexistent.mjs" } });+ const cli = await readPushedCli(root);+ expect(cli.kind).toBe("broken");+ expect(cli.kind === "broken" && cli.reason).toMatch(/missing from the store/);+ });++ it("is the bundle for a legitimate, in-store path", async () => {root = await makeRoot();const storeDir = path.join(root, "hmr", "store", "cli");await fs.mkdir(storeDir, { recursive: true });await fs.writeFile(path.join(storeDir, "abc123.mjs"), "export const cli = async () => 0;\n");await writeManifest(root, { cli: { bundle: "store/cli/abc123.mjs" } });- const resolved = await resolveCliBundlePath(root);- expect(resolved).toBe(path.join(root, "hmr", "store", "cli", "abc123.mjs"));+ await expect(readPushedCli(root)).resolves.toEqual({+ kind: "bundle",+ file: path.join(root, "hmr", "store", "cli", "abc123.mjs"),+ });});- it("returns null when the referenced file does not exist (e.g. pruned)", async () => {+ it("keeps resolveCliBundlePath's shape for the published subpath: the path, or null", async () => {root = await makeRoot();+ await expect(resolveCliBundlePath(root)).resolves.toBeNull();await writeManifest(root, { cli: { bundle: "store/cli/nonexistent.mjs" } });await expect(resolveCliBundlePath(root)).resolves.toBeNull();+ const storeDir = path.join(root, "hmr", "store", "cli");+ await fs.mkdir(storeDir, { recursive: true });+ await fs.writeFile(path.join(storeDir, "abc123.mjs"), "export const cli = async () => 0;\n");+ await writeManifest(root, { cli: { bundle: "store/cli/abc123.mjs" } });+ await expect(resolveCliBundlePath(root)).resolves.toBe(+ path.join(root, "hmr", "store", "cli", "abc123.mjs"),+ );});});diff --git a/packages/server/test/hmr-resources.test.ts b/packages/server/test/hmr-resources.test.tsindex 34e94824..581de9b0 100644--- a/packages/server/test/hmr-resources.test.ts+++ b/packages/server/test/hmr-resources.test.ts@@ -15,23 +15,24 @@ import {upgrade,} from "@prismshadow/penguin-core/kernel";import type { Json } from "@prismshadow/penguin-core/kernel";-import { HotResources } from "../src/hmr/resources.js";+import { HotResources } from "@prismshadow/penguin-hmr";import { TerminalManager } from "../src/terminal/manager.js";import type { TerminalSession } from "../src/terminal/session.js";import { DECLARED_RESOURCES as PARKED, packagedPlatform } from "../src/hmr/platform.js";import {RESOURCE_IFACES_RESOURCE_ID,PENGUIN_FAMILY,- RUNTIME_INTERFACES,- RUNTIME_INTERFACES_RESOURCE_ID,- RUNTIME_LIFECYCLE_RESOURCE_ID,- RUNTIME_CHANNELS_RESOURCE_ID,- RUNTIME_CONFIG_RESOURCE_ID,- RUNTIME_DB_RESOURCE_ID,- RUNTIME_HMR_RESOURCE_ID,- RUNTIME_PROXY_RESOURCE_ID,- RUNTIME_AUTH_STATE_RESOURCE_ID,- claimRuntimeCapabilities,+ HMR_INTERFACES,+ HMR_INTERFACES_RESOURCE_ID,+ HMR_LIFECYCLE_RESOURCE_ID,+ HMR_CHANNELS_RESOURCE_ID,+ HMR_CONFIG_RESOURCE_ID,+ HMR_DB_RESOURCE_ID,+ HMR_HOST_RESOURCE_ID,+ HMR_CONTROL_RESOURCE_ID,+ HMR_PROXY_RESOURCE_ID,+ HMR_AUTH_STATE_RESOURCE_ID,+ claimHmrCapabilities,} from "../src/hmr/capabilities.js";/**@@ -41,7 +42,7 @@ import {* is refused, which is the rule the last describe in this file drives.*/async function bootPlatform(r: HotResources, context?: { terminals?: string[] }) {- r.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });+ r.register(HMR_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });const warn = vi.spyOn(console, "warn").mockImplementation(() => {});try {return await boot(@@ -307,26 +308,27 @@ describe("the parked-pty declaration", () => {});describe("runtime capability handshake", () => {- /** Live objects that actually carry the members RUNTIME_INTERFACES names. */+ /** Live objects that actually carry the members HMR_INTERFACES names. */function stubCaps(r: HotResources): void {const carrying = (name: string): Record<string, unknown> => {- const need = RUNTIME_INTERFACES[name];+ const need = HMR_INTERFACES[name];const obj: Record<string, unknown> = {};if (Array.isArray(need)) for (const m of need) obj[m] = () => undefined;return obj;};- r.register(RUNTIME_CONFIG_RESOURCE_ID, carrying("config"));- r.register(RUNTIME_DB_RESOURCE_ID, carrying("db"));- r.register(RUNTIME_CHANNELS_RESOURCE_ID, carrying("channels"));- r.register(RUNTIME_PROXY_RESOURCE_ID, () => {});- r.register(RUNTIME_HMR_RESOURCE_ID, carrying("hmr"));- r.register(RUNTIME_LIFECYCLE_RESOURCE_ID, carrying("lifecycle"));+ r.register(HMR_CONFIG_RESOURCE_ID, carrying("config"));+ r.register(HMR_DB_RESOURCE_ID, carrying("db"));+ r.register(HMR_CHANNELS_RESOURCE_ID, carrying("channels"));+ r.register(HMR_PROXY_RESOURCE_ID, () => {});+ r.register(HMR_HOST_RESOURCE_ID, carrying("hmr"));+ r.register(HMR_CONTROL_RESOURCE_ID, carrying("hmrControl"));+ r.register(HMR_LIFECYCLE_RESOURCE_ID, carrying("lifecycle"));}it("refuses when the runtime publishes no descriptor (a runtime older than the handshake)", () => {const r = new HotResources();stubCaps(r);- expect(claimRuntimeCapabilities(r)).toMatchObject({+ expect(claimHmrCapabilities(r)).toMatchObject({kind: "refused",reason: expect.stringContaining("no interface descriptor") as unknown,});@@ -336,31 +338,31 @@ describe("runtime capability handshake", () => {// Offering NOTHING, in the same document every host describes itself in, is the// honest statement "no business runtime stands behind me" — terminals-only is legal.const r = new HotResources();- r.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });- expect(claimRuntimeCapabilities(r)).toEqual({ kind: "bare" });+ r.register(HMR_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });+ expect(claimHmrCapabilities(r)).toEqual({ kind: "bare" });});it("refuses when one interface is missing a member the claimer names", () => {const r = new HotResources();stubCaps(r);- r.register(RUNTIME_INTERFACES_RESOURCE_ID, { ...RUNTIME_INTERFACES, channels: ["nope"] });- expect(claimRuntimeCapabilities(r)).toMatchObject({ kind: "refused" });+ r.register(HMR_INTERFACES_RESOURCE_ID, { ...HMR_INTERFACES, channels: ["nope"] });+ expect(claimHmrCapabilities(r)).toMatchObject({ kind: "refused" });});it("claims on a matching descriptor", () => {const r = new HotResources();stubCaps(r);- r.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);- expect(claimRuntimeCapabilities(r)).toMatchObject({ kind: "claimed" });+ r.register(HMR_INTERFACES_RESOURCE_ID, HMR_INTERFACES);+ expect(claimHmrCapabilities(r)).toMatchObject({ kind: "claimed" });});it("declines when the descriptor is honest but the live object is not", () => {// What a member set buys over a number: the declaration is verified, not trusted.const r = new HotResources();stubCaps(r);- r.register(RUNTIME_CHANNELS_RESOURCE_ID, { get: () => undefined }); // missing the rest- r.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);- expect(claimRuntimeCapabilities(r)).toMatchObject({+ r.register(HMR_CHANNELS_RESOURCE_ID, { get: () => undefined }); // missing the rest+ r.register(HMR_INTERFACES_RESOURCE_ID, HMR_INTERFACES);+ expect(claimHmrCapabilities(r)).toMatchObject({kind: "refused",reason: expect.stringContaining("channels lacks") as unknown,});@@ -372,8 +374,8 @@ describe("runtime capability handshake", () => {// values are claimed, and optionally.const r = new HotResources();stubCaps(r);- r.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);- const claim = claimRuntimeCapabilities(r);+ r.register(HMR_INTERFACES_RESOURCE_ID, HMR_INTERFACES);+ const claim = claimHmrCapabilities(r);expect(claim).toMatchObject({ kind: "claimed" });if (claim.kind !== "claimed") return;expect(claim.caps.authState).toEqual({ firstLoginToken: null, apiToken: null });@@ -385,10 +387,10 @@ describe("runtime capability handshake", () => {// so a copy would strand the first-login link the App writes into it.const r = new HotResources();stubCaps(r);- r.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);+ r.register(HMR_INTERFACES_RESOURCE_ID, HMR_INTERFACES);const published = { firstLoginToken: "printed-by-the-old-runtime" };- r.register(RUNTIME_AUTH_STATE_RESOURCE_ID, published);- const claim = claimRuntimeCapabilities(r);+ r.register(HMR_AUTH_STATE_RESOURCE_ID, published);+ const claim = claimHmrCapabilities(r);expect(claim).toMatchObject({ kind: "claimed" });if (claim.kind !== "claimed") return;expect(claim.caps.authState).toBe(published);@@ -401,17 +403,17 @@ describe("runtime capability handshake", () => {it("declines a different family outright — the names are not comparable", () => {const r = new HotResources();stubCaps(r);- r.register(RUNTIME_INTERFACES_RESOURCE_ID, { ...RUNTIME_INTERFACES, family: "acme" });- expect(claimRuntimeCapabilities(r)).toMatchObject({ kind: "refused" });+ r.register(HMR_INTERFACES_RESOURCE_ID, { ...HMR_INTERFACES, family: "acme" });+ expect(claimHmrCapabilities(r)).toMatchObject({ kind: "refused" });});it("an interface the claimer never names may differ freely", () => {// The whole point of per-interface versions: a bump the claimer never touches must- // not decline the claim. `extra` is not in RUNTIME_INTERFACES, so it is not required.+ // not decline the claim. `extra` is not in HMR_INTERFACES, so it is not required.const r = new HotResources();stubCaps(r);- r.register(RUNTIME_INTERFACES_RESOURCE_ID, { ...RUNTIME_INTERFACES, extra: ["x"] });- expect(claimRuntimeCapabilities(r)).toMatchObject({ kind: "claimed" });+ r.register(HMR_INTERFACES_RESOURCE_ID, { ...HMR_INTERFACES, extra: ["x"] });+ expect(claimHmrCapabilities(r)).toMatchObject({ kind: "claimed" });});});diff --git a/packages/server/test/hmr-starting.test.ts b/packages/server/test/hmr-starting.test.tsnew file mode 100644index 00000000..5d2ea797--- /dev/null+++ b/packages/server/test/hmr-starting.test.ts@@ -0,0 +1,24 @@+/**+ * What answers when there is no App: the entry's window before one exists, and the seam+ * finding no generation current. The seam's own case is pinned in hmr-http-seam.test.ts.+ */+import { describe, expect, it } from "vitest";+import { noPlatformResponse, startingResponse } from "../src/hmr/starting.js";++describe("the answers with no App behind them", () => {+ it("asks for a retry while starting, because that window ends by itself", async () => {+ const res = startingResponse();+ expect(res.status).toBe(503);+ expect(res.headers.get("retry-after")).toBe("1");+ // Never cached: the next request has to reach the App, not this answer.+ expect(res.headers.get("cache-control")).toBe("no-store");+ expect(await res.text()).toBe("penguin-server is starting");+ });++ it("names the fault and promises no retry when no platform is running", async () => {+ const res = noPlatformResponse("the packaged platform failed to boot");+ expect(res.status).toBe(503);+ expect(res.headers.get("retry-after")).toBeNull();+ expect(await res.text()).toContain("the packaged platform failed to boot");+ });+});diff --git a/packages/server/test/machines.test.ts b/packages/server/test/machines.test.tsindex 8f16df22..9f585951 100644--- a/packages/server/test/machines.test.ts+++ b/packages/server/test/machines.test.ts@@ -1,5 +1,5 @@/**- * The pure half of the machines capability (platform code — see ../src/hmr/README.md):+ * The pure half of the machines capability (platform code — see packages/hmr/README.md):* reading ~/.ssh/config for its aliases, reading what the identity probe answered, choosing* the Node runtime to send, the container the image travels in, finding the running* server's own pushable image, and the exact ssh/scp commands all of that turns into.diff --git a/packages/server/test/park-quiesce.test.ts b/packages/server/test/park-quiesce.test.tsindex 4e9a2e8c..3860edee 100644--- a/packages/server/test/park-quiesce.test.ts+++ b/packages/server/test/park-quiesce.test.ts@@ -8,11 +8,11 @@*/import { describe, expect, it, vi } from "vitest";import { boot, initialDoc, upgrade } from "@prismshadow/penguin-core/kernel";-import { HotResources } from "../src/hmr/resources.js";+import { HotResources } from "@prismshadow/penguin-hmr";import { packagedPlatform } from "../src/hmr/platform.js";import type { PlatformApi } from "../src/hmr/platform.js";import type { Instance } from "@prismshadow/penguin-core/kernel";-import { PENGUIN_FAMILY, RUNTIME_INTERFACES_RESOURCE_ID } from "../src/hmr/capabilities.js";+import { PENGUIN_FAMILY, HMR_INTERFACES_RESOURCE_ID } from "../src/hmr/capabilities.js";import { TerminalManager } from "../src/terminal/manager.js";import type { TerminalSession } from "../src/terminal/session.js";import { waitFor } from "./helpers.js";@@ -48,7 +48,7 @@ function bareKernel(): HotResources {const r = new HotResources();// The bare-kernel declaration IS an interface descriptor: right family, no// capabilities offered — "there is no business runtime behind me".- r.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });+ r.register(HMR_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });return r;}diff --git a/packages/server/test/plugin.test.ts b/packages/server/test/plugin.test.tsindex 5627d07b..9c5ee9c3 100644--- a/packages/server/test/plugin.test.ts+++ b/packages/server/test/plugin.test.ts@@ -6,9 +6,9 @@import { describe, expect, it } from "vitest";import type { ModuleDef } from "@prismshadow/penguin-core/kernel";import { parseManifest, boot, initialDoc } from "@prismshadow/penguin-core/kernel";-import { HotResources } from "../src/hmr/resources.js";+import { HotResources } from "@prismshadow/penguin-hmr";import { PluginHost, PLUGINS_RESOURCE_ID, pluginHostFrom } from "../src/plugin/host.js";-import { PENGUIN_FAMILY, RUNTIME_INTERFACES_RESOURCE_ID } from "../src/hmr/capabilities.js";+import { PENGUIN_FAMILY, HMR_INTERFACES_RESOURCE_ID } from "../src/hmr/capabilities.js";import { packagedPlatform } from "../src/hmr/platform.js";import type { SandboxProvider } from "@prismshadow/penguin-core/plugin";@@ -75,7 +75,7 @@ describe("plugin modules on the real platform", () => {/** A bare-kernel boot (no capabilities): the sandbox floor plus whatever plugins contribute. */async function bootWith(modules: ModuleDef[]) {const resources = new HotResources();- resources.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });+ resources.register(HMR_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });const host = new PluginHost();host.use({ specifier: "test", modules, replaces: [] });resources.register(PLUGINS_RESOURCE_ID, host);@@ -89,7 +89,7 @@ describe("plugin modules on the real platform", () => {it("boots an App when the runtime published no host at all", async () => {const resources = new HotResources();- resources.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });+ resources.register(HMR_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });const inst = await boot(packagedPlatform.impl,packagedPlatform.iface,diff --git a/packages/server/test/sandbox.test.ts b/packages/server/test/sandbox.test.tsindex c8301e38..6c5afb3f 100644--- a/packages/server/test/sandbox.test.ts+++ b/packages/server/test/sandbox.test.ts@@ -6,8 +6,8 @@import { describe, expect, it, vi } from "vitest";import { boot, initialDoc, parseManifest } from "@prismshadow/penguin-core/kernel";import type { Json } from "@prismshadow/penguin-core/kernel";-import { HotResources } from "../src/hmr/resources.js";-import { PENGUIN_FAMILY, RUNTIME_INTERFACES_RESOURCE_ID } from "../src/hmr/capabilities.js";+import { HotResources } from "@prismshadow/penguin-hmr";+import { PENGUIN_FAMILY, HMR_INTERFACES_RESOURCE_ID } from "../src/hmr/capabilities.js";import { packagedPlatform } from "../src/hmr/platform.js";import { PluginHost, PLUGINS_RESOURCE_ID } from "../src/plugin/host.js";import { SandboxService } from "../src/sandbox/index.js";@@ -167,9 +167,9 @@ describe("sandbox settings ride the parked context across a swap", () => {async function bootObserved(doc: Json) {const resources = new HotResources();// A bare-kernel declaration — right family, no capabilities offered — is what makes a- // terminals-only boot legal (see capabilities.ts's RuntimeClaim). The sandbox floor is+ // terminals-only boot legal (see capabilities.ts's HmrClaim). The sandbox floor is// business-independent, so this is all these tests need behind the platform.- resources.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });+ resources.register(HMR_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });// The observer is itself a plugin module requiring the sandbox — the surface an// actual consumer has.let seen: SandboxService | null = null;diff --git a/packages/server/tsup.config.ts b/packages/server/tsup.config.tsindex 845ebbeb..611f3ec1 100644--- a/packages/server/tsup.config.ts+++ b/packages/server/tsup.config.ts@@ -41,6 +41,9 @@ export default defineConfig({dts: true,clean: true,sourcemap: true,+ // The hot-update mechanism is a package for the boundary, not for npm (it is `private`):+ // inlined here so this package's published dist stays self-contained.+ noExternal: ["@prismshadow/penguin-hmr"],// Scripts that run somewhere else, as REAL files beside the bundles: the release installers// a remote install feeds to the far side (the one thing that has to arrive before the CLI// does; everything after is a `penguin` subcommand the machine already has). Each isdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 59402f1e..35283c17 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -323,6 +323,19 @@ importers:specifier: ^3.2.6version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ packages/hmr:+ dependencies:+ '@prismshadow/penguin-core':+ specifier: workspace:*+ version: file:packages/core([email protected])([email protected])+ devDependencies:+ tsup:+ specifier: ^8.3.0+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: ^3.2.6+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+packages/landing:dependencies:react:@@ -386,6 +399,9 @@ importers:'@prismshadow/penguin-core':specifier: workspace:*version: file:packages/core([email protected])([email protected])+ '@prismshadow/penguin-hmr':+ specifier: workspace:*+ version: file:packages/hmr([email protected])([email protected])'@xterm/headless':specifier: ^5.5.0version: 5.5.0@@ -1518,6 +1534,9 @@ packages:resolution: {directory: packages/core, type: directory}engines: {node: '>=24'}+ '@prismshadow/penguin-hmr@file:packages/hmr':+ resolution: {directory: packages/hmr, type: directory}+'@prismshadow/penguin-server@file:packages/server':resolution: {directory: packages/server, type: directory}engines: {node: '>=24'}@@ -5523,11 +5542,34 @@ snapshots:- ws- zod+ '@prismshadow/penguin-hmr@file:packages/hmr([email protected])([email protected])':+ dependencies:+ '@prismshadow/penguin-core': file:packages/core([email protected])([email protected])+ transitivePeerDependencies:+ - '@modelcontextprotocol/sdk'+ - bufferutil+ - supports-color+ - utf-8-validate+ - ws+ - zod++ '@prismshadow/penguin-hmr@file:packages/hmr([email protected])([email protected])([email protected])':+ dependencies:+ '@prismshadow/penguin-core': file:packages/core([email protected])([email protected])([email protected])+ transitivePeerDependencies:+ - '@modelcontextprotocol/sdk'+ - bufferutil+ - supports-color+ - utf-8-validate+ - ws+ - zod+'@prismshadow/penguin-server@file:packages/server([email protected])':dependencies:'@hono/node-server': 2.0.12([email protected])'@prismshadow/penguin-core': file:packages/core([email protected])([email protected])+ '@prismshadow/penguin-hmr': file:packages/hmr([email protected])([email protected])'@xterm/headless': 5.5.0dotenv: 17.4.2fflate: 0.8.3@@ -5554,6 +5596,7 @@ snapshots:'@hono/node-server': 2.0.12([email protected])'@prismshadow/penguin-core': file:packages/core([email protected])([email protected])([email protected])+ '@prismshadow/penguin-hmr': file:packages/hmr([email protected])([email protected])([email protected])'@xterm/headless': 5.5.0dotenv: 17.4.2fflate: 0.8.3diff --git a/scripts/deploy.mjs b/scripts/deploy.mjsindex d0d6a99f..72c39960 100644--- a/scripts/deploy.mjs+++ b/scripts/deploy.mjs@@ -30,6 +30,7 @@ import { unsafePlaintextTarget } from "./deploy-target-safety.mjs";import { buildGitDefine, checkoutFacts, originUrl } from "./build-git-stamp.mjs";import { ESM_CJS_BANNER } from "./esm-cjs-banner.mjs";import { FAR_SIDE_SCRIPTS } from "./far-side-scripts.mjs";+import { createHash } from "node:crypto";const require = createRequire(import.meta.url);const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");@@ -163,6 +164,12 @@ async function compileEntry(entry, outfile) {bundle: true,format: "esm",platform: "node",+ // The Node that runs it (package.json engines). Without a target esbuild compiles for+ // `esnext`, where it takes standard decorators to be supported and emits them as they+ // were written — and no Node parses those, so the pushed bundle fails to import with+ // "Invalid or unexpected token" and the target keeps the generation it had. The+ // packaged build does not hit this because tsup passes a target of its own.+ target: "node24",outfile,logLevel: "silent",banner: { js: ESM_CJS_BANNER },@@ -184,9 +191,7 @@ async function readWebManifest() {for (const entry of await fsp.readdir(WEB_DIST, { recursive: true, withFileTypes: true })) {if (!entry.isFile()) continue;const abs = path.join(entry.parentPath, entry.name);- files[path.relative(WEB_DIST, abs).split(path.sep).join("/")] = (- await fsp.readFile(abs)- ).toString("base64");+ files[path.relative(WEB_DIST, abs).split(path.sep).join("/")] = await fsp.readFile(abs);}return files;}@@ -226,7 +231,7 @@ async function readNativeAssets() {const rel = path.relative(ptyDir, abs).split(path.sep).join("/");if (!wanted(rel)) continue;const target = `node_modules/node-pty/${rel}`;- files[target] = (await fsp.readFile(abs)).toString("base64");+ files[target] = await fsp.readFile(abs);// node-pty ships its prebuilt spawn-helper as 0644; the runtime restores the bit from// this list, so push it regardless of how it looks on this machine.if (rel.endsWith("spawn-helper") || ((await fsp.stat(abs)).mode & 0o111) !== 0) {@@ -238,7 +243,7 @@ async function readNativeAssets() {// from its own assets directory, so a push that omits one leaves a server that cannot// install a machine at all. Same set the packaged build copies into dist/; see the module.for (const { name, from } of FAR_SIDE_SCRIPTS) {- files[name] = (await fsp.readFile(path.join(ROOT, from))).toString("base64");+ files[name] = await fsp.readFile(path.join(ROOT, from));}return { files, exec };}@@ -264,23 +269,58 @@ async function main() {const files = await readWebManifest();const assets = await readNativeAssets();const source = pushSource();- const gz = zlib.gzipSync(- Buffer.from(- JSON.stringify({- platform: await fsp.readFile(PLATFORM_BUNDLE, "utf8"),- cli: await fsp.readFile(CLI_BUNDLE, "utf8"),- web: { files },- assets,- ...(source === null ? {} : { source }),- }),- ),- );++ const cookie = await login();+ const platform = await fsp.readFile(PLATFORM_BUNDLE);+ const cli = await fsp.readFile(CLI_BUNDLE);+ const mapValues = (o, f) => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, f(v)]));+ const body = (part) => ({+ platform: part(platform, "utf8"),+ cli: part(cli, "utf8"),+ web: { files: mapValues(files, (b) => part(b, "base64")) },+ assets: { files: mapValues(assets.files, (b) => part(b, "base64")), exec: assets.exec },+ ...(source === null ? {} : { source }),+ });+ // Content-addressed transfer, the way git pushes: name every part by its sha256, ask the+ // target which blobs it lacks, PUT only those (raw), then push a body of names. A target+ // without the probe (an older runtime) answers 404 and gets every part inline.+ const blobs = new Map();+ let payload = body((bytes) => {+ const sha = createHash("sha256").update(bytes).digest("hex");+ blobs.set(sha, bytes);+ return { sha };+ });+ const probe = await request(`${baseUrl}/api/hmr/assets/probe`, {+ method: "POST",+ headers: { "content-type": "application/json", cookie },+ body: JSON.stringify({ hashes: [...blobs.keys()] }),+ });+ if (probe.status === 200) {+ let sent = 0;+ for (const sha of JSON.parse(probe.body.toString("utf8")).missing) {+ const bytes = blobs.get(sha);+ if (bytes === undefined) continue;+ const put = await request(`${baseUrl}/api/hmr/blobs/${sha}`, {+ method: "PUT",+ headers: { "content-type": "application/octet-stream", cookie },+ body: bytes,+ });+ if (put.status !== 200) {+ throw new Error(`PUT /api/hmr/blobs/${sha} → ${put.status}: ${put.body.toString("utf8")}`);+ }+ sent += bytes.length;+ }+ log(`${blobs.size} blobs; ${(sent / 1048576).toFixed(1)} MB were new to the target`);+ } else {+ log("target has no probe: pushing everything inline");+ payload = body((bytes, encoding) => bytes.toString(encoding));+ }+ const gz = zlib.gzipSync(Buffer.from(JSON.stringify(payload)));if (source !== null) log(`provenance: ${source.revision}`);log(- `pushing ${Object.keys(files).length} web files + ${Object.keys(assets.files).length} native assets + 2 bundles (${(gz.length / 1048576).toFixed(1)} MB) to ${baseUrl}…`,+ `pushing ${Object.keys(files).length} web files + ${Object.keys(assets.files).length} assets + 2 bundles (${(gz.length / 1048576).toFixed(1)} MB body) to ${baseUrl}…`,);- const cookie = await login();const started = Date.now();const res = await request(`${baseUrl}/api/hmr/upgrade`, {method: "POST",