@rindle/narrator 0.4.3

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # @rindle/narrator
2
+
3
+ Turn a Rindle query's flat-change stream into agent-ready prose.
4
+
5
+ A standing query (`defineQuery`) is a live, incrementally-maintained subscription. As base-table
6
+ writes flow in, the engine emits per-query `FlatChange` diffs (positional, indexed into the view's
7
+ relationship tree). `@rindle/narrator` lifts those into named rows and renders them through small,
8
+ per-query templates into **salience-tagged semantic events** — the "operational context" an agent
9
+ reads — and groups one commit's effects under the **mutator that caused them**.
10
+
11
+ ```
12
+ base writes ──▶ engine maintains the query ──▶ FlatChange[] diffs
13
+
14
+ resolveChange (@rindle/client) ◀────────┘ positional → named rows
15
+
16
+ per-query templates (your registry) named rows → prose
17
+
18
+ SemanticEvent[] ──▶ digest() salience-ranked prompt block
19
+ ```
20
+
21
+ ## Pipeline
22
+
23
+ 1. **Resolve** — `resolveChange(schema, change)` (in `@rindle/client`) is the pure inverse of the
24
+ wire encoder: it names positional cells against the query's `WireSchema` (shipped on its `hello`
25
+ frame, also readable as `view.schema`), surfaces the parent row and the exact aggregate value for
26
+ a `countAs` slot, and lets you read a nested sub-row off an `add` node.
27
+ 2. **Render** — `createNarrator(registry)` matches each resolved change to a template keyed by
28
+ `defineQuery` name + op (+ count alias) and emits a `SemanticEvent` (with `salience`:
29
+ `alert` / `info` / `ambient`). `digest(events)` folds a batch into a salience-ranked block.
30
+ 3. **Attribute** — `narrateCommit(...)` / `createCausalTap(...)` group a commit's per-query batches
31
+ under a `Cause` (the named mutator + args), rendering one append-ready block per commit.
32
+
33
+ ## Usage
34
+
35
+ ```ts
36
+ import { createNarrator, attachCausalTap, type NarratorRegistry, type QueryBinding } from "@rindle/narrator";
37
+
38
+ // The only hand-written part: per-query templates. The names do the work, so this stays small.
39
+ const NARRATORS: NarratorRegistry = {
40
+ unseatedGuests: {
41
+ salience: "alert",
42
+ root: {
43
+ add: ({ sub, context }) => `${sub("guest")?.name ?? "Someone"} is unseated for ${context.subject}.`,
44
+ remove: ({ context }) => `A guest got a seat for ${context.subject}.`,
45
+ },
46
+ },
47
+ };
48
+
49
+ const narrator = createNarrator(NARRATORS);
50
+
51
+ // Single query: the materialized view is self-describing — `qid` + `schema` + `data`.
52
+ const view = store.materialize(unseatedGuestsQuery({ eventId }));
53
+ const off = store.subscribeChanges((qid, ev) => {
54
+ if (qid !== view.qid || !view.schema) return;
55
+ const changes = ev.type === "snapshot" ? ev.adds : ev.type === "batch" ? ev.events : [];
56
+ console.log(narrator.digest(narrator.narrate("unseatedGuests", view.schema, changes, ev.type === "snapshot" ? "snapshot" : "batch", { subject: "the Smith wedding" })));
57
+ });
58
+
59
+ // Causal: bind each live query, wrap a mutator call.
60
+ const bindings = new Map<number, QueryBinding>([[view.qid, { query: "unseatedGuests", schema: view.schema!, ctx: { subject: "the Smith wedding" } }]]);
61
+ const { tap } = attachCausalTap(store, narrator, bindings, { causes: { seatGuest: () => "Seated a guest" } });
62
+ tap.begin({ mutator: "seatGuest", args });
63
+ await store.write((tx) => /* … */ undefined);
64
+ const block = tap.end(); // one CausalDigest for the whole commit
65
+ ```
66
+
67
+ ## Why subscribe to the store, not the view?
68
+
69
+ Narration drives off `store.subscribeChanges` — the raw, qid-tagged `ChangeEvent` stream — rather
70
+ than `view.subscribe`. That looks backwards (the view is right there, self-describing), but the view
71
+ is the wrong seam for three concrete reasons:
72
+
73
+ 1. **The view's `subscribe` carries the folded snapshot, not the diff.** `view.subscribe(d => …)`
74
+ fires with `data: readonly R[]` — the projected tree *after* the `FlatChange[]` has been applied
75
+ and discarded. The narrator's whole job is the diff (`resolveChange` → named rows → per-op
76
+ templates); the view hands you the one thing it throws away. Driving narration off the view would
77
+ mean adding a second, diff-bearing channel to it.
78
+ 2. **Synchronous backends emit the first frame before the view handle exists.** The in-process
79
+ wasm/replica backend dispatches a query's first `hello`+`snapshot` *synchronously inside*
80
+ `registerQuery`, i.e. before `materialize()` returns the view to its caller. `subscribeChanges` is
81
+ attached up front (before `materialize`) precisely so it catches those frames; a per-view
82
+ subscription has no handle to subscribe to yet when they fire, so it misses the initial snapshot.
83
+ 3. **A commit fans out across many queries; the causal tap is a fan-in over all of them.** One
84
+ mutator invocation is one engine commit that returns per-query batches for *every* affected query.
85
+ `createCausalTap` buffers them in a single qid-keyed map and folds them into one block under the
86
+ cause. That correlation is store-level by nature — per-view, you'd re-aggregate N independent
87
+ callbacks back into the qid buffer the store already gives you, and views churn (a changed
88
+ limit/filter destroys + rebuilds the view) while the store subscription rides through.
89
+
90
+ The store fires each change listener *after* the fold (`onEvent` → `applyChanges` → listeners), so a
91
+ listener that wants the post-apply snapshot can still re-read the view by `qid`. Two refinements stay
92
+ open: making the `removedSubtree` opt-in per-qid (today one global counter enriches every view's
93
+ removals once any consumer asks), and widening the change callback to hand the post-fold view
94
+ alongside the diff so a template needing list context doesn't have to look the view up itself.
95
+
96
+ ## What lives where
97
+
98
+ - **Position→name resolution** is in `@rindle/client` (`resolveChange`, `subRow`, `ResolvedChange`,
99
+ `NamedRow`) — it's broadly useful to anything consuming a `FlatChange`.
100
+ - **The narration framework** (registry shape, `createNarrator`, `digest`, salience, the causal
101
+ digest) is here.
102
+ - **The templates and cause headlines** are yours — co-locate them with the queries and mutators.
@@ -0,0 +1,80 @@
1
+ import type { ArrayView, ChangeEvent, FlatChange, QueryId, WireSchema } from "@rindle/client";
2
+ import { type NarrateContext, type Narrator, type Salience, type SemanticEvent } from "./narrator.ts";
3
+ /** The cause: a named mutator + its args (the same `(name, args)` the optimistic envelope carries). */
4
+ export interface Cause {
5
+ mutator: string;
6
+ args?: unknown;
7
+ }
8
+ /** What a subscribed query needs to be narrated: its `defineQuery` name, its `WireSchema` (from the
9
+ * query's `hello` frame / `view.schema`), and ctx. (One per live `materialize()`, keyed by the
10
+ * engine `queryId`.) */
11
+ export interface QueryBinding {
12
+ query: string;
13
+ schema: WireSchema;
14
+ ctx?: NarrateContext;
15
+ }
16
+ /** One commit's per-query batch — exactly the `tx.commit()` / backend-dispatch element shape. */
17
+ export interface CommitBatch {
18
+ queryId: QueryId;
19
+ events: FlatChange[];
20
+ }
21
+ /** Render the cause headline from a mutator name. Co-locate these with the mutators, the way
22
+ * narrators are co-located with queries; absent ⇒ the generic `mutator(k=v, …)` fallback. */
23
+ export type CauseTemplate = (args: unknown) => string;
24
+ /** The narrated effects of the commit on ONE query (suppressed/ambient nulls already dropped). */
25
+ export interface CausalEffect {
26
+ query: string;
27
+ events: SemanticEvent[];
28
+ }
29
+ export interface CausalDigest {
30
+ cause: Cause;
31
+ /** Highest salience across all effects (`ambient` when there are none). */
32
+ salience: Salience;
33
+ /** Only queries with ≥1 narratable effect, ordered by salience then name. */
34
+ effects: CausalEffect[];
35
+ /** The append-ready block (cause headline + indented effect lines); `""` when nothing narratable. */
36
+ text: string;
37
+ }
38
+ export interface DigestOpts {
39
+ /** Per-mutator cause headlines (keyed by mutator name). */
40
+ causes?: Record<string, CauseTemplate>;
41
+ /** Emit the cause headline even when the commit had no narratable effect (default false). */
42
+ includeEmpty?: boolean;
43
+ }
44
+ /** Group one commit's batches under its cause and render the block. */
45
+ export declare function narrateCommit(narrator: Narrator, bindings: ReadonlyMap<QueryId, QueryBinding>, cause: Cause, batches: readonly CommitBatch[], opts?: DigestOpts): CausalDigest;
46
+ /** One commit's correlator. Buffer a commit's per-query batches between {@link CausalTap.begin} and
47
+ * {@link CausalTap.end}, then fold them into a {@link CausalDigest} under the in-flight cause. */
48
+ export interface CausalTap {
49
+ /** Mark the start of a mutator's commit; clears any prior buffer. */
50
+ begin(cause: Cause): void;
51
+ /** Feed one raw change frame (wire `subscribeChanges((qid, ev) => tap.capture(qid, ev))`). Only
52
+ * `batch` frames within an active `begin`/`end` window are buffered; `hello`/`snapshot` ignored. */
53
+ capture(qid: QueryId, ev: ChangeEvent): void;
54
+ /** Close the window and render the digest (or `null` if no `begin` is active). */
55
+ end(): CausalDigest | null;
56
+ }
57
+ /**
58
+ * Correlate a store's change frames with the mutator currently in flight. The local /
59
+ * optimistic-prediction path dispatches a commit's batches synchronously inside `mutate()`, so:
60
+ *
61
+ * tap.begin({ mutator: "seatGuest", args });
62
+ * await store.write(tx => …); // subscribeChanges fires → tap.capture(qid, ev)
63
+ * const digest = tap.end(); // one CausalDigest for the whole commit
64
+ *
65
+ * Wire `capture` into {@link attachCausalTap} (or directly into `store.subscribeChanges`).
66
+ */
67
+ export declare function createCausalTap(narrator: Narrator, bindings: ReadonlyMap<QueryId, QueryBinding>, opts?: DigestOpts): CausalTap;
68
+ /** The minimal store surface {@link attachCausalTap} needs — the supported public change stream.
69
+ * The listener's third arg is the post-fold {@link ArrayView} for the qid (always the plural view);
70
+ * the causal tap ignores it, but the seam carries it for consumers that want list context. */
71
+ export interface ChangeStream {
72
+ subscribeChanges(listener: (qid: QueryId, ev: ChangeEvent, view?: ArrayView<unknown>) => void): () => void;
73
+ }
74
+ /** Create a {@link CausalTap} and wire its `capture` into a store's {@link ChangeStream.subscribeChanges}.
75
+ * Returns the tap (call `begin`/`end` around each mutator) plus a `detach` to stop listening. */
76
+ export declare function attachCausalTap(store: ChangeStream, narrator: Narrator, bindings: ReadonlyMap<QueryId, QueryBinding>, opts?: DigestOpts): {
77
+ tap: CausalTap;
78
+ detach: () => void;
79
+ };
80
+ //# sourceMappingURL=causal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"causal.d.ts","sourceRoot":"","sources":["../src/causal.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE9F,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,QAAQ,EACb,KAAK,QAAQ,EACb,KAAK,a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IACrE,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAC1B;yGACqG;IACrG,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,WAAW,GAAG,IAAI,CAAC;IAC7C,kFAAkF;IAClF,GAAG,IAAI,YAAY,GAAG,IAAI,CAAC;CAC5B;AAED;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,EAC5C,IAAI,GAAE,UAAe,GACpB,SAAS,CAuBX;AAED;;+FAE+F;AAC/F,MAAM,WAAW,YAAY;IAC3B,gBAAgB,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,WAAW,EAAE,IAAI,CAAC,EAAE,SAAS,CAAC,OAAO,CAAC,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CAC5G;AAED;kGACkG;AAClG,wBAAgB,eAAe,CAC7B,KAAK,EAAE,YAAY,EACnB,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,EAC5C,IAAI,GAAE,UAAe,GACpB;IAAE,GAAG,EAAE,SAAS,CAAC;IAAC,MAAM,EAAE,MAAM,IAAI,CAAA;CAAE,CAIxC"}
package/dist/causal.js ADDED
@@ -0,0 +1,115 @@
1
+ // Causal digest — group ONE commit's effects under the named mutator that caused them.
2
+ //
3
+ // In rindle a mutator invocation is one engine commit, and a commit returns per-query batches of
4
+ // FlatChanges. So "cause → effects" is a free join: the mutator name+args is the cause, every batch
5
+ // from that commit is an effect. We narrate each effect through the per-query templates
6
+ // (narrator.ts) and render one block:
7
+ //
8
+ // ↳ Seated a guest (seatGuest guestId=g1, tableId=t7)
9
+ // ⚠️ Jane Doe got a seat for the Smith wedding.
10
+ // • You're seated at Head Table, seat 3.
11
+ //
12
+ // That block is also the natural APPEND UNIT for the cache-coherent context story: one commit, one
13
+ // immutable block appended to the trunk — never a rewrite of earlier turns.
14
+ //
15
+ // Two layers: `narrateCommit` is a pure (bindings + cause + batches) → CausalDigest function; the
16
+ // live-store glue (`createCausalTap` / `attachCausalTap`) wraps a mutator call (begin → mutate →
17
+ // end) and feeds it off the store's supported `subscribeChanges` stream.
18
+ import { SALIENCE_MARK, salienceRank, } from "./narrator.js";
19
+ // ----------------------------- rendering -----------------------------
20
+ function formatArgs(args) {
21
+ if (args === undefined || args === null)
22
+ return "";
23
+ if (typeof args !== "object")
24
+ return String(args);
25
+ const parts = Object.entries(args).map(([k, v]) => {
26
+ const s = typeof v === "string" ? v : JSON.stringify(v);
27
+ return `${k}=${s && s.length > 24 ? s.slice(0, 23) + "…" : s}`;
28
+ });
29
+ return parts.join(", ");
30
+ }
31
+ function causeHeadline(cause, causes) {
32
+ const tmpl = causes?.[cause.mutator];
33
+ if (tmpl)
34
+ return tmpl(cause.args);
35
+ const a = formatArgs(cause.args);
36
+ return `${cause.mutator}(${a})`;
37
+ }
38
+ /** Group one commit's batches under its cause and render the block. */
39
+ export function narrateCommit(narrator, bindings, cause, batches, opts = {}) {
40
+ const effects = [];
41
+ let maxRank = -1;
42
+ let salience = "ambient";
43
+ for (const batch of batches) {
44
+ const b = bindings.get(batch.queryId);
45
+ if (!b || batch.events.length === 0)
46
+ continue;
47
+ const events = narrator.narrate(b.query, b.schema, batch.events, "batch", b.ctx).filter((e) => e.text);
48
+ if (events.length === 0)
49
+ continue;
50
+ effects.push({ query: b.query, events });
51
+ for (const e of events) {
52
+ if (salienceRank(e.salience) > maxRank) {
53
+ maxRank = salienceRank(e.salience);
54
+ salience = e.salience;
55
+ }
56
+ }
57
+ }
58
+ // Strongest-first, then by query name; lines within a query keep engine order.
59
+ effects.sort((x, y) => salienceRank(top(y)) - salienceRank(top(x)) || (x.query < y.query ? -1 : 1));
60
+ let text = "";
61
+ if (effects.length > 0 || opts.includeEmpty) {
62
+ const lines = [`↳ ${causeHeadline(cause, opts.causes)}`];
63
+ for (const eff of effects) {
64
+ for (const e of eff.events)
65
+ lines.push(` ${SALIENCE_MARK[e.salience]} ${e.text}`);
66
+ }
67
+ text = lines.join("\n");
68
+ }
69
+ return { cause, salience, effects, text };
70
+ }
71
+ const top = (eff) => eff.events.reduce((acc, e) => (salienceRank(e.salience) > salienceRank(acc) ? e.salience : acc), "ambient");
72
+ /**
73
+ * Correlate a store's change frames with the mutator currently in flight. The local /
74
+ * optimistic-prediction path dispatches a commit's batches synchronously inside `mutate()`, so:
75
+ *
76
+ * tap.begin({ mutator: "seatGuest", args });
77
+ * await store.write(tx => …); // subscribeChanges fires → tap.capture(qid, ev)
78
+ * const digest = tap.end(); // one CausalDigest for the whole commit
79
+ *
80
+ * Wire `capture` into {@link attachCausalTap} (or directly into `store.subscribeChanges`).
81
+ */
82
+ export function createCausalTap(narrator, bindings, opts = {}) {
83
+ let cause = null;
84
+ const buf = new Map();
85
+ return {
86
+ begin(c) {
87
+ cause = c;
88
+ buf.clear();
89
+ },
90
+ capture(qid, ev) {
91
+ if (!cause || ev.type !== "batch")
92
+ return; // hello/snapshot aren't commit effects
93
+ const list = buf.get(qid) ?? [];
94
+ list.push(...ev.events);
95
+ buf.set(qid, list);
96
+ },
97
+ end() {
98
+ if (!cause)
99
+ return null;
100
+ const batches = [...buf].map(([queryId, events]) => ({ queryId, events }));
101
+ const digest = narrateCommit(narrator, bindings, cause, batches, opts);
102
+ cause = null;
103
+ buf.clear();
104
+ return digest;
105
+ },
106
+ };
107
+ }
108
+ /** Create a {@link CausalTap} and wire its `capture` into a store's {@link ChangeStream.subscribeChanges}.
109
+ * Returns the tap (call `begin`/`end` around each mutator) plus a `detach` to stop listening. */
110
+ export function attachCausalTap(store, narrator, bindings, opts = {}) {
111
+ const tap = createCausalTap(narrator, bindings, opts);
112
+ const detach = store.subscribeChanges((qid, ev) => tap.capture(qid, ev));
113
+ return { tap, detach };
114
+ }
115
+ //# sourceMappingURL=causal.js.map
@@ -0,0 +1 @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AAM,GAAG,GAAG,eAAe,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;IACtD,MAAM,MAAM,GAAG,KAAK,CAAC,gBAAgB,CAAC,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC;IACzE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC;AACzB,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { createNarrator, SALIENCE_MARK, salienceRank, } from "./narrator.ts";
2
+ export type { NamedRow, NarrateContext, Narrator, NarratorRegistry, QueryNarrator, ResolvedChange, Salience, SemanticEvent, Template, TemplateCtx, } from "./narrator.ts";
3
+ export { attachCausalTap, createCausalTap, narrateCommit, } from "./causal.ts";
4
+ export type { Cause, CausalDigest, CausalEffect, CausalTap, CauseTemplate, ChangeStream, CommitBatch, DigestOpts, QueryBinding, } from "./causal.ts";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,cAAc,EACd,aAAa,EACb,YAAY,GACb,MAAM,eAAe,CAAC;AACvB,YAAY,EACV,QAAQ,EACR,cAAc,EACd,QAAQ,EACR,gBAAgB,EAChB,aAAa,EACb,cAAc,EACd,QAAQ,EACR,aAAa,EACb,QAAQ,EACR,WAAW,GACZ,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,eAAe,EACf,eAAe,EACf,aAAa,GACd,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,KAAK,EACL,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,aAAa,EACb,YAAY,EACZ,WAAW,EACX,UAAU,EACV,YAAY,GACb,MAAM,aAAa,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // @rindle/narrator — turn a Rindle query's flat-change stream into agent-ready prose.
2
+ //
3
+ // Pipeline: a backend's per-query `FlatChange`s → `resolveChange` (@rindle/client) lifts each into
4
+ // NAMED rows → per-query templates render salience-tagged `SemanticEvent`s → `digest()` folds a
5
+ // batch into a prompt block. `narrateCommit` / `createCausalTap` additionally group one commit's
6
+ // effects under the named mutator that caused them. Drive it off a live store with the supported
7
+ // `store.subscribeChanges` seam (and read each query's `WireSchema` from `view.schema`).
8
+ export { createNarrator, SALIENCE_MARK, salienceRank, } from "./narrator.js";
9
+ export { attachCausalTap, createCausalTap, narrateCommit, } from "./causal.js";
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;AACtF,EAAE;AACF,mGAAmG;AACnG,gGAAgG;AAChG,iGAAiG;AACjG,iGAAiG;AACjG,yFAAyF;AAEzF,OAAO,EACL,cAAc,EACd,aAAa,EACb,YAAY,GACb,MAAM,eAAe,CAAC;AAcvB,OAAO,EACL,eAAe,EACf,eAAe,EACf,aAAa,GACd,MAAM,aAAa,CAAC"}
@@ -0,0 +1,55 @@
1
+ import { type FlatChange, type NamedRow, type ResolvedChange, type WireSchema } from "@rindle/client";
2
+ export type { NamedRow, ResolvedChange };
3
+ export type Salience = "alert" | "info" | "ambient";
4
+ /** Context a template may interpolate — e.g. a human label for the subscription's subject. */
5
+ export interface NarrateContext {
6
+ /** A human name for what the query is scoped to ("the Smith wedding"). */
7
+ subject?: string;
8
+ [k: string]: unknown;
9
+ }
10
+ export interface TemplateCtx {
11
+ row: NamedRow;
12
+ old?: NamedRow;
13
+ /** The parent row, for an aggregate/nested change (e.g. the `ticket_type` behind a `sold` count). */
14
+ parent?: NamedRow;
15
+ /** Resolve a named sub-row of the change (only populated on `add`). */
16
+ sub: (alias: string) => NamedRow | null;
17
+ aggregate?: ResolvedChange["aggregate"];
18
+ context: NarrateContext;
19
+ }
20
+ export type Template = (ctx: TemplateCtx) => string | null;
21
+ export interface QueryNarrator {
22
+ /** Default importance of this query's events; an op handler may override via the return tuple. */
23
+ salience: Salience;
24
+ /** Handlers for changes at the ROOT level, by op. */
25
+ root?: Partial<Record<"add" | "remove" | "edit", Template>>;
26
+ /** Handlers for an aggregate slot (`countAs`), keyed by the count's alias. */
27
+ counts?: Record<string, Template>;
28
+ }
29
+ /** A registry of {@link QueryNarrator}s, keyed by `defineQuery` name. Supplied by the app. */
30
+ export type NarratorRegistry = Record<string, QueryNarrator>;
31
+ /** One rendered semantic event. `text === null` was suppressed by its template (too ambient). */
32
+ export interface SemanticEvent {
33
+ query: string;
34
+ phase: "snapshot" | "batch";
35
+ salience: Salience;
36
+ resolved: ResolvedChange;
37
+ text: string | null;
38
+ }
39
+ export interface Narrator {
40
+ /** Resolve + render a `FlatChange[]` for a named query into semantic events. `schema` is the
41
+ * query's `WireSchema`, captured from its `hello` frame (or read off `view.schema`) — the
42
+ * position→name source. */
43
+ narrate(query: string, schema: WireSchema, changes: FlatChange[], phase: "snapshot" | "batch", ctx?: NarrateContext): SemanticEvent[];
44
+ /** Format a batch of rendered events for an agent prompt (salience-marked, suppressions dropped). */
45
+ digest(events: SemanticEvent[]): string;
46
+ }
47
+ /** Per-salience glyph for a rendered line (shared with the causal digest). */
48
+ export declare const SALIENCE_MARK: Record<Salience, string>;
49
+ /** Order salience high→low (shared with the causal digest). */
50
+ export declare const salienceRank: (s: Salience) => number;
51
+ /** Build a narrator over an app-supplied {@link NarratorRegistry}. Resolution is driven entirely by
52
+ * the per-query `WireSchema` passed to {@link Narrator.narrate}, so the narrator holds no schema
53
+ * state of its own. */
54
+ export declare function createNarrator(narrators: NarratorRegistry): Narrator;
55
+ //# sourceMappingURL=narrator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"narrator.d.ts","sourceRoot":"","sources":["../src/narrator.ts"],"names":[],"mappings":"AAUA,OAAO,EAAyB,KAAK,UAAU,EAAE,KAAK,QAAQ,EAAE,KAAK,cAAc,EAAE,KAAK,UAAU,EAAE,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E,cAAc,CAAC;IACzB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CACrB;AAED,MAAM,WAAW,QAAQ;IACvB;;gCAE4B;IAC5B,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,EAAE,GAAG,CAAC,EAAE,cAAc,GAAG,aAAa,EAAE,CAAC;IACtI,qGAAqG;IACrG,MAAM,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAAC;CACzC;AAED,8EAA8E;AAC9E,eAAO,MAAM,aAAa,EAAE,MAAM,CAAC,QAAQ,EAAE,MAAM,CAA4C,CAAC;AAEhG,+DAA+D;AAC/D,eAAO,MAAM,YAAY,GAAI,GAAG,QAAQ,KAAG,MAAoD,CAAC;AAEhG;;wBAEwB;AACxB,wBAAgB,cAAc,CAAC,SAAS,EAAE,gBAAgB,GAAG,QAAQ,CAqCpE"}
@@ -0,0 +1,57 @@
1
+ // The narration framework: per-query templates that render a resolved flat-change into prose.
2
+ //
3
+ // The position→name resolution (`resolveChange` / `subRow`) lives in @rindle/client — it is the
4
+ // pure inverse of the wire encoder and broadly useful. This module is the layer ON TOP: a small
5
+ // registry of hand-written, per-query templates keyed by `defineQuery` name + op (+ count alias),
6
+ // salience tagging (alert / info / ambient), and a `digest()` that folds a batch of rendered events
7
+ // into a salience-ranked block for an agent prompt. The templates are the only domain-specific part
8
+ // — small, because the query and relationship NAMES already carry the meaning; the app supplies the
9
+ // registry to {@link createNarrator}.
10
+ import { resolveChange, subRow } from "@rindle/client";
11
+ /** Per-salience glyph for a rendered line (shared with the causal digest). */
12
+ export const SALIENCE_MARK = { alert: "⚠️", info: "•", ambient: "·" };
13
+ /** Order salience high→low (shared with the causal digest). */
14
+ export const salienceRank = (s) => (s === "alert" ? 2 : s === "info" ? 1 : 0);
15
+ /** Build a narrator over an app-supplied {@link NarratorRegistry}. Resolution is driven entirely by
16
+ * the per-query `WireSchema` passed to {@link Narrator.narrate}, so the narrator holds no schema
17
+ * state of its own. */
18
+ export function createNarrator(narrators) {
19
+ return {
20
+ narrate(query, schema, changes, phase, ctx = {}) {
21
+ const spec = narrators[query];
22
+ const out = [];
23
+ for (const change of changes) {
24
+ const resolved = resolveChange(schema, change);
25
+ if (!resolved)
26
+ continue;
27
+ let text = null;
28
+ if (spec) {
29
+ const tctx = {
30
+ row: resolved.row,
31
+ old: resolved.old,
32
+ parent: resolved.parent,
33
+ sub: (alias) => subRow(resolved, alias),
34
+ aggregate: resolved.aggregate,
35
+ context: ctx,
36
+ };
37
+ const tmpl = resolved.aggregate
38
+ ? spec.counts?.[resolved.aggregate.alias]
39
+ : resolved.alias === ""
40
+ ? spec.root?.[resolved.op]
41
+ : undefined; // sub-level changes surface through the root `add` node, not on their own
42
+ text = tmpl ? tmpl(tctx) : null;
43
+ }
44
+ out.push({ query, phase, salience: spec?.salience ?? "info", resolved, text });
45
+ }
46
+ return out;
47
+ },
48
+ digest(events) {
49
+ return events
50
+ .filter((e) => e.text)
51
+ .sort((a, b) => salienceRank(b.salience) - salienceRank(a.salience))
52
+ .map((e) => `${SALIENCE_MARK[e.salience]} ${e.text}`)
53
+ .join("\n");
54
+ },
55
+ };
56
+ }
57
+ //# sourceMappingURL=narrator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"narrator.js","sourceRoot":"","sources":["../src/narrator.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,EAAE;AACF,gGAAgG;AAChG,gGAAgG;AAChG,kGAAkG;AAClG,oGAAoG;AACpG,oGAAoG;AACpG,oGAAoG;AACpG,sCAAsC;AAEtC,OAAO,EAAE,aAAa,EAAE,MAAM,EAAwE,MAAM,gBAAgB,CAAC;AAwD7H,8EAA8E;AAC9E,MAAM,CAAC,MAAM,aAAa,GAA6B,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE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AAE,CAAC,QAAQ,CAAC,EAAE,CAAC;4BAC1B,CAAC,CAAC,SAAS,CAAC,CAAC,0EAA0E;oBAC3F,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;gBAClC,CAAC;gBACD,GAAG,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,IAAI,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;YACjF,CAAC;YACD,OAAO,GAAG,CAAC;QACb,CAAC;QACD,MAAM,CAAC,MAAM;YACX,OAAO,MAAM;iBACV,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;iBACrB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;iBACnE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;iBACpD,IAAI,CAAC,IAAI,CAAC,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC"}
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@rindle/narrator",
3
+ "version": "0.4.3",
4
+ "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/rindle-sh/rindle.git",
8
+ "directory": "packages/narrator"
9
+ },
10
+ "type": "module",
11
+ "description": "Turn a Rindle query's flat-change stream into agent-ready prose: resolve each FlatChange to named rows (via @rindle/client), render per-query templates into salience-tagged SemanticEvents, and group a commit's effects under the mutator that caused them (causal digest).",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "sideEffects": false,
15
+ "exports": {
16
+ ".": {
17
+ "@rindle/source": "./src/index.ts",
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "src",
25
+ "README.md"
26
+ ],
27
+ "dependencies": {
28
+ "@rindle/client": "0.4.3"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "^22.10.0",
32
+ "typescript": "^5.7.0"
33
+ },
34
+ "scripts": {
35
+ "build": "tsc -p tsconfig.build.json",
36
+ "test": "tsc --noEmit && node --conditions=@rindle/source --test test/*.test.ts",
37
+ "typecheck": "tsc --noEmit"
38
+ }
39
+ }
package/src/causal.ts ADDED
@@ -0,0 +1,216 @@
1
+ // Causal digest — group ONE commit's effects under the named mutator that caused them.
2
+ //
3
+ // In rindle a mutator invocation is one engine commit, and a commit returns per-query batches of
4
+ // FlatChanges. So "cause → effects" is a free join: the mutator name+args is the cause, every batch
5
+ // from that commit is an effect. We narrate each effect through the per-query templates
6
+ // (narrator.ts) and render one block:
7
+ //
8
+ // ↳ Seated a guest (seatGuest guestId=g1, tableId=t7)
9
+ // ⚠️ Jane Doe got a seat for the Smith wedding.
10
+ // • You're seated at Head Table, seat 3.
11
+ //
12
+ // That block is also the natural APPEND UNIT for the cache-coherent context story: one commit, one
13
+ // immutable block appended to the trunk — never a rewrite of earlier turns.
14
+ //
15
+ // Two layers: `narrateCommit` is a pure (bindings + cause + batches) → CausalDigest function; the
16
+ // live-store glue (`createCausalTap` / `attachCausalTap`) wraps a mutator call (begin → mutate →
17
+ // end) and feeds it off the store's supported `subscribeChanges` stream.
18
+
19
+ import type { ArrayView, ChangeEvent, FlatChange, QueryId, WireSchema } from "@rindle/client";
20
+
21
+ import {
22
+ type NarrateContext,
23
+ type Narrator,
24
+ type Salience,
25
+ type SemanticEvent,
26
+ SALIENCE_MARK,
27
+ salienceRank,
28
+ } from "./narrator.ts";
29
+
30
+ // ----------------------------- inputs -----------------------------
31
+
32
+ /** The cause: a named mutator + its args (the same `(name, args)` the optimistic envelope carries). */
33
+ export interface Cause {
34
+ mutator: string;
35
+ args?: unknown;
36
+ }
37
+
38
+ /** What a subscribed query needs to be narrated: its `defineQuery` name, its `WireSchema` (from the
39
+ * query's `hello` frame / `view.schema`), and ctx. (One per live `materialize()`, keyed by the
40
+ * engine `queryId`.) */
41
+ export interface QueryBinding {
42
+ query: string;
43
+ schema: WireSchema;
44
+ ctx?: NarrateContext;
45
+ }
46
+
47
+ /** One commit's per-query batch — exactly the `tx.commit()` / backend-dispatch element shape. */
48
+ export interface CommitBatch {
49
+ queryId: QueryId;
50
+ events: FlatChange[];
51
+ }
52
+
53
+ /** Render the cause headline from a mutator name. Co-locate these with the mutators, the way
54
+ * narrators are co-located with queries; absent ⇒ the generic `mutator(k=v, …)` fallback. */
55
+ export type CauseTemplate = (args: unknown) => string;
56
+
57
+ // ----------------------------- outputs -----------------------------
58
+
59
+ /** The narrated effects of the commit on ONE query (suppressed/ambient nulls already dropped). */
60
+ export interface CausalEffect {
61
+ query: string;
62
+ events: SemanticEvent[];
63
+ }
64
+
65
+ export interface CausalDigest {
66
+ cause: Cause;
67
+ /** Highest salience across all effects (`ambient` when there are none). */
68
+ salience: Salience;
69
+ /** Only queries with ≥1 narratable effect, ordered by salience then name. */
70
+ effects: CausalEffect[];
71
+ /** The append-ready block (cause headline + indented effect lines); `""` when nothing narratable. */
72
+ text: string;
73
+ }
74
+
75
+ export interface DigestOpts {
76
+ /** Per-mutator cause headlines (keyed by mutator name). */
77
+ causes?: Record<string, CauseTemplate>;
78
+ /** Emit the cause headline even when the commit had no narratable effect (default false). */
79
+ includeEmpty?: boolean;
80
+ }
81
+
82
+ // ----------------------------- rendering -----------------------------
83
+
84
+ function formatArgs(args: unknown): string {
85
+ if (args === undefined || args === null) return "";
86
+ if (typeof args !== "object") return String(args);
87
+ const parts = Object.entries(args as Record<string, unknown>).map(([k, v]) => {
88
+ const s = typeof v === "string" ? v : JSON.stringify(v);
89
+ return `${k}=${s && s.length > 24 ? s.slice(0, 23) + "…" : s}`;
90
+ });
91
+ return parts.join(", ");
92
+ }
93
+
94
+ function causeHeadline(cause: Cause, causes?: Record<string, CauseTemplate>): string {
95
+ const tmpl = causes?.[cause.mutator];
96
+ if (tmpl) return tmpl(cause.args);
97
+ const a = formatArgs(cause.args);
98
+ return `${cause.mutator}(${a})`;
99
+ }
100
+
101
+ /** Group one commit's batches under its cause and render the block. */
102
+ export function narrateCommit(
103
+ narrator: Narrator,
104
+ bindings: ReadonlyMap<QueryId, QueryBinding>,
105
+ cause: Cause,
106
+ batches: readonly CommitBatch[],
107
+ opts: DigestOpts = {},
108
+ ): CausalDigest {
109
+ const effects: CausalEffect[] = [];
110
+ let maxRank = -1;
111
+ let salience: Salience = "ambient";
112
+
113
+ for (const batch of batches) {
114
+ const b = bindings.get(batch.queryId);
115
+ if (!b || batch.events.length === 0) continue;
116
+ const events = narrator.narrate(b.query, b.schema, batch.events, "batch", b.ctx).filter((e) => e.text);
117
+ if (events.length === 0) continue;
118
+ effects.push({ query: b.query, events });
119
+ for (const e of events) {
120
+ if (salienceRank(e.salience) > maxRank) {
121
+ maxRank = salienceRank(e.salience);
122
+ salience = e.salience;
123
+ }
124
+ }
125
+ }
126
+
127
+ // Strongest-first, then by query name; lines within a query keep engine order.
128
+ effects.sort((x, y) => salienceRank(top(y)) - salienceRank(top(x)) || (x.query < y.query ? -1 : 1));
129
+
130
+ let text = "";
131
+ if (effects.length > 0 || opts.includeEmpty) {
132
+ const lines = [`↳ ${causeHeadline(cause, opts.causes)}`];
133
+ for (const eff of effects) {
134
+ for (const e of eff.events) lines.push(` ${SALIENCE_MARK[e.salience]} ${e.text}`);
135
+ }
136
+ text = lines.join("\n");
137
+ }
138
+
139
+ return { cause, salience, effects, text };
140
+ }
141
+
142
+ const top = (eff: CausalEffect): Salience =>
143
+ eff.events.reduce<Salience>((acc, e) => (salienceRank(e.salience) > salienceRank(acc) ? e.salience : acc), "ambient");
144
+
145
+ // ----------------------------- live-store glue -----------------------------
146
+
147
+ /** One commit's correlator. Buffer a commit's per-query batches between {@link CausalTap.begin} and
148
+ * {@link CausalTap.end}, then fold them into a {@link CausalDigest} under the in-flight cause. */
149
+ export interface CausalTap {
150
+ /** Mark the start of a mutator's commit; clears any prior buffer. */
151
+ begin(cause: Cause): void;
152
+ /** Feed one raw change frame (wire `subscribeChanges((qid, ev) => tap.capture(qid, ev))`). Only
153
+ * `batch` frames within an active `begin`/`end` window are buffered; `hello`/`snapshot` ignored. */
154
+ capture(qid: QueryId, ev: ChangeEvent): void;
155
+ /** Close the window and render the digest (or `null` if no `begin` is active). */
156
+ end(): CausalDigest | null;
157
+ }
158
+
159
+ /**
160
+ * Correlate a store's change frames with the mutator currently in flight. The local /
161
+ * optimistic-prediction path dispatches a commit's batches synchronously inside `mutate()`, so:
162
+ *
163
+ * tap.begin({ mutator: "seatGuest", args });
164
+ * await store.write(tx => …); // subscribeChanges fires → tap.capture(qid, ev)
165
+ * const digest = tap.end(); // one CausalDigest for the whole commit
166
+ *
167
+ * Wire `capture` into {@link attachCausalTap} (or directly into `store.subscribeChanges`).
168
+ */
169
+ export function createCausalTap(
170
+ narrator: Narrator,
171
+ bindings: ReadonlyMap<QueryId, QueryBinding>,
172
+ opts: DigestOpts = {},
173
+ ): CausalTap {
174
+ let cause: Cause | null = null;
175
+ const buf = new Map<QueryId, FlatChange[]>();
176
+ return {
177
+ begin(c: Cause): void {
178
+ cause = c;
179
+ buf.clear();
180
+ },
181
+ capture(qid: QueryId, ev: ChangeEvent): void {
182
+ if (!cause || ev.type !== "batch") return; // hello/snapshot aren't commit effects
183
+ const list = buf.get(qid) ?? [];
184
+ list.push(...ev.events);
185
+ buf.set(qid, list);
186
+ },
187
+ end(): CausalDigest | null {
188
+ if (!cause) return null;
189
+ const batches: CommitBatch[] = [...buf].map(([queryId, events]) => ({ queryId, events }));
190
+ const digest = narrateCommit(narrator, bindings, cause, batches, opts);
191
+ cause = null;
192
+ buf.clear();
193
+ return digest;
194
+ },
195
+ };
196
+ }
197
+
198
+ /** The minimal store surface {@link attachCausalTap} needs — the supported public change stream.
199
+ * The listener's third arg is the post-fold {@link ArrayView} for the qid (always the plural view);
200
+ * the causal tap ignores it, but the seam carries it for consumers that want list context. */
201
+ export interface ChangeStream {
202
+ subscribeChanges(listener: (qid: QueryId, ev: ChangeEvent, view?: ArrayView<unknown>) => void): () => void;
203
+ }
204
+
205
+ /** Create a {@link CausalTap} and wire its `capture` into a store's {@link ChangeStream.subscribeChanges}.
206
+ * Returns the tap (call `begin`/`end` around each mutator) plus a `detach` to stop listening. */
207
+ export function attachCausalTap(
208
+ store: ChangeStream,
209
+ narrator: Narrator,
210
+ bindings: ReadonlyMap<QueryId, QueryBinding>,
211
+ opts: DigestOpts = {},
212
+ ): { tap: CausalTap; detach: () => void } {
213
+ const tap = createCausalTap(narrator, bindings, opts);
214
+ const detach = store.subscribeChanges((qid, ev) => tap.capture(qid, ev));
215
+ return { tap, detach };
216
+ }
package/src/index.ts ADDED
@@ -0,0 +1,42 @@
1
+ // @rindle/narrator — turn a Rindle query's flat-change stream into agent-ready prose.
2
+ //
3
+ // Pipeline: a backend's per-query `FlatChange`s → `resolveChange` (@rindle/client) lifts each into
4
+ // NAMED rows → per-query templates render salience-tagged `SemanticEvent`s → `digest()` folds a
5
+ // batch into a prompt block. `narrateCommit` / `createCausalTap` additionally group one commit's
6
+ // effects under the named mutator that caused them. Drive it off a live store with the supported
7
+ // `store.subscribeChanges` seam (and read each query's `WireSchema` from `view.schema`).
8
+
9
+ export {
10
+ createNarrator,
11
+ SALIENCE_MARK,
12
+ salienceRank,
13
+ } from "./narrator.ts";
14
+ export type {
15
+ NamedRow,
16
+ NarrateContext,
17
+ Narrator,
18
+ NarratorRegistry,
19
+ QueryNarrator,
20
+ ResolvedChange,
21
+ Salience,
22
+ SemanticEvent,
23
+ Template,
24
+ TemplateCtx,
25
+ } from "./narrator.ts";
26
+
27
+ export {
28
+ attachCausalTap,
29
+ createCausalTap,
30
+ narrateCommit,
31
+ } from "./causal.ts";
32
+ export type {
33
+ Cause,
34
+ CausalDigest,
35
+ CausalEffect,
36
+ CausalTap,
37
+ CauseTemplate,
38
+ ChangeStream,
39
+ CommitBatch,
40
+ DigestOpts,
41
+ QueryBinding,
42
+ } from "./causal.ts";
@@ -0,0 +1,113 @@
1
+ // The narration framework: per-query templates that render a resolved flat-change into prose.
2
+ //
3
+ // The position→name resolution (`resolveChange` / `subRow`) lives in @rindle/client — it is the
4
+ // pure inverse of the wire encoder and broadly useful. This module is the layer ON TOP: a small
5
+ // registry of hand-written, per-query templates keyed by `defineQuery` name + op (+ count alias),
6
+ // salience tagging (alert / info / ambient), and a `digest()` that folds a batch of rendered events
7
+ // into a salience-ranked block for an agent prompt. The templates are the only domain-specific part
8
+ // — small, because the query and relationship NAMES already carry the meaning; the app supplies the
9
+ // registry to {@link createNarrator}.
10
+
11
+ import { resolveChange, subRow, type FlatChange, type NamedRow, type ResolvedChange, type WireSchema } from "@rindle/client";
12
+
13
+ export type { NamedRow, ResolvedChange };
14
+
15
+ export type Salience = "alert" | "info" | "ambient";
16
+
17
+ /** Context a template may interpolate — e.g. a human label for the subscription's subject. */
18
+ export interface NarrateContext {
19
+ /** A human name for what the query is scoped to ("the Smith wedding"). */
20
+ subject?: string;
21
+ [k: string]: unknown;
22
+ }
23
+
24
+ export interface TemplateCtx {
25
+ row: NamedRow;
26
+ old?: NamedRow;
27
+ /** The parent row, for an aggregate/nested change (e.g. the `ticket_type` behind a `sold` count). */
28
+ parent?: NamedRow;
29
+ /** Resolve a named sub-row of the change (only populated on `add`). */
30
+ sub: (alias: string) => NamedRow | null;
31
+ aggregate?: ResolvedChange["aggregate"];
32
+ context: NarrateContext;
33
+ }
34
+
35
+ export type Template = (ctx: TemplateCtx) => string | null;
36
+
37
+ export interface QueryNarrator {
38
+ /** Default importance of this query's events; an op handler may override via the return tuple. */
39
+ salience: Salience;
40
+ /** Handlers for changes at the ROOT level, by op. */
41
+ root?: Partial<Record<"add" | "remove" | "edit", Template>>;
42
+ /** Handlers for an aggregate slot (`countAs`), keyed by the count's alias. */
43
+ counts?: Record<string, Template>;
44
+ }
45
+
46
+ /** A registry of {@link QueryNarrator}s, keyed by `defineQuery` name. Supplied by the app. */
47
+ export type NarratorRegistry = Record<string, QueryNarrator>;
48
+
49
+ /** One rendered semantic event. `text === null` was suppressed by its template (too ambient). */
50
+ export interface SemanticEvent {
51
+ query: string;
52
+ phase: "snapshot" | "batch";
53
+ salience: Salience;
54
+ resolved: ResolvedChange;
55
+ text: string | null;
56
+ }
57
+
58
+ export interface Narrator {
59
+ /** Resolve + render a `FlatChange[]` for a named query into semantic events. `schema` is the
60
+ * query's `WireSchema`, captured from its `hello` frame (or read off `view.schema`) — the
61
+ * position→name source. */
62
+ narrate(query: string, schema: WireSchema, changes: FlatChange[], phase: "snapshot" | "batch", ctx?: NarrateContext): SemanticEvent[];
63
+ /** Format a batch of rendered events for an agent prompt (salience-marked, suppressions dropped). */
64
+ digest(events: SemanticEvent[]): string;
65
+ }
66
+
67
+ /** Per-salience glyph for a rendered line (shared with the causal digest). */
68
+ export const SALIENCE_MARK: Record<Salience, string> = { alert: "⚠️", info: "•", ambient: "·" };
69
+
70
+ /** Order salience high→low (shared with the causal digest). */
71
+ export const salienceRank = (s: Salience): number => (s === "alert" ? 2 : s === "info" ? 1 : 0);
72
+
73
+ /** Build a narrator over an app-supplied {@link NarratorRegistry}. Resolution is driven entirely by
74
+ * the per-query `WireSchema` passed to {@link Narrator.narrate}, so the narrator holds no schema
75
+ * state of its own. */
76
+ export function createNarrator(narrators: NarratorRegistry): Narrator {
77
+ return {
78
+ narrate(query, schema, changes, phase, ctx = {}) {
79
+ const spec = narrators[query];
80
+ const out: SemanticEvent[] = [];
81
+ for (const change of changes) {
82
+ const resolved = resolveChange(schema, change);
83
+ if (!resolved) continue;
84
+ let text: string | null = null;
85
+ if (spec) {
86
+ const tctx: TemplateCtx = {
87
+ row: resolved.row,
88
+ old: resolved.old,
89
+ parent: resolved.parent,
90
+ sub: (alias) => subRow(resolved, alias),
91
+ aggregate: resolved.aggregate,
92
+ context: ctx,
93
+ };
94
+ const tmpl = resolved.aggregate
95
+ ? spec.counts?.[resolved.aggregate.alias]
96
+ : resolved.alias === ""
97
+ ? spec.root?.[resolved.op]
98
+ : undefined; // sub-level changes surface through the root `add` node, not on their own
99
+ text = tmpl ? tmpl(tctx) : null;
100
+ }
101
+ out.push({ query, phase, salience: spec?.salience ?? "info", resolved, text });
102
+ }
103
+ return out;
104
+ },
105
+ digest(events) {
106
+ return events
107
+ .filter((e) => e.text)
108
+ .sort((a, b) => salienceRank(b.salience) - salienceRank(a.salience))
109
+ .map((e) => `${SALIENCE_MARK[e.salience]} ${e.text}`)
110
+ .join("\n");
111
+ },
112
+ };
113
+ }