@shivaedev/contract 0.43.5 → 0.44.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 (122) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +262 -44
  3. package/dist/adapters/servedHandlers.d.ts +8 -0
  4. package/dist/adapters/servedHandlers.d.ts.map +1 -0
  5. package/dist/adapters/servedHandlers.js +51 -0
  6. package/dist/adapters/servedHandlers.js.map +1 -0
  7. package/dist/automaticQuery.js +1 -1
  8. package/dist/automaticQuery.js.map +1 -1
  9. package/dist/clientActivity.d.ts +0 -2
  10. package/dist/clientActivity.d.ts.map +1 -1
  11. package/dist/clientActivity.js +1 -1
  12. package/dist/clientActivity.js.map +1 -1
  13. package/dist/clientContract.d.ts +51 -0
  14. package/dist/clientContract.d.ts.map +1 -0
  15. package/dist/clientContract.js +32 -0
  16. package/dist/clientContract.js.map +1 -0
  17. package/dist/clientMatchesModule.d.ts +18 -0
  18. package/dist/clientMatchesModule.d.ts.map +1 -0
  19. package/dist/clientMatchesModule.js +2 -0
  20. package/dist/clientMatchesModule.js.map +1 -0
  21. package/dist/contract.d.ts +23 -1
  22. package/dist/contract.d.ts.map +1 -1
  23. package/dist/contract.js +9 -6
  24. package/dist/contract.js.map +1 -1
  25. package/dist/declarationError.d.ts +1 -2
  26. package/dist/declarationError.d.ts.map +1 -1
  27. package/dist/declarationError.js +3 -1
  28. package/dist/declarationError.js.map +1 -1
  29. package/dist/defineModule.d.ts +41 -0
  30. package/dist/defineModule.d.ts.map +1 -0
  31. package/dist/defineModule.js +17 -0
  32. package/dist/defineModule.js.map +1 -0
  33. package/dist/live-server/subscribe.d.ts.map +1 -1
  34. package/dist/live-server/subscribe.js +64 -6
  35. package/dist/live-server/subscribe.js.map +1 -1
  36. package/dist/live.d.ts +1 -0
  37. package/dist/live.d.ts.map +1 -1
  38. package/dist/live.js +5 -0
  39. package/dist/live.js.map +1 -1
  40. package/dist/liveAnswers.d.ts +9 -0
  41. package/dist/liveAnswers.d.ts.map +1 -0
  42. package/dist/liveAnswers.js +12 -0
  43. package/dist/liveAnswers.js.map +1 -0
  44. package/dist/moduleHandlers.d.ts +15 -0
  45. package/dist/moduleHandlers.d.ts.map +1 -0
  46. package/dist/moduleHandlers.js +5 -0
  47. package/dist/moduleHandlers.js.map +1 -0
  48. package/dist/moduleProof.d.ts +79 -0
  49. package/dist/moduleProof.d.ts.map +1 -0
  50. package/dist/moduleProof.js +2 -0
  51. package/dist/moduleProof.js.map +1 -0
  52. package/dist/operation.d.ts +14 -12
  53. package/dist/operation.d.ts.map +1 -1
  54. package/dist/operation.js +10 -4
  55. package/dist/operation.js.map +1 -1
  56. package/dist/operationDeclaration.d.ts +9 -1
  57. package/dist/operationDeclaration.d.ts.map +1 -1
  58. package/dist/operationDeclaration.js.map +1 -1
  59. package/dist/queryDelivery.js +1 -1
  60. package/dist/queryDelivery.js.map +1 -1
  61. package/dist/querySubscription.d.ts +1 -1
  62. package/dist/querySubscription.d.ts.map +1 -1
  63. package/dist/querySubscription.js +6 -4
  64. package/dist/querySubscription.js.map +1 -1
  65. package/dist/readPolicy.d.ts +2 -1
  66. package/dist/readPolicy.d.ts.map +1 -1
  67. package/dist/readPolicy.js +9 -5
  68. package/dist/readPolicy.js.map +1 -1
  69. package/dist/retainQuery.d.ts +1 -0
  70. package/dist/retainQuery.d.ts.map +1 -1
  71. package/dist/retainQuery.js +5 -0
  72. package/dist/retainQuery.js.map +1 -1
  73. package/dist/runProof.d.ts +69 -0
  74. package/dist/runProof.d.ts.map +1 -0
  75. package/dist/runProof.js +2 -0
  76. package/dist/runProof.js.map +1 -0
  77. package/dist/servedOperation.d.ts +72 -0
  78. package/dist/servedOperation.d.ts.map +1 -0
  79. package/dist/servedOperation.js +11 -0
  80. package/dist/servedOperation.js.map +1 -0
  81. package/dist/servedReadPolicy.d.ts +11 -0
  82. package/dist/servedReadPolicy.d.ts.map +1 -0
  83. package/dist/servedReadPolicy.js +9 -0
  84. package/dist/servedReadPolicy.js.map +1 -0
  85. package/dist/serverMetadata.d.ts +1 -4
  86. package/dist/serverMetadata.d.ts.map +1 -1
  87. package/dist/serverMetadata.js +3 -6
  88. package/dist/serverMetadata.js.map +1 -1
  89. package/dist/successProof.d.ts +51 -0
  90. package/dist/successProof.d.ts.map +1 -0
  91. package/dist/successProof.js +2 -0
  92. package/dist/successProof.js.map +1 -0
  93. package/dist/wire.d.ts +25 -0
  94. package/dist/wire.d.ts.map +1 -0
  95. package/dist/wire.js +13 -0
  96. package/dist/wire.js.map +1 -0
  97. package/package.json +16 -16
  98. package/src/adapters/servedHandlers.ts +69 -0
  99. package/src/automaticQuery.ts +1 -1
  100. package/src/clientActivity.ts +1 -1
  101. package/src/clientContract.ts +128 -0
  102. package/src/clientMatchesModule.ts +24 -0
  103. package/src/contract.ts +24 -17
  104. package/src/declarationError.ts +5 -2
  105. package/src/defineModule.ts +112 -0
  106. package/src/live-server/subscribe.ts +74 -6
  107. package/src/live.ts +7 -0
  108. package/src/liveAnswers.ts +13 -0
  109. package/src/moduleHandlers.ts +23 -0
  110. package/src/moduleProof.ts +101 -0
  111. package/src/operation.ts +47 -33
  112. package/src/operationDeclaration.ts +19 -1
  113. package/src/queryDelivery.ts +1 -1
  114. package/src/querySubscription.ts +6 -4
  115. package/src/readPolicy.ts +15 -5
  116. package/src/retainQuery.ts +7 -0
  117. package/src/runProof.ts +96 -0
  118. package/src/servedOperation.ts +145 -0
  119. package/src/servedReadPolicy.ts +19 -0
  120. package/src/serverMetadata.ts +3 -6
  121. package/src/successProof.ts +120 -0
  122. package/src/wire.ts +45 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.44.0 - 2026-11-11
4
+
5
+ ### Added
6
+
7
+ - `defineModule({ name, operations, requires, middleware?, subject?, keyScope? })` from `@shivaedev/contract/defineModule.ts` defines a module from operations written as `payload` and `*run`. It returns the module's contract, which client and host code accept like any contract; the compiler checks `requires`, which carries no run-time value. Its generics check the definition on the `name` line, naming the operation in the first line of the compiler's message: `OperationNeedsUndeclaredServices` when a `run` or read policy uses a service that `requires`, the middleware and the subject do not provide, `OperationFailsOutsideItsRejections` when an operation can fail outside its rejections other than with an infrastructure failure, and `OperationNameRepeated`.
8
+ - `moduleHandlers(module)` from `@shivaedev/contract/moduleHandlers.ts` builds the module's handler Layer from its operations, requiring exactly the module's `requires`. Each operation runs in a span named `<Module>.<operation>`; a query's read policy is checked inside its handler before `run`, so a policy may read a repository directly, and live subscriptions check the same policy. An undeclared failure that states `isRetryable` answers `ServiceUnavailable`, and anything else undeclared answers `InternalServerError` and is reported.
9
+ - Operations written with `run` report three more mismatches: `RunReturnsAny` when `run` returns `any`, which previously switched the success and rejection checks off; `SuccessClassNotReturned` when the success is a `Schema.Class` and `run` returns something other than that class; and `RejectionClassDiffers` when a listed rejection class and the class `run` raises under the same tag differ in shape. TypeScript compares classes by shape, so a same-shape twin of a class still compiles.
10
+ - Every RPC of a module built with `defineModule` carries the `DefinedModule` annotation with the module's name; a contract built with `contract` carries none.
11
+ - A live query subscription registers each key its handler records with the host the moment it is recorded, before the recording call's statement is sent, and matches recorded keys together with the keys from `reads`, `serverReads` and `readsCollections`.
12
+ - `queryRuntime(query)` from `@shivaedev/contract/retainQuery.ts` returns the atom runtime a bound query runs on.
13
+ - `defineModule` takes an optional `wire`: per operation a success schema and rejection classes, for a generator to write from `run`'s types (until it ships, written by hand). An operation with a wire entry is served with that entry's success and rejections, plus `InternalServerError` and `ServiceUnavailable`, even when it declares its own, so the server encodes with the schemas the browser decodes with; an operation without an entry is served with what it declares. The compiler compares the wire with `run` and reports a stale one on the module's `name` line, one problem per operation: `WireSuccessStale`, `WireRejectionsStale`, and `OperationMissingFromWire` for an operation that declares no success, returns something and has no entry.
14
+ - `clientContract({ name, wire, payloads?, queries?, commands?, middleware?, subject?, keyScope? })` from `@shivaedev/contract/clientContract.ts` builds the browser's contract of a module from its wire, payloads, `reads` and `invalidates`, with no `run` or read policy, for generated files; every query and command it declares needs a wire entry. `ClientMatchesModule<Client, Module>` from `@shivaedev/contract/clientMatchesModule.ts` asserts that its RPCs equal the server module's and otherwise fails with `ClientDiffersFromModule`, naming the operations and `pnpm generate`.
15
+ - The check that a declared success equals what `run` returns also covers a `Schema.Class` held in an array, struct field, tuple, record, union or `Option`: a plain object in that position is `SuccessClassNotReturned`.
16
+ - `query(name, { … })` and `command(name, { … })` accept an operation written as its `payload` and a generator `*run`. `run` becomes an Effect-returning function, so one operation can `yield* Create.run(payload)` and inherit its services and failures. A query without `readPolicy` gets `signedIn` and still declares `reads` (with optional `serverReads` and `readsCollections`); a command without `invalidates` announces no keys of its own. Existing declaration forms are unchanged.
17
+ - `success` and `rejections` are optional on that form. A declared one must equal what `run` infers, and each mismatch is a compile error naming the operation and the problem: `SuccessDiffersFromRun`, `ArrayMutabilityDiffers` (return a readonly array, or declare `Schema.mutable`), `RunFailsOutsideRejections` (also for a read policy's failures), `RejectionsRunNeverRaises` and `RejectionAutomatic`. Failures that state `isRetryable`, `SchemaError` and `QueryReadDenied` are never rejections.
18
+ - Every operation written with `run` carries `InternalServerError` and `ServiceUnavailable` in its type and rejection set and cannot list them. No `Conflict` is added; map a constraint violation in `run` to a domain failure instead.
19
+ - A field failure for that form is an exported class, `Schema.TaggedError<TitleTaken>()("TitleTaken", fieldRejection(NoteFields))`, raised in `run` with `yield* new TitleTaken({ field, message })`; `@shivaedev/form`'s `rejecting` places its message on that field.
20
+ - When a live query that declares no keys finishes a run without recording one, the host logs a warning naming the query and saying to mark its raw reads or declare `reads`. The subscription continues; `reads: () => []` states that a query reads nothing and logs no warning.
21
+ - A query may leave out `reads`. A query that declares no keys in `reads`, `serverReads` or `readsCollections` listens on what its repository reads pin, so an unfiltered read listens on the whole table; declared keys are used exactly as declared, so existing queries listen as before.
22
+ - A live subscription registers a recorded key only when it is not registered yet, so a handler that reads the same row many times registers its key once.
23
+ - Nothing a module query's read policy records counts, whether through repository reads or `recordRead`, so a write to a row only the policy reads does not rerun the query.
24
+ - `liveAnswers(registry, name, query)` from `liveAnswers.ts` counts a bound query's settled answers, pushed or unchanged, for the screen driver's `withLiveAnswer`.
25
+ - `isLiveConnection(atom)` from `live.ts` tells whether an atom is the `connection` of a `live` subscription, which stays waiting for as long as the subscription runs.
26
+ - The check that a declared success, or a module's wire, equals what `run` returns also compares keys: the keys at each `Schema.Struct` position, including an optional or mutable field and a union member, must equal the keys `run` returns there. An optional property that only one side has is `SuccessDiffersFromRun`, or `WireSuccessStale` for a module's wire, instead of a key the `Struct` drops or never sends.
27
+
28
+ ### Fixed
29
+
30
+ - A live query reports `waiting: true` from mount until its subscription delivers the first result. It used to report a non-waiting initial result while the subscription opened, so `useQuery`'s `pending` and screen pending signals read a loading query as idle.
31
+
32
+ ### Breaking
33
+
34
+ - `KeyScope` is no longer exported from `@shivaedev/contract/serverMetadata.ts`, and a `keyScope: "session"` contract no longer annotates its RPCs with it. Nothing read the annotation, so there is no replacement: server keys were and stay unprefixed. Remove any import of `KeyScope`. In the browser, `keyScope: "session"` still prefixes every client read and invalidation key with an opaque id of the binding's registry.
35
+ - `QueryShape["readPolicy"]` is optional, as it already was at run time, because the browser's contract of a module has no read policy; `contract()` still requires one on every query. Code that calls the policy of an erased `QueryShape` checks for `undefined` first.
36
+ - `contract()` requires a read policy on every query in its type, so an array typed `readonly QueryShape[]` passed as `queries` no longer compiles. Type the array with the queries' own type instead, for example `const queries: readonly (typeof Get)[] = [Get, Get];`, or pass the queries inline.
37
+ - `SuccessDiffersFromRun`, `SuccessClassNotReturned` and `ArrayMutabilityDiffers` moved from `@shivaedev/contract/runProof.ts` to `@shivaedev/contract/successProof.ts`; import them from the new path.
38
+ - `activityScreenSignal` no longer reports `hints`; wait for a live change with `liveAnswers` and the screen driver's `withLiveAnswer`.
39
+
3
40
  ## 0.43.5 - 2026-11-10
4
41
 
5
42
  ### Fixed
package/README.md CHANGED
@@ -27,7 +27,7 @@ const Notes = contract("notes", { queries: [List], commands: [Rename] });
27
27
 
28
28
  ### How to think about it
29
29
 
30
- An **operation** describes a boundary, not its implementation: its name, payload schema, success schema and expected failures. A **query** also declares the keys it reads; a **command** declares the keys its successful result changes. A **stream** declares an element schema in `success`, typed rejections and the keys it reads. A **rejection** is an expected typed failure, such as a missing note or an invalid title. Middleware failures and RPC client failures remain separate parts of the native client's error type.
30
+ An **operation** describes a boundary, not its implementation: its name, payload schema, success schema and expected failures. A **query** listens on the keys its repository reads name, or on the keys it declares; a **command** declares the keys its successful result changes. A **stream** declares an element schema in `success`, typed rejections and the keys it reads. A **rejection** is an expected typed failure, such as a missing note or an invalid title. Middleware failures and RPC client failures remain separate parts of the native client's error type.
31
31
 
32
32
  A **contract** groups operations into a native `RpcGroup`. Its RPC tags are the contract name and operation name joined by a dot. A **binding** connects that declaration to an existing `AtomRpc.Service`: queries get native query atoms and call Effects, while commands get call Effects that invalidate after success. Streams expose a native `Stream` through `run`; the caller owns consumption and interruption.
33
33
 
@@ -90,6 +90,213 @@ Operation names must differ within a contract, including across queries, command
90
90
 
91
91
  The native RPC mapping types `OperationRpc` and `Tag` are exported from `@shivaedev/contract/operationRpc.ts`.
92
92
 
93
+ ### An operation written as its payload and run
94
+
95
+ An operation can also be written as its business logic: a `payload` schema and a generator `*run`, with no `Effect.gen` wrapper. Its success, rejections, services and the read policy's failures are inferred from `run`:
96
+
97
+ ```ts
98
+ import { Effect, Schema } from "effect";
99
+ import { command, query } from "@shivaedev/contract/operation.ts";
100
+ import { fieldRejection } from "@shivaedev/contract/rejection.ts";
101
+ import { NotesRepository, SessionUser } from "./services.ts";
102
+
103
+ export const NoteFields = Schema.Struct({ title: Schema.Trim.check(Schema.isNonEmpty({ message: "Enter a title" })) });
104
+ export class TitleTaken extends Schema.TaggedError<TitleTaken>()("TitleTaken", fieldRejection(NoteFields)) {}
105
+
106
+ export const Create = command("create", {
107
+ payload: NoteFields,
108
+ *run({ title }) {
109
+ const repository = yield* NotesRepository;
110
+ const { id: userId } = yield* SessionUser;
111
+ if (title === "reserved") {
112
+ return yield* new TitleTaken({ field: "title", message: "That title is reserved" });
113
+ }
114
+ return yield* repository.insert({ title, userId }).pipe(Effect.map(({ id }) => ({ id, title })));
115
+ },
116
+ });
117
+
118
+ export const List = query("list", {
119
+ *run() {
120
+ const repository = yield* NotesRepository;
121
+ const { id: userId } = yield* SessionUser;
122
+ return yield* repository.findMany({ select: ["id", "title"], where: { userId } });
123
+ },
124
+ });
125
+ ```
126
+
127
+ Here `NotesRepository` is a `@shivaedev/sql` repository whose model marks `userId` as a bucket. Its insert announces the new row and its owner's bucket, so `Create` declares no `invalidates`, and `List` declares no `reads`: its `findMany` pins the owner's bucket, so the live list listens on it.
128
+
129
+ `Create.run` is an Effect-returning function, so another operation composes it with `yield* Create.run({ title })`, and `Create`'s services and failures join that operation's types. A query without `readPolicy` gets `signedIn`, at run time and in its type. It may declare `reads`, `serverReads` and `readsCollections` (which need a `permissionReadPolicy`); one that declares none listens on what its repository reads filter by, as [query policies, record keys and buckets](#query-policies-record-keys-and-buckets) explains. A command without `invalidates` announces no keys of its own. A payload-free operation omits `payload` and gets `Schema.Void`.
130
+
131
+ `success` and `rejections` are optional. A declared one must equal what `run` infers, checked on the declaration object, and each mismatch is a compile error that names the operation and the problem: `RunReturnsAny` when `run` returns `any`, such as the result of `JSON.parse`, which would otherwise pass every check (decode the value with a schema, or type it); `SuccessDiffersFromRun` when the declared success's type and `run`'s return type are not mutually assignable, or when an object that `run` returns and a `Schema.Struct` that the success holds in the same position, at the top or in an array, struct field, tuple, record, union or `Option`, have different keys, such as an optional property only one of them has, which the `Struct` would drop or never send; `SuccessClassNotReturned` when the success is a `Schema.Class`, or holds one in an array, struct field, tuple, record, union or `Option`, and `run` returns something other than that class in that position, such as an object literal of its fields, which fails to encode; `ArrayMutabilityDiffers` when they differ only in array mutability, because `Schema.Array` decodes a readonly array (return one, or declare `Schema.mutable`); `RunFailsOutsideRejections` when `run` or the read policy can fail with a tag that `rejections` misses; `RejectionsRunNeverRaises` for a listed tag nothing raises; `RejectionClassDiffers` when a listed class and the class `run` raises under the same tag differ in shape, such as a local `NotFound` with other fields than the shared one; `RejectionAutomatic` for a listed `InternalServerError` or `ServiceUnavailable`. Rejections are exported classes keyed by their `_tag`. A failure that states `isRetryable` (such as `SqlError`), `SchemaError` and `QueryReadDenied` are never rejections. While the declaration forms above are still accepted, such an error starts with "No overload matches this call" and its last line names the problem.
132
+
133
+ TypeScript compares classes by shape, so two cases still compile: a rejection class whose twin of the same shape is what `run` raises, and a helper typed to return a readonly interface of the same shape where the success is a `Schema.Class`. Neither is silent at run time: the twin is not the declared class, so the boundary answers `InternalServerError` and reports it, and the plain object fails to encode. The generator in [`@shivaedev/build`](https://github.com/ShivaeDev/platform/tree/main/packages/build), which derives `success` and `rejections` from `run`, resolves both by declaration. A `Schema.Struct` behind another schema, such as a transformation, a brand or `Schema.suspend`, is compared with `run` only by mutual assignability, so an optional property that only one side has still compiles there and is dropped or never sent.
134
+
135
+ Every operation written this way carries `InternalServerError` and `ServiceUnavailable` in its type and its rejection set, and cannot list them. Nothing adds `Conflict`: an operation that answers a constraint violation as a domain failure maps it by constraint name in `run`, and inference carries the result. Because object keys are sorted, `invalidates` is checked before `run`, so its result parameter is typed only when `success` is declared.
136
+
137
+ Two limits meet you while writing these operations. On its own, an omitted success is `Schema.Void` and omitted rejections leave only the automatic two in the operation's RPC schemas; a module's wire supplies both (below), and an operation served through `contract()` declares them. Biome's `useYield` refuses a `*run` that yields nothing, so a `run` that needs no service still yields an Effect.
138
+
139
+ A field failure is an exported tagged class built from the payload's fields with `fieldRejection`, as `TitleTaken` above. `run` raises it with `yield* new TitleTaken({ field, message })`, and `@shivaedev/form`'s `rejecting` places its message on that field.
140
+
141
+ ### A module defined from its operations
142
+
143
+ A module lists its operations once, with the services they may use, and serves them without hand-written handlers:
144
+
145
+ ```ts
146
+ import { Effect, Option, Schema } from "effect";
147
+ import { collection } from "@shivaedev/changes/keys.ts";
148
+ import { NotFound, Unauthorized } from "@shivaedev/errors/taxonomy.ts";
149
+ import { defineModule } from "@shivaedev/contract/defineModule.ts";
150
+ import { command, query } from "@shivaedev/contract/operation.ts";
151
+ import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
152
+ import { fieldRejection } from "@shivaedev/contract/rejection.ts";
153
+ import { Caller, NotesStore, type StoredNote } from "./services.ts";
154
+
155
+ const notes = collection("notes", Schema.Number);
156
+ export const NoteFields = Schema.Struct({ title: Schema.String });
157
+ export const Note = Schema.Struct({ id: Schema.Number, title: Schema.String });
158
+ export class TitleTaken extends Schema.TaggedError<TitleTaken>()("TitleTaken", fieldRejection(NoteFields)) {}
159
+
160
+ const signedInUser = Effect.flatMap(CurrentViewer, (viewer) =>
161
+ Option.match(viewer, {
162
+ onNone: () => Effect.fail(new Unauthorized({ message: "Sign in first" })),
163
+ onSome: ({ id }) => Effect.succeed(id),
164
+ }),
165
+ );
166
+
167
+ function toNotes(stored: readonly StoredNote[]): readonly (typeof Note.Type)[] {
168
+ return stored.map(({ id, title }) => ({ id, title }));
169
+ }
170
+
171
+ export const Create = command("create", {
172
+ payload: NoteFields,
173
+ rejections: { TitleTaken, Unauthorized },
174
+ *run({ title }) {
175
+ const store = yield* NotesStore;
176
+ const owner = yield* signedInUser;
177
+ const owned = yield* store.owned(owner);
178
+ if (owned.some((note) => note.title === title)) {
179
+ return yield* new TitleTaken({ field: "title", message: "You already have a note with that title" });
180
+ }
181
+ const { id } = yield* store.insert(title, owner);
182
+ return { id, title };
183
+ },
184
+ success: Note,
185
+ });
186
+
187
+ export const Get = query("get", {
188
+ payload: { id: Schema.Number },
189
+ readPolicy: ({ id }, viewer) =>
190
+ Effect.gen(function* () {
191
+ if (Option.isNone(viewer)) {
192
+ return false;
193
+ }
194
+ const note = yield* (yield* NotesStore).find(id);
195
+ return Option.exists(note, ({ owner }) => owner === viewer.value.id);
196
+ }),
197
+ reads: ({ id }) => [notes.item(id)],
198
+ rejections: { NotFound },
199
+ *run({ id }) {
200
+ const note = yield* (yield* NotesStore).find(id);
201
+ if (Option.isNone(note)) {
202
+ return yield* new NotFound({ message: "Note not found" });
203
+ }
204
+ return { id: note.value.id, title: note.value.title };
205
+ },
206
+ success: Note,
207
+ });
208
+
209
+ export const List = query("list", {
210
+ reads: () => [notes.list],
211
+ rejections: { Unauthorized },
212
+ *run() {
213
+ const store = yield* NotesStore;
214
+ return toNotes(yield* store.owned(yield* signedInUser));
215
+ },
216
+ success: Schema.Array(Note),
217
+ });
218
+
219
+ export const Notes = defineModule({
220
+ middleware: Caller,
221
+ name: "notes",
222
+ operations: [List, Get, Create],
223
+ requires: [NotesStore],
224
+ });
225
+ ```
226
+
227
+ Here `NotesStore` is an ordinary service, `StoredNote` the row it returns, and `Caller` an RPC middleware that sets the viewer. `defineModule` takes the operations written as payload and run, the services they may use in `requires`, optionally `middleware`, `subject` and `keyScope` as `contract` does, and its `wire` (below). It returns the module's contract, so `bind`, `makeClient` and a host accept it as they accept any contract. Each of its RPCs carries the `DefinedModule` annotation from the same file with the module's name, so a host can tell a module's queries from a contract's. The compiler checks `requires`, and the module does not keep the list at run time. Its generics check the definition on the `name` line, so the first line of the compiler's message names the operation and its problem: `OperationNeedsUndeclaredServices` when an operation's `run` or read policy uses a service that neither `requires` nor the middleware or subject provides, `OperationFailsOutsideItsRejections` when it can fail with something outside its rejections other than an infrastructure failure, and `OperationNameRepeated` when two operations share a name:
228
+
229
+ ```
230
+ src/test-support/fixtures/invalid/moduleUndeclaredService.ts(24,2): error TS2322: Type '"imports"' is not assignable to type '"imports" & NoInfer<OperationNeedsUndeclaredServices<"importTitle", NoteSource>>'.
231
+ ```
232
+
233
+ `moduleHandlers(Notes)` builds the module's handler Layer from its operations, and the Layer requires exactly the services in `requires`:
234
+
235
+ ```ts
236
+ import { Layer } from "effect";
237
+ import { moduleHandlers } from "@shivaedev/contract/moduleHandlers.ts";
238
+ import { Notes } from "./notes.ts";
239
+ import { NotesStoreLive } from "./store.ts";
240
+
241
+ export const NotesHandlers = moduleHandlers(Notes).pipe(Layer.provide(NotesStoreLive));
242
+ ```
243
+
244
+ Each operation runs in a span named after the module and the operation, such as `Notes.create`. A query's read policy is checked inside its handler before `run`, with the module's services, so a policy reads a repository directly, as `Get` does above; a live subscription to the query checks the same policy. Failures pass the RPC boundary from `@shivaedev/errors`: a declared rejection reaches the client as itself, an undeclared failure that states `isRetryable` answers `ServiceUnavailable`, and anything else answers `InternalServerError`, for the policy of a live subscription too. A command without `invalidates` publishes only the keys its writes announce.
245
+
246
+ #### The wire and the browser's contract
247
+
248
+ Types are erased, so the success schema and rejection classes the server encodes with and the browser decodes with must exist as values. [`@shivaedev/build`](https://github.com/ShivaeDev/platform/tree/main/packages/build) writes them from each module's `run` types into one file per module under `src/generated/`, which stays out of Git. It is not published yet and no `generate` script exists, so an application outside this repository writes the wire by hand, or its operations declare `success` and `rejections` and the module passes no wire. The module file passes its wire, and every operation that has a wire entry is served with that entry's success and rejections, plus `InternalServerError` and `ServiceUnavailable`, even when the operation declares its own; an operation without an entry is served with what it declares:
249
+
250
+ ```ts
251
+ import { notesWire } from "#generated/modules/notes/notes.ts";
252
+
253
+ export const Notes = defineModule({
254
+ middleware: Caller,
255
+ name: "notes",
256
+ operations: [List, Get, Create],
257
+ requires: [NotesStore],
258
+ wire: notesWire,
259
+ });
260
+ ```
261
+
262
+ The file the generator writes exports the wire, the browser's contract built by `clientContract` from the wire, the copied payloads, `reads` and `invalidates`, and the module's name, middleware, subject and key scope, and it ends with a type-level assertion that the browser's contract and the server module have the same RPCs:
263
+
264
+ ```ts
265
+ import { Schema } from "effect";
266
+ import { Unauthorized } from "@shivaedev/errors/taxonomy.ts";
267
+ import { clientContract } from "@shivaedev/contract/clientContract.ts";
268
+ import type { ClientMatchesModule } from "@shivaedev/contract/clientMatchesModule.ts";
269
+ import type { Notes as NotesModule } from "#modules/notes/notes.ts";
270
+ import { Caller, NoteFields, notes, TitleTaken } from "#modules/notes/model.ts";
271
+
272
+ const Note = Schema.Struct({ createdAt: Schema.Date, id: Schema.Number, title: Schema.String });
273
+
274
+ export const notesWire = {
275
+ create: { rejections: { TitleTaken, Unauthorized }, success: Note },
276
+ list: { rejections: { Unauthorized }, success: Schema.Array(Note) },
277
+ } as const;
278
+
279
+ export const Notes = clientContract({
280
+ commands: { create: { invalidates: () => [notes.list] } },
281
+ middleware: Caller,
282
+ name: "notes",
283
+ payloads: { create: NoteFields },
284
+ queries: { list: { reads: () => [notes.list] } },
285
+ wire: notesWire,
286
+ });
287
+
288
+ export const notesMatchModule: ClientMatchesModule<typeof Notes, typeof NotesModule> = true;
289
+ ```
290
+
291
+ `clientContract` requires a wire entry for every query and command it declares. The browser imports `Notes` from that file and binds it like any contract; it carries no `run`, read policy or service, and its import graph reaches no server code. A command's `invalidates` and a query's `reads` work in the browser exactly as on a contract written by hand. Over RPC's JSON serialization, a `Schema.Date` field arrives as a `Date` equal to the one `run` returned, and a rejection the wire lists arrives as its class. Neither the browser's contract nor an operation without a read policy can be served: `contract()` requires one on every query, and a host refuses a query without one at start-up.
292
+
293
+ The compiler compares the wire with `run` on every type check, exactly as it compares a declared `success` and `rejections`, and a stale file is an error on the module's `name` line that names the operation, one problem per operation: `WireSuccessStale` when the wire's success differs from what `run` returns, by the same comparison as `SuccessDiffersFromRun`, `WireRejectionsStale` when its rejection tags or classes differ from what `run` and a query's read policy raise, other than infrastructure failures, and `OperationMissingFromWire` when an operation declares no success, returns something, and has no wire entry. The browser's assertion fails with `ClientDiffersFromModule`, naming the operations whose RPCs differ. `ClientMatchesModule` compares the operations' payloads, successes and rejections; a stale copy of a query's `reads`, a command's `invalidates` or the key scope in the generated file still compiles; the generator keeps those current, because a change to them makes `shivaedev-build generate --check` report the file stale. A stale wire and a stale browser contract read:
294
+
295
+ ```
296
+ src/test-support/fixtures/invalid/moduleStaleRejection.ts(9,2): error TS2322: Type '"staleRejection"' is not assignable to type '"staleRejection" & NoInfer<WireRejectionsStale<"create", "the generated file is stale; run pnpm generate", "TitleTaken" | "Unauthorized", "Unauthorized">>'.
297
+ src/test-support/fixtures/invalid/staleNotes.ts(17,14): error TS2322: Type 'boolean' is not assignable to type 'ClientDiffersFromModule<"create", "the generated file is stale; run pnpm generate">'.
298
+ ```
299
+
93
300
  ### Whose account a request acts on
94
301
 
95
302
  Set `subject` on a contract to a browser-safe declaration from `@shivaedev/identity/subject.ts`: `selfSubject` selects the session account; `accountSubject({ permission, refusal, deny })` permits another account only with the permission's `any` grant. The declaration applies to the application RPCs and their changes stream. Native middleware carries its typed failures and supplies the branded `Subject` service to handlers and the application services they call. Business payloads need no owner id.
@@ -285,7 +492,7 @@ releaseList();
285
492
  registry.dispose();
286
493
  ```
287
494
 
288
- The successful rename invalidates note 1 and the list. A rejected rename invalidates neither. Bound queries and commands take the schema's decoded payload type; native clients take its constructor input, which can differ when a field has a constructor default. Result and failure types preserve operation rejections, middleware errors and `RpcClientError`.
495
+ The successful rename invalidates note 1 and the list in the browser, and because this client is bound with `live: false`, that invalidation refreshes both queries. A rejected rename invalidates neither. Bound queries and commands take the schema's decoded payload type; native clients take its constructor input, which can differ when a field has a constructor default. Result and failure types preserve operation rejections, middleware errors and `RpcClientError`.
289
496
 
290
497
  The dependency rule is deliberately asymmetric:
291
498
 
@@ -294,9 +501,9 @@ The dependency rule is deliberately asymmetric:
294
501
  | `notes.item(1)` | `"notes:1"` | `"notes:1"` and `"notes"` |
295
502
  | `notes.list` | `"notes"` | `"notes"` |
296
503
 
297
- `readKeys` and `invalidationKeys` from `@shivaedev/changes/keys.ts` produce these native keys and remove duplicates. An item change refreshes that item and its list, preserving other item queries. A list-only invalidation refreshes list queries and leaves item queries alone. These keys match native Reactivity's record-key hashing of `{ notes: [1] }`.
504
+ `readKeys` and `invalidationKeys` from `@shivaedev/changes/keys.ts` produce these native keys and remove duplicates. An item change reaches readers of that item and its list, preserving other item queries. A list-only invalidation reaches list readers and leaves item queries alone. These keys match native Reactivity's record-key hashing of `{ notes: [1] }`.
298
505
 
299
- Client invalidation follows RPC success. Database hosts from `@shivaedev/server` also publish declared command invalidations automatically after the handler succeeds, excluding keys already announced by repository commits, using `transact` from [`sql`](https://github.com/ShivaeDev/platform/tree/main/packages/sql); commit-bound changes belong to [`changes`](https://github.com/ShivaeDev/platform/tree/main/packages/changes).
506
+ The browser invalidates a command's keys after RPC success, together with a key of the command's contract. That local invalidation refreshes queries bound with `live: false`. A query with no keys in the browser, because it leaves out `reads` or its `reads` returns none for `Option.none()`, listens on that contract key instead, so bound with `live: false` it refreshes after every successful command of its contract on that client, including a command that declares no keys. A live bound query, the default on database hosts, gets its refresh from the server push instead: the server reruns it when the command's keys are published there, and the local invalidation only retries its subscription after that subscription failed with something other than `QueryReadDenied` ([Server-pushed live queries](#4-server-pushed-live-queries)). Database hosts from `@shivaedev/server` publish declared command invalidations on the server after the handler succeeds, excluding keys already announced by repository commits, using `transact` from [`sql`](https://github.com/ShivaeDev/platform/tree/main/packages/sql); commit-bound changes belong to [`changes`](https://github.com/ShivaeDev/platform/tree/main/packages/changes).
300
507
 
301
508
  #### Server-only command keys
302
509
 
@@ -331,7 +538,9 @@ Use this helper in hosts from `@shivaedev/server`, or a native RPC host wired wi
331
538
 
332
539
  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
540
 
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.
541
+ `activityScreenSignal(activity)` projects the stream and its `current` Effect into `{ pending, connectionStatus }`. The returned shape is structural and carries no test-story dependency. Stories that need a later live change wait for it with the screen driver's `withLiveAnswer` and `liveAnswers` below, then settle the screen. `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.
542
+
543
+ `liveAnswers(registry, name, query)` from `liveAnswers.ts` projects one bound query's settled answers into `{ name, answered, current }`, for a screen driver's `withLiveAnswer`. A pushed result and an unchanged server rerun each count as an answer, so a story can wait for the push a command causes on a live query after the command itself has settled.
335
544
 
336
545
  ### Query completion
337
546
 
@@ -349,7 +558,7 @@ Mount the query to start it. Wait on `completions` for `completed > before` afte
349
558
 
350
559
  ### Session-owned keys
351
560
 
352
- A self-only feature, such as a user's preferences, reads and changes only the signed-in account's records. Declare its contract with `keyScope: "session"`. The server chooses the account from request-local identity, so payloads carry no owner field, and reads and invalidations name a logical item key for the record:
561
+ A self-only feature, such as a user's preferences, reads and changes only the signed-in account's records. Declare its contract with `keyScope: "session"` and let its handlers read the account from request-local identity, so payloads carry no owner field, and reads and invalidations name a logical item key for the record:
353
562
 
354
563
  ```ts
355
564
  const preferences = collection("preferences", Schema.String);
@@ -389,11 +598,11 @@ Preferences.application.toLayer({
389
598
 
390
599
  `store` is the application's persistence service. No owner or client key scope is accepted from a request. The database app host uses plain repository keys for every subscriber and rechecks each subscriber’s read policy before delivery.
391
600
 
392
- The registry is required for session-scoped bindings. Query atoms and live connections belong in it; command and one-off query Effects execute through it. Explicit streams also run through its client, preserving the session transport and headers; disposing the registry ends those streams. Streams on ordinary contracts use the caller's client. A successful command invalidates its owner's keys, while a rejected command declares no invalidation. Ordinary contracts keep unscoped keys and the two-argument `bind` call.
601
+ The registry is required for session-scoped bindings. Query atoms and live connections belong in it; command and one-off query Effects execute through it. Explicit streams also run through its client, preserving the session transport and headers; disposing the registry ends those streams. Streams on ordinary contracts use the caller's client. A successful command invalidates its registry's prefixed keys, while a rejected command declares no invalidation. Ordinary contracts keep unscoped keys and the two-argument `bind` call.
393
602
 
394
603
  Server subscriptions and committed writes use the same plain record, list and bucket keys, including for `keyScope: "session"`. A background worker needs no request identity or account prefix to refresh a session's query. Matching keys trigger the query's own read policy; authorized reads remain responsible for filtering rows to the viewer. A shared key can therefore trigger authorized rechecks for several accounts. Use model buckets to narrow that fan-out.
395
604
 
396
- Client cache isolation belongs to the owning registry. `bind` supplies its opaque context automatically. Custom client coordination uses these helpers and context type:
605
+ In the browser, `bind` gives each owning registry an opaque id and prefixes every client read and invalidation key of a session-scoped contract with it, so a command in one session's registry refreshes none of another session's queries, even when the registries share one runtime and its Reactivity. The server adds no prefix. Custom client coordination uses these helpers and context type:
397
606
 
398
607
  ```ts
399
608
  import { clientInvalidationKeys, clientReadKeys, type KeyContext } from "@shivaedev/contract/clientKeys.ts";
@@ -427,15 +636,15 @@ Each subscription stores one hash per query in memory in the process holding its
427
636
 
428
637
  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
638
 
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.
639
+ `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. The server then reruns the subscriber's queries and pushes changed results. `Resync` never asks the client to issue reads.
431
640
 
432
641
  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.
433
642
 
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.
643
+ A live query's result stays a native initial result with `waiting: true` from mount until its subscription delivers the first result. 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.
435
644
 
436
645
  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.
437
646
 
438
- `status` exposes `connection`, `failure`, `needsResync` and `pending`. A resume keeps `connection` unchanged and sets `needsResync` until the reopened subscription delivers its first update, while the query results keep their values and report nothing 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.
647
+ `status` exposes `connection`, `failure`, `needsResync` and `pending`. A resume keeps `connection` unchanged and sets `needsResync` until the reopened subscription delivers its first update, while the query results keep their values and report nothing pending. A typed stream rejection settles as `failed`; transport failures and defects retry with the existing jittered exponential backoff. A denied subscription stays refused through matching local invalidations and resume events; it reopens when the viewer changes or the query is refreshed explicitly. A matching local invalidation still retries a subscription that settled with another failure, such as a declared `NotFound`. A query with no keys in the browser has nothing for a local invalidation to match, so such a subscription stays settled through its contract's commands, and an explicit refresh reopens it. 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.
439
648
 
440
649
  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`.
441
650
 
@@ -445,24 +654,21 @@ Server adapters import `LiveServer` from `@shivaedev/contract/live-server/servic
445
654
 
446
655
  Contract groups carry their read-policy guard into native `RpcServer` hosts and Platform’s application host. An ordinary query evaluates its policy once per request, after identity middleware supplies `CurrentViewer` from its validated session. A false policy returns `QueryReadDenied` without running the handler. Native hosts need no policy middleware or guard Layer. Real HTTP stories exercise both hosts with allowed and denied counted policies; they prove this RPC boundary, not an application’s session or deployment policy. Platform’s application host refuses HTTP `$changes` calls with `WebSocketRequired`; subscriptions use its WebSocket protocol. Subscription delivery and pushed reruns continue to check current access.
447
656
 
448
- A query declares its decoded input, result, `readPolicy` and `reads` together. `readPolicy(payload, viewer)` returns an Effect boolean. `viewer` is the session's `Option<{ id: string }>`; the browser does not send the identity. `signedIn` from `readPolicy.ts` allows any signed-in viewer and refuses a signed-out viewer. `QueryReadPolicy<Payload, E, R>` preserves typed failures and required services. Declare policy errors in the query's `rejections`; a failing access check reaches the client as its declared error, including during live reads. Only a successful `false` denies access. [Policy services](#policy-services) explains richer session requirements and where to provide implementations.
657
+ A query declares its decoded input, result and `readPolicy` together, and declares `reads` when its handler's reads do not name its keys, as described below. `readPolicy(payload, viewer)` returns an Effect boolean. `viewer` is the session's `Option<{ id: string }>`; the browser does not send the identity. `signedIn` from `readPolicy.ts` allows any signed-in viewer and refuses a signed-out viewer. `QueryReadPolicy<Payload, E, R>` preserves typed failures and required services. Declare policy errors in the query's `rejections`; a failing access check reaches the client as its declared error, including during live reads. Only a successful `false` denies access. [Policy services](#policy-services) explains richer session requirements and where to provide implementations.
449
658
 
450
659
  ```ts
451
- import { Option, Schema } from "effect";
452
- import { collection } from "@shivaedev/changes/keys.ts";
660
+ import { Schema } from "effect";
453
661
  import { query } from "@shivaedev/contract/operation.ts";
454
662
  import { signedIn } from "@shivaedev/contract/readPolicy.ts";
455
663
 
456
- const notes = collection("notes", Schema.Number, { userId: Schema.String });
457
664
  const Mine = query("mine", {
458
665
  payload: { title: Schema.String },
459
666
  success: Schema.Array(Schema.String),
460
667
  readPolicy: signedIn,
461
- reads: (_input, viewer) => (Option.isSome(viewer) ? [notes.bucket.userId(viewer.value.id)] : []),
462
668
  });
463
669
  ```
464
670
 
465
- On a repository model, annotate tenant fields with `bucket()` from `@shivaedev/changes/buckets.ts` so writes announce the affected buckets. For an admin page spanning every tenant, declare `readsCollections` beside a permission read policy:
671
+ `Mine` declares no `reads`. Its handler reads `findMany({ where: { userId } })` through a `@shivaedev/sql` repository, which names the viewer's `userId` bucket, so the live query listens on that bucket. On a repository model, annotate tenant fields with `bucket()` from `@shivaedev/changes/buckets.ts` so writes announce the affected buckets. For an admin page spanning every tenant, declare `readsCollections` beside a permission read policy:
466
672
 
467
673
  ```ts
468
674
  import { Effect, Schema } from "effect";
@@ -483,7 +689,7 @@ const AllNotes = query("allNotes", {
483
689
  });
484
690
  ```
485
691
 
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 the server reports an untyped declaration with that policy as an Effect defect during host startup. The server also refuses collection queries changed to an ordinary policy after construction as `QueryReadDenied`. Tenant-facing queries use `notes.bucket.userId(viewerId)` instead.
692
+ 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 the server reports an untyped declaration with that policy as an Effect defect during host startup. The server also refuses collection queries changed to an ordinary policy after construction as `QueryReadDenied`. A tenant-facing query instead filters its repository read by the tenant column, which names that tenant's bucket.
487
693
 
488
694
  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.
489
695
 
@@ -511,7 +717,13 @@ const Timeline = query("timeline", {
511
717
  });
512
718
  ```
513
719
 
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.
720
+ 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. After every rerun the server evaluates `reads` and `serverReads` again and replaces the subscription's registrations, so the keys follow the workspace while the subscription stays open. A list that joins is watched once a rerun has seen it, so the write that adds a list must publish a key the query already reads, such as a workspace bucket that `serverReads` also returns. Once a rerun has seen a list leave, that list's writes no longer rerun the query. The browser never runs `serverReads`; matching changes rerun the affected query on the server.
721
+
722
+ A handler can also name keys while it runs, with `recordRead(keys)` from `@shivaedev/changes/readRecorder.ts`, before the statement that reads by them. The live subscription registers each recorded key with the host the moment it is recorded, before that statement is sent, and matches it alongside the keys from `reads`, `serverReads` and `readsCollections`. A key recorded on a rerun is therefore watched before its read, where a `serverReads` key is watched only once the rerun has finished. A key that is already registered is not registered again, so a handler that reads the same row many times registers its key once. Nothing the query's read policy records counts, whether through repository reads or its own `recordRead` calls: permission changes refresh nothing live, so a write to a row only the policy reads does not rerun the query.
723
+
724
+ A query may leave out `reads`. Declared keys are used exactly as declared, even when `reads` returns `[]`. A query that declares none, with no `reads`, `serverReads` or `readsCollections`, listens on what its repository reads from `@shivaedev/sql` pin: a row, a bucket, or the whole table for an unfiltered read. The [sql guide](https://github.com/ShivaeDev/platform/blob/main/packages/sql/README.md#live-reads-listen-on-what-they-filter-by) lists which key each filter pins. Keys a handler records itself with `recordRead` count either way. A raw SQL read written with `readSql` from `@shivaedev/sql/readSql.ts` listens on the bucket and row keys interpolated as its parameters, as the [sql guide](https://github.com/ShivaeDev/platform/blob/main/packages/sql/README.md#a-raw-read-names-its-key-at-its-parameter) shows. A read through the native `sql` tag records no key, so a query whose handler reads only that way and leaves out `reads` registers nothing and never reruns; such a query keeps its `reads`. When a query that declares no keys finishes a run with no key recorded, the host logs a warning that names the query and says to mark its raw reads or declare `reads`; the subscription carries on, because a handler may read nothing for some payloads. Declare `reads: () => []` for a query that reads nothing, which logs no warning. The browser never sees the keys a host records, so there a query without `reads` has no keys, like one with `reads: () => []`; [read and change](#3-every-day-read-and-change) says how a `live: false` binding refreshes such a query, and [server-pushed live queries](#4-server-pushed-live-queries) when its failed subscription reopens.
725
+
726
+ Live query handlers read at READ COMMITTED, PostgreSQL's default, which statements and plain Effect SQL transactions keep: each statement takes its snapshot after the key recorded before it is registered, so a commit to that key is either read by the statement or heard afterwards. A handler that opens a REPEATABLE READ or SERIALIZABLE transaction keeps one snapshot from its first statement, so it declares its keys in `reads` or `serverReads` instead. The [changes guide](https://github.com/ShivaeDev/platform/blob/main/packages/changes/README.md#record-what-a-live-read-listens-on) shows the call.
515
727
 
516
728
  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:
517
729
 
@@ -650,31 +862,37 @@ Observe raw result streams with `watchHints` from `@shivaedev/test-kits/contract
650
862
 
651
863
  Import the module that defines the name; the package has no root entry.
652
864
 
653
- | Module | Functions and schemas |
654
- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
655
- | `operation.ts` | `query(name, { payload?, success?, rejections?, readPolicy, reads, serverReads? })`; `command(name, { payload?, success?, rejections?, invalidates })`; `stream(name, { payload?, success, rejections?, reads })`. |
656
- | `contract.ts` | `contract(name, { queries?, commands?, streams?, keyScope? })`, returning a native RPC group with `declaration: { name, queries, commands, streams, keyScope }`. |
657
- | `rejection.ts` | `fieldRejection(struct, fields?)`; lower-level `rejectionSet(specs)`, which constructs the rejection classes, union schema and failure helpers used by operations. |
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. |
659
- | `clientKeys.ts` | `KeyContext`, `clientReadKeys`, `clientInvalidationKeys`: registry-local cache keys for custom clients. |
660
- | `live.ts` | `LiveHint` schema; `live(runtime, { stream, keyContext?, resume?, retryDelay?, retryKeys? })`, exposing `connection`, `paused` and `status`. |
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. |
662
- | `live-server/service.ts` | `LiveServer`, the shared live server service. |
663
- | `live-server/layer.ts` | `liveServerLayer`, providing `LiveServer` and its dispatcher dependency, requiring `Reactivity`. |
664
- | `live-server/subscribe.ts` | `subscribe(subscription, read?)`, an Effect requiring `LiveServer` that returns an authorized subscription Stream with its policy and query-runner requirements. |
665
- | `makeLiveServer.ts` | `makeLiveServer`, an Effect requiring `Reactivity` that creates scoped server hint streams and a `resync` Effect. |
666
- | `readPolicy.ts` | `QueryReadPolicy`, `Viewer`, `signedIn`, `CurrentViewer`; `authorizeReads(effect, request, viewer)` for direct handler reruns outside RPC middleware. |
667
- | `ReadPolicyGuard.ts` | `ReadPolicyGuard`, the defaulted middleware reference attached to contract queries; `readPolicyGuardLayer({ websocket? })`, an optional override that refuses HTTP `$changes` calls by default. |
668
- | `validateReadPolicies.ts` | `validateReadPolicies(group)`, an Effect that fails with `MissingReadPolicies` when any served or subscribable query omits its policy. |
669
- | `readPolicyErrors.ts` | `MissingReadPolicies` (boot), `MissingReadPolicy` (native-server request fallback) and `QueryReadDenied`. |
670
- | `CommandGuard.ts` | `guardCommands(group)` places command publication inside viewer-providing middleware; `commandGuardLayer(boundary)` evaluates declared invalidations for that viewer and delegates publication to the host boundary. |
671
- | `commandResult.ts` | `commandResult({ result, invalidates })` contributes server-only keys from a guarded command handler and returns only its success value. |
672
- | `serverMetadata.ts` | `KeyScope`, `QueryDefinition.definition`, `CommandInvalidation.invalidates`, `ChangesQueries.queries`, `ChangesQueries.resolve(references)` and `changesRpc(name, queries)` for server adapters. |
673
- | `queryKeys.ts` | `queryKeys(queries, references, viewer?)` authorizes references and resolves payload and server-derived keys using the provided services. |
674
- | `QueryServerReads.ts` | `QueryServerReads<Payload, E, R>`, the server-only resolver type. |
675
- | `resume.ts` | `resumeSignal({ window?, native? })`, returning a native numeric signal atom. |
676
- | `querySignals.ts` | `querySignals(query)` exposes completion counts and subscription status as a native atom. |
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. |
865
+ | Module | Functions and schemas |
866
+ | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
867
+ | `operation.ts` | `query(name, { payload?, success?, rejections?, readPolicy, reads?, serverReads? })`; `command(name, { payload?, success?, rejections?, invalidates })`; `query(name, { payload?, *run, readPolicy?, reads?, serverReads?, readsCollections?, success?, rejections? })` and `command(name, { payload?, *run, invalidates?, success?, rejections? })` with an Effect-returning `run`; `stream(name, { payload?, success, rejections?, reads })`. |
868
+ | `contract.ts` | `contract(name, { queries?, commands?, streams?, keyScope? })`, returning a native RPC group with `declaration: { name, queries, commands, streams, keyScope }`. |
869
+ | `defineModule.ts` | `defineModule({ name, operations, requires, middleware?, subject?, keyScope?, wire? })`, returning the module's contract. |
870
+ | `moduleHandlers.ts` | `moduleHandlers(module)`, the module's handler Layer, requiring exactly its `requires`. |
871
+ | `clientContract.ts` | `clientContract({ name, wire, payloads?, queries?, commands?, middleware?, subject?, keyScope? })`, the browser's contract of a module that generated files build. |
872
+ | `clientMatchesModule.ts` | `ClientMatchesModule<Client, Module>`, `true` when the browser's contract and the server module have the same RPCs, else `ClientDiffersFromModule`. |
873
+ | `rejection.ts` | `fieldRejection(struct, fields?)`; lower-level `rejectionSet(specs)`, which constructs the rejection classes, union schema and failure helpers used by operations. |
874
+ | `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. |
875
+ | `clientKeys.ts` | `KeyContext`, `clientReadKeys`, `clientInvalidationKeys`: registry-local cache keys for custom clients. |
876
+ | `live.ts` | `LiveHint` schema; `live(runtime, { stream, keyContext?, resume?, retryDelay?, retryKeys? })`, exposing `connection`, `paused` and `status`; `isLiveConnection(atom)` tells whether an atom is such a `connection`, which waits for as long as its subscription runs. |
877
+ | `querySubscription.ts` | `querySubscription(rpc, references, viewer)` checks each referenced query, resolves its payload and server-derived keys, and captures its scopes and ongoing authorization. |
878
+ | `live-server/service.ts` | `LiveServer`, the shared live server service. |
879
+ | `live-server/layer.ts` | `liveServerLayer`, providing `LiveServer` and its dispatcher dependency, requiring `Reactivity`. |
880
+ | `live-server/subscribe.ts` | `subscribe(subscription, read?)`, an Effect requiring `LiveServer` that returns an authorized subscription Stream with its policy and query-runner requirements. |
881
+ | `makeLiveServer.ts` | `makeLiveServer`, an Effect requiring `Reactivity` that creates scoped server hint streams and a `resync` Effect. |
882
+ | `readPolicy.ts` | `QueryReadPolicy`, `Viewer`, `signedIn`, `CurrentViewer`; `authorizeReads(effect, request, viewer)` for direct handler reruns outside RPC middleware. |
883
+ | `ReadPolicyGuard.ts` | `ReadPolicyGuard`, the defaulted middleware reference attached to contract queries; `readPolicyGuardLayer({ websocket? })`, an optional override that refuses HTTP `$changes` calls by default. |
884
+ | `validateReadPolicies.ts` | `validateReadPolicies(group)`, an Effect that fails with `MissingReadPolicies` when any served or subscribable query omits its policy. |
885
+ | `readPolicyErrors.ts` | `MissingReadPolicies` (boot), `MissingReadPolicy` (native-server request fallback) and `QueryReadDenied`. |
886
+ | `CommandGuard.ts` | `guardCommands(group)` places command publication inside viewer-providing middleware; `commandGuardLayer(boundary)` evaluates declared invalidations for that viewer and delegates publication to the host boundary. |
887
+ | `commandResult.ts` | `commandResult({ result, invalidates })` contributes server-only keys from a guarded command handler and returns only its success value. |
888
+ | `serverMetadata.ts` | `QueryDefinition.definition`, `CommandInvalidation.invalidates`, `ChangesQueries.queries`, `ChangesQueries.resolve(references)` and `changesRpc(name, queries)` for server adapters. |
889
+ | `queryKeys.ts` | `queryKeys(queries, references, viewer?)` authorizes references and resolves payload and server-derived keys using the provided services. |
890
+ | `QueryServerReads.ts` | `QueryServerReads<Payload, E, R>`, the server-only resolver type. |
891
+ | `resume.ts` | `resumeSignal({ window?, native? })`, returning a native numeric signal atom. |
892
+ | `querySignals.ts` | `querySignals(query)` exposes completion counts and subscription status as a native atom. |
893
+ | `retainQuery.ts` | `queryRuntime(query)` returns the atom runtime a bound query runs on, so a reader can schedule work on the same Effect `Clock`. |
894
+ | `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 for screen waits. |
895
+ | `liveAnswers.ts` | `liveAnswers(registry, name, query)` counts a bound query's settled answers, pushed or unchanged, for screen waits. |
678
896
 
679
897
  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.
680
898
 
@@ -0,0 +1,8 @@
1
+ import { Layer } from "effect";
2
+ import { Rpc } from "effect/rpc";
3
+ import type { Declared } from "#contract.ts";
4
+ import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
5
+ export declare function servedHandlers(application: {
6
+ readonly requests: ReadonlyMap<string, Rpc.Any>;
7
+ }, declaration: Declared<string, readonly QueryShape[], readonly CommandShape[], readonly StreamShape[], "session" | undefined>): Layer.Layer<Rpc.Handler<string>, never, unknown>;
8
+ //# sourceMappingURL=servedHandlers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"servedHandlers.d.ts","sourceRoot":"","sources":["../../src/adapters/servedHandlers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,EAAe,MAAM,QAAQ,CAAC;AACpD,OAAO,EAAE,GAAG,EAAuB,MAAM,YAAY,CAAC;AAItD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AA6C3E,wBAAgB,cAAc,CAC7B,WAAW,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,CAAA;CAAE,EAChE,WAAW,EAAE,QAAQ,CAAC,MAAM,EAAE,SAAS,UAAU,EAAE,EAAE,SAAS,YAAY,EAAE,EAAE,SAAS,WAAW,EAAE,EAAE,SAAS,GAAG,SAAS,CAAC,GAC1H,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAclD"}