A local-first multi-agent app development platform, built on PenguinHarness
test(server): cut what db-upgrade, session-index, machines-api and harness-history write to disk (#934)
Yaowei Zheng7f9f1e475be5
diff --git a/packages/server/test/db-upgrade.test.ts b/packages/server/test/db-upgrade.test.tsindex e6a6fd08..0c9bb531 100644--- a/packages/server/test/db-upgrade.test.ts+++ b/packages/server/test/db-upgrade.test.ts@@ -12,9 +12,26 @@* reinstalls the previous release). Nothing records a schema version, so both properties rest* on every schema change staying additive — and the downgrade one on more than that, which the* last suite pins next to the tolerance rather than leaving it implied.+ *+ * Scenarios:+ * - Given a web.db formed before a column existed, when it is opened, the column is added, the+ * old rows read back with the grandfathered value, and the column takes writes at once+ * (sessions' client / has_trace; each messaging_bindings column added since 0.2.5, with+ * render_markdown the one that starts ON).+ * - Given a database this build already formed, a reopen changes nothing.+ * - Given sessions formed before last_active_at, the open backfills it once from the last+ * request (else created_at); a later open neither re-runs the backfill nor rewrites a row.+ * - Given a stamp, a write never moves it backwards, and a write for one Session touches no+ * other row; both insert paths store a cell even when the caller leaves it out.+ * - Given a database formed before messaging_bindings existed, the open creates it and its+ * index and keeps the rows already there.+ * - Given the retired unique account index, the open drops it, so one bot account can be saved+ * on two Sessions, and an enabled binding still holds its account afterwards.+ * - Given a database from a newer build, unknown tables, columns and indexes survive the open;+ * a defaultless NOT NULL column or a new unique index still breaks this build's writes.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { mkdtemp, rm } from "node:fs/promises";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { copyFile, mkdtemp, rm } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import type { DatabaseSync } from "node:sqlite";@@ -28,7 +45,18 @@ import { wire } from "@prismshadow/penguin-core/kernel";const sqlite = process.getBuiltinModule("node:sqlite");let dir: string;-+/** A database this build formed with a fresh open — once per file, since forming one commits every DDL statement of SCHEMA_SQL on its own. */+let formedDir: string;+let formed: string;++beforeAll(async () => {+ formedDir = await mkdtemp(path.join(tmpdir(), "penguin-db-formed-"));+ formed = path.join(formedDir, "web.db");+ openDatabase(formed).close();+});+afterAll(async () => {+ await rm(formedDir, { recursive: true, force: true, maxRetries: 10 });+});beforeEach(async () => {dir = await mkdtemp(path.join(tmpdir(), "penguin-db-upgrade-"));});@@ -38,6 +66,30 @@ afterEach(async () => {await rm(dir, { recursive: true, force: true, maxRetries: 10 });});+/** The case's own copy of the database this build formed. */+async function copyOfFormed(name: string): Promise<string> {+ const dbPath = path.join(dir, name);+ await copyFile(formed, dbPath);+ return dbPath;+}++/**+ * Writes the file another build left behind, in ONE transaction. The shape is what an open+ * reads; how durably the fixture was written is not. Outside a transaction every statement+ * of SCHEMA_SQL commits on its own — a journal file created, synced and deleted forty-odd+ * times per seed — which on a Windows runner costs seconds per case.+ */+function seedDatabase(dbPath: string, build: (db: DatabaseSync) => void): void {+ const db = new sqlite.DatabaseSync(dbPath);+ try {+ db.exec("BEGIN");+ build(db);+ db.exec("COMMIT");+ } finally {+ db.close();+ }+}+/*** Seeds a database in the shape it had **before** last_active_at existed, derived from the* real SCHEMA_SQL rather than a hand-copied DDL replica (a copy silently forks from the@@ -45,16 +97,13 @@ afterEach(async () => {* things this change introduced — the column, and the reshaped usage index.*/function seedPreLastActiveDb(dbPath: string, seed: (db: DatabaseSync) => void): void {- const db = new sqlite.DatabaseSync(dbPath);- try {+ seedDatabase(dbPath, (db) => {db.exec(SCHEMA_SQL);db.exec("ALTER TABLE sessions DROP COLUMN last_active_at");db.exec("DROP INDEX IF EXISTS idx_usage_session_ts");db.exec("CREATE INDEX IF NOT EXISTS idx_usage_session ON usage_records(session_id)");seed(db);- } finally {- db.close();- }+ });}/** Reads the stored cell directly, bypassing mapRow's coalesce (which would mask a NULL). */@@ -69,26 +118,26 @@ describe("openDatabase column upgrade", () => {it("adds client/has_trace to a sessions table formed before the columns existed", () => {const dbPath = path.join(dir, "web.db");// A database formed by the pre-#139 schema: sessions without client / has_trace.- const old = new sqlite.DatabaseSync(dbPath);- old.exec(`CREATE TABLE sessions (- session_id TEXT PRIMARY KEY,- project_id TEXT NOT NULL,- agent_id TEXT NOT NULL,- provider TEXT NOT NULL,- model_id TEXT NOT NULL,- workspace TEXT NOT NULL,- approval_mode TEXT NOT NULL DEFAULT 'allow-all',- title TEXT,- archived_at TEXT,- created_at TEXT NOT NULL- );`);- old- .prepare(- `INSERT INTO sessions (session_id, project_id, agent_id, provider, model_id, workspace, created_at)- VALUES ('session-legacy', 'p1', 'a1', 'custom', 'm1', '/w', '2026-01-01T00:00:00.000Z')`,- )- .run();- old.close();+ seedDatabase(dbPath, (old) => {+ old.exec(`CREATE TABLE sessions (+ session_id TEXT PRIMARY KEY,+ project_id TEXT NOT NULL,+ agent_id TEXT NOT NULL,+ provider TEXT NOT NULL,+ model_id TEXT NOT NULL,+ workspace TEXT NOT NULL,+ approval_mode TEXT NOT NULL DEFAULT 'allow-all',+ title TEXT,+ archived_at TEXT,+ created_at TEXT NOT NULL+ );`);+ old+ .prepare(+ `INSERT INTO sessions (session_id, project_id, agent_id, provider, model_id, workspace, created_at)+ VALUES ('session-legacy', 'p1', 'a1', 'custom', 'm1', '/w', '2026-01-01T00:00:00.000Z')`,+ )+ .run();+ });const db = openDatabase(dbPath);try {@@ -139,8 +188,7 @@ describe("openDatabase column upgrade", () => {// A database formed by 0.2.7 or earlier: messaging_bindings exists (it shipped in 0.2.5)// but has no redelivery watermark. Derived from the real SCHEMA_SQL, then the one column// this change adds is dropped back off, so the fixture cannot fork from the schema.- const old = new sqlite.DatabaseSync(dbPath);- try {+ seedDatabase(dbPath, (old) => {old.exec(SCHEMA_SQL);old.exec("ALTER TABLE messaging_bindings DROP COLUMN last_inbound_message_id");old@@ -151,9 +199,7 @@ describe("openDatabase column upgrade", () => {VALUES ('session-legacy-binding', 'feishu', 'cli_app', '{}', 1, 'oc_old', 1, ?, ?)`,).run("2026-01-01T00:00:00.000Z", "2026-01-01T00:00:00.000Z");- } finally {- old.close();- }+ });const db = openDatabase(dbPath);try {@@ -177,10 +223,8 @@ describe("openDatabase column upgrade", () => {}});- it("is idempotent: reopening an already-upgraded database changes nothing", () => {- const dbPath = path.join(dir, "web.db");- openDatabase(dbPath).close();- const db = openDatabase(dbPath);+ it("is idempotent: reopening an already-upgraded database changes nothing", async () => {+ const db = openDatabase(await copyOfFormed("web.db"));try {const cols = db.prepare("PRAGMA table_info(sessions)").all() as { name: string }[];expect(cols.filter((c) => c.name === "client")).toHaveLength(1);@@ -350,14 +394,11 @@ describe("openDatabase table and index upgrades", () => {* drop exactly what that change introduced (dropping the table takes its index with it).*/function seedPreMessagingDb(dbPath: string, seed: (db: DatabaseSync) => void): void {- const db = new sqlite.DatabaseSync(dbPath);- try {+ seedDatabase(dbPath, (db) => {db.exec(SCHEMA_SQL);db.exec("DROP TABLE messaging_bindings");seed(db);- } finally {- db.close();- }+ });}it("creates messaging_bindings on a database formed before it existed, keeping existing rows", () => {@@ -424,35 +465,17 @@ describe("openDatabase table and index upgrades", () => {column: string,seed: (db: DatabaseSync) => void,): void {- const db = new sqlite.DatabaseSync(dbPath);- try {+ seedDatabase(dbPath, (db) => {db.exec(SCHEMA_SQL);db.exec(`ALTER TABLE messaging_bindings DROP COLUMN ${column}`);seed(db);- } finally {- db.close();- }- }-- /**- * Seeds a database in the shape it had before messaging_bindings.render_markdown existed:- * today's schema with that column dropped. Same derivation rule as the helpers around it.- */- function seedPreRenderMarkdownDb(dbPath: string, seed: (db: DatabaseSync) => void): void {- const db = new sqlite.DatabaseSync(dbPath);- try {- db.exec(SCHEMA_SQL);- db.exec("ALTER TABLE messaging_bindings DROP COLUMN render_markdown");- seed(db);- } finally {- db.close();- }+ });}it("adds render_markdown to a messaging_bindings formed before it, existing rows ON", () => {const dbPath = path.join(dir, "web-md.db");const ts = "2026-01-01T00:00:00.000Z";- seedPreRenderMarkdownDb(dbPath, (old) => {+ seedPreDeliveryColumnDb(dbPath, "render_markdown", (old) => {old.prepare(`INSERT INTO messaging_bindings@@ -595,17 +618,14 @@ describe("openDatabase table and index upgrades", () => {* the schema it is imitating.*/function seedUniqueAccountIndexDb(dbPath: string, seed: (db: DatabaseSync) => void): void {- const db = new sqlite.DatabaseSync(dbPath);- try {+ seedDatabase(dbPath, (db) => {db.exec(SCHEMA_SQL);db.exec("DROP INDEX idx_messaging_by_account");db.exec("CREATE UNIQUE INDEX idx_messaging_account ON messaging_bindings(channel, account_id)",);seed(db);- } finally {- db.close();- }+ });}it("drops the retired unique account index, so one bot account fits on two Sessions", () => {@@ -744,8 +764,8 @@ describe("openDatabase tolerates a database from a newer build", () => {return SCHEMA_SQL.replace(anchor, `${anchor}\n ${ddl},`);}- it("leaves unknown tables, columns and indexes intact across an open", () => {- const dbPath = path.join(dir, "web.db");+ it("leaves unknown tables, columns and indexes intact across an open", async () => {+ const dbPath = await copyOfFormed("web.db");const current = openDatabase(dbPath);wire(SessionsRepo, { db: current }).insert({sessionId: "s1",@@ -811,7 +831,7 @@ describe("openDatabase tolerates a database from a newer build", () => {}});- it("a defaultless NOT NULL column or a new unique index still breaks this build's writes", () => {+ it("a defaultless NOT NULL column or a new unique index still breaks this build's writes", async () => {// Neither change removes anything, so both pass an "is it additive?" reading — and both// leave this build opening the database happily and then failing on its first write. The// open is where a version stamp would be checked, so the failure surfaces at an arbitrary@@ -821,12 +841,9 @@ describe("openDatabase tolerates a database from a newer build", () => {// COLUMN, which is what makes every ensureColumn entry safe — but a newer build that// forms the database writes CREATE TABLE, where the shape is perfectly legal.const formedByNewer = path.join(dir, "formed-by-newer.db");- const newer = new sqlite.DatabaseSync(formedByNewer);- try {- newer.exec(schemaWithExtraSessionsColumn("future_required TEXT NOT NULL"));- } finally {- newer.close();- }+ seedDatabase(formedByNewer, (newer) =>+ newer.exec(schemaWithExtraSessionsColumn("future_required TEXT NOT NULL")),+ );const opened = openDatabase(formedByNewer);try {expect(() =>@@ -849,7 +866,7 @@ describe("openDatabase tolerates a database from a newer build", () => {// 2. A unique index over columns this build already writes. Nothing is added to any row,// yet rows this build creates today stop being insertable.- const withUniqueIndex = path.join(dir, "unique-index.db");+ const withUniqueIndex = await copyOfFormed("unique-index.db");const newerIndexed = openDatabase(withUniqueIndex);try {newerIndexed.exec(diff --git a/packages/server/test/harness-history.test.ts b/packages/server/test/harness-history.test.tsindex 988c0105..78f479fc 100644--- a/packages/server/test/harness-history.test.ts+++ b/packages/server/test/harness-history.test.ts@@ -3,6 +3,21 @@* commit together with the booting platform's own interface table, under* <root>/harness-history/ — so the record is complete on any runtime old enough to boot* the platform, and never depends on the runtime knowing about it.+ *+ * Scenarios:+ * - Given a boot, one line is recorded per version with this platform's table, newest first;+ * the same version booting again is the same line.+ * - Given another platform's line for the committed version, the boot leaves it alone.+ * - Given two committed versions, rolling back hands the runtime's upgrade channel the kept+ * body and tells live clients to reload; a refused push is reported on the next read.+ * - Given a boot whose commit has not landed, nothing is recorded until it has, and a+ * generation put back never records.+ * - Given concurrent records, one line is written; an unchanged line is not rewritten.+ * - Given more versions than kept, the newest KEEP_VERSIONS keep their artifacts and the newest+ * HISTORY_KEEP keep their lines; a corrupt file degrades to what still parses.+ * - Given two interface tables, the diff names what appeared, vanished or changed.+ * - Given the route, a fresh root already shows this boot, and a committed version is shown+ * current with the runtime's provenance.*/import { afterEach, describe, expect, it } from "vitest";import fs from "node:fs/promises";@@ -94,8 +109,20 @@ function bootedAt(root: string) {}describe("harness history store", () => {- it("records a boot once per version, with this platform's own table, newest first", async () => {+ const roots: string[] = [];+ const tempRoot = async () => {const root = await makeTempRoot();+ roots.push(root);+ return root;+ };+ afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true, maxRetries: 10 })),+ );+ });++ it("records a boot once per version, with this platform's own table, newest first", async () => {+ const root = await tempRoot();const store = storeAt(root);// Nothing committed yet: a packaged boot, identified by its table.await store.record();@@ -128,7 +155,7 @@ describe("harness history store", () => {});it("never overwrites another platform's line: the boot before a push sees the previous commit", async () => {- const root = await makeTempRoot();+ const root = await tempRoot();// The previous platform recorded version 1 with ITS table …await commit(root, 1);await fs.mkdir(path.join(root, "harness-history"), { recursive: true });@@ -161,7 +188,7 @@ describe("harness history store", () => {});it("keeps a committed version's body and hands it back to the runtime's own upgrade channel", async () => {- const root = await makeTempRoot();+ const root = await tempRoot();const store = storeAt(root);await commit(root, 1, { repo: "r", revision: "v1" });await store.record();@@ -204,7 +231,7 @@ describe("harness history store", () => {});it("a push the runtime refuses is reported on the next read, in the runtime's words", async () => {- const root = await makeTempRoot();+ const root = await tempRoot();const store = storeAt(root);await commit(root, 1);await store.record();@@ -231,7 +258,7 @@ describe("harness history store", () => {it("records a boot only once the runtime's commit has landed, and never after being put back", async () => {// Version 1 is committed and the platform booting is version 2's: while its boot is in// flight harness.json still names version 1, and no line may be written for it.- const root = await makeTempRoot();+ const root = await tempRoot();await commit(root, 1);let commitLanded!: () => void;landed = () =>@@ -260,7 +287,7 @@ describe("harness history store", () => {});it("writes one record at a time, and rewrites nothing when the line is unchanged", async () => {- const root = await makeTempRoot();+ const root = await tempRoot();const store = storeAt(root);await commit(root, 1);await Promise.all([store.record(), store.record(), store.list(), store.record()]);@@ -274,7 +301,7 @@ describe("harness history store", () => {});it("keeps the newest KEEP_VERSIONS versions' artifacts", async () => {- const root = await makeTempRoot();+ const root = await tempRoot();const store = storeAt(root);for (let i = 0; i < KEEP_VERSIONS + 2; i++) {await commit(root, i);@@ -286,18 +313,38 @@ describe("harness history store", () => {expect(dirs).toContain(`p${KEEP_VERSIONS + 1}-c${KEEP_VERSIONS + 1}-w${KEEP_VERSIONS + 1}`);});- it("keeps HISTORY_KEEP entries and degrades a corrupt file to what still parses", async () => {- const root = await makeTempRoot();+ it("keeps the newest HISTORY_KEEP entries, and degrades a corrupt file to what still parses", async () => {+ const root = await tempRoot();const store = storeAt(root);- for (let i = 0; i < HISTORY_KEEP + 3; i++) {+ const file = path.join(root, "harness-history", "history.json");+ await commit(root, 0);+ await store.record();+ // A history already at the cap, in the store's own format: its one line, then older+ // versions under bundles of their own.+ const [line] = JSON.parse(await fs.readFile(file, "utf8")) as Array<Record<string, unknown>>;+ const older = Array.from({ length: HISTORY_KEEP - 1 }, (_, i) => ({+ ...line,+ bundles: { platform: `store/platform/old${i}.mjs`, cli: null, web: null },+ }));+ await fs.writeFile(file, JSON.stringify([line, ...older]));+ for (let i = 1; i <= 3; i++) {await commit(root, i);await store.record();}- expect(await store.entries()).toHaveLength(HISTORY_KEEP);- await fs.writeFile(path.join(root, "harness-history", "history.json"), "{ not json");+ const platforms = (await store.entries()).map((e) => e.bundles.platform);+ expect(platforms).toHaveLength(HISTORY_KEEP);+ expect(platforms.slice(0, 4)).toEqual([+ "store/platform/p3.mjs",+ "store/platform/p2.mjs",+ "store/platform/p1.mjs",+ "store/platform/p0.mjs",+ ]);+ // The three oldest lines made room for them.+ expect(platforms.at(-1)).toBe(`store/platform/old${HISTORY_KEEP - 5}.mjs`);+ await fs.writeFile(file, "{ not json");expect(await store.entries()).toEqual([]);await fs.writeFile(- path.join(root, "harness-history", "history.json"),+ file,JSON.stringify([{ pushedAt: "x" }, { bundles: { platform: "store/platform/z.mjs" } }]),);expect((await store.entries()).map((e) => e.bundles.platform)).toEqual([diff --git a/packages/server/test/machines-api.test.ts b/packages/server/test/machines-api.test.tsindex f2653c3f..c74a743c 100644--- a/packages/server/test/machines-api.test.ts+++ b/packages/server/test/machines-api.test.ts@@ -7,12 +7,40 @@* read the developer's own ~/.ssh/config and spawn ssh against whatever it names. What the* push actually does over ssh is covered by machines-push.test.ts, against a fake ssh* binary and the real installOnRemote.+ *+ * One App serves the file; each case builds its own service (data root, store, effects),+ * which the App's machines node forwards to. The one case about the App's own boot boots+ * an App of its own.+ *+ * Scenarios:+ * - Given a member, a stranger or an admin, only the admin reaches the routes and a machine's+ * proxied API.+ * - Given an ssh config, the list is its aliases with the version this server would push; an+ * empty or unreadable config leaves this machine alone, and no image is said as such.+ * - Given an install, the job narrates, finishes and is remembered per Project; every failure+ * (far-side words, a refused build, a throw, an unwritten version) ends the job and records+ * nothing; a machine already on this build is a result, and still gets pushed state.+ * - Given installed machines, status is probed only when asked, once per round, and a stopped+ * server or an unreachable machine is an answer; a restart follows an install only where a+ * server was running.+ * - Given a connect, the remembered port is the one used, a dead server is started, a live one+ * is left alone, and a held session is re-held at start() and at the App's boot — never+ * after a disconnect.+ * - Given a model edit during a sync, it is written once afterwards, never dropped.+ * - Given a connected machine, its directories are listed through the alias holding it.+ * - Given a probe, the machine's own id is learned and kept; this machine's id is minted once.+ * - Given a batch to use, machines work side by side and each ends connected; stop using keeps+ * the install.+ * - Given an ssh-config edit, a new block is appended, this app's block is rewritten in place,+ * and a hand-written one is refused.+ * - Given a refusal decidable without ssh (self-install, a second install, an unknown host, no+ * image), nothing runs.*/import fs from "node:fs";import http from "node:http";import type { AddressInfo } from "node:net";import path from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";import type { MachinesUseResponse, MachinesResponse } from "../src/api/types.js";import type { DatabaseSync } from "node:sqlite";import { openDatabase } from "../src/db/database.js";@@ -32,6 +60,7 @@ import {waitFor,} from "./helpers.js";import type { TestApp } from "./helpers.js";+import { forwardingTo } from "./fixtures/forwarding.js";/** Every route is under a Project; the seeded one every server has. */const PROJECT = "default_project";@@ -100,7 +129,12 @@ describe("machines API", () => {let machinesRoot: string;let machinesRepo: MachinesRepo;let store: DatabaseSync;+ /** The case's service: what the App's routes and `t.deps.machines` reach. */+ let service: MachinesService;+ /** Every service built so far (the App's first included), retired after the case. */+ const built: Array<{ service: MachinesService; store: DatabaseSync; root: string }> = [];+ /** Builds the case's service over a fresh data root and store, with its effects overridden. */const boot = async (over: Partial<MachinesEffects> = {}, layout?: RemoteLayout) => {connected.clear();machinesRoot = await makeTempRoot();@@ -116,19 +150,36 @@ describe("machines API", () => {.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,- LOCAL_ID,- machinesRepo,- effects(over),- undefined,- layout,- ),- });- admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);+ service = new MachinesService(+ machinesRoot,+ LOCAL_ID,+ machinesRepo,+ effects(over),+ undefined,+ layout,+ );+ built.push({ service, store, root: machinesRoot });};+ beforeAll(async () => {+ await boot();+ t = await createTestApp({ machines: forwardingTo(() => service) });+ admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });+ afterEach(async () => {+ for (const retired of built.splice(0)) {+ // Its jobs finish before the next case's service takes over, so nothing a job does+ // lands in another case.+ await waitFor(() => retired.service.jobs().every((job) => !job.running && !job.queued));+ retired.service.stop();+ retired.store.close();+ fs.rmSync(retired.root, { recursive: true, force: true });+ }+ });+/** What the store holds for each machine, as the service left it. */const recordsInStore = (): Record<string, { version: string; at: string }> =>Object.fromEntries(@@ -138,17 +189,14 @@ describe("machines API", () => {.map((row) => [row.address, { version: row.version!, at: row.installedAt! }]),);- afterEach(async () => {- await t.cleanup();- fs.rmSync(machinesRoot, { recursive: true, force: true });- });-describe("permission", () => {+ let member: ReturnType<typeof apiClient>;+ beforeAll(async () => {+ member = apiClient(t.app, (await provisionUser(t.app, "member")).cookie);+ });beforeEach(() => boot());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/projects/default_project/machines")).status).toBe(403);expect((await member.post("/api/projects/default_project/machines/ssh:nas/install")).status,@@ -164,8 +212,6 @@ describe("machines API", () => {// the user on the context, and an ungated prefix left the handler reading isAdmin off// nothing — a 500, for the admin who was allowed and the stranger who was not.expect((await t.app.request("/server/tXIvjrl0pgKa5_dD/api/version")).status).toBe(401);- const user = await provisionUser(t.app, "member");- const member = apiClient(t.app, user.cookie);expect((await member.get("/server/tXIvjrl0pgKa5_dD/api/version")).status).toBe(403);// An admin reaches the proxy itself, which answers for a machine it does not hold.const res = await admin.get("/server/tXIvjrl0pgKa5_dD/api/version");@@ -1041,42 +1087,28 @@ describe("machines API", () => {// What a hot push or a restart finds: a record written by the generation before. Nobody// calls start() here — the Startup component does, as the App comes up.const heldNow: string[] = [];- connected.clear();- machinesRoot = await makeTempRoot();- 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);+ await boot({+ hold: async (target) => {+ heldNow.push(target.alias);+ connected.add(`ssh:${target.alias}`);+ return { ok: true, session: { pid: process.pid, socksPort: 1 } };+ },+ });machinesRepo.patch("ssh:nas", {version: "9.9.9",installedAt: "2026-08-01T00:00:00.000Z",sessionPid: 424242,remotePort: 7364,});- t = await createTestApp({- machines: new MachinesService(- machinesRoot,- LOCAL_ID,- machinesRepo,- effects({- hold: async (target) => {- heldNow.push(target.alias);- connected.add(`ssh:${target.alias}`);- return { ok: true, session: { pid: process.pid, socksPort: 1 } };- },- }),- ),- });- admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);- await waitFor(() => heldNow.length > 0);- expect(heldNow).toEqual(["nas"]);- expect(machinesRepo.get("ssh:nas")?.sessionPid).toBe(process.pid);+ // An App of its own, booted over that record: its boot is the behaviour.+ const booted = await createTestApp({ machines: service });+ try {+ await waitFor(() => heldNow.length > 0);+ expect(heldNow).toEqual(["nas"]);+ expect(machinesRepo.get("ssh:nas")?.sessionPid).toBe(process.pid);+ } finally {+ await booted.cleanup();+ }});it("disconnect clears the record, so a later boot leaves the machine alone", async () => {diff --git a/packages/server/test/session-index.test.ts b/packages/server/test/session-index.test.tsindex c0025b9c..b9d0b1f1 100644--- a/packages/server/test/session-index.test.ts+++ b/packages/server/test/session-index.test.ts@@ -2,10 +2,32 @@* Integration tests for the Session index: creation (default model / workspace* guard), listing (DB union Trace directory discovery), PATCH approval mode and* thinking level, and createdAt parsing.+ *+ * One app and one Project serve the file; each case works in an Agent of its own, which it+ * deletes on the way out.+ *+ * Scenarios:+ * - Given no default model, or a model with no usable credential, creating a Session is a 400+ * with its own code; half a model reference is a 400, never completed for the caller.+ * - Given a configured model, a created Session gets a temporary Workspace inside its Agent,+ * allow-all, a lastActiveAt equal to its creation stored on the row, and shows in the list;+ * an explicit Workspace only has to exist.+ * - Given a Session's origin, it is read from session_meta, never the row: a schedule's+ * Session, one only a Trace head knows after a restart, and adopted ones (junk narrowed).+ * - Given many rows, the list pages newest first, filters by sidebar category, by Workspace+ * group and by organization, and its counts stay whole-Agent; junk parameters are 400s.+ * - Given an unmanaged Trace, the startup sweep adopts it once as a client:'cli' row.+ * - Given a client hint, 'cli' or 'web' is stored and listed; 'org' cannot be claimed.+ * - Given a PATCH, the answer is the row after the write; approval mode and thinking level+ * persist; bad values are 400s.+ * - Given a DELETE, the row and every Trace shard go and the list does not resurrect it; the+ * Workspace directory stays.+ * - Given a Trace, the single GET names its latest shard; list rows do not.+ * - Given a goal, a malformed budget, an image-only objective or a file attachment is a 400.*/import fs from "node:fs/promises";import path from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { sessionMeta, userText } from "@prismshadow/penguin-core";import type { OmniMessage, SessionMetaPayload } from "@prismshadow/penguin-core";import type {@@ -22,9 +44,12 @@ describe("session-index", () => {let t: TestApp;let api: ReturnType<typeof apiClient>;let projectId: string;- const base = () => `/api/projects/${projectId}/agents/default_agent/sessions`;+ /** The case's own Agent: every list here is one Agent's, so no case sees another's rows. */+ let agentId: string;+ let cases = 0;+ const base = () => `/api/projects/${projectId}/agents/${agentId}/sessions`;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const { cookie } = await provisionUser(t.app, "alice");api = apiClient(t.app, cookie);@@ -33,9 +58,18 @@ describe("session-index", () => {).json()) as ProjectCreateResponse;projectId = created.project.projectId;});- afterEach(async () => {+ afterAll(async () => {await t.cleanup();});+ beforeEach(async () => {+ agentId = `case_${++cases}`;+ expect((await api.post(`/api/projects/${projectId}/agents`, { agentId })).status).toBe(201);+ });+ afterEach(async () => {+ // Deleting the Agent takes its index rows and Traces with it, so a retried case starts+ // from nothing, the fixed session ids below included.+ await api.delete(`/api/projects/${projectId}/agents/${agentId}`);+ });async function configureModels(): Promise<void> {const res = await api.put(`/api/projects/${projectId}/models`, {@@ -95,9 +129,7 @@ describe("session-index", () => {expect(session.status).toBe("idle");expect(session.hasTrace).toBe(false);// The temporary Workspace lives inside this Agent's workspaces directory.- expect(session.workspace).toContain(- path.join(projectId, "agents", "default_agent", "workspaces"),- );+ expect(session.workspace).toContain(path.join(projectId, "agents", agentId, "workspaces"));const list = (await (await api.get(base())).json()) as SessionsResponse;expect(list.sessions.map((s) => s.sessionId)).toContain(session.sessionId);@@ -149,7 +181,7 @@ describe("session-index", () => {// The scheduler goes through SessionService.createSession directly (no HTTP route exposes source).const info = await t.deps.sessionService.createSession({projectId,- agentId: "default_agent",+ agentId,source: "schedule",});expect(info.source).toBe("schedule");@@ -175,7 +207,7 @@ describe("session-index", () => {t.deps.sessionsRepo.insert({sessionId: sid,projectId,- agentId: "default_agent",+ agentId,provider: "custom",modelId: "m-x",workspace: "/tmp/w-restart",@@ -194,7 +226,7 @@ describe("session-index", () => {workspace: "/tmp/w-restart",source: "subagent",};- await writeTraceFile(t.root, projectId, "default_agent", "2026-07-02", sid, 1, [+ await writeTraceFile(t.root, projectId, agentId, "2026-07-02", sid, 1, [sessionMeta(meta),userText("child work"),]);@@ -219,7 +251,7 @@ describe("session-index", () => {workspace: "/tmp/w-cli",source: "schedule",};- await writeTraceFile(t.root, projectId, "default_agent", "2026-07-03", adopted, 1, [+ await writeTraceFile(t.root, projectId, agentId, "2026-07-03", adopted, 1, [sessionMeta(sourced),userText("adopted"),]);@@ -230,7 +262,7 @@ describe("session-index", () => {session_id: junk,source: "weird-origin",} as unknown as SessionMetaPayload;- await writeTraceFile(t.root, projectId, "default_agent", "2026-07-03", junk, 1, [+ await writeTraceFile(t.root, projectId, agentId, "2026-07-03", junk, 1, [sessionMeta(junkMeta),userText("junk"),]);@@ -246,7 +278,7 @@ describe("session-index", () => {const mk = (n: number) => ({sessionId: `session-2026-07-0${n}-08-00-00-aaaa000${n}`,projectId,- agentId: "default_agent",+ agentId,provider: "custom",modelId: "m-page",workspace: `/tmp/w-${n}`,@@ -292,7 +324,7 @@ describe("session-index", () => {(await t.deps.sessionService.createSession({projectId,- agentId: "default_agent",+ agentId,source: "schedule",})).sessionId;@@ -305,7 +337,7 @@ describe("session-index", () => {t.deps.sessionsRepo.insert({sessionId: subagentE,projectId,- agentId: "default_agent",+ agentId,provider: "custom",modelId: "m-x",workspace: "/tmp/w-sub",@@ -314,7 +346,7 @@ describe("session-index", () => {createdAt: "2026-07-02T09:30:00.000Z",lastActiveAt: "2026-07-02T09:30:00.000Z",});- await writeTraceFile(t.root, projectId, "default_agent", "2026-07-02", subagentE, 1, [+ await writeTraceFile(t.root, projectId, agentId, "2026-07-02", subagentE, 1, [sessionMeta({session_id: subagentE,model_id: "m-x",@@ -420,12 +452,12 @@ describe("session-index", () => {it("workspaceGroup pages one Workspace group's own stream, temporary workspaces as one group", async () => {// Rows are inserted straight into the index: the group filter reads the stored path, and// going through create() would only add realpath validation this has nothing to say about.- const agentDir = `${t.root}/${projectId}/agents/default_agent`;+ const agentDir = `${t.root}/${projectId}/agents/${agentId}`;const seed = async (sessionId: string, workspace: string, createdAt: string) =>t.deps.sessionsRepo.insert({sessionId,projectId,- agentId: "default_agent",+ agentId,provider: "custom",modelId: "m-x",workspace,@@ -572,7 +604,7 @@ describe("session-index", () => {agent_state: "/tmp/a",workspace: "/tmp/cli-workspace",};- await writeTraceFile(t.root, projectId, "default_agent", "2026-07-01", discovered, 1, [+ await writeTraceFile(t.root, projectId, agentId, "2026-07-01", discovered, 1, [sessionMeta(meta),userText("cli session"),]);@@ -631,7 +663,7 @@ describe("session-index", () => {t.deps.sessionsRepo.insert({sessionId: deskSession,projectId,- agentId: "default_agent",+ agentId,provider: "custom",modelId: "m-desk",workspace: "/tmp/w-desk",@@ -650,7 +682,7 @@ describe("session-index", () => {t.deps.sessionsRepo.insert({sessionId: legacyId,projectId,- agentId: "default_agent",+ agentId,provider: "custom",modelId: "m-legacy",workspace: "/tmp/w-legacy",@@ -668,7 +700,7 @@ describe("session-index", () => {t.deps.sessionsRepo.insert({sessionId: legacy,projectId,- agentId: "default_agent",+ agentId,provider: "custom",modelId: "m-legacy",workspace: "/tmp/w-legacy",@@ -696,24 +728,14 @@ describe("session-index", () => {agent_state: "/tmp/a",workspace: session.workspace,};- const f1 = await writeTraceFile(- t.root,- projectId,- "default_agent",- "2026-07-01",- sessionId,- 1,- [sessionMeta(meta), userText("round one")],- );- const f2 = await writeTraceFile(- t.root,- projectId,- "default_agent",- "2026-07-02",- sessionId,- 2,- [sessionMeta(meta), userText("round two")],- );+ const f1 = await writeTraceFile(t.root, projectId, agentId, "2026-07-01", sessionId, 1, [+ sessionMeta(meta),+ userText("round one"),+ ]);+ const f2 = await writeTraceFile(t.root, projectId, agentId, "2026-07-02", sessionId, 2, [+ sessionMeta(meta),+ userText("round two"),+ ]);const del = await api.delete(`/api/sessions/${sessionId}`);expect(del.status).toBe(204);@@ -742,7 +764,7 @@ describe("session-index", () => {it("the list is sorted by createdAt descending", async () => {await configureModels();const older = "session-2020-01-01-00-00-00-00000001";- await writeTraceFile(t.root, projectId, "default_agent", "2020-01-01", older, 1, [+ await writeTraceFile(t.root, projectId, agentId, "2020-01-01", older, 1, [sessionMeta({session_id: older,model_id: "m",@@ -813,7 +835,7 @@ describe("session-index", () => {t.deps.sessionsRepo.insert({sessionId,projectId,- agentId: "default_agent",+ agentId,provider: "custom",modelId: "m-org",workspace: "/tmp/w-org",@@ -824,13 +846,7 @@ describe("session-index", () => {lastActiveAt: createdAt,});}- t.deps.orgCacheRepo.addTicketSession(- projectId,- "acme",- "2026-09-02-site",- ticket,- "default_agent",- );+ t.deps.orgCacheRepo.addTicketSession(projectId, "acme", "2026-09-02-site", ticket, agentId);const list = async (qs: string) => {const res = await api.get(`${base()}${qs}`);expect(res.status, qs).toBe(200);@@ -906,7 +922,7 @@ describe("session-index", () => {const row = {sessionId: "session-2026-07-02-00-00-00-11223344",projectId,- agentId: "default_agent",+ agentId,modelId: "cli-model",provider: "custom",workspace: "/tmp/w",@@ -949,11 +965,11 @@ describe("session-index", () => {agent_state: "/tmp/a",workspace: session.workspace,};- await writeTraceFile(t.root, projectId, "default_agent", "2026-07-02", session.sessionId, 1, [+ await writeTraceFile(t.root, projectId, agentId, "2026-07-02", session.sessionId, 1, [sessionMeta(meta),userText("a"),]);- await writeTraceFile(t.root, projectId, "default_agent", "2026-07-03", session.sessionId, 2, [+ await writeTraceFile(t.root, projectId, agentId, "2026-07-03", session.sessionId, 2, [sessionMeta(meta),userText("b"),]);@@ -989,10 +1005,10 @@ describe("session-index", () => {// the assertion is about validation alone — a real goal loop would still be settling// after the test closed its database.const started: OmniMessage[][] = [];- t.deps.manager.startGoal = async (sessionId, args) => {+ vi.spyOn(t.deps.manager, "startGoal").mockImplementation(async (sessionId, args) => {started.push(args.messages);return { sessionId };- };+ });const withText = await api.post(`/api/sessions/${session.sessionId}/tasks`, {input: [{ type: "text", text: "objective" },