@rindle/narrator 0.4.3 → 0.4.4
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/README.md +16 -82
- package/dist/index.d.ts +1 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -6
- package/dist/index.js.map +1 -1
- package/dist/narrator.d.ts +20 -2
- package/dist/narrator.d.ts.map +1 -1
- package/dist/narrator.js +15 -5
- package/dist/narrator.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +6 -22
- package/src/narrator.ts +34 -5
- package/dist/causal.d.ts +0 -80
- package/dist/causal.d.ts.map +0 -1
- package/dist/causal.js +0 -115
- package/dist/causal.js.map +0 -1
- package/src/causal.ts +0 -216
package/README.md
CHANGED
|
@@ -1,41 +1,16 @@
|
|
|
1
1
|
# @rindle/narrator
|
|
2
2
|
|
|
3
|
-
Turn a Rindle
|
|
3
|
+
Turn a Rindle view's netted change stream into agent-ready prose.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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
|
|
5
|
+
<<<<<<< HEAD
|
|
6
|
+
Full docs — the agent loop this package powers (named diffs in, salience-ranked
|
|
7
|
+
digests out, observe→act): **[rindle.sh/docs/agents](https://rindle.sh/docs/agents)** ·
|
|
8
|
+
markdown mirror: [`agents.md`](https://rindle.sh/docs/agents.md) · for agents:
|
|
9
|
+
[llms.txt](https://rindle.sh/llms.txt)
|
|
34
10
|
|
|
35
11
|
```ts
|
|
36
|
-
import { createNarrator,
|
|
12
|
+
import { createNarrator, type NarratorRegistry } from "@rindle/narrator";
|
|
37
13
|
|
|
38
|
-
// The only hand-written part: per-query templates. The names do the work, so this stays small.
|
|
39
14
|
const NARRATORS: NarratorRegistry = {
|
|
40
15
|
unseatedGuests: {
|
|
41
16
|
salience: "alert",
|
|
@@ -47,56 +22,15 @@ const NARRATORS: NarratorRegistry = {
|
|
|
47
22
|
};
|
|
48
23
|
|
|
49
24
|
const narrator = createNarrator(NARRATORS);
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
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" })));
|
|
25
|
+
store.materialize(unseatedGuestsQuery({ eventId }), {
|
|
26
|
+
onChanges: (changes, phase, schema) => {
|
|
27
|
+
const block = narrator.digest(narrator.narrate("unseatedGuests", schema, changes, phase, ctx));
|
|
28
|
+
if (block) agentContext.append(block);
|
|
29
|
+
},
|
|
57
30
|
});
|
|
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
31
|
```
|
|
66
32
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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.
|
|
33
|
+
In React, `useNarration(query, NARRATORS, { ctx })` wires the view lifecycle and change
|
|
34
|
+
channel for you and returns a stable `Narration` handle — drain it with `take()` when you
|
|
35
|
+
prompt the model. See [rindle.sh/docs/agents](https://rindle.sh/docs/agents) for the full
|
|
36
|
+
walkthrough (resolution, nested `related` templates, salience, and the observe→act loop).
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
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";
|
|
2
|
+
export type { NamedRow, NarrateContext, Narrator, NarratorRegistry, QueryNarrator, RelatedNarrator, ResolvedChange, Salience, SemanticEvent, Template, TemplateCtx, } from "./narrator.ts";
|
|
5
3
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +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
|
|
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,eAAe,EACf,cAAc,EACd,QAAQ,EACR,aAAa,EACb,QAAQ,EACR,WAAW,GACZ,MAAM,eAAe,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
// @rindle/narrator — turn a Rindle query's flat-change stream into agent-ready prose.
|
|
2
2
|
//
|
|
3
|
-
// Pipeline: a
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
3
|
+
// Pipeline: a view's per-query `FlatChange`s (delivered by `view.onChanges` / `store.materialize(
|
|
4
|
+
// query, { onChanges })`, net of no-op rebase cycles) → `resolveChange` (@rindle/client) lifts each
|
|
5
|
+
// into NAMED rows → per-query templates render salience-tagged `SemanticEvent`s → `digest()` folds a
|
|
6
|
+
// batch into a prompt block. Drive it off a live view's OWN change channel — the position→name source
|
|
7
|
+
// is that view's `schema`. In React, `@rindle/react`'s `useNarration` wires this for you.
|
|
8
8
|
export { createNarrator, SALIENCE_MARK, salienceRank, } from "./narrator.js";
|
|
9
|
-
export { attachCausalTap, createCausalTap, narrateCommit, } from "./causal.js";
|
|
10
9
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;AACtF,EAAE;AACF,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;AACtF,EAAE;AACF,kGAAkG;AAClG,oGAAoG;AACpG,qGAAqG;AACrG,sGAAsG;AACtG,0FAA0F;AAE1F,OAAO,EACL,cAAc,EACd,aAAa,EACb,YAAY,GACb,MAAM,eAAe,CAAC"}
|
package/dist/narrator.d.ts
CHANGED
|
@@ -18,11 +18,29 @@ export interface TemplateCtx {
|
|
|
18
18
|
context: NarrateContext;
|
|
19
19
|
}
|
|
20
20
|
export type Template = (ctx: TemplateCtx) => string | null;
|
|
21
|
+
/** Handlers for changes to ONE nested relationship (keyed by its alias in {@link QueryNarrator.related}),
|
|
22
|
+
* by op — plus an optional salience override for that relationship's events. A nested template reads
|
|
23
|
+
* `row` (the nested row), `old`, and `parent` (its immediate container — the deck for a slide, the
|
|
24
|
+
* slide for a component). */
|
|
25
|
+
export interface RelatedNarrator {
|
|
26
|
+
/** Override the query's default salience for events on this relationship (else inherits it). */
|
|
27
|
+
salience?: Salience;
|
|
28
|
+
add?: Template;
|
|
29
|
+
remove?: Template;
|
|
30
|
+
edit?: Template;
|
|
31
|
+
}
|
|
21
32
|
export interface QueryNarrator {
|
|
22
33
|
/** Default importance of this query's events; an op handler may override via the return tuple. */
|
|
23
34
|
salience: Salience;
|
|
24
35
|
/** Handlers for changes at the ROOT level, by op. */
|
|
25
36
|
root?: Partial<Record<"add" | "remove" | "edit", Template>>;
|
|
37
|
+
/** Handlers for changes to a NESTED relationship, keyed by op — so ONE materialized view narrates
|
|
38
|
+
* its whole tree: e.g. a deck's title at the root, slide edits under `slides`, component adds under
|
|
39
|
+
* `components`. Key by the relationship's LEAF alias (`components`) for the common case, or by the
|
|
40
|
+
* FULL dotted alias-chain from the root (`slides.components`) to disambiguate two relationships that
|
|
41
|
+
* share a leaf alias at different tree positions (e.g. `slides.components` vs `appendix.components`).
|
|
42
|
+
* A dotted key wins over a leaf key when both match; a bare leaf key still matches at any depth. */
|
|
43
|
+
related?: Record<string, RelatedNarrator>;
|
|
26
44
|
/** Handlers for an aggregate slot (`countAs`), keyed by the count's alias. */
|
|
27
45
|
counts?: Record<string, Template>;
|
|
28
46
|
}
|
|
@@ -44,9 +62,9 @@ export interface Narrator {
|
|
|
44
62
|
/** Format a batch of rendered events for an agent prompt (salience-marked, suppressions dropped). */
|
|
45
63
|
digest(events: SemanticEvent[]): string;
|
|
46
64
|
}
|
|
47
|
-
/** Per-salience glyph for a rendered line
|
|
65
|
+
/** Per-salience glyph for a rendered line. */
|
|
48
66
|
export declare const SALIENCE_MARK: Record<Salience, string>;
|
|
49
|
-
/** Order salience high→low
|
|
67
|
+
/** Order salience high→low. */
|
|
50
68
|
export declare const salienceRank: (s: Salience) => number;
|
|
51
69
|
/** Build a narrator over an app-supplied {@link NarratorRegistry}. Resolution is driven entirely by
|
|
52
70
|
* the per-query `WireSchema` passed to {@link Narrator.narrate}, so the narrator holds no schema
|
package/dist/narrator.d.ts.map
CHANGED
|
@@ -1 +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,MAAM,gBAAgB,CAAC;AAE7H,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAE,CAAC;AAEzC,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,M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Q,KAAG,MAAoD,CAAC;AAEhG;;wBAEwB;AACxB,wBAAgB,cAAc,CAAC,SAAS,EAAE,gBAAgB,GAAG,QAAQ,CA+CpE"}
|
package/dist/narrator.js
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
// — small, because the query and relationship NAMES already carry the meaning; the app supplies the
|
|
9
9
|
// registry to {@link createNarrator}.
|
|
10
10
|
import { resolveChange, subRow } from "@rindle/client";
|
|
11
|
-
/** Per-salience glyph for a rendered line
|
|
11
|
+
/** Per-salience glyph for a rendered line. */
|
|
12
12
|
export const SALIENCE_MARK = { alert: "⚠️", info: "•", ambient: "·" };
|
|
13
|
-
/** Order salience high→low
|
|
13
|
+
/** Order salience high→low. */
|
|
14
14
|
export const salienceRank = (s) => (s === "alert" ? 2 : s === "info" ? 1 : 0);
|
|
15
15
|
/** Build a narrator over an app-supplied {@link NarratorRegistry}. Resolution is driven entirely by
|
|
16
16
|
* the per-query `WireSchema` passed to {@link Narrator.narrate}, so the narrator holds no schema
|
|
@@ -25,6 +25,7 @@ export function createNarrator(narrators) {
|
|
|
25
25
|
if (!resolved)
|
|
26
26
|
continue;
|
|
27
27
|
let text = null;
|
|
28
|
+
let salience = spec?.salience ?? "info";
|
|
28
29
|
if (spec) {
|
|
29
30
|
const tctx = {
|
|
30
31
|
row: resolved.row,
|
|
@@ -34,20 +35,29 @@ export function createNarrator(narrators) {
|
|
|
34
35
|
aggregate: resolved.aggregate,
|
|
35
36
|
context: ctx,
|
|
36
37
|
};
|
|
38
|
+
// A nested relationship change (not the root, not an aggregate) matches a `related` template
|
|
39
|
+
// keyed by its FULL dotted alias-chain (`slides.components`) if present, else its leaf alias
|
|
40
|
+
// (`components`) — so two same-leaf relationships at different tree positions never collide,
|
|
41
|
+
// while the common single-position case still keys by the bare alias.
|
|
42
|
+
const relSpec = resolved.alias !== "" && !resolved.aggregate
|
|
43
|
+
? (spec.related?.[resolved.aliasChain.join(".")] ?? spec.related?.[resolved.alias])
|
|
44
|
+
: undefined;
|
|
37
45
|
const tmpl = resolved.aggregate
|
|
38
46
|
? spec.counts?.[resolved.aggregate.alias]
|
|
39
47
|
: resolved.alias === ""
|
|
40
48
|
? spec.root?.[resolved.op]
|
|
41
|
-
:
|
|
49
|
+
: relSpec?.[resolved.op];
|
|
42
50
|
text = tmpl ? tmpl(tctx) : null;
|
|
51
|
+
if (relSpec?.salience)
|
|
52
|
+
salience = relSpec.salience;
|
|
43
53
|
}
|
|
44
|
-
out.push({ query, phase, salience
|
|
54
|
+
out.push({ query, phase, salience, resolved, text });
|
|
45
55
|
}
|
|
46
56
|
return out;
|
|
47
57
|
},
|
|
48
58
|
digest(events) {
|
|
49
59
|
return events
|
|
50
|
-
.filter((e) => e.text)
|
|
60
|
+
.filter((e) => e.text !== null)
|
|
51
61
|
.sort((a, b) => salienceRank(b.salience) - salienceRank(a.salience))
|
|
52
62
|
.map((e) => `${SALIENCE_MARK[e.salience]} ${e.text}`)
|
|
53
63
|
.join("\n");
|
package/dist/narrator.js.map
CHANGED
|
@@ -1 +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;
|
|
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;AA2E7H,8CAA8C;AAC9C,MAAM,CAAC,MAAM,aA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C,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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rindle/narrator",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.4",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"directory": "packages/narrator"
|
|
9
9
|
},
|
|
10
10
|
"type": "module",
|
|
11
|
-
"description": "Turn a Rindle
|
|
11
|
+
"description": "Turn a Rindle view's netted flat-change stream into agent-ready prose: resolve each FlatChange to named rows (via @rindle/client), render per-query templates (root + nested relationships) into salience-tagged SemanticEvents, and digest a batch into a ranked block for an agent prompt.",
|
|
12
12
|
"main": "./dist/index.js",
|
|
13
13
|
"types": "./dist/index.d.ts",
|
|
14
14
|
"sideEffects": false,
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"README.md"
|
|
26
26
|
],
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@rindle/client": "0.4.
|
|
28
|
+
"@rindle/client": "0.4.4"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@types/node": "^22.10.0",
|
package/src/index.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @rindle/narrator — turn a Rindle query's flat-change stream into agent-ready prose.
|
|
2
2
|
//
|
|
3
|
-
// Pipeline: a
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
3
|
+
// Pipeline: a view's per-query `FlatChange`s (delivered by `view.onChanges` / `store.materialize(
|
|
4
|
+
// query, { onChanges })`, net of no-op rebase cycles) → `resolveChange` (@rindle/client) lifts each
|
|
5
|
+
// into NAMED rows → per-query templates render salience-tagged `SemanticEvent`s → `digest()` folds a
|
|
6
|
+
// batch into a prompt block. Drive it off a live view's OWN change channel — the position→name source
|
|
7
|
+
// is that view's `schema`. In React, `@rindle/react`'s `useNarration` wires this for you.
|
|
8
8
|
|
|
9
9
|
export {
|
|
10
10
|
createNarrator,
|
|
@@ -17,26 +17,10 @@ export type {
|
|
|
17
17
|
Narrator,
|
|
18
18
|
NarratorRegistry,
|
|
19
19
|
QueryNarrator,
|
|
20
|
+
RelatedNarrator,
|
|
20
21
|
ResolvedChange,
|
|
21
22
|
Salience,
|
|
22
23
|
SemanticEvent,
|
|
23
24
|
Template,
|
|
24
25
|
TemplateCtx,
|
|
25
26
|
} 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";
|
package/src/narrator.ts
CHANGED
|
@@ -34,11 +34,30 @@ export interface TemplateCtx {
|
|
|
34
34
|
|
|
35
35
|
export type Template = (ctx: TemplateCtx) => string | null;
|
|
36
36
|
|
|
37
|
+
/** Handlers for changes to ONE nested relationship (keyed by its alias in {@link QueryNarrator.related}),
|
|
38
|
+
* by op — plus an optional salience override for that relationship's events. A nested template reads
|
|
39
|
+
* `row` (the nested row), `old`, and `parent` (its immediate container — the deck for a slide, the
|
|
40
|
+
* slide for a component). */
|
|
41
|
+
export interface RelatedNarrator {
|
|
42
|
+
/** Override the query's default salience for events on this relationship (else inherits it). */
|
|
43
|
+
salience?: Salience;
|
|
44
|
+
add?: Template;
|
|
45
|
+
remove?: Template;
|
|
46
|
+
edit?: Template;
|
|
47
|
+
}
|
|
48
|
+
|
|
37
49
|
export interface QueryNarrator {
|
|
38
50
|
/** Default importance of this query's events; an op handler may override via the return tuple. */
|
|
39
51
|
salience: Salience;
|
|
40
52
|
/** Handlers for changes at the ROOT level, by op. */
|
|
41
53
|
root?: Partial<Record<"add" | "remove" | "edit", Template>>;
|
|
54
|
+
/** Handlers for changes to a NESTED relationship, keyed by op — so ONE materialized view narrates
|
|
55
|
+
* its whole tree: e.g. a deck's title at the root, slide edits under `slides`, component adds under
|
|
56
|
+
* `components`. Key by the relationship's LEAF alias (`components`) for the common case, or by the
|
|
57
|
+
* FULL dotted alias-chain from the root (`slides.components`) to disambiguate two relationships that
|
|
58
|
+
* share a leaf alias at different tree positions (e.g. `slides.components` vs `appendix.components`).
|
|
59
|
+
* A dotted key wins over a leaf key when both match; a bare leaf key still matches at any depth. */
|
|
60
|
+
related?: Record<string, RelatedNarrator>;
|
|
42
61
|
/** Handlers for an aggregate slot (`countAs`), keyed by the count's alias. */
|
|
43
62
|
counts?: Record<string, Template>;
|
|
44
63
|
}
|
|
@@ -64,10 +83,10 @@ export interface Narrator {
|
|
|
64
83
|
digest(events: SemanticEvent[]): string;
|
|
65
84
|
}
|
|
66
85
|
|
|
67
|
-
/** Per-salience glyph for a rendered line
|
|
86
|
+
/** Per-salience glyph for a rendered line. */
|
|
68
87
|
export const SALIENCE_MARK: Record<Salience, string> = { alert: "⚠️", info: "•", ambient: "·" };
|
|
69
88
|
|
|
70
|
-
/** Order salience high→low
|
|
89
|
+
/** Order salience high→low. */
|
|
71
90
|
export const salienceRank = (s: Salience): number => (s === "alert" ? 2 : s === "info" ? 1 : 0);
|
|
72
91
|
|
|
73
92
|
/** Build a narrator over an app-supplied {@link NarratorRegistry}. Resolution is driven entirely by
|
|
@@ -82,6 +101,7 @@ export function createNarrator(narrators: NarratorRegistry): Narrator {
|
|
|
82
101
|
const resolved = resolveChange(schema, change);
|
|
83
102
|
if (!resolved) continue;
|
|
84
103
|
let text: string | null = null;
|
|
104
|
+
let salience: Salience = spec?.salience ?? "info";
|
|
85
105
|
if (spec) {
|
|
86
106
|
const tctx: TemplateCtx = {
|
|
87
107
|
row: resolved.row,
|
|
@@ -91,20 +111,29 @@ export function createNarrator(narrators: NarratorRegistry): Narrator {
|
|
|
91
111
|
aggregate: resolved.aggregate,
|
|
92
112
|
context: ctx,
|
|
93
113
|
};
|
|
114
|
+
// A nested relationship change (not the root, not an aggregate) matches a `related` template
|
|
115
|
+
// keyed by its FULL dotted alias-chain (`slides.components`) if present, else its leaf alias
|
|
116
|
+
// (`components`) — so two same-leaf relationships at different tree positions never collide,
|
|
117
|
+
// while the common single-position case still keys by the bare alias.
|
|
118
|
+
const relSpec =
|
|
119
|
+
resolved.alias !== "" && !resolved.aggregate
|
|
120
|
+
? (spec.related?.[resolved.aliasChain.join(".")] ?? spec.related?.[resolved.alias])
|
|
121
|
+
: undefined;
|
|
94
122
|
const tmpl = resolved.aggregate
|
|
95
123
|
? spec.counts?.[resolved.aggregate.alias]
|
|
96
124
|
: resolved.alias === ""
|
|
97
125
|
? spec.root?.[resolved.op]
|
|
98
|
-
:
|
|
126
|
+
: relSpec?.[resolved.op];
|
|
99
127
|
text = tmpl ? tmpl(tctx) : null;
|
|
128
|
+
if (relSpec?.salience) salience = relSpec.salience;
|
|
100
129
|
}
|
|
101
|
-
out.push({ query, phase, salience
|
|
130
|
+
out.push({ query, phase, salience, resolved, text });
|
|
102
131
|
}
|
|
103
132
|
return out;
|
|
104
133
|
},
|
|
105
134
|
digest(events) {
|
|
106
135
|
return events
|
|
107
|
-
.filter((e) => e.text)
|
|
136
|
+
.filter((e) => e.text !== null)
|
|
108
137
|
.sort((a, b) => salienceRank(b.salience) - salienceRank(a.salience))
|
|
109
138
|
.map((e) => `${SALIENCE_MARK[e.salience]} ${e.text}`)
|
|
110
139
|
.join("\n");
|
package/dist/causal.d.ts
DELETED
|
@@ -1,80 +0,0 @@
|
|
|
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
|
package/dist/causal.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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,aAAa,EAGnB,MAAM,eAAe,CAAC;AAIvB,uGAAuG;AACvG,MAAM,WAAW,KAAK;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED;;yBAEyB;AACzB,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,UAAU,CAAC;IACnB,GAAG,CAAC,EAA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,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
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
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
|
package/dist/causal.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"causal.js","sourceRoot":"","sources":["../src/causal.ts"],"names":[],"mappings":"AAAA,uFAAuF;AACvF,EAAE;AACF,iGAAiG;AACjG,oGAAoG;AACpG,wFAAwF;AACxF,sCAAsC;AACtC,EAAE;AACF,wDAAwD;AACxD,qDAAqD;AACrD,8CAA8C;AAC9C,EAAE;AACF,mGAAmG;AACnG,4EAA4E;AAC5E,EAAE;AACF,kGAAkG;AAClG,iGAAiG;AACjG,yEAAyE;AAIzE,OAAO,EAKL,aAAa,EACb,YAAY,GACb,MAAM,eAAe,CAAC;AAsDvB,wEAAwE;AAExE,SAAS,UAAU,CAAC,IAAa;IAC/B,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,EAAE,CAAC;IACnD,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC;IAClD,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,IAA+B,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,GAAG,EAAE,IAAI,CAAC,CAAC;QACrB,CAAC;QACD,GAAG;YACD,IAAI,CAAC,KAAK;gBAAE,OAAO,IAAI,CAAC;YACxB,MAAM,OAAO,GAAkB,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC;YAC1F,MAAM,MAAM,GAAG,aAAa,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;YACvE,KAAK,GAAG,IAAI,CAAC;YACb,GAAG,CAAC,KAAK,EAAE,CAAC;YACZ,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC;AASD;kGACkG;AAClG,MAAM,UAAU,eAAe,CAC7B,KAAmB,EACnB,QAAkB,EAClB,QAA4C,EAC5C,OAAmB,EAAE;IAErB,MAAM,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"}
|
package/src/causal.ts
DELETED
|
@@ -1,216 +0,0 @@
|
|
|
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
|
-
}
|