Repository navigation
Description
Request: none
Problem
Business events (lease.granted, device.crash-detected, and the rest) live
only in an in-memory ring buffer of 1000 entries. A daemon restart or crash
empties it. A busy machine or a gateway overwrites it within minutes.
daemon.log survives a restart, but it records only two events
(component.installed, device.slimmed). So "what happened to this lease or
device" has no answer after a restart, which is often when it is asked.
Who it is for
An operator or agent debugging a lease or a device after the fact: after a
daemon restart, after a crash, or more than 1000 events later. Later, anyone
who needs an audit trail.
Outcome
- Every business event the daemon emits is also written to an event file of
its own in the data directory: one JSON line per event, with the same
fieldssimlock eventsshows. - The file survives daemon restarts and crashes. Events from before a
restart are still there afterwards. - The file is separate from
daemon.log. Operational log lines cannot
rotate events out, and events cannot rotate log lines out. - Its size is bounded by a configurable limit. When the limit is passed, the
oldest events are dropped and the newest are kept. - On a gateway the file holds the relayed fleet events as well as the
gateway's own. - The file is
events.jsonl, and the limit iseventLog.rotateBytes,
default 5 MB. simlock events --sinceandGET /v1/events?since=reach into the file,
so they return events from before a restart and from beyond the ring
buffer.simlock events --since <d> --followprints that history and then keeps
streaming live events, with no event missing or printed twice at the join.- With no daemon running,
simlock events --sincereads the file directly
and does not start one. simlock events --followwithout--sincebehaves as it does today.daemon.logno longer gets its own copies ofcomponent.installedand
device.slimmed. The event file is the durable record.- A failure to write the file never fails or delays a lease operation.
Non-goals
- Turning log lines into events, or merging the logger into the event bus.
They stay two things. - Recording
device.execcommands. That is a different audit feature. - Tuning for high event volume on a large gateway. Revisit when it is seen
failing. - Sending events off the machine.
- Retention by age, or more than one rotated generation.
Completion conditions
- Lease a device, stop the daemon, start it again: the event file still
holds that lease'slease.granted, with its timestamp. - Every line of the file parses as JSON and carries
seq,timestamp,
event,payloadandmodule. - With the size limit set small, the file and its rotated generation stay
within about twice the limit, and the newest events are present. - Filling
daemon.logpast its own limit removes nothing from the event
file. - With the event file unwritable, a lease is still granted and released.
- Lease a device, restart the daemon, run
simlock events --since 1h: the
lease.grantedfrom before the restart is printed. - Stop the daemon and run
simlock events --since 1h: the history is
printed and no daemon is started. - Run
simlock events --since 1h --follow, then lease a device: the old
events are printed once, then the newlease.grantedappears. - CONFIGURATION.md documents the new key. CLI.md and EVENTS.md say where
the history is kept and how far back--sincereaches.
Open questions
None.
Decisions
- ADR 0006 — Events and the daemon log are two records: every event is persisted to a file of its own, and no fact is copied into
daemon.log.
Technical spec
Modules touched
src/bus/event-file.ts(new, exported fromsrc/bus/index.ts): the durable half of the bus.EVENT_FILE_NAME = "events.jsonl".readEventFile(filesystem, path, { sinceTs }): returns the envelopes withtimestamp > sinceTs, oldest first. It readspathfirst andpath + ".1"second, then drops any envelope seen twice (sameseqandtimestamp). That order means a rotation between the two reads can repeat a generation but never skip one. A line that is not JSON is skipped. A missing file is empty.EventHistory({ bus, sink?, filesystem, path, logger }):- With a
sink, it subscribes withsubscribeAlland writesJSON.stringify(envelope)per event: the same five fieldssimlock eventsprints, nothing added. - A write that throws is caught inside the handler. It logs one error line, stops writing for the rest of the run, and never reaches the emitter.
replay({ sinceTs }): withoutsinceTsit returnsbus.replay(), as today. WithsinceTsit returnsreadEventFile(...)while the writer is writing, andbus.replay({ sinceTs })when there is no sink, the writer has stopped, or the read fails.
- With a
src/ports/logger.ts:NodeFileLogSinkis reused as the sink, unchanged. Rotation and the one kept generation are its existing behaviour.src/core/config.ts:eventLog: { rotateBytes: number }, default5 * 1024 * 1024, validated as a positive integer. AddeventLogto the known top-level keys and toGATEWAY_CONFIG_KEYS.src/contract/schemas.ts:configSchemagainseventLog: z.object({ rotateBytes: z.number() }).optional(). Optional because a client parsesconfig.getoutput, and a newer gateway reads it from an older worker.src/daemon/main.ts:- Right after
new EventBus(...)and before the mode branch, openNodeFileLogSink({ path: <dataDirectory>/events.jsonl, maxBytes: config.eventLog.rotateBytes })in atry. On failure log one error line and continue with no sink. Build oneEventHistoryand pass it toDispatcherand, throughstartGatewayDaemon, toGatewayDispatcher. - Delete
wireComponentInstallLogging, its call, and the comment above the call.
- Right after
src/daemon/dispatcher.ts,src/gateway/dispatcher.ts:#eventsReplaycallseventHistory.replay(input). Neither reads the bus for replay any more.src/cli/index.ts,runEvents:- No
--since: replay asks for nosinceTs, as today. --sincewithout--follow: connect with{ launch: false }. If nothing is listening (the same testdaemon statususes for "stopped"), printenvironment.readEventFile(sinceTs)and exit 0. Otherwise replay through the daemon.- Any
--follow: subscribe first and buffer pushes, then replay and print it, then print each buffered push that was not in the replay (sameseqandtimestamp), then stream. One code path with and without--since. CliEnvironmentgainsreadEventFile(sinceTs), built inbuildCliEnvironmentfrom theFilesystemport and the data directory.
- No
src/http/app.ts: no code change.GET /v1/events?since=already dispatchesevents.replay.- Docs:
docs/CONFIGURATION.md: theeventLog.rotateBytesrow, andeventLog.*in both lists of keys a gateway reads.docs/CLI.md:simlock events(where history is kept, how far--sincereaches, the daemon-stopped case), the gateway paragraph on the ring buffer, and the data-directory file list.docs/HTTP-API.md:GET /v1/events?since=.docs/EVENTS.md,docs/internal/EVENTS.md: the conventions recap and the gateway relay paragraphs.docs/internal/agent-rules/events.mdrule 7: an event is appended to the ring buffer and to the event file.docs/internal/ARCHITECTURE.md: the operational-logging section (drop thewireComponentInstallLoggingparagraph, describe the event file), and the gateway config-key list.docs/internal/KNOWN-PITFALLS.md: the install-progress pitfall names acomponent.install-startedlog line; correct it.CHANGELOG.md, Unreleased: one entry.docs/internal/adr/0006-events-and-log-are-two-records.mdand the ADR index: status becomes Accepted in whichever PR closes the second of Keep business events on disk so the history survives a restart #168 and Daemon log records every request and background failure, and can be followed live #169.
Contract and event changes
- No operation is added and no operation's shape changes.
events.replaywithsinceTsnow answers from the event file. config.getoutput gains optionaleventLog.rotateBytes. No protocol version bump.- Events are written as emitted. Redacting
gateway.tokenfromdaemon.startedis The worker's gateway join token is written in plaintext to the daemon log and the event stream #170, not this PR. - No event is added, renamed, or reshaped. The catalog tables in both
EVENTS.mdfiles stay as they are; only the prose named above changes.
Rules in play
architecture.md4: the bus module's public surface grows byEventHistory,readEventFileandEVENT_FILE_NAME; nothing reaches into the ring.architecture.md8: the CLI reads the file only when no daemon answers. It decides nothing else.architecture.md9: file access throughFilesystemandLogSink. The Node sink is built inmain.tsonly.architecture.md10: one replay implementation for both dispatchers, one join path in the CLI.architecture.md13: the comments inmain.ts,bus/index.tsandlogger.tsthat say events are memory-only or that component installs are kept indaemon.log.events.md5, 7, 8: the writer is an observer and never throws intoemit; rule 7's text changes in this PR.safety.md, wire input is a claim: a gateway writes relayed worker payloads to disk.JSON.stringifykeeps one event on one line whatever the payload holds.documentation.md: end-user docs name~/.simlock/events.jsonl, never a path in this repo and never an ADR.testing.md: every title below is a claim; break the code and watch each fail.
Tests
Unit, src/bus/event-file.test.ts:
- Every emitted event is written as one JSON line equal to its envelope.
- A sink that throws is logged once, and later events still reach the ring and other subscribers.
- Replay with
sinceTsreturns events written by an earlier bus on the same file. - Replay with
sinceTsreturns events the ring has already overwritten. - Replay without
sinceTsreturns the ring and reads no file. - Replay with
sinceTsanswers from the ring when there is no sink, and when the writer has stopped. - The rotated generation is returned before the current file.
- A generation that shows up in both reads is returned once.
- A line that is not JSON is skipped and the lines around it are returned.
Unit, src/core/config.test.ts:
eventLog.rotateBytesdefaults to 5 MiB and rejects zero and negative values.- A gateway config with
eventLog.rotateBytesraises no unknown-key warning.
Unit, src/daemon/dispatcher.test.ts, src/gateway/dispatcher.test.ts:
events.replaywithsinceTsreturns what the event history returns.
Unit, src/daemon/main.test.ts (the wireComponentInstallLogging tests are deleted):
- A daemon whose event file cannot be opened starts, and logs one error line.
component.installedanddevice.slimmedwrite no line to the daemon log.
Unit, src/cli/index.test.ts:
events --sincewith nothing listening prints the file's events and launches no daemon.events --sincewith a daemon listening replays through the daemon.events --followprints an event emitted between the subscribe and the replay exactly once.events --followwithout--sinceasks for nosinceTs.
E2e, fast lane, e2e/event-history.test.ts:
- A lease granted before a daemon restart is printed by
simlock events --since 1hafter it. - With the daemon stopped,
simlock events --since 1hprints the history and the daemon stays stopped. - With
eventLog.rotateBytessmall,events.jsonlplusevents.jsonl.1stay under twice the limit and hold the newest event. - With
log.rotateBytessmall anddaemon.logrotated, every event emitted is still in the event file. - With a directory at the event file's path, a lease is granted and released.
E2e, fast lane, e2e/http-api.test.ts:
GET /v1/events?since=1hreturns an event from before a daemon restart.
Written by an agent.
Activity
V3RON commentedon Oct 1, 2026
Spec updated: Decisions and Technical spec added.
Written by an agent.
docs(adr): 0006 — events and the daemon log are two records; docs fol…
feat(daemon,cli): daemon log records every request and background fai…