Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
0e645b9
test: openStateDatabase creates state.db and records each owner's ver…
V3RON Oct 20, 2026
8778966
feat(state): openStateDatabase creates state.db and records each owne…
V3RON Oct 20, 2026
041ce47
test: a registry restarted on the same state.db returns every record …
V3RON Oct 20, 2026
8c3f2bd
feat(core): the registry keeps devices, leases, requests and componen…
V3RON Oct 20, 2026
7e78fbc
test(e2e): the physical-device flows keep their state in state.db (#761)
V3RON Oct 20, 2026
d09dc93
test: openStateDatabase refuses with each Shared values message (#761)
V3RON Oct 20, 2026
e6a5f74
feat(state): a daemon refuses an old file, a damaged file, a newer ve…
V3RON Oct 20, 2026
f6c48bb
test(daemon): every start that injects drivers passes the fake device…
V3RON Oct 20, 2026
fc2de34
test: a lock held past 5 s gives the lock message, not the damage one…
V3RON Oct 20, 2026
d267120
test: the versions are read inside the write transaction (#761)
V3RON Oct 20, 2026
4474e6f
test: a renew with 1,000 settled requests stored changes exactly one …
V3RON Oct 20, 2026
44a0ef9
test: a grant writes the lease, the device's move to leased and the r…
V3RON Oct 20, 2026
fa9db7a
test: a commit that throws in SQLite leaves snapshot and listeners as…
V3RON Oct 20, 2026
1948b2b
test: pruning deletes the rows of dropped requests and their grant an…
V3RON Oct 20, 2026
04f0d8a
test: a replayed answer's device is the current device record (#761)
V3RON Oct 20, 2026
9e44d76
test: load refuses with RegistryLoadError naming the table and key (#…
V3RON Oct 20, 2026
d15ac6c
fix(core): a registry load that finds a bad row rejects (#761)
V3RON Oct 20, 2026
fb4f92e
test: a physical device loads with empty driver data and has no devic…
V3RON Oct 20, 2026
e4ac6d7
test: two transitions of two devices started in one tick both persist…
V3RON Oct 20, 2026
0874c2a
test: describeDeviceDataTable holds for the fake driver's table (#761)
V3RON Oct 20, 2026
8676848
test: a worker refuses an old state.json and a drivers module without…
V3RON Oct 20, 2026
7f134d7
test: resolveDeviceDataTables answers the option, else the module's e…
V3RON Oct 20, 2026
fe471e9
test(e2e): the built daemon entry exits 1 on a folder holding state.j…
V3RON Oct 20, 2026
704b634
docs: state.db replaces state.json in the manuals, the flows and docs…
V3RON Oct 20, 2026
28e7111
refactor(state): split the version step and the device row values (#761)
V3RON Oct 20, 2026
6e1dfb5
chore(contract): the schemas keep their wire shape (#761)
V3RON Oct 20, 2026
5170119
docs(state): the module's manual sits beside a CLAUDE.md and links th…
V3RON Oct 20, 2026
89ddc57
test: a worker started with startDaemon and fake drivers, leased, sto…
V3RON Oct 20, 2026
6b08379
test: audit probes for state.db; a failed start closes state.db; stal…
V3RON Oct 20, 2026
551e6ec
test: drop two comments that do not say why (#761)
V3RON Oct 20, 2026
c3431ba
fix(core): lease ttl columns hold fractional milliseconds (#761)
V3RON Oct 20, 2026
6fe4d0e
fix(core): the fake device table refuses extra keys (#761)
V3RON Oct 20, 2026
feaa48d
test(daemon): pin that the startup lease end comes before core's devi…
V3RON Oct 20, 2026
36f94f6
test(daemon): the option wins over SIMLOCK_DRIVERS_MODULE when both a…
V3RON Oct 20, 2026
6ae6e99
docs: the state.db upgrade section sits under simlock daemon; two com…
V3RON Oct 20, 2026
fa9ffaa
fix(core): a fractional quarantine retry time and lease_grants ttl ar…
V3RON Oct 20, 2026
5bdb6fb
fix(e2e): the e2e fake table refuses data with extra keys (#761)
V3RON Oct 20, 2026
fabe940
test(daemon): several leases prove the startup lease end comes before…
V3RON Oct 20, 2026
3cf805d
test(daemon): the restart lease-end test gets the time a loaded runne…
V3RON Oct 20, 2026
bc24123
test(daemon): the restart lease-end test fixes the host's cpus and me…
V3RON Oct 20, 2026
6c4df08
fix(daemon): a second daemon refuses before it opens a live daemon's …
V3RON Oct 20, 2026
fc5076f
test(daemon): a daemon that loses the claim at listen never runs afte…
V3RON Oct 20, 2026
d2b520d
Merge remote-tracking branch 'origin/feature/754-adr' into task/761
V3RON Oct 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -2606,6 +2606,37 @@ as a contract. Growth is bounded: once the file passes `log.rotateBytes` it is
rotated to `daemon.log.1` (replacing any previous generation), so `logs` always
shows the current file with the immediately preceding one prepended.

### Breaking: state moves to state.db

A worker keeps its devices, leases, lease requests and installed components in
`state.db` in its data directory (`~/.simlock`), one row per record, instead of
in `state.json`. A change writes only the rows it touches, so a renew writes
one lease row however many lease requests are stored. Nothing is imported from
`state.json`. The upgrade therefore loses the record of which components
Simlock installed, so `simlock component remove` refuses a component
installed before it (`Simlock has no record of installing …`).

A daemon whose folder still holds `state.json` does not start. To upgrade:

1. With the older Simlock, release every lease and run
`simlock nuke --delete-devices`, so no simulator, emulator or lease is left
that the new Simlock would not know about.
2. Remove `state.json`.
3. Start the new Simlock, then add physical devices again with
`simlock device add`.

A daemon also does not start when `state.db` is damaged, when another Simlock
daemon holds it locked for more than five seconds, or when it was written by a
newer Simlock (the message names the file and what to do). The reason is
logged as `Daemon failed to start` and exits `1`; read it with
`simlock daemon logs`, which works with no daemon up. A damaged `state.db` is
never repaired or deleted for you: move it away to start with empty state, and
know that every device and lease it held is forgotten.

To go back to an older Simlock, release every lease and run
`simlock nuke --delete-devices` first: the older Simlock does not read
`state.db`.

## `simlock worker <list|drain|undrain|remove>`

The operator's view of a fleet. Every subcommand is an admin
Expand Down
3 changes: 2 additions & 1 deletion docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘
dispatcher in process, never through the socket.
- A gateway is a second set of handlers for the same contract. Every frontend
works against either mode unchanged.
- State lives on the worker (`state.json`, written only by core's
- State lives on the worker (`state.db`, its registry tables written only by core's
`Registry`). A gateway keeps only its tokens, its instance id and its drained-worker set on
disk; everything else is rebuilt from the workers that reconnect.

Expand Down Expand Up @@ -56,6 +56,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘
| simlock-client, client, admin | The typed programmatic client (`simlock/client`, `simlock/admin`) | [simlock-client](../../src/simlock-client/AGENTS.md) · [client](../../src/client/AGENTS.md) · [admin](../../src/admin/AGENTS.md) |
| lease-policy | Client-side renew timer | [lease-policy](../../src/lease-policy/AGENTS.md) |
| bus | Post-commit business events and their in-memory ring | [bus](../../src/bus/AGENTS.md) |
| state | `state.db`: opens it, refuses an old file, damage and a newer version, migrates each owner's tables | [state](../../src/state/AGENTS.md) |
| history | The durable event history: `history.db`, prune, set-aside, projections (usage: request, minute and device fact rows) | [history](../../src/history/AGENTS.md) |
| ports | Every external API behind an interface, with a fake | [ports](../../src/ports/AGENTS.md) |
| host-load | CPU, memory and disk load samples | [host-load](../../src/host-load/AGENTS.md) |
Expand Down
14 changes: 10 additions & 4 deletions docs/internal/flows/startup.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,18 @@ Entry: `src/daemon/main.ts` `startDaemon` → `DaemonServer.start` (`src/daemon/
2. `Logger` → `daemon.log`. At `log.level: debug` the `ProcessRunner` is wrapped.
3. Host info read once (`sw_vers` on macOS); bounded, never throws.
4. `EventBus` → the event history is created (`createEventHistory`). It touches no file yet.
`refuseWhenDaemonAnswers` (`src/daemon/main.ts:241`) first connects to the socket: a daemon
that answers makes this one fail with `DaemonAlreadyRunningError`, before any `state.db` is opened.
`openStateDatabase` then opens the role's `state.db` (both roles) in this order, each failure
being the daemon's start error: an old file of the role's former state refuses, then
`node:sqlite` missing, the open and its pragmas, `quick_check`, and in one `BEGIN IMMEDIATE`
transaction each owner's version (a newer one, or a migration that throws, refuses).
`createAuth` then builds the token store and the admin secret (hash in memory), once, for both modes.
5. Started with `--gateway` (role `gateway`, data directory `<root>/gateway`) → the gateway section. Otherwise go on.

## Worker: build (before the claim)

6. `Registry.load` — `state.json`.
6. `Registry.load` — the `registry` and device-data tables of `state.db`.
7. Instance identity — `loadInstanceId`, `instance.json`. Written once per home,
never regenerated.
8. Root validation — `discoverDrivers`: each driver checks its owned root against
Expand Down Expand Up @@ -43,7 +49,7 @@ Entry: `src/daemon/main.ts` `startDaemon` → `DaemonServer.start` (`src/daemon/

Converge (`src/daemon/main.ts` `convergeStartup`), one step after another. Once a stop
reaches its settle step, the steps after the read are skipped. Before step 16 it
removes the `.<name>.<pid>.<uuid>.tmp` files and `.<root>.<pid>.<id>.staging` directories of dead writers beside `state.json`, beside each device root and in
removes the `.<name>.<pid>.<uuid>.tmp` files and `.<root>.<pid>.<id>.staging` directories of dead writers beside each device root and in
the data directory (`sweepWriteLeftovers`).

16. Settle open requests — `leasing.settleRequests`: every `open` request fails
Expand Down Expand Up @@ -122,7 +128,7 @@ platform runs the deferred reclaim (step 21.2).
7. Close connections, remove `admin.token`, release the socket (released even when the removal fails).

A gateway's stop: agent-device edge and HTTP, then `FleetLeaseCoordinator` and
`GatewayService` are disposed, then the event history stops.
`GatewayService` are disposed, then the event history stops and `state.db` closes.

A stop releases nothing. Leases stay in `state.json` with their deadlines; the
A stop releases nothing. Leases stay in `state.db` with their deadlines; the
next start re-arms or ends them (steps 19–20).
35 changes: 34 additions & 1 deletion e2e/daemon-folders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { existsSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { describe, expect, it } from "vitest";

import { freeLoopbackPort, REPO_ROOT, type TestEnv, waitFor, withDaemon } from "./helpers/index.js";
Expand Down Expand Up @@ -108,7 +109,15 @@ describe("daemon folders (ADR 0034)", () => {
const workerInstance = await readFile(join(env.home, "instance.json"), "utf8");
const gatewayInstance = await readFile(join(gatewayFolder(env), "instance.json"), "utf8");
expect(gatewayInstance).not.toBe(workerInstance);
expect(existsSync(join(gatewayFolder(env), "state.json"))).toBe(false);
const gatewayState = new DatabaseSync(join(gatewayFolder(env), "state.db"));
try {
const devicesTables = gatewayState
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'devices'")
.all();
expect(devicesTables).toEqual([]);
} finally {
gatewayState.close();
}
} finally {
await stopGateway(env);
}
Expand Down Expand Up @@ -185,6 +194,30 @@ describe("daemon folders (ADR 0034)", () => {
);
});

it("the daemon entry run in a folder that still holds state.json exits 1, logs the upgrade instructions as its last line and creates no state.db", async () => {
const env = await withDaemon({ mode: "auto" });
await writeFile(join(env.home, "state.json"), "{}\n", "utf8");

const code = await new Promise<number | null>((resolve, reject) => {
const child = spawn(process.execPath, [join(REPO_ROOT, "dist/daemon/main.js")], {
env: env.env,
stdio: "ignore",
});
child.once("error", reject);
child.once("close", resolve);
});

expect(code).toBe(1);
const lines = (await readFile(join(env.home, "daemon.log"), "utf8")).trim().split("\n");
expect(JSON.parse(lines.at(-1) ?? "{}")).toMatchObject({
fields: {
message: `Found ${join(env.home, "state.json")}, which this Simlock no longer reads. To upgrade: with the older Simlock, release every lease and run \`simlock nuke --delete-devices\`; then remove ${join(env.home, "state.json")} and start again. See "Breaking: state moves to state.db" in docs/CLI.md.`,
},
message: "Daemon failed to start",
});
expect(existsSync(join(env.home, "state.db"))).toBe(false);
});

it("on a machine with only a present gateway, plain daemon start and plain status reach the gateway and start no worker", async () => {
const env = await withDaemon({ mode: "auto" });

Expand Down
30 changes: 30 additions & 0 deletions e2e/fake-driver/device-data.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { DatabaseSync } from "node:sqlite";
import { describe, expect, it } from "vitest";
import { e2eFakeDeviceDataTable } from "./device-data.js";

function openTable(): DatabaseSync {
const database = new DatabaseSync(":memory:");
for (const statement of e2eFakeDeviceDataTable.migrations) database.exec(statement);
return database;
}

describe("e2e fake device data table", () => {
it("writes and reads back its one key", () => {
const database = openTable();

e2eFakeDeviceDataTable.write(database, "dev_1", { fakeDeviceId: "fk-1" });

expect(e2eFakeDeviceDataTable.read(database, "dev_1")).toEqual({ fakeDeviceId: "fk-1" });
});

it("refuses data with a key besides fakeDeviceId, and stores nothing", () => {
const database = openTable();

expect(() =>
e2eFakeDeviceDataTable.write(database, "dev_1", { extra: 1, fakeDeviceId: "fk-1" }),
).toThrow("Invalid fake driver data for device dev_1");
expect(() => e2eFakeDeviceDataTable.read(database, "dev_1")).toThrow(
"No fake driver data for device dev_1",
);
});
});
30 changes: 30 additions & 0 deletions e2e/fake-driver/device-data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { DeviceDataTable } from "../../dist/core/index.js";

// why: e2e may enter the project only through dist/<module>/index.js, so the e2e fake driver keeps its own table beside src/core's fakeDeviceDataTable.
export const e2eFakeDeviceDataTable: DeviceDataTable = {
migrations: [
"CREATE TABLE e2e_fake_device_data (device_id TEXT PRIMARY KEY, fake_device_id TEXT NOT NULL) STRICT",
],
name: "e2e-fake-device-data",
read(database, deviceId) {
const row = database
.prepare("SELECT fake_device_id FROM e2e_fake_device_data WHERE device_id = ?")
.get(deviceId);
if (row === undefined) throw new Error(`No fake driver data for device ${deviceId}`);
return { fakeDeviceId: row["fake_device_id"] };
},
version: 1,
write(database, deviceId, driverData) {
const data = driverData as Record<string, unknown> | null | undefined;
const fakeDeviceId = data?.["fakeDeviceId"];
if (typeof fakeDeviceId !== "string" || Object.keys(data ?? {}).length !== 1) {
throw new Error(`Invalid fake driver data for device ${deviceId}`);
}
database
.prepare(
`INSERT INTO e2e_fake_device_data (device_id, fake_device_id) VALUES (?, ?)
ON CONFLICT (device_id) DO UPDATE SET fake_device_id = excluded.fake_device_id`,
)
.run(deviceId, fakeDeviceId);
},
};
8 changes: 7 additions & 1 deletion e2e/fake-driver/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Driver, PrerequisiteCheck } from "../../dist/core/index.js";
import type { DeviceDataTable, Driver, PrerequisiteCheck } from "../../dist/core/index.js";
import { e2eFakeDeviceDataTable } from "./device-data.js";
import { OutOfProcessFakeDriver, readPlatformScript, type FakeDriverClock } from "./fake-driver.js";
import { DEFAULT_LOG_ENV, DEFAULT_PLATFORMS_ENV, DEFAULT_SCRIPT_ENV } from "./types.js";

Expand Down Expand Up @@ -36,3 +37,8 @@ export const prerequisiteChecks: readonly PrerequisiteCheck[] = (["ios", "androi
platform,
}),
);

export const deviceDataTables: ReadonlyMap<"ios" | "android", DeviceDataTable> = new Map([
["ios", e2eFakeDeviceDataTable],
["android", e2eFakeDeviceDataTable],
]);
16 changes: 3 additions & 13 deletions e2e/helpers/physical-presence.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";

import { expect } from "vitest";

import type { FakeDriverErrorSpec, FakeDriverPlatformScript } from "../fake-driver/types.js";
Expand All @@ -14,6 +11,7 @@ import {
type PhysicalSeed,
type SeededLease,
} from "./physical-state.js";
import { patchPhysicalRows, readPhysicalRecords } from "./state-db.js";
import { waitFor } from "./wait.js";

export const ENROLLED = ["com.example.mail", "com.example.maps"] as const;
Expand Down Expand Up @@ -167,21 +165,13 @@ export async function patchPhysicalRecords(
env: Pick<TestEnv, "home">,
patch: (record: Record<string, unknown>) => Record<string, unknown>,
): Promise<void> {
const path = join(env.home, "state.json");
const state = JSON.parse(await readFile(path, "utf8")) as {
physicalDevices: Record<string, unknown>[];
};
state.physicalDevices = state.physicalDevices.map(patch);
await writeFile(path, JSON.stringify(state, null, 2), "utf8");
patchPhysicalRows(env, patch);
}

export async function physicalRecords(
env: Pick<TestEnv, "home">,
): Promise<Record<string, unknown>[]> {
const state = JSON.parse(await readFile(join(env.home, "state.json"), "utf8")) as {
physicalDevices: Record<string, unknown>[];
};
return state.physicalDevices;
return readPhysicalRecords(env);
}

export interface DeviceRow {
Expand Down
Loading
Loading