Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,17 @@ those changes add, alongside the breaking changes above.
`EXEC_TIMEOUT` error code (CLI exit `10`, the code the other "ran out of
time" outcome already uses, and HTTP `504`) rather than reporting the exit
code the kill produced.
- **events:** every business event is also written to `~/.simlock/events.jsonl`,
one JSON line each, so the history survives a daemon restart or crash.
`simlock events --since` and `GET /v1/events?since=` read it, reaching past
a restart and past the 1000 events kept in memory; with no daemon running,
`simlock events --since` (without `--follow`) reads the file and starts
none. `--since` with
`--follow` prints that history, then streams, with nothing lost or repeated
where they meet. The file is capped by the new `eventLog.rotateBytes`
(default 5 MiB, one rotated generation). `daemon.log` no longer gets its own
copies of `component.installed` and `device.slimmed`; read them from the
event file.

### ADR 0005: gateway and worker modes

Expand Down
30 changes: 22 additions & 8 deletions docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -627,7 +627,7 @@ catalog lists is leasable *somewhere*, not necessarily everywhere.
republished on the gateway's bus with `workerId` added to the payload,
alongside the gateway's own `worker.*` and `request.dispatched` facts (see
[EVENTS.md](EVENTS.md)). `--follow` and `--since` work as always, over the
gateway's own ring buffer.
gateway's own event history.

**`simlock simctl` and `simlock adb`** keep working, but not the same way
underneath. Against a **worker** they behave exactly as documented above: the
Expand Down Expand Up @@ -1042,8 +1042,22 @@ offer.

## `simlock events [--follow] [--since <duration>]`

Stream the business-event ring buffer (see [EVENTS.md](EVENTS.md)) as JSON
lines. `--follow` keeps streaming; `--since 1h` replays recent history.
Print business events (see [EVENTS.md](EVENTS.md)) as JSON lines.

- With no flags, prints the recent events the daemon holds in memory
(`eventBuffer.capacity`, 1000 by default), which start empty after a
restart.
- `--since 1h` reaches further back. Every event is also written to
`~/.simlock/events.jsonl`, which survives restarts and crashes, so
`--since` returns events from before the last restart and beyond the
in-memory limit, back to the oldest event the file still holds. The file
is capped by `eventLog.rotateBytes` (see
[CONFIGURATION.md](CONFIGURATION.md)); the oldest events go first.
- `--since` without `--follow`, with no daemon running, reads the file
directly and does not start a daemon. `--follow` starts one as usual.
- `--follow` keeps streaming live events. With `--since`, it prints that
history first and then streams, with no event missing or printed twice
where the two meet.

Against a **gateway** this is the fleet's stream: every connected worker's
business events, republished on the gateway's bus with `workerId` added to
Expand All @@ -1052,10 +1066,10 @@ the payload, interleaved with the gateway's own `worker.connected` /
`worker.drain-started` / `worker.drain-ended` / `request.dispatched` facts.
`worker.rejected` is how you find out why a machine never appeared in
`simlock worker list` at all — it reports an uplink refused at the door,
which nothing else records. It is one ring buffer like
any other, so it resets when the gateway restarts and it holds only what
arrived while the gateway was up — a worker's events from before its uplink
connected are not backfilled.
which nothing else records. The gateway writes these relayed events to its
own `events.jsonl` along with its own, so `--since` reaches back across a
gateway restart. It holds only what arrived while the gateway was up — a
worker's events from before its uplink connected are not backfilled.

## `simlock daemon <start|stop|status|logs>`

Expand Down Expand Up @@ -1251,7 +1265,7 @@ fleet; `simlock worker remove` then forgets its view.
### `SIMLOCK_HOME`

Overrides the data directory the CLI, MCP server, and daemon all use for
`config.json`, `state.json`, `daemon.sock`, `daemon.log`, and — unless
`config.json`, `state.json`, `daemon.sock`, `daemon.log`, `events.jsonl`, and — unless
overridden — the device roots themselves under `devices/`. Defaults to
`~/.simlock`. Because devices live under it, it needs a local volume with tens
of gigabytes free. All three frontends resolve it through the same function
Expand Down
7 changes: 4 additions & 3 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ a warning. Inspect the effective, merged configuration at any time with
| `gateway.execTimeoutMs` | **Gateway side.** Backstop on a proxied `device.exec`, deliberately longer than the worker's own `exec.timeoutMs`, which is the authoritative one. | `11 minutes` |
| `gateway.leaseRequestTimeoutMs` | **Gateway side.** Backstop on a forwarded `lease.request` -- expiry answers `WORKER_UNREACHABLE`, freeing the request for the queue's own deadline/cancel handling again. | `5 minutes` |
| `diskPressure.freeBytesThreshold` | Free disk space below which Simlock treats the machine as under disk pressure. | `10 GiB` |
| `eventBuffer.capacity` | Number of business events kept in the in-memory ring buffer (see `simlock events`). | `1000` |
| `eventBuffer.capacity` | Number of recent business events kept in memory, which `simlock events` without `--since` replays. | `1000` |
| `eventLog.rotateBytes` | Size of the event file, `~/.simlock/events.jsonl`, before it rotates. Every business event is written there and survives a daemon restart. One rotated generation, `events.jsonl.1`, is kept, so the history on disk stays within about twice this size and the oldest events are dropped first. | `5 MiB` |
| `health.enabled` | Master switch for leased-device crash detection and recovery. | `true` |
| `health.probeIntervalMs` | How often the health monitor observes leased devices against driver reality. | `30 seconds` |
| `health.stableObservations` | Consecutive `stopped` observations required before a leased device is treated as crashed; guards against transient `Booting`/`Shutting Down`/adb-offline readings. | `2` |
Expand Down Expand Up @@ -134,7 +135,7 @@ local agents whether or not its gateway is reachable, and `http.enabled` stays
off by default.

**A gateway reads a deliberately small slice of this file**: `mode`, `http.*`,
`log.*`, `lease.*`, `eventBuffer.*` and `gateway.*`. Every other key —
`log.*`, `lease.*`, `eventBuffer.*`, `eventLog.*` and `gateway.*`. Every other key —
capacity, drivers, downloads, idle, warmPool, health, ios, android, stalledTransition —
configures devices, which a gateway does not have; each one present in a
gateway's config is reported with a warning and ignored, the same treatment an
Expand Down Expand Up @@ -200,7 +201,7 @@ does not apply to it. It reads:
| `gateway.routing`, `gateway.disconnectedRetentionMs`, `gateway.execTimeoutMs`, `gateway.leaseRequestTimeoutMs` | how to run the fleet |
| `http.*` | it is the fleet's contact point |
| `lease.*` | `defaultTtlMs`/`maxTtlMs` bound what its own clients may ask for, before a request is dispatched — see below |
| `log.*`, `eventBuffer.*` | logging and the event ring buffer, as anywhere |
| `log.*`, `eventBuffer.*`, `eventLog.*` | logging and the event history, as anywhere |

**Both ends have a `lease.*` block, and on a fleet lease the gateway's is the
one that decides the width.** A request arriving at a gateway with no `ttlMs`
Expand Down
17 changes: 12 additions & 5 deletions docs/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,12 @@ documented above arrives with an extra field: additive, and only ever on a
gateway. The events in this section's own table are the gateway's own, and
carry no `workerId` beyond the worker they are about.

Two consequences of relaying rather than owning: the gateway's ring buffer
only holds what arrived while its uplinks were up (a worker's events from
before it connected are not backfilled), and a worker's own
Relayed events are written to the gateway's own event file
(`events.jsonl`) along with its own, so `simlock events --since` against a
gateway reaches back across a gateway restart. Two consequences of relaying
rather than owning: the gateway's history only holds what arrived while its
uplinks were up (a worker's events from before it connected are not
backfilled), and a worker's own
`simlock events` keeps showing exactly what it always did, un-prefixed and
unaware that anything is watching.

Expand All @@ -142,5 +145,9 @@ lease index, rather than trusting the relayed payload's `ownerId` verbatim.
## Conventions recap

- Every event carries: `timestamp`, `event`, `payload`, emitting module.
- Events are appended to a ring buffer that powers `simlock events --follow`
and serves as the audit trail.
- Events are appended to an in-memory ring buffer, which `simlock events`
without `--since` replays, and to the event file `~/.simlock/events.jsonl`,
one JSON line per event with the same fields. The file survives daemon
restarts and crashes, is what `simlock events --since` reads, and is the
durable record: no event is copied into `daemon.log`. It is capped by
`eventLog.rotateBytes`, keeping one rotated generation.
8 changes: 6 additions & 2 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -621,8 +621,12 @@ an all-or-nothing that leaves the operator guessing.
- `GET /v1/leases` — every active lease (`simlock list --leases`).
- `GET /v1/devices` — every managed device, with state and
`transitionAgeMs` (`simlock list --devices`).
- `GET /v1/events?since=<duration>` — replay from the in-memory business-event
ring buffer (`simlock events`).
- `GET /v1/events?since=<duration>` — replay business events newer than
`since` (`simlock events --since`). They come from the daemon's event file,
so they include events from before a daemon restart and beyond the 1000
held in memory, back to the oldest event the file still holds
(`eventLog.rotateBytes`). Without `since`, the recent events held in
memory.
- `GET /v1/events/stream` — Server-Sent Events follow of the event bus
(`simlock events --follow`).

Expand Down
67 changes: 37 additions & 30 deletions docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,8 @@ agent / console ──token auth──> │ HTTP frontend + unix socket
the fleet.
- **What a gateway does not do.** It starts no drivers, validates no device
roots, and runs no reaper, health monitor or capacity strategy; of the
config it reads only `mode`, `http.*`, `log.*`, `lease.*`, `eventBuffer.*`
and `gateway.*` (worker-only keys warn and are ignored). It always listens
config it reads only `mode`, `http.*`, `log.*`, `lease.*`, `eventBuffer.*`,
`eventLog.*` and `gateway.*` (worker-only keys warn and are ignored). It always listens
on HTTP — that is how agents reach it and what the uplink upgrades from — so
`http.enabled: false` in gateway mode fails the start rather than being
silently overridden. `nuke.run`, `cleanup.run`, `doctor.run` and
Expand Down Expand Up @@ -665,8 +665,9 @@ views, and `workerId` on every device and lease in the aggregate.
annotated with the workers that have it.

Worker business events are republished on the gateway's bus with `workerId`
added to the payload and land in the gateway's own ring buffer, so `simlock
events --follow` against a gateway shows the whole fleet. The gateway also
added to the payload and land in the gateway's own ring buffer and event
file, so `simlock events --follow` against a gateway shows the whole fleet and
`--since` reaches back across a gateway restart. The gateway also
emits its own facts — `worker.connected`, `worker.disconnected`,
`worker.rejected`, `worker.removed`, `worker.drain-started`,
`worker.drain-ended`, and `request.dispatched`; see [EVENTS.md](EVENTS.md).
Expand Down Expand Up @@ -1371,32 +1372,38 @@ kicked off has settled — `simlock status` already reports each device's own
state (`reclaiming` included), so a separate aggregate would duplicate
information already visible per-device rather than add any.

Operational logging is a separate concern from the event bus: `simlock events`
carries business facts (lease granted, device cleaned up, …) in an in-memory
ring buffer that resets on restart, while the `Logger` port writes durable,
structured JSON lines — one per record — for startup, socket claim/recovery,
driver discovery, connection lifecycle, shutdown, and unexpected/handled
errors. `startDaemon` builds the production `Logger` (`JsonLinesLogger` over a
`NodeFileLogSink`) from `config.log` right after config loads, then hands
module-scoped children (`logger.child("server")`, `.child("connection-host")`,
`.child("driver-discovery")`) to each component so every line is attributable.
The sink tracks bytes written and rotates `daemon.log` to `daemon.log.1`
(replacing any previous generation) once `config.log.rotateBytes` is exceeded,
so growth is bounded and `simlock daemon logs` reads the rotated generation
before the current file. The one exception is the fatal top-level handler: it
cannot depend on `config.log` having loaded successfully, so it builds its own
logger straight from the default log path at a fixed level, falling back to
`console.error` only if that itself fails.

`startDaemon` also subscribes `logger.child("components")` to `component.installed`
(`wireComponentInstallLogging` in `src/daemon/main.ts`) so a component simlock
installed on an agent's behalf stays attributable in `daemon.log` after the
event ring buffer resets on restart — the same durable-vs-ring-buffer split as
everything else in this section, applied to component installs specifically
because there is no registry entry or uninstall for them to be recovered from
otherwise (see "Out of scope" in the #67 issue). The log line carries
`requesterId` whenever the event payload has one, so the durable record names
which agent's request caused the install, not just that one happened.
Operational logging is a separate concern from the event bus (ADR 0006): two
records, and no fact is copied from one into the other. The `Logger` port
writes durable, structured JSON lines — one per record — for startup, socket
claim/recovery, driver discovery, connection lifecycle, shutdown, and
unexpected/handled errors. `startDaemon` builds the production `Logger`
(`JsonLinesLogger` over a `NodeFileLogSink`) from `config.log` right after
config loads, then hands module-scoped children (`logger.child("server")`,
`.child("connection-host")`, `.child("driver-discovery")`) to each component
so every line is attributable. The sink tracks bytes written and rotates
`daemon.log` to `daemon.log.1` (replacing any previous generation) once
`config.log.rotateBytes` is exceeded, so growth is bounded and `simlock daemon
logs` reads the rotated generation before the current file. The one exception
is the fatal top-level handler: it cannot depend on `config.log` having loaded
successfully, so it builds its own logger straight from the default log path
at a fixed level, falling back to `console.error` only if that itself fails.

Business facts live in the bus's two records. The ring buffer
(`eventBuffer.capacity`) holds recent events in memory and resets on restart.
`EventHistory` (`src/bus/event-file.ts`) subscribes to every event and writes
each envelope as one JSON line to `events.jsonl` in the data directory,
through a second `NodeFileLogSink` that `startDaemon` opens right after the
bus with `config.eventLog.rotateBytes`. That file is the durable record and
the audit trail: it survives restarts and crashes, rotates independently of
`daemon.log`, and on a gateway holds the relayed fleet events too. A file
that cannot be opened, or a write that fails, costs the history and never the
daemon or the emitter: one error line, writing stops, and replay falls back
to the ring. `events.replay` in both dispatchers asks `EventHistory`: without
`sinceTs` it answers from the ring, with `sinceTs` from the file (current
file, then its rotated generation, deduplicated by `seq` and `timestamp`).
The CLI reads the file itself only for `simlock events --since` when no
daemon answers; `--follow` subscribes first, replays, and drops replayed
pushes, so the join neither loses nor repeats an event.

## Device requests

Expand Down
17 changes: 12 additions & 5 deletions docs/internal/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,12 @@ field: additive, and only ever on a gateway. The seven events in this
section's own table are the gateway's own, and carry no `workerId` beyond
the worker they are about.

Two consequences of relaying rather than owning: the gateway's ring buffer
only holds what arrived while its uplinks were up (a worker's events from
before it connected are not backfilled), and a worker's own
Relayed events are written to the gateway's own event file
(`events.jsonl`) along with its own, so `simlock events --since` against a
gateway reaches back across a gateway restart. Two consequences of relaying
rather than owning: the gateway's history only holds what arrived while its
uplinks were up (a worker's events from before it connected are not
backfilled), and a worker's own
`simlock events` keeps showing exactly what it always did, un-prefixed and
unaware that anything is watching.

Expand All @@ -185,5 +188,9 @@ verbatim off the wire.
## Conventions recap

- Every event carries: `timestamp`, `event`, `payload`, emitting module.
- Events are appended to a ring buffer that powers `simlock events --follow`
and serves as the audit trail.
- Events are appended to an in-memory ring buffer, which `simlock events`
without `--since` replays, and to the event file `~/.simlock/events.jsonl`,
one JSON line per event with the same fields. The file survives daemon
restarts and crashes, is what `simlock events --since` reads, and is the
durable record: no event is copied into `daemon.log`. It is capped by
`eventLog.rotateBytes`, keeping one rotated generation. See ADR 0006.
5 changes: 3 additions & 2 deletions docs/internal/KNOWN-PITFALLS.md
Original file line number Diff line number Diff line change
Expand Up @@ -329,8 +329,9 @@ step, and `Driver.resolveSpec`'s signature carries no progress callback the
way `provision`/`makeReady` do. A CLI or MCP caller waiting on a
multi-minute install today sees nothing on the wire between its request and
either the eventual grant or a timeout; the only visibility is the daemon's
own `component.install-started` bus event (`simlock events --follow`) and log
line, neither reaching the waiting connection itself. Threading a
own `component.install-started` bus event (`simlock events --follow`, and
the event file behind `simlock events --since`), which never reaches the
waiting connection itself. There is no `daemon.log` line for it. Threading a
`downloading` stage through would mean widening the `Driver` interface
(`resolveSpec` gaining an `onProgress`-shaped option, both drivers
implementing it), a new `LeaseProgress` variant, and CLI/MCP wire changes —
Expand Down
Loading
Loading