@shivaedev/contract 0.41.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +28 -178
  3. package/dist/AutomaticQueryOptions.d.ts +0 -5
  4. package/dist/AutomaticQueryOptions.d.ts.map +1 -1
  5. package/dist/HostVersion.d.ts +1 -19
  6. package/dist/HostVersion.d.ts.map +1 -1
  7. package/dist/adapters/activityState.d.ts.map +1 -1
  8. package/dist/adapters/activityState.js +0 -1
  9. package/dist/adapters/activityState.js.map +1 -1
  10. package/dist/adapters/liveHintStream.d.ts +0 -1
  11. package/dist/adapters/liveHintStream.d.ts.map +1 -1
  12. package/dist/adapters/openLiveHints.d.ts +0 -1
  13. package/dist/adapters/openLiveHints.d.ts.map +1 -1
  14. package/dist/adapters/retainedQueries.d.ts +7 -0
  15. package/dist/adapters/retainedQueries.d.ts.map +1 -0
  16. package/dist/adapters/retainedQueries.js +45 -0
  17. package/dist/adapters/retainedQueries.js.map +1 -0
  18. package/dist/adapters/standaloneLiveServer.d.ts +1 -7
  19. package/dist/adapters/standaloneLiveServer.d.ts.map +1 -1
  20. package/dist/adapters/standaloneLiveServer.js.map +1 -1
  21. package/dist/automaticLive.d.ts +2 -4
  22. package/dist/automaticLive.d.ts.map +1 -1
  23. package/dist/automaticLive.js +5 -14
  24. package/dist/automaticLive.js.map +1 -1
  25. package/dist/automaticQuery.d.ts +1 -1
  26. package/dist/automaticQuery.d.ts.map +1 -1
  27. package/dist/automaticQuery.js +20 -26
  28. package/dist/automaticQuery.js.map +1 -1
  29. package/dist/bind.d.ts +1 -2
  30. package/dist/bind.d.ts.map +1 -1
  31. package/dist/bind.js +8 -12
  32. package/dist/bind.js.map +1 -1
  33. package/dist/bindOperations.d.ts +6 -0
  34. package/dist/bindOperations.d.ts.map +1 -0
  35. package/dist/bindOperations.js +10 -0
  36. package/dist/bindOperations.js.map +1 -0
  37. package/dist/changesSuccess.d.ts +2 -3
  38. package/dist/changesSuccess.d.ts.map +1 -1
  39. package/dist/changesSuccess.js +1 -3
  40. package/dist/changesSuccess.js.map +1 -1
  41. package/dist/clientActivities.d.ts +0 -2
  42. package/dist/clientActivities.d.ts.map +1 -1
  43. package/dist/clientActivities.js +0 -4
  44. package/dist/clientActivities.js.map +1 -1
  45. package/dist/clientActivity.d.ts +0 -1
  46. package/dist/clientActivity.d.ts.map +1 -1
  47. package/dist/clientActivity.js +1 -1
  48. package/dist/clientActivity.js.map +1 -1
  49. package/dist/clientOperations.d.ts +1 -1
  50. package/dist/clientOperations.d.ts.map +1 -1
  51. package/dist/clientOperations.js +53 -52
  52. package/dist/clientOperations.js.map +1 -1
  53. package/dist/compareQueries.d.ts +2 -19
  54. package/dist/compareQueries.d.ts.map +1 -1
  55. package/dist/compareQueries.js +6 -33
  56. package/dist/compareQueries.js.map +1 -1
  57. package/dist/live-server/register.d.ts +0 -1
  58. package/dist/live-server/register.d.ts.map +1 -1
  59. package/dist/live-server/service.d.ts +0 -2
  60. package/dist/live-server/service.d.ts.map +1 -1
  61. package/dist/live-server/stream.d.ts +0 -1
  62. package/dist/live-server/stream.d.ts.map +1 -1
  63. package/dist/live-server/subscribe.d.ts +2 -2
  64. package/dist/live-server/subscribe.d.ts.map +1 -1
  65. package/dist/live-server/subscribe.js.map +1 -1
  66. package/dist/live.d.ts +5 -12
  67. package/dist/live.d.ts.map +1 -1
  68. package/dist/live.js +15 -85
  69. package/dist/live.js.map +1 -1
  70. package/dist/liveAttempt.d.ts +3 -6
  71. package/dist/liveAttempt.d.ts.map +1 -1
  72. package/dist/liveAttempt.js +11 -30
  73. package/dist/liveAttempt.js.map +1 -1
  74. package/dist/liveHintQueue.d.ts +0 -1
  75. package/dist/liveHintQueue.d.ts.map +1 -1
  76. package/dist/liveHintQueue.js +9 -12
  77. package/dist/liveHintQueue.js.map +1 -1
  78. package/dist/makeLiveServer.d.ts +1 -5
  79. package/dist/makeLiveServer.d.ts.map +1 -1
  80. package/dist/operation.d.ts +2 -4
  81. package/dist/operation.d.ts.map +1 -1
  82. package/dist/operation.js +0 -1
  83. package/dist/operation.js.map +1 -1
  84. package/dist/operationDeclaration.d.ts +1 -2
  85. package/dist/operationDeclaration.d.ts.map +1 -1
  86. package/dist/operationDeclaration.js.map +1 -1
  87. package/dist/publicConfig.d.ts +6 -21
  88. package/dist/publicConfig.d.ts.map +1 -1
  89. package/dist/queryDelivery.d.ts +4 -5
  90. package/dist/queryDelivery.d.ts.map +1 -1
  91. package/dist/queryDelivery.js +4 -15
  92. package/dist/queryDelivery.js.map +1 -1
  93. package/dist/queryProgress.d.ts.map +1 -1
  94. package/dist/queryProgress.js +0 -3
  95. package/dist/queryProgress.js.map +1 -1
  96. package/dist/queryRetention.d.ts +8 -0
  97. package/dist/queryRetention.d.ts.map +1 -0
  98. package/dist/queryRetention.js +3 -0
  99. package/dist/queryRetention.js.map +1 -0
  100. package/dist/querySignals.d.ts +1 -0
  101. package/dist/querySignals.d.ts.map +1 -1
  102. package/dist/querySignals.js.map +1 -1
  103. package/dist/querySubscription.d.ts +1 -1
  104. package/dist/querySubscription.d.ts.map +1 -1
  105. package/dist/queryUpdate.d.ts +15 -4
  106. package/dist/queryUpdate.d.ts.map +1 -1
  107. package/dist/queryUpdate.js +7 -1
  108. package/dist/queryUpdate.js.map +1 -1
  109. package/dist/retainQuery.d.ts +4 -0
  110. package/dist/retainQuery.d.ts.map +1 -0
  111. package/dist/retainQuery.js +35 -0
  112. package/dist/retainQuery.js.map +1 -0
  113. package/package.json +8 -8
  114. package/src/AutomaticQueryOptions.ts +0 -5
  115. package/src/adapters/activityState.ts +0 -1
  116. package/src/adapters/retainedQueries.ts +47 -0
  117. package/src/adapters/standaloneLiveServer.ts +1 -5
  118. package/src/automaticLive.ts +4 -16
  119. package/src/automaticQuery.ts +28 -42
  120. package/src/bind.ts +16 -22
  121. package/src/bindOperations.ts +20 -0
  122. package/src/changesSuccess.ts +3 -5
  123. package/src/clientActivities.ts +1 -5
  124. package/src/clientActivity.ts +1 -2
  125. package/src/clientOperations.ts +77 -85
  126. package/src/compareQueries.ts +12 -38
  127. package/src/live-server/subscribe.ts +5 -9
  128. package/src/live.ts +19 -97
  129. package/src/liveAttempt.ts +17 -41
  130. package/src/liveHintQueue.ts +9 -12
  131. package/src/operation.ts +3 -17
  132. package/src/operationDeclaration.ts +0 -2
  133. package/src/queryDelivery.ts +6 -26
  134. package/src/queryProgress.ts +0 -3
  135. package/src/queryRetention.ts +9 -0
  136. package/src/querySignals.ts +1 -0
  137. package/src/querySubscription.ts +1 -1
  138. package/src/queryUpdate.ts +10 -4
  139. package/src/retainQuery.ts +36 -0
  140. package/dist/liveInvalidation.d.ts +0 -12
  141. package/dist/liveInvalidation.d.ts.map +0 -1
  142. package/dist/liveInvalidation.js +0 -14
  143. package/dist/liveInvalidation.js.map +0 -1
  144. package/dist/livePending.d.ts +0 -7
  145. package/dist/livePending.d.ts.map +0 -1
  146. package/dist/livePending.js +0 -27
  147. package/dist/livePending.js.map +0 -1
  148. package/dist/queryCoalesceWindow.d.ts +0 -4
  149. package/dist/queryCoalesceWindow.d.ts.map +0 -1
  150. package/dist/queryCoalesceWindow.js +0 -11
  151. package/dist/queryCoalesceWindow.js.map +0 -1
  152. package/dist/queryFailure.d.ts +0 -4
  153. package/dist/queryFailure.d.ts.map +0 -1
  154. package/dist/queryFailure.js +0 -12
  155. package/dist/queryFailure.js.map +0 -1
  156. package/dist/queryHints.d.ts +0 -9
  157. package/dist/queryHints.d.ts.map +0 -1
  158. package/dist/queryHints.js +0 -34
  159. package/dist/queryHints.js.map +0 -1
  160. package/dist/queryReactivity.d.ts +0 -5
  161. package/dist/queryReactivity.d.ts.map +0 -1
  162. package/dist/queryReactivity.js +0 -109
  163. package/dist/queryReactivity.js.map +0 -1
  164. package/src/liveInvalidation.ts +0 -21
  165. package/src/livePending.ts +0 -28
  166. package/src/queryCoalesceWindow.ts +0 -13
  167. package/src/queryFailure.ts +0 -13
  168. package/src/queryHints.ts +0 -39
  169. package/src/queryReactivity.ts +0 -127
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.43.0 - 2026-11-06
4
+
5
+ ### Changed
6
+
7
+ - Keep current query values during transient subscription recovery. Explicit refresh retains the value and reports pending until the fresh pushed result arrives; declared query failures and read denials remain visible.
8
+ - Coalesce each subscription's pending changes into one rerun, including server-side reconciliation after backlog overflow or PostgreSQL listener recovery. Different subscriptions run independently and in parallel. Changed encoded results are pushed; equal reads acknowledge completion with `Unchanged`.
9
+
10
+ ### Breaking
11
+
12
+ - Live queries always receive server-pushed results. Remove `live: "rerun-and-compare"` from query declarations; query handlers, result shapes and screens need no changes. Deploy matching client and server versions. Custom subscription hosts must supply an authorized query runner to `subscribe`. Raw consumers handle `Result`, `Unchanged` and `QueryReadDenied` instead of change hints. Remove obsolete query and live connection coalescing settings; coalescing now happens on the server.
13
+
14
+ ## 0.42.0 - 2026-11-06
15
+
16
+ ### Added
17
+
18
+ - Keep successful bound query results for five minutes after their last reader leaves, bounded to 100 idle queries per registry. Reopened queries show stale data immediately while revalidating. Configure `timeToLive` and `capacity` through the registry's `queryRetention` atom or React's `SessionBoundary.queryRetention` prop.
19
+
20
+ ### Breaking
21
+
22
+ - Replace bound queries' per-query `timeToLive` option with the registry's `queryRetention` policy. Move that setting to `SessionBoundary.queryRetention` or set the native `queryRetention` atom in the owning registry. Query execution now ends with the last reader; retained data revalidates on reopening.
23
+
3
24
  ## 0.41.0 - 2026-11-06
4
25
 
5
26
  ### Added
package/README.md CHANGED
@@ -33,7 +33,7 @@ A **contract** groups operations into a native `RpcGroup`. Its RPC tags are the
33
33
 
34
34
  A **collection key** names a dependency. Its item key identifies one item; its list key identifies a list in that collection. Keys do not hold data. Native query atoms hold results, and native Reactivity asks matching queries to run again.
35
35
 
36
- Optional live hints use those same keys. A hint asks for another read; it does not supply a replacement value, a journal entry or proof that a query is fresh.
36
+ Live subscriptions use those same keys to rerun each subscriber’s authorized query on the server and push its changed result.
37
37
 
38
38
  ### 1. Once per feature: schemas and operations
39
39
 
@@ -244,7 +244,7 @@ const note = api.get.query({ id: 1 });
244
244
  const rename = runtime.fn(api.rename.run);
245
245
  ```
246
246
 
247
- Browsers send the session cookie at upgrade. Mounting a query opens its subscription before running its first authorized read; unmounting cancels that subscription without restarting the socket or another query. Changed keys rerun only their readers, and equal results retain the bound atom's value. Connection failures use Effect RPC's reconnect backoff; subscriptions resume and mounted queries read again because there is no retained key history. `LiveConnection.status` reports `connecting`, `live` or `reconnecting`.
247
+ Browsers send the session cookie at upgrade. Mounting a query opens its subscription before running its first authorized read; unmounting cancels that subscription without restarting the socket or another query. Changed keys rerun only their readers, and equal results retain the bound atom's value. Connection failures use Effect RPC's reconnect backoff; subscriptions reopen and the server pushes current results because there is no retained key history. `LiveConnection.status` reports `connecting`, `live` or `reconnecting`.
248
248
 
249
249
  On visible `visibilitychange`, `online` and `pageshow` events, or an injected native resume, the default socket client probes an open connection with RPC Ping/Pong. Commands wait during that probe. A missing Pong after 2.5 seconds fails the socket reader and starts native reconnection without waiting for a browser close handshake. Bound commands issued during reconnection wait up to 10 seconds before sending; a timeout fails with a typed `RpcClientError` whose reason is `SocketOpenError` with kind `Timeout`. A held command immediately reports `waiting-for-connection` through `clientActivity(client)`, including without a mounted query. Only commands that have not been sent wait; in-flight commands fail on disconnect and are never replayed. Supplied native socket protocols inherit the command wait through Effect’s connection hooks without additional wiring.
250
250
 
@@ -319,7 +319,7 @@ const move = ({ id, household }) =>
319
319
 
320
320
  Here `audienceFor` reads household members and people who ate from the pot from the application's database, `movePot` performs the write, and `pots` declares a `viewerId` bucket. Read the audience after the write to include new readers, and retain the old audience when the write removes access. Each viewer's list reads its own bucket. Keep these reads and the write in the same transaction when they must describe one change.
321
321
 
322
- Use this helper in hosts from `@shivaedev/server`, or a native RPC host wired with `guardCommands` and `commandGuardLayer`. Keys are isolated per command, deduplicated with declared keys, and published through the existing `@shivaedev/changes` command publication boundary after success. A failed handler discards them. They do not enter the browser's pure `invalidates` callback; live subscriptions receive the server's refresh hints.
322
+ Use this helper in hosts from `@shivaedev/server`, or a native RPC host wired with `guardCommands` and `commandGuardLayer`. Keys are isolated per command, deduplicated with declared keys, and published through the existing `@shivaedev/changes` command publication boundary after success. A failed handler discards them. They do not enter the browser's pure `invalidates` callback; live subscriptions receive the server’s changed query results.
323
323
 
324
324
  ### Host build announcements
325
325
 
@@ -331,7 +331,7 @@ Use this helper in hosts from `@shivaedev/server`, or a native RPC host wired wi
331
331
 
332
332
  For screen stories, pass `activityScreenSignal(clientActivity(client))` to a test-story screen driver's `activity` option. By default, `settle()` waits for commands in flight and the first result of each mounted query, then flushes the renderer. Contract identifies commands from its own RPC annotations; kits need no query-name exceptions. The activity state's `commands` count includes commands held for a connection, and `initialQueries` counts mounted queries until their first success or failure. Unmounting releases that query's pending activity. `isClientSettled(state)` checks these two counts. An open live query that has delivered its first result, including one awaiting a later refresh, does not keep a screen story pending.
333
333
 
334
- `activityScreenSignal(activity)` projects the stream and its `current` Effect into `{ pending, hints, connectionStatus }`, with `hints` carrying the received live-hint count. The returned shape is structural and carries no test-story dependency. Stories that need a later live change start `nextLiveHint()` before the outside write, then settle with `activityScreenSignal(activity, isClientIdle)` to wait through its refresh. `isClientIdle(state)` retains the full finite-work check: `rpcCalls` for finite calls, `liveInvalidations` for queued live refreshes, and `refreshingAtoms` for mounted query atoms awaiting values must all be zero. Long-lived subscription streams themselves do not count as finite calls.
334
+ `activityScreenSignal(activity)` projects the stream and its `current` Effect into `{ pending, hints, connectionStatus }`, with `hints` carrying the received pushed-update count. The returned shape is structural and carries no test-story dependency. Stories that need a later live change start `nextLiveHint()` before the outside write, then settle the screen after its pushed result arrives. `isClientIdle(state)` retains the full finite-work check: `rpcCalls` for finite calls, `refreshingAtoms` for mounted query atoms awaiting values must all be zero. Long-lived subscription streams and server reruns themselves do not count as finite calls.
335
335
 
336
336
  ### Query completion
337
337
 
@@ -345,7 +345,7 @@ const before = registry.get(signals).completed;
345
345
  const completions = AtomRegistry.toStream(registry, signals);
346
346
  ```
347
347
 
348
- Mount the query to start it. Wait on `completions` for `completed > before` after an action that refreshes it; compare the counter rather than the result's identity. A server-pushed equal result completes without changing the visible value. Raw rerun-and-compare `$changes` consumers receive an `Unchanged` update with `queryIndex` for these completed reads. Clients and servers must understand the same stream schema.
348
+ Mount the query to start it. Wait on `completions` for `completed > before` after an action that refreshes it; compare the counter rather than the result's identity. A server-pushed equal result completes without changing the visible value. Raw `$changes` consumers receive an `Unchanged` update with `queryIndex` for these completed reads. Clients and servers must understand the same stream schema.
349
349
 
350
350
  ### Session-owned keys
351
351
 
@@ -417,168 +417,29 @@ const connection = composeBindings(
417
417
 
418
418
  `notesModule` and `tasksModule` are application modules whose `api` values come from `bind` or `makeClient`. Return `connection` from React's `SessionBoundary` connection callback to mount both bindings while keeping the modules nested.
419
419
 
420
- ### 4. Live invalidation and resume
420
+ ### 4. Server-pushed live queries
421
421
 
422
- The automatic live connection exposed at `api[LiveConnection]` includes a writable `paused` atom. Set it in the binding’s registry to pause refreshes; clearing it reconciles the mounted queries. Bindings on the same client runtime share this pause state.
422
+ Database hosts from `@shivaedev/server` serve the reserved `<contract>.$changes` stream automatically. Mounted query atoms and route loaders receive their first authorized `Result` on that subscription, using the client's shared WebSocket. Registration precedes the first read so a concurrent commit cannot fall into a registration gap. Subscribing over HTTP fails with `WebSocketRequired`.
423
423
 
424
- Opening a live query checks its policies, registers its read keys, then runs the authorized query and sends its first `Result` on the subscription. The screen and route loaders receive data in one RPC request; they do not send an ordinary query after the first signal. Registration precedes the read because PostgreSQL notifications cannot be replayed. Later changes send hints followed by ordinary query reads, unless the query declares `live: "rerun-and-compare"` to push changed results and acknowledge equal values.
424
+ After a matching committed change, the process holding the socket reloads that subscriber's session, checks its read policy, and reruns the same handler as an ordinary read. It encodes the result with the query's success schema and compares its hash. A changed value produces `Result`; an equal value produces only `Unchanged`, acknowledging completion without replacing the visible value. Queries return their declared shape, with no transport envelope required in application data. The client sends no follow-up read.
425
425
 
426
- Database hosts from `@shivaedev/server` serve the contract's reserved `<contract>.$changes` stream automatically. With the native WebSocket protocol, `bind` and a React `SessionBoundary` connect query atoms without an application subscribe operation or `live()` call. The boundary mounts the bindings declared with `composeBindings`, or finds bound APIs returned directly by `connect` or nested in properties such as `client.api.notes`. See [automatic changes](https://github.com/ShivaeDev/platform/blob/main/docs/framework/changes.md) for defaults.
426
+ Each subscription stores one hash per query in memory in the process holding its socket. Identical queries from different subscribers rerun independently under their own session and policy. A denied recheck sends `QueryReadDenied` before query SQL runs and clears that subscription's stored hashes. A later authorized change can therefore push the value again, even if it equals the value sent before denial. Render the denial before retained data.
427
427
 
428
- Subscribing to the hosted `$changes` stream over HTTP fails with `WebSocketRequired` from `@shivaedev/contract/WebSocketRequired.ts`; its message names the stream and says it needs the WebSocket protocol.
428
+ The server coalesces changes per subscription: one rerun can be in flight and one can be pending. Further hints merge into the pending rerun. When the current rerun finishes, the server runs once more if dirty. Different subscriptions progress independently and in parallel; there is no global rerun limit and no client coalescing timer.
429
429
 
430
- A native shell supplies its lifecycle events through the optional `resume` source on `makeClient` or `bind`:
430
+ `Resync` is an internal server reconciliation signal. When more than 256 hints accumulate behind a stalled subscription, pending keys collapse to one `Resync`; further hints are absorbed until it is consumed. PostgreSQL listener recovery also resynchronizes affected subscriptions. In either case, the server reruns the subscriber's queries and pushes changed results. `Resync` never asks the client to issue reads.
431
431
 
432
- ```ts
433
- import { makeClient } from "@shivaedev/contract/bind.ts";
434
- import type { ResumeSource } from "@shivaedev/contract/resume.ts";
435
- import { onAppResume, onNetworkReturn } from "./native-lifecycle.ts";
436
-
437
- const resume: ResumeSource = (notify) => {
438
- const stopApp = onAppResume(notify);
439
- const stopNetwork = onNetworkReturn(notify);
440
- return () => {
441
- stopApp();
442
- stopNetwork();
443
- };
444
- };
445
- const { api, runtime } = makeClient(Notes, { url: "https://app.example/rpc", resume });
446
- ```
447
-
448
- The application owns `onAppResume` and `onNetworkReturn`; each subscribes a callback and returns an unsubscribe function. The source joins the visible browser visibility and online defaults. Each notification reopens the live subscription and reconciles all reads tracked by the connection. The owning registry releases the source on disposal. Omitting `resume` keeps the browser defaults. Pass the same binding from React's `SessionBoundary.connect` to use it with automatic session subscriptions. An embedded browser can pass `resumeWindow` to `makeClient` or `bind` to observe that window’s visibility and online events.
449
-
450
- For a direct subscription, configure the server and `NotesClient` with `RpcSerialization.layerNdjson` and use the client already typed from `Notes`:
451
-
452
- ```ts
453
- import { Effect, Stream } from "effect";
454
- import { NotesClient } from "./client.ts";
455
-
456
- const changes = Stream.unwrap(
457
- NotesClient.use((client) => Effect.succeed(client("notes.$changes", { queries: [{ query: "get", payload: { id: 1 } }] }))),
458
- );
459
- ```
460
-
461
- The contract includes the reserved stream's payload, hints, typed `Result` values and middleware failures in its native RPC type. The subscription uses the contract's middleware and needs no separate RPC group or cast. The caller owns stream consumption and interruption. References name declared queries and reuse their payload schemas; payloadless queries use `{ query: "list", payload: undefined }`. Custom subscription handlers call `querySubscription(rpc, references, viewer)` with the native changes RPC definition and pass its authorized result and authorized query runner to `subscribe(subscription, read)`. The runner uses the same query handlers and policies as ordinary reads. Omitting the runner keeps an explicit hint-only stream for custom transports. Hosted applications use `resolveChanges` from identity to supply that subscription. Session-scoped bindings track mounted queries per registry and drop their references on unmount or disposal. Ordinary bindings track query references when atoms are created.
462
-
463
- Custom subscription handlers use `changesHandlerLayer` to derive the reserved handler Layer from the contract:
464
-
465
- ```ts
466
- import { Effect, Stream } from "effect";
467
- import { changesHandlerLayer } from "@shivaedev/contract/changesHandlerLayer.ts";
468
- import { subscribe } from "@shivaedev/contract/live-server/subscribe.ts";
469
- import { querySubscription } from "@shivaedev/contract/querySubscription.ts";
470
- import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
471
- import { Notes } from "./notes.ts";
472
-
473
- const changes = changesHandlerLayer(
474
- Notes,
475
- (rpc) =>
476
- ({ queries }) =>
477
- Stream.unwrap(
478
- Effect.gen(function* () {
479
- const viewer = yield* CurrentViewer;
480
- const subscription = yield* querySubscription(rpc, queries, viewer);
481
- return yield* subscribe(subscription);
482
- }),
483
- ),
484
- );
485
- ```
486
-
487
- Merge this Layer with `Notes.application.toLayer(...)`. It retains the query read-policy and custom stream services as requirements, excluding services supplied by RPC middleware. The builder can also return an Effect to acquire services or fail during Layer construction. Declared stream failures remain in the contract's error channel. Pushed results are validated against the contract's decoded success types; custom handlers do not decode `changesSuccess` themselves.
488
-
489
- For a custom transport or explicit pause and status controls, use the native live APIs.
490
-
491
- Declare subscriptions with `stream` in the same contract. Its `success` schema describes each element, and its `rejections` become the native stream error schema. `bind` exposes `run(payload)` as a native `Stream`, preserving declared rejections, middleware errors and RPC client errors. Completion and client interruption release the server subscription. The compiler rejects a unary client for a streaming operation.
492
-
493
- Each item query reads its own item key, and each list query reads its list key. Commands invalidate the keys they change; an item invalidation also refreshes its collection list. Reuse the feature's `Get`, `List`, `Rename` and `Create` declarations:
494
-
495
- ```ts
496
- import { contract } from "@shivaedev/contract/contract.ts";
497
- import { LiveHint } from "@shivaedev/contract/live.ts";
498
- import { stream } from "@shivaedev/contract/operation.ts";
499
- import { Create, Get, List, notes, Rename } from "./notes.ts";
500
-
501
- export const Subscribe = stream("subscribe", { reads: () => [notes.list], success: LiveHint });
502
- export const LiveNotes = contract("notes", { queries: [Get, List], commands: [Rename, Create], streams: [Subscribe] });
503
- ```
504
-
505
- Save the shared module as `live-notes.ts`. Keep full reconciliation in the session's explicit `resyncKeys`: enumerate the item keys the session reads and its list keys. A list key alone does not cover separately registered item queries. Having every query read a broad shared key makes every invalidation of that key refetch them all.
506
-
507
- Use `LiveNotes` as the server group and implement `notes.subscribe` with a native Stream. For streaming HTTP, use `RpcSerialization.layerNdjson` on both sides. This client mounts live coordination alongside its queries:
508
-
509
- ```ts
510
- import { Layer } from "effect";
511
- import { FetchHttpClient } from "effect/http";
512
- import * as AtomRegistry from "effect/reactivity/AtomRegistry";
513
- import * as AtomRpc from "effect/reactivity/AtomRpc";
514
- import { RpcClient, RpcSerialization } from "effect/rpc";
515
- import { bind } from "@shivaedev/contract/bind.ts";
516
- import { live } from "@shivaedev/contract/live.ts";
517
- import { resumeSignal } from "@shivaedev/contract/resume.ts";
518
- import { LiveNotes } from "./live-notes.ts";
519
- import { notes } from "./notes.ts";
520
-
521
- class Client extends AtomRpc.Service<Client>()("app/LiveNotes", {
522
- group: LiveNotes,
523
- protocol: RpcClient.layerProtocolHttp({ url: "http://127.0.0.1:3000/rpc" }).pipe(
524
- Layer.provide([FetchHttpClient.layer, RpcSerialization.layerNdjson]),
525
- ),
526
- }) {}
527
- const api = bind(LiveNotes, Client);
528
- const registry = AtomRegistry.make();
529
- const updates = live(Client.runtime, {
530
- stream: api.subscribe.run(undefined),
531
- resyncKeys: [notes.item(1), notes.item(2), notes.list],
532
- resume: resumeSignal({ window }),
533
- retryDelay: "100 millis",
534
- });
535
- const releaseQuery = registry.mount(api.get.query({ id: 1 }));
536
- const releaseConnection = registry.mount(updates.connection);
537
- ```
538
-
539
- `LiveNotes` supplies both the declaration for binding and the native RPC group for transport. Stream read keys describe its dependencies; `run` does not mount query atoms or trigger automatic invalidation. Here the caller explicitly reconciles two items and their list. `bind` also accepts a larger native client group that preserves the contract RPC types. The [live updates guide](https://github.com/ShivaeDev/platform/blob/main/docs/framework/live-updates.md) shows server and client composition, and the [HTTP fixture](https://github.com/ShivaeDev/platform/tree/main/packages/contract/src/test-support/live) supplies a complete working server.
540
-
541
- | Observation | Invalidation |
542
- | ----------------------------------------- | ------------------------------------------------------ |
543
- | `Changed` with keys after the first hint | Affected items and their lists. |
544
- | `Resync` | The exact `resyncKeys` read scope. |
545
- | First hint on a new or reconnected stream | The full explicit scope, even if the hint is targeted. |
546
-
547
- Changed hints share a fixed 20 ms window by default. Their keys merge, and each affected bound query refetches once per window. A bound query already fetching keeps its request and refetches once more after it settles if further hints arrive. Set `coalesceWindow` in `live()` to a native Duration, or set `SessionBoundary`'s `liveCoalesceWindow` for automatic session connections. Zero restores immediate per-hint invalidation, including interruption of in-flight reads. Full reconciliation on first hint, reconnect, resume and unpause stays immediate. Registry teardown and resyncs cancel a pending window. Windows sleep on the atom runtime's Clock, so `TestClock` drives them.
548
-
549
- `queryCoalesceWindow(query)` from `@shivaedev/contract/queryCoalesceWindow.ts` returns a writable native atom for that bound query's live changed-hint window. Set it through the query's registry to a Duration, or `undefined` to use the live connection's default. Changing it does not refetch or reconnect; the next window uses the new value. React consumers can set it with `useQuery(query, { coalesceWindow: "2 seconds" })`.
432
+ The `paused` atom at `api[LiveConnection]` suppresses applying pushed values to the screen while continuing to observe the stream. Its `status.pending` count saturates at 256. Unpausing reopens the subscription for a current authorized result and resets that count. Bindings on one client runtime share pause state.
550
433
 
551
- `LiveHint` and `Key` are schemas. Decoding rejects unknown hint tags and item keys with an invalid ID type.
434
+ An explicit query refresh reopens its subscription, retaining its current value with `waiting: true` until the fresh result arrives. Retryable connection failures retain the current query value during reconnection. Declared query failures and read denials still reach the query's error channel.
552
435
 
553
- ```ts
554
- registry.set(updates.paused, true);
555
- registry.set(updates.paused, false);
556
- const status = registry.get(updates.status);
557
- ```
558
-
559
- While paused, live coordination keeps observing hints and suppresses automatic refresh. `status.pending` saturates at 256 observations. Unpausing reconciles the explicit scope and resets the count. A resume signal also requests reconciliation: an injected native source and visible browser `online` and `visibilitychange` events request it, while hidden events do not.
560
-
561
- `status` exposes `connection`, `failure`, `needsResync` and `pending`. Expected stream rejections settle with `connection: "failed"` and their typed cause in `failure`. Typed rejections do not retry on a timer. An initial `QueryReadDenied` refusal stays settled through matching change invalidations and resume events; changing the query input or viewer identity starts a new subscription. A denial delivered on an established subscription also sets `connection: "failed"`, but the stream remains open and a later authorized hint restores the query and live status. Other expected rejections can reopen on matching invalidations. Low-level `live()` listens to `retryKeys`, defaulting to its `resyncKeys`, for matching invalidations. Transport errors and server defects reconnect with jittered exponential backoff, starting at `retryDelay` (one second by default) and capped at a nominal 30 seconds. A resume signal interrupts that delay, retries immediately and resets the backoff schedule. Healthy hint subscriptions reconcile without reopening; pushed subscriptions reopen to obtain their current value. A reconnection reconciles changes missed while disconnected, and successful delivery clears the stream failure. Native query atoms keep previous successful data during a read failure and reject stale responses after invalidation. Query failures remain in their own `AsyncResult`; stream failures appear in `status.failure`.
562
-
563
- A `$changes` request is authorized as a whole: one denied member rejects or ends the entire batch, including its other queries. Split queries with independent permissions into separate `$changes` requests. Automatic bound query atoms already subscribe separately.
564
-
565
- The resume signal is a scoped native atom. Disposing the registry removes its browser listeners, cleans up an injected source, including one used only through `live`, and releases the stream subscription:
566
-
567
- ```ts
568
- releaseQuery();
569
- releaseConnection();
570
- registry.dispose();
571
- ```
572
-
573
- Call the release functions and dispose the registry when the application's root no longer owns them.
574
-
575
- ### Server hint streams
436
+ Visible browser `online` and `visibilitychange` events reopen active subscriptions for current values. Supply an optional native `resume` source on `makeClient` or `bind` for application or network lifecycle events; it registers a callback and returns its cleanup function. `resumeWindow` selects an embedded browser window. Disposing the registry releases the source, query subscriptions and socket resources.
576
437
 
577
- Import `LiveServer` from `@shivaedev/contract/live-server/service.ts`. Import `liveServerLayer` from `@shivaedev/contract/live-server/layer.ts` and provide it with the server's `Reactivity` Layer; PostgreSQL `appHost` apps already provide it. Yield `LiveServer` to obtain the shared service. Its methods return Effects: unwrap `hints.stream(keys)` with `Stream.unwrap`, and call `hints.resync()` to reconcile its active streams. For authorized query subscriptions, import `subscribe` from `@shivaedev/contract/live-server/subscribe.ts` and unwrap `subscribe(subscription, read?)`. This operation yields `LiveServer`; its Layer binds Reactivity, while subscription policy failures and query-runner requirements remain on the returned Stream. Each Layer build owns its resync identity and stream counter. The package Layer also provides its dispatcher service. `register(keys)` exposes a scoped stream registration with `replaceKeys` for updating its read scope; consumption and interruption own that registration.
438
+ `status` exposes `connection`, `failure`, `needsResync` and `pending`. A typed stream rejection settles as `failed`; transport failures and defects retry with the existing jittered exponential backoff. A denied subscription can reopen on an identity change or matching local invalidation; resume events leave a settled rejection alone. An established subscription remains open after a policy denial so a later authorized change can restore its value. A `$changes` request is authorized as a whole; automatic query atoms subscribe separately so independent permissions remain independent.
578
439
 
579
- Import `makeLiveServer` from `@shivaedev/contract/makeLiveServer.ts` and create it once with the server's `Reactivity` service. After application authorization, return `hints.stream([orders.item(id)])` from the native streaming RPC handler. Each subscription starts with `Resync`; invalidating its read keys produces `Changed` with those declared keys. `hints.resync` sends `Resync` to every live stream owned by that helper, including streams for otherwise unrelated keys. Independent helpers keep their resync scopes separate even when they share Reactivity. The native stream owns registration and interruption. Keep this server helper separate from the browser's `live` coordinator.
440
+ Custom native hosts use `changesHandlerLayer`, `querySubscription(rpc, references, viewer)` and `subscribe(subscription, read)`. The authorized query runner is required and must use the same handler and read policy as an ordinary read; session-backed hosts must provide a fresh session context on each rerun. Platform's host supplies this composition. The caller owns consumption and interruption of a raw `$changes` stream, whose values are `Result`, `Unchanged` and `QueryReadDenied`.
580
441
 
581
- Each stream queues at most 256 hints. Overflow discards the pending hints and retains one `Resync`; further hints are absorbed until that reconciliation hint is pulled. Hint consumers read current query results; rerun-and-compare subscriptions rerun on the server and push changed current results. The [PostgreSQL and React stories](https://github.com/ShivaeDev/platform/blob/main/packages/react/src/comparedPostgres.dom.spec.ts) prove compared delivery without client reads, suppression of equal and SQL-filtered results, and reconciliation into a rendered query after a real loopback WebSocket withholds RPC acknowledgements across 257 repository commits. The [in-memory slow-consumer stories](src/slowConsumer.spec.ts) cover hint reconciliation. The queue bound counts hints, not commits or bytes: each hint's keys depend on the subscription. Transport buffers remain the transport's responsibility; a client lagging by 256 commits does not necessarily overflow this queue. Browser suspension, proxy buffering and deployment delivery are not proven here.
442
+ Server adapters import `LiveServer` from `@shivaedev/contract/live-server/service.ts` and `liveServerLayer` from `@shivaedev/contract/live-server/layer.ts`. The Layer captures the server's Reactivity service and dispatcher. `register(keys)` provides a scoped registration with `replaceKeys`; `resync()` reconciles its active subscriptions. `makeLiveServer` supplies a standalone server using the same subscription engine. Server hints contain keys, never authoritative row data.
582
443
 
583
444
  ### Query policies, record keys and buckets
584
445
 
@@ -622,7 +483,7 @@ const AllNotes = query("allNotes", {
622
483
  });
623
484
  ```
624
485
 
625
- The application supplies the permission checker through `permissionReadPolicy(permission, check)`; `check` receives that permission and the current viewer, and must check the viewer's grant using server services. Its failures and service requirements flow through the query like any other read policy. Supply `SessionUser` with the application's identity middleware. The policy guards both calls and subscriptions, and runs again before changed hints are delivered. `readsCollections` requires this policy at declaration: a `signedIn` or ordinary boolean policy fails TypeScript checking, and building an untyped contract with that declaration throws an error explaining the required permission policy. The server also refuses collection queries changed to an ordinary policy after construction as `QueryReadDenied`. Tenant-facing queries use `notes.bucket.userId(viewerId)` instead.
486
+ The application supplies the permission checker through `permissionReadPolicy(permission, check)`; `check` receives that permission and the current viewer, and must check the viewer's grant using server services. Its failures and service requirements flow through the query like any other read policy. Supply `SessionUser` with the application's identity middleware. The policy guards both calls and subscriptions, and runs again before queries rerun. `readsCollections` requires this policy at declaration: a `signedIn` or ordinary boolean policy fails TypeScript checking, and building an untyped contract with that declaration throws an error explaining the required permission policy. The server also refuses collection queries changed to an ordinary policy after construction as `QueryReadDenied`. Tenant-facing queries use `notes.bucket.userId(viewerId)` instead.
626
487
 
627
488
  Collection reads reuse the bare repository table key, the same key as `notes.list`, even when the contract uses `keyScope: "session"`; record and bucket reads also use plain server keys. They add no wildcard matching or write-side work. Every committed repository insert, update, delete, upsert and bulk write already publishes that key. Generated-id inserts also publish the bare collection key alongside their generated record key, so `publishes` stories that check exact published keys must allow the bare key today. For a table named `notes`, that is `"notes"` alongside `"notes:<id>"` and any affected bucket keys. Mounting a collection subscriber adds **zero PostgreSQL NOTIFY messages per write**: it consumes the existing payloads. It adds a normal query subscription and an authorized reread when the collection changes.
628
489
 
@@ -650,7 +511,7 @@ const Timeline = query("timeline", {
650
511
  });
651
512
  ```
652
513
 
653
- Provide `TimelineData` on the server to load the workspace's lists and return their keys. Use an application policy that checks workspace access; derived keys are refresh dependencies and grant no read access. Each write must publish the same keys. Keys are resolved once when the subscription opens. If new lists can join the workspace while it remains open, include a workspace bucket that every record write in that workspace also publishes, or reopen the subscription when membership changes. The browser never runs `serverReads`; changed hints identify the affected query for its normal authorized reread.
514
+ Provide `TimelineData` on the server to load the workspace's lists and return their keys. Use an application policy that checks workspace access; derived keys are refresh dependencies and grant no read access. Each write must publish the same keys. Keys are resolved once when the subscription opens. If new lists can join the workspace while it remains open, include a workspace bucket that every record write in that workspace also publishes, or reopen the subscription when membership changes. The browser never runs `serverReads`; matching changes rerun the affected query on the server.
654
515
 
655
516
  Return `false` when denial may be disclosed; the caller receives `QueryReadDenied`. For a private item whose existence the viewer must not learn, fail with a declared `NotFound` for both an absent item and an item owned by someone else:
656
517
 
@@ -683,13 +544,13 @@ The server provides `NoteOwner`; the shared declaration holds only its browser-s
683
544
 
684
545
  A record key, `notes.item(id)`, names one record. A bucket, `notes.bucket.userId(id)`, names every row with that field value. Declare bucket fields on the collection model with their schemas. A list may add title, state or other filters to its input and handler, but those filters never narrow its bucket. It reruns whenever any row in that bucket changes, including a row excluded by the filter. Writers explicitly announce the record and affected buckets with the same constructors from `@shivaedev/changes/keys.ts`.
685
546
 
686
- The same query policy guards running the query and subscribing to it. A subscription is meant to carry one query. It names query references, never arbitrary record or bucket keys. If a subscription mixes queries the viewer may and may not read, the entire subscription is refused with `QueryReadDenied`; it delivers no partial set of hints. Every query requires `readPolicy` at declaration, including queries used only through one-off `run` calls. TypeScript rejects a policy-less declaration before handlers or a live server can be built. Platform’s application host validates the complete RPC group while building its Layer, before listening; untyped declarations missing policies fail with `MissingReadPolicies`, whose `queries` and `message` name every affected RPC. Native hosts enforce read policies automatically at request time. `MissingReadPolicy` remains a request-time refusal for untyped declarations served through native servers that bypass that boot check, on plain calls and subscriptions alike. Reads outside a declared query acquire no automatic subscription.
547
+ The same query policy guards running the query and subscribing to it. A subscription is meant to carry one query. It names query references, never arbitrary record or bucket keys. If a subscription mixes queries the viewer may and may not read, the entire subscription is refused with `QueryReadDenied`; it delivers no partial results. Every query requires `readPolicy` at declaration, including queries used only through one-off `run` calls. TypeScript rejects a policy-less declaration before handlers or a live server can be built. Platform’s application host validates the complete RPC group while building its Layer, before listening; untyped declarations missing policies fail with `MissingReadPolicies`, whose `queries` and `message` name every affected RPC. Native hosts enforce read policies automatically at request time. `MissingReadPolicy` remains a request-time refusal for untyped declarations served through native servers that bypass that boot check, on plain calls and subscriptions alike. Reads outside a declared query acquire no automatic subscription.
687
548
 
688
- Session middleware supplies `CurrentViewer`; the guard attached to each contract query owns policy evaluation. Custom authentication middleware provides that viewer after validating its session. Before delivering changed keys, the stream rechecks the owning query's policy without memoization. In a session-backed host, a signed-out, revoked or expired session ends the subscription with `Unauthorized`; a signed-in viewer whose policy refuses receives a `QueryReadDenied` delivery while the established subscription stays open. A later authorized hint resumes delivery, including an unchanged pushed value. An initial subscription refusal still fails the stream with `QueryReadDenied`. Custom stream consumers handle the denial delivery alongside `Changed`, `Resync` and `Result`; `SubscriptionHint` from `queryUpdate.ts` types hint consumers. This distinction is the same whether a change hint or the session revalidation interval detects session removal. A client refresh runs the same authorized query that produced its first value; hints carry no row values.
549
+ Session middleware supplies `CurrentViewer` after validating the session. Each rerun uses a freshly loaded session and the same authorized handler as an ordinary read. A removed session ends the subscription with `Unauthorized`; a current session denied by the read policy receives `QueryReadDenied`, with no query SQL and its stored hash cleared. The established subscription stays open for later authorized changes. Raw consumers handle `Result`, `Unchanged` and `QueryReadDenied`.
689
550
 
690
551
  ### Policy services
691
552
 
692
- Use the policy's `viewer` argument for the viewer ID. Read richer session context from Effect requirements. For example, a policy service can require `SessionUserWithProviderAccounts` from `@shivaedev/identity/identity.ts` and yield its `providerAccounts` Effect. Apply `AuthenticatedUserWithProviderAccounts` middleware to the contract and supply `authenticatedUserWithProviderAccountsLayer()` from `@shivaedev/identity/server/session.ts` alongside its handlers, with the shared `SessionPolicy` Layer provided once by the application host. The middleware provides this request-local context for both RPC calls and live change hints, including each policy recheck before a hint is delivered. Session-backed hosts reload that context before each hint, and use the same snapshot for its policy and query rerun.
553
+ Use the policy's `viewer` argument for the viewer ID. Read richer session context from Effect requirements. For example, a policy service can require `SessionUserWithProviderAccounts` from `@shivaedev/identity/identity.ts` and yield its `providerAccounts` Effect. Apply `AuthenticatedUserWithProviderAccounts` middleware to the contract and supply `authenticatedUserWithProviderAccountsLayer()` from `@shivaedev/identity/server/session.ts` alongside its handlers, with the shared `SessionPolicy` Layer provided once by the application host. The middleware provides this request-local context for both RPC calls and live reruns, including each policy recheck before a result is delivered. Session-backed hosts reload that context before each rerun, and use the same snapshot for its policy and query rerun.
693
554
 
694
555
  Keep the policy service tag and query declaration browser-safe; put its implementation on the server. Its method retains the session service in its requirements so the session is read when the policy runs:
695
556
 
@@ -746,7 +607,7 @@ const DocumentHandlers = Documents.application
746
607
  .pipe(Layer.provide(ReadAccessLive));
747
608
  ```
748
609
 
749
- The generated subscription uses the owning query handler's captured services too, so this handler-only provision serves subscriptions as well as RPC calls. Request-local services take precedence over captured services; a session value installed while building handlers cannot replace the current viewer's session. The policy runs again for live hints; its allow or deny result is not cached.
610
+ The generated subscription uses the owning query handler's captured services too, so this handler-only provision serves subscriptions as well as RPC calls. Request-local services take precedence over captured services; a session value installed while building handlers cannot replace the current viewer's session. The policy runs again for live reruns; its allow or deny result is not cached.
750
611
 
751
612
  ### In-memory clients in story kits
752
613
 
@@ -781,19 +642,9 @@ const current = yield* results.latest;
781
642
 
782
643
  `next` consumes the current settled result, then each completed refresh, including equal values and failures, as native `AsyncResult` values. Pending reads are not queued. `latest` reads the current `AsyncResult`, which may still be loading. Closing the Effect scope releases the watcher; independent scopes can observe the same query.
783
644
 
784
- ### Live hints in stories
785
-
786
- Use `watchHints` and `heard` from `@shivaedev/test-kits/contract/testing.ts` in an application's story kit. Pass each viewer's authenticated live stream to `watchHints`; it starts a scoped subscription and waits for its first update, including an initial result, before returning the viewer handle.
787
-
788
- ```ts
789
- const alice = yield* watchHints(aliceChanges);
790
- const bob = yield* watchHints(bobChanges);
791
- yield* renameNote;
792
- expect(yield* heard(alice, [notes.item(1)])).toBe(true);
793
- expect(yield* heard(bob, [notes.item(1)], { within: "50 millis" })).toBe(false);
794
- ```
645
+ ### Live results in stories
795
646
 
796
- `heard` returns `true` once a delivered `Changed` hint contains all the requested keys, including hints received before the call. Extra keys are allowed; `Resync` does not count. It returns `false` when no matching hint arrives within `within` (one second by default). Waiting uses the story's Effect clock, so a test clock controls expiry. Stream failures stay in the typed error channel. Keep expectations in the spec; the support verbs need no retry loops or hidden assertions.
647
+ Observe raw result streams with `watchHints` from `@shivaedev/test-kits/contract/testing.ts`, or wait on a mounted query's completion counter through `querySignals`. Assert the delivered value or rendered screen. An equal rerun increments completion through `Unchanged`, so waiting on value identity alone misses it.
797
648
 
798
649
  ### API by module
799
650
 
@@ -805,9 +656,8 @@ Import the module that defines the name; the package has no root entry.
805
656
  | `contract.ts` | `contract(name, { queries?, commands?, streams?, keyScope? })`, returning a native RPC group with `declaration: { name, queries, commands, streams, keyScope }`. |
806
657
  | `rejection.ts` | `fieldRejection(struct, fields?)`; lower-level `rejectionSet(specs)`, which constructs the rejection classes, union schema and failure helpers used by operations. |
807
658
  | `bind.ts` | `bind(contract, atomRpcService, { registry?, live?, resume?, resumeWindow? }?)`, requiring the registry for session-scoped contracts and exposing `{ query, run }` for queries, `{ run }` Effects for commands and `{ run }` native Streams for streams; `makeClient(contract, { url, protocol?, headers?, webSocketConstructor?, group?, registry?, live?, resume?, resumeWindow? })`, which builds the shared WebSocket client and binds it. |
808
- | `queryCoalesceWindow.ts` | `queryCoalesceWindow(query)`, a writable atom for a bound query's live changed-hint window. |
809
659
  | `clientKeys.ts` | `KeyContext`, `clientReadKeys`, `clientInvalidationKeys`: registry-local cache keys for custom clients. |
810
- | `live.ts` | `LiveHint` schema; `live(runtime, { stream, resyncKeys, coalesceWindow?, initialResync?, keyContext?, resume?, retryDelay?, retryKeys? })`, exposing `connection`, `coalesceWindow`, `paused` and `status`. |
660
+ | `live.ts` | `LiveHint` schema; `live(runtime, { stream, keyContext?, resume?, retryDelay?, retryKeys? })`, exposing `connection`, `paused` and `status`. |
811
661
  | `querySubscription.ts` | `querySubscription(rpc, references, viewer)` checks each referenced query, resolves its payload and server-derived keys, and captures its scopes and ongoing authorization. |
812
662
  | `live-server/service.ts` | `LiveServer`, the shared live server service. |
813
663
  | `live-server/layer.ts` | `liveServerLayer`, providing `LiveServer` and its dispatcher dependency, requiring `Reactivity`. |
@@ -826,7 +676,7 @@ Import the module that defines the name; the package has no root entry.
826
676
  | `querySignals.ts` | `querySignals(query)` exposes completion counts and subscription status as a native atom. |
827
677
  | `clientActivity.ts` | `clientActivity(client)` exposes a native activity Stream with a `current` Effect; `isClientSettled(state)` checks commands and first query results; `isClientIdle(state)` checks all finite work; `activityScreenSignal(activity, settled?)` projects pending work and hints for screen waits. |
828
678
 
829
- A query atom takes native query options as its optional second argument, for example `api.get.query({ id: 1 }, { timeToLive: "1 minute" })`. A native resume source receives a callback and returns a cleanup function.
679
+ A bound query’s optional second argument accepts `headers` and `serializationKey`. Successful results remain in their owning registry for five minutes after the last reader leaves, up to 100 idle queries, evicting the least recently left first. Reopening a query immediately returns the retained success with native `waiting: true` while a new subscription or read supplies fresh data. Execution stops between readers. Configure the registry’s `queryRetention` atom from `@shivaedev/contract/queryRetention.ts` with `{ timeToLive: "1 minute", capacity: 50 }`, or set React’s `SessionBoundary` prop of the same name. Zero for either disables idle retention. Expiry runs on the query runtime’s Effect Clock. Registry disposal clears all retained results; applications outside `SessionBoundary` own that disposal when their session changes. A native resume source receives a callback and returns a cleanup function.
830
680
 
831
681
  ### Install, setup and limits
832
682
 
@@ -839,4 +689,4 @@ pnpm add @shivaedev/contract effect
839
689
  - Run command Effects with the Reactivity instance that owns the queries to refresh, as in the registry example.
840
690
  - Choose a common read key for every query in a full reconciliation scope. A list key does not implicitly cover item queries.
841
691
  - Supply browser or native resume sources explicitly.
842
- - Live hints carry refresh requests, not authoritative data or durable history. Applications own dependency discovery, authenticated subscriptions, delivery across processes, SSR and deployment behavior.
692
+ - Live results carry the query’s current authorized value; server change hints carry keys and no durable history. Applications own dependency discovery, authenticated subscriptions, delivery across processes, SSR and deployment behavior.
@@ -1,18 +1,13 @@
1
- import type { Duration } from "effect";
2
1
  import type * as AsyncResult from "effect/reactivity/AsyncResult";
3
2
  import type * as Atom from "effect/reactivity/Atom";
4
3
  import type { LiveBound, LiveConnection } from "#automaticLive.ts";
5
4
  import type { LiveStatus } from "#live.ts";
6
5
  import type { QuerySignals } from "#querySignals.ts";
7
6
  export interface AutomaticQueryOptions<A, E> {
8
- readonly atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>;
9
7
  readonly clientStatuses: Atom.Writable<ReadonlyMap<object, LiveStatus<unknown>>> | undefined;
10
- readonly coalesceWindow: Atom.Writable<Duration.Input>;
11
8
  readonly equivalent: (left: A, right: A) => boolean;
12
9
  readonly paused: Atom.Writable<boolean>;
13
- readonly pushed: boolean;
14
10
  readonly ready: Atom.Writable<boolean>;
15
- readonly resultVersion: Atom.Atom<number>;
16
11
  readonly signals: Atom.Writable<QuerySignals>;
17
12
  readonly source: Atom.Atom<AsyncResult.AsyncResult<A, E>>;
18
13
  readonly statuses: Atom.Writable<ReadonlyMap<object, LiveStatus<unknown>>>;
@@ -1 +1 @@
1
- {"version":3,"file":"AutomaticQueryOptions.d.ts","sourceRoot":"","sources":["../src/AutomaticQueryOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,KAAK,KAAK,WAAW,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,KAAK,IAAI,MAAM,wBAAwB,CAAC;AACpD,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM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IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;CAChD"}
@@ -1,25 +1,7 @@
1
1
  import { Schema } from "effect";
2
2
  export declare const HostVersion: import("#contract.ts").Contract<"platform.hostVersion", readonly [], readonly [], import("effect/rpc/Rpc").Rpc<"platform.hostVersion.$changes", Schema.Struct<{
3
3
  queries: Schema.$Array<Schema.Union<readonly never[]>>;
4
- }>, import("effect/rpc/RpcSchema").Stream<Schema.Union<readonly [Schema.Union<readonly [Schema.Struct<{
5
- readonly _tag: Schema.Literal<"Changed">;
6
- readonly keys: Schema.$Array<Schema.Union<readonly [Schema.Struct<{
7
- readonly _tag: Schema.Literal<"Bucket">;
8
- readonly collection: Schema.String;
9
- readonly field: Schema.String;
10
- readonly value: Schema.Union<readonly [Schema.String, Schema.Number]>;
11
- }>, Schema.Struct<{
12
- readonly _tag: Schema.Literal<"List">;
13
- readonly collection: Schema.String;
14
- }>, Schema.Struct<{
15
- readonly _tag: Schema.Literal<"Item">;
16
- readonly collection: Schema.String;
17
- readonly id: Schema.Union<readonly [Schema.String, Schema.Number]>;
18
- }>]>>;
19
- readonly queryIndexes: Schema.optional<Schema.$Array<Schema.Number>>;
20
- }>, Schema.Struct<{
21
- readonly _tag: Schema.Literal<"Resync">;
22
- }>]>, typeof import("./readPolicyErrors.ts").QueryReadDenied, ...never[]]>, Schema.Union<readonly [typeof import("./readPolicyErrors.ts").MissingReadPolicy, typeof import("./readPolicyErrors.ts").QueryReadDenied, typeof import("./WebSocketRequired.ts").WebSocketRequired, ...never[]]>>, Schema.Never, import("effect/Context").Reference<<A, E, R>(effect: import("effect/Effect").Effect<A, E, R>, request: {
4
+ }>, import("effect/rpc/RpcSchema").Stream<Schema.Union<readonly [typeof import("./readPolicyErrors.ts").QueryReadDenied, ...never[]]>, Schema.Union<readonly [typeof import("./readPolicyErrors.ts").MissingReadPolicy, typeof import("./readPolicyErrors.ts").QueryReadDenied, typeof import("./WebSocketRequired.ts").WebSocketRequired, ...never[]]>>, Schema.Never, import("effect/Context").Reference<<A, E, R>(effect: import("effect/Effect").Effect<A, E, R>, request: {
23
5
  readonly rpc: import("effect/rpc/Rpc").Any;
24
6
  readonly payload: unknown;
25
7
  }) => import("effect/Effect").Effect<A, E | import("./readPolicyErrors.ts").MissingReadPolicy | import("./readPolicyErrors.ts").QueryReadDenied | import("./WebSocketRequired.ts").WebSocketRequired | import("effect/Types").unhandled, R>> & {
@@ -1 +1 @@
1
- {"version":3,"file":"HostVersion.d.ts","sourceRoot":"","sources":["../src/HostVersion.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAIhC,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;+RAEtB,CAAC"}
1
+ {"version":3,"file":"HostVersion.d.ts","sourceRoot":"","sources":["../src/HostVersion.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAIhC,eAAO,MAAM,WAAW;;;;;;;;;;+RAEtB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"activityState.d.ts","sourceRoot":"","sources":["../../src/adapters/activityState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAmB,MAAM,QAAQ,CAAC;AACjD,OAAO,KAAK,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEhF,wBAAgB,aAAa;IAqB3B,QAAQ;;;IACR,MAAM,QAAQ,OAAO,CAAC,MAAM,mBAAmB,EAAE,kBAAkB,CAAC,SAAS,MAAM;IAGnF,IAAI;IAQJ,aAAa,qBAAqB,gBAAgB;EAKnD"}
1
+ {"version":3,"file":"activityState.d.ts","sourceRoot":"","sources":["../../src/adapters/activityState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAmB,MAAM,QAAQ,CAAC;AACjD,OAAO,KAAK,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEhF,wBAAgB,aAAa;IAoB3B,QAAQ;;;IACR,MAAM,QAAQ,OAAO,CAAC,MAAM,mBAAmB,EAAE,kBAAkB,CAAC,SAAS,MAAM;IAGnF,IAAI;IAQJ,aAAa,qBAAqB,gBAAgB;EAKnD"}
@@ -7,7 +7,6 @@ export function activityState() {
7
7
  connectionStatus: "live",
8
8
  initialQueries: 0,
9
9
  liveHints: 0,
10
- liveInvalidations: 0,
11
10
  refreshingAtoms: 0,
12
11
  rpcCalls: 0,
13
12
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"activityState.js","sourceRoot":"","sources":["../../src/adapters/activityState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAGjD,MAAM,UAAU,aAAa;IAC5B,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,UAAU,GAAqB,MAAM,CAAC;IAC1C,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAC3B,eAAe,CAAC,IAAI,CAAsB;QACzC,QAAQ,EAAE,CAAC;QACX,gBAAgB,EAAE,MAAM;QACxB,cAAc,EAAE,CAAC;QACjB,SAAS,EAAE,CAAC;QACZ,iBAAiB,EAAE,CAAC;QACpB,eAAe,EAAE,CAAC;QAClB,QAAQ,EAAE,CAAC;KACX,CAAC,CACF,CAAC;IACF,SAAS,OAAO;QACf,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,UAAU,CAAC;QAC1E,MAAM,CAAC,OAAO,CACb,eAAe,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,gBAAgB,KAAK,gBAAgB,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,EAAE,gBAAgB,EAAE,CAAC,CAAC,CACxI,CAAC;IACH,CAAC;IACD,OAAO;QACN,QAAQ,EAAE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O;QACf,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,UAAU,CAAC;QAC1E,MAAM,CAAC,OAAO,CACb,eAAe,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,gBAAgB,KAAK,gBAAgB,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,EAAE,gBAAgB,EAAE,CAAC,CAAC,CACxI,CAAC;IACH,CAAC;IACD,OAAO;QACN,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,EAAE,OAAO,EAAE,eAAe,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;QAChG,MAAM,EAAE,CAAC,GAA2D,EAAE,KAAa,EAAE,EAAE;YACtF,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,OAAO,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;QAC3G,CAAC;QACD,IAAI,EAAE,GAAG,EAAE;YACV,IAAI,IAAI,CAAC,CAAC;YACV,OAAO,EAAE,CAAC;YACV,OAAO,GAAG,EAAE;gBACX,IAAI,IAAI,CAAC,CAAC;gBACV,OAAO,EAAE,CAAC;YACX,CAAC,CAAC;QACH,CAAC;QACD,aAAa,EAAE,CAAC,gBAAkC,EAAE,EAAE;YACrD,UAAU,GAAG,gBAAgB,CAAC;YAC9B,OAAO,EAAE,CAAC;QACX,CAAC;KACD,CAAC;AACH,CAAC"}
@@ -22,7 +22,6 @@ export declare const liveHintStream: (state: {
22
22
  readonly collection: string;
23
23
  readonly id: string | number;
24
24
  })[];
25
- readonly queryIndexes?: readonly number[] | undefined;
26
25
  } | {
27
26
  readonly _tag: "Resync";
28
27
  }, never, never>;
@@ -1 +1 @@
1
- {"version":3,"file":"liveHintStream.d.ts","sourceRoot":"","sources":["../../src/adapters/liveHintStream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,KAAK,UAAU,MAAM,8BAA8B,CAAC;AAC3D,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,4BAA4B,CAAC;AAEtD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAGrD,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;gEAOzB,CAAC"}
1
+ {"version":3,"file":"liveHintStream.d.ts","sourceRoot":"","sources":["../../src/adapters/liveHintStream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,KAAK,UAAU,MAAM,8BAA8B,CAAC;AAC3D,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,4BAA4B,CAAC;AAEtD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAGrD,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;gEAOzB,CAAC"}
@@ -22,7 +22,6 @@ export declare const openLiveHints: (state: {
22
22
  readonly collection: string;
23
23
  readonly id: string | number;
24
24
  })[];
25
- readonly queryIndexes?: readonly number[] | undefined;
26
25
  } | {
27
26
  readonly _tag: "Resync";
28
27
  }, never, never>;
@@ -1 +1 @@
1
- {"version":3,"file":"openLiveHints.d.ts","sourceRoot":"","sources":["../../src/adapters/openLiveHints.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAS,GAAG,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACpD,OAAO,KAAK,UAAU,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAE,KAAK,GAAG,EAAY,MAAM,4BAA4B,CAAC;AAGhE,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,eAAO,MAAM,aAAa;;;;2BAwBK,SAAS,GAAG,EAAE;;;;;;;;;;;;;;;;;;;;gFA8B3C,CAAC"}
1
+ {"version":3,"file":"openLiveHints.d.ts","sourceRoot":"","sources":["../../src/adapters/openLiveHints.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAS,GAAG,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACpD,OAAO,KAAK,UAAU,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAE,KAAK,GAAG,EAAY,MAAM,4BAA4B,CAAC;AAGhE,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,eAAO,MAAM,aAAa;;;;2BAwBK,SAAS,GAAG,EAAE;;;;;;;;;;;;;;;;;;;gFA8B3C,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { Option } from "effect";
2
+ import * as Atom from "effect/reactivity/Atom";
3
+ export declare const retainedQueries: Atom.Atom<{
4
+ keep: <A>(query: Atom.Atom<unknown>, snapshot: Atom.Writable<Option.Option<A>>, runtime: Atom.AtomRuntime<unknown, unknown>) => void;
5
+ take: (atom: Atom.Atom<unknown>) => void | undefined;
6
+ }>;
7
+ //# sourceMappingURL=retainedQueries.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retainedQueries.d.ts","sourceRoot":"","sources":["../../src/adapters/retainedQueries.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,MAAM,EAAE,MAAM,QAAQ,CAAC;AAElD,OAAO,KAAK,IAAI,MAAM,wBAAwB,CAAC;AAG/C,eAAO,MAAM,eAAe;WAKlB,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,OAAO,CAAC;iBAiC9G,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC;EAGjC,CAAC"}
@@ -0,0 +1,45 @@
1
+ import { Duration, Effect, Option } from "effect";
2
+ import * as AsyncResult from "effect/reactivity/AsyncResult";
3
+ import * as Atom from "effect/reactivity/Atom";
4
+ import { queryRetention } from "#queryRetention.ts";
5
+ export const retainedQueries = Atom.keepAlive(Atom.make((get) => {
6
+ const idle = new Map();
7
+ get.addFinalizer(() => idle.clear());
8
+ return {
9
+ keep: (query, snapshot, runtime) => {
10
+ const { capacity = 100, timeToLive = "5 minutes" } = get.registry.get(queryRetention);
11
+ const duration = Duration.fromInputUnsafe(timeToLive);
12
+ if (capacity <= 0 || Duration.toMillis(duration) <= 0) {
13
+ get.registry.set(snapshot, Option.none());
14
+ return;
15
+ }
16
+ const registry = get.registry;
17
+ const unmount = registry.mount(snapshot);
18
+ function release() {
19
+ idle.delete(query);
20
+ stop();
21
+ unmount();
22
+ }
23
+ function expire() {
24
+ registry.set(snapshot, Option.none());
25
+ release();
26
+ }
27
+ idle.set(query, { expire, release });
28
+ const timer = Atom.make((context) => {
29
+ const services = context(runtime);
30
+ if (AsyncResult.isSuccess(services)) {
31
+ context.addFinalizer(Effect.runCallbackWith(services.value)(Effect.sleep(duration).pipe(Effect.andThen(Effect.sync(expire)))));
32
+ }
33
+ }).pipe(Atom.setIdleTTL(0));
34
+ const stop = registry.mount(timer);
35
+ while (idle.size > capacity) {
36
+ const oldest = idle.keys().next().value;
37
+ if (oldest !== undefined) {
38
+ idle.get(oldest)?.expire();
39
+ }
40
+ }
41
+ },
42
+ take: (atom) => idle.get(atom)?.release(),
43
+ };
44
+ }));
45
+ //# sourceMappingURL=retainedQueries.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retainedQueries.js","sourceRoot":"","sources":["../../src/adapters/retainedQueries.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAClD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