@intentius/behold 0.29.40 → 0.29.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/AGENTS.md +180 -10
  2. package/README.md +6 -2
  3. package/dist/cli.js +16121 -13141
  4. package/example-writes/README.md +1 -1
  5. package/example-writes/chant.config.ts +0 -6
  6. package/package.json +5 -2
  7. package/web/app.js +327 -21
  8. package/web/carve-export.js +142 -0
  9. package/web/carve-narration.js +294 -0
  10. package/web/carve-narration.test.js +48 -0
  11. package/web/change-set-overlay.js +147 -0
  12. package/web/change-set-overlay.test.js +83 -0
  13. package/web/dots-border.js +66 -0
  14. package/web/dots-border.test.js +27 -0
  15. package/web/dots-kiosk.js +279 -0
  16. package/web/dots-kiosk.test.js +60 -0
  17. package/web/dots-layout.d.ts +10 -0
  18. package/web/dots-layout.js +201 -0
  19. package/web/dots-live.js +316 -0
  20. package/web/dots-live.test.js +220 -0
  21. package/web/dots-lod.js +122 -0
  22. package/web/dots-lod.test.js +78 -0
  23. package/web/dots-recording.d.ts +7 -0
  24. package/web/dots-recording.js +247 -0
  25. package/web/dots-recording.test.js +71 -0
  26. package/web/dots-scene.js +294 -0
  27. package/web/dots-scene.test.js +118 -0
  28. package/web/dots-timeline.js +128 -0
  29. package/web/dots-timeline.test.js +83 -0
  30. package/web/dots-tour.js +153 -0
  31. package/web/dots.js +2124 -0
  32. package/web/dots.test.js +15 -0
  33. package/web/event-help-modal.js +1 -1
  34. package/web/index.html +215 -121
  35. package/web/kiosk-carve.js +225 -0
  36. package/web/kiosk-carve.test.js +26 -0
  37. package/web/kiosk-event-help-ui.js +7 -1
  38. package/web/kiosk-link.js +68 -0
  39. package/web/kiosk-link.test.js +69 -0
  40. package/web/kiosk-metrics.js +2 -2
  41. package/web/kiosk-trace.js +1 -1
  42. package/web/kiosk.html +186 -135
  43. package/web/kiosk.js +65 -7
  44. package/web/motion.js +42 -0
  45. package/web/motion.test.js +64 -0
  46. package/web/operator.js +1 -1
  47. package/web/run-playhead.js +102 -19
  48. package/web/run-playhead.test.js +81 -11
  49. package/web/terralith.html +2 -2
  50. package/web/theme.js +99 -26
  51. package/web/theme.test.js +70 -6
  52. package/web/tooltip.js +212 -0
  53. package/web/tooltip.test.js +193 -0
  54. package/web/tour-player.js +204 -0
  55. package/web/tour-player.test.js +115 -0
  56. package/web/tours/behold.tour.v1.schema.json +182 -0
  57. package/web/tours/terralith.json +330 -0
  58. package/web/trunk-lane.js +406 -0
  59. package/web/trunk-lane.test.js +224 -0
  60. package/web/workspace-gates.js +29 -4
  61. package/web/workspace-gates.test.js +23 -2
@@ -0,0 +1,247 @@
1
+ // The dots layer's recorded data (#712; the live driver is web/dots-live.js, #715): a carve recording (#457's JSON Lines,
2
+ // scripts/dot-bench/record-carve.mjs) or the terralith walkthrough's
3
+ // snapshots (src/terralith-demo.ts readTerralith), read into one "show":
4
+ //
5
+ // { kind, source, estates[], roster[], owners0, ownersEnd, events[], threads[], t0, t1 }
6
+ //
7
+ // Every event is a line of the recording or a fact of a snapshot. Nothing is
8
+ // made up: a recording's times are its own stamps; the snapshots carry one
9
+ // time per phase, so their events are spaced evenly inside it and the show
10
+ // says so (`spaced: true`). Pure: text or JSON in, plain data out.
11
+
12
+ import { recordedClock } from "./dots-timeline.js";
13
+
14
+ /** A carve recording's lines -> { header, end, roster, estates, keyframes, timeline } (after #457's recording.js). */
15
+ export function readCarve(text) {
16
+ // Each record keeps its line in the file, for a timeline mark or a dot's provenance to name it.
17
+ const lines = text
18
+ .split("\n")
19
+ .map((l, i) => (l.trim() ? { ...JSON.parse(l), line: i + 1 } : null))
20
+ .filter(Boolean);
21
+ const header = lines.find((l) => l.kind === "header");
22
+ const keyframes = lines.filter((l) => l.kind === "keyframe");
23
+ if (!header || !keyframes.length) throw new Error("not a carve recording: no header or no keyframe");
24
+ const rosterLine = lines.find((l) => l.kind === "roster");
25
+ const byAddress = new Map();
26
+ if (rosterLine) {
27
+ for (const i of rosterLine.instances) byAddress.set(i.address, { address: i.address, type: i.type, taggable: i.rung === "tag-governable", rung: i.rung });
28
+ } else {
29
+ for (const doc of Object.values(keyframes[0].estates)) {
30
+ for (const it of doc.items ?? []) if (it.address && !byAddress.has(it.address)) byAddress.set(it.address, { address: it.address, type: it.type, taggable: true });
31
+ for (const g of doc.gaps ?? []) if (!byAddress.has(g.address)) byAddress.set(g.address, { address: g.address, type: g.type, taggable: false });
32
+ }
33
+ }
34
+ const owners = (kf) => {
35
+ const o = new Map();
36
+ for (const [estate, doc] of Object.entries(kf.estates)) for (const it of doc.items ?? []) if (it.address) o.set(it.address, estate);
37
+ return o;
38
+ };
39
+ const timeline = lines
40
+ .filter((l) => l.kind === "move")
41
+ .map((m) => {
42
+ const end = Date.parse(m.t);
43
+ const seconds = Number.isFinite(m.seconds) ? m.seconds : 0;
44
+ return {
45
+ seq: m.seq,
46
+ t: end,
47
+ start: end - seconds * 1000,
48
+ address: m.address,
49
+ from: m.doc?.from?.estate ?? header.source,
50
+ to: m.estate,
51
+ ok: m.exit === 0 && !!m.doc && m.doc.written !== false,
52
+ refusal: m.doc?.refusal?.code ?? (m.exit !== 0 ? "exit" : undefined),
53
+ ...(m.doc?.refusal?.summary ? { refusalSummary: m.doc.refusal.summary } : {}),
54
+ followers: (m.doc?.followers ?? []).map((f) => f.address),
55
+ line: m.line,
56
+ };
57
+ })
58
+ .sort((a, b) => a.seq - b.seq);
59
+ return {
60
+ header,
61
+ end: lines.find((l) => l.kind === "end"),
62
+ roster: [...byAddress.values()],
63
+ estates: [header.source, ...(header.destinations ?? [])],
64
+ keyframes: keyframes.map((k) => ({ seq: k.seq, t: Date.parse(k.t), owners: owners(k), line: k.line })),
65
+ timeline,
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Owner of every address after `upto` moves: the nearest keyframe at or before
71
+ * it, then the landed moves between (each carries its followers). A child no
72
+ * keyframe lists takes its parent's owner.
73
+ */
74
+ export function ownersAt(rec, upto, parents) {
75
+ let kf = rec.keyframes[0];
76
+ for (const k of rec.keyframes) if (k.seq <= upto && k.seq >= kf.seq) kf = k;
77
+ const owner = new Map(kf.owners);
78
+ for (const m of rec.timeline) {
79
+ if (m.seq <= kf.seq || m.seq > upto || !m.ok) continue;
80
+ owner.set(m.address, m.to);
81
+ for (const f of m.followers) owner.set(f, m.to);
82
+ }
83
+ for (const r of rec.roster) {
84
+ if (owner.has(r.address)) continue;
85
+ const p = parents.get(r.address);
86
+ owner.set(r.address, (p && owner.get(p)) || rec.header.source);
87
+ }
88
+ return owner;
89
+ }
90
+
91
+ /** A carve recording as a show: one `write` event per live-mv line. */
92
+ export function carveShow(rec, parents) {
93
+ const last = rec.keyframes.reduce((a, k) => (k.seq > a.seq ? k : a), rec.keyframes[0]);
94
+ const events = rec.timeline.map((m) => ({
95
+ kind: "write",
96
+ t: m.t,
97
+ start: Math.min(m.start, m.t),
98
+ address: m.address,
99
+ followers: m.followers,
100
+ from: m.from,
101
+ to: m.to,
102
+ ok: m.ok,
103
+ ...(m.refusal ? { refusal: m.refusal } : {}),
104
+ ...(m.refusalSummary ? { refusalSummary: m.refusalSummary } : {}),
105
+ seq: m.seq,
106
+ line: m.line,
107
+ }));
108
+ const t0 = Math.min(rec.keyframes[0].t, ...events.map((e) => e.start));
109
+ const t1 = Math.max(last.t, ...events.map((e) => e.t));
110
+ return {
111
+ kind: "carve",
112
+ title: rec.header.source,
113
+ recordedAt: Date.parse(rec.header.t) || t0,
114
+ source: rec.header.source,
115
+ estates: rec.estates,
116
+ roster: rec.roster,
117
+ owners0: ownersAt(rec, 0, parents),
118
+ ownersEnd: ownersAt(rec, last.seq, parents),
119
+ events,
120
+ threads: [],
121
+ phases: [],
122
+ parents,
123
+ t0,
124
+ t1,
125
+ spaced: false,
126
+ // A recording of a real event stream: its replay runs on the recording's own clock (web/dots-timeline.js).
127
+ timeline: recordedClock(events.flatMap((e) => [e.start, e.t]).concat(rec.keyframes.map((k) => k.t)), t0, t1),
128
+ records: {
129
+ header: { t: Date.parse(rec.header.t) || null, line: rec.header.line, source: rec.header.source || null, plan: rec.header.plan || null },
130
+ keyframes: rec.keyframes.map((k) => ({ t: k.t, line: k.line })),
131
+ end: rec.end && Date.parse(rec.end.t) ? { t: Date.parse(rec.end.t), line: rec.end.line } : null,
132
+ },
133
+ };
134
+ }
135
+
136
+ /**
137
+ * The walkthrough's four phases (readTerralith's model) as a show:
138
+ * adopt each card live-import stamped (identity.marked) leaves a ring;
139
+ * split each card that moved recolours, with a comet toward its estate;
140
+ * plan each card a root's plan read glows dimly, a planned change
141
+ * brighter, and each planned output is a thread from its estate to
142
+ * its readers, with a pulse handed along it (wave 1 to wave 2).
143
+ */
144
+ export function walkthroughShow(model) {
145
+ const phases = model.phases ?? [];
146
+ const stock = phases.find((p) => p.id === "stock") ?? phases[0];
147
+ if (!stock) throw new Error("no phases in the walkthrough's snapshots");
148
+ const adopt = phases.find((p) => p.id === "adopt");
149
+ const split = phases.find((p) => p.id === "split");
150
+ const plan = phases.find((p) => p.id === "plan");
151
+ const source = stock.boxes[0]?.id ?? "terralith";
152
+ const marked = new Map();
153
+ for (const b of adopt?.boxes ?? []) for (const c of b.cards) marked.set(c.id, !!c.identity?.marked);
154
+ const roster = stock.boxes
155
+ .flatMap((b) => b.cards)
156
+ .map((c) => ({ address: c.id, type: c.type, taggable: adopt ? !!marked.get(c.id) : true }));
157
+ const at = (p, i) => Date.parse(p?.at ?? "") || i * 10_000;
158
+ const times = phases.map((p, i) => at(p, i));
159
+ // A phase runs from its stamp to the next one's; the last gets the mean length.
160
+ const spanOf = (i) => (i + 1 < times.length ? times[i + 1] - times[i] : Math.max(10_000, (times.at(-1) - times[0]) / Math.max(1, times.length - 1)));
161
+ const iOf = (p) => phases.indexOf(p);
162
+ const spread = (p, items, mk) => {
163
+ const i = iOf(p);
164
+ const t = times[i];
165
+ const span = spanOf(i) * 0.8;
166
+ return items.map((it, k) => mk(it, t + (span * (k + 0.5)) / items.length, span / Math.max(1, items.length)));
167
+ };
168
+ const events = [];
169
+ if (adopt) {
170
+ const cards = adopt.boxes.flatMap((b) => b.cards).filter((c) => c.identity?.marked);
171
+ events.push(...spread(adopt, cards, (c, t, d) => ({ kind: "adopt", t, start: t - d * 0.6, address: c.id, source: c.identity.source })));
172
+ }
173
+ const owners0 = new Map(roster.map((r) => [r.address, source]));
174
+ const ownersEnd = new Map(owners0);
175
+ if (split) {
176
+ const cards = split.boxes.flatMap((b) => b.cards).filter((c) => c.moved && !c.moved.follows);
177
+ const followers = new Map();
178
+ for (const b of split.boxes) for (const c of b.cards) if (c.moved?.follows) followers.set(c.moved.follows, [...(followers.get(c.moved.follows) ?? []), c.id]);
179
+ events.push(
180
+ ...spread(split, cards, (c, t, d) => ({ kind: "write", t, start: t - d * 0.6, address: c.id, followers: followers.get(c.id) ?? [], from: c.moved.from, to: c.moved.to, ok: true })),
181
+ );
182
+ for (const b of split.boxes) for (const c of b.cards) ownersEnd.set(c.id, b.estate ?? b.id);
183
+ }
184
+ const threads = [];
185
+ if (plan) {
186
+ const i = iOf(plan);
187
+ const t = times[i];
188
+ const span = spanOf(i) * 0.8;
189
+ for (const b of plan.boxes) {
190
+ const whole = !!(b.plan?.fallback || (b.plan?.cone && b.plan.cone.full && b.plan.cone.kind !== "empty-cone"));
191
+ for (const c of b.cards) {
192
+ if (c.planned) events.push({ kind: "planned", t: t + span * 0.55, start: t + span * 0.3, address: c.id, actions: c.planned.actions });
193
+ if (whole || c.inCone || c.planned) events.push({ kind: "read", t: t + span * 0.5, start: t + span * 0.25, address: c.id, root: b.id });
194
+ }
195
+ }
196
+ for (const o of plan.plan?.outputs ?? []) {
197
+ for (const r of o.readers) {
198
+ threads.push({ from: o.estate, to: r, name: o.name, known: o.known });
199
+ events.push({ kind: "handoff", t: t + span * 0.35, start: t + span * 0.1, from: o.estate, to: r, name: o.name });
200
+ }
201
+ }
202
+ }
203
+ events.sort((a, b) => a.start - b.start);
204
+ const estates = [source, ...new Set([...ownersEnd.values()].filter((e) => e !== source))];
205
+ return {
206
+ kind: "walkthrough",
207
+ title: `${source} walkthrough`,
208
+ recordedAt: times[0],
209
+ source,
210
+ estates,
211
+ roster,
212
+ owners0,
213
+ ownersEnd,
214
+ events,
215
+ threads,
216
+ parents: new Map(),
217
+ phases: phases.map((p, k) => ({ id: p.id, t: times[k] })),
218
+ t0: times[0],
219
+ t1: times[times.length - 1] + spanOf(times.length - 1),
220
+ spaced: true,
221
+ };
222
+ }
223
+
224
+ /** Owners at show time `t`: every landed write that has finished by then. */
225
+ export function ownersAtTime(show, t) {
226
+ const o = new Map(show.owners0);
227
+ const touched = new Set();
228
+ for (const e of show.events) {
229
+ if (e.kind !== "write" || !e.ok || e.t > t) continue;
230
+ o.set(e.address, e.to);
231
+ touched.add(e.address);
232
+ for (const f of e.followers ?? []) {
233
+ o.set(f, e.to);
234
+ touched.add(f);
235
+ }
236
+ }
237
+ // A child no follower record names goes where its parent went.
238
+ for (const [child, parent] of show.parents ?? []) if (!touched.has(child) && touched.has(parent)) o.set(child, o.get(parent));
239
+ return o;
240
+ }
241
+
242
+ /** The phase a show is in at `t` (walkthrough only), or null. */
243
+ export function phaseAt(show, t) {
244
+ let at = null;
245
+ for (const p of show.phases) if (p.t <= t) at = p;
246
+ return at;
247
+ }
@@ -0,0 +1,71 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { readFileSync } from "node:fs";
3
+ import { gunzipSync } from "node:zlib";
4
+ import { fileURLToPath } from "node:url";
5
+ import { readCarve, ownersAt, carveShow, walkthroughShow, ownersAtTime, phaseAt } from "./dots-recording.js";
6
+ import { parentsOf } from "./dots-layout.js";
7
+
8
+ // #457's committed recording of the terralith-14 carve, and the walkthrough's
9
+ // snapshots as src/terralith-demo.ts reads them (src/dots-preview.test.ts
10
+ // checks the server hands the page the same model).
11
+ const text = gunzipSync(readFileSync(fileURLToPath(new URL("../scripts/dot-bench/carve-terralith-14.jsonl.gz", import.meta.url)))).toString("utf8");
12
+
13
+ describe("the carve recording reader (#712)", () => {
14
+ const rec = readCarve(text);
15
+ it("reads the roster, the keyframes and every move", () => {
16
+ expect(rec.roster).toHaveLength(1041);
17
+ expect(rec.roster.filter((r) => r.taggable)).toHaveLength(467);
18
+ expect(rec.keyframes.map((k) => k.seq)).toEqual([0, 100, 200, 300, 400, 463]);
19
+ expect(rec.timeline).toHaveLength(463);
20
+ expect(rec.timeline.filter((m) => !m.ok)).toHaveLength(14);
21
+ expect(rec.estates).toHaveLength(9);
22
+ expect(rec.timeline.every((m) => m.start <= m.t)).toBe(true);
23
+ expect(rec.timeline.find((m) => !m.ok).refusal).toBe("plan_changes_more_than_tags");
24
+ });
25
+ it("refuses a file that is not a recording", () => {
26
+ expect(() => readCarve('{"kind":"move"}\n')).toThrow(/not a carve recording/);
27
+ });
28
+ it("starts with every resource in the source and ends in the last keyframe's owners", () => {
29
+ const parents = parentsOf(rec.roster);
30
+ const start = ownersAt(rec, 0, parents);
31
+ expect(new Set(start.values())).toEqual(new Set([rec.header.source]));
32
+ const end = ownersAt(rec, 463, parents);
33
+ expect(new Set(end.values()).size).toBe(9);
34
+ });
35
+ it("replays its moves to the account's own answer at the end", () => {
36
+ const parents = parentsOf(rec.roster);
37
+ const show = carveShow(rec, parents);
38
+ const replayed = ownersAtTime(show, Infinity);
39
+ const differ = rec.roster.filter((r) => replayed.get(r.address) !== show.ownersEnd.get(r.address));
40
+ expect(differ).toEqual([]);
41
+ expect(show.events.filter((e) => e.kind === "write")).toHaveLength(463);
42
+ });
43
+ });
44
+
45
+ describe("the walkthrough reader (#712)", async () => {
46
+ const { readTerralith } = await import("../src/terralith-demo.ts");
47
+ const model = readTerralith(fileURLToPath(new URL("../src/__fixtures__/terralith", import.meta.url)));
48
+ const show = walkthroughShow(model);
49
+ it("takes the roster from the stock phase and its events from the snapshots", () => {
50
+ expect(show.roster).toHaveLength(23);
51
+ expect(show.events.filter((e) => e.kind === "adopt")).toHaveLength(17);
52
+ expect(show.events.filter((e) => e.kind === "write")).toHaveLength(15);
53
+ expect(show.events.filter((e) => e.kind === "planned")).toHaveLength(3);
54
+ expect(show.threads).toEqual([
55
+ { from: "terralith", to: "team-a", name: "log_retention_days", known: true },
56
+ { from: "terralith", to: "team-b", name: "log_retention_days", known: true },
57
+ { from: "terralith", to: "team-c", name: "log_retention_days", known: true },
58
+ ]);
59
+ expect(show.spaced).toBe(true);
60
+ });
61
+ it("ends with the split's owners, followers included", () => {
62
+ const end = ownersAtTime(show, Infinity);
63
+ expect(end.get("aws_iam_role_policy.team_a_inline")).toBe("team-a");
64
+ expect(end.get("aws_vpc.main")).toBe("terralith");
65
+ for (const r of show.roster) expect(end.get(r.address)).toBe(show.ownersEnd.get(r.address));
66
+ });
67
+ it("knows its phase at a time", () => {
68
+ expect(phaseAt(show, show.t0).id).toBe("stock");
69
+ expect(phaseAt(show, show.t1).id).toBe("plan");
70
+ });
71
+ });
@@ -0,0 +1,294 @@
1
+ // The dots layer's scene (#712, #715): where every dot and every estate box is at
2
+ // any moment of a replay, and the choreography of the carve.
3
+ //
4
+ // Each estate has its own box at the dot level. A dot's slot is its unit's
5
+ // place inside its estate's box (web/dots-layout.js), so a carved dot leaves
6
+ // the terralith's box and lands in its estate's. The boxes have stable slots:
7
+ // the source estate keeps the place its cards had on the page, and the new
8
+ // estates sit in a grid beside it in name order, each cell sized for what the
9
+ // estate holds at the end of the recording. A reset or a replay lays out the
10
+ // same way.
11
+ //
12
+ // The choreography: a carve recording plays on its own clock (#711): each move
13
+ // flies when the recording says it was written, and an idle stretch plays as a
14
+ // break the timeline names (web/dots-timeline.js). A show without its own
15
+ // clock (the walkthrough) is flown by unit, the order #457 recommends, so one
16
+ // team's cluster lifts off together as a flock; what moves, where to, and
17
+ // whether it landed are its records', and the order and timing the replay's. Pure: show in, plain data out. Units are in
18
+ // pitches (one dot spacing); the page scales them into the viewBox.
19
+
20
+ import { unitsOf, unitOf, packBlock, blockWidth, shelfPack } from "./dots-layout.js";
21
+
22
+ export const CHOREO = { duration: 90_000, flight: 1_300, stagger: 28, lead: 2_500, tail: 3_000 };
23
+ export const BOX = { pad: 1.5, title: 3, gap: 5 };
24
+
25
+ /** A show's own time -> replay ms, linear over [t0, t1]. */
26
+ export function replayClock(show, duration = CHOREO.duration) {
27
+ // #715: a live carve's clock is the show's own, one to one; its length grows as the page runs.
28
+ if (show.kind === "live") return { length: Math.max(1, show.t1 - show.t0), at: (t) => t - show.t0, live: true };
29
+ // A recording of a real event stream plays on its own clock: wall-clock time, with its idle stretches drawn as breaks (web/dots-timeline.js).
30
+ if (show.timeline) return { length: show.timeline.length, at: (t) => show.timeline.toReplay(t), real: (p) => show.timeline.toReal(p), recorded: true };
31
+ const span = Math.max(1, show.t1 - show.t0);
32
+ return { length: duration, at: (t) => ((t - show.t0) / span) * duration };
33
+ }
34
+
35
+ /**
36
+ * The flights: one per landed or refused move, plus one per follower and per
37
+ * untaggable child that moves with its parent. Sorted by start.
38
+ * Each is { address, from, to, ok, refusal?, start, end, flock, parent? }.
39
+ */
40
+ export function choreograph(show, opts = {}) {
41
+ const o = { ...CHOREO, ...opts };
42
+ const clock = replayClock(show, o.duration);
43
+ const writes = show.events.filter((e) => e.kind === "write");
44
+ if (!writes.length) return [];
45
+ // The window the flights fill: the whole replay for a carve recording, the
46
+ // split phase's stretch of it for the walkthrough.
47
+ let a = o.lead;
48
+ let b = o.duration - o.tail - o.flight;
49
+ if (show.kind !== "carve") {
50
+ a = clock.at(Math.min(...writes.map((e) => e.start)));
51
+ b = Math.max(a + o.flight, clock.at(Math.max(...writes.map((e) => e.t))) - o.flight);
52
+ }
53
+ // Children that move with a parent but that no follower record names.
54
+ const kidsOf = new Map();
55
+ for (const [child, parent] of show.parents ?? []) {
56
+ if (!kidsOf.has(parent)) kidsOf.set(parent, []);
57
+ kidsOf.get(parent).push(child);
58
+ }
59
+ // #715: a live carve flies each write when it was seen, in the show's own
60
+ // time (its clock is one to one), never regrouped: the order and the timing
61
+ // are the job's.
62
+ // A recording with its own clock flies each write when the recording says it was written, the same way.
63
+ if (show.kind === "live" || show.timeline) {
64
+ const out = [];
65
+ for (const w of writes) {
66
+ const start = show.kind === "live" ? w.start - show.t0 : Math.max(0, clock.at(w.t) - o.flight);
67
+ const base = { from: w.from, to: w.to, ok: w.ok, flock: 0, start, end: start + o.flight, at: w.at ?? w.t };
68
+ out.push({ ...base, address: w.address, ...(w.refusal ? { refusal: w.refusal } : {}), ...(w.refusalSummary ? { refusalSummary: w.refusalSummary } : {}) });
69
+ const followers = new Set(w.followers ?? []);
70
+ if (w.ok) for (const c of kidsOf.get(w.address) ?? []) followers.add(c);
71
+ [...followers].forEach((f, m) => {
72
+ const s = start + (m % 3) * 8;
73
+ out.push({ ...base, start: s, end: s + o.flight, address: f, parent: w.address });
74
+ });
75
+ }
76
+ // A resource may move twice (adopted into one estate, then split into another); the same write read twice flies once.
77
+ // A recording's follower named by two moves goes with the first, as the flocks do.
78
+ const seen = new Set();
79
+ const keyOf = (f) => (show.kind === "live" ? `${f.address}@${f.start}` : f.address);
80
+ return out.sort((x, y) => x.start - y.start).filter((f) => !seen.has(keyOf(f)) && seen.add(keyOf(f)));
81
+ }
82
+ const typeOf = new Map(show.roster.map((r) => [r.address, r.type]));
83
+ const order = new Map(show.roster.map((r, i) => [r.address, i]));
84
+ const unitKey = (addr) => unitOf(addr, typeOf.get(addr));
85
+ const flocks = new Map();
86
+ for (const w of writes) {
87
+ const k = unitKey(w.address);
88
+ if (!flocks.has(k)) flocks.set(k, []);
89
+ flocks.get(k).push(w);
90
+ }
91
+ const keys = [...flocks.keys()].sort();
92
+ // Children that move with a parent but that no follower record names.
93
+ const kids = new Map();
94
+ for (const [child, parent] of show.parents ?? []) {
95
+ if (!kids.has(parent)) kids.set(parent, []);
96
+ kids.get(parent).push(child);
97
+ }
98
+ const flights = [];
99
+ // Each unit lifts off as one flock: its dots a short stagger apart, the
100
+ // flocks evenly spaced, so one team's cluster leaves together.
101
+ const gap = (b - a) / Math.max(1, keys.length);
102
+ keys.forEach((k, fi) => {
103
+ const ws = flocks.get(k).sort((x, y) => (order.get(x.address) ?? 0) - (order.get(y.address) ?? 0));
104
+ const t = a + gap * fi;
105
+ ws.forEach((w, j) => {
106
+ const start = t + j * o.stagger;
107
+ // `at`: when the recording says the move happened, for a viewer who asks.
108
+ const base = { from: w.from, to: w.to, ok: w.ok, flock: fi, start, end: start + o.flight, at: w.t };
109
+ flights.push({ ...base, address: w.address, ...(w.refusal ? { refusal: w.refusal } : {}), ...(w.refusalSummary ? { refusalSummary: w.refusalSummary } : {}) });
110
+ const followers = new Set(w.followers ?? []);
111
+ if (w.ok) for (const c of kids.get(w.address) ?? []) followers.add(c);
112
+ [...followers].forEach((f, m) => {
113
+ const s = start + (m % 3) * 8;
114
+ flights.push({ ...base, start: s, end: s + o.flight, address: f, parent: w.address });
115
+ });
116
+ });
117
+ });
118
+ // A resource flies once: a follower named by two moves goes with the first.
119
+ const seen = new Set();
120
+ const once = flights.sort((x, y) => x.start - y.start).filter((f) => !seen.has(f.address) && seen.add(f.address));
121
+ return once;
122
+ }
123
+
124
+ /**
125
+ * The scene: the flights, and the layout after every takeoff, in pitches.
126
+ * `layoutAt(k)` is the layout once the first k landing flights have taken off
127
+ * (a dot in flight already holds its slot in the box it is flying to).
128
+ */
129
+ export function buildScene(show, opts = {}) {
130
+ const o = { ...opts };
131
+ const flights = choreograph(show, opts);
132
+ const landing = flights.filter((f) => f.ok);
133
+ landing.forEach((f, i) => (f.k = i + 1));
134
+ const source = show.source;
135
+ const rosterBy = new Map(show.roster.map((r) => [r.address, r]));
136
+ const end = show.ownersEnd;
137
+ const estates = [...new Set([source, ...show.estates, ...end.values()])];
138
+ const membersOf = (owners, e) => show.roster.filter((r) => owners.get(r.address) === e);
139
+ // Fixed widths: the source's from its first members, each estate's from its last.
140
+ const width = new Map();
141
+ const finalSize = new Map();
142
+ for (const e of estates) {
143
+ const first = e === source ? membersOf(show.owners0, e) : membersOf(end, e);
144
+ if (!first.length && e !== source) continue;
145
+ const us = unitsOf(first);
146
+ // The source's box takes its cards' shape on the page, so a card's dot has a short way to go.
147
+ width.set(e, blockWidth(us, e === source && o.sourceAspect ? o.sourceAspect : 1.3));
148
+ const p = packBlock(us, { width: width.get(e), fromEnd: e === source });
149
+ finalSize.set(e, { w: p.w + 2 * BOX.pad, h: p.h + 2 * BOX.pad + BOX.title });
150
+ }
151
+ const src = finalSize.get(source) ?? { w: 10, h: 10 };
152
+ const dests = estates.filter((e) => e !== source && finalSize.has(e)).sort();
153
+ const area = dests.reduce((s, e) => s + finalSize.get(e).w * finalSize.get(e).h, 0);
154
+ // A box's label sits over its outline and may be wider than the box: each cell leaves room for it, so two labels
155
+ // never touch. `labelPx(e)` is the label's width on screen and `avail` the screen area the boxes are framed in; the
156
+ // pitch on screen follows from the extent, so it is found in a few passes.
157
+ const labelRoom = (ppp) => (e) => (o.labelPx && ppp ? o.labelPx(e) / ppp + 1 : 0);
158
+ const pack = (ppp) => {
159
+ const room = labelRoom(ppp);
160
+ const ws = dests.map((e) => Math.max(finalSize.get(e).w, room(e)));
161
+ const gridW = Math.max(Math.sqrt(area) * 1.25, ...ws);
162
+ // A row's labels sit in the gap above it.
163
+ const gap = Math.max(BOX.gap, o.labelPx && ppp ? (o.labelH ?? 18) / ppp + 1 : 0);
164
+ const cells = shelfPack(
165
+ dests.map((e, i) => ({ key: e, w: ws[i], h: finalSize.get(e).h })),
166
+ { width: gridW, gap },
167
+ );
168
+ let h = src.h;
169
+ for (const e of dests) h = Math.max(h, cells.get(e).y + finalSize.get(e).h);
170
+ return { gridW, cells, w: src.w + BOX.gap * 3 + gridW, h };
171
+ };
172
+ let packed = pack(null);
173
+ if (o.labelPx && o.avail && o.avail.w > 0 && o.avail.h > 0) {
174
+ for (let i = 0; i < 3; i++) {
175
+ // The director's widest shot frames the whole extent, with its padding: the smallest pitch a label must fit.
176
+ const ppp = Math.min(o.avail.w / (packed.w + 7), o.avail.h / (packed.h + 7));
177
+ packed = pack(ppp);
178
+ }
179
+ }
180
+ const { gridW, cells } = packed;
181
+ const destX = src.w + BOX.gap * 3;
182
+ const origin = new Map([[source, { x: 0, y: 0 }]]);
183
+ for (const e of dests) origin.set(e, { x: destX + cells.get(e).x, y: cells.get(e).y });
184
+ let extentW = destX + gridW;
185
+ let extentH = src.h;
186
+ for (const e of dests) extentH = Math.max(extentH, cells.get(e).y + finalSize.get(e).h);
187
+ if (!dests.length) extentW = src.w;
188
+
189
+ const cache = new Map();
190
+ const layoutAt = (k) => {
191
+ const kk = Math.max(0, Math.min(k, landing.length));
192
+ if (cache.has(kk)) return cache.get(kk);
193
+ const owners = new Map(show.owners0);
194
+ for (let i = 0; i < kk; i++) owners.set(landing[i].address, landing[i].to);
195
+ const slots = new Map();
196
+ const boxes = new Map();
197
+ for (const e of estates) {
198
+ if (!width.has(e)) continue;
199
+ const ms = show.roster.filter((r) => owners.get(r.address) === e);
200
+ if (!ms.length && e !== source) continue;
201
+ const fromEnd = e === source;
202
+ const p = packBlock(unitsOf(ms), { width: width.get(e), fromEnd });
203
+ const o = origin.get(e);
204
+ let bx;
205
+ let by;
206
+ if (fromEnd) {
207
+ // Bottom edge fixed: the source loses its top rows as units leave.
208
+ bx = o.x;
209
+ by = o.y + src.h - (p.h + 2 * BOX.pad + BOX.title);
210
+ } else {
211
+ bx = o.x;
212
+ by = o.y;
213
+ }
214
+ const ix = bx + BOX.pad;
215
+ const iy = by + BOX.pad + BOX.title + (fromEnd ? p.h : 0);
216
+ for (const [addr, s] of p.slots) slots.set(addr, { x: ix + s.x, y: iy + s.y, ...(s.parent ? { parent: s.parent } : {}) });
217
+ // The source's box narrows to the dots it still holds once its last row is partial.
218
+ let x0 = bx;
219
+ let w = Math.max(p.w, ms.length ? 0 : 4) + 2 * BOX.pad;
220
+ if (fromEnd && ms.length) {
221
+ let lo = Infinity;
222
+ for (const [, sl] of p.slots) lo = Math.min(lo, sl.x);
223
+ const cellHalf = 1.5;
224
+ const left = Math.max(0, Math.min(p.w, lo - cellHalf));
225
+ x0 = bx + left;
226
+ w = p.w - left + 2 * BOX.pad;
227
+ }
228
+ boxes.set(e, { x: x0, y: by, w, h: p.h + 2 * BOX.pad + BOX.title, members: ms.length });
229
+ }
230
+ const out = { k: kk, slots, boxes, owners };
231
+ if (cache.size > 2000) cache.clear();
232
+ cache.set(kk, out);
233
+ return out;
234
+ };
235
+ return { show, flights, landing, estates, source, layoutAt, extent: { w: extentW, h: extentH }, sourceBox: src, finalSize, rosterBy };
236
+ }
237
+
238
+ /** How many landing flights have taken off by replay time `t` (binary search). */
239
+ export function takeoffsBy(scene, t) {
240
+ const l = scene.landing;
241
+ let lo = 0;
242
+ let hi = l.length;
243
+ while (lo < hi) {
244
+ const mid = (lo + hi) >> 1;
245
+ if (l[mid].start <= t) lo = mid + 1;
246
+ else hi = mid;
247
+ }
248
+ return lo;
249
+ }
250
+
251
+ /** Each estate's resource count at `t`: a dot counts where it is until it lands. */
252
+ export function countsAt(scene, t) {
253
+ const c = new Map();
254
+ for (const [, e] of scene.show.owners0) c.set(e, (c.get(e) ?? 0) + 1);
255
+ for (const f of scene.landing) {
256
+ if (f.end > t) continue;
257
+ c.set(f.from, (c.get(f.from) ?? 0) - 1);
258
+ c.set(f.to, (c.get(f.to) ?? 0) + 1);
259
+ }
260
+ return c;
261
+ }
262
+
263
+ /** The first landing in each estate (when its box draws in). */
264
+ export function firstLandings(scene) {
265
+ const out = new Map();
266
+ for (const f of scene.landing) if (!out.has(f.to) || f.end < out.get(f.to)) out.set(f.to, f.end);
267
+ return out;
268
+ }
269
+
270
+ /** Ease in and out. */
271
+ export function easeInOut(t) {
272
+ const x = Math.max(0, Math.min(1, t));
273
+ return x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2;
274
+ }
275
+
276
+ /**
277
+ * A point on a flight at progress u in [0, 1]: a gentle arc from a to b,
278
+ * bowed to the left of travel by `bow` of the distance. A refused flight goes
279
+ * out `reach` of the way and comes back to a.
280
+ */
281
+ export function flightPoint(a, b, u, { ok = true, bow = 0.18, reach = 0.32 } = {}) {
282
+ const e = easeInOut(u);
283
+ let p = e;
284
+ let tx = b.x;
285
+ let ty = b.y;
286
+ if (!ok) {
287
+ // Out and back: progress rises to `reach` at mid-flight and returns to 0.
288
+ p = Math.sin(Math.PI * e) * reach;
289
+ }
290
+ const dx = tx - a.x;
291
+ const dy = ty - a.y;
292
+ const lift = (ok ? Math.sin(Math.PI * e) : Math.sin(Math.PI * e) * reach) * bow;
293
+ return { x: a.x + dx * p - dy * lift, y: a.y + dy * p + dx * lift };
294
+ }