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
4 changes: 3 additions & 1 deletion docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -1670,7 +1670,9 @@ offer.

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

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
Expand Down
2 changes: 1 addition & 1 deletion docs/CLIENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion docs/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 11 additions & 1 deletion docs/internal/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions docs/internal/adr/0006-events-and-log-are-two-records.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/internal/agent-rules/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions e2e/console/long-lists.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
19 changes: 19 additions & 0 deletions e2e/event-history.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
51 changes: 50 additions & 1 deletion src/bus/event-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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({
"/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, "/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({
"/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, "/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({
"/data/events.jsonl": lines(envelope(1, 100, "evt_same"), envelope(2, 200)),
"/data/events.jsonl.1": lines(envelope(1, 100, "evt_same")),
});

const read = await readEventFile(filesystem, "/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({
"/data/events.jsonl": lines(envelope(1, 100, "evt_a")),
"/data/events.jsonl.1": lines(envelope(1, 100, "evt_b")),
});

const read = await readEventFile(filesystem, "/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({
"/data/events.jsonl": `${lines(envelope(1, 100))}{"seq":2,"times\n${lines(envelope(3, 300))}`,
Expand Down
17 changes: 10 additions & 7 deletions src/bus/event-file.ts
Original file line number Diff line number Diff line change
@@ -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). */
Expand All @@ -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 (`<path>.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,
Expand All @@ -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<string[]> {
Expand All @@ -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;
}
Expand Down
15 changes: 14 additions & 1 deletion src/bus/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)), "..", "..");
Expand Down Expand Up @@ -83,6 +83,7 @@ describe("EventBus", () => {
);

const expectedEnvelope = {
id: expect.stringMatching(/^evt_/),
seq: 1,
timestamp: 1_234,
event: "lease.expired",
Expand All @@ -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);
Expand Down
7 changes: 6 additions & 1 deletion src/bus/index.ts
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down Expand Up @@ -297,6 +297,9 @@ export type EventName = keyof EventMap;

export type EventEnvelope<Event extends EventName = EventName> = 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;
Expand Down Expand Up @@ -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");
Expand All @@ -346,6 +350,7 @@ export class EventBus {
module: string,
): EventEnvelope<Event> {
const envelope = {
id: `evt_${this.idGenerator.generate()}`,
seq: this.#nextSequence,
timestamp: this.clock.now(),
event,
Expand Down
16 changes: 12 additions & 4 deletions src/cli/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] {
Expand Down Expand Up @@ -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;
Expand All @@ -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)];
},
}),
Expand All @@ -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 () => {
Expand Down
Loading
Loading