iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

The catalog answers watched queries: itx.contexts.watch, in three orders, with an answered summary

A member's client keeps a query of the mind's catalog answered: `itx.contexts.watch(query, onFrame)`
sends the answer and then each change to a capnweb callback, over the session's one connection.
No query is declared ahead of time.

- core/itx/src/context/reactive-catalog.ts: the engine, in the context that accepts the awake
  sockets. A row for each context, an index of its facts for each order (active, created, path),
  and for each watched query its size and bound. A write that no window holds costs no statement
  beyond its own and sends no frame. It keeps nothing until the first watch, which copies the
  catalog's rows a page at a time.
- core/itx/src/context/catalog-watch.ts and iterate-context.ts: the session's end. One hibernated
  socket into the catalog for all of a session's watches; the query passes the context's table as
  `contexts.list` does, so who may list may watch. A socket that drops is dialled again.
- core/itx/src/context/awake.ts: the catalog answers each summary. A context that goes quiet
  waits for the answer, and an unanswered summary is said again by the context's own alarm, on
  the durable ladder, eight times at most.
- Tests: the engine against a brute-force oracle in every order, the session's end against a
  socket written by hand, and the whole path in workerd through both ways a session ends.

Session: agy b859a067-e1f8-4f91-8d14-337c9a19b40b on beelink
Worker: claude 02c7d409-d06c-4792-af54-c1861507c2e0 on beelink

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NCuxgWcYQGgMn3WtDburVD

Jonas Templestein, 2026-11-26 22:40 UTC · d39881cbbb6554bfd3c38b3939fffcb9a28edbbc · parent d1d06c4

15 files changed

M core/itx/src/context/awake.test.ts
@@ -3,10 +3,14 @@
 // (core/alchemy/scripts/smoke).
 import { expect, test, vi } from "vitest";
 import {
+  AWAKE_ANSWER_WAIT_MS,
   AWAKE_CONTEXT_PATH,
   AWAKE_MAX_HOLD_MS,
   AWAKE_QUIET_MS,
+  AWAKE_RECOVER_AFTER_MS,
   AWAKE_REDIAL_AFTER_MS,
+  AWAKE_SAY_AGAIN_AFTER_MS,
+  AWAKE_SAY_AGAIN_TRIES,
   AWAKE_SUMMARY_EVERY_MS,
   AwakeSocket,
   decideAwakeSocket,
@@ -180,23 +184,222 @@
   vi.useRealTimers();
 });
 
-/** The accepting context, as the dialer sees it: counts dials and the sockets that are open. */
+test("an entry leaves an alarm, and a quiet close with every summary answered takes it away", async () => {
+  vi.useFakeTimers();
+  const far = farEnd();
+  let changes = 0;
+  const awake = new AwakeSocket({
+    path: "/agents/a",
+    dial: far.dial,
+    busy: () => false,
+    summary: () => "one",
+    recoveryChanged: () => (changes += 1),
+  });
+  expect(awake.recoverAt()).toBeNull();
+  const enteredAt = Date.now();
+  awake.entered();
+  // past the longest hold: a context that lives takes the alarm away before it fires
+  expect(awake.recoverAt()).toBe(enteredAt + AWAKE_RECOVER_AFTER_MS);
+  awake.entered();
+  expect(changes).toBe(1);
+  await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
+  expect(far).toMatchObject({ sent: ["one"], open: 0 });
+  expect(awake.recoverAt()).toBeNull();
+  expect(changes).toBe(2);
+  expect(vi.getTimerCount()).toBe(0);
+  vi.useRealTimers();
+});
+
+test("a quiet context keeps its socket for the catalog's answer, and no longer than the answer wait", async () => {
+  vi.useFakeTimers();
+  const far = farEnd();
+  far.answers = false;
+  const unanswered = counted();
+  const awake = new AwakeSocket({
+    path: "/agents/a",
+    dial: far.dial,
+    busy: () => false,
+    summary: () => "one",
+    unanswered,
+  });
+  awake.entered();
+  await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS - 1);
+  expect(far).toMatchObject({ sent: ["one"], open: 1 });
+  await vi.advanceTimersByTimeAsync(1);
+  expect(far).toMatchObject({ open: 0 });
+  // the alarm wakes the context to say it again
+  expect(unanswered).toMatchObject({ tries: 1 });
+  expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS);
+  expect(vi.getTimerCount()).toBe(0);
+  vi.useRealTimers();
+});
+
+test("work that comes back during the wait for an answer keeps the socket", async () => {
+  vi.useFakeTimers();
+  const far = farEnd();
+  far.answers = false;
+  let summary = "one";
+  const awake = new AwakeSocket({
+    path: "/agents/a",
+    dial: far.dial,
+    busy: () => false,
+    summary: () => summary,
+  });
+  awake.entered();
+  await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + 100);
+  expect(far).toMatchObject({ sent: ["one"], open: 1 });
+  awake.entered();
+  summary = "two";
+  far.answers = true;
+  far.answer();
+  await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
+  expect(far).toMatchObject({ dials: 1, sent: ["one", "two"], open: 0 });
+  expect(awake.recoverAt()).toBeNull();
+  vi.useRealTimers();
+});
+
+test("an unanswered summary is said again by the alarm, at longer waits, and then no more", async () => {
+  vi.useFakeTimers();
+  const far = farEnd();
+  far.answers = false;
+  const unanswered = counted();
+  const warned = vi.spyOn(console, "warn").mockImplementation(() => {});
+  vi.spyOn(console, "info").mockImplementation(() => {});
+  const awake = new AwakeSocket({
+    path: "/agents/a",
+    dial: far.dial,
+    busy: () => false,
+    summary: () => "one",
+    unanswered,
+  });
+  awake.entered();
+  const waits: number[] = [];
+  for (let tried = 1; tried <= AWAKE_SAY_AGAIN_TRIES; tried++) {
+    await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS);
+    expect(unanswered, `try ${tried}`).toMatchObject({ tries: tried });
+    const at = awake.recoverAt()!;
+    waits.push(at - Date.now());
+    // the alarm is not due before its time
+    expect(awake.recover(at - 1)).toBe(false);
+    await vi.advanceTimersByTimeAsync(at - Date.now());
+    expect(awake.recover(Date.now())).toBe(true);
+  }
+  expect(waits).toEqual([30_000, 60_000, 120_000, 240_000, 480_000, 960_000, 1_800_000, 1_800_000]);
+  // the last try is unanswered too: a warning, and nothing is owed
+  await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS);
+  // each try said the summary again, on a socket of its own
+  expect(far).toMatchObject({ dials: AWAKE_SAY_AGAIN_TRIES + 1, open: 0 });
+  expect(far.sent).toHaveLength(AWAKE_SAY_AGAIN_TRIES + 1);
+  expect(warned).toHaveBeenCalledWith(
+    expect.objectContaining({ event: "context.awake-summary-gave-up", path: "/agents/a" }),
+  );
+  expect(awake.recoverAt()).toBeNull();
+  expect(unanswered).toMatchObject({ tries: 0 });
+  expect(vi.getTimerCount()).toBe(0);
+  vi.useRealTimers();
+});
+
+test("the catalog's answer to a summary said again takes the count away", async () => {
+  vi.useFakeTimers();
+  vi.spyOn(console, "info").mockImplementation(() => {});
+  const far = farEnd();
+  far.answers = false;
+  const unanswered = counted();
+  const awake = new AwakeSocket({
+    path: "/agents/a",
+    dial: far.dial,
+    busy: () => false,
+    summary: () => "one",
+    unanswered,
+  });
+  awake.entered();
+  await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS);
+  expect(unanswered).toMatchObject({ tries: 1 });
+  far.answers = true;
+  expect(awake.recover(awake.recoverAt()!)).toBe(true);
+  await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
+  expect(far).toMatchObject({ sent: ["one", "one"], open: 0 });
+  expect(unanswered).toMatchObject({ tries: 0 });
+  expect(awake.recoverAt()).toBeNull();
+  vi.useRealTimers();
+});
+
+test("a socket that ends with a summary unanswered under a working context: the next socket says it at once", async () => {
+  vi.useFakeTimers();
+  const far = farEnd();
+  far.answers = false;
+  const awake = new AwakeSocket({
+    path: "/agents/a",
+    dial: far.dial,
+    busy: () => true,
+    summary: () => "one",
+  });
+  awake.entered();
+  await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
+  expect(far).toMatchObject({ dials: 1, sent: ["one"] });
+  far.closeAll();
+  far.answers = true;
+  // the same words again, and long before the next summary would be due
+  await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
+  expect(far).toMatchObject({ dials: 2, sent: ["one", "one"], open: 1 });
+  vi.useRealTimers();
+});
+
+test("a context that goes quiet with no socket owes its summary to the alarm", async () => {
+  vi.useFakeTimers();
+  vi.spyOn(console, "info").mockImplementation(() => {});
+  const far = farEnd();
+  far.refuse = true;
+  const unanswered = counted();
+  const awake = new AwakeSocket({
+    path: "/agents/a",
+    dial: far.dial,
+    busy: () => false,
+    summary: () => "one",
+    unanswered,
+  });
+  awake.entered();
+  await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
+  expect(far).toMatchObject({ dials: 1, sent: [] });
+  expect(unanswered).toMatchObject({ tries: 1 });
+  expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS);
+  vi.useRealTimers();
+});
+
+/** Where a context keeps how often its summary went unanswered: its own storage, here a field. */
+function counted() {
+  const kept = {
+    tries: 0,
+    count: () => kept.tries,
+    set: (tries: number) => void (kept.tries = tries),
+  };
+  return kept;
+}
+
+/** The accepting context, as the dialer sees it: counts dials and the sockets that are open, and
+ *  answers each summary as the catalog does, unless `answers` is off. */
 function farEnd() {
   const closers = new Set<() => void>();
+  const answerers = new Set<() => void>();
   const far = {
     dials: 0,
     open: 0,
     sent: [] as string[],
     refuse: false,
+    answers: true,
     closeAll: () => closers.forEach((close) => close()),
+    /** One answer on each open socket: what a catalog that was slow sends at last. */
+    answer: () => answerers.forEach((answer) => answer()),
     dial: async () => {
       far.dials += 1;
       if (far.refuse) return { status: 503 };
-      const listeners: (() => void)[] = [];
+      const listeners: Record<string, (() => void)[]> = {};
+      const answer = () => (listeners.message || []).forEach((listener) => listener());
       const close = () => {
         if (!closers.delete(close)) return;
+        answerers.delete(answer);
         far.open -= 1;
-        listeners.forEach((listener) => listener());
+        (listeners.close || []).forEach((listener) => listener());
       };
       return {
         status: 101,
@@ -204,12 +407,16 @@
           accept: () => {
             far.open += 1;
             closers.add(close);
+            answerers.add(answer);
           },
           close,
-          send: (message: string) => void far.sent.push(message),
+          send: (message: string) => {
+            far.sent.push(message);
+            if (far.answers) queueMicrotask(answer);
+          },
           // the one cast: a test socket has only what the dialer uses
-          addEventListener: ((_type: string, listener: () => void) =>
-            void listeners.push(listener)) as WebSocket["addEventListener"],
+          addEventListener: ((type: string, listener: () => void) =>
+            void (listeners[type] ||= []).push(listener)) as WebSocket["addEventListener"],
         },
       };
     },
M core/itx/src/context/awake.ts
@@ -18,6 +18,18 @@
 // one SQLite row (context-catalog.ts): one row written per wake of a context, beside the rows that
 // wake writes in its own log.
 //
+// THE CATALOG ANSWERS EACH SUMMARY, on the same socket: it kept it, or it refused it. A context
+// that goes quiet keeps its socket until its last summary is answered, at most
+// `AWAKE_ANSWER_WAIT_MS`. What stays unanswered is said again:
+// - while the context works, on the next socket, at once;
+// - after it went quiet, by its own alarm, on the durable ladder (`AWAKE_SAY_AGAIN_AFTER_MS`,
+//   doubled to at most 30 minutes, `AWAKE_SAY_AGAIN_TRIES` times, then a warning and no more);
+// - after its object died with the summary unsaid, by the alarm that every entry leaves no later
+//   than `AWAKE_RECOVER_AFTER_MS` ahead, and that a quiet close with every answer takes away.
+// So a row of the catalog is behind its context's log for a bounded time, and a row that stays
+// behind is in the log of the context that gave up. It costs a context that has no earlier alarm
+// two alarm writes for each time it works.
+//
 // The accepting context is not `/`: every wake of `/` restarts the root's facets, and the root
 // would wake twice for each wake of any other context.
 
@@ -39,6 +51,23 @@
 export const AWAKE_ACTIVITY_DEBOUNCE_MS = 100;
 /** After a dial that failed, no other dial for this long. */
 export const AWAKE_REDIAL_AFTER_MS = 10_000;
+/** What the accepting context answers a summary with, on the same socket: it kept it as the
+ *  context's row, or it refused it (a summary that is none, which would be refused again). */
+export const AWAKE_SUMMARY_KEPT = "kept";
+export const AWAKE_SUMMARY_REFUSED = "refused";
+/** How long a context that went quiet keeps its socket for the answer to its last summary. It is
+ *  billed as the quiet window is. The accepting context wakes from hibernation for a summary,
+ *  which took 0.1 to 0.6 s on a deployed mind (26 November 2026). */
+export const AWAKE_ANSWER_WAIT_MS = 3_000;
+/** A context that entered keeps an alarm no later than this after the entry, until the catalog
+ *  has answered all it said. It is past the longest hold, so a context that closes its socket
+ *  with every answer takes the alarm away before it fires. */
+export const AWAKE_RECOVER_AFTER_MS = AWAKE_MAX_HOLD_MS + 60_000;
+/** After a quiet close with a summary unanswered: the wait before the context says it again. It
+ *  doubles at each try in a row, to at most 30 minutes. */
+export const AWAKE_SAY_AGAIN_AFTER_MS = 30_000;
+/** How many times in a row a context says an unanswered summary again before it gives up. */
+export const AWAKE_SAY_AGAIN_TRIES = 8;
 
 export type AwakeContext = {
   path: string;
@@ -113,13 +142,15 @@
 
 /** Every context with an open socket here, by path, with when it woke and its latest live
  *  activities. A context that dialed twice (its first socket's close has not arrived) is there
- *  once, with its earlier wake time and the newest socket state. */
+ *  once, with its earlier wake time and the newest socket state. `except` is a socket whose close
+ *  is being handled: it counts as closed, whatever its state says. */
 export function awakeContexts(
   ctx: Pick<DurableObjectState, "getWebSockets">,
+  except?: WebSocket,
 ): Map<string, AwakeContextState> {
   const byPath = new Map<string, AwakeContextState & { updatedAt: number }>();
   for (const ws of ctx.getWebSockets(AWAKE_WEBSOCKET_TAG)) {
-    if (ws.readyState !== WebSocket.OPEN) continue;
+    if (ws === except || ws.readyState !== WebSocket.OPEN) continue;
     const { path, since, updatedAt, activities } = awakeContextOf(ws);
     const rank = updatedAt ?? since;
     const prior = byPath.get(path);
@@ -172,6 +203,12 @@
    *  socket before the socket closes, and while the context works, whenever it differs from what
    *  was sent last. */
   summary?: () => string;
+  /** `recoverAt()` changed: the context's alarm is set again from it. */
+  recoveryChanged?: () => void;
+  /** How many times in a row the context went quiet with a summary unanswered, kept where the
+   *  end of the object does not lose it. Read only when that happens again, and written then and
+   *  when the catalog answers at last. Absent: counted in memory. */
+  unanswered?: { count(): number; set(count: number): void };
 };
 
 /** The dialing side: one per context. `entered()` at every entry that is work; the socket and the
@@ -188,6 +225,17 @@
   #activityDirty = false;
   #sentSummary: string | undefined;
   #sentSummaryAt = 0;
+  /** Summaries that this socket sent and the catalog has not answered. */
+  #unanswered = 0;
+  /** Runs while a quiet context keeps its socket for the answer to its last summary. */
+  #answerWait: ReturnType<typeof setTimeout> | undefined;
+  /** A socket ended with a summary unanswered: the next one says the summary at once. */
+  #sayAgain = false;
+  #recoverAt: number | undefined;
+  /** This object counted an unanswered summary, or was woken to say one again: the catalog's
+   *  answer then takes the count away. */
+  #counted = false;
+  #triesInMemory = 0;
 
   constructor(deps: AwakeSocketDeps) {
     this.#deps = deps;
@@ -195,13 +243,35 @@
 
   entered(): void {
     if (this.#deps.path === AWAKE_CONTEXT_PATH) return;
-    this.#lastEntryAt = Date.now();
+    const now = Date.now();
+    this.#lastEntryAt = now;
+    // work came back while the socket waited for its last answer: the socket stays
+    this.#stopAnswerWait();
+    if (this.#recoverAt === undefined || this.#recoverAt <= now)
+      this.#recoverBy(now + AWAKE_RECOVER_AFTER_MS);
     this.#open();
     if (this.#timer === undefined) this.#recheckIn(AWAKE_QUIET_MS);
   }
 
+  /** When the context's alarm must wake it, so that it says its summary again: from an entry
+   *  until the catalog has answered all that the context said. Null: nothing is owed. */
+  recoverAt(): number | null {
+    return this.#recoverAt ?? null;
+  }
+
+  /** The context's alarm fired. When that time has come, the context enters as for work, and so
+   *  says its summary again: true. It writes no wake record: the summary is of the log as it is. */
+  recover(now: number): boolean {
+    if (this.#recoverAt === undefined || this.#recoverAt > now) return false;
+    this.#counted = true;
+    this.entered();
+    return true;
+  }
+
   /** Coalesces rapid activity stack mutations and pushes the updated summary while the context
-   *  is awake, without holding an idle context open or leaving a timer after close. */
+   *  is awake, without holding an idle context open or leaving a timer after close. The commit of
+   *  what the summary says of the context for good (`events.iterate.com/itx/described`) calls it
+   *  too, so a watcher of the catalog sees a new title within the debounce. */
   activityChanged(): void {
     if (this.#deps.path === AWAKE_CONTEXT_PATH || this.#timer === undefined) return;
     this.#activityDirty = true;
@@ -216,6 +286,12 @@
     }, AWAKE_ACTIVITY_DEBOUNCE_MS);
   }
 
+  #recoverBy(at: number | undefined): void {
+    if (at === this.#recoverAt) return;
+    this.#recoverAt = at;
+    this.#deps.recoveryChanged?.();
+  }
+
   #recheckIn(ms: number): void {
     this.#timer = setTimeout(() => {
       this.#timer = undefined;
@@ -247,17 +323,33 @@
           throw new Error(`the dial was answered ${response.status}`);
         socket.accept();
         this.#socket = socket;
+        this.#unanswered = 0;
+        const gone = () => {
+          if (this.#socket !== socket) return;
+          this.#socket = undefined;
+          if (this.#unanswered === 0) return;
+          // what this socket said may not be kept: the next socket says it at once
+          this.#unanswered = 0;
+          this.#sentSummary = undefined;
+          this.#sayAgain = true;
+          if (this.#answerWait === undefined) return;
+          this.#stopAnswerWait();
+          this.#wentQuietUnanswered("its socket closed before the answer");
+        };
+        socket.addEventListener("close", gone);
+        socket.addEventListener("error", gone);
+        // each message of the far end answers one summary, in the order they were sent
+        socket.addEventListener("message", () => {
+          if (this.#socket !== socket || this.#unanswered === 0) return;
+          this.#unanswered -= 1;
+          if (this.#unanswered === 0 && this.#answerWait !== undefined) this.#closeAnswered();
+        });
         // the context went quiet while the dial was on its way: its summary still goes
         if (this.#timer === undefined) return this.#close();
-        if (this.#activityDirty && this.#activityTimer === undefined) {
+        if (this.#sayAgain || (this.#activityDirty && this.#activityTimer === undefined)) {
           this.#activityDirty = false;
           this.#sendSummary();
         }
-        const gone = () => {
-          if (this.#socket === socket) this.#socket = undefined;
-        };
-        socket.addEventListener("close", gone);
-        socket.addEventListener("error", gone);
       })
       .catch((error: unknown) => {
         this.#noDialBefore = Date.now() + AWAKE_REDIAL_AFTER_MS;
@@ -266,6 +358,9 @@
           path: this.#deps.path,
           message: error instanceof Error ? error.message : String(error),
         });
+        // quiet already, and no socket came: nothing said the context's last summary
+        if (this.#timer === undefined && this.#answerWait === undefined)
+          this.#wentQuietUnanswered("its dial failed");
       })
       .finally(() => {
         this.#dialing = false;
@@ -281,6 +376,8 @@
       this.#socket.send(summary);
       this.#sentSummary = summary;
       this.#sentSummaryAt = Date.now();
+      this.#sayAgain = false;
+      this.#unanswered += 1;
     } catch (error) {
       console.info({
         event: "context.awake-summary-failed",
@@ -290,19 +387,80 @@
     }
   }
 
+  // The context is quiet: its last summary goes, and the socket closes when the catalog has
+  // answered it, or after `AWAKE_ANSWER_WAIT_MS`.
   #close(): void {
     if (this.#activityTimer !== undefined) {
       clearTimeout(this.#activityTimer);
       this.#activityTimer = undefined;
     }
     this.#activityDirty = false;
+    // a context that says nothing of itself owes the catalog nothing
+    if (!this.#deps.summary) return this.#closeAnswered();
     this.#sendSummary();
+    if (!this.#socket) {
+      // a dial on its way closes the socket it brings (`#open`), with the summary
+      if (!this.#dialing) this.#wentQuietUnanswered("it had no socket");
+      return;
+    }
+    if (this.#unanswered === 0 && !this.#sayAgain) return this.#closeAnswered();
+    this.#answerWait = setTimeout(() => {
+      this.#answerWait = undefined;
+      this.#closeSocket();
+      this.#wentQuietUnanswered("the catalog did not answer in time");
+    }, AWAKE_ANSWER_WAIT_MS);
+  }
+
+  #stopAnswerWait(): void {
+    if (this.#answerWait === undefined) return;
+    clearTimeout(this.#answerWait);
+    this.#answerWait = undefined;
+  }
+
+  #closeSocket(): void {
     const socket = this.#socket;
     this.#socket = undefined;
+    this.#unanswered = 0;
     try {
       socket?.close(1000, "quiet");
     } catch {
       // already closing
     }
+  }
+
+  /** Quiet, and the catalog answered all that the context said: nothing is owed. */
+  #closeAnswered(): void {
+    this.#stopAnswerWait();
+    this.#closeSocket();
+    if (this.#counted) {
+      this.#counted = false;
+      this.#triesInMemory = 0;
+      this.#deps.unanswered?.set(0);
+    }
+    this.#recoverBy(undefined);
+  }
+
+  /** Quiet with a summary that the catalog did not answer: the context's alarm wakes it to say
+   *  the summary again, a longer wait at each try in a row, and after the last try nothing does. */
+  #wentQuietUnanswered(why: string): void {
+    this.#sentSummary = undefined;
+    const tries = (this.#deps.unanswered?.count() ?? this.#triesInMemory) + 1;
+    const gaveUp = tries > AWAKE_SAY_AGAIN_TRIES;
+    this.#counted = !gaveUp;
+    this.#triesInMemory = gaveUp ? 0 : tries;
+    this.#deps.unanswered?.set(this.#triesInMemory);
+    if (gaveUp) {
+      console.warn({
+        event: "context.awake-summary-gave-up",
+        path: this.#deps.path,
+        message: `the catalog did not answer this context's summary ${AWAKE_SAY_AGAIN_TRIES} times in a row: its row stays as it is until the context next has work`,
+        why,
+      });
+      return this.#recoverBy(undefined);
+    }
+    console.info({ event: "context.awake-summary-unanswered", path: this.#deps.path, why, tries });
+    this.#recoverBy(
+      Date.now() + Math.min(AWAKE_SAY_AGAIN_AFTER_MS * 2 ** (tries - 1), 30 * 60_000),
+    );
   }
 }
M core/itx/src/context/built-ins.ts
@@ -9,7 +9,7 @@
   type ItxExpressionInput,
   InvokeHandle,
 } from "iterate/expression";
-import type { FacetSpec, IterateContextApi } from "iterate/api";
+import type { CatalogWatches, FacetSpec, IterateContextApi } from "iterate/api";
 import { failureKind, ONCE_NOW, retryPlatformFailures } from "iterate/platform-retry";
 import type { Cause } from "../cause.ts";
 import { refusePlatformIdempotencyKeys, sha256Hex, stampCaller, type Caller } from "../caller.ts";
@@ -37,6 +37,7 @@
 import { unavailableError } from "../unavailable.ts";
 import { facetSpecOf, hostedFacetMarkerOf } from "../stream/core-processor.ts";
 import { AWAKE_CONTEXT_PATH } from "./awake.ts";
+import { catalogWatchTicket, type CatalogWatchTicket } from "./catalog-watch.ts";
 import { DurableObjectNameCodec } from "./paths.ts";
 import { requestScriptRun } from "./run.ts";
 import type { Connections } from "./connections.ts";
@@ -86,7 +87,11 @@
     get(rpcStubKey: string): RpcStubHandle;
   };
   rewriteRules: IterateContextApi["rewriteRules"];
-  contexts: IterateContextApi["contexts"];
+  contexts: Omit<IterateContextApi["contexts"], "watch"> & {
+    // The half of a watch that this table gates: the query, checked, as a ticket for the session's
+    // end, which alone holds the callback and the socket (../iterate-context.ts `#watchContexts`).
+    watch(query: unknown, options?: unknown): Promise<CatalogWatchTicket>;
+  };
   facets: Omit<IterateContextApi["facets"], "get"> & {
     get(name: string, spec?: FacetSpec): FacetHandle;
   };
@@ -434,6 +439,14 @@
         contexts()
           .getByName(DurableObjectNameCodec.stringify(AWAKE_CONTEXT_PATH))
           .listContexts(options || {}),
+      // A ticket opens nothing: the session's end dials the catalog with it (catalog-watch.ts).
+      // It is answered here so that a watch passes this table as a list does.
+      watch: async (query, options) => catalogWatchTicket(query, options),
+      // The cast: workerd's RPC types read a window's bound, a pair, as a list.
+      watches: (options) =>
+        contexts()
+          .getByName(DurableObjectNameCodec.stringify(AWAKE_CONTEXT_PATH))
+          .catalogWatches(options || {}) as unknown as Promise<CatalogWatches>,
     },
     workers: workersRoot({
       path,
A core/itx/src/context/catalog-watch.test.ts
@@ -0,0 +1,295 @@
+// The session's end of a watch of the catalog: what it does when the socket into the catalog
+// drops, when a frame is missing, when the catalog refuses a query and when the session ends. The
+// catalog's end is a socket that a test writes to by hand; the whole path, with a real catalog and
+// a real capnweb session, is core/mind-worker/src/context/catalog-watch.test.ts.
+import type { CatalogFrame } from "iterate/api";
+import { expect, onTestFinished, test, vi } from "vitest";
+import { CatalogWatchRelay, catalogWatchTicket, isCatalogWatchTicket } from "./catalog-watch.ts";
+import {
+  RPC_STUB_PAGER_KEEPALIVE_REQUEST,
+  RPC_STUB_PAGER_KEEPALIVE_RESPONSE,
+} from "./rpc-stubs.ts";
+
+test("a watch sends the query once, and the catalog's answer and changes come as frames", async () => {
+  const far = catalog();
+  const relay = far.relay();
+  const frames: CatalogFrame<unknown>[] = [];
+  const watching = relay.watch(ticket({ where: { status: "open" } }), (frame) =>
+    frames.push(frame),
+  );
+  const socket = await far.asked();
+  expect(socket).toMatchObject({
+    sent: [{ op: "subscribe", sub: "w1", query: { where: { status: "open" } } }],
+  });
+  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [{ path: "/a" }] });
+  using _watch = await watching;
+  socket.say({ gen: "g", rows: [{ path: "/b" }], d: [["w1", 4, 5, ["/a"], ["/b"]]] });
+  expect(frames).toEqual([
+    { type: "reset", gen: "g", rev: 4, q: "q", full: false, rows: [{ path: "/a" }] },
+    { type: "change", gen: "g", from: 4, rev: 5, del: ["/a"], rows: [{ path: "/b" }] },
+  ]);
+});
+
+test("a cursor goes with the query, and its answer is a resume frame", async () => {
+  const far = catalog();
+  const relay = far.relay();
+  const frames: CatalogFrame<unknown>[] = [];
+  const cursor = { gen: "g", rev: 3, q: "q", bound: [7, "/a"] as [number, string] };
+  const watching = relay.watch(catalogWatchTicket({ limit: 5 }, { cursor }), (frame) =>
+    frames.push(frame),
+  );
+  const socket = await far.asked();
+  expect(socket.sent[0]).toMatchObject({ cursor });
+  socket.say({ sub: "w1", q: "q", gen: "g", rev: 6, full: true, ids: ["/a", "/b"], put: [] });
+  using _watch = await watching;
+  expect(frames).toEqual([
+    { type: "resume", gen: "g", rev: 6, q: "q", full: true, ids: ["/a", "/b"], rows: [] },
+  ]);
+});
+
+test("one message of the catalog is one batch: every frame but the last says that more comes", async () => {
+  const far = catalog();
+  const relay = far.relay();
+  const batch: [string, boolean][] = [];
+  const first = relay.watch(ticket({ limit: 1 }), (frame) => batch.push(["first", !!frame.more]));
+  const socket = await far.asked();
+  const second = relay.watch(ticket({ limit: 2 }), (frame) => batch.push(["second", !!frame.more]));
+  await far.asked(2);
+  for (const sub of ["w1", "w2"])
+    socket.say({ sub, q: "q", gen: "g", rev: 1, full: false, reset: [] });
+  using _first = await first;
+  using _second = await second;
+  batch.length = 0;
+  socket.say({
+    gen: "g",
+    rows: [{ path: "/a" }],
+    d: [
+      ["w1", 1, 2, [], ["/a"]],
+      ["w2", 1, 2, [], ["/a"]],
+    ],
+  });
+  expect(batch).toEqual([
+    ["first", true],
+    ["second", false],
+  ]);
+});
+
+test("a frame that does not follow the one before asks the query again, and the watcher gets the whole answer", async () => {
+  const far = catalog();
+  const relay = far.relay();
+  const frames: CatalogFrame<unknown>[] = [];
+  const watching = relay.watch(ticket({ limit: 5 }), (frame) => frames.push(frame));
+  const socket = await far.asked();
+  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] });
+  using _watch = await watching;
+  // revision 5 never came
+  socket.say({ gen: "g", rows: [{ path: "/a" }], d: [["w1", 5, 6, [], ["/a"]]] });
+  expect(frames).toHaveLength(1);
+  // asked again with no cursor: this end holds no row to make one from
+  expect(socket.sent.at(-1)).toEqual({ op: "subscribe", sub: "w1", query: { limit: 5 } });
+  // a change that comes before the new answer is older than it, and is not passed on
+  socket.say({ gen: "g", rows: [], d: [["w1", 6, 7, ["/a"], []]] });
+  socket.say({ sub: "w1", q: "q", gen: "g", rev: 7, full: false, reset: [{ path: "/b" }] });
+  expect(frames.at(-1)).toMatchObject({ type: "reset", rev: 7, rows: [{ path: "/b" }] });
+  expect(frames).toHaveLength(2);
+});
+
+test("a socket that drops under a live session is dialled again, and every watch gets its whole answer", async () => {
+  vi.useFakeTimers();
+  onTestFinished(() => void vi.useRealTimers());
+  vi.spyOn(console, "info").mockImplementation(() => {});
+  const far = catalog();
+  const relay = far.relay();
+  const frames: CatalogFrame<unknown>[] = [];
+  const watching = relay.watch(ticket({ limit: 5 }), (frame) => frames.push(frame));
+  const socket = await far.asked();
+  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [{ path: "/a" }] });
+  using _watch = await watching;
+  // a deploy resets the catalog's object: the socket closes
+  socket.drop();
+  await vi.advanceTimersByTimeAsync(10);
+  const again = await far.asked();
+  expect(again).not.toBe(socket);
+  expect(again).toMatchObject({ sent: [{ op: "subscribe", sub: "w1", query: { limit: 5 } }] });
+  again.say({ sub: "w1", q: "q", gen: "h", rev: 1, full: false, reset: [{ path: "/b" }] });
+  expect(frames.at(-1)).toEqual({
+    type: "reset",
+    gen: "h",
+    rev: 1,
+    q: "q",
+    full: false,
+    rows: [{ path: "/b" }],
+  });
+});
+
+test("a socket whose keepalives go unanswered is taken for dead and dialled again", async () => {
+  vi.useFakeTimers();
+  onTestFinished(() => void vi.useRealTimers());
+  vi.spyOn(console, "info").mockImplementation(() => {});
+  const far = catalog();
+  const relay = far.relay();
+  const watching = relay.watch(ticket({ limit: 5 }), () => {});
+  const socket = await far.asked();
+  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] });
+  using _watch = await watching;
+  // the runtime answers for a catalog that sleeps: the socket stays
+  socket.answersKeepalives = true;
+  await vi.advanceTimersByTimeAsync(60_000);
+  expect(far).toMatchObject({ dials: 1 });
+  // a reset with no close: nothing answers any more
+  socket.answersKeepalives = false;
+  await vi.advanceTimersByTimeAsync(20_100);
+  expect(far).toMatchObject({ dials: 2 });
+});
+
+test("when the catalog cannot be dialled again, every watch ends and its handle says why", async () => {
+  vi.useFakeTimers();
+  onTestFinished(() => void vi.useRealTimers());
+  const failed = vi.spyOn(console, "error").mockImplementation(() => {});
+  const far = catalog();
+  const relay = far.relay();
+  const watching = relay.watch(ticket({ limit: 5 }), () => {});
+  const socket = await far.asked();
+  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] });
+  const watch = await watching;
+  far.refuses = true;
+  socket.drop();
+  await vi.advanceTimersByTimeAsync(61_000);
+  await expect(watch.ended()).resolves.toMatch(/could not be reached again/);
+  expect(failed).toHaveBeenCalledWith(
+    expect.objectContaining({ event: "catalog-watch.redial-failed" }),
+  );
+});
+
+test("a query that the catalog refuses rejects the call, and leaves no watch and no socket", async () => {
+  const far = catalog();
+  const relay = far.relay();
+  const watching = relay.watch(ticket({ limit: 5 }), () => {});
+  const socket = await far.asked();
+  socket.say({ sub: "w1", error: "the catalog holds at most 512 live queries" });
+  await expect(watching).rejects.toMatchObject({
+    code: "INVALID_INPUT",
+    message: expect.stringContaining("at most 512 live queries"),
+  });
+  expect(socket).toMatchObject({ closed: true });
+});
+
+test("the watcher's dispose takes the query off, and the last watch closes the socket", async () => {
+  const far = catalog();
+  const relay = far.relay();
+  const first = relay.watch(ticket({ limit: 1 }), () => {});
+  const socket = await far.asked();
+  const second = relay.watch(ticket({ limit: 2 }), () => {});
+  await far.asked(2);
+  for (const sub of ["w1", "w2"])
+    socket.say({ sub, q: "q", gen: "g", rev: 1, full: false, reset: [] });
+  const [one, two] = await Promise.all([first, second]);
+  one[Symbol.dispose]();
+  expect(socket.sent.at(-1)).toEqual({ op: "unsubscribe", sub: "w1" });
+  expect(socket).toMatchObject({ closed: false });
+  await expect(one.ended()).resolves.toBe("the watcher ended it");
+  two[Symbol.dispose]();
+  expect(socket).toMatchObject({ closed: true });
+});
+
+test("the session's end ends every watch, closes the socket, and takes no new watch", async () => {
+  const far = catalog();
+  const relay = far.relay();
+  const watching = relay.watch(ticket({ limit: 5 }), () => {});
+  const socket = await far.asked();
+  socket.say({ sub: "w1", q: "q", gen: "g", rev: 1, full: false, reset: [] });
+  const watch = await watching;
+  relay.dispose();
+  await expect(watch.ended()).resolves.toBe("the session ended");
+  expect(socket).toMatchObject({ closed: true });
+  await expect(relay.watch(ticket({ limit: 5 }), () => {})).rejects.toMatchObject({
+    code: "UNAVAILABLE",
+  });
+});
+
+test("a ticket is the query, checked: a callback, a second option or a query the catalog cannot answer is refused", () => {
+  expect(catalogWatchTicket({ under: "/agents", order: "path" }, undefined)).toEqual({
+    $itxCatalogWatch: { query: { under: "/agents", order: "path" }, cursor: undefined },
+  });
+  expect(isCatalogWatchTicket(catalogWatchTicket({}, {}))).toBe(true);
+  expect(isCatalogWatchTicket([{ path: "/a" }])).toBe(false);
+  // a function where the options stand: the call did not come through a session's end
+  expect(() => catalogWatchTicket({}, () => {})).toThrow(/a session's call/);
+  expect(() => catalogWatchTicket({}, { cursor: {}, more: 1 })).toThrow(/a session's call/);
+  expect(() => catalogWatchTicket({ orderBy: "title" }, undefined)).toThrow(/orderBy/);
+  expect(() => catalogWatchTicket({ keys: ["/a"], limit: 2 }, undefined)).toThrow(/stands alone/);
+});
+
+function ticket(query: Parameters<typeof catalogWatchTicket>[0]) {
+  return catalogWatchTicket(query, undefined);
+}
+
+/** The catalog's end of a watch socket, written to by hand. */
+function catalog() {
+  type Listener = (event: { data?: unknown; reason?: string }) => void;
+  const sockets: FarSocket[] = [];
+  const onSend: (() => void)[] = [];
+  class FarSocket {
+    sent: unknown[] = [];
+    closed = false;
+    answersKeepalives = false;
+    #listeners: Record<string, Listener[]> = {};
+    accept() {}
+    send(raw: string) {
+      if (this.closed) throw new Error("the socket is closed");
+      if (raw === RPC_STUB_PAGER_KEEPALIVE_REQUEST) {
+        if (this.answersKeepalives)
+          this.#emit("message", { data: RPC_STUB_PAGER_KEEPALIVE_RESPONSE });
+        return;
+      }
+      this.sent.push(JSON.parse(raw));
+      onSend.splice(0).forEach((heard) => heard());
+    }
+    close() {
+      this.closed = true;
+    }
+    addEventListener(type: string, listener: Listener) {
+      (this.#listeners[type] ||= []).push(listener);
+    }
+    #emit(type: string, event: { data?: unknown; reason?: string }) {
+      for (const listener of this.#listeners[type] || []) listener(event);
+    }
+    /** The catalog sends a message. */
+    say(message: unknown) {
+      this.#emit("message", { data: JSON.stringify(message) });
+    }
+    /** The catalog's object is gone: the socket closes under the session. */
+    drop() {
+      this.closed = true;
+      this.#emit("close", { reason: "the object was reset" });
+    }
+  }
+  const far = {
+    dials: 0,
+    refuses: false,
+    /** The newest socket, once the session's end has sent it `count` messages: it listens then. */
+    asked: async (count = 1) => {
+      for (;;) {
+        const socket = sockets.at(-1);
+        if (socket && !socket.closed && socket.sent.length >= count) return socket;
+        await new Promise<void>((heard) => onSend.push(heard));
+      }
+    },
+    relay: () => {
+      const relay = new CatalogWatchRelay({
+        dial: async () => {
+          far.dials += 1;
+          if (far.refuses) return { status: 503 };
+          const socket = new FarSocket();
+          sockets.push(socket);
+          return { status: 101, webSocket: socket as unknown as WebSocket };
+        },
+        waitUntil: () => {},
+      });
+      // its keepalive is a timer: a relay that outlives its test would dial in the next one
+      onTestFinished(() => relay.dispose());
+      return relay;
+    },
+  };
+  return far;
+}
A core/itx/src/context/catalog-watch.ts
@@ -0,0 +1,418 @@
+// catalog-watch.ts — THE SESSION'S END OF A WATCH OF THE CATALOG (`itx.contexts.watch`). A client
+// holds a capnweb callback and nothing else: its frames ride the connection that its session has
+// already. This file is what stands between that callback and the object that owns the rows:
+//
+//   client ─capnweb, the session's one connection─► the session's end (../iterate-context.ts)
+//   the session's end ─ONE hibernated WebSocket for all of the session's watches─► /awake
+//   /awake (reactive-catalog.ts) ─a message for each write─► here ─`onFrame(frame)`─► client
+//
+// The socket is dialled at the session's first watch and closed with its last one, or with the
+// session. It is the kernel's own dial into the context that accepts the awake sockets, as a
+// context's awake socket is (awake.ts): no client, no loaded code and no other Worker can open one.
+// The callback's stub lives here, in the stateless Worker, never in a Durable Object, so /awake
+// hibernates under any number of watchers.
+//
+// A SOCKET THAT ENDS UNDER A LIVE SESSION (a deploy resets every Durable Object) is dialled again,
+// and every watch is asked again with no cursor: each watcher gets a `reset` frame with the whole
+// answer. A frame that does not follow the one before (`from`) is treated the same way. When the
+// socket cannot be dialled again, every watch ends, and its handle's `ended()` says why.
+import { RpcTarget } from "capnweb";
+import { z } from "zod";
+import type { CatalogCursor, CatalogFrame, CatalogQuery } from "iterate/api";
+import { codedError } from "iterate/lib";
+import { redial } from "./redial.ts";
+import { CatalogRefusal, normalizeQuery } from "./reactive-catalog.ts";
+import {
+  disposeRpcStub,
+  RPC_STUB_PAGER_KEEPALIVE_REQUEST,
+  RPC_STUB_PAGER_KEEPALIVE_RESPONSE,
+} from "./rpc-stubs.ts";
+
+/** On a request to the context that accepts the awake sockets: the upgrade of a watch socket. */
+export const CATALOG_WATCH_HEADER = "x-itx-catalog-watch";
+
+/** How long a watch socket that dropped under a live session is dialled again before every watch
+ *  ends: as long as a lent stub's pager (rpc-stub-relay.ts). */
+const REDIAL_DEADLINE_MS = 60_000;
+/** A subscribe that the catalog does not answer in this time fails. The first watch of a mind
+ *  waits for the catalog's first fill, a page of 500 rows at a time. */
+const ANSWER_DEADLINE_MS = 60_000;
+/** The runtime answers a keepalive for /awake, which sleeps on (the Durable Object's
+ *  `setWebSocketAutoResponse`). Three in a row unanswered: the socket is dead, with no close. */
+const KEEPALIVE_EVERY_MS = 5_000;
+
+const WatchOptions = z.strictObject({ cursor: z.unknown().optional() }).optional();
+
+/** WHAT THE BUILT-IN `contexts.watch(query, options)` ANSWERS: the query, checked, for the
+ *  session's end, which alone holds a callback and a socket. The built-in is reached through a
+ *  context's own table, as `contexts.list` is, so who may list may watch. A ticket is data: it
+ *  opens nothing, and whoever else reads one has what it sent. */
+export type CatalogWatchTicket = {
+  $itxCatalogWatch: { query: CatalogQuery; cursor?: CatalogCursor };
+};
+
+export function catalogWatchTicket(query: unknown, options: unknown): CatalogWatchTicket {
+  const parsed = WatchOptions.safeParse(options);
+  if (!parsed.success)
+    throw codedError(
+      "INVALID_INPUT",
+      "contexts.watch(query, onFrame, { cursor? }) is a session's call: the callback stays at the session's end, and the only option is a cursor. Loaded code reads the catalog with contexts.list(options)",
+    );
+  try {
+    normalizeQuery(query);
+  } catch (error) {
+    if (error instanceof CatalogRefusal)
+      throw codedError("INVALID_INPUT", `contexts.watch: ${error.message}`);
+    throw error;
+  }
+  return {
+    $itxCatalogWatch: {
+      // checked above, and again by the catalog itself, which trusts no ticket
+      query: query as CatalogQuery,
+      cursor: parsed.data?.cursor as CatalogCursor | undefined,
+    },
+  };
+}
+
+export function isCatalogWatchTicket(value: unknown): value is CatalogWatchTicket {
+  // oxlint-disable-next-line iterate/simple-truthiness-check -- an answer of any shape: a table may send `contexts` to another object, which answers what it likes
+  return typeof value === "object" && value !== null && "$itxCatalogWatch" in value;
+}
+
+/** What `itx.contexts.watch` answers: a handle whose dispose ends the watch. `ended()` settles
+ *  when the watch ends in any other way, with the reason: the session ended, or the catalog could
+ *  not be reached again. */
+export class CatalogWatchHandle extends RpcTarget {
+  readonly #end: () => void;
+  readonly #ended: Promise<string>;
+  constructor(end: () => void, ended: Promise<string>) {
+    super();
+    this.#end = end;
+    this.#ended = ended;
+  }
+  ended(): Promise<string> {
+    return this.#ended;
+  }
+  [Symbol.dispose](): void {
+    this.#end();
+  }
+}
+
+/** A watcher's callback as this end holds it: a stub of the client's function, or the function. */
+type FrameCallback = ((frame: CatalogFrame<unknown>) => unknown) & { dup?(): FrameCallback };
+
+type Watch = {
+  query: CatalogQuery;
+  onFrame: FrameCallback;
+  /** Of the watch's last frame: a change must follow it. */
+  gen: string;
+  rev: number;
+  /** Settles the call that made the watch, at the catalog's first answer or its refusal. */
+  answered?: { resolve: () => void; reject: (error: Error) => void; timer: unknown };
+  end: (reason: string) => void;
+};
+
+/** What the catalog sends down a watch socket (reactive-catalog.ts, "THE WIRE"). */
+const SocketMessage = z.union([
+  z.object({
+    sub: z.string(),
+    q: z.string(),
+    gen: z.string(),
+    rev: z.number(),
+    full: z.boolean(),
+    reset: z.array(z.unknown()).optional(),
+    ids: z.array(z.string()).optional(),
+    put: z.array(z.unknown()).optional(),
+  }),
+  z.object({
+    gen: z.string(),
+    rows: z.array(z.looseObject({ path: z.string() })),
+    d: z.array(
+      z.tuple([z.string(), z.number(), z.number(), z.array(z.string()), z.array(z.string())]),
+    ),
+  }),
+  z.object({ sub: z.string().optional(), error: z.string() }),
+]);
+
+type DialAnswer = { status: number; webSocket?: WebSocket | null; body?: ReadableStream | null };
+
+/** ONE SESSION'S WATCHES, over one socket into the catalog. */
+export class CatalogWatchRelay {
+  readonly #dial: () => Promise<DialAnswer>;
+  readonly #waitUntil: (work: Promise<unknown>) => void;
+  readonly #watches = new Map<string, Watch>();
+  #socket: WebSocket | undefined;
+  #opening: Promise<WebSocket> | undefined;
+  #keepalive: ReturnType<typeof setInterval> | undefined;
+  #names = 0;
+  #over = false;
+
+  constructor(deps: {
+    /** The upgrade request to the context that accepts the awake sockets. */
+    dial: () => Promise<DialAnswer>;
+    waitUntil: (work: Promise<unknown>) => void;
+  }) {
+    this.#dial = deps.dial;
+    this.#waitUntil = deps.waitUntil;
+  }
+
+  /** Asks the catalog to keep answering the ticket's query. Resolves when the first frame, the
+   *  answer, has gone to `onFrame`; rejects with the catalog's reason when it refuses the query. */
+  async watch(ticket: CatalogWatchTicket, onFrame: FrameCallback): Promise<CatalogWatchHandle> {
+    if (this.#over) throw codedError("UNAVAILABLE", "contexts.watch: the session ended");
+    const { query, cursor } = ticket.$itxCatalogWatch;
+    // dup first: the stub is the call's alone, and a watch outlives the call
+    const callback = onFrame.dup ? onFrame.dup() : onFrame;
+    const sub = `w${(this.#names += 1).toString(36)}`;
+    let settleEnded = (_reason: string) => {};
+    const ended = new Promise<string>((resolve) => (settleEnded = resolve));
+    const watch: Watch = {
+      query,
+      onFrame: callback,
+      gen: "",
+      rev: -1,
+      end: (reason) => {
+        if (this.#watches.get(sub) !== watch) return;
+        this.#watches.delete(sub);
+        if (watch.answered) {
+          clearTimeout(watch.answered.timer as never);
+          watch.answered.reject(codedError("UNAVAILABLE", `contexts.watch: ${reason}`));
+        }
+        disposeRpcStub(callback);
+        settleEnded(reason);
+        if (this.#watches.size === 0) this.#closeSocket();
+      },
+    };
+    this.#watches.set(sub, watch);
+    // capnweb's death signal for the client's stub: the watch has nobody to tell
+    (callback as { onRpcBroken?: (broken: () => void) => void }).onRpcBroken?.(() =>
+      this.#drop(sub, "the watcher's session broke"),
+    );
+    try {
+      const socket = await this.#open();
+      await new Promise<void>((resolve, reject) => {
+        watch.answered = {
+          resolve,
+          reject,
+          timer: setTimeout(
+            () => reject(codedError("UNAVAILABLE", "contexts.watch: the catalog did not answer")),
+            ANSWER_DEADLINE_MS,
+          ),
+        };
+        socket.send(JSON.stringify({ op: "subscribe", sub, query, cursor }));
+      });
+    } catch (error) {
+      watch.answered = undefined;
+      this.#drop(sub, "the watch was refused");
+      throw error;
+    }
+    return new CatalogWatchHandle(() => this.#drop(sub, "the watcher ended it"), ended);
+  }
+
+  /** The session's end: every watch ends with it, and the socket closes. Final. */
+  dispose(): void {
+    this.#over = true;
+    for (const watch of [...this.#watches.values()]) watch.end("the session ended");
+    this.#closeSocket();
+  }
+
+  #drop(sub: string, reason: string): void {
+    const watch = this.#watches.get(sub);
+    if (!watch) return;
+    try {
+      this.#socket?.send(JSON.stringify({ op: "unsubscribe", sub }));
+    } catch {
+      // a socket that is closing takes its queries with it
+    }
+    watch.end(reason);
+  }
+
+  #closeSocket(): void {
+    clearInterval(this.#keepalive);
+    this.#keepalive = undefined;
+    const socket = this.#socket;
+    this.#socket = undefined;
+    try {
+      socket?.close(1000, "no watch is left");
+    } catch {
+      // already closing
+    }
+  }
+
+  #open(): Promise<WebSocket> {
+    if (this.#socket) return Promise.resolve(this.#socket);
+    this.#opening ||= this.#dial()
+      .then(async (answer) => {
+        if (answer.status !== 101 || !answer.webSocket) {
+          await answer.body?.cancel();
+          throw codedError(
+            "UNAVAILABLE",
+            `contexts.watch: the catalog answered the dial ${answer.status}`,
+          );
+        }
+        answer.webSocket.accept();
+        // the session ended, or its last watch went, while the dial was on its way
+        if (this.#over || this.#watches.size === 0) {
+          answer.webSocket.close(1000, "no watch is left");
+          throw codedError("UNAVAILABLE", "contexts.watch: the session ended");
+        }
+        this.#attach(answer.webSocket);
+        return answer.webSocket;
+      })
+      .finally(() => (this.#opening = undefined));
+    return this.#opening;
+  }
+
+  #attach(socket: WebSocket): void {
+    this.#socket = socket;
+    let unanswered = 0;
+    clearInterval(this.#keepalive);
+    this.#keepalive = setInterval(() => {
+      if (this.#socket !== socket) return;
+      if (unanswered >= 3) return this.#lost(socket, "its keepalives went unanswered");
+      // counted before the send: a send that throws is a keepalive that nobody answers
+      unanswered += 1;
+      try {
+        socket.send(RPC_STUB_PAGER_KEEPALIVE_REQUEST);
+      } catch {
+        // closing: its close event, or three unanswered keepalives, dials again
+      }
+    }, KEEPALIVE_EVERY_MS);
+    socket.addEventListener("message", (event) => {
+      unanswered = 0;
+      if (this.#socket !== socket || typeof event.data !== "string") return;
+      if (event.data === RPC_STUB_PAGER_KEEPALIVE_RESPONSE) return;
+      this.#received(event.data);
+    });
+    const gone = (event: { reason?: string }) => this.#lost(socket, event.reason || "it closed");
+    socket.addEventListener("close", gone);
+    socket.addEventListener("error", () => gone({ reason: "it failed" }));
+  }
+
+  /** The socket ended under watches that live: dial again, and ask every query again. */
+  #lost(socket: WebSocket, why: string): void {
+    if (this.#socket !== socket) return;
+    this.#closeSocket();
+    if (this.#over || this.#watches.size === 0) return;
+    this.#waitUntil(
+      redial(
+        this.#dial as () => Promise<DialAnswer & { webSocket?: WebSocket | null }>,
+        () => this.#over || this.#watches.size === 0,
+        REDIAL_DEADLINE_MS,
+      ).then((redialed) => {
+        if (!redialed) return;
+        if ("gaveUp" in redialed) {
+          console.error({
+            event: "catalog-watch.redial-failed",
+            message:
+              "a session's watch socket dropped and could not be dialled again: its watches end",
+            why,
+            lastFailure: redialed.gaveUp,
+          });
+          for (const watch of [...this.#watches.values()])
+            watch.end("the catalog could not be reached again: watch again");
+          return;
+        }
+        console.info({ event: "catalog-watch.redialed", why, attempt: redialed.dials });
+        this.#attach(redialed.socket);
+        for (const sub of this.#watches.keys()) this.#askAgain(sub);
+      }),
+    );
+  }
+
+  /** The watcher's next frame is the whole answer: it holds a frame that the catalog's next one
+   *  does not follow, or none that this socket knows of. */
+  #askAgain(sub: string): void {
+    const watch = this.#watches.get(sub);
+    if (!watch) return;
+    watch.gen = "";
+    watch.rev = -1;
+    try {
+      this.#socket?.send(JSON.stringify({ op: "subscribe", sub, query: watch.query }));
+    } catch {
+      // closing: the socket's end dials again and asks again
+    }
+  }
+
+  #received(raw: string): void {
+    let message: z.infer<typeof SocketMessage>;
+    try {
+      message = SocketMessage.parse(JSON.parse(raw));
+    } catch {
+      // the catalog's greeting, and its word that a query is taken off: nothing for a watcher
+      return;
+    }
+    if ("error" in message) {
+      const watch = this.#watches.get(message.sub || "");
+      if (!watch) return;
+      const refusal = codedError("INVALID_INPUT", `contexts.watch: ${message.error}`);
+      if (!watch.answered) return watch.end(message.error);
+      clearTimeout(watch.answered.timer as never);
+      watch.answered.reject(refusal);
+      return;
+    }
+    if ("d" in message) {
+      const rows = new Map(message.rows.map((row) => [row.path, row]));
+      message.d.forEach(([sub, from, rev, del, put], at) => {
+        const watch = this.#watches.get(sub);
+        // a watch that waits for its answer takes no change: the answer is newer than it
+        if (!watch || watch.rev < 0) return;
+        if (watch.gen !== message.gen || watch.rev !== from) return this.#askAgain(sub);
+        watch.rev = rev;
+        this.#send(watch, {
+          type: "change",
+          gen: message.gen,
+          from,
+          rev,
+          del,
+          rows: put.map((path) => rows.get(path)),
+          ...(at < message.d.length - 1 && { more: true }),
+        });
+      });
+      return;
+    }
+    const watch = this.#watches.get(message.sub);
+    if (!watch) return;
+    watch.gen = message.gen;
+    watch.rev = message.rev;
+    const head = { gen: message.gen, rev: message.rev, q: message.q, full: message.full };
+    this.#send(
+      watch,
+      message.reset
+        ? { type: "reset", ...head, rows: message.reset }
+        : { type: "resume", ...head, ids: message.ids || [], rows: message.put || [] },
+    );
+    if (!watch.answered) return;
+    clearTimeout(watch.answered.timer as never);
+    watch.answered.resolve();
+    watch.answered = undefined;
+  }
+
+  /** One frame to one watcher. Nothing waits for the watcher: the catalog's next frame goes when
+   *  it comes, and a callback that throws is its own page's fault. */
+  #send(watch: Watch, frame: CatalogFrame<unknown>): void {
+    try {
+      void Promise.resolve(watch.onFrame(frame)).then(disposeRpcStub, () => {});
+    } catch {
+      // a stub that broke: its `onRpcBroken` ends the watch
+    }
+  }
+}
+
+const relays = new WeakMap<object, CatalogWatchRelay>();
+
+/** The one relay of a session: every context that the session reaches by `cd` shares its
+ *  teardown, and so shares the socket. `register` puts the relay's end into that teardown. */
+export function catalogWatchRelayOf(
+  session: object,
+  make: () => CatalogWatchRelay,
+  register: (relay: CatalogWatchRelay) => void,
+): CatalogWatchRelay {
+  let relay = relays.get(session);
+  if (!relay) {
+    relay = make();
+    relays.set(session, relay);
+    register(relay);
+  }
+  return relay;
+}
M core/itx/src/context/context-activity-stack.test.ts
@@ -206,7 +206,24 @@
   };
 
   const extracted = catalog.store("/agents/builder", JSON.stringify(summaryMsg));
-  setAwakeActivities(ws, extracted);
+  setAwakeActivities(ws, extracted.activities);
+  // the row as a watched query serves it: the listing, and the two times the orders sort by
+  expect(extracted.row).toMatchObject({
+    path: "/agents/builder",
+    activeMs: Date.parse("2026-11-25T12:00:05.000Z"),
+    createdMs: Date.parse("2026-11-25T12:00:00.000Z"),
+    eventCount: 8,
+    processors: ["agent"],
+    description: "Builds pull requests",
+  });
+  expect(extracted.row).not.toHaveProperty("activities");
+  expect(extracted.row).not.toHaveProperty("throughOffset");
+  // a summary of an earlier offset is not kept, and so is no row for a watcher either
+  expect(
+    catalog.store("/agents/builder", JSON.stringify({ ...summaryMsg, throughOffset: 7 })),
+  ).toMatchObject({ row: undefined });
+  expect(catalog.rowsAfter("", 10)).toEqual([extracted.row]);
+  expect(catalog.rowsAfter("/agents/builder", 10)).toEqual([]);
 
   // SQLite `context_catalog.summary` must NOT contain ephemeral `activities`
   const storedColumns = rawRows();
@@ -249,6 +266,8 @@
     let open = 0;
     let busy = true;
     let stack: string[] = [];
+    // the accepting context answers each summary, as the catalog does (awake.ts)
+    const answerers: (() => void)[] = [];
     const awake = new AwakeSocket({
       path: "/agents/a",
       busy: () => busy,
@@ -262,8 +281,13 @@
           close: () => {
             open -= 1;
           },
-          send: (msg: string) => void sent.push(msg),
-          addEventListener: (() => undefined) as WebSocket["addEventListener"],
+          send: (msg: string) => {
+            sent.push(msg);
+            queueMicrotask(() => answerers.forEach((answer) => answer()));
+          },
+          addEventListener: ((type: string, listener: () => void) => {
+            if (type === "message") answerers.push(listener);
+          }) as WebSocket["addEventListener"],
         },
       }),
     });
@@ -503,8 +527,8 @@
       const rows = db.prepare(query).all(...(bindings as never[])) as T[];
       return { toArray: () => rows };
     }
-    db.prepare(query).run(...(bindings as never[]));
-    return { toArray: () => [] as T[] };
+    const { changes } = db.prepare(query).run(...(bindings as never[]));
+    return { toArray: () => [] as T[], rowsWritten: Number(changes) };
   };
   return {
     sql: { exec } as unknown as SqlStorage,
M core/itx/src/context/context-catalog.ts
@@ -2,11 +2,13 @@
 // storage of the context that accepts the awake sockets (awake.ts). A row is the newest summary
 // its context sent (context-summary.ts). A list joins the rows with the open sockets, so "awake"
 // and live `activities` are never stored in SQLite: when a socket closes, both vanish at once.
+// A watched query reads a copy of these rows, kept beside them (reactive-catalog.ts).
 import { z } from "zod";
 import type { ContextListing, ContextListOptions } from "iterate/api";
 import type { AwakeContextState } from "./awake.ts";
 import { activeContextActivities, ContextActivity } from "./context-activity-stack.ts";
 import { ContextSummary } from "./context-summary.ts";
+import type { CatalogRowInput } from "./reactive-catalog.ts";
 
 /** Durable fields stored in SQLite `context_catalog.summary` (never live `activities`). */
 const StoredContextSummary = ContextSummary.extend({
@@ -47,11 +49,16 @@
 
   /** Keeps the durable part of `message` as `path`'s row unless the row is of a later offset, and
    *  returns the live `activities` carried on the message so the caller can attach them to the
-   *  open awake socket (never SQLite). A message that is no summary is refused with a thrown error. */
-  store(path: string, message: string): ContextActivity[] | undefined {
+   *  open awake socket (never SQLite). `row` is the row as a watched query serves it, when the
+   *  message was kept: the copy beside this table takes it (reactive-catalog.ts). A message that
+   *  is no summary is refused with a thrown error. */
+  store(
+    path: string,
+    message: string,
+  ): { activities: ContextActivity[] | undefined; row: CatalogRowInput | undefined } {
     const { activities, ...durable } = ContextSummaryMessage.parse(JSON.parse(message));
     this.#table();
-    this.#sql.exec(
+    const { rowsWritten } = this.#sql.exec(
       `INSERT INTO context_catalog (path, through_offset, active_at, summary) VALUES (?, ?, ?, ?)
        ON CONFLICT (path) DO UPDATE SET
          through_offset = excluded.through_offset,
@@ -63,9 +70,26 @@
       durable.lastActivityAt || durable.lastEventAt || "",
       JSON.stringify(durable),
     );
-    return activities;
+    return { activities, row: rowsWritten > 0 ? watchedRowOf(path, durable) : undefined };
   }
 
+  /** A page of the rows, in path order, after the path `after`: what the copy for watched queries
+   *  is first filled from. A row that no longer parses as a summary is left out. */
+  rowsAfter(after: string, limit: number): CatalogRowInput[] {
+    this.#table();
+    return this.#sql
+      .exec<{ path: string; summary: string }>(
+        "SELECT path, summary FROM context_catalog WHERE path > ? ORDER BY path LIMIT ?",
+        after,
+        limit,
+      )
+      .toArray()
+      .flatMap(({ path, summary }) => {
+        const stored = StoredContextSummary.safeParse(JSON.parse(summary));
+        return stored.success ? [watchedRowOf(path, stored.data)] : [];
+      });
+  }
+
   /** The contexts that match, the most recently active first. `awake` is the open sockets, by
    *  path, with their live in-memory activities. Sleeping contexts never carry `activities`. */
   list(
@@ -171,4 +195,19 @@
     const unlisted = candidates.filter((path) => !storedByPath.has(path)).map(toUnlistedAwake);
     return [...unlisted, ...listed].slice(0, limit);
   }
+}
+
+/** A context's row as a watched query serves it (iterate/api `CatalogRow`): its listing, and the
+ *  two times that the orders sort by, as numbers. The order `active` is this table's own order:
+ *  the newest activity, or the newest event without one. A context with no time yet sorts last. */
+function watchedRowOf(
+  path: string,
+  { throughOffset: _, ...listing }: z.infer<typeof StoredContextSummary>,
+): CatalogRowInput {
+  return {
+    path,
+    activeMs: Date.parse(listing.lastActivityAt || listing.lastEventAt || "") || 0,
+    createdMs: Date.parse(listing.createdAt || "") || 0,
+    ...listing,
+  };
 }
M core/itx/src/context/itx-expression-rewriting.ts
@@ -53,7 +53,7 @@
   rpcStubs: "live values clients lent here: `rpcStubs.list()` · `rpcStubs.get(key)`",
   rewriteRules: "this table, described: `await rewriteRules.list()`",
   contexts:
-    "the mind's catalog of its contexts, the most recently active first: `await itx.cd('/').contexts.list({ search?, under?, awake?, limit? })` → [{ path, awake?, lastActivityAt, eventCount, eventTypes, recentTypes, processors, description?, metadata? }]; a context describes itself with `itx.append({ type: 'events.iterate.com/itx/described', payload: { description, metadata } })`",
+    "the mind's catalog of its contexts, the most recently active first: `await itx.cd('/').contexts.list({ search?, under?, awake?, limit? })` → [{ path, awake?, lastActivityAt, eventCount, eventTypes, recentTypes, processors, description?, metadata? }]; a context describes itself with `itx.append({ type: 'events.iterate.com/itx/described', payload: { description, metadata } })`; a session keeps a query answered with `contexts.watch({ where?, under?, childrenOf?, order?, limit? } | { keys } | { awake: true }, onFrame)`, and `contexts.watches()` says who watches what",
   facets:
     "a durable facet hosted here: `facets.get(name)` · `facets.abort(name, reason?)` resets that one facet",
   abort:
A core/itx/src/context/reactive-catalog.test.ts
@@ -0,0 +1,909 @@
+// The reactive catalog against a brute-force oracle. The oracle shares no code with the engine:
+// its own facts, its own byte order (Buffer.compare), a filter, a sort and a slice over a model of
+// the rows. After EVERY operation each watcher's rows must equal the oracle's, each stored window
+// must agree with the rows, and a write must send a frame to exactly the queries whose answer it
+// changed.
+import { DatabaseSync } from "node:sqlite";
+import type { CatalogCursor, CatalogOrder, CatalogQuery } from "iterate/api";
+import { expect, test } from "vitest";
+import {
+  CATALOG_LIMITS,
+  compareTextBinary,
+  ReactiveCatalog,
+  type CatalogRowInput,
+} from "./reactive-catalog.ts";
+
+test("holds against a brute-force oracle through random writes, queries in every order, hibernations and reconnects", () => {
+  const total = { writes: 0, frames: 0, quiet: 0, resumes: 0, rowsHeld: 0, hibernations: 0 };
+  // a short run by default; the long run is 40 seeds of 3,000 operations
+  const seeds = Number(process.env.CATALOG_TEST_SEEDS || 6);
+  const steps = Number(process.env.CATALOG_TEST_STEPS || 800);
+  for (let seed = 1; seed <= seeds; seed++) {
+    const tally = runSeed(seed, steps);
+    for (const key of Object.keys(total) as (keyof typeof total)[]) total[key] += tally[key];
+  }
+  console.info({ event: "reactive-catalog.random-run", seeds, steps, ...total });
+  // the run did what it is for
+  expect(total.quiet).toBeGreaterThan(seeds * 20);
+  expect(total.resumes).toBeGreaterThan(seeds);
+  expect(total.rowsHeld).toBeGreaterThan(seeds);
+  expect(total.hibernations).toBeGreaterThan(seeds * 10);
+}, 600_000);
+
+test("orders text as SQLite does, by UTF-8 bytes", () => {
+  const texts = ["", "a", "a/", "ab", "b", "é", "z", "", "￿", "😀", "😀a", "𐀀", "퟿", "a", "a😀"];
+  for (const a of texts)
+    for (const b of texts)
+      expect(
+        Math.sign(compareTextBinary(a, b)),
+        `${JSON.stringify(a)} against ${JSON.stringify(b)}`,
+      ).toBe(Math.sign(byteOrder(a, b)));
+  // the case that JavaScript's own comparison gets wrong: U+E000 is before an emoji in UTF-8
+  expect(["😀", ""].sort()).toEqual(["😀", ""]);
+  expect(compareTextBinary("", "😀")).toBeLessThan(0);
+});
+
+test("the six steps of the acceptance test, counted", () => {
+  using object = fakeObject();
+  const catalog = object.wake();
+  catalog.fill();
+  // 600 open and 400 closed rows
+  catalog.upsertMany(
+    Array.from({ length: 1000 }, (_, index) =>
+      task(index, index < 600 ? "open" : "closed", 10_000 - index),
+    ),
+  );
+  const client = new Client();
+  client.connect(catalog);
+  const spec = { where: { status: "open" }, limit: 50 };
+  const statements = () => catalog.counters.statements;
+
+  // 1. the snapshot
+  let before = statements();
+  client.subscribe(catalog, "open", spec);
+  const sub = client.subs.get("open")!;
+  expect(sub.rows).toMatchObject({ size: 50 });
+  const snapshotStatements = statements() - before;
+  const paths = () => client.sorted(sub).map((row) => row.path);
+  expect(paths().slice(0, 1)).toEqual(["/tasks/t0000"]);
+  expect(paths().slice(49)).toEqual(["/tasks/t0049"]);
+
+  // 2. a row enters: the old 50th leaves in the same frame
+  before = statements();
+  sub.frames = 0;
+  expect(catalog.upsert(task(2000, "open", 20_000))).toMatchObject({ frames: 1, messages: 1 });
+  expect(sub).toMatchObject({ frames: 1 });
+  expect(paths()).toHaveLength(50);
+  expect(paths().slice(0, 1)).toEqual(["/tasks/t2000"]);
+  expect(sub.rows.has("/tasks/t0049")).toBe(false);
+  const enterStatements = statements() - before;
+
+  // 3. a row leaves: the 51st takes its place in the same frame
+  sub.frames = 0;
+  before = statements();
+  expect(catalog.upsert(task(2000, "closed", 20_001))).toMatchObject({ frames: 1 });
+  expect(sub).toMatchObject({ frames: 1 });
+  expect(paths()).toHaveLength(50);
+  expect(sub.rows.has("/tasks/t0049")).toBe(true);
+  const leaveStatements = statements() - before;
+
+  // 4. a row moves inside the window
+  sub.frames = 0;
+  expect(catalog.upsert(task(25, "open", 30_000))).toMatchObject({ frames: 1 });
+  expect(paths().slice(0, 1)).toEqual(["/tasks/t0025"]);
+
+  // 5. 1,000 unrelated updates of each kind: no frame, and no statement beyond the write's own
+  sub.frames = 0;
+  before = statements();
+  const seeks = catalog.counters.seeks;
+  for (let index = 0; index < 1000; index++)
+    catalog.upsert(task(600 + (index % 400), "closed", 40_000 + index));
+  const closedStatements = (statements() - before) / 1000;
+  before = statements();
+  for (let index = 0; index < 500; index++)
+    catalog.upsert(task(100 + index, "open", 5_000 - index));
+  const outsideStatements = (statements() - before) / 500;
+  expect(sub).toMatchObject({ frames: 0 });
+  expect(catalog.counters).toMatchObject({ seeks });
+  // the write's own statements: one read of the row, one write of it, the revision, and for each
+  // of its five facts one entry out and one in, in the index of the order `active` alone
+  expect({ closedStatements, outsideStatements }).toEqual({
+    closedStatements: 13,
+    outsideStatements: 13,
+  });
+
+  // 6. the watcher goes away, four rows change, and it comes back with its cursor
+  const heldBefore = new Set(sub.rows.keys());
+  client.socket!.close();
+  object.sockets.delete(client.socket!);
+  const woken = object.wake();
+  woken.upsert(task(3000, "open", 50_000));
+  woken.upsert(task(25, "closed", 50_001));
+  woken.upsert(task(10, "closed", 50_002));
+  woken.upsert(task(3, "open", 50_003));
+  client.connect(woken);
+  client.subscribe(woken, "open", spec, true);
+  const answer = sub.answers.at(-1)!;
+  // The new row, the touched row, and ONE row that was never written while the watcher was away:
+  // two rows closed and one came, so the window took a row from after the watcher's bound. Its
+  // revision is old, and only the cursor's bound shows that the watcher lacks it.
+  expect(answer).toMatchObject({ reset: false, put: 3 });
+  expect(
+    [...sub.rows.keys()].filter((path) => !heldBefore.has(path) && path !== "/tasks/t3000"),
+  ).toEqual(["/tasks/t0050"]);
+  expect(sub.rows).toMatchObject({ size: heldBefore.size });
+  expect(answer.chars).toBeLessThan(sub.answers[0]!.chars / 3);
+  console.info({
+    event: "reactive-catalog.acceptance",
+    snapshotStatements,
+    enterStatements,
+    leaveStatements,
+    closedStatements,
+    outsideStatements,
+    snapshotChars: sub.answers[0]!.chars,
+    resumeChars: answer.chars,
+  });
+  expect(woken.verify()).toEqual([]);
+});
+
+test("a row's new activity writes the entries of one order, and a new fact one entry in each", () => {
+  using object = fakeObject();
+  const catalog = object.wake();
+  catalog.fill();
+  const row = (activeMs: number, status: string) => ({
+    path: "/agents/a/b",
+    activeMs,
+    createdMs: 5,
+    processors: ["agent"],
+    metadata: { status, tags: ["x", "y"] },
+  });
+  catalog.upsert(row(10, "open"));
+  // $parent, $under ×3, $processor, status, tags ×2
+  const facts = 8;
+  const count = (table: string) =>
+    object.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number };
+  for (const table of ["rcat_fact_active", "rcat_fact_created", "rcat_fact_path"])
+    expect(count(table), table).toEqual({ n: facts });
+
+  // the same row again: one read, and no write
+  let before = catalog.counters.statements;
+  expect(catalog.upsert(row(10, "open"))).toMatchObject({ changed: 0 });
+  expect(catalog.counters.statements - before).toBe(1);
+
+  // new activity: a read, the row, the revision, and each entry of `active` out and in
+  before = catalog.counters.statements;
+  expect(catalog.upsert(row(11, "open"))).toMatchObject({ changed: 1 });
+  expect(catalog.counters.statements - before).toBe(3 + 2 * facts);
+
+  // one fact changes and the time stays: one entry out and one in, in each of the three indexes
+  before = catalog.counters.statements;
+  expect(catalog.upsert(row(11, "closed"))).toMatchObject({ changed: 1 });
+  expect(catalog.counters.statements - before).toBe(3 + 2 * 3);
+  for (const table of ["rcat_fact_active", "rcat_fact_created", "rcat_fact_path"])
+    expect(count(table), table).toEqual({ n: facts });
+});
+
+test("refuses a query it cannot answer exactly, with a reason", () => {
+  using object = fakeObject();
+  const catalog = object.wake();
+  catalog.fill();
+  const client = new Client();
+  client.connect(catalog);
+  const ask = (query: unknown) => {
+    client.errors = [];
+    client.subs.set("q", newSub({}));
+    catalog.handleWatchMessage(
+      client.socket as never,
+      JSON.stringify({ op: "subscribe", sub: "q", query }),
+    );
+    return client.errors[0];
+  };
+  expect(ask({ where: { status: { not: "open" } } })).toMatch(/where\.status/);
+  expect(ask({ limit: 0 })).toMatch(/limit/);
+  expect(ask({ limit: 1.5 })).toMatch(/limit/);
+  expect(ask({ limit: CATALOG_LIMITS.limit + 1 })).toMatch(/limit/);
+  expect(ask({ orderBy: "title" })).toMatch(/orderBy/);
+  expect(ask({ order: "title" })).toMatch(/order/);
+  expect(ask({ keys: ["/a"], limit: 3 })).toMatch(/stands alone/);
+  expect(ask({ awake: true, order: "path" })).toMatch(/stands alone/);
+  expect(ask({ under: "tasks" })).toMatch(/starts with/);
+  expect(ask({ where: { a: "\ud800" } })).toMatch(/not plain text/);
+  expect(ask("status=open")).toMatch(/not a query/);
+  // a message that is no request
+  client.errors = [];
+  catalog.handleWatchMessage(client.socket as never, "not JSON");
+  expect(client.errors[0]).toMatch(/one JSON object/);
+  // and a write the catalog cannot order
+  expect(() => catalog.upsert({ path: "/a", activeMs: Number.NaN, createdMs: 1 })).toThrow(
+    /activeMs/,
+  );
+  expect(() => catalog.upsert({ path: "a", activeMs: 1, createdMs: 1 })).toThrow(/starts with/);
+  // a refused row in a batch undoes the batch
+  expect(() =>
+    catalog.upsertMany([
+      { path: "/ok", activeMs: 1, createdMs: 1 },
+      { path: "/bad", activeMs: 1.5, createdMs: 1 },
+    ]),
+  ).toThrow();
+  client.subscribe(catalog, "all", { limit: 5 });
+  expect(client.subs.get("all")!.rows).toMatchObject({ size: 0 });
+});
+
+test("a cursor of another query gets every row, and a cursor of the same facts serves a larger limit", () => {
+  using object = fakeObject();
+  const catalog = object.wake();
+  catalog.fill();
+  const model = new Map<string, ModelRow>();
+  const rows = [
+    ...Array.from({ length: 6 }, (_, index) => ({
+      path: `/t/open${index}`,
+      activeMs: 10 - index,
+      createdMs: index,
+      metadata: { status: "open" },
+    })),
+    ...Array.from({ length: 6 }, (_, index) => ({
+      path: `/t/closed${index}`,
+      activeMs: 30 - index,
+      createdMs: index,
+      metadata: { status: "closed" },
+    })),
+  ];
+  catalog.upsertMany(rows);
+  rows.forEach((row, index) =>
+    model.set(row.path, { ...row, processors: [], metadata: row.metadata, rev: index + 1 }),
+  );
+  const client = new Client();
+  client.connect(catalog);
+  client.subscribe(catalog, "q", { where: { status: "open" }, limit: 3 });
+  const sub = client.subs.get("q")!;
+  expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 3 });
+
+  // the same facts, a larger limit: the cursor holds, and only the three new rows come
+  client.subscribe(catalog, "q", { where: { status: "open" }, limit: 6 }, true);
+  expect(sub.answers.at(-1)).toMatchObject({ reset: false, put: 3 });
+  expectClientMatches(client, model, "a larger limit");
+
+  // other facts under the same name, with the old cursor: every closed row is newer than the
+  // cursor's bound and older than its revision, so a trusted cursor would send no row at all
+  client.subscribe(catalog, "q", { where: { status: "closed" }, limit: 3 }, true);
+  expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 3 });
+  expectClientMatches(client, model, "another query");
+
+  // the same facts in another order: the bound is a key of the old order, so every row comes
+  client.subscribe(catalog, "q", { where: { status: "closed" }, order: "path", limit: 3 }, true);
+  expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 3 });
+  expectClientMatches(client, model, "another order");
+});
+
+test("the awake list comes from the sockets, with no row and no revision", () => {
+  using object = fakeObject();
+  const catalog = object.wake();
+  expect(catalog.awakeWatched()).toBe(false);
+  object.awake.set("/agents/a", { since: 111 });
+  const client = new Client();
+  client.connect(catalog);
+  client.subscribe(catalog, "awake", { awake: true });
+  const sub = client.subs.get("awake")!;
+  expect([...sub.rows.values()]).toEqual([{ path: "/agents/a", since: 111 }]);
+  expect(catalog.awakeWatched()).toBe(true);
+  // the awake list needs no row: a watch of it alone keeps the catalog asleep
+  expect(catalog.active()).toBe(false);
+  // after a hibernation the window is found in storage, and the frame still arrives
+  const woken = object.wake();
+  const working = { since: 222, activities: [{ key: "run", text: "Runs a script" }] };
+  object.awake.set("/agents/b", working);
+  woken.awakeChanged("/agents/b", working);
+  object.awake.delete("/agents/a");
+  woken.awakeChanged("/agents/a", undefined);
+  expect([...sub.rows.values()]).toEqual([{ path: "/agents/b", ...working }]);
+  client.unsubscribe(woken, "awake");
+  expect(woken.awakeWatched()).toBe(false);
+});
+
+test("a window that no socket names goes at its first frame", () => {
+  using object = fakeObject();
+  const catalog = object.wake();
+  const client = new Client();
+  client.connect(catalog);
+  client.subscribe(catalog, "open", { where: { status: "open" }, limit: 5 });
+  // the socket ends with no close event, and the object hibernates
+  client.socket!.close();
+  object.sockets.delete(client.socket!);
+  const woken = object.wake();
+  expect(woken.watches().windows).toHaveLength(1);
+  woken.upsert({ path: "/t/1", activeMs: 1, createdMs: 1, metadata: { status: "open" } });
+  expect(woken.watches().windows).toHaveLength(0);
+});
+
+test("nothing is kept before the first watch, and the first watch copies every row of the catalog", () => {
+  const source = Array.from({ length: 1_203 }, (_, index) =>
+    task(index, index % 3 ? "open" : "closed", 1_000 + index),
+  );
+  // a row that this collection refuses is left out, and the others are kept
+  source.push({ ...task(0, "open", 1), path: "/tasks/zz-bad", activeMs: 1.5 });
+  source.sort((a, b) => byteOrder(a.path, b.path));
+  const pages: number[] = [];
+  using object = fakeObject((after, limit) => {
+    const page = source.filter((row) => byteOrder(row.path, after) > 0).slice(0, limit);
+    pages.push(page.length);
+    return page;
+  });
+  const catalog = object.wake();
+  expect(catalog.active()).toBe(false);
+  // a write before the first watch is no write: no row, no revision
+  expect(catalog.upsert(task(9_000, "open", 1))).toMatchObject({ changed: 0, rev: 0 });
+  expect(catalog.watches()).toMatchObject({ active: false, rows: 0 });
+
+  const client = new Client();
+  client.connect(catalog);
+  client.subscribe(catalog, "open", { where: { status: "open" }, order: "path", limit: 4 });
+  expect(pages).toEqual([500, 500, 204, 0]);
+  expect(catalog.watches()).toMatchObject({ active: true, rows: 1_203, rev: 1_203 });
+  expect(client.sorted(client.subs.get("open")!).map((row) => row.path)).toEqual([
+    "/tasks/t0001",
+    "/tasks/t0002",
+    "/tasks/t0004",
+    "/tasks/t0005",
+  ]);
+  // from then on a write is kept, and a later object does not fill again
+  const woken = object.wake();
+  expect(woken.upsert(task(9_000, "open", 1))).toMatchObject({ changed: 1, rev: 1_204 });
+  woken.fill();
+  expect(pages).toHaveLength(4);
+});
+
+test("a fill that stopped goes on from the last page it wrote", () => {
+  const source = Array.from({ length: 1_100 }, (_, index) => task(index, "open", index)).sort(
+    (a, b) => byteOrder(a.path, b.path),
+  );
+  let calls = 0;
+  using object = fakeObject((after, limit) => {
+    calls += 1;
+    if (calls === 2) throw new Error("the object died");
+    return source.filter((row) => byteOrder(row.path, after) > 0).slice(0, limit);
+  });
+  expect(() => object.wake().fill()).toThrow("the object died");
+  const woken = object.wake();
+  // a fill that began keeps what is written meanwhile
+  expect(woken.active()).toBe(true);
+  woken.fill();
+  expect(woken.watches()).toMatchObject({ rows: 1_100, rev: 1_100 });
+  // the second object read the two pages that were left, and the empty page that ends the fill
+  expect(calls).toBe(5);
+});
+
+test("one write is one message for a socket, over all of its queries", () => {
+  using object = fakeObject();
+  const catalog = object.wake();
+  const client = new Client();
+  client.connect(catalog);
+  client.subscribe(catalog, "open", { where: { status: "open" }, limit: 5 });
+  client.subscribe(catalog, "byPath", { under: "/tasks", order: "path", limit: 5 });
+  client.subscribe(catalog, "key", { keys: ["/tasks/t0001"] });
+  client.messages = 0;
+  expect(catalog.upsert(task(1, "open", 10))).toMatchObject({ frames: 3, messages: 1 });
+  expect(client).toMatchObject({ messages: 1 });
+  for (const name of ["open", "byPath", "key"])
+    expect(client.subs.get(name)!.rows.has("/tasks/t0001"), name).toBe(true);
+});
+
+// ── A Durable Object's SQLite, sockets and hibernation, in Node ──
+
+function sqlOf(db: DatabaseSync) {
+  // prepared once for each text, as a Durable Object's own `sql.exec` keeps its statements
+  const prepared = new Map<string, ReturnType<DatabaseSync["prepare"]>>();
+  return {
+    exec(query: string, ...params: unknown[]) {
+      let statement = prepared.get(query);
+      if (!statement) prepared.set(query, (statement = db.prepare(query)));
+      const rows = statement.all(...(params as never[])) as Record<string, unknown>[];
+      return { toArray: () => rows };
+    },
+  };
+}
+
+class FakeSocket {
+  readyState = WebSocket.OPEN;
+  attachment: unknown = null;
+  onMessage: (raw: string) => void = () => {};
+  send(raw: string) {
+    if (this.readyState !== WebSocket.OPEN) throw new Error("the socket is closed");
+    this.onMessage(raw);
+  }
+  close() {
+    this.readyState = WebSocket.CLOSED;
+  }
+  serializeAttachment(value: unknown) {
+    this.attachment = structuredClone(value);
+  }
+  deserializeAttachment() {
+    return structuredClone(this.attachment);
+  }
+}
+
+function fakeObject(seed: (after: string, limit: number) => CatalogRowInput[] = () => []) {
+  const db = new DatabaseSync(":memory:");
+  const sockets = new Set<FakeSocket>();
+  const awake = new Map<string, { since: number; activities?: { key: string; text: string }[] }>();
+  const ctx = {
+    getWebSockets: () => [...sockets],
+    acceptWebSocket: (ws: FakeSocket) => void sockets.add(ws),
+    getTags: () => ["catalog-watch"],
+    storage: {
+      transactionSync<T>(work: () => T): T {
+        db.exec("BEGIN");
+        try {
+          const answer = work();
+          db.exec("COMMIT");
+          return answer;
+        } catch (error) {
+          db.exec("ROLLBACK");
+          throw error;
+        }
+      },
+    },
+  };
+  return {
+    db,
+    sockets,
+    awake,
+    /** A new instance over the same storage and sockets: what a hibernation leaves. */
+    wake: () => new ReactiveCatalog(sqlOf(db) as never, ctx as never, { awake: () => awake, seed }),
+    [Symbol.dispose]: () => db.close(),
+  };
+}
+
+function task(index: number, status: string, at: number): Omit<ModelRow, "rev"> {
+  return {
+    path: `/tasks/t${String(index).padStart(4, "0")}`,
+    activeMs: at,
+    createdMs: index,
+    description: `Task ${index}`,
+    processors: ["task"],
+    metadata: { status },
+  };
+}
+
+// ── The oracle ──
+
+/** A row as these tests write and read it. The engine keeps any body: here a description and a
+ *  count, which change with no change of a sort value. */
+type ModelRow = {
+  path: string;
+  activeMs: number;
+  createdMs: number;
+  rev: number;
+  description?: string;
+  eventCount?: number;
+  processors: string[];
+  metadata: Record<string, unknown>;
+};
+
+const bytes = new Map<string, Buffer>();
+function byteOrder(a: string, b: string): number {
+  const of = (text: string) => bytes.get(text) || bytes.set(text, Buffer.from(text)).get(text)!;
+  return Buffer.compare(of(a), of(b));
+}
+
+/** A window's order, written again here: the engine's own comparison is what is tested. */
+function windowOrder(order: CatalogOrder | undefined) {
+  return (a: ModelRow, b: ModelRow) => {
+    if (order === "path") return byteOrder(a.path, b.path);
+    const [x, y] = order === "created" ? [a.createdMs, b.createdMs] : [a.activeMs, b.activeMs];
+    return x !== y ? y - x : -byteOrder(a.path, b.path);
+  };
+}
+
+// a write replaces a model row by a new object, so a row's facts are worked out once
+const factsOfRow = new WeakMap<ModelRow, Set<string>>();
+function oracleFacts(row: ModelRow): Set<string> {
+  const known = factsOfRow.get(row);
+  if (known) return known;
+  const facts = new Set<string>();
+  factsOfRow.set(row, facts);
+  const parts = row.path.split("/").filter(Boolean);
+  if (row.path !== "/")
+    facts.add(`$parent=${parts.length > 1 ? `/${parts.slice(0, -1).join("/")}` : "/"}`);
+  parts.forEach((_, index) => facts.add(`$under=/${parts.slice(0, index + 1).join("/")}`));
+  for (const name of row.processors) facts.add(`$processor=${name}`);
+  for (const [key, raw] of Object.entries(row.metadata)) {
+    if (key.startsWith("$")) continue;
+    for (const item of Array.isArray(raw) ? raw : [raw])
+      if (["string", "number", "boolean"].includes(typeof item))
+        facts.add(`${key}=${String(item)}`);
+  }
+  return facts;
+}
+
+function oracle(model: ReadonlyMap<string, ModelRow>, spec: CatalogQuery): ModelRow[] {
+  if (spec.keys) {
+    const wanted = new Set(spec.keys);
+    return [...model.values()].filter((row) => wanted.has(row.path));
+  }
+  const wanted: string[] = Object.entries(spec.where || {}).map(
+    ([key, value]) => `${key}=${String(value)}`,
+  );
+  if (spec.under && spec.under !== "/") wanted.push(`$under=${spec.under}`);
+  if (spec.childrenOf) wanted.push(`$parent=${spec.childrenOf}`);
+  return [...model.values()]
+    .filter((row) => {
+      const facts = oracleFacts(row);
+      return wanted.every((fact) => facts.has(fact));
+    })
+    .sort(windowOrder(spec.order))
+    .slice(0, spec.limit || 50);
+}
+
+/** A row as a watcher gets it: a key whose value is absent is not sent. */
+const wireRows = new WeakMap<ModelRow, ModelRow>();
+function wireRow(row: ModelRow): ModelRow {
+  const known = wireRows.get(row);
+  if (known) return known;
+  const wire = JSON.parse(JSON.stringify(row)) as ModelRow;
+  wireRows.set(row, wire);
+  return wire;
+}
+
+// ── A watcher: a map of rows for each query, as the session's end keeps none and a page does ──
+
+type ClientSub = {
+  spec: CatalogQuery;
+  rows: Map<string, ModelRow>;
+  gen: string;
+  rev: number;
+  q: string;
+  /** Change frames since the test last looked. */
+  frames: number;
+  answers: { reset: boolean; put: number; chars: number }[];
+};
+
+function newSub(spec: CatalogQuery): ClientSub {
+  return { spec, rows: new Map(), gen: "", rev: -1, q: "", frames: 0, answers: [] };
+}
+
+class Client {
+  socket: FakeSocket | undefined;
+  subs = new Map<string, ClientSub>();
+  errors: string[] = [];
+  /** Messages since the test last looked. */
+  messages = 0;
+
+  connect(catalog: ReactiveCatalog) {
+    const socket = new FakeSocket();
+    socket.onMessage = (raw) => this.#receive(raw);
+    this.socket = socket;
+    catalog.attachWatchSocket(socket as never);
+  }
+
+  #receive(raw: string) {
+    const message = JSON.parse(raw);
+    if (message.hello) return;
+    this.messages += 1;
+    if (message.error) return void this.errors.push(message.error);
+    if (message.unsubscribed) return;
+    if (message.sub) {
+      const sub = this.subs.get(message.sub)!;
+      if (message.reset) sub.rows = new Map(message.reset.map((row: ModelRow) => [row.path, row]));
+      else {
+        const keep = new Set<string>(message.ids);
+        for (const path of [...sub.rows.keys()]) if (!keep.has(path)) sub.rows.delete(path);
+        for (const row of message.put) sub.rows.set(row.path, row);
+        expect([...sub.rows.keys()].sort()).toEqual([...keep].sort());
+      }
+      Object.assign(sub, { gen: message.gen, rev: message.rev, q: message.q });
+      sub.answers.push({
+        reset: !!message.reset,
+        put: (message.reset || message.put).length,
+        chars: raw.length,
+      });
+      return;
+    }
+    const rows = new Map<string, ModelRow>(message.rows.map((row: ModelRow) => [row.path, row]));
+    for (const [name, from, rev, del, put] of message.d as [
+      string,
+      number,
+      number,
+      string[],
+      string[],
+    ][]) {
+      const sub = this.subs.get(name);
+      if (!sub) throw new Error(`a frame for the query ${name}, which this watcher does not hold`);
+      expect({ gen: message.gen, from }).toEqual({ gen: sub.gen, from: sub.rev });
+      for (const path of del) expect(sub.rows.delete(path), `${name} deletes ${path}`).toBe(true);
+      for (const path of put) sub.rows.set(path, rows.get(path)!);
+      sub.rev = rev;
+      sub.frames += 1;
+    }
+  }
+
+  /** The rows of a query in its own order. */
+  sorted(sub: ClientSub): ModelRow[] {
+    return [...sub.rows.values()].sort(windowOrder(sub.spec.order));
+  }
+
+  cursorOf(sub: ClientSub): CatalogCursor {
+    const base = { gen: sub.gen, rev: sub.rev, q: sub.q };
+    if (sub.spec.keys) return { ...base, have: [...sub.rows.keys()] };
+    const last = this.sorted(sub).at(-1);
+    if (!last) return { ...base, bound: null };
+    const at =
+      sub.spec.order === "path" ? 0 : sub.spec.order === "created" ? last.createdMs : last.activeMs;
+    return { ...base, bound: [at, last.path] };
+  }
+
+  subscribe(catalog: ReactiveCatalog, name: string, spec: CatalogQuery, withCursor = false) {
+    const had = this.subs.get(name);
+    // the cursor is of the rows that the watcher holds, in the order it held them
+    const cursor = withCursor && had ? this.cursorOf(had) : undefined;
+    const sub = had && withCursor ? had : newSub(spec);
+    sub.spec = spec;
+    this.subs.set(name, sub);
+    catalog.handleWatchMessage(
+      this.socket as never,
+      JSON.stringify({ op: "subscribe", sub: name, query: spec, cursor }),
+    );
+  }
+
+  unsubscribe(catalog: ReactiveCatalog, name: string) {
+    this.subs.delete(name);
+    catalog.handleWatchMessage(
+      this.socket as never,
+      JSON.stringify({ op: "unsubscribe", sub: name }),
+    );
+  }
+}
+
+/** A watcher's row, and the oracle's row that it was found equal to: a row is an object that a
+ *  write replaces, on both sides, so each pair is compared in depth once. */
+const foundEqual = new WeakMap<ModelRow, ModelRow>();
+
+function expectClientMatches(client: Client, model: ReadonlyMap<string, ModelRow>, label: string) {
+  for (const [name, sub] of client.subs) {
+    // a keys query has no order of its own
+    const order = (rows: ModelRow[]) =>
+      sub.spec.keys ? rows.toSorted((a, b) => byteOrder(a.path, b.path)) : rows;
+    const wanted = order(oracle(model, sub.spec).map(wireRow));
+    const have = order(client.sorted(sub));
+    if (
+      have.length === wanted.length &&
+      have.every((row, at) => foundEqual.get(row) === wanted[at])
+    )
+      continue;
+    expect(have, `${label}: query ${name} ${JSON.stringify(sub.spec)}`).toEqual(wanted);
+    have.forEach((row, at) => foundEqual.set(row, wanted[at]!));
+  }
+  expect(client, label).toMatchObject({ errors: [] });
+}
+
+// ── The random run ──
+
+function random(seed: number) {
+  let state = seed >>> 0;
+  const next = () => {
+    state = (state + 0x6d2b79f5) >>> 0;
+    let t = state;
+    t = Math.imul(t ^ (t >>> 15), t | 1);
+    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+  };
+  const int = (below: number) => Math.floor(next() * below);
+  return { next, int, pick: <T>(items: readonly T[]): T => items[int(items.length)]! };
+}
+
+// paths outside ASCII on purpose: U+E000 sorts BEFORE an emoji in UTF-8 and AFTER it in UTF-16
+const PATHS = [
+  ...Array.from({ length: 36 }, (_, index) => `/tasks/t${String(index).padStart(2, "0")}`),
+  ...Array.from({ length: 6 }, (_, index) => `/agents/a${index}`),
+  "/agents/a0/sub",
+  "/agents/a1/sub/deeper",
+  "/docs/😀",
+  "/docs/x",
+  "/docs/é",
+  "/docs/z",
+  "/docs/😀/child",
+  "/x",
+];
+
+const QUERIES: CatalogQuery[] = [
+  { where: { status: "open" }, limit: 1 },
+  { where: { status: "open" }, limit: 2 },
+  { where: { status: "open" }, limit: 7 },
+  { where: { status: "open" }, limit: 50 },
+  { where: { status: "closed" }, limit: 3 },
+  { where: { status: "open", priority: "high" }, limit: 3 },
+  { where: { tags: "pinned" }, limit: 5 },
+  { where: { tags: "a", status: "open" }, limit: 4 },
+  { where: { priority: 3 }, limit: 4 },
+  { where: { flag: true }, limit: 2 },
+  { under: "/tasks", limit: 7 },
+  { under: "/docs", limit: 3 },
+  { under: "/agents", where: { kind: "agent" }, limit: 3 },
+  { childrenOf: "/agents", limit: 4 },
+  { childrenOf: "/docs", limit: 2 },
+  { where: { $processor: "agent" }, limit: 3 },
+  { limit: 5 },
+  { limit: 1 },
+  // the other two orders, with one fact, two facts and none
+  { where: { status: "open" }, order: "created", limit: 3 },
+  { where: { status: "open", priority: "high" }, order: "created", limit: 2 },
+  { under: "/tasks", order: "created", limit: 6 },
+  { order: "created", limit: 4 },
+  { order: "created", limit: 1 },
+  { where: { status: "open" }, order: "path", limit: 3 },
+  { where: { tags: "a", status: "open" }, order: "path", limit: 2 },
+  { childrenOf: "/docs", order: "path", limit: 3 },
+  { under: "/docs", order: "path", limit: 4 },
+  { order: "path", limit: 5 },
+  { order: "path", limit: 1 },
+];
+
+function randomRow(rng: ReturnType<typeof random>, clock: { now: number }): Omit<ModelRow, "rev"> {
+  const path = rng.pick(PATHS);
+  const agent = path.startsWith("/agents");
+  // a few timestamps, to force ties; and now and then a fresh one, the newest of all
+  const activeMs = rng.next() < 0.25 ? (clock.now += 1 + rng.int(3)) : 1_000 + rng.int(6);
+  const tags = ["a", "b", "pinned"].filter(() => rng.next() < 0.3);
+  return {
+    path,
+    activeMs,
+    // a context is made once: its time mostly stays, and a few contexts share one
+    createdMs: rng.next() < 0.1 ? 500 + rng.int(4) : 100 + (path.length % 5),
+    ...(rng.next() < 0.3 && { description: `about ${rng.int(3)}` }),
+    ...(rng.next() < 0.5 && { eventCount: rng.int(3) }),
+    processors: agent ? ["agent"] : rng.next() < 0.2 ? ["task", "agent"] : [],
+    metadata: {
+      status: rng.pick(["open", "open", "closed"]),
+      priority: rng.pick(["high", "normal", 3]),
+      ...(tags.length > 0 && { tags }),
+      ...(agent && { kind: "agent" }),
+      ...(rng.next() < 0.2 && { flag: rng.next() < 0.5 }),
+      nested: { ignored: true },
+    },
+  };
+}
+
+function runSeed(seed: number, steps: number) {
+  const rng = random(seed);
+  using object = fakeObject();
+  let catalog = object.wake();
+  catalog.fill();
+  const model = new Map<string, ModelRow>();
+  let rev = 0;
+  const clock = { now: 2_000 };
+  const clients: Client[] = [];
+  const away: Client[] = [];
+  const tally = { writes: 0, frames: 0, quiet: 0, resumes: 0, rowsHeld: 0, hibernations: 0 };
+
+  const valueOf = (row: Omit<ModelRow, "rev">) => JSON.stringify(wireRow({ ...row, rev: 0 }));
+
+  /** Applies a write to the model as the engine must apply it. True when it changed a row. */
+  const modelUpsert = (input: Omit<ModelRow, "rev">): boolean => {
+    const old = model.get(input.path);
+    if (old && valueOf(old) === valueOf(input)) return false;
+    rev += 1;
+    model.set(input.path, { ...input, rev });
+    return true;
+  };
+  const modelDelete = (path: string): boolean => {
+    if (!model.delete(path)) return false;
+    rev += 1;
+    return true;
+  };
+  const answerOf = (spec: CatalogQuery) =>
+    JSON.stringify(oracle(model, spec).map((row) => [row.path, row.rev]));
+
+  for (let step = 0; step < steps; step++) {
+    const roll = rng.next();
+    const label = `seed ${seed} step ${step}`;
+
+    if (roll < 0.52) {
+      // one write: a frame goes to exactly the queries whose answer changed
+      const watched = clients.flatMap((client) =>
+        [...client.subs].map(([name, sub]) => ({ name, sub, before: answerOf(sub.spec) })),
+      );
+      for (const entry of watched) entry.sub.frames = 0;
+      let changed: boolean;
+      let result;
+      const kind = rng.next();
+      if (kind < 0.12 && model.size > 0) {
+        const path = rng.pick([...model.keys()]);
+        changed = modelDelete(path);
+        result = catalog.deleteMany([path]);
+      } else if (kind < 0.2 && model.size > 0) {
+        // the same row again: no revision, no frame
+        const { rev: _rev, ...same } = model.get(rng.pick([...model.keys()]))!;
+        changed = modelUpsert(same);
+        result = catalog.upsert(same);
+      } else {
+        const input = randomRow(rng, clock);
+        changed = modelUpsert(input);
+        result = catalog.upsert(input);
+      }
+      expect(result, label).toMatchObject({ rev, changed: changed ? 1 : 0 });
+      tally.writes += 1;
+      let expectedFrames = 0;
+      for (const { sub, before, name } of watched) {
+        const frames = before === answerOf(sub.spec) ? 0 : 1;
+        // said only when it fails: an assertion for each query at each write is most of the run
+        if (sub.frames !== frames)
+          expect(sub, `${label}: frames for ${name} ${JSON.stringify(sub.spec)}`).toMatchObject({
+            frames,
+          });
+        expectedFrames += sub.frames;
+      }
+      tally.frames += expectedFrames;
+      if (expectedFrames === 0) tally.quiet += 1;
+    } else if (roll < 0.58) {
+      // a batch in one transaction
+      const inputs = Array.from({ length: 2 + rng.int(5) }, () => randomRow(rng, clock));
+      const changed = inputs.filter((input) => modelUpsert(input)).length;
+      expect(catalog.upsertMany(inputs), label).toMatchObject({ rev, changed });
+    } else if (roll < 0.6 && model.size > 3) {
+      const paths = [rng.pick([...model.keys()]), rng.pick([...model.keys()]), "/never/there"];
+      const changed = paths.filter((path) => modelDelete(path)).length;
+      expect(catalog.deleteMany(paths), label).toMatchObject({ changed });
+    } else if (roll < 0.7) {
+      if (clients.length < 5 && (clients.length === 0 || rng.next() < 0.4)) {
+        const client = new Client();
+        client.connect(catalog);
+        clients.push(client);
+      }
+      const client = rng.pick(clients);
+      if (client.subs.size < 6)
+        client.subscribe(
+          catalog,
+          `s${step}`,
+          rng.next() < 0.15
+            ? { keys: Array.from({ length: 1 + rng.int(6) }, () => rng.pick(PATHS)) }
+            : rng.pick(QUERIES),
+        );
+    } else if (roll < 0.74 && clients.length > 0) {
+      const client = rng.pick(clients);
+      if (client.subs.size > 0) client.unsubscribe(catalog, rng.pick([...client.subs.keys()]));
+    } else if (roll < 0.77 && clients.length > 0) {
+      // the same name, another query: the old window is let go
+      const client = rng.pick(clients);
+      if (client.subs.size > 0)
+        client.subscribe(catalog, rng.pick([...client.subs.keys()]), rng.pick(QUERIES));
+    } else if (roll < 0.82) {
+      // hibernation: the object's memory goes, its storage and its sockets stay
+      catalog = object.wake();
+      tally.hibernations += 1;
+    } else if (roll < 0.87 && clients.length > 0) {
+      // a watcher goes away, with a close event or with none
+      const client = clients.splice(rng.int(clients.length), 1)[0]!;
+      const socket = client.socket!;
+      socket.close();
+      object.sockets.delete(socket);
+      if (rng.next() < 0.5) catalog.handleWatchClose(socket as never);
+      away.push(client);
+    } else if (roll < 0.94 && away.length > 0) {
+      // it comes back on a new socket, with its cursor for each query or with none
+      const client = away.splice(rng.int(away.length), 1)[0]!;
+      client.connect(catalog);
+      const withCursor = rng.next() < 0.8;
+      for (const [name, sub] of [...client.subs]) {
+        const held = sub.rows.size;
+        client.subscribe(catalog, name, sub.spec, withCursor);
+        const answer = client.subs.get(name)!.answers.at(-1)!;
+        if (withCursor && !answer.reset) {
+          tally.resumes += 1;
+          tally.rowsHeld += Math.max(0, held - answer.put);
+        }
+      }
+      clients.push(client);
+    } else {
+      // six queries of the pool, asked anew by a watcher that holds nothing, against the oracle
+      const fresh = new Client();
+      fresh.connect(catalog);
+      for (let index = 0; index < 6; index++)
+        fresh.subscribe(catalog, `f${index}`, rng.pick(QUERIES));
+      expectClientMatches(fresh, model, `${label}: asked anew`);
+      catalog.handleWatchClose(fresh.socket as never);
+      object.sockets.delete(fresh.socket!);
+    }
+    for (const client of clients) expectClientMatches(client, model, label);
+    expect(catalog.verify(), label).toEqual([]);
+  }
+  return tally;
+}
A core/itx/src/context/reactive-catalog.ts
@@ -0,0 +1,1439 @@
+// reactive-catalog.ts — THE CATALOG AS A COLLECTION THAT ANSWERS REACTIVE QUERIES. It runs in the
+// context that accepts the awake sockets (awake.ts), beside the catalog's own rows
+// (context-catalog.ts), in tables of its own (`rcat_*`). Nothing under it changes: a context still
+// folds its log into a summary and sends it down its awake socket. This file keeps a copy of what
+// arrives, as a row with an index of facts, and tells the watchers of a query what a write changed.
+//
+// A ROW is one context: its path, when it was last active, when it was made, and what its listing
+// says of it (iterate/api `CatalogRow`). Its FACTS are every scalar at the top of its metadata (and
+// each scalar of a list there), and the kernel's own: `$parent`, `$under` for the path and each
+// ancestor, `$processor`.
+//
+// A WATCHED QUERY is a window over that index: the rows that hold every fact the query names, in
+// one order, up to a limit. No query is known ahead of time: a watcher sends one at run time, and
+// any two watchers may send different ones (iterate/api `CatalogQuery`).
+//
+// THE ORDERS. Each is total (the path breaks every tie) and each has one index of the facts:
+//   active   the newest activity first   rcat_fact_active  (k, v, active_at DESC, path DESC)
+//   created  the newest context first    rcat_fact_created (k, v, created_at DESC, path DESC)
+//   path     by path, A to Z             rcat_fact_path    (k, v, path)
+// A row's new activity moves its entries of `active` alone. The entries of the other two change
+// only when the row's facts do, so two more orders cost a common write nothing.
+//
+// For a window the object keeps two values, in SQLite: its SIZE and its BOUND, the sort key of its
+// last row (Zero's `take` operator). A write changes a window only when the row's old key or its
+// new key is at or before the bound. Any other write costs the window nothing: no statement, no
+// frame. A row that leaves a full window is replaced by the one row after the bound, in the same
+// frame.
+//
+// Three kinds of query:
+//   a window — `{ where, under, childrenOf, order, limit }`
+//   keys     — `{ keys: [paths] }`: exactly these rows, which is what a join asks for
+//   awake    — `{ awake: true }`: the contexts that hold an awake socket now, from the sockets alone
+//
+// TEXT IS ORDERED AS SQLITE ORDERS IT: a path is compared as UTF-8 bytes, here and in every
+// watcher (`compareTextBinary`). JavaScript's `<` puts U+E000 after an emoji, and UTF-8 puts it
+// before.
+//
+// NOTHING IS KEPT UNTIL SOMEONE WATCHES. The first watch copies every row of the catalog, a page
+// at a time (`fill`), and from then on each summary that the catalog keeps is written here too. A
+// mind that never watches pays for no index.
+//
+// THE WIRE, as JSON on a hibernated WebSocket of its own. Its other end is the session's end
+// (catalog-watch.ts), never a client: a client holds a capnweb callback.
+//   to the object:  { op: "subscribe", sub, query, cursor? } · { op: "unsubscribe", sub }
+//   the answer to a subscribe:  { sub, q, gen, rev, full, reset: [rows] }, or with a cursor the
+//                   object accepts { sub, q, gen, rev, full, ids: [paths], put: [rows] }: every
+//                   path of the window, and only the rows the watcher lacks
+//   a change:       { gen, rows: [rows], d: [[sub, from, rev, [paths to delete], [paths to put]]] }
+//                   ONE message for each socket and write (or batch of writes), over all of the
+//                   socket's queries, so a join never sees half of a write. `from` is the revision
+//                   of the query's frame before.
+//
+// A watcher that comes back sends its cursor `{ gen, rev, q, bound }`: the generation, the
+// revision of its last frame, the name of what the query selects, and the sort key of the last row
+// it holds. A row is HELD when it is unchanged since `rev` and its key is at or before `bound`.
+// The second half matters: a row that backfilled while the watcher was away has an old revision,
+// and the watcher never had it.
+import { z } from "zod";
+import type { CatalogOrder, CatalogWatches } from "iterate/api";
+import type { AwakeContextState } from "./awake.ts";
+import { activeContextActivities } from "./context-activity-stack.ts";
+
+export const CATALOG_LIMITS = {
+  /** The most rows of one window. */
+  limit: 500,
+  /** The most live windows of the object, over all sockets. */
+  windows: 512,
+  /** The most queries of one socket. */
+  subsPerSocket: 64,
+  predicates: 8,
+  keys: 500,
+  factsPerRow: 64,
+  factKeyChars: 80,
+  factValueChars: 200,
+  pathChars: 512,
+  /** The most characters of a row's stored JSON. A summary's own limits keep a row far below it:
+   *  200 event types, 4,000 characters of metadata, 2,000 of description. */
+  bodyChars: 32_000,
+  subChars: 16,
+  /** A change message is cut into parts of about this many characters. */
+  messageChars: 256_000,
+  /** How many rows one transaction of the first fill writes. */
+  fillPage: 500,
+} as const;
+
+const SCHEMA = "1";
+const WATCH_SOCKET_TAG = "catalog-watch";
+
+/** A refusal that the watcher or the writer caused: its message goes back to them. */
+export class CatalogRefusal extends Error {}
+
+// ── The order ──
+
+/** No lone surrogate: such a text has one UTF-8 form, which is what SQLite stores and compares. */
+function wellFormed(text: string): boolean {
+  for (let i = 0; i < text.length; i++) {
+    const unit = text.charCodeAt(i);
+    if (unit < 0xd800 || unit > 0xdfff) continue;
+    const next = text.charCodeAt(i + 1);
+    if (unit > 0xdbff || !(next >= 0xdc00 && next <= 0xdfff)) return false;
+    i += 1;
+  }
+  return true;
+}
+
+/** As SQLite's BINARY collation compares two texts: by their UTF-8 bytes. For well-formed strings
+ *  that differs from UTF-16 code unit order in one case: a surrogate (a code point from U+10000)
+ *  against a code unit from U+E000 to U+FFFF. No bytes are made. */
+export function compareTextBinary(a: string, b: string): number {
+  if (a === b) return 0;
+  const shared = Math.min(a.length, b.length);
+  for (let i = 0; i < shared; i++) {
+    const x = a.charCodeAt(i);
+    const y = b.charCodeAt(i);
+    if (x === y) continue;
+    const xSurrogate = x >= 0xd800 && x <= 0xdfff;
+    const ySurrogate = y >= 0xd800 && y <= 0xdfff;
+    if (xSurrogate === ySurrogate) return x < y ? -1 : 1;
+    return xSurrogate ? 1 : -1;
+  }
+  return a.length < b.length ? -1 : 1;
+}
+
+/** Where a row stands in a window: the order's own value (0 for the order `path`), then the path. */
+export type SortKey = [at: number, path: string];
+
+/** Each order's index of the facts, and the column that holds the order's own value there and in
+ *  `rcat_row`. The order `path` has none: the path is the whole key. */
+const ORDER_INDEX = {
+  active: { facts: "rcat_fact_active", column: "active_at" },
+  created: { facts: "rcat_fact_created", column: "created_at" },
+  path: { facts: "rcat_fact_path", column: "" },
+} as const satisfies Record<CatalogOrder, { facts: string; column: string }>;
+
+/** Negative: `a` is before `b` in the window. */
+export function compareSortKeys(order: CatalogOrder, a: SortKey, b: SortKey): number {
+  if (order === "path") return compareTextBinary(a[1], b[1]);
+  if (a[0] !== b[0]) return a[0] > b[0] ? -1 : 1;
+  return -compareTextBinary(a[1], b[1]);
+}
+
+/** `ORDER BY` in a window's order (`forward`) or against it, for the table alias `at`. */
+function orderTerms(order: CatalogOrder, at: string, forward: boolean): string {
+  const { column } = ORDER_INDEX[order];
+  if (!column) return `${at}.path ${forward ? "ASC" : "DESC"}`;
+  const direction = forward ? "DESC" : "ASC";
+  return `${at}.${column} ${direction}, ${at}.path ${direction}`;
+}
+
+/** The rows strictly after `key` in a window's order (`after`), or strictly before it. */
+function beyond(order: CatalogOrder, at: string, after: boolean, key: SortKey): Statement {
+  const { column } = ORDER_INDEX[order];
+  if (!column) return { sql: `${at}.path ${after ? ">" : "<"} ?`, args: [key[1]] };
+  return { sql: `(${at}.${column}, ${at}.path) ${after ? "<" : ">"} (?, ?)`, args: [...key] };
+}
+
+// ── Facts ──
+
+type Fact = [key: string, value: string];
+const factId = ([key, value]: Fact) => `${key}\0${value}`;
+
+function usableFact(key: string, value: string): boolean {
+  return (
+    key.length > 0 &&
+    key.length <= CATALOG_LIMITS.factKeyChars &&
+    value.length <= CATALOG_LIMITS.factValueChars &&
+    !key.includes("\0") &&
+    !value.includes("\0") &&
+    wellFormed(key) &&
+    wellFormed(value)
+  );
+}
+
+const FactValue = z.union([z.string(), z.number(), z.boolean()]);
+
+/** The facts of a row: the kernel's own (`$parent`, `$under` for the path and each ancestor,
+ *  `$processor`), then each scalar and each scalar of a list at the top of `metadata`. A key that
+ *  starts with `$` is the kernel's. At most `CATALOG_LIMITS.factsPerRow`; the kernel's come first. */
+export function extractFacts(
+  path: string,
+  processors: readonly string[],
+  metadata: Record<string, unknown>,
+): Fact[] {
+  const facts: Fact[] = [];
+  const seen = new Set<string>();
+  const add = (key: string, value: string) => {
+    if (facts.length >= CATALOG_LIMITS.factsPerRow || !usableFact(key, value)) return;
+    const id = factId([key, value]);
+    if (seen.has(id)) return;
+    seen.add(id);
+    facts.push([key, value]);
+  };
+  const parts = path.split("/").filter(Boolean);
+  if (path !== "/") add("$parent", `/${parts.slice(0, -1).join("/")}`);
+  parts.forEach((_, index) => add("$under", `/${parts.slice(0, index + 1).join("/")}`));
+  for (const processor of processors) add("$processor", processor);
+  for (const [key, raw] of Object.entries(metadata)) {
+    if (key.startsWith("$")) continue;
+    for (const item of Array.isArray(raw) ? raw : [raw]) {
+      const value = FactValue.safeParse(item);
+      // a number that is no number (NaN, an infinity) is no fact: it has no one text
+      if (value.success && (typeof value.data !== "number" || Number.isFinite(value.data)))
+        add(key, String(value.data));
+    }
+  }
+  return facts;
+}
+
+// ── Queries ──
+
+const ContextPath = z
+  .string()
+  .startsWith("/", 'a path starts with "/"')
+  .max(CATALOG_LIMITS.pathChars)
+  .refine((path) => !path.includes("\0") && wellFormed(path), "a path is well-formed text")
+  // one spelling of a path: no slash at its end
+  .transform((path) => (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path));
+
+/** A query as a watcher sends it (iterate/api `CatalogQuery`). Strict: a field that the catalog
+ *  does not know is refused, never dropped, since dropping a condition answers other rows. */
+const WatchedQuery = z.strictObject({
+  where: z.record(z.string(), FactValue).optional(),
+  under: ContextPath.optional(),
+  childrenOf: ContextPath.optional(),
+  order: z.enum(["active", "created", "path"]).optional(),
+  limit: z.number().int().min(1).max(CATALOG_LIMITS.limit).optional(),
+  keys: z.array(ContextPath).max(CATALOG_LIMITS.keys).optional(),
+  awake: z.literal(true).optional(),
+});
+
+type RangeQuery = { kind: "range"; predicates: Fact[]; order: CatalogOrder; limit: number };
+type Query = RangeQuery | { kind: "keys"; keys: string[] } | { kind: "awake" };
+
+/** The one form of a query. Two queries that mean the same have the same `key`, and so share a
+ *  window. A query that cannot be answered exactly is refused: nothing is dropped silently. */
+export function normalizeQuery(spec: unknown): { query: Query; key: string } {
+  const parsed = WatchedQuery.safeParse(spec);
+  if (!parsed.success)
+    throw new CatalogRefusal(`not a query of the catalog: ${z.prettifyError(parsed.error)}`);
+  const { where, under, childrenOf, order, limit, keys, awake } = parsed.data;
+  const ranged = Boolean(where || under || childrenOf || order || limit);
+  if (awake) {
+    if (ranged || keys) throw new CatalogRefusal("`awake: true` stands alone");
+    return { query: { kind: "awake" }, key: '{"awake":true}' };
+  }
+  if (keys) {
+    if (ranged) throw new CatalogRefusal("`keys` stands alone");
+    const paths = [...new Set(keys)].sort(compareTextBinary);
+    return { query: { kind: "keys", keys: paths }, key: JSON.stringify({ k: paths }) };
+  }
+  const facts = new Map<string, Fact>();
+  const add = (key: string, value: string) => {
+    if (!usableFact(key, value))
+      throw new CatalogRefusal(`the fact "${key.slice(0, 40)}" is too long or is not plain text`);
+    facts.set(factId([key, value]), [key, value]);
+  };
+  for (const [key, value] of Object.entries(where || {})) add(key, String(value));
+  if (under && under !== "/") add("$under", under);
+  if (childrenOf) add("$parent", childrenOf);
+  if (facts.size > CATALOG_LIMITS.predicates)
+    throw new CatalogRefusal(`a query names at most ${CATALOG_LIMITS.predicates} facts`);
+  const query: RangeQuery = {
+    kind: "range",
+    predicates: [...facts.values()].sort(
+      (a, b) => compareTextBinary(a[0], b[0]) || compareTextBinary(a[1], b[1]),
+    ),
+    order: order || "active",
+    limit: limit || 50,
+  };
+  return { query, key: JSON.stringify({ p: query.predicates, o: query.order, l: query.limit }) };
+}
+
+/** A short name of what a query selects, without its limit: a cursor is good for any limit of the
+ *  same facts in the same order, because its bound says which part the watcher holds. FNV-1a, 32
+ *  bits. */
+function queryName(query: Query): string {
+  const text =
+    query.kind === "range" ? JSON.stringify([query.order, query.predicates]) : query.kind;
+  let hash = 0x811c9dc5;
+  for (let i = 0; i < text.length; i++) {
+    hash ^= text.charCodeAt(i);
+    hash = Math.imul(hash, 0x01000193);
+  }
+  return (hash >>> 0).toString(36);
+}
+
+/** What a watcher holds of a query (iterate/api `CatalogCursor`). */
+const WatcherCursor = z.object({
+  gen: z.string(),
+  rev: z.number(),
+  q: z.string(),
+  bound: z.tuple([z.number(), z.string()]).nullable().optional(),
+  have: z.array(z.string()).optional(),
+});
+
+// ── Rows ──
+
+/** A row as its writer hands it over: the whole new value of its path. `activeMs` and `createdMs`
+ *  are what the orders sort by. Every other field is the row's body, which a watcher gets as it
+ *  is: `processors` and `metadata` are in it, and the facts are read from those two. */
+export type CatalogRowInput = {
+  path: string;
+  activeMs: number;
+  createdMs: number;
+  processors?: string[];
+  metadata?: Record<string, unknown>;
+  [field: string]: unknown;
+};
+
+type StoredRow = { path: string; active_at: number; created_at: number; rev: number; body: string };
+
+/** A stored row as the JSON a watcher gets (iterate/api `CatalogRow`), with no parse: the body is
+ *  an object's JSON, and it always holds `processors`. */
+function rowJson(row: StoredRow): string {
+  return `{"path":${JSON.stringify(row.path)},"activeMs":${row.active_at},"createdMs":${row.created_at},"rev":${row.rev},${row.body.slice(1)}`;
+}
+
+function keyOf(
+  order: CatalogOrder,
+  row: Pick<StoredRow, "active_at" | "created_at" | "path">,
+): SortKey {
+  if (order === "path") return [0, row.path];
+  return [order === "active" ? row.active_at : row.created_at, row.path];
+}
+
+const ROW_COLUMNS = "r.path, r.active_at, r.created_at, r.rev, r.body";
+
+// ── Windows ──
+
+type LiveWindow = {
+  id: number;
+  key: string;
+  query: Query;
+  /** Of a range query: which fact its index is read by, the one with the fewest rows when the
+   *  window was made. Any choice is correct; this one reads the least. */
+  driver: number;
+  /** Of a range query: `min(matching rows, limit)`. */
+  size: number;
+  /** Of a range query: the sort key of the last row, kept only while the window is full. */
+  bound: SortKey | null;
+  /** The catalog's revision at the window's last frame. */
+  rev: number;
+};
+
+type PendingFrame = {
+  windowId: number;
+  from: number;
+  rev: number;
+  del: string[];
+  /** `[path, the row's JSON]`. */
+  put: [string, string][];
+};
+
+/** What a watch socket remembers through a hibernation: its id, and its queries by the name the
+ *  watcher gave each. */
+const WatchAttachment = z.object({ sid: z.string(), subs: z.record(z.string(), z.number()) });
+
+/** What a watch socket's other end sends. */
+const WatchRequest = z.object({
+  op: z.enum(["subscribe", "unsubscribe"]),
+  sub: z.string().min(1).max(CATALOG_LIMITS.subChars),
+  query: z.unknown().optional(),
+  cursor: z.unknown().optional(),
+});
+
+type Statement = { sql: string; args: unknown[] };
+
+/** What the engine needs of the Durable Object it runs in. */
+type CatalogHost = Pick<DurableObjectState, "getWebSockets" | "acceptWebSocket" | "getTags"> & {
+  storage: Pick<DurableObjectStorage, "transactionSync">;
+};
+
+/** A watch socket and its queries, by the name the watcher gave each. */
+type WatchSocket = { ws: WebSocket; subs: Map<string, number> };
+
+type CatalogDeps = {
+  /** The contexts that hold an awake socket now, by path. */
+  awake: () => ReadonlyMap<string, AwakeContextState>;
+  /** A page of the catalog's own rows, in path order, after `after`: what the first fill copies. */
+  seed: (after: string, limit: number) => CatalogRowInput[];
+};
+
+export class ReactiveCatalog {
+  readonly #sql: SqlStorage;
+  readonly #ctx: CatalogHost;
+  readonly #deps: CatalogDeps;
+  #ready = false;
+  #gen = "";
+  #rev = 0;
+  /** How far the first fill came: "" before it began, then the last path it copied, then `done`. */
+  #filled: { started: boolean; done: boolean; after: string } = {
+    started: false,
+    done: false,
+    after: "",
+  };
+
+  // What follows is memory that a hibernation drops. Each is read again when it is first needed:
+  // the windows from `rcat_window`, the sockets from their attachments.
+  #windows: Map<number, LiveWindow> | undefined;
+  #windowIdByKey = new Map<string, number>();
+  /** A range window is found by its driver fact; one with no fact is under `*`. */
+  #rangeWindowsByFact = new Map<string, Set<number>>();
+  #keysWindowsByPath = new Map<string, Set<number>>();
+  #awakeWindowId: number | undefined;
+  #sockets: Map<string, WatchSocket> | undefined;
+  /** window id → socket id → the socket's names for the query. */
+  #watchers = new Map<number, Map<string, Set<string>>>();
+
+  counters = {
+    statements: 0,
+    writes: 0,
+    /** Writes of a row equal to the stored one. */
+    sameWrites: 0,
+    /** Rows whose write changed no window: no statement beyond the write's own, and no frame. */
+    quietWrites: 0,
+    windowChecks: 0,
+    seeks: 0,
+    messagesSent: 0,
+    charsSent: 0,
+    /** Rows that an answer to a cursor did not send again, because the watcher held them. */
+    rowsNotResent: 0,
+    windowsMade: 0,
+    windowsDropped: 0,
+  };
+
+  constructor(sql: SqlStorage, ctx: CatalogHost, deps: CatalogDeps) {
+    this.#sql = sql;
+    this.#ctx = ctx;
+    this.#deps = deps;
+  }
+
+  // ── Storage ──
+
+  #ensureTables(): void {
+    if (this.#ready) return;
+    this.#sql.exec(
+      "CREATE TABLE IF NOT EXISTS rcat_meta (k TEXT PRIMARY KEY NOT NULL, v TEXT NOT NULL) WITHOUT ROWID",
+    );
+    const read = () =>
+      new Map(
+        this.#sql
+          .exec<{ k: string; v: string }>("SELECT k, v FROM rcat_meta")
+          .toArray()
+          .map((row) => [row.k, row.v]),
+      );
+    let meta = read();
+    // The tables are made once for a schema. An object that wakes reads `rcat_meta` and no more:
+    // this runs at the first summary after every wake of the object, watched or not.
+    if (meta.get("schema") !== SCHEMA) {
+      // Every row here is a copy of the catalog's own, so tables of another schema are made again
+      // and filled again. A new generation: no cursor of the old tables is good for the new ones.
+      for (const table of [
+        "rcat_row",
+        "rcat_fact",
+        "rcat_fact_active",
+        "rcat_fact_created",
+        "rcat_fact_path",
+        "rcat_window",
+      ])
+        this.#sql.exec(`DROP TABLE IF EXISTS ${table}`);
+      this.#sql.exec(
+        `CREATE TABLE rcat_row (
+          path TEXT COLLATE BINARY PRIMARY KEY NOT NULL,
+          active_at INTEGER NOT NULL,
+          created_at INTEGER NOT NULL,
+          rev INTEGER NOT NULL,
+          body TEXT NOT NULL,
+          facts TEXT NOT NULL
+        ) WITHOUT ROWID`,
+      );
+      this.#sql.exec("CREATE INDEX rcat_row_active ON rcat_row (active_at DESC, path DESC)");
+      this.#sql.exec("CREATE INDEX rcat_row_created ON rcat_row (created_at DESC, path DESC)");
+      for (const { facts, column } of Object.values(ORDER_INDEX))
+        this.#sql.exec(
+          `CREATE TABLE ${facts} (
+            k TEXT COLLATE BINARY NOT NULL,
+            v TEXT COLLATE BINARY NOT NULL,
+            ${column && `${column} INTEGER NOT NULL,`}
+            path TEXT COLLATE BINARY NOT NULL,
+            PRIMARY KEY (k, v, ${column && `${column} DESC,`} path${column && " DESC"})
+          ) WITHOUT ROWID`,
+        );
+      this.#sql.exec(
+        `CREATE TABLE rcat_window (
+          id INTEGER PRIMARY KEY AUTOINCREMENT,
+          key TEXT COLLATE BINARY NOT NULL UNIQUE,
+          driver INTEGER NOT NULL,
+          size INTEGER NOT NULL,
+          b_at INTEGER,
+          b_path TEXT COLLATE BINARY,
+          rev INTEGER NOT NULL
+        )`,
+      );
+      this.#sql.exec("DELETE FROM rcat_meta");
+      // written last: tables that were half made are made again
+      this.#sql.exec(
+        "INSERT INTO rcat_meta (k, v) VALUES ('schema', ?), ('gen', ?), ('rev', '0')",
+        SCHEMA,
+        crypto.randomUUID().slice(0, 8),
+      );
+      meta = read();
+    }
+    this.#gen = meta.get("gen") || "";
+    this.#rev = Number(meta.get("rev") || "0");
+    const filled = meta.get("filled");
+    this.#filled = {
+      started: meta.has("filled"),
+      done: filled === "done",
+      after: filled?.startsWith(">") ? filled.slice(1) : "",
+    };
+    this.#ready = true;
+  }
+
+  #exec<T extends Record<string, SqlStorageValue>>(sql: string, ...args: unknown[]): T[] {
+    this.counters.statements += 1;
+    return this.#sql.exec<T>(sql, ...args).toArray();
+  }
+
+  /** Memory that no longer matches SQLite (a transaction that threw) is read again. */
+  #forget(): void {
+    this.#ready = false;
+    this.#windows = undefined;
+    this.#sockets = undefined;
+  }
+
+  /** Whether the catalog keeps rows: false until the first watch, and then for good. A writer
+   *  asks before it builds a row. */
+  active(): boolean {
+    this.#ensureTables();
+    return this.#filled.started;
+  }
+
+  /** THE FIRST FILL: every row of the catalog, copied a page at a time, each page one transaction.
+   *  It runs to its end before the first window is made. A fill that stopped (the object died
+   *  under it) goes on from the last page it wrote. A row that this collection refuses is left
+   *  out, and the others are kept. */
+  fill(): void {
+    this.#ensureTables();
+    while (!this.#filled.done) {
+      const page = this.#deps.seed(this.#filled.after, CATALOG_LIMITS.fillPage);
+      const last = page.at(-1)?.path;
+      const mark = last ? `>${last}` : "done";
+      const pending: PendingFrame[] = [];
+      try {
+        this.#ctx.storage.transactionSync(() => {
+          for (const row of page) {
+            try {
+              this.#upsertOne(row, pending);
+            } catch (error) {
+              if (!(error instanceof CatalogRefusal)) throw error;
+            }
+          }
+          this.#exec("UPDATE rcat_meta SET v = ? WHERE k = 'rev'", String(this.#rev));
+          this.#exec(
+            "INSERT INTO rcat_meta (k, v) VALUES ('filled', ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v",
+            mark,
+          );
+        });
+      } catch (error) {
+        this.#forget();
+        throw error;
+      }
+      this.#filled = { started: true, done: !last, after: last || "" };
+      this.#dispatch(pending);
+    }
+  }
+
+  #loadWindows(): Map<number, LiveWindow> {
+    this.#ensureTables();
+    if (this.#windows) return this.#windows;
+    const windows = new Map<number, LiveWindow>();
+    this.#windows = windows;
+    this.#windowIdByKey = new Map();
+    this.#rangeWindowsByFact = new Map();
+    this.#keysWindowsByPath = new Map();
+    this.#awakeWindowId = undefined;
+    const rows = this.#exec<{
+      id: number;
+      key: string;
+      driver: number;
+      size: number;
+      b_at: number | null;
+      b_path: string | null;
+      rev: number;
+    }>("SELECT id, key, driver, size, b_at, b_path, rev FROM rcat_window");
+    for (const row of rows)
+      this.#indexWindow(windows, {
+        id: row.id,
+        key: row.key,
+        query: queryOfKey(row.key),
+        driver: row.driver,
+        size: row.size,
+        // oxlint-disable-next-line iterate/simple-truthiness-check -- SQL NULL means "no bound"; a bound's own time may be 0 and its path is never empty
+        bound: row.b_at === null || row.b_path === null ? null : [row.b_at, row.b_path],
+        rev: row.rev,
+      });
+    return windows;
+  }
+
+  #indexWindow(windows: Map<number, LiveWindow>, win: LiveWindow): void {
+    windows.set(win.id, win);
+    this.#windowIdByKey.set(win.key, win.id);
+    const into = (index: Map<string, Set<number>>, at: string) => {
+      let ids = index.get(at);
+      if (!ids) index.set(at, (ids = new Set()));
+      ids.add(win.id);
+    };
+    if (win.query.kind === "range") into(this.#rangeWindowsByFact, driverFactOf(win));
+    else if (win.query.kind === "keys")
+      for (const path of win.query.keys) into(this.#keysWindowsByPath, path);
+    else this.#awakeWindowId = win.id;
+  }
+
+  #dropWindow(win: LiveWindow): void {
+    this.#loadWindows().delete(win.id);
+    this.#windowIdByKey.delete(win.key);
+    this.#watchers.delete(win.id);
+    const out = (index: Map<string, Set<number>>, at: string) => {
+      const ids = index.get(at);
+      ids?.delete(win.id);
+      if (ids?.size === 0) index.delete(at);
+    };
+    if (win.query.kind === "range") out(this.#rangeWindowsByFact, driverFactOf(win));
+    else if (win.query.kind === "keys")
+      for (const path of win.query.keys) out(this.#keysWindowsByPath, path);
+    else this.#awakeWindowId = undefined;
+    this.#exec("DELETE FROM rcat_window WHERE id = ?", win.id);
+    this.counters.windowsDropped += 1;
+  }
+
+  #saveWindow(win: LiveWindow): void {
+    this.#exec(
+      "UPDATE rcat_window SET size = ?, b_at = ?, b_path = ?, rev = ? WHERE id = ?",
+      win.size,
+      win.bound ? win.bound[0] : null,
+      win.bound ? win.bound[1] : null,
+      win.rev,
+      win.id,
+    );
+  }
+
+  // ── The statements of a range query. Every one reads one index in its order. ──
+
+  /** FROM and WHERE for a query's rows. With a fact: the driver fact's entries in the index of the
+   *  query's order, and one point lookup in `rcat_fact_path` for each other fact. With none: the
+   *  rows themselves, by the index of the order. `join` adds the row to a fact's entry. */
+  #rangeSql(
+    query: RangeQuery,
+    driver: number,
+  ): { from: string; join: string; where: string[]; args: unknown[]; at: string } {
+    const driven = query.predicates[driver];
+    if (!driven) return { from: "rcat_row r", join: "", where: [], args: [], at: "r" };
+    const where = ["f0.k = ?", "f0.v = ?"];
+    const args: unknown[] = [...driven];
+    query.predicates.forEach((fact, index) => {
+      if (index === driver) return;
+      where.push(
+        "EXISTS (SELECT 1 FROM rcat_fact_path fi WHERE fi.k = ? AND fi.v = ? AND fi.path = f0.path)",
+      );
+      args.push(...fact);
+    });
+    return {
+      from: `${ORDER_INDEX[query.order].facts} f0`,
+      join: " JOIN rcat_row r ON r.path = f0.path",
+      where,
+      args,
+      at: "f0",
+    };
+  }
+
+  /** The window's rows, in order. */
+  #windowSql(query: RangeQuery, driver: number): Statement {
+    const { from, join, where, args, at } = this.#rangeSql(query, driver);
+    return {
+      sql: `SELECT ${ROW_COLUMNS} FROM ${from}${join}${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY ${orderTerms(query.order, at, true)} LIMIT ?`,
+      args: [...args, query.limit],
+    };
+  }
+
+  /** F, the follower: the first row after `bound`. THE BACKFILL. */
+  #followerSql(query: RangeQuery, driver: number, bound: SortKey): Statement {
+    const { from, join, where, args, at } = this.#rangeSql(query, driver);
+    const after = beyond(query.order, at, true, bound);
+    return {
+      sql: `SELECT ${ROW_COLUMNS} FROM ${from}${join} WHERE ${[...where, after.sql].join(" AND ")} ORDER BY ${orderTerms(query.order, at, true)} LIMIT 1`,
+      args: [...args, ...after.args],
+    };
+  }
+
+  /** The sort key of ONE row, read against the window's order: A, the row above `bound` (the last
+   *  row before it), or with no bound M, the last matching row, which is the bound of a window
+   *  that has just become full. */
+  #edgeSql(query: RangeQuery, driver: number, bound: SortKey | null): Statement {
+    const { from, where, args, at } = this.#rangeSql(query, driver);
+    const before = bound ? beyond(query.order, at, false, bound) : { sql: "", args: [] };
+    const conditions = [...where, before.sql].filter(Boolean);
+    const column = ORDER_INDEX[query.order].column;
+    return {
+      sql: `SELECT ${column ? `${at}.${column}` : "0"} AS at, ${at}.path AS path FROM ${from}${conditions.length ? ` WHERE ${conditions.join(" AND ")}` : ""} ORDER BY ${orderTerms(query.order, at, false)} LIMIT 1`,
+      args: [...args, ...before.args],
+    };
+  }
+
+  #windowRows(query: RangeQuery, driver: number): StoredRow[] {
+    const { sql, args } = this.#windowSql(query, driver);
+    return this.#exec<StoredRow>(sql, ...args);
+  }
+
+  #follower(win: LiveWindow, query: RangeQuery, bound: SortKey): StoredRow | undefined {
+    this.counters.seeks += 1;
+    const { sql, args } = this.#followerSql(query, win.driver, bound);
+    return this.#exec<StoredRow>(sql, ...args)[0];
+  }
+
+  #edge(win: LiveWindow, query: RangeQuery, bound: SortKey | null): SortKey | null {
+    this.counters.seeks += 1;
+    const { sql, args } = this.#edgeSql(query, win.driver, bound);
+    const row = this.#exec<{ at: number; path: string }>(sql, ...args)[0];
+    return row ? [row.at, row.path] : null;
+  }
+
+  /** The fact with the fewest rows, counted up to 1,000 each. */
+  #chooseDriver(query: RangeQuery): number {
+    if (query.predicates.length < 2) return 0;
+    let best = 0;
+    let fewest = Infinity;
+    query.predicates.forEach((fact, index) => {
+      const counted =
+        this.#exec<{ n: number }>(
+          "SELECT COUNT(*) AS n FROM (SELECT 1 FROM rcat_fact_path WHERE k = ? AND v = ? LIMIT 1000)",
+          ...fact,
+        )[0]?.n || 0;
+      if (counted < fewest) {
+        fewest = counted;
+        best = index;
+      }
+    });
+    return best;
+  }
+
+  #keysRows(paths: readonly string[]): StoredRow[] {
+    return this.#exec<StoredRow>(
+      `SELECT ${ROW_COLUMNS} FROM rcat_row r WHERE r.path IN (SELECT value FROM json_each(?)) ORDER BY r.path`,
+      JSON.stringify(paths),
+    );
+  }
+
+  // ── Writes ──
+
+  /** Writes rows, each a whole new value of its path, in one transaction. A row equal to the one
+   *  stored is no write: no revision, no frame. Before the first watch it writes nothing. */
+  upsertMany(inputs: readonly CatalogRowInput[]): WriteResult {
+    return this.#write((out) => inputs.filter((input) => this.#upsertOne(input, out)).length);
+  }
+
+  upsert(input: CatalogRowInput): WriteResult {
+    return this.upsertMany([input]);
+  }
+
+  /** Takes rows out. No writer of the kernel does so today: a context keeps its row for good, here
+   *  as in the catalog. It is the collection's other verb, and the case table needs it. */
+  deleteMany(paths: readonly string[]): WriteResult {
+    return this.#write((out) => paths.filter((path) => this.#deleteOne(path, out)).length);
+  }
+
+  #write(work: (out: PendingFrame[]) => number): WriteResult {
+    if (!this.active()) return { rev: this.#rev, changed: 0, frames: 0, messages: 0, chars: 0 };
+    const pending: PendingFrame[] = [];
+    let changed = 0;
+    try {
+      this.#ctx.storage.transactionSync(() => {
+        changed = work(pending);
+        if (changed > 0)
+          this.#exec("UPDATE rcat_meta SET v = ? WHERE k = 'rev'", String(this.#rev));
+      });
+    } catch (error) {
+      // the transaction is undone, and so the windows and the revision in memory are stale
+      this.#forget();
+      throw error;
+    }
+    return { rev: this.#rev, changed, frames: pending.length, ...this.#dispatch(pending) };
+  }
+
+  #storedRow(path: string): (StoredRow & { facts: string }) | undefined {
+    return this.#exec<StoredRow & { facts: string }>(
+      "SELECT path, active_at, created_at, rev, body, facts FROM rcat_row WHERE path = ?",
+      path,
+    )[0];
+  }
+
+  #upsertOne(input: CatalogRowInput, out: PendingFrame[]): boolean {
+    const row = RowInput.safeParse(input);
+    if (!row.success)
+      throw new CatalogRefusal(`not a row of the catalog: ${z.prettifyError(row.error)}`);
+    const { path, activeMs: activeAt, createdMs: createdAt, ...listing } = row.data;
+    const { processors, metadata } = listing;
+    const body = JSON.stringify(listing);
+    if (body.length > CATALOG_LIMITS.bodyChars)
+      throw new CatalogRefusal(
+        `the row of ${path} is longer than ${CATALOG_LIMITS.bodyChars} characters`,
+      );
+    const old = this.#storedRow(path);
+    if (old && old.active_at === activeAt && old.created_at === createdAt && old.body === body) {
+      this.counters.sameWrites += 1;
+      return false;
+    }
+    const facts = extractFacts(path, processors, metadata);
+    // the stored list is the truth of what the old row has in each index: no parse of its body
+    const oldFacts = old ? (JSON.parse(old.facts) as Fact[]) : [];
+    this.#rev += 1;
+    const next: StoredRow = {
+      path,
+      active_at: activeAt,
+      created_at: createdAt,
+      rev: this.#rev,
+      body,
+    };
+    this.#exec(
+      `INSERT INTO rcat_row (path, active_at, created_at, rev, body, facts) VALUES (?, ?, ?, ?, ?, ?)
+       ON CONFLICT (path) DO UPDATE SET active_at = excluded.active_at,
+         created_at = excluded.created_at, rev = excluded.rev, body = excluded.body,
+         facts = excluded.facts`,
+      path,
+      activeAt,
+      createdAt,
+      next.rev,
+      body,
+      JSON.stringify(facts),
+    );
+    this.#moveFacts(old, oldFacts, next, facts);
+    this.counters.writes += 1;
+    this.#notify(old, new Set(oldFacts.map(factId)), next, new Set(facts.map(factId)), out);
+    return true;
+  }
+
+  #deleteOne(path: string, out: PendingFrame[]): boolean {
+    const old = this.#storedRow(path);
+    if (!old) return false;
+    const oldFacts = JSON.parse(old.facts) as Fact[];
+    this.#rev += 1;
+    this.#exec("DELETE FROM rcat_row WHERE path = ?", path);
+    this.#moveFacts(old, oldFacts, undefined, []);
+    this.counters.writes += 1;
+    this.#notify(old, new Set(oldFacts.map(factId)), undefined, new Set(), out);
+    return true;
+  }
+
+  /** A row's entries in each order's index, brought from what the old row had to what the new one
+   *  has. An entry holds the order's own value, so every entry of an order moves when that value
+   *  does; otherwise only the facts that came or went are written. */
+  #moveFacts(
+    old: StoredRow | undefined,
+    oldFacts: readonly Fact[],
+    next: StoredRow | undefined,
+    nextFacts: readonly Fact[],
+  ): void {
+    const oldIds = new Set(oldFacts.map(factId));
+    const nextIds = new Set(nextFacts.map(factId));
+    for (const [order, { facts: table, column }] of Object.entries(ORDER_INDEX) as [
+      CatalogOrder,
+      (typeof ORDER_INDEX)[CatalogOrder],
+    ][]) {
+      const oldAt = old && keyOf(order, old)[0];
+      const nextAt = next && keyOf(order, next)[0];
+      const moved = oldAt !== nextAt;
+      const at = column && ` AND ${column} = ?`;
+      if (old)
+        for (const fact of oldFacts)
+          if (moved || !nextIds.has(factId(fact)))
+            this.#exec(
+              `DELETE FROM ${table} WHERE k = ? AND v = ?${at} AND path = ?`,
+              ...fact,
+              ...(column ? [oldAt] : []),
+              old.path,
+            );
+      if (next)
+        for (const fact of nextFacts)
+          if (moved || !oldIds.has(factId(fact)))
+            this.#exec(
+              `INSERT INTO ${table} (k, v, ${column && `${column}, `}path) VALUES (?, ?, ${column && "?, "}?)`,
+              ...fact,
+              ...(column ? [nextAt] : []),
+              next.path,
+            );
+    }
+  }
+
+  // ── The case table: what one write does to one window ──
+
+  #notify(
+    old: StoredRow | undefined,
+    oldFacts: ReadonlySet<string>,
+    next: StoredRow | undefined,
+    nextFacts: ReadonlySet<string>,
+    out: PendingFrame[],
+  ): void {
+    const windows = this.#loadWindows();
+    if (windows.size === 0) return;
+    const before = out.length;
+    const candidates = new Set<number>();
+    const collect = (ids: ReadonlySet<number> | undefined) => {
+      if (ids) for (const id of ids) candidates.add(id);
+    };
+    collect(this.#rangeWindowsByFact.get("*"));
+    // a window is under ONE of its facts: a row that never held that fact never matched it
+    for (const fact of oldFacts) collect(this.#rangeWindowsByFact.get(fact));
+    for (const fact of nextFacts) collect(this.#rangeWindowsByFact.get(fact));
+    for (const id of candidates) {
+      const win = windows.get(id);
+      if (win?.query.kind === "range")
+        this.#advance(win, win.query, old, oldFacts, next, nextFacts, out);
+    }
+
+    const path = next?.path || old?.path || "";
+    for (const id of this.#keysWindowsByPath.get(path) || []) {
+      const win = windows.get(id);
+      if (!win) continue;
+      this.counters.windowChecks += 1;
+      out.push({
+        windowId: id,
+        from: win.rev,
+        rev: this.#rev,
+        del: next ? [] : [path],
+        put: next ? [[path, rowJson(next)]] : [],
+      });
+      win.rev = this.#rev;
+      this.#saveWindow(win);
+    }
+    if (out.length === before) this.counters.quietWrites += 1;
+  }
+
+  #advance(
+    win: LiveWindow,
+    query: RangeQuery,
+    old: StoredRow | undefined,
+    oldFacts: ReadonlySet<string>,
+    next: StoredRow | undefined,
+    nextFacts: ReadonlySet<string>,
+    out: PendingFrame[],
+  ): void {
+    this.counters.windowChecks += 1;
+    const matches = (facts: ReadonlySet<string>) =>
+      query.predicates.every((fact) => facts.has(factId(fact)));
+    const compare = (a: SortKey, b: SortKey) => compareSortKeys(query.order, a, b);
+    const oldKey = old && matches(oldFacts) ? keyOf(query.order, old) : null;
+    const nextKey = next && matches(nextFacts) ? keyOf(query.order, next) : null;
+
+    const emit = (del: string[], put: StoredRow[]) => {
+      out.push({
+        windowId: win.id,
+        from: win.rev,
+        rev: this.#rev,
+        del,
+        put: put.map((row) => [row.path, rowJson(row)]),
+      });
+      win.rev = this.#rev;
+      this.#saveWindow(win);
+    };
+
+    if (win.size < query.limit) {
+      // a window with room holds every matching row, and keeps no bound
+      if (!oldKey && !nextKey) return;
+      if (!nextKey || !next) {
+        win.size -= 1;
+        return emit([oldKey ? oldKey[1] : ""], []);
+      }
+      if (!oldKey) {
+        win.size += 1;
+        if (win.size === query.limit) win.bound = this.#edge(win, query, null);
+      }
+      return emit([], [next]);
+    }
+
+    const bound = win.bound;
+    if (!bound) throw new Error(`the full window ${win.id} has no bound`);
+    const wasIn = !!oldKey && compare(oldKey, bound) <= 0;
+    if (!wasIn) {
+      // THE COMMON CASE: neither the old key nor the new one is in the window
+      if (!nextKey || !next || compare(nextKey, bound) > 0) return;
+      // the row enters: the last row leaves, and the row above it is the bound
+      win.bound = this.#edge(win, query, bound);
+      return emit([bound[1]], [next]);
+    }
+    if (!nextKey || !next) {
+      // the row leaves: the follower takes the place, in the same frame
+      const follower = this.#follower(win, query, bound);
+      if (follower) win.bound = keyOf(query.order, follower);
+      else {
+        win.size -= 1;
+        win.bound = null;
+      }
+      return emit([oldKey[1]], follower ? [follower] : []);
+    }
+    const moved = compare(nextKey, bound);
+    const wasLast = compare(oldKey, bound) === 0;
+    if (moved === 0 || (moved < 0 && !wasLast)) return emit([], [next]);
+    if (moved < 0) {
+      // the last row moved up: the row that is last now is the bound
+      win.bound = this.#edge(win, query, bound);
+      return emit([], [next]);
+    }
+    // the row moved to after the bound: the follower is the last row, and it may be this row
+    const follower = this.#follower(win, query, bound);
+    if (!follower) throw new Error(`the window ${win.id} lost the row that moved past its bound`);
+    win.bound = keyOf(query.order, follower);
+    if (follower.path === next.path) return emit([], [next]);
+    return emit([oldKey[1]], [follower]);
+  }
+
+  // ── Awake ──
+
+  /** Whether anyone watches the awake list: when nobody does, the object does nothing for a wake. */
+  awakeWatched(): boolean {
+    this.#loadWindows();
+    return this.#awakeWindowId !== undefined;
+  }
+
+  /** A context woke or said what it does now (`state`), or went quiet (undefined). No row and no
+   *  revision: the awake list is the sockets. */
+  awakeChanged(path: string, state: AwakeContextState | undefined): void {
+    const windows = this.#loadWindows();
+    const win = this.#awakeWindowId === undefined ? undefined : windows.get(this.#awakeWindowId);
+    if (!win) return;
+    this.#dispatch([
+      {
+        windowId: win.id,
+        from: win.rev,
+        rev: win.rev,
+        del: state ? [] : [path],
+        put: state ? [[path, awakeJson(path, state)]] : [],
+      },
+    ]);
+  }
+
+  // ── Sockets ──
+
+  #loadSockets(): Map<string, WatchSocket> {
+    if (this.#sockets) return this.#sockets;
+    this.#loadWindows();
+    const sockets = new Map<string, WatchSocket>();
+    this.#sockets = sockets;
+    this.#watchers = new Map();
+    for (const ws of this.#ctx.getWebSockets(WATCH_SOCKET_TAG)) {
+      if (ws.readyState !== WebSocket.OPEN) continue;
+      const attachment = WatchAttachment.safeParse(ws.deserializeAttachment()).data;
+      if (!attachment) continue;
+      const subs = new Map(Object.entries(attachment.subs));
+      sockets.set(attachment.sid, { ws, subs });
+      for (const [sub, windowId] of subs) this.#watch(windowId, attachment.sid, sub);
+    }
+    return sockets;
+  }
+
+  #watch(windowId: number, sid: string, sub: string): void {
+    let bySocket = this.#watchers.get(windowId);
+    if (!bySocket) this.#watchers.set(windowId, (bySocket = new Map()));
+    let subs = bySocket.get(sid);
+    if (!subs) bySocket.set(sid, (subs = new Set()));
+    subs.add(sub);
+  }
+
+  /** Takes a socket's name for a query off its window. A window that nobody watches goes. */
+  #unwatch(windowId: number, sid: string, sub: string): void {
+    const bySocket = this.#watchers.get(windowId);
+    const subs = bySocket?.get(sid);
+    subs?.delete(sub);
+    if (subs?.size === 0) bySocket?.delete(sid);
+    if (bySocket && bySocket.size > 0) return;
+    const win = this.#loadWindows().get(windowId);
+    if (win) this.#dropWindow(win);
+  }
+
+  /** Sends each socket ONE message with every frame that is for it. Returns what was sent. */
+  #dispatch(pending: readonly PendingFrame[]): { messages: number; chars: number } {
+    if (pending.length === 0) return { messages: 0, chars: 0 };
+    const sockets = this.#loadSockets();
+    const windows = this.#loadWindows();
+    type Part = { rows: Map<string, string>; frames: string[]; chars: number };
+    const bySocket = new Map<string, Part[]>();
+    for (const frame of pending) {
+      const watchers = this.#watchers.get(frame.windowId);
+      if (!watchers?.size) {
+        // left by a socket that ended with no close event: the window goes at its first frame
+        const win = windows.get(frame.windowId);
+        if (win) this.#dropWindow(win);
+        continue;
+      }
+      const tail = `,${frame.from},${frame.rev},${JSON.stringify(frame.del)},${JSON.stringify(frame.put.map(([path]) => path))}]`;
+      const rowChars = frame.put.reduce((sum, [, json]) => sum + json.length, 0);
+      for (const [sid, subs] of watchers) {
+        let parts = bySocket.get(sid);
+        if (!parts) bySocket.set(sid, (parts = [{ rows: new Map(), frames: [], chars: 0 }]));
+        let part = parts[parts.length - 1];
+        if (!part || part.chars > CATALOG_LIMITS.messageChars)
+          parts.push((part = { rows: new Map(), frames: [], chars: 0 }));
+        for (const [path, json] of frame.put) part.rows.set(path, json);
+        for (const sub of subs) part.frames.push(`[${JSON.stringify(sub)}${tail}`);
+        part.chars += rowChars + tail.length * subs.size;
+      }
+    }
+    let messages = 0;
+    let chars = 0;
+    for (const [sid, parts] of bySocket) {
+      const socket = sockets.get(sid);
+      if (!socket) continue;
+      for (const part of parts) {
+        const message = `{"gen":${JSON.stringify(this.#gen)},"rows":[${[...part.rows.values()].join(",")}],"d":[${part.frames.join(",")}]}`;
+        if (!this.#send(socket.ws, message)) continue;
+        messages += 1;
+        chars += message.length;
+      }
+    }
+    return { messages, chars };
+  }
+
+  #send(ws: WebSocket, message: string): boolean {
+    try {
+      ws.send(message);
+      this.counters.messagesSent += 1;
+      this.counters.charsSent += message.length;
+      return true;
+    } catch {
+      // a socket that is closing: its close event takes its queries off
+      return false;
+    }
+  }
+
+  /** The upgrade of a watch socket: the object's end is accepted with the hibernation API. */
+  acceptWatchWebSocket(): Response {
+    const pair = new WebSocketPair();
+    try {
+      this.attachWatchSocket(pair[1]);
+    } catch (error) {
+      // the limit of sockets on one Durable Object
+      return new Response(`${error instanceof Error ? error.message : String(error)}\n`, {
+        status: 503,
+      });
+    }
+    return new Response(null, { status: 101, webSocket: pair[0] });
+  }
+
+  attachWatchSocket(ws: WebSocket): void {
+    this.#ensureTables();
+    this.#ctx.acceptWebSocket(ws, [WATCH_SOCKET_TAG]);
+    const sid = crypto.randomUUID().slice(0, 12);
+    ws.serializeAttachment({ sid, subs: {} } satisfies z.infer<typeof WatchAttachment>);
+    this.#sockets?.set(sid, { ws, subs: new Map() });
+    this.#send(ws, JSON.stringify({ hello: { gen: this.#gen, rev: this.#rev } }));
+  }
+
+  isWatchWebSocket(ws: WebSocket): boolean {
+    return this.#ctx.getTags(ws).includes(WATCH_SOCKET_TAG);
+  }
+
+  handleWatchMessage(ws: WebSocket, raw: string | ArrayBuffer): void {
+    let request: z.infer<typeof WatchRequest> | undefined;
+    try {
+      try {
+        request = WatchRequest.parse(JSON.parse(typeof raw === "string" ? raw : ""));
+      } catch {
+        throw new CatalogRefusal(
+          `a message is one JSON object, { op: "subscribe" | "unsubscribe", sub: a name of 1 to ${CATALOG_LIMITS.subChars} characters, query?, cursor? }`,
+        );
+      }
+      const sockets = this.#loadSockets();
+      const sid = WatchAttachment.safeParse(ws.deserializeAttachment()).data?.sid || "";
+      const socket = sockets.get(sid);
+      if (!socket) throw new CatalogRefusal("this socket is not a watch socket");
+      socket.ws = ws;
+      if (request.op === "subscribe") {
+        this.#subscribe(sid, socket, request.sub, request.query, request.cursor);
+        return;
+      }
+      const windowId = socket.subs.get(request.sub);
+      socket.subs.delete(request.sub);
+      ws.serializeAttachment({ sid, subs: Object.fromEntries(socket.subs) });
+      if (windowId !== undefined) this.#unwatch(windowId, sid, request.sub);
+      this.#send(ws, JSON.stringify({ sub: request.sub, unsubscribed: true }));
+    } catch (error) {
+      const refused = error instanceof CatalogRefusal;
+      if (!refused) {
+        this.#forget();
+        console.info({
+          event: "context.reactive-catalog-failed",
+          message: error instanceof Error ? error.message : String(error),
+        });
+      }
+      this.#send(
+        ws,
+        JSON.stringify({
+          sub: request?.sub,
+          error: refused ? error.message : "the catalog failed, and its log says why",
+        }),
+      );
+    }
+  }
+
+  #subscribe(sid: string, socket: WatchSocket, sub: string, spec: unknown, cursor: unknown): void {
+    const { query, key } = normalizeQuery(spec);
+    const had = socket.subs.get(sub);
+    if (had === undefined && socket.subs.size >= CATALOG_LIMITS.subsPerSocket)
+      throw new CatalogRefusal(`a socket holds at most ${CATALOG_LIMITS.subsPerSocket} queries`);
+    // the awake list is the sockets: it needs no row
+    if (query.kind !== "awake") this.fill();
+    const windows = this.#loadWindows();
+
+    let win = windows.get(this.#windowIdByKey.get(key) ?? -1);
+    let rows: StoredRow[] | undefined;
+    if (!win) {
+      if (windows.size >= CATALOG_LIMITS.windows)
+        // windows that no open socket names: left by a socket that ended with no close event
+        for (const stale of [...windows.values()])
+          if (!this.#watchers.get(stale.id)?.size) this.#dropWindow(stale);
+      if (windows.size >= CATALOG_LIMITS.windows)
+        throw new CatalogRefusal(
+          `the catalog holds at most ${CATALOG_LIMITS.windows} live queries`,
+        );
+      const driver = query.kind === "range" ? this.#chooseDriver(query) : 0;
+      rows = query.kind === "range" ? this.#windowRows(query, driver) : undefined;
+      const last =
+        rows && query.kind === "range" && rows.length === query.limit ? rows.at(-1) : undefined;
+      const bound = last && query.kind === "range" ? keyOf(query.order, last) : null;
+      const made = this.#exec<{ id: number }>(
+        "INSERT INTO rcat_window (key, driver, size, b_at, b_path, rev) VALUES (?, ?, ?, ?, ?, ?) RETURNING id",
+        key,
+        driver,
+        rows?.length || 0,
+        bound ? bound[0] : null,
+        bound ? bound[1] : null,
+        this.#rev,
+      )[0];
+      if (!made) throw new Error("the window was not stored");
+      win = { id: made.id, key, query, driver, size: rows?.length || 0, bound, rev: this.#rev };
+      this.#indexWindow(windows, win);
+      this.counters.windowsMade += 1;
+    }
+    // the socket's name moves to this window before the old one is let go
+    socket.subs.set(sub, win.id);
+    socket.ws.serializeAttachment({ sid, subs: Object.fromEntries(socket.subs) });
+    this.#watch(win.id, sid, sub);
+    if (had !== undefined && had !== win.id) this.#unwatch(had, sid, sub);
+    this.#sendAnswer(socket.ws, sub, win, cursor, rows);
+  }
+
+  /** The answer to a subscribe: the window now. With a cursor of this generation and this query,
+   *  every path and only the rows the watcher lacks; otherwise every row. */
+  #sendAnswer(
+    ws: WebSocket,
+    sub: string,
+    win: LiveWindow,
+    rawCursor: unknown,
+    known?: StoredRow[],
+  ): void {
+    const query = win.query;
+    const q = queryName(query);
+    const head = `{"sub":${JSON.stringify(sub)},"q":"${q}","gen":${JSON.stringify(this.#gen)},"rev":${win.rev}`;
+    if (query.kind === "awake") {
+      const awake = [...this.#deps.awake()].map(([path, state]) => awakeJson(path, state));
+      this.#send(ws, `${head},"full":false,"reset":[${awake.join(",")}]}`);
+      return;
+    }
+    const rows =
+      known ||
+      (query.kind === "range" ? this.#windowRows(query, win.driver) : this.#keysRows(query.keys));
+    const full = query.kind === "range" && rows.length === query.limit;
+    const cursor = WatcherCursor.safeParse(rawCursor).data;
+    if (!cursor || cursor.gen !== this.#gen || cursor.q !== q) {
+      this.#send(ws, `${head},"full":${full},"reset":[${rows.map(rowJson).join(",")}]}`);
+      return;
+    }
+    const have = new Set(cursor.have);
+    const { bound } = cursor;
+    const held = (row: StoredRow) =>
+      row.rev <= cursor.rev &&
+      (query.kind === "range"
+        ? !!bound && compareSortKeys(query.order, keyOf(query.order, row), bound) <= 0
+        : have.has(row.path));
+    const put = rows.filter((row) => !held(row));
+    this.counters.rowsNotResent += rows.length - put.length;
+    this.#send(
+      ws,
+      `${head},"full":${full},"ids":${JSON.stringify(rows.map((row) => row.path))},"put":[${put.map(rowJson).join(",")}]}`,
+    );
+  }
+
+  handleWatchClose(ws: WebSocket): void {
+    try {
+      ws.close(1000, "closed");
+    } catch {
+      // already closing
+    }
+    const attachment = WatchAttachment.safeParse(ws.deserializeAttachment()).data;
+    if (!attachment) return;
+    const sockets = this.#loadSockets();
+    // a socket that closed is no longer open: when memory does not have its queries, they come
+    // from its attachment
+    const subs = sockets.get(attachment.sid)?.subs || new Map(Object.entries(attachment.subs));
+    sockets.delete(attachment.sid);
+    for (const [sub, windowId] of subs) this.#unwatch(windowId, attachment.sid, sub);
+  }
+
+  // ── What a test and a person can ask ──
+
+  /** Each window's stored size and bound against the rows now. Empty when all agree. */
+  verify(): string[] {
+    const faults: string[] = [];
+    for (const win of this.#loadWindows().values()) {
+      if (win.query.kind !== "range") continue;
+      const rows = this.#windowRows(win.query, win.driver);
+      const last = rows.length === win.query.limit ? rows.at(-1) : undefined;
+      const bound = last ? keyOf(win.query.order, last) : null;
+      if (rows.length !== win.size || JSON.stringify(bound) !== JSON.stringify(win.bound))
+        faults.push(
+          `window ${win.id} ${win.key}: stored size ${win.size} bound ${JSON.stringify(win.bound)}, rows give size ${rows.length} bound ${JSON.stringify(bound)}`,
+        );
+      const newest = rows.reduce((max, row) => Math.max(max, row.rev), 0);
+      if (newest > win.rev)
+        faults.push(
+          `window ${win.id}: a row of revision ${newest} is past the window's ${win.rev}`,
+        );
+    }
+    return faults;
+  }
+
+  /** Who watches what, and what the object did since it last woke (iterate/api `CatalogWatches`). */
+  watches(options: { verify?: boolean; plans?: boolean } = {}): CatalogWatches {
+    const windows = [...this.#loadWindows().values()];
+    const sockets = this.#loadSockets();
+    return {
+      active: this.#filled.started,
+      gen: this.#gen,
+      rev: this.#rev,
+      rows:
+        this.#sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rcat_row").toArray()[0]?.n || 0,
+      sockets: sockets.size,
+      awake: this.#deps.awake().size,
+      windows: windows.map((win) => ({
+        query: win.key,
+        size: win.size,
+        bound: win.bound,
+        rev: win.rev,
+        watchers: [...(this.#watchers.get(win.id)?.values() || [])].reduce(
+          (sum, subs) => sum + subs.size,
+          0,
+        ),
+      })),
+      counters: { ...this.counters },
+      ...(options.verify && { faults: this.verify() }),
+      ...(options.plans && { plans: this.#plans() }),
+    };
+  }
+
+  /** How SQLite reads the statements that the engine builds, for one fact, two facts and no fact
+   *  in each order. */
+  #plans(): Record<string, string[]> {
+    const plan = ({ sql, args }: Statement) =>
+      this.#sql
+        .exec<{ detail: string }>(`EXPLAIN QUERY PLAN ${sql}`, ...args)
+        .toArray()
+        .map((row) => row.detail);
+    const plans: Record<string, string[]> = {};
+    const at: SortKey = [1_000, "/t"];
+    for (const order of Object.keys(ORDER_INDEX) as CatalogOrder[]) {
+      const queries: Record<string, RangeQuery> = {
+        "no fact": { kind: "range", predicates: [], order, limit: 50 },
+        "one fact": { kind: "range", predicates: [["status", "open"]], order, limit: 50 },
+        "two facts": {
+          kind: "range",
+          predicates: [
+            ["priority", "high"],
+            ["status", "open"],
+          ],
+          order,
+          limit: 50,
+        },
+      };
+      for (const [facts, query] of Object.entries(queries)) {
+        plans[`${order}, ${facts}: the window`] = plan(this.#windowSql(query, 0));
+        plans[`${order}, ${facts}: the follower (the backfill)`] = plan(
+          this.#followerSql(query, 0, at),
+        );
+        plans[`${order}, ${facts}: the row above the bound`] = plan(this.#edgeSql(query, 0, at));
+        plans[`${order}, ${facts}: the last matching row`] = plan(this.#edgeSql(query, 0, null));
+      }
+    }
+    plans["rows by key"] = plan({
+      sql: `SELECT ${ROW_COLUMNS} FROM rcat_row r WHERE r.path IN (SELECT value FROM json_each(?))`,
+      args: ["[]"],
+    });
+    return plans;
+  }
+}
+
+export type WriteResult = {
+  /** The catalog's revision after the write. */
+  rev: number;
+  /** How many rows changed: a row equal to the stored one is not counted. */
+  changed: number;
+  /** How many windows got a frame. */
+  frames: number;
+  /** How many socket messages carried them, and their length in characters. */
+  messages: number;
+  chars: number;
+};
+
+/** A row as the catalog can order and index it. A time that is no whole number of milliseconds
+ *  orders differently in SQLite and in JavaScript, and so does a path that is not well-formed.
+ *  Every other field passes: it is the row's body. */
+const RowInput = z.looseObject({
+  path: ContextPath,
+  activeMs: z.number().int(),
+  createdMs: z.number().int(),
+  processors: z.array(z.string()).default([]),
+  metadata: z.record(z.string(), z.unknown()).default({}),
+});
+
+/** A window's query, read back from its stored key (`normalizeQuery` wrote it). */
+function queryOfKey(key: string): Query {
+  const stored = JSON.parse(key) as { p?: Fact[]; o?: CatalogOrder; l?: number; k?: string[] };
+  if (stored.p)
+    return {
+      kind: "range",
+      predicates: stored.p,
+      order: stored.o || "active",
+      limit: stored.l || 50,
+    };
+  return stored.k ? { kind: "keys", keys: stored.k } : { kind: "awake" };
+}
+
+function driverFactOf(win: LiveWindow): string {
+  const fact = win.query.kind === "range" ? win.query.predicates[win.driver] : undefined;
+  return fact ? factId(fact) : "*";
+}
+
+/** A row of the awake list (iterate/api `CatalogAwakeRow`). */
+function awakeJson(path: string, state: AwakeContextState): string {
+  const activities = activeContextActivities(state.activities);
+  return JSON.stringify({ path, since: state.since, ...(activities.length > 0 && { activities }) });
+}
M core/itx/src/iterate-context-durable-object.ts
@@ -23,6 +23,7 @@
   normalizedItxExpression,
 } from "iterate/expression";
 import type {
+  CatalogWatches,
   ContextListing,
   ContextListOptions,
   RewriteRuleListEntry,
@@ -91,6 +92,8 @@
 import { Residency } from "./context/residency.ts";
 import {
   AWAKE_CONTEXT_PATH,
+  AWAKE_SUMMARY_KEPT,
+  AWAKE_SUMMARY_REFUSED,
   AWAKE_WEBSOCKET_HEADER,
   AwakeSocket,
   acceptAwakeWebSocket,
@@ -99,6 +102,7 @@
   isAwakeWebSocket,
   setAwakeActivities,
 } from "./context/awake.ts";
+import { CATALOG_WATCH_HEADER } from "./context/catalog-watch.ts";
 import {
   ContextActivityReport,
   ContextActivityTracker,
@@ -108,7 +112,12 @@
   withTrackedActivity,
 } from "./context/context-activity-stack.ts";
 import { ContextCatalog, type ContextSummaryMessage } from "./context/context-catalog.ts";
-import { ContextSummaryTracker } from "./context/context-summary.ts";
+import { CONTEXT_DESCRIBED_TYPE, ContextSummaryTracker } from "./context/context-summary.ts";
+import {
+  CatalogRefusal,
+  ReactiveCatalog,
+  type CatalogRowInput,
+} from "./context/reactive-catalog.ts";
 import { egress } from "./context/egress.ts";
 import {
   SNAPSHOT_TTL_MS,
@@ -369,6 +378,10 @@
       });
       this.#contextSummary.committed(events);
       this.#activityStack.committed(events, this.#durableObjectAddress.path);
+      // What a context says of itself for good goes to the catalog within the debounce, not at the
+      // next summary that is due: a watcher of the catalog sees a new title at once (awake.ts).
+      if (events.some((event) => !event.ephemeral && event.type === CONTEXT_DESCRIBED_TYPE))
+        this.#awakeSocket.activityChanged();
       const woken = events.find((event) => event.type === "events.iterate.com/itx/woken");
       if (woken) this.#announceToAncestors(woken.source?.cause);
       this.#measureSize();
@@ -1039,6 +1052,8 @@
       ...this.#durableAlarmDeadlines(),
       ...Object.values(this.#residency.deadlines()),
       ...[...this.#runsOwedToTheAlarm.values()].map(({ requestedAt }) => requestedAt),
+      // until the catalog has answered all that this context said of itself (context/awake.ts)
+      this.#awakeSocket.recoverAt(),
     ],
     held: () => this.#residency.holdsResident() || this.#runsOwedToTheAlarm.size > 0,
     // The prd fault alarm's pin (PINNED_WORKAROUNDS) counts the re-arm warning.
@@ -1148,6 +1163,16 @@
             [AWAKE_WEBSOCKET_HEADER]: encodeURIComponent(this.#durableObjectAddress.path),
           },
         }),
+    recoveryChanged: () => this.#alarmCoordinator.reconcile(),
+    // A count that the end of this object does not lose: written only when the catalog left a
+    // summary unanswered, and taken away when it answers.
+    unanswered: {
+      count: () => Number(this.ctx.storage.kv.get("awake-summary-unanswered")) || 0,
+      set: (count) => {
+        if (count > 0) this.ctx.storage.kv.put("awake-summary-unanswered", count);
+        else this.ctx.storage.kv.delete("awake-summary-unanswered");
+      },
+    },
   });
 
   // Live in-flight activities in RAM only (never persisted to KV/SQLite), streaming deltas via
@@ -1174,6 +1199,13 @@
 
   // The rows of the context that accepts the awake sockets (context/context-catalog.ts).
   readonly #contextCatalog = new ContextCatalog(this.ctx.storage.sql);
+  // A copy of those rows that answers watched queries, in the same context
+  // (context/reactive-catalog.ts). It keeps nothing until the first watch, and fills itself then
+  // from the catalog's own rows.
+  readonly #reactiveCatalog = new ReactiveCatalog(this.ctx.storage.sql, this.ctx, {
+    awake: () => awakeContexts(this.ctx),
+    seed: (after, limit) => this.#contextCatalog.rowsAfter(after, limit),
+  });
 
   /** The mind's catalog of its contexts, asked of the context that accepts their sockets. It
    *  records no wake: a list reads the rows and the sockets this object holds. */
@@ -1181,6 +1213,19 @@
     return this.#contextCatalog.list(options, awakeContexts(this.ctx));
   }
 
+  /** Who watches what in the catalog, asked as `listContexts` is: it records no wake. */
+  catalogWatches(options: { verify?: boolean; plans?: boolean }): CatalogWatches {
+    return this.#reactiveCatalog.watches(options);
+  }
+
+  /** A context woke, said what it does now, or went quiet: who watches the awake list hears of
+   *  it. `closing` is the socket whose close is being handled. With no watcher this reads
+   *  nothing. */
+  #awakeListChanged(path: string, closing?: WebSocket): void {
+    if (!this.#reactiveCatalog.awakeWatched()) return;
+    this.#reactiveCatalog.awakeChanged(path, awakeContexts(this.ctx, closing).get(path));
+  }
+
   #traceAlarm(
     reason: AlarmTrace["reason"],
     before: number | null,
@@ -1291,7 +1336,13 @@
       !wakeRecordSettlesARun &&
       !(schedule || delivery || facetClaim)
     ) {
-      await this.#alarmCoordinator.pass(async () => this.#residency.alarmPassStarted(wokeAt));
+      await this.#alarmCoordinator.pass(async () => {
+        // The catalog did not answer what this context last said of itself: it says it again. No
+        // wake record: nothing happened here, and the summary is of the log as it is. Inside the
+        // pass, so its next alarm is written once, when the pass ends.
+        this.#awakeSocket.recover(wokeAt);
+        await this.#residency.alarmPassStarted(wokeAt);
+      });
       return;
     }
     try {
@@ -1561,7 +1612,23 @@
     // nothing. Loaded code dials none, as it attaches no pager.
     if (!fromLoadedCode) {
       const awake = acceptAwakeWebSocket(this.ctx, this.#durableObjectAddress.path, request);
-      if (awake) return awake;
+      if (awake) {
+        if (awake.status === 101)
+          this.#awakeListChanged(
+            decodeURIComponent(request.headers.get(AWAKE_WEBSOCKET_HEADER) || ""),
+          );
+        return awake;
+      }
+      // A watch of the catalog, dialled by a session's end (context/catalog-watch.ts): the kernel's
+      // own dial, as the awake socket is. A request that names an expression is a caller's `fetch`
+      // and is none: no session and no code opens a watch socket by a header.
+      if (
+        request.headers.has(CATALOG_WATCH_HEADER) &&
+        !request.headers.has(ITX_EXPRESSION_FETCH_HEADER)
+      )
+        return this.#durableObjectAddress.path === AWAKE_CONTEXT_PATH
+          ? this.#reactiveCatalog.acceptWatchWebSocket()
+          : new Response(`only ${AWAKE_CONTEXT_PATH} accepts a watch socket\n`, { status: 404 });
     }
     this.#awakeSocket.entered();
     const kind = fromLoadedCode ? "loaded" : "other";
@@ -1650,25 +1717,56 @@
   webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): void {
     // A context's summary: one durable row written, live activities kept on the socket attachment.
     if (isAwakeWebSocket(this.ctx, ws)) {
-      const { path } = awakeContextOf(ws);
+      const { path, activities: saidBefore } = awakeContextOf(ws);
+      let answer = AWAKE_SUMMARY_KEPT;
       try {
-        const activities = this.#contextCatalog.store(
+        const { activities, row } = this.#contextCatalog.store(
           path,
           typeof message === "string" ? message : "",
         );
         setAwakeActivities(ws, activities);
+        if (JSON.stringify(activities || []) !== JSON.stringify(saidBefore || []))
+          this.#awakeListChanged(path);
+        if (row && this.#reactiveCatalog.active()) this.#keepWatchedRow(row);
       } catch (error) {
+        answer = AWAKE_SUMMARY_REFUSED;
         console.info({
           event: "context.catalog-summary-refused",
           path,
           message: error instanceof Error ? error.message : String(error),
         });
       }
+      // The context waits for this before it closes its socket (context/awake.ts). The runtime
+      // holds it until the row is durable.
+      try {
+        ws.send(answer);
+      } catch {
+        // a socket that is closing: the context says its summary again
+      }
       return;
     }
+    if (this.#reactiveCatalog.isWatchWebSocket(ws))
+      return this.#reactiveCatalog.handleWatchMessage(ws, message);
     this.#inboundRequestInOneTurn("webSocketMessage");
     this.#rpcStubFetch.handleWebSocketMessage(ws, message);
   }
+
+  /** A row that the catalog kept is also the row of the copy that answers watched queries. One
+   *  that the copy refuses (a path it cannot order) is taken out of it: a watcher then sees no
+   *  row of that context, and never an old one. */
+  #keepWatchedRow(row: CatalogRowInput): void {
+    try {
+      this.#reactiveCatalog.upsert(row);
+    } catch (error) {
+      if (error instanceof CatalogRefusal) this.#reactiveCatalog.deleteMany([row.path]);
+      console.info({
+        event: "context.reactive-catalog-row-refused",
+        path: row.path,
+        message: error instanceof Error ? error.message : String(error),
+      });
+    }
+  }
+
   webSocketClose(ws: WebSocket, code: number, reason: string): void {
     // An awake socket that closed is off the list already: no wake record, no entry.
     if (isAwakeWebSocket(this.ctx, ws)) {
@@ -1678,8 +1776,11 @@
       } catch {
         // already closing
       }
+      this.#awakeListChanged(awakeContextOf(ws).path, ws);
       return;
     }
+    if (this.#reactiveCatalog.isWatchWebSocket(ws))
+      return this.#reactiveCatalog.handleWatchClose(ws);
     this.#inboundRequestInOneTurn("webSocketClose");
     if (this.#rpcStubFetch.handleWebSocketClose(ws, code, reason)) return;
     this.#rpcStubs.rpcStubPagerClosed(ws);
M core/itx/src/iterate-context.ts

Not shown: the change is larger than this page shows. A clone has it.

M core/lib/src/api.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/mind-worker/src/context/catalog-watch.test.ts
@@ -0,0 +1,341 @@
+// catalog-watch.test.ts — `itx.contexts.watch` in workerd (./fixtures/catalog-watch.ts): a client
+// with one capnweb connection and a callback, real contexts that say what they are through their
+// own logs, the object that accepts their awake sockets with its SQLite, and the hibernation API's
+// sockets between them. Nothing here writes a row of the catalog: every row comes from a context's
+// `events.iterate.com/itx/described` on its own log, as it does in a mind.
+import { fileURLToPath } from "node:url";
+import { build } from "esbuild";
+import { Miniflare } from "miniflare";
+import { newWebSocketRpcSession } from "capnweb";
+import type {
+  CatalogAwakeRow,
+  CatalogCursor,
+  CatalogFrame,
+  CatalogQuery,
+  CatalogRow,
+  CatalogWatches,
+  ContextListing,
+} from "iterate/api";
+import { COMPATIBILITY_DATE } from "iterate/compatibility-date";
+import { expect, test } from "vitest";
+
+test.for([
+  { ends: "the mind's own Worker, as a page's /itx does", path: "/page" },
+  { ends: "the boundary, as the API's does", path: "/" },
+])(
+  "a session that ends in $ends: the answer and then each change come to the watcher's callback",
+  { timeout: 60_000 },
+  async ({ path }) => {
+    await using runtime = await mind();
+    using itx = await session(runtime, path);
+    await described(itx, "/tasks/one", { status: "open", title: "One" });
+    await described(itx, "/tasks/two", { status: "closed", title: "Two" });
+    await listed(itx, { "/tasks/one": "open", "/tasks/two": "closed" });
+
+    // 1. the answer: the open task, and no other context
+    const open = watcher();
+    using _watch = await itx.contexts.watch({ where: { status: "open" }, limit: 5 }, open.take);
+    expect(open.frames).toHaveLength(1);
+    expect(open.frames[0]).toMatchObject({
+      type: "reset",
+      full: false,
+      rows: [
+        {
+          path: "/tasks/one",
+          metadata: { status: "open", title: "One" },
+          description: "What /tasks/one is for",
+          processors: [],
+        },
+      ],
+    });
+    // a watched row is the context's listing, with the two times that the orders sort by
+    const [one] = open.rows();
+    expect(one).toMatchObject({
+      activeMs: Date.parse(one!.lastActivityAt || one!.lastEventAt || ""),
+      createdMs: Date.parse(one!.createdAt || ""),
+      eventCount: expect.any(Number),
+      eventTypes: { "events.iterate.com/itx/described": 1 },
+    });
+
+    // 2. a context enters the answer: one frame, with the row
+    await described(itx, "/tasks/two", { status: "open", title: "Two" });
+    await open.until((rows) => rows.length === 2);
+    expect(open.frames.at(-1)).toMatchObject({
+      type: "change",
+      del: [],
+      rows: [{ path: "/tasks/two" }],
+    });
+    // the newest activity first
+    expect(open.rows().map((row) => row.path)).toEqual(["/tasks/two", "/tasks/one"]);
+
+    // 3. a context leaves it: one frame, with the path
+    await described(itx, "/tasks/one", { status: "closed", title: "One" });
+    await open.until((rows) => rows.length === 1);
+    expect(open.frames.at(-1)).toMatchObject({ type: "change", del: ["/tasks/one"], rows: [] });
+
+    // 4. a write that the query does not select sends this watcher nothing
+    const framesBefore = open.frames.length;
+    await described(itx, "/tasks/three", { status: "closed" });
+    await listed(itx, { "/tasks/three": "closed" });
+    expect(open.frames).toHaveLength(framesBefore);
+
+    // 5. every frame followed the one before it
+    expect(open).toMatchObject({ gaps: [] });
+  },
+);
+
+test(
+  "one write is one batch for a session: a watcher of two queries gets both frames together",
+  { timeout: 60_000 },
+  async () => {
+    await using runtime = await mind();
+    using itx = await session(runtime, "/page");
+    await described(itx, "/tasks/one", { status: "open" });
+    await listed(itx, { "/tasks/one": "open" });
+    const batches: string[][] = [];
+    let batch: string[] = [];
+    const take = (name: string) => (frame: CatalogFrame) => {
+      if (frame.type !== "change") return;
+      batch.push(name);
+      if (frame.more) return;
+      batches.push(batch);
+      batch = [];
+    };
+    using _open = await itx.contexts.watch({ where: { status: "open" } }, take("open"));
+    using _byPath = await itx.contexts.watch({ under: "/tasks", order: "path" }, take("byPath"));
+    using _key = await itx.contexts.watch({ keys: ["/tasks/one"] }, take("key"));
+    await described(itx, "/tasks/one", { status: "open", title: "Renamed" });
+    await until(() => batches.length > 0);
+    expect(batches[0]!.toSorted()).toEqual(["byPath", "key", "open"]);
+  },
+);
+
+test(
+  "a watcher that comes back with its cursor gets every path and only the rows it lacks",
+  { timeout: 60_000 },
+  async () => {
+    await using runtime = await mind();
+    const query: CatalogQuery = { under: "/tasks", order: "path", limit: 10 };
+    let cursor: CatalogCursor;
+    {
+      using itx = await session(runtime, "/");
+      for (const name of ["a", "b", "c"])
+        await described(itx, `/tasks/${name}`, { status: "open" });
+      await listed(itx, { "/tasks/a": "open", "/tasks/b": "open", "/tasks/c": "open" });
+      const first = watcher();
+      using _watch = await itx.contexts.watch(query, first.take);
+      const last = first.frames.at(-1)!;
+      if (last.type !== "reset") throw new Error("the first answer is every row");
+      // by path, A to Z
+      expect(last.rows.map((row) => row.path)).toEqual(["/tasks/a", "/tasks/b", "/tasks/c"]);
+      // what the watcher holds: the order `path` has no time, so the bound's first part is 0
+      cursor = { gen: last.gen, rev: last.rev, q: last.q, bound: [0, "/tasks/c"] };
+    }
+    // the session is over; one row changes while the watcher is away
+    using itx = await session(runtime, "/");
+    await described(itx, "/tasks/b", { status: "closed" });
+    await listed(itx, { "/tasks/b": "closed" });
+    const again = watcher();
+    using _watch = await itx.contexts.watch(query, again.take, { cursor });
+    expect(again.frames[0]).toMatchObject({
+      type: "resume",
+      ids: ["/tasks/a", "/tasks/b", "/tasks/c"],
+      rows: [{ path: "/tasks/b", metadata: { status: "closed" } }],
+    });
+  },
+);
+
+test(
+  "the awake list is a watch too, and the catalog says who watches what",
+  { timeout: 60_000 },
+  async () => {
+    await using runtime = await mind();
+    using itx = await session(runtime, "/page");
+    const awake: CatalogFrame<CatalogAwakeRow>[] = [];
+    using _watch = await itx.contexts.watch<CatalogAwakeRow>(
+      { awake: true },
+      (frame) => void awake.push(frame),
+    );
+    expect(awake[0]).toMatchObject({ type: "reset" });
+    // the awake list needs no row: the catalog keeps none until a query asks for rows
+    expect(await itx.contexts.watches()).toMatchObject({ active: false, rows: 0, sockets: 1 });
+
+    await described(itx, "/tasks/one", { status: "open" });
+    // the context wakes, and a second after its work it goes quiet
+    await until(() =>
+      awake.some(
+        (frame) => frame.type === "change" && frame.rows.some((row) => row.path === "/tasks/one"),
+      ),
+    );
+    await until(() =>
+      awake.some((frame) => frame.type === "change" && frame.del.includes("/tasks/one")),
+    );
+
+    using _open = await itx.contexts.watch({ where: { status: "open" } }, () => {});
+    const watches = await itx.contexts.watches({ verify: true, plans: true });
+    expect(watches).toMatchObject({ active: true, sockets: 1, faults: [] });
+    expect(watches.windows.map((window) => window.query).toSorted()).toEqual([
+      '{"awake":true}',
+      '{"p":[["status","open"]],"o":"active","l":50}',
+    ]);
+    // WORKERD'S OWN SQLITE reads each statement by one index, in its order: no sort in a
+    // temporary b-tree, and no scan of an index of facts. With no fact the rows themselves are
+    // read in the order's own index, which SQLite calls a scan: it stops at the limit.
+    for (const [statement, plan] of Object.entries(watches.plans!)) {
+      expect(plan.join(" | "), statement).not.toMatch(/TEMP B-TREE|SCAN f/);
+      if (!statement.includes("no fact") && statement !== "rows by key")
+        expect(plan.join(" | "), statement).not.toMatch(/SCAN/);
+    }
+    expect(watches.plans!["active, one fact: the follower (the backfill)"]).toEqual([
+      "SEARCH f0 USING PRIMARY KEY (k=? AND v=? AND (active_at,path)<(?,?))",
+      "SEARCH r USING PRIMARY KEY (path=?)",
+    ]);
+  },
+);
+
+test(
+  "a query that the catalog cannot answer exactly rejects the call, and the end of a session ends its watches",
+  { timeout: 60_000 },
+  async () => {
+    await using runtime = await mind();
+    const itx = await session(runtime, "/");
+    await expect(itx.contexts.watch({ orderBy: "title" } as never, () => {})).rejects.toThrow(
+      /orderBy/,
+    );
+    await expect(itx.contexts.watch({ limit: 5_000 }, () => {})).rejects.toThrow(/limit/);
+    // a watch is the catalog's alone: another context has no `contexts`
+    await expect(itx.cd("/tasks/one").contexts.watch({}, () => {})).rejects.toThrow();
+    await itx.contexts.watch({ limit: 5 }, () => {});
+    expect(await itx.contexts.watches()).toMatchObject({ sockets: 1 });
+    itx[Symbol.dispose]();
+    using other = await session(runtime, "/");
+    await until(async () => (await other.contexts.watches()).sockets === 0);
+    expect(await other.contexts.watches()).toMatchObject({ windows: [] });
+  },
+);
+
+type Session = Disposable & {
+  cd(path: string): Session;
+  append(event: { type: string; payload: unknown }): Promise<unknown>;
+  contexts: {
+    list(options?: { under?: string }): Promise<ContextListing[]>;
+    watch<Row = CatalogRow>(
+      query: CatalogQuery,
+      onFrame: (frame: CatalogFrame<Row>) => void,
+      options?: { cursor?: CatalogCursor },
+    ): Promise<Disposable>;
+    watches(options?: { verify?: boolean; plans?: boolean }): Promise<CatalogWatches>;
+  };
+};
+
+async function session(runtime: Miniflare, path: string): Promise<Session> {
+  const origin = (await runtime.ready).href.replace(/^http/, "ws").replace(/\/$/, "");
+  return newWebSocketRpcSession<Session>(`${origin}${path}`) as unknown as Session;
+}
+
+/** A context says what it is, on its own log: the one way a row of the catalog comes to be. */
+async function described(itx: Session, path: string, metadata: Record<string, unknown>) {
+  await itx.cd(path).append({
+    type: "events.iterate.com/itx/described",
+    payload: { description: `What ${path} is for`, metadata },
+  });
+}
+
+/** Until the catalog has each context's own word of its status: a summary travels the context's
+ *  awake socket first. A context is listed as awake before that, with no row. */
+async function listed(itx: Session, statusByPath: Record<string, string>) {
+  await until(async () => {
+    const rows = new Map((await itx.contexts.list()).map((row) => [row.path, row.metadata]));
+    return Object.entries(statusByPath).every(
+      ([path, status]) => rows.get(path)?.status === status,
+    );
+  });
+}
+
+async function until(done: () => boolean | Promise<boolean>): Promise<void> {
+  for (let attempt = 0; attempt < 200; attempt++) {
+    if (await done()) return;
+    await new Promise((resolve) => setTimeout(resolve, 50));
+  }
+  throw new Error("it did not come within 10 s");
+}
+
+/** A watcher as a page is one: it keeps the rows of one query, frame by frame. */
+function watcher() {
+  const rows = new Map<string, CatalogRow>();
+  const state = {
+    frames: [] as CatalogFrame[],
+    /** A change frame whose `from` is not the revision of the frame before. */
+    gaps: [] as CatalogFrame[],
+    rev: -1,
+    take: (frame: CatalogFrame) => {
+      state.frames.push(frame);
+      if (frame.type === "change") {
+        if (frame.from !== state.rev) state.gaps.push(frame);
+        for (const path of frame.del) rows.delete(path);
+      } else {
+        const keep = new Set(frame.type === "reset" ? [] : frame.ids);
+        for (const path of [...rows.keys()]) if (!keep.has(path)) rows.delete(path);
+      }
+      for (const row of frame.rows) rows.set(row.path, row);
+      state.rev = frame.rev;
+    },
+    /** The rows, the newest activity first. */
+    rows: () => [...rows.values()].toSorted((a, b) => b.activeMs - a.activeMs),
+    until: (done: (rows: CatalogRow[]) => boolean) => until(() => done(state.rows())),
+  };
+  return state;
+}
+
+async function mind() {
+  const fixture = await build({
+    entryPoints: [fileURLToPath(new URL("./fixtures/catalog-watch.ts", import.meta.url).href)],
+    bundle: true,
+    write: false,
+    format: "esm",
+    platform: "neutral",
+    mainFields: ["module", "main"],
+    conditions: ["workerd"],
+    target: "es2022",
+    external: ["cloudflare:*", "node:*"],
+  });
+  const script = {
+    compatibilityDate: COMPATIBILITY_DATE,
+    compatibilityFlags: ["nodejs_compat", "allow_irrevocable_stub_storage"],
+    manifest: {
+      mainModule: "worker.js",
+      modules: { "worker.js": { type: "esm" as const, contents: fixture.outputFiles[0]!.text } },
+    },
+  };
+  const runtime = new Miniflare({
+    workers: [
+      {
+        config: {
+          ...script,
+          name: "boundary",
+          env: { MIND: { type: "worker", worker: "mind", exportName: "Mind" } },
+        },
+      },
+      {
+        config: {
+          ...script,
+          name: "mind",
+          env: {
+            CONTEXTS: {
+              type: "durable-object",
+              worker: "mind",
+              exportName: "IterateContextDurableObject",
+            },
+            CF_VERSION_METADATA: { type: "version-metadata" },
+          },
+          exports: {
+            IterateContextDurableObject: { type: "durable-object", storage: "sqlite" },
+            ItxEntrypoint: { type: "worker" },
+          },
+        },
+      },
+    ],
+  });
+  await runtime.ready;
+  return Object.assign(runtime, { [Symbol.asyncDispose]: () => runtime.dispose() });
+}
A core/mind-worker/src/context/fixtures/catalog-watch.ts
@@ -0,0 +1,45 @@
+// catalog-watch.ts — a watch of the mind's catalog (`itx.contexts.watch`) from a client's callback
+// to the object that owns the rows and back, run in workerd by ../catalog-watch.test.ts. Two
+// Workers of one bundle, as a stack has them: "mind" runs the kernel (core-itx), and "boundary"
+// ends a client's capnweb session and holds the mind's part of it through core/boundary-worker's
+// own `SessionMind`. A client reaches the mind in the two ways a session ends:
+//   /page   the session ends in the mind's own Worker, as a page's `/itx` does (`serveSession`)
+//   /       the session ends in the boundary, as the API's does (`sessionContext` over Workers RPC)
+import { WorkerEntrypoint } from "cloudflare:workers";
+import { newWebSocketRpcSession } from "capnweb";
+import { defineItxHost, serveSession, sessionContext } from "core-itx";
+import { SessionMind, type MindApiStub } from "../../../../boundary-worker/src/session-mind.ts";
+
+export { IterateContextDurableObject, ItxEntrypoint } from "core-itx";
+
+type Env = { MIND: Service<Mind> };
+
+defineItxHost({ firstPartyFacets: {} });
+
+const member = { principal: { actor: "usr_aaaaabbbbbccccc", email: "member@mind.example" } };
+
+export class Mind extends WorkerEntrypoint<Env> {
+  override fetch() {
+    return serveSession(this.ctx, { caller: member, endsAt: null, endReason: "" });
+  }
+
+  api() {
+    return sessionContext((promise) => this.ctx.waitUntil(promise), member);
+  }
+}
+
+export default {
+  async fetch(request: Request, env: Env) {
+    if (new URL(request.url).pathname === "/page") return env.MIND.fetch(request);
+    // the boundary: the client's session, whose `mind` is the mind's own part of it
+    // (core/boundary-worker/src/control-plane-api.ts `#watchedMind`)
+    const stub = (await env.MIND.api()) as unknown as MindApiStub;
+    const pair = new WebSocketPair();
+    pair[1].accept();
+    newWebSocketRpcSession(
+      pair[1] as unknown as WebSocket,
+      new SessionMind(stub, (dial) => env.MIND.fetch(dial), false),
+    );
+    return new Response(null, { status: 101, webSocket: pair[0] });
+  },
+} satisfies ExportedHandler<Env>;