Skip to content

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

refactor(server,web): machines are remembered in web.db, and belong to a Project (#565)

Myriad-Dreamin7919f3c50b39
diff --git a/changelog/unreleased/2026-09-01-machines-store.md b/changelog/unreleased/2026-09-01-machines-store.md
new file mode 100644
index 00000000..700a8f46
--- /dev/null
+++ b/changelog/unreleased/2026-09-01-machines-store.md
@@ -0,0 +1,24 @@
+# Machines are remembered in web.db, and belong to a Project
+
+- **Date:** 2026-09-01
+- **Type:** refactor
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#565](https://github.com/Prism-Shadow/penguin-harness/pull/565)
+- **Breaking:** yes — the machines routes moved under a Project, and `machines-installs.json` is read no longer
+
+[中文版](2026-09-01-machines-store.zh.md)
+
+What this server has installed on which machine moves out of `<data root>/machines-installs.json` and into `web.db`, and a machine now belongs to a Project. The install itself is unchanged — same ssh, same job, same progress lines.
+
+## Details
+
+- **One store.** Migration 4 adds the machines tables, and the install record is written and read there. The JSON file could not carry a schema change, and nothing else this server remembers lives outside the database. The migration is `swapSafe`: it adds tables and touches nothing existing, so a platform rolled back to a build without machines simply never queries them.
+- **A machine belongs to a Project**, because a Project's machines are where that Project's work runs. The host itself is not project-scoped — one program, one ssh config entry, shared by every Project that adopted it; what a Project owns is the membership. Installing is how a Project acquires one; `POST …/release` gives it back without touching the install.
+- **A host another Project installed reads as `elsewhere`, not as uninstalled.** The two lead to different actions: adopting costs a row, re-installing costs a 30 MB transfer to reach the same place. A row that silently looked untouched would send someone to do the second.
+- **The routes moved** from `/api/machines` to `/api/projects/:projectId/machines`. Still admin-only: the Project scope says which machines are answered, never who may reach them — installing spawns ssh with the server account's keys either way.
+
+## Compatibility
+
+`<data root>/machines-installs.json` is **not read** and not migrated. A server that installed on machines under 0.2.9 comes up with an empty **Installed machines** list; the file is left on disk untouched. Re-installing is the recovery and is cheap: every step is idempotent, and a machine that already carries this version is a no-op that only rewrites the record.
+
+A machine belongs to the Project that installs it, and nothing is inherited — the default Project included — so re-install from the Project that should have it. A Project that is deleted takes its machine list with it; the installs themselves stay.
diff --git a/changelog/unreleased/2026-09-01-machines-store.zh.md b/changelog/unreleased/2026-09-01-machines-store.zh.md
new file mode 100644
index 00000000..da4587c3
--- /dev/null
+++ b/changelog/unreleased/2026-09-01-machines-store.zh.md
@@ -0,0 +1,24 @@
+# 机器记录改存 web.db,并归属于 Project
+
+- **Date:** 2026-09-01
+- **Type:** refactor
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#565](https://github.com/Prism-Shadow/penguin-harness/pull/565)
+- **Breaking:** yes — machines 路由移到 Project 之下,且 `machines-installs.json` 不再被读取
+
+[English](2026-09-01-machines-store.md)
+
+本服务端在哪台机器上装过什么,从 `<data root>/machines-installs.json` 移进 `web.db`,并且机器现在归属于某个 Project。安装过程本身没有变化——同样的 ssh、同样的任务、同样的进度输出。
+
+## 细节
+
+- **只有一处存储。** migration 4 建立 machines 相关的表,安装记录在那里读写。JSON 文件承载不了 schema 变更,而本服务端记住的其他东西也都不在数据库之外。该 migration 是 `swapSafe` 的:只新增表、不动既有表,因此平台回滚到没有 machines 的构建时,只是不再查询这些表而已。
+- **机器归属于 Project**,因为一个 Project 的机器就是它的工作运行的地方。主机本身不按 Project 划分——一份程序、一条 ssh config 条目,被每个纳入它的 Project 共享;Project 拥有的是这层归属关系。安装就是一个 Project 取得机器的方式;`POST …/release` 把它交还,且不触碰安装本身。
+- **别的 Project 装过的主机读作 `elsewhere`,而不是「未安装」。** 二者导向不同的操作:纳入只需写一行记录,重装则要为同一个结果再传 30 MB。一个看起来没人动过的条目,会让人去做后者。
+- **路由从 `/api/machines` 移到 `/api/projects/:projectId/machines`。** 依然仅限管理员:Project 作用域决定回答哪些机器,不决定谁有权触达它们——无论如何,安装用的都是服务端账号的 ssh 密钥。
+
+## 兼容性
+
+`<data root>/machines-installs.json` **不会被读取**,也不会被迁移。在 0.2.9 下装过机器的服务端升上来后,**已安装机器**列表是空的;该文件原样留在磁盘上。重新安装即可恢复,代价很低:每一步都幂等,已经是该版本的机器只是一次 no-op,仅重写记录。
+
+机器归属于安装它的那个 Project,没有任何继承——默认 Project 也不例外——所以请从应当拥有它的 Project 重新安装。Project 被删除时会带走自己的机器列表;机器上的安装本身保持不动。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index cdd2f567..c44543f3 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -112,8 +112,9 @@ In every on-state the effective NO_PROXY always includes `localhost,127.0.0.1,::
| Method | Path | Description |
| --- | --- | --- |
-| GET | /api/machines | The host aliases of the SERVER's own `~/.ssh/config`, the version this server would install, and the running or last install job: `{machines: [{id, alias, installed}], imageVersion, job}` |
-| POST | /api/machines/:machineId/install | Start installing this build on that host; `202` with the same body, the job now running |
+| GET | /api/projects/:projectId/machines | The host aliases of the SERVER's own `~/.ssh/config` with what THIS PROJECT has installed on each, the version this server would install, and the running or last install job: `{machines: [{id, alias, installed, elsewhere?}], imageVersion, job}`. `elsewhere` is a host another Project installed — a machine to adopt rather than install |
+| POST | /api/projects/:projectId/machines/:machineId/install | Start installing this build on that host and give it to this Project; `202` with the same body, the job now running |
+| POST | /api/projects/:projectId/machines/:machineId/release | Drop that machine from this Project; the install on it stays |
Admin only on a personal server as much as a multi-user one: the install spawns ssh with the **server account's** keys and writes a program directory on another machine, which is an owner's capability rather than a visitor's. Nothing writes to the ssh config — it is read, and `ssh -G` resolves an alias only at install time, so a config declaring hundreds of hosts costs one file read.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 87d9a775..66e59a05 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -112,8 +112,9 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /api/machines | **服务端自身** `~/.ssh/config` 中的主机别名、本服务端会安装的版本,以及正在运行或最近一次的安装任务:`{machines: [{id, alias, installed}], imageVersion, job}` |
-| POST | /api/machines/:machineId/install | 在该主机上安装当前构建;返回 `202` 与同样的响应体,此时任务已在运行 |
+| GET | /api/projects/:projectId/machines | **服务端自身** `~/.ssh/config` 中的主机别名,附带**本 Project** 在每台上安装了什么、本服务端会安装的版本,以及正在运行或最近一次的安装任务:`{machines: [{id, alias, installed, elsewhere?}], imageVersion, job}`。`elsewhere` 表示该主机由别的 Project 装过——可以纳入,不必重装 |
+| POST | /api/projects/:projectId/machines/:machineId/install | 在该主机上安装当前构建,并把它归入本 Project;返回 `202` 与同样的响应体,此时任务已在运行 |
+| POST | /api/projects/:projectId/machines/:machineId/release | 把该机器移出本 Project;机器上已安装的程序保持不动 |
无论个人服务端还是多用户服务端都仅限管理员:安装会以**服务端账户**的密钥派生 ssh,并在另一台机器上写入程序目录——这是所有者的能力,而非访客的。ssh 配置只读不写,`ssh -G` 仅在真正安装时才解析别名,因此哪怕配置声明了几百台主机,列表也只是一次文件读取。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 0ff9bac2..101d9644 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -3314,9 +3314,9 @@ export interface MachineInfo {
*/
alias: string;
/**
- * The last install THIS server carried out there, remembered on disk so it survives a
- * restart, a hot push, and installing on some other machine. Null when this server has
- * never installed there.
+ * The last install THIS server carried out there FOR THIS PROJECT, remembered in web.db so
+ * it survives a restart, a hot push, and installing on some other machine. Null when this
+ * Project has never installed there — a host another Project did is `elsewhere` below.
*
* A record of what was done, not a survey of the far side: a machine wiped by hand still
* reads as installed until the next install probes it and corrects the record. Asking the
@@ -3324,6 +3324,17 @@ export interface MachineInfo {
* the config-text list exists to avoid.
*/
installed: { version: string; at: string } | null;
+ /**
+ * Installed by this server, but not this Project's machine — another Project's, or nobody's
+ * since it was released — and so not a host nobody has touched either. Absent in every
+ * other case, including when it IS this Project's (where `installed` carries the same record).
+ *
+ * Reported rather than folded into `installed` because the two lead to different actions:
+ * one is a machine to use, the other is a machine to adopt, which costs a row and no ssh.
+ * Reported rather than hidden because a row that silently looked uninstalled would send
+ * someone to spend a 30 MB transfer re-doing what is already done.
+ */
+ elsewhere?: { version: string; at: string };
}
/**
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index fae0868a..28de2ae9 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -44,6 +44,7 @@ import {
} from "./hmr/capabilities.js";
import type { ProxyControl } from "./hmr/capabilities.js";
import { openDatabase } from "./db/database.js";
+import { MachinesRepo } from "./db/repos/machines.js";
import { migrate } from "./db/migrations.js";
import { ErrorsRepo } from "./db/repos/errors.js";
import { MessagingBindingsRepo } from "./db/repos/messaging-bindings.js";
@@ -1094,7 +1095,9 @@ export function buildAppDeps(
lifecycle: caps.lifecycle,
// Anchored at the data root: that is where the hmr store the pushable image comes from
// lives, and where verified Node runtime downloads are cached between installs.
- machines: overrides.machines ?? new MachinesService(config.root, {}, () => hmr.assetsDir()),
+ machines:
+ overrides.machines ??
+ new MachinesService(config.root, new MachinesRepo(db), {}, () => hmr.assetsDir()),
hmr,
proxyControl: caps.proxyControl,
log,
@@ -1191,10 +1194,10 @@ export function createApp(
app.route("/api/version", versionRoutes(deps));
app.route("/api/admin/users", adminUsersRoutes(deps));
app.route("/api/admin/settings", adminSettingsRoutes(deps));
- app.route("/api/machines", machinesRoutes(deps));
app.route("/api/events", eventsRoutes(deps));
// Plugin library listing: readable once logged in, not nested under a Project prefix.
app.route("/api/plugins", pluginLibraryRoutes());
+ app.route("/api/projects/:projectId/machines", machinesRoutes(deps));
app.route("/api/projects", projectsRoutes(deps));
app.route("/api/projects/:projectId/members", membersRoutes(deps));
app.route("/api/projects/:projectId/models", modelsRoutes(deps));
diff --git a/packages/server/src/db/migrations.ts b/packages/server/src/db/migrations.ts
index f05d1c05..f869335f 100644
--- a/packages/server/src/db/migrations.ts
+++ b/packages/server/src/db/migrations.ts
@@ -178,6 +178,46 @@ export const MIGRATIONS: readonly Migration[] = [
`);
},
},
+ {
+ version: 4,
+ name: "machines",
+ // Three new tables, nothing existing touched: a platform rolled back to one without
+ // machines never queries them. Swap-safe on its own; a database still behind
+ // drop-goal-state is refused whole by that one first, which is the rule.
+ swapSafe: true,
+ up(db) {
+ // Frozen copy of the DDL as of the machines feature; do not re-derive from schema.ts.
+ // IF NOT EXISTS because the declarative track may already have created them (ADOPTION).
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS machine (
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
+ machine_id TEXT NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS machines (
+ address TEXT PRIMARY KEY,
+ machine_id TEXT,
+ version TEXT,
+ installed_at TEXT,
+ session_pid INTEGER,
+ remote_port INTEGER
+ );
+ CREATE TABLE IF NOT EXISTS machine_project (
+ project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,
+ addresses TEXT NOT NULL
+ );
+ `);
+ },
+ // LOSES this server's own machine id (every stored reference to it on other machines
+ // then points at nothing), what was installed where, the sessions held, and which
+ // machines each Project used.
+ down(db) {
+ db.exec(`
+ DROP TABLE IF EXISTS machine_project;
+ DROP TABLE IF EXISTS machines;
+ DROP TABLE IF EXISTS machine;
+ `);
+ },
+ },
];
/** The highest version this build knows how to reach. */
diff --git a/packages/server/src/db/repos/machines.ts b/packages/server/src/db/repos/machines.ts
new file mode 100644
index 00000000..015c3d56
--- /dev/null
+++ b/packages/server/src/db/repos/machines.ts
@@ -0,0 +1,93 @@
+/**
+ * What this server remembers about machines: one row per machine it has installed on, and
+ * which machines each Project uses. In web.db, so a hot swap or a restart reads back exactly
+ * what the last generation wrote — the JSON file this replaces could not survive a schema
+ * change, and nothing else this server remembers lives outside the database.
+ *
+ * `MachineRow` mirrors the table rather than the columns written today: the DDL lands in one
+ * migration, and the fields nothing reads yet (a machine's own id, the session held to it)
+ * are the table's, not this store's opinion of what matters.
+ */
+import type { DatabaseSync } from "node:sqlite";
+
+export interface MachineRow {
+ /** `ssh:<alias>` */
+ address: string;
+ /** That machine's own id, once heard. */
+ machineId: string | null;
+ /** What this server last installed there; null when it never has. */
+ version: string | null;
+ installedAt: string | null;
+ /** The ssh session this server holds to it — recorded so a successor generation can close it. */
+ sessionPid: number | null;
+ /** The port its server was bound to over there, as of the last connect. */
+ remotePort: number | null;
+}
+
+/** Everything but the address may be patched; absent fields keep their value. */
+type MachinePatch = Partial<Omit<MachineRow, "address">>;
+
+export class MachinesRepo {
+ constructor(private readonly db: DatabaseSync) {}
+
+ get(address: string): MachineRow | null {
+ const row = this.db.prepare("SELECT * FROM machines WHERE address = ?").get(address);
+ return row === undefined ? null : toRow(row);
+ }
+
+ all(): MachineRow[] {
+ return this.db.prepare("SELECT * FROM machines").all().map(toRow);
+ }
+
+ /** Writes the fields given, creating the row when there is none. */
+ patch(address: string, patch: MachinePatch): void {
+ const next: MachineRow = {
+ ...(this.get(address) ?? {
+ address,
+ machineId: null,
+ version: null,
+ installedAt: null,
+ sessionPid: null,
+ remotePort: null,
+ }),
+ ...patch,
+ };
+ this.db
+ .prepare(
+ "INSERT OR REPLACE INTO machines (address, machine_id, version, installed_at, session_pid, remote_port) VALUES (?, ?, ?, ?, ?, ?)",
+ )
+ .run(
+ address,
+ next.machineId,
+ next.version,
+ next.installedAt,
+ next.sessionPid,
+ next.remotePort,
+ );
+ }
+
+ /** The addresses a Project uses, or null when it has never had a list written for it. */
+ members(projectId: string): string[] | null {
+ const row = this.db
+ .prepare("SELECT addresses FROM machine_project WHERE project_id = ?")
+ .get(projectId);
+ return row ? (JSON.parse(row.addresses as string) as string[]) : null;
+ }
+
+ setMembers(projectId: string, addresses: string[]): void {
+ this.db
+ .prepare("INSERT OR REPLACE INTO machine_project (project_id, addresses) VALUES (?, ?)")
+ .run(projectId, JSON.stringify(addresses));
+ }
+}
+
+function toRow(row: Record<string, unknown>): MachineRow {
+ return {
+ address: row.address as string,
+ machineId: (row.machine_id as string | null) ?? null,
+ version: (row.version as string | null) ?? null,
+ installedAt: (row.installed_at as string | null) ?? null,
+ sessionPid: (row.session_pid as number | null) ?? null,
+ remotePort: (row.remote_port as number | null) ?? null,
+ };
+}
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index 485818aa..f3df42f5 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -141,6 +141,22 @@ CREATE TABLE IF NOT EXISTS server_settings ( -- admin-level server-global sett
key TEXT PRIMARY KEY, -- setting name, e.g. 'proxy_for_app'
value TEXT NOT NULL -- JSON-encoded value; an absent row means the setting's built-in default
);
+CREATE TABLE IF NOT EXISTS machine ( -- this server's OWN identity, minted here and never assigned from outside (what 'penguin server status' reports)
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1), -- exactly one row, enforced by the schema rather than by convention
+ machine_id TEXT NOT NULL -- 16 base64url characters; what every stored reference to this machine points at
+);
+CREATE TABLE IF NOT EXISTS machines ( -- one row per machine this server installed on or reached (machines/service.ts)
+ address TEXT PRIMARY KEY, -- 'ssh:<alias>'
+ machine_id TEXT, -- that machine's own id, once heard
+ version TEXT, -- what this server last installed there; NULL = never
+ installed_at TEXT,
+ session_pid INTEGER, -- the ssh session this server holds to it; what a successor App closes after a hot swap
+ remote_port INTEGER -- its server's port over there, as of the last connect
+);
+CREATE TABLE IF NOT EXISTS machine_project ( -- which machines a Project uses; no row = none yet. Follows the Project out, like project_members
+ project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,
+ addresses TEXT NOT NULL -- JSON array of 'ssh:<alias>'
+);
CREATE TABLE IF NOT EXISTS trace_files ( -- DERIVED CACHE of the on-disk Trace tree (services/trace-index.ts): the directories stay the single source of truth, every row is rebuildable from disk, and a row is never authority for absence — consumers reconcile + retry on a miss, so a stale index costs one extra scan, never a false 404
project_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
diff --git a/packages/server/src/http/routes/machines.ts b/packages/server/src/http/routes/machines.ts
index 66d25c5b..5b5a9a75 100644
--- a/packages/server/src/http/routes/machines.ts
+++ b/packages/server/src/http/routes/machines.ts
@@ -1,13 +1,23 @@
/**
- * Machines routes (admin only, 403 for non-admins):
- * GET /api/machines — the ssh config's host aliases, the version this
- * server would install, and the running or last job.
- * POST /api/machines/:machineId/install — start an install; 202, or 409 when one runs.
+ * Machines routes, under a Project (admin only, 403 for non-admins). Relative to
+ * `/api/projects/:projectId/machines`:
+ *
+ * POST /:machineId/install — start an install and give the machine to this Project; 202, or
+ * 409 when one runs.
+ * POST /:machineId/release — drop it from this Project. The install stays.
+ * GET / — the ssh config's host aliases with what this Project has
+ * installed on each, the version this server would install, and
+ * the running or last job.
+ *
+ * Under a Project because the page is, and because a Project's machines are where that
+ * Project's work runs. The machine itself is not project-scoped — one host, one program,
+ * shared by every Project that adopted it; what a Project owns is the membership.
*
* Admin rather than any logged-in user, on a multi-user server as much as a personal one:
* installing spawns ssh with the SERVER ACCOUNT's keys and writes a program directory on
* another machine. That is an owner's capability, not a visitor's, and the account whose
- * keys are used is not the account making the request.
+ * keys are used is not the account making the request. The Project scope says WHICH
+ * machines are answered, never who may reach them.
*
* The install is a job because it can take minutes (see ../../machines/service.ts); this
* route only starts it and reports it. Progress arrives by polling GET rather than over the
@@ -15,8 +25,10 @@
* that dies with its App has nothing to replay to a reconnecting subscriber.
*/
import { Hono } from "hono";
+import type { Context } from "hono";
import type { MachinesResponse } from "../../api/types.js";
import { HttpError } from "../errors.js";
+import { requireValidId } from "../validate.js";
import type { AppEnv } from "../../auth/middleware.js";
import type { AppDeps } from "../../app.js";
@@ -27,19 +39,28 @@ export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {
if (!c.var.user.isAdmin) {
throw new HttpError(403, "admin_required", "Only an admin can install on a machine.");
}
+ deps.projectService.requireProjectAccess(c.var.user.userId, requireValidId(c, "projectId"));
await next();
});
- const state = (): MachinesResponse => ({
- machines: deps.machines.list(),
+ const state = (c: Context<AppEnv>): MachinesResponse => ({
+ machines: deps.machines.list(requireValidId(c, "projectId")),
imageVersion: deps.machines.imageVersion(),
job: deps.machines.job(),
});
- app.get("/", (c) => c.json(state()));
+ app.get("/", (c) => c.json(state(c)));
+
+ app.post("/:machineId/release", (c) => {
+ deps.machines.release(requireValidId(c, "projectId"), c.req.param("machineId"));
+ return c.json(state(c));
+ });
app.post("/:machineId/install", async (c) => {
- const started = await deps.machines.startInstall(c.req.param("machineId"));
+ const started = await deps.machines.startInstall(
+ requireValidId(c, "projectId"),
+ c.req.param("machineId"),
+ );
if (!started.ok) {
// Each refusal is its own code: the page renders a sentence per case, and "no image"
// in particular is a property of THIS server rather than of the machine picked.
@@ -62,7 +83,7 @@ export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {
"ssh could not resolve that host. Check ~/.ssh/config, or that ssh is on PATH.",
);
}
- return c.json(state(), 202);
+ return c.json(state(c), 202);
});
return app;
diff --git a/packages/server/src/machines/installs.ts b/packages/server/src/machines/installs.ts
deleted file mode 100644
index b3eeeb28..00000000
--- a/packages/server/src/machines/installs.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * What this server has installed on which machine, remembered across restarts and hot
- * pushes in one JSON file under the data root.
- *
- * Without it, "installed" is a property of the ONE in-memory job: it dies with the process,
- * and installing on a second machine erases the first machine's answer. The record is what
- * makes the picker able to say which hosts already carry this program and which version
- * they got, without an ssh round trip per host at page load — the whole reason the list is
- * config text in the first place.
- *
- * It is a record of what WE did, not a survey of the far side. A machine someone wiped by
- * hand still reads as installed here; the install itself is what corrects that, since it
- * probes the remote before deciding anything (an unchanged version is a no-op, a missing
- * one installs). Treating the file as authoritative about the remote would be a lie, so
- * nothing here does.
- *
- * Pure functions over the file's text; the service owns the I/O.
- */
-
-/** One machine's last successful install, as this server carried it out. */
-export interface InstallRecord {
- /** The version that landed — the image version this server sent, or what the remote already had. */
- version: string;
- /** ISO timestamp, so the picker can say "installed" with a date rather than just a flag. */
- at: string;
-}
-
-/**
- * Parses the file's text: machine id → record. Damage, a wrong shape, or a missing file all
- * read as "nothing remembered" — this is a convenience over the ssh config, and refusing to
- * serve the machines list because a cache file got corrupted would be the worse failure.
- */
-export function parseInstallRecords(raw: string | null): Record<string, InstallRecord> {
- if (raw === null || raw.trim() === "") return {};
- try {
- const parsed: unknown = JSON.parse(raw);
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
- const out: Record<string, InstallRecord> = {};
- for (const [machineId, value] of Object.entries(parsed)) {
- if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
- const entry = value as Record<string, unknown>;
- if (typeof entry.version !== "string" || entry.version === "") continue;
- if (typeof entry.at !== "string" || entry.at === "") continue;
- out[machineId] = { version: entry.version, at: entry.at };
- }
- return out;
- } catch {
- return {};
- }
-}
-
-/** The file's next text after updating one machine's record (null forgets it). */
-export function withInstallRecord(
- raw: string | null,
- machineId: string,
- record: InstallRecord | null,
-): string {
- const all = parseInstallRecords(raw);
- if (record === null) delete all[machineId];
- else all[machineId] = record;
- return JSON.stringify(all, null, 2) + "\n";
-}
diff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.ts
index e7350961..6d6ebf5f 100644
--- a/packages/server/src/machines/service.ts
+++ b/packages/server/src/machines/service.ts
@@ -13,19 +13,22 @@
* step is idempotent — the far side's installer stages, smoke-tests and swaps, and an
* unchanged version is a no-op.
*
- * The RESULT is. Which machines carry this program is not a property of the last job — it
- * has to outlive the job, the process and the next install somewhere else — so a successful
- * install is written to `<data root>/machines-installs.json` (installs.ts) and read back
- * into every list(). Without it "installed" would blink out the moment anything else
- * happened, which is exactly what it did before this file wrote anything down.
+ * The RESULT is, in web.db (MachinesRepo): which machines carry this program, and which
+ * Project uses which. It has to outlive the job, the process and the next install somewhere
+ * else. It is a record of what WE did, not a survey of the far side — a machine someone
+ * wiped by hand still reads as installed here, and the install itself is what corrects that,
+ * since it probes the remote before deciding anything.
+ *
+ * A machine BELONGS TO A PROJECT. The host is shared — one program, one ssh config entry —
+ * but which Projects use it is this server's own bookkeeping, because a Project's machines
+ * are where that Project's work runs. A host installed for another Project is reported as
+ * `elsewhere` rather than hidden: adopting it costs a row, while re-installing costs a
+ * 30 MB transfer to reach the same place.
*/
-import fs from "node:fs";
-import path from "node:path";
import type { MachineInfo, MachineInstallJob } from "../api/types.js";
import { listHostAliases, resolveTarget } from "./targets.js";
import { installOnRemote, resolvePushPlan } from "./install-server.js";
-import { parseInstallRecords, withInstallRecord } from "./installs.js";
-import type { InstallRecord } from "./installs.js";
+import type { MachinesRepo } from "../db/repos/machines.js";
/** Why a start was refused before any ssh ran. */
export type InstallRefusal = "busy" | "unknown-machine" | "unresolvable" | "no-image";
@@ -50,15 +53,13 @@ export class MachinesService {
#job: MachineInstallJob | null = null;
readonly #effects: MachinesEffects;
- /**
- * `dataRoot` is the server's own data root: it holds the hmr state a push replicates, and
- * the install records below.
- */
/** Where a pushed bundle's assets were unpacked; null in a packaged server (hmr.assetsDir). */
readonly #assets: () => string | null;
+ /** `dataRoot` is the server's own data root: it holds the hmr state a push replicates. */
constructor(
private readonly dataRoot: string,
+ private readonly repo: MachinesRepo,
effects: Partial<MachinesEffects> = {},
assets: () => string | null = () => null,
) {
@@ -73,32 +74,55 @@ export class MachinesService {
};
}
- /** Where the install records live — beside the other per-machine state in the data root. */
- get #recordsFile(): string {
- return path.join(this.dataRoot, "machines-installs.json");
+ /**
+ * The addresses a Project uses: exactly its own list, empty until an install gives it one.
+ *
+ * Nothing is inherited, the default Project included. The store starts empty (the JSON
+ * file it replaces is not read), so there is nothing for a first Project to inherit — and
+ * an inheritance that materialised on the Project's first write made the answer depend on
+ * whether that write had happened yet. A machine belongs to the Project that installed it
+ * or adopted it, and to no other; one released by every Project reads as `elsewhere` for
+ * all of them, which is what makes it adoptable again.
+ */
+ #members(projectId: string): string[] {
+ return this.repo.members(projectId) ?? [];
}
- /** The records file's text, or null when there is none yet (or it cannot be read). */
- #readRecords(): string | null {
- try {
- return fs.readFileSync(this.#recordsFile, "utf8");
- } catch {
- return null; // Never installed from this server yet, or an unreadable file: nothing remembered.
- }
+ #setMember(projectId: string, address: string, member: boolean): void {
+ const current = this.#members(projectId);
+ this.repo.setMembers(
+ projectId,
+ member ? [...new Set([...current, address])] : current.filter((entry) => entry !== address),
+ );
}
/**
- * The ssh config's host aliases, each carrying what this server last installed there.
- * Empty when there is no config, which is not an error.
+ * The ssh config's host aliases, answered for one Project: `installed` means installed FOR
+ * THIS PROJECT, and a host this server installed on but this Project does not use is
+ * reported through `elsewhere`. Empty when there is no config, which is not an error.
*/
- list(): MachineInfo[] {
- const records = parseInstallRecords(this.#readRecords());
- return this.#effects.listAliases().map((alias) => {
+ list(projectId: string): MachineInfo[] {
+ const members = new Set(this.#members(projectId));
+ return this.#effects.listAliases().map((alias): MachineInfo => {
const id = `ssh:${alias}`;
- return { id, alias, installed: records[id] ?? null };
+ const row = this.repo.get(id);
+ const installed =
+ row?.version == null ? null : { version: row.version, at: row.installedAt ?? "" };
+ const mine = members.has(id);
+ return {
+ id,
+ alias,
+ installed: mine ? installed : null,
+ ...(!mine && installed !== null ? { elsewhere: installed } : {}),
+ };
});
}
+ /** Drops a machine from a Project. The program stays installed; only the membership goes. */
+ release(projectId: string, address: string): void {
+ this.#setMember(projectId, address, false);
+ }
+
/**
* The version this server would install, or null when it has no image to push — a dev
* checkout that has never been pushed to is the one shape with none. The page asks for it
@@ -118,24 +142,29 @@ export class MachinesService {
* a job already running, an alias this config does not declare, an ssh that cannot resolve
* it, no image to send — are answered synchronously, so the page distinguishes "did not
* start" from "started and failed" without reading the log.
+ *
+ * Success also gives the machine to the Project that asked for it: an install is how a
+ * Project acquires a machine, and one that installed but belonged to nobody would not
+ * appear in the list it was started from.
*/
async startInstall(
+ projectId: string,
machineId: string,
): Promise<{ ok: true } | { ok: false; why: InstallRefusal }> {
if (this.#job?.running === true) return { ok: false, why: "busy" };
- const machine = this.list().find((entry) => entry.id === machineId);
- if (machine === undefined) return { ok: false, why: "unknown-machine" };
+ const alias = this.#effects.listAliases().find((entry) => `ssh:${entry}` === machineId);
+ if (alias === undefined) return { ok: false, why: "unknown-machine" };
const plan = this.#effects.resolvePlan(this.dataRoot);
if (plan === null) return { ok: false, why: "no-image" };
- const resolved = await this.#effects.resolveTarget(machine.alias);
+ const resolved = await this.#effects.resolveTarget(alias);
if (resolved === null) return { ok: false, why: "unresolvable" };
const job: MachineInstallJob = {
machineId,
- alias: machine.alias,
+ alias,
running: true,
log: [],
result: null,
@@ -154,7 +183,7 @@ export class MachinesService {
// No identity passed: installOnRemote runs the probe itself as its first step and
// narrates it, so the page shows what the machine turned out to be.
const outcome = await this.#effects.install({
- target: { alias: machine.alias, user: resolved.settings.user },
+ target: { alias, user: resolved.settings.user },
plan,
onProgress: say,
assets: this.#assets,
@@ -164,10 +193,11 @@ export class MachinesService {
return;
}
const version = outcome.kind === "already-installed" ? outcome.version : plan.version;
- // Remember it BEFORE the job settles, so the first poll that sees `running: false`
+ // Remembered BEFORE the job settles, so the first poll that sees `running: false`
// already sees the machine marked installed — otherwise the page would flash the
// verdict and a still-uninstalled row in the same frame.
- this.#remember(machineId, { version, at: this.#effects.now().toISOString() });
+ this.repo.patch(machineId, { version, installedAt: this.#effects.now().toISOString() });
+ this.#setMember(projectId, machineId, true);
job.result = { ok: true, kind: outcome.kind, version };
} catch (err) {
job.result = {
@@ -182,33 +212,4 @@ export class MachinesService {
return { ok: true };
}
-
- /**
- * Writes one machine's record.
- *
- * Through a temp file and a rename rather than straight onto the target: a plain write
- * truncates first, so a crash mid-write leaves bytes the parser reads as "nothing
- * installed anywhere" — treating damage as empty is right for a cache, but it means a
- * torn write silently forgets every OTHER machine too, not just the one being recorded.
- * Rename is one step; a reader sees the old file or the new one.
- *
- * A failure here is swallowed: the install itself already succeeded, and the far side has
- * the program whether or not this side managed to note it down. Forgetting costs one
- * needless reinstall, which is a no-op on the remote.
- */
- #remember(machineId: string, record: InstallRecord): void {
- const next = withInstallRecord(this.#readRecords(), machineId, record);
- const tmp = `${this.#recordsFile}.tmp-${process.pid}`;
- try {
- fs.mkdirSync(path.dirname(this.#recordsFile), { recursive: true });
- fs.writeFileSync(tmp, next);
- fs.renameSync(tmp, this.#recordsFile);
- } catch {
- try {
- fs.rmSync(tmp, { force: true });
- } catch {
- /* the temp file is litter at worst */
- }
- }
- }
}
diff --git a/packages/server/src/services/project-service.ts b/packages/server/src/services/project-service.ts
index bd0d2ef2..2c585ce9 100644
--- a/packages/server/src/services/project-service.ts
+++ b/packages/server/src/services/project-service.ts
@@ -306,7 +306,7 @@ export class ProjectService {
new Promise<void>((resolve) => setTimeout(resolve, ABORT_SETTLE_TIMEOUT_MS).unref?.()),
]);
}
- this.deps.projects.delete(projectId); // project_members cascade-deleted
+ this.deps.projects.delete(projectId); // project_members and machine_project cascade-deleted
this.deps.agents.deleteByProject(projectId);
this.deps.sessions.deleteByProject(projectId);
this.deps.usage.deleteByProject(projectId);
diff --git a/packages/server/test/db-migrations.test.ts b/packages/server/test/db-migrations.test.ts
index 4e3d1666..30db4485 100644
--- a/packages/server/test/db-migrations.test.ts
+++ b/packages/server/test/db-migrations.test.ts
@@ -63,6 +63,9 @@ function open029(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
db.exec(GOAL_STATE_DDL);
+ // SCHEMA_SQL declares the CURRENT shape, and a 0.2.9 database has no machines tables —
+ // migration 4 is what adds them. Without this the fixture is a database no release made.
+ db.exec("DROP TABLE machine_project; DROP TABLE machines; DROP TABLE machine;");
db.exec("PRAGMA user_version = 2");
return db;
}
@@ -142,6 +145,7 @@ describe("migration mechanism", () => {
"messaging-bindings",
"messaging-delivery-flags",
"drop-goal-state",
+ "machines",
]);
expect(schemaVersion(db)).toBe(LATEST_VERSION);
} finally {
@@ -200,6 +204,7 @@ describe("the swap path refuses what a rollback could not survive", () => {
expect(withoutRestartOnly(() => migrate(db, { swapPath: true }).applied)).toEqual([
"messaging-bindings",
"messaging-delivery-flags",
+ "machines",
]);
} finally {
db.close();
@@ -219,6 +224,7 @@ describe("the swap path refuses what a rollback could not survive", () => {
"messaging-bindings",
"messaging-delivery-flags",
"drop-goal-state",
+ "machines",
]);
} finally {
db.close();
@@ -242,12 +248,12 @@ describe("0.2.9 → current: drop-goal-state", () => {
const fresh = new sqlite.DatabaseSync(":memory:");
try {
fresh.exec(SCHEMA_SQL);
- expect(migrate(db).applied).toEqual(["drop-goal-state"]);
+ expect(migrate(db).applied).toEqual(["drop-goal-state", "machines"]);
expect(shape(db)).toBe(shape(fresh));
// IF EXISTS: a database this build created, stamped 2 by an older mechanism, has no
// goal_state to drop and must not fail on it.
fresh.exec("PRAGMA user_version = 2");
- expect(migrate(fresh).applied).toEqual(["drop-goal-state"]);
+ expect(migrate(fresh).applied).toEqual(["drop-goal-state", "machines"]);
} finally {
db.close();
fresh.close();
@@ -336,12 +342,16 @@ describe("rollbackTo", () => {
const r = rollbackTo(db, LATEST_VERSION - 2);
expect(r.from).toBe(LATEST_VERSION);
expect(r.to).toBe(LATEST_VERSION - 2);
- expect(r.reverted).toEqual(["drop-goal-state", "messaging-delivery-flags"]);
- const cols = (
- db.prepare("PRAGMA table_info(messaging_bindings)").all() as { name: string }[]
- ).map((c) => c.name);
- expect(cols).not.toContain("render_markdown");
- expect(cols).not.toContain("final_reply_only");
+ // Newest first: the machines tables go, then goal_state comes back.
+ expect(r.reverted).toEqual(["machines", "drop-goal-state"]);
+ const tables = (
+ db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as {
+ name: string;
+ }[]
+ ).map((t) => t.name);
+ expect(tables).not.toContain("machines");
+ expect(tables).not.toContain("machine_project");
+ expect(tables).toContain("goal_state");
} finally {
db.close();
}
@@ -372,6 +382,7 @@ describe("rollbackTo", () => {
migrate(db);
const r = rollbackTo(db, 0);
expect(r.reverted).toEqual([
+ "machines",
"drop-goal-state",
"messaging-delivery-flags",
"messaging-bindings",
diff --git a/packages/server/test/machines-api.test.ts b/packages/server/test/machines-api.test.ts
index 39ae4450..0a72663a 100644
--- a/packages/server/test/machines-api.test.ts
+++ b/packages/server/test/machines-api.test.ts
@@ -12,6 +12,9 @@ import fs from "node:fs";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { MachinesResponse } from "../src/api/types.js";
+import type { DatabaseSync } from "node:sqlite";
+import { openDatabase } from "../src/db/database.js";
+import { MachinesRepo } from "../src/db/repos/machines.js";
import { MachinesService } from "../src/machines/service.js";
import type { MachinesEffects } from "../src/machines/service.js";
import type { RemoteInstallOutcome } from "../src/machines/install-server.js";
@@ -26,6 +29,9 @@ import {
} from "./helpers.js";
import type { TestApp } from "./helpers.js";
+/** Every route is under a Project now; the seeded one every server has. */
+const PROJECT = "default_project";
+
const IDENTITY: RemoteIdentity = {
platform: "linux",
arch: "x64",
@@ -61,18 +67,40 @@ function effects(over: Partial<MachinesEffects> = {}): Partial<MachinesEffects>
describe("machines API", () => {
let t: TestApp;
let admin: ReturnType<typeof apiClient>;
- /** The service's own data root — where it writes the install records this suite reads back. */
+ /** The service's own data root — where the pushable image would live. */
let machinesRoot: string;
+ /** The store the service records installs and memberships in; this suite reads it back. */
+ let machinesRepo: MachinesRepo;
+ let store: DatabaseSync;
const boot = async (over: Partial<MachinesEffects> = {}) => {
machinesRoot = await makeTempRoot();
- t = await createTestApp({ machines: new MachinesService(machinesRoot, effects(over)) });
+ // The store is the service's own here, not the App's, so it needs the Project row the
+ // membership table's foreign key points at — a membership follows its Project out.
+ store = openDatabase(":memory:");
+ store
+ .prepare(
+ "INSERT INTO users (user_id, password_hash, is_admin, created_at) VALUES (?, ?, 1, ?)",
+ )
+ .run("admin", "x", "2026-08-24T00:00:00.000Z");
+ store
+ .prepare("INSERT INTO projects (project_id, owner_user_id, created_at) VALUES (?, ?, ?)")
+ .run("default_project", "admin", "2026-08-24T00:00:00.000Z");
+ machinesRepo = new MachinesRepo(store);
+ t = await createTestApp({
+ machines: new MachinesService(machinesRoot, machinesRepo, effects(over)),
+ });
admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
};
- /** The records file as the service left it on disk. */
- const recordsOnDisk = (): unknown =>
- JSON.parse(fs.readFileSync(path.join(machinesRoot, "machines-installs.json"), "utf8"));
+ /** What the store holds for each machine, as the service left it. */
+ const recordsInStore = (): Record<string, { version: string; at: string }> =>
+ Object.fromEntries(
+ machinesRepo
+ .all()
+ .filter((row) => row.version !== null)
+ .map((row) => [row.address, { version: row.version!, at: row.installedAt! }]),
+ );
afterEach(async () => {
await t.cleanup();
@@ -85,19 +113,23 @@ describe("machines API", () => {
it("is admin-only: a provisioned user gets 403", async () => {
const user = await provisionUser(t.app, "member");
const member = apiClient(t.app, user.cookie);
- expect((await member.get("/api/machines")).status).toBe(403);
- expect((await member.post("/api/machines/ssh:nas/install")).status).toBe(403);
+ expect((await member.get(`/api/projects/${PROJECT}/machines`)).status).toBe(403);
+ expect((await member.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`)).status).toBe(
+ 403,
+ );
});
it("needs a session at all", async () => {
- expect((await t.app.request("/api/machines")).status).toBe(401);
+ expect((await t.app.request(`/api/projects/${PROJECT}/machines`)).status).toBe(401);
});
});
describe("the list", () => {
it("is the ssh config's aliases, with the version this server would push", async () => {
await boot();
- const body = (await (await admin.get("/api/machines")).json()) as MachinesResponse;
+ const body = (await (
+ await admin.get(`/api/projects/${PROJECT}/machines`)
+ ).json()) as MachinesResponse;
expect(body.machines).toEqual([
{ id: "ssh:build-box", alias: "build-box", installed: null },
{ id: "ssh:nas", alias: "nas", installed: null },
@@ -108,14 +140,16 @@ describe("machines API", () => {
it("an empty or unreadable ssh config is a list of none, not an error", async () => {
await boot({ listAliases: () => [] });
- const res = await admin.get("/api/machines");
+ const res = await admin.get(`/api/projects/${PROJECT}/machines`);
expect(res.status).toBe(200);
expect(((await res.json()) as MachinesResponse).machines).toEqual([]);
});
it("reports no image when this server has none to push", async () => {
await boot({ resolvePlan: () => null });
- const body = (await (await admin.get("/api/machines")).json()) as MachinesResponse;
+ const body = (await (
+ await admin.get(`/api/projects/${PROJECT}/machines`)
+ ).json()) as MachinesResponse;
expect(body.imageVersion).toBeNull();
});
});
@@ -135,7 +169,7 @@ describe("machines API", () => {
return { kind: "installed", output: "done", identity: IDENTITY };
},
});
- const started = await admin.post("/api/machines/ssh:nas/install");
+ const started = await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
expect(started.status).toBe(202);
expect(((await started.json()) as MachinesResponse).job).toMatchObject({
machineId: "ssh:nas",
@@ -146,7 +180,9 @@ describe("machines API", () => {
release();
await waitFor(() => t.deps.machines.job()?.running === false);
- const body = (await (await admin.get("/api/machines")).json()) as MachinesResponse;
+ const body = (await (
+ await admin.get(`/api/projects/${PROJECT}/machines`)
+ ).json()) as MachinesResponse;
expect(body.job?.result).toEqual({ ok: true, kind: "installed", version: "9.9.9" });
// The first line is this server's own, the rest are the push's.
expect(body.job?.log[0]).toBe("Installing 9.9.9 on deploy@nas…");
@@ -161,7 +197,7 @@ describe("machines API", () => {
detail: "Permission denied (publickey).",
}),
});
- await admin.post("/api/machines/ssh:nas/install");
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
expect(t.deps.machines.job()?.result).toEqual({
ok: false,
@@ -174,7 +210,7 @@ describe("machines API", () => {
await boot({
install: async () => ({ kind: "already-installed", version: "9.9.9", identity: IDENTITY }),
});
- await admin.post("/api/machines/ssh:nas/install");
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
expect(t.deps.machines.job()?.result).toEqual({
ok: true,
@@ -189,7 +225,7 @@ describe("machines API", () => {
throw new Error("scp vanished");
},
});
- await admin.post("/api/machines/ssh:nas/install");
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
expect(t.deps.machines.job()?.result).toMatchObject({ ok: false, message: "scp vanished" });
});
@@ -198,11 +234,12 @@ describe("machines API", () => {
describe("what stays installed", () => {
/** GET /api/machines, as the page reads it. */
const listed = async () =>
- ((await (await admin.get("/api/machines")).json()) as MachinesResponse).machines;
+ ((await (await admin.get(`/api/projects/${PROJECT}/machines`)).json()) as MachinesResponse)
+ .machines;
it("a successful install is remembered, and is already visible on the first settled poll", async () => {
await boot();
- await admin.post("/api/machines/ssh:nas/install");
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
const machines = await listed();
@@ -216,14 +253,42 @@ describe("machines API", () => {
it("survives the process: a fresh service over the same data root reads it back", async () => {
await boot();
- await admin.post("/api/machines/ssh:nas/install");
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
// A new instance has no job and no memory — only the file. This is the restart case,
// and the hot-push case: the App is rebuilt, the data root is not.
- const reborn = new MachinesService(machinesRoot, effects());
+ const reborn = new MachinesService(machinesRoot, machinesRepo, effects());
expect(reborn.job()).toBeNull();
- expect(reborn.list().find((m) => m.id === "ssh:nas")?.installed).toEqual({
+ expect(reborn.list(PROJECT).find((m) => m.id === "ssh:nas")?.installed).toEqual({
+ version: "9.9.9",
+ at: "2026-08-24T12:00:00.000Z",
+ });
+ });
+
+ it("belongs to the Project that installed it, and to no other", async () => {
+ await boot();
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await waitFor(() => t.deps.machines.job()?.running === false);
+
+ // Another Project sees the same host as installed-but-not-mine: an adoption, not an
+ // install. The record is one machine's, the membership is per Project.
+ const other = t.deps.machines.list("other_project").find((m) => m.id === "ssh:nas");
+ expect(other?.installed).toBeNull();
+ expect(other?.elsewhere).toEqual({ version: "9.9.9", at: "2026-08-24T12:00:00.000Z" });
+ });
+
+ it("release drops the membership and leaves the install alone", async () => {
+ await boot();
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await waitFor(() => t.deps.machines.job()?.running === false);
+
+ const body = (await (
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/release`)
+ ).json()) as MachinesResponse;
+ expect(body.machines.find((m) => m.id === "ssh:nas")?.installed).toBeNull();
+ // Still installed — the program is on that host whoever uses it.
+ expect(recordsInStore()["ssh:nas"]).toEqual({
version: "9.9.9",
at: "2026-08-24T12:00:00.000Z",
});
@@ -233,15 +298,15 @@ describe("machines API", () => {
// The job is one slot, so before the records file existed this is exactly what made an
// installed machine disappear: the second install overwrote the only evidence.
await boot();
- await admin.post("/api/machines/ssh:nas/install");
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
- await admin.post("/api/machines/ssh:build-box/install");
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:build-box/install`);
await waitFor(() => t.deps.machines.job()?.machineId === "ssh:build-box");
await waitFor(() => t.deps.machines.job()?.running === false);
const machines = await listed();
expect(machines.every((m) => m.installed !== null)).toBe(true);
- expect(recordsOnDisk()).toEqual({
+ expect(recordsInStore()).toEqual({
"ssh:nas": { version: "9.9.9", at: "2026-08-24T12:00:00.000Z" },
"ssh:build-box": { version: "9.9.9", at: "2026-08-24T12:00:00.000Z" },
});
@@ -251,16 +316,33 @@ describe("machines API", () => {
await boot({
install: async () => ({ kind: "already-installed", version: "8.8.8", identity: IDENTITY }),
});
- await admin.post("/api/machines/ssh:nas/install");
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
expect((await listed()).find((m) => m.id === "ssh:nas")?.installed?.version).toBe("8.8.8");
});
+ it("a deleted Project takes its machine list with it, and leaves the install alone", async () => {
+ await boot();
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(machinesRepo.members(PROJECT)).toEqual(["ssh:nas"]);
+
+ // The membership row is the Project's and follows it out (ON DELETE CASCADE), so a
+ // Project later recreated under the same id does not inherit a dead one's machines.
+ // The install record is the machine's, and stays.
+ store.prepare("DELETE FROM projects WHERE project_id = ?").run(PROJECT);
+ expect(machinesRepo.members(PROJECT)).toBeNull();
+ expect(recordsInStore()["ssh:nas"]).toEqual({
+ version: "9.9.9",
+ at: "2026-08-24T12:00:00.000Z",
+ });
+ });
+
it("a failed install records nothing", async () => {
await boot({
install: async () => ({ kind: "failed", step: "connect", detail: "no route to host" }),
});
- await admin.post("/api/machines/ssh:nas/install");
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
expect((await listed()).every((m) => m.installed === null)).toBe(true);
expect(fs.existsSync(path.join(machinesRoot, "machines-installs.json"))).toBe(false);
@@ -287,8 +369,10 @@ describe("machines API", () => {
return { kind: "installed", output: "", identity: IDENTITY };
},
});
- expect((await admin.post("/api/machines/ssh:nas/install")).status).toBe(202);
- const second = await admin.post("/api/machines/ssh:build-box/install");
+ expect((await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`)).status).toBe(
+ 202,
+ );
+ const second = await admin.post(`/api/projects/${PROJECT}/machines/ssh:build-box/install`);
expect(second.status).toBe(409);
expect(((await second.json()) as { error: { code: string } }).error.code).toBe(
"install_running",
@@ -299,7 +383,7 @@ describe("machines API", () => {
it("404s a host this server's config does not declare", async () => {
await boot();
- const res = await admin.post("/api/machines/ssh:not-in-config/install");
+ const res = await admin.post(`/api/projects/${PROJECT}/machines/ssh:not-in-config/install`);
expect(res.status).toBe(404);
expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
"unknown_machine",
@@ -309,7 +393,7 @@ describe("machines API", () => {
it("409s when this server carries no install image", async () => {
await boot({ resolvePlan: () => null });
- const res = await admin.post("/api/machines/ssh:nas/install");
+ const res = await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
expect(res.status).toBe(409);
expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
"no_install_image",
@@ -318,7 +402,7 @@ describe("machines API", () => {
it("502s a host ssh itself cannot resolve", async () => {
await boot({ resolveTarget: async () => null });
- const res = await admin.post("/api/machines/ssh:nas/install");
+ const res = await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
expect(res.status).toBe(502);
expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
"unresolvable_host",
diff --git a/packages/server/test/machines-installs.test.ts b/packages/server/test/machines-installs.test.ts
deleted file mode 100644
index 6b0d0e66..00000000
--- a/packages/server/test/machines-installs.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * The install-records file: what this server remembers having installed where. Damage of
- * every shape has to read as "nothing remembered" rather than throw, because this file is a
- * convenience over the ssh config — refusing to serve the machines list because a cache got
- * corrupted would be the worse failure.
- */
-import { describe, expect, it } from "vitest";
-import { parseInstallRecords, withInstallRecord } from "../src/machines/installs.js";
-
-const record = { version: "9.9.9", at: "2026-08-24T12:00:00.000Z" };
-
-describe("parseInstallRecords", () => {
- it("reads back what withInstallRecord wrote", () => {
- const raw = withInstallRecord(null, "ssh:nas", record);
- expect(parseInstallRecords(raw)).toEqual({ "ssh:nas": record });
- });
-
- it("treats absence, emptiness and damage alike: nothing remembered", () => {
- for (const raw of [null, "", " ", "{ not json", "[]", "null", '"a string"']) {
- expect(parseInstallRecords(raw)).toEqual({});
- }
- });
-
- it("drops entries that are not a usable record, keeping the ones that are", () => {
- const raw = JSON.stringify({
- "ssh:good": record,
- "ssh:no-version": { at: record.at },
- "ssh:empty-version": { version: "", at: record.at },
- "ssh:no-date": { version: "9.9.9" },
- "ssh:not-an-object": 7,
- "ssh:an-array": [record],
- });
- expect(parseInstallRecords(raw)).toEqual({ "ssh:good": record });
- });
-});
-
-describe("withInstallRecord", () => {
- it("adds without disturbing the others — the whole point of a per-machine file", () => {
- let raw = withInstallRecord(null, "ssh:nas", record);
- raw = withInstallRecord(raw, "ssh:build-box", { version: "8.8.8", at: record.at });
- expect(parseInstallRecords(raw)).toEqual({
- "ssh:nas": record,
- "ssh:build-box": { version: "8.8.8", at: record.at },
- });
- });
-
- it("replaces one machine's record in place", () => {
- const raw = withInstallRecord(withInstallRecord(null, "ssh:nas", record), "ssh:nas", {
- version: "10.0.0",
- at: "2026-08-25T00:00:00.000Z",
- });
- expect(parseInstallRecords(raw)["ssh:nas"]?.version).toBe("10.0.0");
- });
-
- it("null forgets one machine and leaves the rest", () => {
- let raw = withInstallRecord(null, "ssh:nas", record);
- raw = withInstallRecord(raw, "ssh:build-box", record);
- expect(parseInstallRecords(withInstallRecord(raw, "ssh:nas", null))).toEqual({
- "ssh:build-box": record,
- });
- });
-
- it("writes over damage rather than propagating it", () => {
- expect(parseInstallRecords(withInstallRecord("{ not json", "ssh:nas", record))).toEqual({
- "ssh:nas": record,
- });
- });
-});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 9fa5013d..929cffe6 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -1175,14 +1175,18 @@ export const importAgent = (projectId: string, agentId: string, body: AgentImpor
* job. The Machines page polls this while a job runs — the progress lines live on the job,
* not on the event channel, because they belong to the one page that is waiting for them.
*/
-export const getMachines = () => apiFetch<MachinesResponse>("/api/machines");
+export const getMachines = (projectId: string) =>
+ apiFetch<MachinesResponse>(`/api/projects/${encodeURIComponent(projectId)}/machines`);
-/** Starts an install (202, long-running); the returned body already carries the new job. */
-export const installOnMachine = (machineId: string) =>
- apiFetch<MachinesResponse>(`/api/machines/${encodeURIComponent(machineId)}/install`, {
- method: "POST",
- body: {},
- });
+/**
+ * Starts an install (202, long-running) and gives the machine to this Project; the returned
+ * body already carries the new job.
+ */
+export const installOnMachine = (projectId: string, machineId: string) =>
+ apiFetch<MachinesResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/machines/${encodeURIComponent(machineId)}/install`,
+ { method: "POST", body: {} },
+ );
// Version & self-update ----------------------------------------------------------------
diff --git a/packages/web/src/features/machines/machines-page.tsx b/packages/web/src/features/machines/machines-page.tsx
index 315052fa..acc37646 100644
--- a/packages/web/src/features/machines/machines-page.tsx
+++ b/packages/web/src/features/machines/machines-page.tsx
@@ -32,6 +32,7 @@ import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { useDocumentTitle } from "../../lib/use-document-title";
+import { useProject } from "../../state/project";
import { formatDateTime } from "../../lib/format";
import { toneInk, toneStrip } from "../../lib/tone";
import type { Tone } from "../../lib/tone";
@@ -67,6 +68,11 @@ function verdictLine(verdict: MachineVerdict): { text: string; tone: Tone } {
export function MachinesPage() {
useDocumentTitle(S.machines.pageTitle);
+ // Machines belong to the Project, like every other row in this nav group: switching
+ // Projects switches which machines are listed, and installing here gives the machine to
+ // THIS Project.
+ const { currentProject } = useProject();
+ const projectId = currentProject?.projectId ?? null;
const [state, setState] = useState<MachinesResponse | null>(null);
const [error, setError] = useState<string | null>(null);
/** True while a POST has not come back yet — the server has no job to report in that window. */
@@ -82,13 +88,14 @@ export function MachinesPage() {
};
const load = useCallback(async () => {
+ if (projectId === null) return; // No Project chosen yet: nothing to list machines for.
try {
- setState(await api.getMachines());
+ setState(await api.getMachines(projectId));
setError(null);
} catch (err) {
setError(apiErrorText(err));
}
- }, []);
+ }, [projectId]);
useEffect(() => {
void load();
@@ -125,10 +132,10 @@ export function MachinesPage() {
const selected = machines.find((machine) => machine.id === selectedId) ?? null;
const install = async () => {
- if (selectedId === null) return;
+ if (selectedId === null || projectId === null) return;
setStarting(true);
try {
- setState(await api.installOnMachine(selectedId));
+ setState(await api.installOnMachine(projectId, selectedId));
setError(null);
} catch (err) {
setError(apiErrorText(err));