Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(core): process failures of hot update (#387)

Myriad-Dreamin399ca0fc7883
diff --git a/changelog/unreleased/2026-08-20-hot-update-failure-modes.md b/changelog/unreleased/2026-08-20-hot-update-failure-modes.md
new file mode 100644
index 00000000..59b4f96a
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-hot-update-failure-modes.md
@@ -0,0 +1,80 @@
+# The hot update path answers its three failure modes
+
+- **Date:** 2026-08-20
+- **Type:** fix
+- **Scope:** `core`, `server`
+- **PR:** [#387](https://github.com/Prism-Shadow/penguin-harness/pull/387)
+
+Pushing a platform ([hot update](../0.2.3/2026-08-18-hot-update.md)) had three ways to go
+wrong that ended somewhere other than "the push failed": a bundle the target could not run
+landed as half a version, a swap left the old App's work running behind the new one's back,
+and a bundle that failed to boot took the business surface down until a restart. Each is now
+a definite outcome.
+
+## A bundle the target cannot run
+
+Pushing a current bundle to an installation whose runtime predates the resource-interface
+handshake left the machine serving the **new** frontend against the **old** API — the browser
+crashed with `Cannot read properties of undefined (reading 'attachmentLimitMinMb')` on opening
+Upload limits, because `/api/me` was still the previous version's. The push is atomic, but the
+platform it delivers has to *claim* the runtime's business capabilities before it can serve the
+business API, and a runtime too old to publish them made that claim fail. The platform's answer
+was to degrade to a terminals-only App: it declined every business route, the seam handed those
+requests back, and the older runtime answered them out of its own built-in routes. One atomic
+push therefore landed as half a version, silently, reported as a success.
+
+A platform that cannot claim the capabilities now refuses to boot, so the upgrade rolls back
+the way any failed boot does — the running version keeps serving, the web dist is not
+committed, nothing is persisted — and the push reports the reason: the installation itself has
+to be updated, because a push replaces the platform and never the runtime. A machine already
+carrying such a half version needs that update too; its committed bundle predates the check, so
+a restart restores it degraded again, and updating the installation lets the same bundle claim
+successfully and serve whole (clearing `<data root>/hmr/harness.json` falls back to the
+packaged version instead).
+
+A host that genuinely has no business runtime behind it declares that in the same interface
+descriptor every host describes itself with, and still gets a terminals-only platform. Being
+*unable to answer* stopped being read as *asking for terminals only*.
+
+## The handover between generations
+
+Replacing the platform used to stop the old App loosely: the scheduler was stopped and agent
+runs were aborted, but the abort was fire-and-forget, so the new App could serve while the old
+one's runs were still winding down. Resources fell through the cracks with it — a dev server a
+conversation had started kept running with no successor able to see or stop it, and the old
+App's pty reap timers and exit listeners kept firing from a dead generation, disposing sessions
+and removing registry entries the new App owned.
+
+Every resource an App creates was put on a written inventory with one of three fates, and the
+swap executes it:
+
+- **Delivered** — ptys survive through the resource registry and are adopted by the successor;
+ the runtime's own singletons are re-claimed.
+- **Suspended** — the scheduler stops, runs abort, and each Session's environment is disposed,
+ killing the background commands it owns; the successor rebuilds all of it.
+- **Detached** — the old App unsubscribes its pty exit listeners, so nothing of a dead
+ generation acts on an object the new one owns.
+
+The list is the contract rather than a description of the services that exist today: a build
+adding a service with state of its own puts it on the right list, or the swap leaks it.
+
+Dispose is synchronous, so the asynchronous rest — waiting for aborted runs to actually end —
+is exposed by the App and awaited by the kernel between disposing the old tree and booting the
+new one. A successor therefore never races its predecessor.
+
+## A bundle that fails to boot
+
+The kernel's swap is validate-then-swap: the old App is disposed first, so the new one can
+adopt what it delivered. When the new platform's boot then threw, there was no way back — the
+error surfaced as a throw with the parked state lost inside it, and the process was left
+half-dead, the disposed App's routes still answering out of closures while its manager was
+closed (new work got 503), until someone restarted the server.
+
+The kernel now returns that failure — `status: "failed"`, carrying the boot error and the
+parked document — instead of throwing, and the host answers it by re-booting the version that
+was running before, from that parked document. The inventory above is what makes the recovery
+an ordinary load: the disposed App had already suspended and detached, so the recovered App
+adopts the delivered resources and restarts the suspended machinery like any successor. The
+pusher still gets an error, because the push did fail, but the machine keeps working with its
+live state carried through. A double fault only warns: `/api/hmr` is runtime-owned and stays
+reachable for a follow-up push, and a restart restores the committed version regardless.
diff --git a/changelog/unreleased/2026-08-20-hot-update-failure-modes.zh.md b/changelog/unreleased/2026-08-20-hot-update-failure-modes.zh.md
new file mode 100644
index 00000000..9a461468
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-hot-update-failure-modes.zh.md
@@ -0,0 +1,60 @@
+# 热更新这条路补齐了自己的三种失败模式
+
+- **Date:** 2026-08-20
+- **Type:** fix
+- **Scope:** `core`, `server`
+- **PR:** [#387](https://github.com/Prism-Shadow/penguin-harness/pull/387)
+
+推送 platform([热更新](../0.2.3/2026-08-18-hot-update.zh.md))有三种出错方式的结局不是「推送失败」:
+目标跑不了的 bundle 只落地半个版本、交换之后旧 App 的工作还在新 App 背后跑、启动失败的 bundle
+会让业务面一直半死到重启。现在每一种都有确定的结局。
+
+## 目标跑不了的 bundle
+
+把当前的 bundle 推到 runtime 早于资源接口握手的机器上,会让它用**新**前端去打**旧** API——打开
+「上传限制」时浏览器报 `Cannot read properties of undefined (reading 'attachmentLimitMinMb')`,
+因为 `/api/me` 仍然是上一个版本的。推送是原子的,但它送过去的 platform 必须先**认领** runtime
+发布的业务能力才能服务业务 API,而过旧的 runtime 发布不出这些能力,认领失败。platform 当时的
+处理是降级成一个只有终端的 App:它拒绝了所有业务路由,seam 把这些请求交还回去,更旧的 runtime
+就用自己内建的路由回答了它们。于是一次原子推送悄悄地只落地了半个版本,还报告为成功。
+
+现在认领不到业务能力的 platform 会拒绝启动,升级按任何一次启动失败的方式整体回滚——正在运行的
+版本继续服务,web dist 不提交,什么都不持久化——推送方拿到的是原因:需要更新的是这台机器的安装
+本身,因为推送替换的是 platform,从来不是 runtime。已经处在半个版本状态的机器同样需要这次更新:
+它已提交的 bundle 早于这项检查,重启只会把它原样降级恢复;更新安装后,同一个 bundle 就能认领
+成功、完整服务(或者删掉 `<数据根>/hmr/harness.json`,退回打包自带的版本)。
+
+真的没有业务 runtime 的宿主,会在每个宿主用来自我描述的那份接口描述符里把这件事说出来,照旧得到
+只有终端的 platform。「答不上来」不再被当成「只要终端」。
+
+## 两代之间的交接
+
+替换 platform 以前停旧 App 停得很松:调度器停了、agent 运行中止了,但中止是发完即忘,于是新 App
+可能已经在服务,旧 App 的运行还在收尾。资源也跟着漏了——会话里启动的 dev server 一直跑着,继任者
+既看不见也停不掉;旧 App 的 pty 回收定时器和退出监听会从一个已死的世代里继续触发,dispose 的会话、
+移除的注册表条目却已经归新 App 所有。
+
+App 创建的每一个资源都被列进一份成文清单,三种命运之一,交换按清单执行:
+
+- **交付**——pty 通过资源注册表跨代存活,由继任者接管;runtime 自己的单例由每代重新认领。
+- **暂停**——调度器停止,运行中止,每个会话的环境被 dispose,杀掉它拥有的后台命令;继任者全部
+ 重新构建。
+- **脱钩**——旧 App 注销自己的 pty 退出监听,已死的世代不再对新世代拥有的对象做任何动作。
+
+这份清单是契约,而不是对当下存在的服务的描述:新增自带状态的服务要自己选一条列表,否则交换就会
+漏掉它。
+
+dispose 是同步的,所以异步的剩余部分——等被中止的运行真正结束——由 App 暴露出来,内核在 dispose
+旧树与启动新树之间等待它。继任者因此绝不会与前任并行。
+
+## 启动失败的 bundle
+
+内核的交换是先校验、后交换:旧 App 先被 dispose,新 App 才能接管它交付的资源。此前如果新 platform
+的启动随后抛错,就没有回头路了——错误以异常抛出、park 状态丢在异常里,进程陷入半死:被 dispose 的
+App 的路由还靠闭包应答,但它的 manager 已关闭(新任务一律 503),直到有人重启服务器。
+
+现在内核以返回值报告这次失败——`status: "failed"`,携带启动错误和 park 文档——而不是抛出,host 用
+它把之前运行的那个版本从这份 park 文档重新启动。上面那份清单正是让恢复变成一次普通 load 的东西:
+被 dispose 的 App 已经完成了暂停与脱钩,恢复的 App 接管交付的资源、重启被暂停的机器,和任何继任者
+一样。推送方仍然拿到错误,因为推送确实失败了,但那台机器继续工作,活状态原样延续。二次故障只会
+告警:`/api/hmr` 归 runtime 所有、始终可达,后续推送仍能修复,重启则无论如何都会恢复已提交的版本。
diff --git a/packages/core/src/kernel/boot.ts b/packages/core/src/kernel/boot.ts
index 877f1eb1..97526280 100644
--- a/packages/core/src/kernel/boot.ts
+++ b/packages/core/src/kernel/boot.ts
@@ -22,10 +22,17 @@ export interface Resources {
* `dispose` is how a resource says what "shut down" means for it — the registry
* itself knows nothing about kinds, so a platform can introduce a resource type the
* runtime has never heard of and still have it cleaned up at process exit.
+ *
+ * Returns the PAIRED unregister for this exact registration: it removes the entry AND
+ * runs its dispose — out of the registry means shut down, or the process-exit sweep
+ * could no longer reach it. Both are identity-checked: a later overwrite by a successor
+ * turns the handle into a no-op and moves shutdown responsibility to the new
+ * registration — a dead generation can never touch a slot it no longer owns. This is
+ * the only way to remove a single entry; there is deliberately no release-by-id, which
+ * would be an unpaired delete aimed at whatever happens to occupy the slot.
*/
- register(id: string, resource: unknown, dispose?: () => void): void;
+ register(id: string, resource: unknown, dispose?: () => void): () => void;
claim<T = unknown>(id: string): T | undefined;
- release(id: string): void;
/**
* Disposes and removes every entry whose id belongs to the group (`terminal` covers
* `terminal:*`), in reverse registration order — later entries may depend on earlier
diff --git a/packages/core/src/kernel/index.ts b/packages/core/src/kernel/index.ts
index 5c3a9957..912c2b68 100644
--- a/packages/core/src/kernel/index.ts
+++ b/packages/core/src/kernel/index.ts
@@ -21,5 +21,5 @@ export type {
Resources,
} from "./boot.js";
export { boot, BootError, initialDoc } from "./boot.js";
-export type { UpgradeBlocked, UpgradeResult } from "./upgrade.js";
+export type { UpgradeBlocked, UpgradeFailed, UpgradeResult } from "./upgrade.js";
export { upgrade } from "./upgrade.js";
diff --git a/packages/core/src/kernel/upgrade.ts b/packages/core/src/kernel/upgrade.ts
index 9bd5c144..b8f368f3 100644
--- a/packages/core/src/kernel/upgrade.ts
+++ b/packages/core/src/kernel/upgrade.ts
@@ -9,9 +9,12 @@
* the kernel.
*
* Validate-then-swap: the running tree is only disposed after the whole
- * document reconciles. MVP accepts the residual risk that boot itself may still
- * throw after dispose — the doc is returned to the caller for persistence, so
- * the worst case is "old impl + parked doc, re-boot by hand", never data loss.
+ * document reconciles. Boot itself can still fail after the dispose — that
+ * residual risk is surfaced as a RETURNED outcome (`status: "failed"`, carrying
+ * the parked document), never a throw: the caller holds everything needed to
+ * re-boot the previous implementation from that document, so the worst case is
+ * an automatic recovery boot, never data loss and never a half-dead process
+ * whose old tree is disposed with nothing booted in its place.
*/
import type { Json } from "./json.js";
import { isJsonObject } from "./json.js";
@@ -29,8 +32,22 @@ export interface UpgradeBlocked {
doc: Json;
}
+export interface UpgradeFailed {
+ status: "failed";
+ /** What the new implementation's boot threw. */
+ error: unknown;
+ /**
+ * The parked document. The OLD tree is disposed by this point (validate-then-swap
+ * disposes before boot, so the new tree can adopt what the old one delivered) — this
+ * document is what the previous implementation re-boots from.
+ */
+ doc: Json;
+}
+
export type UpgradeResult<A extends Park> =
- { status: "ok"; mode: "silent" | "migrated"; instance: Instance<A>; doc: Json } | UpgradeBlocked;
+ | { status: "ok"; mode: "silent" | "migrated"; instance: Instance<A>; doc: Json }
+ | UpgradeBlocked
+ | UpgradeFailed;
/** An undeclared child that is an empty container (no data to lose). */
function isEmptyChildDoc(doc: Json): boolean {
@@ -134,6 +151,17 @@ export async function upgrade<A extends Park, C extends Json>(opts: {
};
}
opts.current.dispose();
- const instance = await boot(opts.impl, opts.iface, doc, opts.resources);
+ // A disposed tree may have an asynchronous tail — work its dispose effects aborted but
+ // could not await (effects are synchronous). An implementation exposes it as an optional
+ // in-process `drained` member; awaiting it HERE, between dispose and boot, is what makes
+ // a successor never race its predecessor — and a failed boot below cannot lose it,
+ // because it has already been awaited.
+ await (opts.current.api as { drained?: () => Promise<void> | undefined }).drained?.();
+ let instance: Instance<A>;
+ try {
+ instance = await boot(opts.impl, opts.iface, doc, opts.resources);
+ } catch (error) {
+ return { status: "failed", error, doc: parked };
+ }
return { status: "ok", mode: state.migrated ? "migrated" : "silent", instance, doc };
}
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index ddb5c42e..174744f3 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -3,10 +3,11 @@
*
* 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 runtime core (database, auth, channels, HmrHost),
- * publishes its capabilities into the resource registry (see hmr/capabilities.ts), and
- * boots the platform — which returns the merged view. Neither listens on a port: tests
- * inject requests via `app.request()`, and the startup entry point is index.ts.
+ * `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.
*
* The BUSINESS surface — `buildAppDeps` + `createApp`, at the bottom of this
* file — is what a hot push replaces. Both are called from `platformImpl.create`
@@ -26,7 +27,6 @@ import type { DatabaseSync } from "node:sqlite";
import type { ServerConfig } from "./config.js";
import { applyProxySettings, mergedNoProxy } from "./net/proxy.js";
import {
- PLATFORM_CURRENT_RESOURCE_ID,
RUNTIME_INTERFACES,
RUNTIME_INTERFACES_RESOURCE_ID,
RUNTIME_AUTH_RESOURCE_ID,
@@ -39,7 +39,7 @@ import {
RUNTIME_PROXY_RESOURCE_ID,
RuntimeCapabilities,
} from "./hmr/capabilities.js";
-import type { PlatformCurrent, ProxyControl } from "./hmr/capabilities.js";
+import type { ProxyControl } from "./hmr/capabilities.js";
import { openDatabase } from "./db/database.js";
import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";
import { ErrorsRepo } from "./db/repos/errors.js";
@@ -50,8 +50,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, SESSION_COOKIE } from "./auth/middleware.js";
-import { IDENTITY_RESOURCE_ID } from "./terminal/identity.js";
+import { authMiddleware, jsonOnlyWrites } from "./auth/middleware.js";
import type { Identity } from "./terminal/identity.js";
import { terminalRoutes } from "./terminal/routes.js";
import type { TerminalManager } from "./terminal/manager.js";
@@ -216,17 +215,11 @@ export async function bootAppDeps(
// against it.
const hmr = new HmrHost(config.root);
- // Channel idle reclamation skips active Sessions (running/compacting can go a long time
- // without a publish, e.g. while waiting for approval). The manager lives platform-side
- // and is rebuilt by every swap: resolve the CURRENT one through the registry at sweep
- // time rather than capturing any one incarnation.
- const channels = new ChannelHub({
- isActive: (key) => {
- const manager = hmr.resources.claim<PlatformCurrent>(PLATFORM_CURRENT_RESOURCE_ID)?.deps
- ?.manager;
- return manager !== undefined && manager.statusOf(key) !== "idle";
- },
- });
+ // 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
+ // create (see hmr/platform.ts) — ordinary use of the claimed capability, re-installed
+ // by each generation. Until the first App boots, nothing is active.
+ const channels = new ChannelHub();
// Any password update for the built-in admin makes the persisted initial-password
// plaintext stale (either the password is no longer initial, or a reset replaced it
@@ -239,13 +232,11 @@ export async function bootAppDeps(
users: usersRepo,
authSessions: authSessionsRepo,
// Auth is runtime mechanism, but WHAT a fresh user is provisioned with is business
- // policy — late-bound through the registry so it always reaches the current App.
- provisionInitialProject: (user, isAdmin) => {
- const deps = hmr.resources.claim<PlatformCurrent>(PLATFORM_CURRENT_RESOURCE_ID)?.deps;
- if (deps == null) {
- throw new Error("no business platform is running to provision the initial Project");
- }
- return deps.projectService.provisionInitialProject(user, isAdmin);
+ // policy: the App installs the real provisioner via setProvisioner at every create
+ // (see hmr/platform.ts). This constructor fallback only answers before the first
+ // boot, which the startup order below makes unreachable in practice.
+ provisionInitialProject: () => {
+ throw new Error("no business platform is running to provision the initial Project");
},
seedAdminPassword: config.seedAdminPassword,
onPasswordChanged,
@@ -257,15 +248,6 @@ export async function bootAppDeps(
...(overrides.now ? { now: overrides.now } : {}),
});
- // The seam runs before the auth middleware, so a platform serving an API of its own has
- // no `c.var.user`. Authenticating is the runtime's job, not something a bundle should
- // re-implement against cookie names and session TTLs — so it is published as a
- // capability the booting platform claims (see terminal/identity.ts).
- hmr.resources.register(IDENTITY_RESOURCE_ID, async (request: Request) => {
- const token = readSessionCookie(request.headers.get("cookie"));
- const authed = token === null ? null : authService.authenticateWithMeta(token);
- return authed === null ? null : { userId: authed.user.userId };
- });
// 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.
@@ -281,13 +263,20 @@ export async function bootAppDeps(
hmr.resources.register(RUNTIME_DESKTOP_RESOURCE_ID, desktop);
// Boot the platform now rather than on the first request: the business surface —
- // services, routes, the scheduler — is assembled inside its create().
- await hmr.ensure();
- const deps = hmr.resources.claim<PlatformCurrent>(PLATFORM_CURRENT_RESOURCE_ID)?.deps;
- if (deps == null) {
+ // services, routes, the scheduler — is assembled inside its create(). The check reads
+ // the in-process api member, not a registry entry: the instance IS the current App.
+ const instance = await hmr.ensure();
+ const business = instance.api.business();
+ if (business === null) {
throw new Error("the packaged platform built no business surface");
}
- return deps;
+ // The App's own deps, read off the booted instance — the same bag every caller of this
+ // function always received. Callers that outlive swaps (index.ts, the runtime app) may
+ // only touch its swap-stable members: the runtime singletons published above, and the
+ // stateless repos over this process's own db handle. The business machinery on it
+ // (manager, services, scheduler) belongs to THIS generation and goes stale at the next
+ // push — per-request business dispatch rides the seam, never this reference.
+ return business;
}
/** Assembles the Hono app (does not listen on a port). */
@@ -513,18 +502,6 @@ function registerStaticRoutes(app: Hono<AppEnv>, resolveSource: () => Promise<We
});
}
-/** The session cookie out of a raw Cookie header (the seam hands over a plain Request). */
-function readSessionCookie(header: string | null): string | null {
- if (header === null) return null;
- for (const part of header.split(";")) {
- const eq = part.indexOf("=");
- if (eq === -1) continue;
- if (part.slice(0, eq).trim() !== SESSION_COOKIE) continue;
- return decodeURIComponent(part.slice(eq + 1).trim());
- }
- return null;
-}
-
// ---------------------------------------------------------------------------
// The business surface: everything below travels with the platform version.
// Called from hmr/platform.ts's create() at every App creation — see the module doc.
@@ -755,8 +732,10 @@ const RUNTIME_PREFIXES = ["/api/auth", "/api/desktop", "/api/hmr"];
* group and the business groups — registered together, so a swap replaces the whole route
* table as a unit (routes + auth + error shaping; no listening, no logging).
*
- * `deps` is null when the runtime published no business capabilities (an older runtime, a
- * bare kernel): the terminal group still serves, everything else declines.
+ * `deps` is null when the host published no business capabilities — a declared bare kernel:
+ * the terminal group still serves, everything else declines. A runtime merely too OLD to
+ * publish them never reaches here; the platform refuses to boot on one (hmr/platform.ts's
+ * create), because that runtime still answers the business API out of its own routes.
*/
export function createApp(
deps: AppDeps | null,
diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.ts
index 35ba50b3..435612c1 100644
--- a/packages/server/src/auth/service.ts
+++ b/packages/server/src/auth/service.ts
@@ -98,10 +98,20 @@ export interface AuthServiceDeps {
}
export class AuthService {
+ /**
+ * What a fresh user is provisioned with is business policy, answered by the CURRENT
+ * App: the platform installs its answer at create over the claimed auth capability
+ * (ordinary capability use, not a registry entry), and each swap's successor overwrites
+ * it. Starts as the constructor-supplied fallback so standalone/test constructions
+ * keep working unchanged.
+ */
+ private provisioner: (user: UserRow, isAdmin: boolean) => Promise<void>;
+
private readonly now: () => Date;
private readonly hashCost: number;
constructor(private readonly deps: AuthServiceDeps) {
+ this.provisioner = deps.provisionInitialProject;
this.now = deps.now ?? (() => new Date());
this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;
}
@@ -135,7 +145,7 @@ export class AuthService {
};
this.deps.users.insert(user);
try {
- await this.deps.provisionInitialProject(user, true);
+ await this.provisioner(user, true);
} catch (err) {
this.deps.users.delete(user.userId);
throw err;
@@ -143,6 +153,11 @@ export class AuthService {
return password;
}
+ /** Installs the current App's provisioning policy (see the `provisioner` field). */
+ setProvisioner(provision: (user: UserRow, isAdmin: boolean) => Promise<void>): void {
+ this.provisioner = provision;
+ }
+
/** Whether the built-in admin still runs on its initial password (drives the startup reminder notice). */
adminPasswordIsInitial(): boolean {
return this.deps.users.findById(ADMIN_USER_ID)?.passwordIsInitial === true;
diff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.ts
index a4ce2758..b60b7e87 100644
--- a/packages/server/src/hmr/capabilities.ts
+++ b/packages/server/src/hmr/capabilities.ts
@@ -13,13 +13,12 @@
* single-writer; the ServerConfig object — the listen callback writes the real port
* back into it and every reader must observe that write).
*
- * A platform booted by a runtime that publishes none of this (an older runtime, or a
- * bare kernel in tests) simply builds no business surface — the capability being absent
- * IS the signal, and terminals keep working regardless.
+ * 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.
*
- * The reverse direction is ONE entry: the pointer to the current App ({@link
- * PlatformCurrent}) — deps, route table and graceful wrap-up published together in a
- * single registry write.
+ * 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
+ * registry.
*/
import type { DatabaseSync } from "node:sqlite";
import type { Resources } from "@prismshadow/penguin-core/kernel";
@@ -27,9 +26,9 @@ import type { ServerConfig } from "../config.js";
import type { AuthService } from "../auth/service.js";
import type { ChannelHub } from "../runtime/channel.js";
import type { ProxySettings } from "../net/proxy.js";
+import type { BuildDepsOverrides } from "../app.js";
import type { HmrHost } from "../hmr/host.js";
import type { DesktopService } from "../services/desktop-service.js";
-import type { AppDeps } from "../app.js";
/**
* What one side of the seam speaks: a family, and a Go-style structural interface per
@@ -119,10 +118,15 @@ export const RUNTIME_INTERFACES: RuntimeInterfaces = {
"changePassword",
"loginDesktop",
"setPasswordDesktop",
+ "setProvisioner",
],
- channels: ["get", "peek", "broadcast", "dispose"],
+ channels: ["get", "peek", "broadcast", "dispose", "setActivityProbe"],
proxy: [],
- hmr: ["resources", "ensure", "resolveWebSource", "dispose"],
+ hmr: ["resources", "ensure", "resolveWebSource", "assetsDir", "dispose"],
+ // The construction-override seam (BuildDepsOverrides): production publishes {}, tests
+ // publish live collaborators (loader fakes, clocks). Presence-only — its fields are all
+ // optional, so there are no members to verify.
+ overrides: [],
desktop: ["onShutdownRequest", "requestShutdown", "verifyToken", "redeemLoginToken"],
};
@@ -186,8 +190,6 @@ export const RUNTIME_HMR_RESOURCE_ID = "runtime:hmr-host";
export const RUNTIME_DESKTOP_RESOURCE_ID = "runtime:desktop";
/** Test-only: BuildDepsOverrides published by bootAppDeps for the platform boot to claim. */
export const RUNTIME_OVERRIDES_RESOURCE_ID = "runtime:overrides";
-/** Reverse direction: THE pointer to the current App (see {@link PlatformCurrent}). */
-export const PLATFORM_CURRENT_RESOURCE_ID = "platform:current";
/**
* The {@link Interfaces} descriptor each App leaves for its successor, naming the
@@ -203,22 +205,16 @@ export const PLATFORM_CURRENT_RESOURCE_ID = "platform:current";
*/
export const RESOURCE_IFACES_RESOURCE_ID = "resource-interfaces";
-/**
- * The one object a swap publishes — deps, route table and wrap-up together, so flipping
- * to a new App is a single registry write and no reader can ever see a half-swapped pair
- * (new deps with the old routes, or the reverse). Everything runtime-side that needs the
- * current App resolves this pointer at use time: the seam middleware dispatches into
- * `app`, auth late-binds provisioning through `deps`, index.ts's shutdown awaits
- * `shutdown`.
+/*
+ * There is deliberately NO reverse-direction registry entry. The runtime already holds
+ * the current App — it is `hmr.ensure()`'s instance — and everything it needs from the
+ * business side is an in-process member on that instance's api (`business()`,
+ * `shutdown()`, `drained()`) or a hook the App installs over a claimed capability
+ * (ChannelHub.setActivityProbe, AuthService.setProvisioner). A "current App" pointer in
+ * the registry was a duplicate of the host's own instance field, and the registry should
+ * carry only what has no other channel: resources, capabilities, and the contract
+ * declarations about them.
*/
-export interface PlatformCurrent {
- /** The business deps this App built, or null when the runtime published no capabilities. */
- deps: AppDeps | null;
- /** The App's whole Hono route table (terminal + business), fetch-shaped for cross-bundle safety. */
- app: { fetch(request: Request): Response | Promise<Response> };
- /** Process-exit graceful drain (manager ≤5s wrap-up); absent when no business runs. */
- shutdown?: () => Promise<void>;
-}
/** Applies proxy settings to the RUNTIME's global dispatcher (see net/proxy.ts). */
export type ProxyControl = (settings: ProxySettings) => void;
@@ -233,34 +229,61 @@ export interface RuntimeCapabilities {
hmr: HmrHost;
/** Null on a non-desktop server (a real value, not an absent capability). */
desktop: DesktopService | null;
+ /** The construction-override seam; {} outside tests. */
+ overrides: BuildDepsOverrides;
}
/**
- * Claims the full capability set, or null when any piece is missing — a partial claim
- * would build a business surface over half a runtime, which is worse than the honest
- * "this runtime publishes no business capabilities" degradation.
+ * The outcome of asking the host what it is, decided entirely by what it published:
+ *
+ * - `claimed` — a descriptor of this family offering the full capability set, with every
+ * live object carrying the members the descriptor names.
+ * - `bare` — a descriptor of this family offering NONE of the capabilities: the host's
+ * own declaration that there is no business runtime behind it (a bare kernel in
+ * tests). Terminals-only is legal there. The declaration rides the descriptor the
+ * handshake already reads — a host that offers nothing SAYS so, in the same document
+ * every host describes itself in, rather than through a side-channel marker.
+ * - `refused` — everything else, with the reason: no descriptor (a runtime too old for
+ * the handshake), a different family, a partial offer, or a live object that does not
+ * 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 function claimRuntimeCapabilities(resources: Resources): RuntimeCapabilities | null {
- // The handshake first: a runtime speaking different interfaces (or one too old to
- // publish a descriptor at all) must not be claimed against — the members behind the IDs
- // are exactly what the descriptor stands for.
- const mismatch = interfaceMismatch(
- resources.claim<Interfaces>(RUNTIME_INTERFACES_RESOURCE_ID),
- RUNTIME_INTERFACES,
- );
- if (mismatch !== null) {
- console.warn(`[platform] runtime interfaces: ${mismatch}; declining the claim`);
- return null;
+export type RuntimeClaim =
+ | { kind: "claimed"; caps: RuntimeCapabilities }
+ | { kind: "bare" }
+ | { kind: "refused"; reason: string };
+
+export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {
+ const offered = resources.claim<Interfaces>(RUNTIME_INTERFACES_RESOURCE_ID);
+ if (offered === undefined) {
+ return { kind: "refused", reason: "no interface descriptor published" };
}
+ if (offered.family !== RUNTIME_INTERFACES.family) {
+ return {
+ kind: "refused",
+ reason: `family '${String(offered.family)}' != '${String(RUNTIME_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");
+ if (required.every((name) => members(offered, name) === undefined)) {
+ return { kind: "bare" };
+ }
+ const mismatch = interfaceMismatch(offered, RUNTIME_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 authService = resources.claim<AuthService>(RUNTIME_AUTH_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);
- if (!config || !db || !authService || !channels || !proxyControl || !hmr) return null;
+ if (!config || !db || !authService || !channels || !proxyControl || !hmr) {
+ 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 overrides = resources.claim<BuildDepsOverrides>(RUNTIME_OVERRIDES_RESOURCE_ID) ?? {};
// …then the objects themselves. A descriptor is a claim about what is there; this is
// the part that checks it, so an honest-but-wrong runtime is caught here rather than at
// the first call site. `desktop` is exempt when null — that is a value, not a shortfall.
@@ -278,9 +301,11 @@ export function claimRuntimeCapabilities(resources: Resources): RuntimeCapabilit
if (!Array.isArray(need)) continue;
const lacking = lacksMembers(value, need);
if (lacking.length > 0) {
- console.warn(`[platform] runtime ${name} lacks ${lacking.join(", ")}; declining the claim`);
- return null;
+ return { kind: "refused", reason: `runtime ${name} lacks ${lacking.join(", ")}` };
}
}
- return { config, db, authService, channels, proxyControl, hmr, desktop };
+ return {
+ kind: "claimed",
+ caps: { config, db, authService, channels, proxyControl, hmr, desktop, overrides },
+ };
}
diff --git a/packages/server/src/hmr/host.ts b/packages/server/src/hmr/host.ts
index d0126c69..d0fd4056 100644
--- a/packages/server/src/hmr/host.ts
+++ b/packages/server/src/hmr/host.ts
@@ -126,14 +126,6 @@ export interface UpgradeAllTarget {
source?: GitSource;
}
-/**
- * Where the runtime publishes the unpacked assets directory for the booting platform.
- * The resource registry is the only runtime→platform channel the kernel offers (ctx
- * carries `resources`, nothing else), and it is kind-agnostic by design — see
- * ./resources.ts.
- */
-export const ASSETS_RESOURCE_ID = "runtime:assets-dir";
-
/**
* 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
@@ -168,6 +160,8 @@ export class HmrHost {
private instance: Instance<PlatformApi> | null = null;
private implId = packagedPlatform.id;
+ /** Current version's materialized native assets dir (see assetsDir()). */
+ private assets: string | null = null;
private readonly hmrDir: string;
private readonly storeDir: string;
private readonly manifestPath: string;
@@ -343,7 +337,7 @@ export class HmrHost {
// Assets land BEFORE the boot: the platform's create() may load a native module out of
// them. A failed boot puts the pointer back, so the surviving old platform keeps
// claiming the assets it booted with.
- const previousAssets = this.resources.claim<string>(ASSETS_RESOURCE_ID) ?? null;
+ const previousAssets = this.assets;
const assetsDir = target.assets ? await this.materializeAssets(target.assets) : null;
if (assetsDir !== null) this.publishAssets(assetsDir);
@@ -370,6 +364,21 @@ export class HmrHost {
invalid: result.invalid,
};
}
+ if (result.status === "failed") {
+ // The pushed platform's boot threw AFTER the old tree was disposed
+ // (validate-then-swap disposes first so the new tree can adopt what the old one
+ // delivered). Without recovery the process is half-dead: `this.instance` still
+ // answers HTTP out of closures, but its manager is closed and the current-App
+ // pointer is released — until a restart. So re-boot the PREVIOUS platform from the
+ // parked document the kernel handed back. The park-by-inventory contract is what
+ // makes this an ordinary load: the old App's dispose suspended and detached
+ // everything, so the recovered App adopts the delivered resources and restarts the
+ // suspended machinery like any successor. The pusher still gets an error — the
+ // push DID fail — but the machine it failed on keeps working.
+ this.publishAssets(previousAssets);
+ await this.recoverPrevious(result.doc);
+ throw new Error(`the pushed platform failed to boot: ${errMsg(result.error)}`);
+ }
// Boot succeeded: commit web to memory too, then persist platform + cli + web
// as one atomic version — never a platform that's newer (or older) than the
@@ -399,6 +408,38 @@ export class HmrHost {
};
}
+ /**
+ * Boot-failure recovery: re-boot the version that was running before the failed
+ * upgrade, from its own parked document. The committed manifest still names that
+ * version (a failed push persists nothing), so the bundle comes from there — or it is
+ * the packaged default when nothing was ever pushed. Best-effort by design: a double
+ * fault only warns and leaves the disposed instance in place, because /api/hmr is
+ * runtime-owned and therefore still reachable for a follow-up push, and a process
+ * restart restores the committed version regardless.
+ */
+ private async recoverPrevious(doc: Json): Promise<void> {
+ try {
+ let bundle: PlatformBundle = packagedPlatform;
+ if (this.implId !== packagedPlatform.id) {
+ const manifest = JSON.parse(await fsp.readFile(this.manifestPath, "utf8")) as Manifest;
+ if (manifest.platform === undefined) throw new Error("harness.json has no `platform`");
+ bundle = await this.importBundleFile(path.join(this.hmrDir, manifest.platform.bundle));
+ }
+ this.instance = (await boot(
+ bundle.impl,
+ bundle.iface,
+ doc,
+ this.resources,
+ )) as Instance<PlatformApi>;
+ // implId unchanged: the previous version is the running version again.
+ } catch (err) {
+ this.warn(
+ `boot-failure recovery failed too — the process serves a half-stopped App until ` +
+ `a successful push or a restart: ${errMsg(err)}`,
+ );
+ }
+ }
+
/** Layer (a) core: import one JS file, cache-busted so re-imports load fresh code. */
private async importBundleFile(file: string): Promise<PlatformBundle> {
const resolved = path.resolve(file);
@@ -505,8 +546,17 @@ export class HmrHost {
/** Points the registry at this version's assets (or clears it when a push has none). */
private publishAssets(dir: string | null): void {
- if (dir === null) this.resources.release(ASSETS_RESOURCE_ID);
- else this.resources.register(ASSETS_RESOURCE_ID, dir);
+ this.assets = dir;
+ }
+
+ /**
+ * 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
+ * the bundle's pty loader — not a registry key: the host is already the claimed
+ * object, so its per-push state belongs on it.
+ */
+ assetsDir(): string | null {
+ return this.assets;
}
private async persistVersion(
diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.ts
index f618d0f5..d360bc3e 100644
--- a/packages/server/src/hmr/platform.ts
+++ b/packages/server/src/hmr/platform.ts
@@ -34,12 +34,10 @@ import { buildAppDeps, createApp, type AppDeps, type BuildDepsOverrides } from "
import { seamHttp } from "./hono-seam.js";
import {
PENGUIN_FAMILY,
- PLATFORM_CURRENT_RESOURCE_ID,
RESOURCE_IFACES_RESOURCE_ID,
- RUNTIME_OVERRIDES_RESOURCE_ID,
claimRuntimeCapabilities,
} from "./capabilities.js";
-import type { Interfaces, MembersOf, PlatformCurrent } from "./capabilities.js";
+import type { Interfaces, MembersOf } from "./capabilities.js";
export interface PlatformApi extends Park {
info(): Json;
@@ -56,6 +54,20 @@ export interface PlatformApi extends Park {
*/
terminals(): TerminalManager;
attachStream(ws: WebSocket, session: TerminalSession, url: URL, log: (l: string) => void): void;
+ /**
+ * The business deps this App built (null on a declared bare kernel). In-process member,
+ * NOT a registry entry: the runtime holds this instance already (hmr.ensure()), so a
+ * "current App" pointer in the registry would be a duplicate channel.
+ */
+ business(): AppDeps | null;
+ /** Process-exit graceful drain (manager ≤5s wrap-up, workflow park); no-op without business. */
+ shutdown(): Promise<void>;
+ /**
+ * The asynchronous tail of this App's dispose — set by the dispose effect, awaited by
+ * the KERNEL between dispose and the successor's boot (see core kernel/upgrade.ts), so
+ * a new App never races the old one's aborted work. Undefined until disposed.
+ */
+ drained(): Promise<void> | undefined;
}
/**
@@ -84,7 +96,6 @@ export const PlatformIface = defineIface<PlatformApi, PlatformCtx>({
interface ParkedInterfaces extends Interfaces {
family: string;
terminal: MembersOf<TerminalSession>;
- platform: MembersOf<PlatformCurrent>;
}
export const DECLARED_RESOURCES: ParkedInterfaces = {
@@ -113,12 +124,32 @@ export const DECLARED_RESOURCES: ParkedInterfaces = {
"kill",
"dispose",
],
- // The current-App pointer (see PlatformCurrent).
- platform: ["deps", "app"],
};
+/**
+ * How long a swap or a process exit waits for aborted work to actually end (the kernel
+ * awaits api.drained() between dispose and the successor's boot). A cap, not a sleep: the
+ * drain resolves the moment the last aborted run settles.
+ */
+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).
+ // 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);
+ if (claim.kind === "refused") {
+ throw new Error(
+ `this runtime publishes no business capabilities this platform can claim ` +
+ `(${claim.reason}) — update the installation itself; a push replaces the ` +
+ `platform, never the runtime`,
+ );
+ }
+ const caps = claim.kind === "claimed" ? claim.caps : null;
// Resource-interface reconciliation, BEFORE anything is adopted: integrate the groups
// the predecessor declared at the version this build also declares, hard-stop the
// rest — a version bump or a dropped group means this create() does not speak the
@@ -140,23 +171,26 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
// declaration, whatever generation it is.
ctx.resources.register(RESOURCE_IFACES_RESOURCE_ID, DECLARED_RESOURCES);
- const terminals = new TerminalManager(ctx.resources);
+ const terminals = new TerminalManager(ctx.resources, {
+ // A pushed bundle's node-pty binaries live where the host materialized them.
+ assets: () => caps?.hmr.assetsDir() ?? null,
+ });
// Shells started before this instance existed are still running in the registry: claim
// them back so a push is invisible to whoever was typing in one.
terminals.adopt(context.terminals ?? []);
- const identity = identityFrom(ctx.resources);
+ // Ordinary code over the claimed capability (see terminal/identity.ts): the resolver
+ // wraps caps.authService, the same object the business routes authenticate with. A
+ // bare kernel has no auth — terminals stay fail-closed there.
+ const identity = identityFrom(caps?.authService ?? null);
// The business deps, built per App over the runtime's published capabilities — see
- // app.ts's buildAppDeps and ./capabilities.ts. A runtime that publishes nothing
- // (an older runtime, a bare kernel) gets a terminals-only platform rather than a
- // failed boot.
+ // app.ts's buildAppDeps and ./capabilities.ts. Null only for a declared bare kernel;
+ // every other capability-less host was refused above.
let deps: AppDeps | null = null;
- const caps = claimRuntimeCapabilities(ctx.resources);
if (caps === null) {
- console.warn("[platform] runtime publishes no business capabilities; terminals only");
+ console.warn("[platform] bare kernel: terminals only, no business surface");
} else {
- const overrides = ctx.resources.claim<BuildDepsOverrides>(RUNTIME_OVERRIDES_RESOURCE_ID);
- deps = buildAppDeps(caps, overrides ?? {});
+ deps = buildAppDeps(caps, caps.overrides);
// Schedule scheduler: startup reconciliation (missed, don't backfill) + periodic
// scan; only active while this App is.
await deps.scheduler.start();
@@ -173,23 +207,57 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
// wrap-up as a single registry write, so no reader can observe a half-swapped pair.
const app = createApp(deps, terminals, identity);
const business = deps;
- const current: PlatformCurrent = {
- deps,
- app,
- // Process exit wants the manager's graceful ≤5s drain, which a synchronous dispose
- // effect cannot await — carried on the pointer for index.ts's shutdown to call.
- ...(business === null ? {} : { shutdown: () => business.manager.shutdown(5000) }),
- };
- ctx.resources.register(PLATFORM_CURRENT_RESOURCE_ID, current);
+ // The runtime's two mid-request needs of the CURRENT App are hooks installed over the
+ // claimed capabilities — ordinary capability use, overwrite-only across swaps (a dead
+ // generation's hook is replaced, never removed, so nothing ever un-installs a
+ // successor's): "is this session busy" for channel sweep, and "what does a fresh user
+ // get" for login provisioning.
+ if (caps !== null && business !== null) {
+ caps.channels.setActivityProbe((key) => business.manager.statusOf(key) !== "idle");
+ caps.authService.setProvisioner((user, isAdmin) =>
+ business.projectService.provisionInitialProject(user, isAdmin),
+ );
+ }
+ // PARK — the App's complete resource inventory, split by fate. Everything stateful
+ // this App creates is on one of these three lists; a new resource must pick its list
+ // when it is added, or the swap leaks it.
+ //
+ // DELIVERED (survives the swap; the successor adopts it at load):
+ // - pty sessions registry `terminal:*` + parked handle ids → terminals.adopt
+ // - runtime singletons db / auth / channels / config / proxy / desktop —
+ // runtime-owned, re-claimed by every App; not this App's to park
+ // SUSPENDED (stopped here; the successor rebuilds it fresh at load):
+ // - scheduler stop() now; successor start() reconciles missed fires
+ // - agent runs approvals → deny, drives → abort; goal rows reconciled by
+ // the successor's abortOrphanedActive
+ // - session environments dispose() after the drive settles — kills background
+ // commands (dev servers etc.) that would otherwise run on
+ // orphaned and invisible to the successor's fresh Session
+ // - reap timers TerminalManager.quiesce runs them now (dead ptys only)
+ // DETACHED (the object survives, this App's grip on it does not):
+ // - pty exit listeners unsubscribed, so a dead generation never releases a
+ // registry id the successor owns
+ // Known exceptions, accepted with reasons: an in-flight self-update child (rare,
+ // bounded by its own 10-minute cap, and a successful update restarts the process
+ // anyway) and SSE subscriber closures (they serve the old generation's stream until
+ // the client reloads on web_updated — the channel hub itself is runtime-owned).
+ // A build that adds a service with state of its own (sandbox settings, workflow
+ // refs, ssh tunnels, an in-flight job) adds it to the right list here — the list is
+ // the contract, not a description of today's services.
+ //
+ // The synchronous part runs here; the ASYNC part (waiting for aborted runs to
+ // actually end) cannot — dispose is sync — so it is exposed as api.drained(), which
+ // the KERNEL awaits between dispose and the successor's boot (kernel/upgrade.ts).
+ // Nothing about the handover touches the registry.
+ let drained: Promise<void> | undefined;
ctx.effect(() => {
- // Swap semantics for unparked state: HARD STOP. Pending approvals converge to
- // deny, active runs abort, the scheduler's timer dies with this App; the next
- // App rebuilds all of it. Only parked resources (terminals) ride across.
+ terminals.quiesce();
+ const drains: Promise<unknown>[] = [];
if (business !== null) {
business.scheduler.stop();
- void business.manager.shutdown(0);
+ drains.push(business.manager.shutdown(DRAIN_GRACE_MS));
}
- ctx.resources.release(PLATFORM_CURRENT_RESOURCE_ID);
+ drained = Promise.allSettled(drains).then(() => undefined);
});
const http = seamHttp(app);
@@ -208,6 +276,13 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
http,
terminals: () => terminals,
attachStream: (ws, session, url, log) => bindTerminalStream(ws, session, url, log),
+ business: () => business,
+ // Process exit wants the manager's graceful ≤5s drain, which a synchronous dispose
+ // effect cannot await — exposed for index.ts's shutdown to call before disposing.
+ shutdown: async () => {
+ if (business !== null) await business.manager.shutdown(DRAIN_GRACE_MS);
+ },
+ drained: () => drained,
};
},
};
diff --git a/packages/server/src/hmr/resources.ts b/packages/server/src/hmr/resources.ts
index 57a26461..f432ae44 100644
--- a/packages/server/src/hmr/resources.ts
+++ b/packages/server/src/hmr/resources.ts
@@ -17,23 +17,31 @@ import type { Resources } from "@prismshadow/penguin-core/kernel";
export class HotResources implements Resources {
private readonly map = new Map<string, { resource: unknown; dispose?: () => void }>();
- register(id: string, resource: unknown, dispose?: () => void): void {
+ register(id: string, resource: unknown, dispose?: () => void): () => void {
+ const entry = { resource, dispose };
// Delete before set: Map.set on an existing key KEEPS its original insertion
// position, so a re-registration (a successor adopting a pty, say) would still be
- // disposed in the old owner's slot — and both sweeps below claim to run in reverse
- // REGISTRATION order, which later entries depending on earlier ones rely on.
+ // swept in the old owner's slot — and both sweeps below promise reverse REGISTRATION
+ // order, which later entries depending on earlier ones rely on.
this.map.delete(id);
- this.map.set(id, { resource, dispose });
+ this.map.set(id, entry);
+ // The paired unregister: identity-checked, so it only ever acts on THIS registration.
+ // Out of the registry means SHUT DOWN — the map is the list of live resources, and an
+ // entry that left it silently would also leave the process-exit sweep's reach. The
+ // one way a resource outlives its registration is takeover: an overwrite by a
+ // successor retires this handle into a no-op, and shutdown responsibility moves to
+ // the new registration with it.
+ return () => {
+ if (this.map.get(id) !== entry) return;
+ this.map.delete(id);
+ entry.dispose?.();
+ };
}
claim<T = unknown>(id: string): T | undefined {
return this.map.get(id)?.resource as T | undefined;
}
- release(id: string): void {
- this.map.delete(id);
- }
-
/**
* The reconciliation hook a booting App calls (never the kernel — see the interface in
* core's boot.ts): disposes and removes every entry of one ID-prefix group (`terminal`
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 61240b03..e8d54aaf 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -29,8 +29,6 @@ import {
} from "./initial-password.js";
import { applyProxySettings, installGlobalProxyDispatcher } from "./net/proxy.js";
import { attachTerminalWebSocket } from "./terminal/ws.js";
-import { PLATFORM_CURRENT_RESOURCE_ID } from "./hmr/capabilities.js";
-import type { PlatformCurrent } from "./hmr/capabilities.js";
import { loopbackHostRoles } from "./services/preview-token.js";
import { acquireServerLock, liveServerLock, releaseServerLock } from "./lock.js";
import { shellPortOf, wireShellUpdatePort } from "./services/desktop-update-port.js";
@@ -312,10 +310,9 @@ class PenguinServer {
this.shuttingDown = true;
console.log(`Received ${signal}, shutting down…`);
// The CURRENT App's graceful drain (manager: interrupt runs, deny approvals, wait ≤5s
- // for wrap-up) — claimed through the registry rather than deps, which after a hot swap
- // would point at an already-disposed business incarnation.
- const current = this.deps.hmr.resources.claim<PlatformCurrent>(PLATFORM_CURRENT_RESOURCE_ID);
- if (current?.shutdown !== undefined) await current.shutdown();
+ // for wrap-up) — through the instance the host holds, which a hot swap keeps current;
+ // no registry pointer needed.
+ await (await this.deps.hmr.ensure()).api.shutdown();
// Disposing the host drains the App's effects (scheduler stop, manager hard-stop) and
// sweeps the resource registry (live ptys).
this.deps.hmr.dispose();
diff --git a/packages/server/src/runtime/channel.ts b/packages/server/src/runtime/channel.ts
index 39568f3a..9c2b48b1 100644
--- a/packages/server/src/runtime/channel.ts
+++ b/packages/server/src/runtime/channel.ts
@@ -170,7 +170,7 @@ export class ChannelHub {
private readonly channels = new Map<string, Channel>();
private readonly timer: NodeJS.Timeout;
private readonly idleMs: number;
- private readonly isActive: (key: string) => boolean;
+ private isActive: (key: string) => boolean;
constructor(opts: ChannelHubOptions = {}) {
this.idleMs = opts.idleMs ?? DEFAULT_IDLE_MS;
@@ -179,6 +179,18 @@ export class ChannelHub {
this.timer.unref?.();
}
+ /**
+ * Replaces the activity probe. "Is this session busy" is a business question the hub
+ * (runtime mechanism) cannot answer itself; the App installs its answer at create over
+ * the claimed hub — ordinary capability use, not a registry entry. Overwrite-only, the
+ * cross-generation discipline: a successor installs its own probe and a dead
+ * generation's is simply left behind (its manager has drained, so it reports idle —
+ * never wrong, only replaced).
+ */
+ setActivityProbe(probe: (key: string) => boolean): void {
+ this.isActive = probe;
+ }
+
get(key: string): Channel {
let ch = this.channels.get(key);
if (!ch) {
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index 34c9e88b..f841dd7f 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -1293,11 +1293,20 @@ export class SessionManager {
clearInterval(this.sweepTimer);
const pending: Promise<void>[] = [];
for (const entry of this.entries.values()) {
- if (!entry.abort) continue;
entry.approvals.denyAll();
- entry.abort.abort();
+ entry.abort?.abort();
if (entry.running) pending.push(entry.running);
+ // Suspend means the environment too: dispose kills the Session's remaining
+ // background processes (a dev server the conversation started, etc.). Without
+ // this, a hot swap orphans them — the OS process keeps running while the next
+ // App's freshly resumed Session starts with an empty process list, so the stop
+ // control has gone blind. Sequenced after the in-flight drive settles, the same
+ // ordering disposeRemoved uses.
+ const dispose = (): void => entry.session.dispose?.();
+ if (entry.running) void entry.running.then(dispose, dispose);
+ else dispose();
}
+ this.entries.clear();
if (pending.length === 0) return;
await Promise.race([
Promise.allSettled(pending).then(() => undefined),
diff --git a/packages/server/src/terminal/identity.ts b/packages/server/src/terminal/identity.ts
index 003a4f92..041d459d 100644
--- a/packages/server/src/terminal/identity.ts
+++ b/packages/server/src/terminal/identity.ts
@@ -2,17 +2,15 @@
* Who a seam request belongs to.
*
* The platform is offered every request BEFORE the runtime's auth middleware runs — that
- * ordering is deliberate (a push must be able to decide its own authentication), but it
- * means `c.var.user` does not exist here. Rather than re-implement session lookup in
- * pushed code, the runtime publishes this capability through the resource registry:
- * authenticating is the runtime layer's own job ("boots, transports, authenticates"), and
- * a copy of it inside a bundle would be a second implementation to keep in step with
- * cookie names, session TTLs and renewal.
+ * ordering is deliberate (a push must be able to decide its own authentication), so
+ * `c.var.user` does not exist here. The resolver is ORDINARY CODE over the claimed auth
+ * capability, not a registry entry: the App already authenticates every business request
+ * with the same cookie name and the same claimed AuthService (auth/middleware.ts rides in
+ * the bundle), so a second, registry-published copy of "cookie → user" was a duplicate
+ * channel pretending to be a resource. The registry carries resources and capabilities;
+ * a function derivable from an already-claimed capability is neither.
*/
-import type { Resources } from "@prismshadow/penguin-core/kernel";
-
-/** Registry key the runtime publishes its resolver under. */
-export const IDENTITY_RESOURCE_ID = "runtime:identity";
+import { SESSION_COOKIE } from "../auth/middleware.js";
export interface IdentifiedUser {
userId: string;
@@ -20,12 +18,33 @@ export interface IdentifiedUser {
export type Identity = (request: Request) => Promise<IdentifiedUser | null>;
+/** What the resolver needs of the claimed AuthService — the member the handshake verifies. */
+export interface AuthenticatesSessions {
+ authenticateWithMeta(token: string): { user: { userId: string } } | null;
+}
+
+/** The session cookie out of a raw Cookie header (the seam hands over a plain Request). */
+export function readSessionCookie(header: string | null): string | null {
+ if (header === null) return null;
+ for (const part of header.split(";")) {
+ const eq = part.indexOf("=");
+ if (eq === -1) continue;
+ if (part.slice(0, eq).trim() !== SESSION_COOKIE) continue;
+ return decodeURIComponent(part.slice(eq + 1).trim());
+ }
+ return null;
+}
+
/**
- * The published resolver, or one that authenticates nobody. A runtime too old to publish
- * it must not silently hand out terminals — an unattributable request is not a request
- * from everyone.
+ * Builds the resolver from the claimed auth capability. Null (a bare kernel, which has no
+ * auth to claim) authenticates nobody: an unattributable request is not a request from
+ * everyone, so terminals stay fail-closed.
*/
-export function identityFrom(resources: Resources): Identity {
- const resolver = resources.claim<Identity>(IDENTITY_RESOURCE_ID);
- return resolver ?? (async () => null);
+export function identityFrom(auth: AuthenticatesSessions | null): Identity {
+ if (auth === null) return async () => null;
+ return async (request) => {
+ const token = readSessionCookie(request.headers.get("cookie"));
+ const authed = token === null ? null : auth.authenticateWithMeta(token);
+ return authed === null ? null : { userId: authed.user.userId };
+ };
}
diff --git a/packages/server/src/terminal/manager.ts b/packages/server/src/terminal/manager.ts
index 68fa0557..7fd09b19 100644
--- a/packages/server/src/terminal/manager.ts
+++ b/packages/server/src/terminal/manager.ts
@@ -45,11 +45,23 @@ export class TerminalManager {
*/
constructor(
private readonly resources: Resources,
- private readonly graceMs: number = EXITED_SESSION_GRACE_MS,
+ private readonly opts: {
+ graceMs?: number;
+ /** Where a pushed bundle's node-pty assets live (hmr.assetsDir); absent falls back to the packaged require. */
+ assets?: () => string | null;
+ } = {},
) {}
+ private get graceMs(): number {
+ return this.opts.graceMs ?? EXITED_SESSION_GRACE_MS;
+ }
+
private readonly sessions = new Map<string, TerminalSession>();
private readonly reapTimers = new Map<string, ReturnType<typeof setTimeout>>();
+ /** Exit-listener unsubscribers, so quiesce() can detach this manager from delivered ptys. */
+ private readonly exitUnsubs = new Set<() => void>();
+ /** Paired unregister per pty (register's return): the only way an entry leaves the registry. */
+ private readonly unregisters = new Map<string, () => void>();
async create(request: CreateTerminalRequest): Promise<TerminalSession> {
const cwd = await resolveCwd(request.cwd);
@@ -85,7 +97,7 @@ export class TerminalManager {
ownerUserId: request.ownerUserId,
seq,
name,
- resources: this.resources,
+ ...(this.opts.assets !== undefined ? { assets: this.opts.assets } : {}),
...(request.cols !== undefined ? { cols: request.cols } : {}),
...(request.rows !== undefined ? { rows: request.rows } : {}),
...(request.shell !== undefined ? { shell: request.shell } : {}),
@@ -118,8 +130,11 @@ export class TerminalManager {
*/
private track(session: TerminalSession): void {
this.sessions.set(session.id, session);
- session.onExit(() => this.scheduleReap(session.id));
- this.resources.register(resourceId(session.id), session, () => session.dispose());
+ this.exitUnsubs.add(session.onExit(() => this.scheduleReap(session.id)));
+ this.unregisters.set(
+ session.id,
+ this.resources.register(resourceId(session.id), session, () => session.dispose()),
+ );
}
/**
@@ -132,8 +147,40 @@ export class TerminalManager {
const session = this.resources.claim<TerminalSession>(resourceId(id));
if (session === undefined) continue;
this.sessions.set(session.id, session);
- session.onExit(() => this.scheduleReap(session.id));
+ this.exitUnsubs.add(session.onExit(() => this.scheduleReap(session.id)));
+ // Re-register under THIS generation: the overwrite retires the previous owner's
+ // paired unregister (it no-ops from now on), and ours becomes the live one — the
+ // registry's ownership rule, applied to adoption.
+ this.unregisters.set(
+ session.id,
+ this.resources.register(resourceId(session.id), session, () => session.dispose()),
+ );
+ // Died during the swap freeze: its exit fired into the PREVIOUS generation (whose
+ // listeners are detached by then), so this listener will never fire — reap it here
+ // or nobody ever releases its registry entry.
+ if (!session.alive) this.scheduleReap(session.id);
+ }
+ }
+
+ /**
+ * Park-side detach (hot swap only — never process exit): the ptys are DELIVERED to the
+ * next App through the registry, so this manager must stop acting on them. Exit
+ * listeners are unsubscribed (the successor adopts and re-listens), and every pending
+ * reap — each targeting an already-dead session that was therefore NOT parked for
+ * adoption — runs immediately instead of firing later from a dead generation, where it
+ * would release a registry id out from under whoever owns it next.
+ */
+ quiesce(): void {
+ for (const unsub of this.exitUnsubs) unsub();
+ this.exitUnsubs.clear();
+ for (const [id, timer] of this.reapTimers) {
+ clearTimeout(timer);
+ this.sessions.delete(id);
+ // Unregister disposes as it removes — one call, paired and identity-safe.
+ this.unregisters.get(id)?.();
+ this.unregisters.delete(id);
}
+ this.reapTimers.clear();
}
/** Handle ids for the parked context document — live sessions only. */
@@ -176,10 +223,12 @@ export class TerminalManager {
if (existing) clearTimeout(existing);
const timer = setTimeout(() => {
this.reapTimers.delete(id);
- this.sessions.get(id)?.dispose();
this.sessions.delete(id);
- // Out of the registry too: a disposed pty must not be claimable by the next boot.
- this.resources.release(resourceId(id));
+ // The paired unregister both removes the entry and disposes the session ("out of
+ // the registry means shut down"), and only ever acts on our own registration — a
+ // reap can never touch an entry a successor re-registered.
+ this.unregisters.get(id)?.();
+ this.unregisters.delete(id);
}, delayMs);
timer.unref?.();
this.reapTimers.set(id, timer);
diff --git a/packages/server/src/terminal/pty-module.ts b/packages/server/src/terminal/pty-module.ts
index 46bbcf75..ef005728 100644
--- a/packages/server/src/terminal/pty-module.ts
+++ b/packages/server/src/terminal/pty-module.ts
@@ -15,8 +15,6 @@
*/
import { createRequire } from "node:module";
import path from "node:path";
-import type { Resources } from "@prismshadow/penguin-core/kernel";
-import { ASSETS_RESOURCE_ID } from "../hmr/host.js";
/** The slice of node-pty this package uses (kept narrow so the fallback stays checkable). */
export interface NodePty {
@@ -39,16 +37,17 @@ let cached: NodePty | null = null;
* Resolves node-pty once per platform instance. `resources` comes from the kernel's node
* context; a runtime that published no assets simply leaves the fallback unused.
*/
-export function loadNodePty(resources: Resources): NodePty {
+export function loadNodePty(assets?: () => string | null): NodePty {
if (cached !== null) return cached;
const attempts: Array<() => NodePty> = [
// Packaged server: this module is part of the runtime's own graph.
() => createRequire(import.meta.url)("node-pty") as NodePty,
- // Pushed bundle: the binary rides along as an asset, laid out as a real package dir.
+ // Pushed bundle: the binary rides along as an asset, laid out as a real package dir —
+ // located through the hmr capability's declared assetsDir(), not a registry key.
() => {
- const dir = resources.claim<string>(ASSETS_RESOURCE_ID);
- if (dir === undefined) throw new Error("no assets directory published");
+ const dir = assets?.() ?? null;
+ if (dir === null) throw new Error("no assets directory available");
// A require anchored inside the assets dir resolves `node_modules/node-pty` there,
// which lets node-pty's own relative loader find its binary as it normally would.
return createRequire(path.join(dir, "index.mjs"))("node-pty") as NodePty;
diff --git a/packages/server/src/terminal/routes.ts b/packages/server/src/terminal/routes.ts
index 28639cdb..d996e041 100644
--- a/packages/server/src/terminal/routes.ts
+++ b/packages/server/src/terminal/routes.ts
@@ -8,10 +8,10 @@
* attached per-route, not as a prefix middleware, so a request nothing here serves
* declines BEFORE authentication, same as a request outside the prefix.
*
- * Identity is resolved through a runtime capability, not re-implemented here: the seam
- * runs BEFORE the auth middleware (app.ts mounts it there on purpose, so a push can
- * decide its own authentication), and "who is this request from" is exactly what the
- * runtime layer owns — it boots, transports and authenticates. Body limits and the
+ * Identity is built over the claimed auth capability (terminal/identity.ts), not
+ * re-implemented here: the seam runs BEFORE the auth middleware (app.ts mounts it there
+ * on purpose, so a push can decide its own authentication), and the resolver wraps the
+ * same AuthService the business routes authenticate with. Body limits and the
* JSON-only rule for writes DO apply already: both middlewares sit above the seam.
*
* Split the way this server is built: JSON over HTTP for control, and a separate binary
diff --git a/packages/server/src/terminal/session.ts b/packages/server/src/terminal/session.ts
index 52299045..937c4e37 100644
--- a/packages/server/src/terminal/session.ts
+++ b/packages/server/src/terminal/session.ts
@@ -18,7 +18,6 @@ import path from "node:path";
import { randomUUID } from "node:crypto";
import xterm, { type Terminal } from "@xterm/headless";
import type { IPty } from "node-pty";
-import type { Resources } from "@prismshadow/penguin-core/kernel";
import { loadNodePty } from "./pty-module.js";
import { defaultTerminalShell, shellArgs } from "./shell.js";
import { TerminalInputModeTracker } from "./input-mode.js";
@@ -78,10 +77,10 @@ export interface CreateTerminalSessionOptions {
rows?: number;
env?: Record<string, string>;
/**
- * Where node-pty comes from. The platform cannot import a native module directly (see
- * pty-module.ts): the kernel's resource registry is how the runtime hands it over.
+ * Where a pushed bundle's node-pty assets live (the hmr capability's assetsDir);
+ * absent falls back to the packaged require (see pty-module.ts).
*/
- resources: Resources;
+ assets?: () => string | null;
}
export interface TerminalSessionInfo {
@@ -171,7 +170,7 @@ export class TerminalSession {
// Before the first spawn on macOS: node-pty's prebuilt spawn-helper ships without an
// exec bit, and posix_spawnp refuses it (see spawn-helper.ts).
ensureSpawnHelperExecutable();
- this.ptyProcess = loadNodePty(options.resources).spawn(shell, shellArgs(shell), {
+ this.ptyProcess = loadNodePty(options.assets).spawn(shell, shellArgs(shell), {
name: "xterm-256color",
cols,
rows,
diff --git a/packages/server/test/hmr-host.test.ts b/packages/server/test/hmr-host.test.ts
index 3d1ec6e4..3ca0b1af 100644
--- a/packages/server/test/hmr-host.test.ts
+++ b/packages/server/test/hmr-host.test.ts
@@ -390,3 +390,70 @@ describe("upgrade assets: an unchanged set is not copied again", () => {
expect(fsSync.existsSync(path.join(dir, ".materialized"))).toBe(true);
});
});
+
+/** A bundle whose create() throws — the boot-failure shape a bad push lands in. */
+const BOOM_PLATFORM = `
+const anySchema = {
+ strictParse: (doc) => ({ ok: true, value: doc === undefined ? {} : doc }),
+ describe: () => ({ kind: "any" }),
+};
+const iface = {
+ kind: "iface",
+ name: "platform",
+ version: 1,
+ context: anySchema,
+ methods: ["park", "info"],
+ children: {},
+ migrations: {},
+};
+const impl = {
+ create() {
+ throw new Error("boom: create failed");
+ },
+};
+export const hotPlatform = { id: "boom", iface, impl, context: {} };
+`;
+
+describe("upgrade boot failure: the previous version is re-booted, not left half-dead", () => {
+ let t: TestApp | undefined;
+
+ afterEach(async () => {
+ if (t) await t.cleanup();
+ t = undefined;
+ });
+
+ it("a failing push errors, and the machine keeps serving on a RE-BOOTED previous version", async () => {
+ t = await createTestApp();
+ const cookie = (await loginAdmin(t.app)).cookie;
+ const before = await t.deps.hmr.ensure();
+
+ const res = await pushPlatform(t.app, cookie, BOOM_PLATFORM);
+ expect(res.status).toBe(400);
+ expect(JSON.stringify(await res.json())).toMatch(/failed to boot.*boom/);
+
+ // Recovery is a fresh boot of the previous version — a NEW instance, not the
+ // disposed old one limping on through its closures (whose manager is closed and
+ // whose current-App pointer is released).
+ const after = await t.deps.hmr.ensure();
+ expect(after).not.toBe(before);
+ expect(after.api.info()).toMatchObject({ impl: "packaged" });
+ // The business surface answers — the half-dead symptom this recovery exists to
+ // prevent was "routes answer but the App behind them is stopped".
+ const client = apiClient(t.app, cookie);
+ const me = await client.get("/api/me");
+ expect(me.status).toBe(200);
+
+ // And the channel is not poisoned: the next good push lands normally.
+ const good = await pushPlatform(
+ t.app,
+ cookie,
+ platformServing(["/api/demo/after-recovery"], "recovered-push"),
+ );
+ expect(good.status).toBe(200);
+ const served = await t.app.request("/api/demo/after-recovery", {
+ headers: { cookie },
+ });
+ expect(served.status).toBe(200);
+ expect((await served.json()) as object).toMatchObject({ servedBy: "recovered-push" });
+ });
+});
diff --git a/packages/server/test/hmr-resources.test.ts b/packages/server/test/hmr-resources.test.ts
index 9f99c9b4..4ba01f92 100644
--- a/packages/server/test/hmr-resources.test.ts
+++ b/packages/server/test/hmr-resources.test.ts
@@ -25,8 +25,14 @@ import {
claimRuntimeCapabilities,
} from "../src/hmr/capabilities.js";
-/** Boots the packaged platform against `r` (capability-less: terminals-only, quiet). */
+/**
+ * Boots the packaged platform against `r` as a BARE KERNEL: capability-less, terminals-only,
+ * quiet. The empty (family-only) descriptor is what makes that legal — the host's own
+ * declaration that no business runtime stands behind it. Without any descriptor the boot
+ * is refused, which is the rule the last describe in this file drives.
+ */
async function bootPlatform(r: HotResources) {
+ r.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
return await boot(
@@ -270,28 +276,35 @@ describe("runtime capability handshake", () => {
r.register(RUNTIME_HMR_RESOURCE_ID, carrying("hmr"));
}
- it("declines when the runtime publishes no descriptor (a runtime older than the handshake)", () => {
+ it("refuses when the runtime publishes no descriptor (a runtime older than the handshake)", () => {
const r = new HotResources();
stubCaps(r);
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
- expect(claimRuntimeCapabilities(r)).toBeNull();
- warn.mockRestore();
+ expect(claimRuntimeCapabilities(r)).toMatchObject({
+ kind: "refused",
+ reason: expect.stringContaining("no interface descriptor") as unknown,
+ });
+ });
+
+ it("reads a family-only descriptor as the bare-kernel declaration", () => {
+ // 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" });
});
- it("declines when one interface is missing a member the claimer names", () => {
+ 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, auth: ["login"] });
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
- expect(claimRuntimeCapabilities(r)).toBeNull();
- warn.mockRestore();
+ expect(claimRuntimeCapabilities(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)).not.toBeNull();
+ expect(claimRuntimeCapabilities(r)).toMatchObject({ kind: "claimed" });
});
it("declines when the descriptor is honest but the live object is not", () => {
@@ -300,18 +313,17 @@ describe("runtime capability handshake", () => {
stubCaps(r);
r.register(RUNTIME_AUTH_RESOURCE_ID, { login: () => undefined }); // missing the rest
r.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
- expect(claimRuntimeCapabilities(r)).toBeNull();
- warn.mockRestore();
+ expect(claimRuntimeCapabilities(r)).toMatchObject({
+ kind: "refused",
+ reason: expect.stringContaining("auth lacks") as unknown,
+ });
});
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" });
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
- expect(claimRuntimeCapabilities(r)).toBeNull();
- warn.mockRestore();
+ expect(claimRuntimeCapabilities(r)).toMatchObject({ kind: "refused" });
});
it("an interface the claimer never names may differ freely", () => {
@@ -320,6 +332,38 @@ describe("runtime capability handshake", () => {
const r = new HotResources();
stubCaps(r);
r.register(RUNTIME_INTERFACES_RESOURCE_ID, { ...RUNTIME_INTERFACES, extra: ["x"] });
- expect(claimRuntimeCapabilities(r)).not.toBeNull();
+ expect(claimRuntimeCapabilities(r)).toMatchObject({ kind: "claimed" });
+ });
+});
+
+describe("a runtime too old to publish capabilities", () => {
+ it("is refused, not degraded to terminals-only", async () => {
+ // The shape this rule exists for. A runtime that publishes nothing is NOT a bare
+ // kernel: it still answers the business API out of its own older routes, so a
+ // terminals-only App would leave the frontend this same push just shipped talking to
+ // the previous version's API — which is how `/api/me` came back without the fields the
+ // new frontend reads off it.
+ const r = new HotResources();
+ await expect(
+ boot(
+ packagedPlatform.impl,
+ packagedPlatform.iface,
+ initialDoc(packagedPlatform.iface, packagedPlatform.context),
+ r,
+ ),
+ ).rejects.toThrow(/no business capabilities/);
+ // Refused before the registry was touched at all: the running App's declaration and
+ // its parked groups are exactly as they were, so a rejected push costs it nothing.
+ expect(r.claim(RESOURCE_IFACES_RESOURCE_ID)).toBeUndefined();
+ });
+
+ it("boots terminals-only when the host declares itself a bare kernel", async () => {
+ const r = new HotResources();
+ const inst = await bootPlatform(r);
+ try {
+ expect(inst.api.info()).toMatchObject({ impl: "packaged" });
+ } finally {
+ inst.dispose();
+ }
});
});
diff --git a/packages/server/test/park-quiesce.test.ts b/packages/server/test/park-quiesce.test.ts
new file mode 100644
index 00000000..4e9a2e8c
--- /dev/null
+++ b/packages/server/test/park-quiesce.test.ts
@@ -0,0 +1,199 @@
+/**
+ * The park contract across a hot swap (hmr/platform.ts's inventory): DELIVERED resources
+ * reach the successor intact, SUSPENDED work actually stops, and the process is clean in
+ * between — the KERNEL awaits the disposed App's `drained` tail before booting the
+ * successor, so a new App never races the old one's aborted work — and it
+ * builds anything. Driven over a bare-kernel registry (the packaged platform boots
+ * terminals-only there), with fake ptys standing in for delivered resources.
+ */
+import { describe, expect, it, vi } from "vitest";
+import { boot, initialDoc, upgrade } from "@prismshadow/penguin-core/kernel";
+import { HotResources } from "../src/hmr/resources.js";
+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 { TerminalManager } from "../src/terminal/manager.js";
+import type { TerminalSession } from "../src/terminal/session.js";
+import { waitFor } from "./helpers.js";
+
+/** A pty stand-in carrying exactly what the manager touches: id, alive, onExit, dispose. */
+function fakePty(id: string) {
+ const listeners = new Set<(info: unknown) => void>();
+ return {
+ id,
+ ownerUserId: "u",
+ alive: true,
+ disposed: 0,
+ onExit(listener: (info: unknown) => void) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ dispose() {
+ this.alive = false;
+ this.disposed++;
+ },
+ exit() {
+ this.alive = false;
+ for (const listener of [...listeners]) listener({ exitCode: 0 });
+ },
+ listenerCount: () => listeners.size,
+ };
+}
+
+const asSession = (fake: ReturnType<typeof fakePty>): TerminalSession =>
+ fake as unknown as TerminalSession;
+
+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 });
+ return r;
+}
+
+async function quietBoot(r: HotResources, doc = packagedPlatform.context) {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ return (await boot(
+ packagedPlatform.impl,
+ packagedPlatform.iface,
+ initialDoc(packagedPlatform.iface, doc),
+ r,
+ )) as Instance<PlatformApi>;
+ } finally {
+ warn.mockRestore();
+ }
+}
+
+describe("the drain handshake", () => {
+ it("upgrade() awaits the disposed App's drained tail before booting the successor", async () => {
+ // Kernel-level: a toy impl whose dispose effect leaves a controllable drain. The
+ // successor's create must not run until it settles — that IS the handover, with no
+ // registry id involved.
+ const anySchema = {
+ strictParse: (doc: unknown) => ({ ok: true, value: doc ?? {} }),
+ describe: () => ({ kind: "any" }),
+ };
+ const iface = {
+ kind: "iface",
+ name: "t",
+ version: 1,
+ context: anySchema,
+ methods: ["park"],
+ children: {},
+ migrations: {},
+ };
+ let resolveDrain!: () => void;
+ const implA = {
+ create(ctx: { effect: (d: () => void) => void }) {
+ let drained: Promise<void> | undefined;
+ ctx.effect(() => {
+ drained = new Promise<void>((resolve) => (resolveDrain = resolve));
+ });
+ return { park: () => ({}), drained: () => drained };
+ },
+ };
+ let successorBooted = false;
+ const implB = {
+ create() {
+ successorBooted = true;
+ return { park: () => ({}) };
+ },
+ };
+ const r = new HotResources();
+ const instA = await boot(implA as never, iface as never, initialDoc(iface as never, {}), r);
+ const upgradeP = upgrade({
+ current: instA,
+ impl: implB as never,
+ iface: iface as never,
+ resources: r,
+ });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(successorBooted).toBe(false); // parked on the drain, after dispose
+ resolveDrain();
+ const result = await upgradeP;
+ expect(result.status).toBe("ok");
+ expect(successorBooted).toBe(true);
+ if (result.status === "ok") result.instance.dispose();
+ });
+
+ it("a real swap: only the successor listens to a delivered pty", async () => {
+ const r = bareKernel();
+ const instA = await quietBoot(r);
+ const pty = fakePty("t1");
+ r.register("terminal:t1", asSession(pty));
+ instA.api.terminals().adopt(["t1"]);
+ expect(pty.listenerCount()).toBe(1);
+
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const result = await upgrade({
+ current: instA,
+ impl: packagedPlatform.impl,
+ iface: packagedPlatform.iface,
+ resources: r,
+ });
+ warn.mockRestore();
+ expect(result.status).toBe("ok");
+ // A detached (quiesce), B adopted and re-listened: exactly one listener, B's.
+ expect(pty.listenerCount()).toBe(1);
+ if (result.status === "ok") result.instance.dispose();
+ });
+});
+
+describe("upgrade boot failure", () => {
+ it("returns status failed with the parked doc instead of throwing", async () => {
+ const r = bareKernel();
+ const instA = await quietBoot(r);
+ const boom = {
+ create() {
+ throw new Error("boom: create failed");
+ },
+ };
+ const result = await upgrade({
+ current: instA,
+ impl: boom as never,
+ iface: packagedPlatform.iface,
+ resources: r,
+ });
+ expect(result.status).toBe("failed");
+ if (result.status === "failed") {
+ expect(String(result.error)).toMatch(/boom/);
+ // The parked doc is intact — the caller re-boots the previous impl from it.
+ const rebooted = (await boot(
+ packagedPlatform.impl,
+ packagedPlatform.iface,
+ result.doc as never,
+ r,
+ )) as Instance<PlatformApi>;
+ expect(rebooted.api.info()).toMatchObject({ impl: "packaged" });
+ rebooted.dispose();
+ }
+ });
+});
+
+describe("TerminalManager quiesce", () => {
+ it("runs pending reaps now instead of leaving timers to fire from a dead generation", () => {
+ const r = new HotResources();
+ const manager = new TerminalManager(r, { graceMs: 10_000 });
+ const pty = fakePty("t1");
+ r.register("terminal:t1", asSession(pty));
+ manager.adopt(["t1"]);
+ pty.exit(); // schedules a reap 10s out
+ manager.quiesce();
+ expect(pty.disposed).toBeGreaterThan(0); // reaped immediately…
+ expect(r.claim("terminal:t1")).toBeUndefined(); // …and released from the registry
+ expect(pty.listenerCount()).toBe(0); // detached from everything still alive
+ });
+
+ it("adopt reaps a pty that died during the swap freeze (its exit fired into the old generation)", async () => {
+ const r = new HotResources();
+ const manager = new TerminalManager(r, { graceMs: 5 });
+ const pty = fakePty("t1");
+ pty.alive = false; // died before this manager ever listened
+ r.register("terminal:t1", asSession(pty));
+ manager.adopt(["t1"]);
+ await waitFor(() => r.claim("terminal:t1") === undefined);
+ expect(pty.disposed).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index 3fcb3581..6683cf26 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -1051,6 +1051,21 @@ describe("session-manager", () => {
expect((err as { code: string }).code).toBe("workspace_missing");
});
+ it("shutdown disposes each Session's environment, so background commands die with the App", async () => {
+ // A hot swap that skipped this would orphan e.g. a dev server the conversation
+ // started: the OS process keeps running while the successor's freshly resumed
+ // Session starts with an empty process list — the stop control has gone blind.
+ const fake = approvalFakeSession("session-1");
+ let disposed = 0;
+ (fake as { dispose?: () => void }).dispose = () => {
+ disposed++;
+ };
+ const manager = makeManager(loaderOf(fake));
+ manager.adopt(ROW, fake);
+ await manager.shutdown();
+ expect(disposed).toBe(1);
+ });
+
it("rejects new Tasks once shutdown is set (503 shutting_down)", async () => {
const manager = makeManager(loaderOf(approvalFakeSession("session-1")));
await manager.shutdown();
diff --git a/packages/server/test/terminal.test.ts b/packages/server/test/terminal.test.ts
index 33b60e22..06df4b40 100644
--- a/packages/server/test/terminal.test.ts
+++ b/packages/server/test/terminal.test.ts
@@ -499,11 +499,18 @@ describePty("terminal manager lifecycle", () => {
const registry = new Map<string, unknown>();
return new TerminalManager(
{
- register: (id, resource) => void registry.set(id, resource),
+ register: (id, resource, dispose) => {
+ registry.set(id, resource);
+ // Mirrors HotResources: unregister removes AND disposes (identity-checked).
+ return () => {
+ if (registry.get(id) !== resource) return;
+ registry.delete(id);
+ dispose?.();
+ };
+ },
claim: <T>(id: string) => registry.get(id) as T | undefined,
- release: (id) => void registry.delete(id),
},
- graceMs,
+ { graceMs },
);
}