diff --git a/docs/CLI.md b/docs/CLI.md index 4975e27d8..6cfa727ae 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1670,7 +1670,9 @@ offer. ## `simlock events [--follow] [--since ]` -Print business events (see [EVENTS.md](EVENTS.md)) as JSON lines. +Print business events (see [EVENTS.md](EVENTS.md)) as JSON lines. Every line +carries an `id` that stays the same for that event across a daemon restart; +history from before the upgrade that added it is not shown. - With no flags, prints the recent events the daemon holds in memory (`eventBuffer.capacity`, 1000 by default), which start empty after a diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 1166b9926..0637ddf6e 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -15,7 +15,7 @@ import { connectSimlockAdmin } from "simlock/admin"; // agent + admin role `connectSimlockAdmin` returns a superset of `connectSimlock`'s client — every agent-role method plus the admin-role ones (`list`, `runCleanup`, `runNuke`, -`getConfig`, `stopDaemon`, `replayEvents`/`subscribeEvents`, +`getConfig`, `stopDaemon`, `replayEvents`/`subscribeEvents` (each event carries an `id`), `createToken`/`listTokens`/`revokeToken`, `installComponent`, `removeComponent`). The split exists so `simlock/client` doesn't even show admin methods in a caller's editor; the daemon's own role check is what actually stops an agent-role session from diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 140f9e6ca..2a68a9274 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -151,7 +151,11 @@ lease index, rather than trusting the relayed payload's `ownerId` verbatim. ## Conventions recap -- Every event carries: `timestamp`, `event`, `payload`, emitting module. +- Every event carries: `id` (`evt_` and a unique suffix; it names the event for + good and survives a daemon restart), `seq`, `timestamp`, `event`, `payload`, + emitting module. +- The `id` arrived with protocol 10. Lines already in `events.jsonl` from before + the upgrade have none and are not shown by `simlock events --since`. - 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 diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 03b39c226..3d3c02aec 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1181,9 +1181,11 @@ an all-or-nothing that leaves the operator guessing. 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. + memory. Every event carries an `id`, the same one after a daemon restart; + events written before the upgrade that added it are not returned. - `GET /v1/events/stream` — Server-Sent Events follow of the event bus - (`simlock events --follow`). + (`simlock events --follow`). Each event carries the same `id` as in + `GET /v1/events`. - `GET /v1/tokens` — every token this daemon knows (`simlock token list`): ```json diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 7f8a95d71..682b714ed 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -1870,7 +1870,7 @@ 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`). +file, then its rotated generation, deduplicated by `id`). 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. diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index e74869989..e2580fdf7 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -7,6 +7,12 @@ in short: `subject.past-tense-fact`, emitted post-commit, facts not commands. > Status: **planned catalog** — update the Status column as events are > implemented, and add new events here in the same change that introduces them. +> **The event `id` is a one-time exception to additive-only** for the event +> file, taken by [ADR 0014](adr/0014-an-event-has-one-id-minted-where-the-fact-happened.md) +> the way ADR 0004's was: every envelope gains a required `id`, and a line in +> `events.jsonl` without one is not replayed. History from before the upgrade +> is not shown. + > **The payload removals in the lease rows are a deliberate exception to > events rule 6** ("treat payload shape as a public contract: additive > changes only"), granted by [ADR @@ -204,7 +210,11 @@ verbatim off the wire. ## Conventions recap -- Every event carries: `timestamp`, `event`, `payload`, emitting module. +- Every event carries: `id` (`evt_` and a unique suffix; it names the event for + good and survives a daemon restart), `seq`, `timestamp`, `event`, `payload`, + emitting module. +- The `id` arrived with protocol 10. Lines already in `events.jsonl` from before + the upgrade have none and are not shown by `simlock events --since`. - 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 diff --git a/docs/internal/adr/0006-events-and-log-are-two-records.md b/docs/internal/adr/0006-events-and-log-are-two-records.md index f911e222e..66ce1742d 100644 --- a/docs/internal/adr/0006-events-and-log-are-two-records.md +++ b/docs/internal/adr/0006-events-and-log-are-two-records.md @@ -84,6 +84,9 @@ post-commit emission. Promoting a log line onto the bus, or adding an ### 5. The contract follows the record +> ADR 0014 narrows this once: every envelope gains a required `id`, and a line without +> one is not replayed. + A line in `events.jsonl` is the event envelope, so it is under the event payload contract: additive changes only. A line in `daemon.log` is under no contract. Its message and fields may change in any release. diff --git a/docs/internal/adr/0013-the-console-reads-routes-and-follows-the-event-stream.md b/docs/internal/adr/0013-the-console-reads-routes-and-follows-the-event-stream.md index 0b63a71b4..99c8d23e1 100644 --- a/docs/internal/adr/0013-the-console-reads-routes-and-follows-the-event-stream.md +++ b/docs/internal/adr/0013-the-console-reads-routes-and-follows-the-event-stream.md @@ -57,6 +57,9 @@ today. #88's tasks add them. This ADR does not decide their shape. ### 2. One event stream, read with `fetch` +> ADR 0014 narrows this: two events are the same when their `id` matches, and `seq` and +> `timestamp` no longer take part. + The console opens one connection to `GET /v1/events/stream`. It reads it with `fetch` and a stream reader, so it can send the `Authorization` header. It does not use `EventSource` or a WebSocket: a browser can send diff --git a/docs/internal/agent-rules/events.md b/docs/internal/agent-rules/events.md index b087576fb..f5a92b5d7 100644 --- a/docs/internal/agent-rules/events.md +++ b/docs/internal/agent-rules/events.md @@ -23,8 +23,8 @@ Rules for defining and emitting events on the daemon's event bus. consumer needs (lease id, device id, reason, durations) so handlers don't have to query state that may have moved on. Treat payload shape as a public contract: additive changes only. -7. **Every event carries** `timestamp`, `event`, `payload`, and the emitting - module, and is appended to the ring buffer and to the event file +7. **Every event carries** `id`, `timestamp`, `event`, `payload`, and the + emitting module (and `seq`, which orders events within one daemon run), and is appended to the ring buffer and to the event file (`events.jsonl`, ADR 0006). The ring powers `simlock events`; the file powers `simlock events --since` and is the audit trail. 8. **New events are documented in the same change.** Adding or modifying an diff --git a/e2e/console/long-lists.spec.ts b/e2e/console/long-lists.spec.ts index 1a96bf094..9edfd0f40 100644 --- a/e2e/console/long-lists.spec.ts +++ b/e2e/console/long-lists.spec.ts @@ -403,6 +403,7 @@ function events(count: number): unknown[] { const newest = Date.now() - 1_000; return Array.from({ length: count }, (_, index) => ({ event: "load.generated", + id: `evt_load_${count - index}`, module: "load", payload: { n: count - index }, seq: count - index, diff --git a/e2e/event-history.test.ts b/e2e/event-history.test.ts index ff7c3d9d7..c888c4833 100644 --- a/e2e/event-history.test.ts +++ b/e2e/event-history.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest"; import { type TestEnv, waitFor, withDaemon } from "./helpers/index.js"; interface Envelope { + readonly id: string; readonly seq: number; readonly timestamp: number; readonly event: string; @@ -68,6 +69,24 @@ describe("event history", () => { expect(grantOf(parseLines(history.stdout), leaseId)).toEqual(before); }); + it("simlock events --since 1h after a daemon restart prints each event with the id it had before the restart", async () => { + const env = await withDaemon(); + await prepare(env); + const leaseId = await leaseDevice(env); + const beforeRestart = parseLines((await env.cli(["events", "--since", "1h"])).stdout); + const granted = grantOf(beforeRestart, leaseId); + expect(granted?.id).toMatch(/^evt_[A-Za-z0-9_-]{1,64}$/); + + await env.restartDaemon(); + const afterRestart = parseLines((await env.cli(["events", "--since", "1h"])).stdout); + + for (const before of beforeRestart) { + expect(before.id).toMatch(/^evt_/); + expect(afterRestart.find((entry) => entry.id === before.id)).toEqual(before); + } + expect(new Set(afterRestart.map((entry) => entry.id)).size).toBe(afterRestart.length); + }); + it("prints the history with the daemon stopped, and the daemon stays stopped", async () => { const env = await withDaemon(); await prepare(env); diff --git a/src/bus/event-file.test.ts b/src/bus/event-file.test.ts index c6eded316..f33ea1458 100644 --- a/src/bus/event-file.test.ts +++ b/src/bus/event-file.test.ts @@ -55,8 +55,9 @@ function history(options: { }); } -function envelope(seq: number, timestamp: number): EventEnvelope { +function envelope(seq: number, timestamp: number, id = `evt_${seq}`): EventEnvelope { return { + id, seq, timestamp, event: "daemon.stopping", @@ -254,6 +255,54 @@ describe("readEventFile", () => { expect(read.map((entry) => entry.seq)).toEqual([1, 3]); }); + it("the event file reader skips a line with no id", async () => { + const { id: _id, ...withoutId } = envelope(2, 200); + const { seq: _seq, ...withoutSeq } = envelope(5, 500); + const { timestamp: _timestamp, ...withoutTimestamp } = envelope(6, 600); + const filesystem = await filesystemWith({ + "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/data/events.jsonl": `${lines(envelope(1, 100))}${JSON.stringify(withoutId)}\n${JSON.stringify({ ...envelope(4, 400), id: 4 })}\n${JSON.stringify(withoutSeq)}\n${JSON.stringify(withoutTimestamp)}\n${lines(envelope(3, 300))}`, + }); + + const read = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(read.map((entry) => entry.seq)).toEqual([1, 3]); + }); + + it("the event file reader skips a line whose id the envelope schema refuses", async () => { + const refused = ["evt_", "evt_has space", `evt_${"a".repeat(65)}`, "nope_1", ["evt_array"]]; + const filesystem = await filesystemWith({ + "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/data/events.jsonl": `${lines(envelope(1, 100))}${refused + .map((id, index) => `${JSON.stringify({ ...envelope(10 + index, 200 + index), id })}\n`) + .join("")}${lines(envelope(3, 300))}`, + }); + + const read = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(read.map((entry) => entry.seq)).toEqual([1, 3]); + }); + + it("the event file reader returns an event found in both generations once", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl": lines(envelope(1, 100, "evt_same"), envelope(2, 200)), + "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/data/events.jsonl.1": lines(envelope(1, 100, "evt_same")), + }); + + const read = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(read.map((entry) => entry.id)).toEqual(["evt_same", "evt_2"]); + }); + + it("two events with the same seq and timestamp but different ids are both read back from the file", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl": lines(envelope(1, 100, "evt_a")), + "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/data/events.jsonl.1": lines(envelope(1, 100, "evt_b")), + }); + + const read = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(read.map((entry) => entry.id)).toEqual(["evt_b", "evt_a"]); + }); + it("skips a line that is not JSON and returns the lines around it", async () => { const filesystem = await filesystemWith({ "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/data/events.jsonl": `${lines(envelope(1, 100))}{"seq":2,"times\n${lines(envelope(3, 300))}`, diff --git a/src/bus/event-file.ts b/src/bus/event-file.ts index 500dda36f..691091f8b 100644 --- a/src/bus/event-file.ts +++ b/src/bus/event-file.ts @@ -1,4 +1,5 @@ import { type Filesystem, isMissingPathError, type Logger, type LogSink } from "../ports/index.js"; +import { EVENT_ID_PATTERN } from "../contract/schemas.js"; import type { EventBus, EventEnvelope } from "./index.js"; /** The durable record of every business event, in the data directory (ADR 0006). */ @@ -8,8 +9,8 @@ export const EVENT_FILE_NAME = "events.jsonl"; * Every envelope in the event file newer than `sinceTs`, oldest first. The current file is * read before its rotated generation (`.1`), so a rotation landing between the two reads * can only make one generation show up twice -- never make one go missing -- and the repeat is - * dropped by `seq` and `timestamp`. A line that is not JSON (a write cut short by a crash) is - * skipped; a file that is not there is empty. + * dropped by `id`. A line that is not JSON (a write cut short by a crash), or has no `id` of the shape + * the envelope contract accepts (written before events had one, ADR 0014), is skipped; a file that is not there is empty. */ export async function readEventFile( filesystem: Filesystem, @@ -31,10 +32,10 @@ export async function readEventFile( return envelopes; } -/** What identifies one event across the ring, the file and a live push: `seq` restarts with - * every daemon, so it is paired with the timestamp. */ -export function eventKey(event: { readonly seq: number; readonly timestamp: number }): string { - return `${event.seq}:${event.timestamp}`; +/** What identifies one event across the ring, the file and a live push: its `id` and nothing + * else (ADR 0014). `seq` restarts with every daemon, so it never could. */ +export function eventKey(event: { readonly id: string }): string { + return event.id; } async function readLines(filesystem: Filesystem, path: string): Promise { @@ -58,7 +59,9 @@ function parseEnvelope(line: string): EventEnvelope | undefined { typeof value !== "object" || value === null || typeof (value as { seq?: unknown }).seq !== "number" || - typeof (value as { timestamp?: unknown }).timestamp !== "number" + typeof (value as { timestamp?: unknown }).timestamp !== "number" || + typeof (value as { id?: unknown }).id !== "string" || + !EVENT_ID_PATTERN.test((value as { id: string }).id) ) { return undefined; } diff --git a/src/bus/index.test.ts b/src/bus/index.test.ts index 5e386b495..cae6dc506 100644 --- a/src/bus/index.test.ts +++ b/src/bus/index.test.ts @@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url"; import { describe, expect, expectTypeOf, it, vi } from "vitest"; -import { FakeClock } from "../ports/index.js"; +import { FakeClock, type IdGenerator } from "../ports/index.js"; import { type EventBusLogger, EventBus, type EventMap, type EventName } from "./index.js"; const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", ".."); @@ -83,6 +83,7 @@ describe("EventBus", () => { ); const expectedEnvelope = { + id: expect.stringMatching(/^evt_/), seq: 1, timestamp: 1_234, event: "lease.expired", @@ -93,6 +94,18 @@ describe("EventBus", () => { expect(allEnvelopes).toEqual([expectedEnvelope]); }); + it("emit stamps each envelope with evt_ and the id generator's next value", () => { + let next = 0; + const idGenerator: IdGenerator = { generate: () => `gen-${++next}` }; + const bus = new EventBus(new FakeClock(1), 10, undefined, idGenerator); + + const first = bus.emit("daemon.stopping", { reason: "a" }, "daemon"); + const second = bus.emit("daemon.stopping", { reason: "b" }, "daemon"); + + expect([first.id, second.id]).toEqual(["evt_gen-1", "evt_gen-2"]); + expect(bus.replay().map((entry) => entry.id)).toEqual(["evt_gen-1", "evt_gen-2"]); + }); + it("isolates a throwing handler and continues dispatching", () => { const logger: EventBusLogger = { error: vi.fn() }; const bus = new EventBus(new FakeClock(), 1_000, logger); diff --git a/src/bus/index.ts b/src/bus/index.ts index 1194518a6..9f9f409d4 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -1,4 +1,4 @@ -import type { Clock } from "../ports/index.js"; +import { type Clock, CryptoIdGenerator, type IdGenerator } from "../ports/index.js"; export interface EventMap { "lease.requested": { @@ -297,6 +297,9 @@ export type EventName = keyof EventMap; export type EventEnvelope = Event extends EventName ? { + /** Names this event for good: minted once where it happened, it survives a restart and is + * what every reader tells events apart by (ADR 0014). `seq` only orders within one run. */ + readonly id: string; readonly seq: number; readonly timestamp: number; readonly event: Event; @@ -333,6 +336,7 @@ export class EventBus { private readonly clock: Clock, private readonly capacity = 1_000, private readonly logger: EventBusLogger = defaultLogger, + private readonly idGenerator: IdGenerator = new CryptoIdGenerator(), ) { if (!Number.isInteger(capacity) || capacity < 1) { throw new Error("Event bus capacity must be a positive integer"); @@ -346,6 +350,7 @@ export class EventBus { module: string, ): EventEnvelope { const envelope = { + id: `evt_${this.idGenerator.generate()}`, seq: this.#nextSequence, timestamp: this.clock.now(), event, diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index be54c0b1d..9aba6a8cd 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -3892,8 +3892,8 @@ describe("CLI: mcp command (ADR 0003 §11 -- lazy module load)", () => { describe("CLI: events history", () => { const hour = 3_600_000; - function envelope(seq: number, timestamp: number) { - return { seq, timestamp, event: "lease.granted", payload: { seq }, module: "leases" }; + function envelope(seq: number, timestamp: number, id = `evt_${seq}`) { + return { id, seq, timestamp, event: "lease.granted", payload: { seq }, module: "leases" }; } function printed(stdout: string): unknown[] { @@ -3979,7 +3979,7 @@ describe("CLI: events history", () => { expect(fileRead).toBe(false); }); - it("events --follow prints an event emitted between the subscribe and the replay exactly once", async () => { + it("simlock events --follow prints an event pushed during the replay once", async () => { const output = outputCapture(); const signals = new EventEmitter(); let listener: ((push: EventPush) => void) | undefined; @@ -4001,6 +4001,8 @@ describe("CLI: events history", () => { // seq 2, and seq 3 lands just after its snapshot. listener?.(push(2)); listener?.(push(3)); + // Same seq and timestamp as the replayed event 2, another id: another event. + listener?.({ subscriptionId: "sub_1", event: envelope(2, 2, "evt_other") }); return [envelope(1, 1), envelope(2, 2)]; }, }), @@ -4012,7 +4014,13 @@ describe("CLI: events history", () => { signals.emit("SIGINT"); expect(await runPromise).toBe(0); - expect(printed(output.stdout)).toEqual([envelope(1, 1), envelope(2, 2), push(3), push(4)]); + expect(printed(output.stdout)).toEqual([ + envelope(1, 1), + envelope(2, 2), + push(3), + { subscriptionId: "sub_1", event: envelope(2, 2, "evt_other") }, + push(4), + ]); }); it("events --since --follow prints the history once and then the live events", async () => { diff --git a/src/contract/event-envelope.test.ts b/src/contract/event-envelope.test.ts new file mode 100644 index 000000000..0913cb1bb --- /dev/null +++ b/src/contract/event-envelope.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vitest"; + +import { eventEnvelopeSchema } from "./schemas.js"; + +describe("eventEnvelopeSchema", () => { + const valid = { + id: "evt_abc", + seq: 1, + timestamp: 1_000, + event: "daemon.stopping", + payload: { reason: "x" }, + module: "daemon", + }; + + it("the event envelope schema refuses a missing id, an id over 68 characters, an id without evt_, and a non-finite timestamp", () => { + expect(eventEnvelopeSchema.safeParse(valid).success).toBe(true); + expect(eventEnvelopeSchema.safeParse({ ...valid, id: `evt_${"a".repeat(64)}` }).success).toBe( + true, + ); + + const { id: _id, ...withoutId } = valid; + expect(eventEnvelopeSchema.safeParse(withoutId).success).toBe(false); + expect(eventEnvelopeSchema.safeParse({ ...valid, id: `evt_${"a".repeat(65)}` }).success).toBe( + false, + ); + expect(eventEnvelopeSchema.safeParse({ ...valid, id: "evt_" }).success).toBe(false); + expect(eventEnvelopeSchema.safeParse({ ...valid, id: "abc" }).success).toBe(false); + expect(eventEnvelopeSchema.safeParse({ ...valid, id: "xevt_abc" }).success).toBe(false); + expect(eventEnvelopeSchema.safeParse({ ...valid, id: "evt_a b" }).success).toBe(false); + expect(eventEnvelopeSchema.safeParse({ ...valid, id: 7 }).success).toBe(false); + for (const timestamp of [Number.POSITIVE_INFINITY, Number.NaN]) { + expect(eventEnvelopeSchema.safeParse({ ...valid, timestamp }).success).toBe(false); + } + }); +}); diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 4089f2365..2a3e407e6 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -27,7 +27,8 @@ const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().in * 8). ADR 0010 adds `component.install` and its `component-progress` push (taking it to 9): a * gateway's `worker.install-component` (ADR 0010 §7) relays that operation to its * workers, so a worker without it must be `incompatible` rather than fail in the middle of a - * relay. It only ever widens once a second version is actually kept alive side by side with the + * relay. ADR 0014 gives every event envelope an `id` (taking it to 10): a worker's pushed events + * without one would fail the gateway's schema, so a worker on 9 is `incompatible` instead. It only ever widens once a second version is actually kept alive side by side with the * first, which nothing here does. * * A client from before any of those changes simply does not overlap this daemon, and `hello` @@ -42,7 +43,7 @@ const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().in * A worker on 5 is marked `incompatible` the same way (ADR 0008 §10), and so is one on 7 * (ADR 0007 §12), and so is one on 8 (ADR 0010 §9). */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 9, max: 9 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 10, max: 10 }; /** * The one protocol version that ever existed before ranges did. Used only to build the diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 564bfaf21..6cc17a5b1 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -590,9 +590,13 @@ export const nukeReportSchema = z.object({ * for a channel this PR does not change the routing of. Tightening this (e.g. a discriminated * union keyed on `event`) is left as follow-up work; flagged in the PR description. */ +export const EVENT_ID_PATTERN = /^evt_[A-Za-z0-9_-]{1,64}$/; + export const eventEnvelopeSchema = z.object({ + /** Wire input is a claim (safety.md): a pushed `id` is bounded, not trusted. */ + id: z.string().regex(EVENT_ID_PATTERN), seq: z.number(), - timestamp: z.number(), + timestamp: z.number().finite(), event: z.string(), payload: z.unknown(), module: z.string(), diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 7b2f7b8a1..0c87faaa0 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -17,8 +17,8 @@ describe("daemon protocol", () => { // taking it to 6, and ADR 0007 makes a device's mode a required `mode`, taking it to 7, then // lets a lease request choose it, taking it to 8, each the same way. ADR 0010 adds // `component.install` and its `component-progress` push, which a gateway relays to its - // workers, taking it to 9. - expect(DAEMON_PROTOCOL_VERSION).toBe(9); + // workers, taking it to 9. ADR 0014 gives every event envelope an `id`, taking it to 10. + expect(DAEMON_PROTOCOL_VERSION).toBe(10); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 73a5ea4c2..5492cd41d 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1061,7 +1061,14 @@ describe("Dispatcher: lease.release-all", () => { describe("Dispatcher: events.replay", () => { it("events.replay with sinceTs returns what the event history returns", async () => { const fromHistory: EventEnvelope[] = [ - { seq: 7, timestamp: 50, event: "daemon.stopping", payload: { reason: "x" }, module: "d" }, + { + id: "evt_7", + seq: 7, + timestamp: 50, + event: "daemon.stopping", + payload: { reason: "x" }, + module: "d", + }, ]; const asked: unknown[] = []; const { dispatcher } = await buildDispatcher({ diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 31e5a2362..06a651ae6 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -1295,6 +1295,29 @@ describe("startDaemon event file", () => { ).toHaveLength(1); }); + it("mints event ids from the idGenerator the daemon was given", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-main-event-file-")); + temporaryDirectories.push(directory); + process.env.SIMLOCK_DRIVERS_MODULE = await writeModule( + `export function createDrivers({ eventBus }) { + eventBus.emit("component.installed", { componentId: "18.6", durationMs: 1, platform: "ios" }, "test"); + return []; + }`, + ); + + await start({ + dataDirectory: directory, + drivers: undefined, + idGenerator: { generate: () => "from-the-given-generator" }, + }); + + const ids = (await readFile(join(directory, "events.jsonl"), "utf8")) + .trimEnd() + .split("\n") + .map((line) => (JSON.parse(line) as { id: string }).id); + expect(ids).toContain("evt_from-the-given-generator"); + }); + it("writes no daemon log line for component.installed and device.slimmed", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-main-event-file-")); temporaryDirectories.push(directory); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index e9082ac0d..022aa9318 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -151,7 +151,12 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise { it("events.replay with sinceTs returns what the event history returns", async () => { const fromHistory: EventEnvelope[] = [ - { seq: 7, timestamp: 50, event: "daemon.stopping", payload: { reason: "x" }, module: "d" }, + { + id: "evt_7", + seq: 7, + timestamp: 50, + event: "daemon.stopping", + payload: { reason: "x" }, + module: "d", + }, ]; const asked: unknown[] = []; const { dispatcher } = harness({ diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index f17f711b5..ac7c61ad4 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -843,6 +843,31 @@ describe("GatewayService", () => { await harness.service.stop(); }); + it("a worker advertising protocol 9 is incompatible on the gateway and nothing it pushes reaches the gateway's bus", async () => { + const worker9 = { min: 9, max: 9 }; + expect(negotiateProtocolVersion(PROTOCOL_VERSION_RANGE, worker9)).toBeUndefined(); + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + worker.failWith = protocolMismatchError(worker9); + // A gateway that subscribed anyway would get a live listener, so the push below could reach it. + worker.subscribeDespiteFailure = true; + + await harness.join("wrk_1", worker); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.connection).toBe("incompatible"), + ); + worker.pushEvent({ event: "lease.granted", payload: { leaseId: "l1" } }); + + expect(worker.subscribed).toBe(false); + expect(harness.service.workers.view("wrk_1")).toMatchObject({ + protocol: { gateway: PROTOCOL_VERSION_RANGE, worker: worker9 }, + }); + expect(eventNames(harness.events)).not.toContain("lease.granted"); + + await harness.service.stop(); + }); + it("marks a worker incompatible when hello finds no overlapping range, and asks it nothing else", async () => { const harness = fleet(); await harness.service.start(); diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index b553c2dc9..f2dc667cc 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -233,6 +233,9 @@ export class ScriptedWorkerClient { readonly calls: string[] = []; /** Set to reject every call with this error -- e.g. a protocol mismatch. */ failWith: unknown; + /** Set to let `events.subscribe` succeed while every other call still rejects with `failWith`, + * so a test can prove the gateway does not listen to a worker it marked incompatible. */ + subscribeDespiteFailure = false; closed = false; /** * Names of calls (`"status.get"`, `"list.get:devices"`, `"catalog.get"`, `"config.get"`) that @@ -303,6 +306,7 @@ export class ScriptedWorkerClient { pushEvent(envelope: Partial & { readonly event: string }): void { this.#eventListener?.({ event: { + id: "evt_test", module: "test", payload: {}, seq: 1, @@ -449,7 +453,7 @@ export class ScriptedWorkerClient { listener: (push: { event: EventEnvelope }) => void, ): Promise<() => Promise> { this.calls.push("events.subscribe"); - this.#throwIfFailing(); + if (!this.subscribeDespiteFailure) this.#throwIfFailing(); this.#eventListener = listener; return async () => { if (this.hangUnsubscribe) return new Promise(() => {}); diff --git a/ui/src/views/events-model.ts b/ui/src/views/events-model.ts index 0d98a355a..8cd66d94a 100644 --- a/ui/src/views/events-model.ts +++ b/ui/src/views/events-model.ts @@ -8,6 +8,8 @@ import type { Stat } from "../layout"; /** One business event, as the daemon sent it. */ export interface ConsoleEvent { + /** What names the event for good: survives a daemon restart (ADR 0014). */ + readonly id: string; readonly seq: number; readonly timestamp: number; readonly event: string; @@ -26,17 +28,22 @@ export const RECENT = "1h"; /** * An envelope off the wire, or `undefined` when it is not one: without a numeric `seq`, a - * `timestamp` that is a date, and a string `event`, it cannot be placed in time or told apart + * `timestamp` that is a date, and a string `event` and `id`, it cannot be placed in time or told apart * from another. */ export function readEvent(data: unknown): ConsoleEvent | undefined { if (typeof data !== "object" || data === null) return undefined; - const { event, payload, seq, timestamp } = data as Record; - if (typeof seq !== "number" || typeof timestamp !== "number" || typeof event !== "string") { + const { event, id, payload, seq, timestamp } = data as Record; + if ( + typeof seq !== "number" || + typeof timestamp !== "number" || + typeof event !== "string" || + typeof id !== "string" + ) { return undefined; } if (Number.isNaN(new Date(timestamp).getTime())) return undefined; - return { event, payload, seq, timestamp }; + return { event, id, payload, seq, timestamp }; } /** @@ -49,12 +56,9 @@ export function readReplay(body: unknown): readonly ConsoleEvent[] { return events.flatMap((data: unknown) => readEvent(data) ?? []); } -/** - * What makes two events the same: `seq` and `timestamp` both. `seq` alone starts again when the - * daemon restarts (ADR 0013 §2). - */ +/** What makes two events the same: their `id`, and nothing else (ADR 0014). */ export function keyOf(event: ConsoleEvent): string { - return `${event.seq}:${event.timestamp}`; + return event.id; } /** Newest first: by time, and by `seq` within the same millisecond. */ diff --git a/ui/src/views/events.test.tsx b/ui/src/views/events.test.tsx index e3fc2403f..52439bf08 100644 --- a/ui/src/views/events.test.tsx +++ b/ui/src/views/events.test.tsx @@ -19,8 +19,14 @@ const fakeClock: Clock = { clearTimeout: (handle) => clearTimeout(handle as ReturnType), }; -function envelope(seq: number, timestamp: number, event = "lease.granted", payload: unknown = {}) { - return { event, module: "lease", payload, seq, timestamp }; +function envelope( + seq: number, + timestamp: number, + event = "lease.granted", + payload: unknown = {}, + id = `evt_${seq}_${timestamp}`, +) { + return { event, id, module: "lease", payload, seq, timestamp }; } /** One event as the stream frames it. */ @@ -82,6 +88,10 @@ function openView(first: Replay = []) { replayWith(next: Replay) { replay = next; }, + /** The ids of the events the view shows, newest first. */ + ids(): string[] { + return (feed.snapshot().data ?? []).map((event) => event.id); + }, /** The events the view shows, as `seq@timestamp`, newest first. */ shown(): string[] { return (feed.snapshot().data ?? []).map((event) => `${event.seq}@${event.timestamp}`); @@ -150,6 +160,26 @@ describe("the events view", () => { expect(view.shown()).toEqual([`7@${T0}`, `6@${T0 - 1_000}`]); }); + it("two events with the same seq and timestamp but different ids are both shown", async () => { + const view = openView(); + view.replayWith([envelope(1, T0, "lease.granted", {}, "evt_a")]); + await settle(); + + view.daemon.openStream()?.send(frame(envelope(1, T0, "lease.granted", {}, "evt_b"))); + await settle(); + + expect(view.ids().sort()).toEqual(["evt_a", "evt_b"]); + }); + + it("an envelope without an id is not shown", async () => { + const view = openView(); + const { id: _id, ...withoutId } = envelope(2, T0); + view.replayWith([withoutId, { ...envelope(3, T0), id: 3 }, envelope(4, T0)]); + await settle(); + + expect(view.ids()).toEqual(["evt_4_" + T0]); + }); + it("events with the same seq from before and after a daemon restart are both shown", async () => { const view = openView(); await settle(); @@ -256,14 +286,15 @@ describe("the events view", () => { const events: ConsoleEvent[] = [ { event: "gizmo.frobnicated", + id: "evt_3", payload: { count: 3, nested: { deep: true }, reason: "because", workerId: "wrk_1" }, seq: 3, timestamp: T0, }, // A payload that is not an object at all. - { event: "gizmo.listed", payload: ["a", 1], seq: 2, timestamp: T0 - 1_000 }, + { event: "gizmo.listed", id: "evt_2", payload: ["a", 1], seq: 2, timestamp: T0 - 1_000 }, // No payload at all. - { event: "gizmo.pinged", payload: undefined, seq: 1, timestamp: T0 - 2_000 }, + { event: "gizmo.pinged", id: "evt_1", payload: undefined, seq: 1, timestamp: T0 - 2_000 }, ]; const html = renderToStaticMarkup( @@ -284,7 +315,13 @@ describe("the events view", () => { // Five and a half hours ahead of UTC, so neither the hour nor the minute matches UTC's. process.env.TZ = "Asia/Kolkata"; try { - const event: ConsoleEvent = { event: "lease.granted", payload: {}, seq: 1, timestamp: T0 }; + const event: ConsoleEvent = { + event: "lease.granted", + id: "evt_1", + payload: {}, + seq: 1, + timestamp: T0, + }; const html = renderToStaticMarkup(); @@ -298,7 +335,9 @@ describe("the events view", () => { }); it("an empty list says why it is empty", () => { - const leases: ConsoleEvent[] = [{ event: "lease.granted", payload: {}, seq: 1, timestamp: T0 }]; + const leases: ConsoleEvent[] = [ + { event: "lease.granted", id: "evt_1", payload: {}, seq: 1, timestamp: T0 }, + ]; const render = (events: ConsoleEvent[], filter: "all" | "device") => text(renderToStaticMarkup()); @@ -315,7 +354,13 @@ describe("the events view", () => { "component.installed", "daemon.started", "gizmo.frobnicated", - ].map((event, index) => ({ event, payload: {}, seq: index, timestamp: T0 - index })); + ].map((event, index) => ({ + event, + id: `evt_${index}`, + payload: {}, + seq: index, + timestamp: T0 - index, + })); const names = (filter: "all" | "lease" | "device" | "worker" | "component" | "other") => [ ...renderToStaticMarkup( @@ -334,6 +379,7 @@ describe("the events view", () => { it("a worker the console does not know, or that has no label, shows as its id", () => { const about = (workerId: string, seq: number): ConsoleEvent => ({ event: "lease.granted", + id: `evt_${seq}`, payload: { workerId }, seq, timestamp: T0 - seq, @@ -355,6 +401,7 @@ describe("the events view", () => { it("a worker.rejected event names no worker, even one the console knows", () => { const rejected: ConsoleEvent = { event: "worker.rejected", + id: "evt_1", payload: { reason: "unauthenticated", workerId: "wrk_1" }, seq: 1, timestamp: T0, @@ -373,13 +420,14 @@ describe("the events view", () => { it("an envelope without a numeric seq, a timestamp that is a date, or a name is not shown", async () => { const view = openView(); view.replayWith([ - { event: "lease.granted", timestamp: T0 }, - { event: "lease.granted", seq: 1 }, - { seq: 2, timestamp: T0 }, - { event: "lease.granted", seq: 3, timestamp: 1e300 }, + { event: "lease.granted", id: "evt_a", timestamp: T0 }, + { event: "lease.granted", id: "evt_b", seq: 1 }, + { id: "evt_c", seq: 2, timestamp: T0 }, + { event: "lease.granted", id: "evt_d", seq: 3, timestamp: 1e300 }, // A date, but as a string: not a timestamp. - { event: "lease.granted", seq: 5, timestamp: "2026-10-02T11:30:00Z" }, - { event: "lease.granted", seq: "6", timestamp: T0 }, + { event: "lease.granted", id: "evt_e", seq: 5, timestamp: "2026-10-02T11:30:00Z" }, + { event: "lease.granted", id: "evt_f", seq: "6", timestamp: T0 }, + { event: 7, id: "evt_g", seq: 7, timestamp: T0 }, envelope(4, T0), ]); await settle(); diff --git a/ui/src/views/history-model.test.ts b/ui/src/views/history-model.test.ts index 8ccdff037..d2555fedf 100644 --- a/ui/src/views/history-model.test.ts +++ b/ui/src/views/history-model.test.ts @@ -17,7 +17,7 @@ const CURRENT = Date.parse("2026-10-02T12:00:00Z"); let seq = 0; function event(name: string, timestamp: number): ConsoleEvent { seq += 1; - return { event: name, payload: {}, seq, timestamp }; + return { event: name, id: `evt_${seq}`, payload: {}, seq, timestamp }; } /** The count of each minute, keyed by how many minutes before the current one it starts. */ diff --git a/ui/src/views/stats.test.tsx b/ui/src/views/stats.test.tsx index 94ca012af..c0f902b42 100644 --- a/ui/src/views/stats.test.tsx +++ b/ui/src/views/stats.test.tsx @@ -149,12 +149,14 @@ describe("the stat cards", () => { const newest: ConsoleEvent = { event: "lease.granted", + id: "evt_2", payload: {}, seq: 2, timestamp: NOW - 5_000, }; const older: ConsoleEvent = { event: "device.ready", + id: "evt_1", payload: {}, seq: 1, timestamp: NOW - 9_000,