@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,118 @@
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, carveShow } from "./dots-recording.js";
6
+ import { parentsOf, unitsOf, unitOf, packBlock, ringsOf } from "./dots-layout.js";
7
+ import { choreograph, buildScene, takeoffsBy, countsAt, flightPoint, CHOREO } from "./dots-scene.js";
8
+
9
+ const text = gunzipSync(readFileSync(fileURLToPath(new URL("../scripts/dot-bench/carve-terralith-14.jsonl.gz", import.meta.url)))).toString("utf8");
10
+ const rec = readCarve(text);
11
+ const show = carveShow(rec, parentsOf(rec.roster));
12
+
13
+ describe("the dots layout (#712)", () => {
14
+ it("groups a unit by module, block stem and count index", () => {
15
+ expect(unitOf("aws_iam_role.team_0003_role", "aws_iam_role")).toBe(unitOf("aws_iam_instance_profile.team_0003_profile", "aws_iam_instance_profile"));
16
+ expect(unitOf("aws_cloudwatch_log_group.team_a_0")).toBe(unitOf("aws_cloudwatch_log_group.team_a_2"));
17
+ expect(unitOf("aws_ecs_service.svc_0001")).not.toBe(unitOf("aws_ecs_service.svc_0002"));
18
+ expect(unitOf('aws_route53_record.records["www"]', "aws_route53_record")).toBe("|dns");
19
+ });
20
+ it("packs a large ring into concentric rings", () => {
21
+ const rs = ringsOf(141);
22
+ expect(rs.reduce((s, r) => s + r.n, 0)).toBe(141);
23
+ expect(rs.length).toBeGreaterThan(3);
24
+ });
25
+ it("keeps every slot when units leave from the front of a box packed from the end", () => {
26
+ const us = unitsOf(rec.roster);
27
+ const width = 60;
28
+ const all = packBlock(us, { width, fromEnd: true });
29
+ const rest = packBlock(us.slice(5), { width, fromEnd: true });
30
+ for (const [a, s] of rest.slots) expect(all.slots.get(a)).toEqual(s);
31
+ });
32
+ });
33
+
34
+ describe("the carve choreography (#712)", () => {
35
+ const flights = choreograph(show);
36
+ it("flies every resource that changes estate exactly once, and lands it where the recording ends", () => {
37
+ const seen = new Set(flights.map((f) => f.address));
38
+ expect(seen.size).toBe(flights.length);
39
+ const owners = new Map(show.owners0);
40
+ for (const f of flights) if (f.ok) owners.set(f.address, f.to);
41
+ for (const r of rec.roster) expect(owners.get(r.address)).toBe(show.ownersEnd.get(r.address));
42
+ expect(flights.filter((f) => !f.ok && !f.parent)).toHaveLength(14);
43
+ });
44
+ it("flies each move when the recording says it was written, on the recording's own clock", () => {
45
+ const clock = show.timeline;
46
+ const byAddr = new Map(show.events.map((e) => [e.address, e]));
47
+ for (const f of flights.filter((x) => !x.parent)) {
48
+ const w = byAddr.get(f.address);
49
+ expect(f.start).toBeCloseTo(Math.max(0, clock.toReplay(w.t) - CHOREO.flight), 6);
50
+ }
51
+ expect(Math.min(...flights.map((f) => f.start))).toBeGreaterThanOrEqual(0);
52
+ expect(Math.max(...flights.map((f) => f.start))).toBeLessThanOrEqual(clock.length);
53
+ });
54
+ it("carries a child with its parent", () => {
55
+ const child = flights.find((f) => f.parent);
56
+ const parent = flights.find((f) => f.address === child.parent);
57
+ expect(child.to).toBe(parent.to);
58
+ expect(child.start - parent.start).toBeLessThan(60);
59
+ });
60
+ });
61
+
62
+ describe("the scene (#712)", () => {
63
+ const scene = buildScene(show, { sourceAspect: 2.5 });
64
+ it("is the same every time it is built", () => {
65
+ const again = buildScene(show, { sourceAspect: 2.5 });
66
+ const a = scene.layoutAt(200);
67
+ const b = again.layoutAt(200);
68
+ expect([...a.slots]).toEqual([...b.slots]);
69
+ });
70
+ it("puts every dot inside its estate's box, at the start and at the end", () => {
71
+ for (const k of [0, scene.landing.length]) {
72
+ const L = scene.layoutAt(k);
73
+ for (const [addr, s] of L.slots) {
74
+ const b = L.boxes.get(L.owners.get(addr));
75
+ expect(s.x).toBeGreaterThanOrEqual(b.x - 1e-9);
76
+ expect(s.x).toBeLessThanOrEqual(b.x + b.w + 1e-9);
77
+ expect(s.y).toBeGreaterThanOrEqual(b.y - 1e-9);
78
+ expect(s.y).toBeLessThanOrEqual(b.y + b.h + 1e-9);
79
+ }
80
+ }
81
+ expect(scene.layoutAt(0).boxes.size).toBe(1);
82
+ expect(scene.layoutAt(scene.landing.length).boxes.size).toBe(9);
83
+ });
84
+ it("never overlaps two estates' final boxes", () => {
85
+ const bs = [...scene.layoutAt(scene.landing.length).boxes.values()];
86
+ for (let i = 0; i < bs.length; i++)
87
+ for (let j = i + 1; j < bs.length; j++) {
88
+ const a = bs[i];
89
+ const b = bs[j];
90
+ expect(a.x + a.w <= b.x || b.x + b.w <= a.x || a.y + a.h <= b.y || b.y + b.h <= a.y).toBe(true);
91
+ }
92
+ });
93
+ it("counts a dot where it is until it lands", () => {
94
+ const f = scene.landing[10];
95
+ const before = countsAt(scene, f.end - 1);
96
+ const after = countsAt(scene, f.end);
97
+ expect(after.get(f.to) - (before.get(f.to) ?? 0)).toBeGreaterThanOrEqual(1);
98
+ expect(takeoffsBy(scene, f.start)).toBeGreaterThanOrEqual(f.k);
99
+ });
100
+ });
101
+
102
+ describe("a flight's path (#712)", () => {
103
+ const a = { x: 0, y: 0 };
104
+ const b = { x: 100, y: 0 };
105
+ it("leaves its old slot, arcs, and lands in its new one", () => {
106
+ expect(flightPoint(a, b, 0)).toEqual({ x: 0, y: 0 });
107
+ const end = flightPoint(a, b, 1);
108
+ expect(end.x).toBeCloseTo(100, 9);
109
+ expect(end.y).toBeCloseTo(0, 9);
110
+ expect(Math.abs(flightPoint(a, b, 0.5).y)).toBeGreaterThan(5);
111
+ });
112
+ it("comes back to its slot when the move was refused", () => {
113
+ const back = flightPoint(a, b, 1, { ok: false });
114
+ expect(back.x).toBeCloseTo(0, 9);
115
+ expect(back.y).toBeCloseTo(0, 9);
116
+ expect(flightPoint(a, b, 0.5, { ok: false }).x).toBeGreaterThan(10);
117
+ });
118
+ });
@@ -0,0 +1,128 @@
1
+ // The timeline of a recorded replay: a recording of a real event stream,
2
+ // played on the recording's own clock. Pure: the recording's times in, the
3
+ // mapping between replay time and wall-clock time, the ticks, the marks and
4
+ // the label out.
5
+ //
6
+ // Replay time is wall-clock time, one to one, except across an idle stretch
7
+ // longer than `maxGap`: that stretch plays as `keep` ms, and the timeline
8
+ // draws a break there with the real gap's length ("+48 s skipped"). Nothing is
9
+ // compressed without a break to say so. The ticks are the recording's
10
+ // wall-clock times, and every mark is a line of the recording (its file and
11
+ // line, and its time).
12
+
13
+ export const GAPS = { maxGap: 10_000, keep: 2_000 };
14
+
15
+ /**
16
+ * The replay's clock over a recording whose events happened at `times` (ms),
17
+ * from `t0` to `t1`: { length, toReplay(real), toReal(p), breaks, t0, t1 }.
18
+ * Each break is { p, real0, real1, skipped } in replay ms and wall-clock ms.
19
+ */
20
+ export function recordedClock(times, t0, t1, { maxGap = GAPS.maxGap, keep = GAPS.keep } = {}) {
21
+ const ts = [...new Set([t0, ...times.filter((x) => Number.isFinite(x) && x >= t0 && x <= t1), t1])].sort((a, b) => a - b);
22
+ const segs = []; // { r0, r1, p0 }: wall-clock [r0, r1] plays from replay p0, one to one
23
+ const breaks = [];
24
+ let p = 0;
25
+ let r0 = ts[0];
26
+ for (let i = 1; i < ts.length; i++) {
27
+ const a = ts[i - 1];
28
+ const b = ts[i];
29
+ if (b - a > maxGap) {
30
+ // Play up to a, then the gap as `keep` ms, the first half before the break and the second after.
31
+ segs.push({ r0, r1: a + keep / 2, p0: p });
32
+ p += a + keep / 2 - r0;
33
+ breaks.push({ p, real0: a + keep / 2, real1: b - keep / 2, skipped: b - a - keep });
34
+ r0 = b - keep / 2;
35
+ }
36
+ }
37
+ segs.push({ r0, r1: ts[ts.length - 1], p0: p });
38
+ p += ts[ts.length - 1] - r0;
39
+ const length = Math.max(1, p);
40
+ const toReplay = (real) => {
41
+ if (real <= segs[0].r0) return 0;
42
+ for (const s of segs) {
43
+ if (real <= s.r1) return real < s.r0 ? s.p0 : s.p0 + (real - s.r0);
44
+ }
45
+ return length;
46
+ };
47
+ const toReal = (q) => {
48
+ let s = segs[0];
49
+ for (const x of segs) if (x.p0 <= q) s = x;
50
+ return Math.min(s.r1, s.r0 + Math.max(0, q - s.p0));
51
+ };
52
+ return { length, toReplay, toReal, breaks, segs, t0: ts[0], t1: ts[ts.length - 1] };
53
+ }
54
+
55
+ const pad = (n) => String(n).padStart(2, "0");
56
+ /** A wall-clock time as the timeline shows it, in UTC: "16:37" or, with seconds, "16:37:26". */
57
+ export function clockWords(ms, seconds = false) {
58
+ const d = new Date(ms);
59
+ return `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}${seconds ? `:${pad(d.getUTCSeconds())}` : ""}`;
60
+ }
61
+
62
+ const STEPS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600].map((s) => s * 1000);
63
+
64
+ /** The wall-clock ticks: round times inside the played stretches, about `want` of them, each { p, real, label }. */
65
+ export function wallTicks(clock, want = 7) {
66
+ const played = clock.segs.reduce((s, x) => s + (x.r1 - x.r0), 0);
67
+ const step = STEPS.find((s) => played / s <= want) ?? STEPS[STEPS.length - 1];
68
+ const out = [];
69
+ for (const s of clock.segs) {
70
+ for (let r = Math.ceil(s.r0 / step) * step; r <= s.r1; r += step) out.push({ p: s.p0 + (r - s.r0), real: r, label: clockWords(r, step < 60_000) });
71
+ }
72
+ return out;
73
+ }
74
+
75
+ const DAY = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" });
76
+
77
+ /**
78
+ * The timeline's label: "Recorded 22 Sep 2026, 16:37:26–17:13:00 UTC from
79
+ * behold-terralith-14 · plan domains", from the recording's own header and
80
+ * times. A source the records do not name is left out. `short`: the phone's
81
+ * "Recorded 16:37–17:13 UTC".
82
+ */
83
+ export function recordedLabel({ t0, t1, source = null, plan = null }, { short = false } = {}) {
84
+ if (short) return `Recorded ${clockWords(t0)}–${clockWords(t1)} UTC`;
85
+ const from = [source, plan ? `plan ${plan}` : null].filter(Boolean).join(" · ");
86
+ return `Recorded ${DAY.format(new Date(t0))}, ${clockWords(t0, true)}–${clockWords(t1, true)} UTC${from ? ` from ${from}` : ""}`;
87
+ }
88
+
89
+ /** The speed control's words, always its state: "1x real time", "slowed ×10", "sped up ×4". */
90
+ export function speedWords(speed) {
91
+ if (speed === 1) return "1x real time";
92
+ if (speed < 1) return `slowed ×${Math.round(1 / speed)}`;
93
+ return `sped up ×${speed}`;
94
+ }
95
+
96
+ /** The speeds a recorded replay offers, real time first. */
97
+ export const RECORDED_SPEEDS = [1, 4, 16, 0.5, 0.1];
98
+
99
+ /** A gap's length in words: "+48 s skipped", "+2 min 5 s skipped". */
100
+ export function skippedWords(ms) {
101
+ const s = Math.round(ms / 1000);
102
+ return s < 60 ? `+${s} s skipped` : `+${Math.floor(s / 60)} min${s % 60 ? ` ${s % 60} s` : ""} skipped`;
103
+ }
104
+
105
+ /**
106
+ * The marks on the timeline, each a line of the recording: the first and
107
+ * last move, each keyframe (an estate listing), and the end. Each is
108
+ * { p, real, kind, words, record } where `record` names the file, line and time.
109
+ */
110
+ export function recordedMarks(show, clock, file = "the recording") {
111
+ const r = show && show.records;
112
+ if (!r) return [];
113
+ const out = [];
114
+ const add = (real, kind, words, line) => {
115
+ if (!Number.isFinite(real)) return;
116
+ out.push({ p: clock.toReplay(real), real, kind, words, record: `${file}${line ? ` line ${line}` : ""} · ${new Date(real).toISOString()}` });
117
+ };
118
+ const moves = show.events.filter((e) => e.kind === "write");
119
+ if (moves.length) {
120
+ const first = moves.reduce((a, e) => (e.t < a.t ? e : a));
121
+ const last = moves.reduce((a, e) => (e.t > a.t ? e : a));
122
+ add(first.t, "first", `first move: ${first.address}`, first.line);
123
+ add(last.t, "last", `last move: ${last.address}`, last.line);
124
+ }
125
+ for (const k of r.keyframes || []) add(k.t, "keyframe", "keyframe: each estate listed (live-ls)", k.line);
126
+ if (r.end) add(r.end.t, "end", "the recording's end", r.end.line);
127
+ return out.sort((a, b) => a.p - b.p);
128
+ }
@@ -0,0 +1,83 @@
1
+ // A recorded replay's timeline: wall-clock time one to one, an idle stretch
2
+ // played as a break that says how long it really was, ticks at the
3
+ // recording's own times, marks that name their line, and a label and a speed
4
+ // that always say this is a recording.
5
+ import { describe, it, expect } from "vitest";
6
+ import { readFileSync } from "node:fs";
7
+ import { gunzipSync } from "node:zlib";
8
+ import { fileURLToPath } from "node:url";
9
+ import { recordedClock, wallTicks, recordedLabel, speedWords, skippedWords, recordedMarks, clockWords, GAPS, RECORDED_SPEEDS } from "./dots-timeline.js";
10
+ import { readCarve, carveShow } from "./dots-recording.js";
11
+ import { parentsOf } from "./dots-layout.js";
12
+ import { replayClock } from "./dots-scene.js";
13
+
14
+ const T = Date.parse("2026-09-22T16:38:15Z");
15
+
16
+ describe("the recorded clock", () => {
17
+ it("plays wall-clock time one to one", () => {
18
+ const c = recordedClock([T + 1_000, T + 4_000], T, T + 6_000);
19
+ expect(c.length).toBe(6_000);
20
+ expect(c.toReplay(T + 4_000)).toBe(4_000);
21
+ expect(c.toReal(2_500)).toBe(T + 2_500);
22
+ expect(c.breaks).toEqual([]);
23
+ });
24
+
25
+ it("plays an idle stretch as a break that keeps the real gap's length", () => {
26
+ const c = recordedClock([T + 1_000, T + 61_000], T, T + 62_000);
27
+ expect(c.breaks).toHaveLength(1);
28
+ expect(c.breaks[0].skipped).toBe(60_000 - GAPS.keep);
29
+ expect(c.length).toBe(62_000 - c.breaks[0].skipped);
30
+ // Before the gap and after it, one to one.
31
+ expect(c.toReplay(T + 61_000) - c.toReplay(T + 61_000 - 500)).toBe(500);
32
+ expect(c.toReal(c.toReplay(T + 61_500))).toBe(T + 61_500);
33
+ expect(skippedWords(c.breaks[0].skipped)).toBe("+58 s skipped");
34
+ expect(skippedWords(125_000)).toBe("+2 min 5 s skipped");
35
+ });
36
+
37
+ it("ticks at the recording's own wall-clock times, never 0:00", () => {
38
+ // A write every 5 s for ten minutes: no stretch is idle, so none is skipped.
39
+ const c = recordedClock(Array.from({ length: 120 }, (_, i) => T + i * 5_000), T, T + 10 * 60_000);
40
+ expect(c.breaks).toEqual([]);
41
+ const ticks = wallTicks(c, 6);
42
+ expect(ticks.length).toBeGreaterThan(2);
43
+ expect(ticks[0].label).toMatch(/^16:\d\d$/);
44
+ for (const t of ticks) expect(clockWords(t.real)).toBe(t.label);
45
+ });
46
+ });
47
+
48
+ describe("what the timeline says", () => {
49
+ it("says it is a recording, when and from what, and shortens on a phone", () => {
50
+ const facts = { t0: T, t1: T + 34 * 60_000 + 44_000, source: "behold-terralith-14", plan: "domains" };
51
+ expect(recordedLabel(facts)).toMatch(/^Recorded 22 Sept? 2026, 16:38:15–17:12:59 UTC from behold-terralith-14 · plan domains$/);
52
+ expect(recordedLabel({ t0: T, t1: T + 60_000 })).not.toMatch(/from/);
53
+ expect(recordedLabel(facts, { short: true })).toBe("Recorded 16:38–17:12 UTC");
54
+ });
55
+
56
+ it("always says the speed in words", () => {
57
+ expect(speedWords(1)).toBe("1x real time");
58
+ expect(speedWords(0.1)).toBe("slowed ×10");
59
+ expect(speedWords(4)).toBe("sped up ×4");
60
+ expect(RECORDED_SPEEDS[0]).toBe(1);
61
+ });
62
+ });
63
+
64
+ describe("the committed recording on its own clock", () => {
65
+ const text = gunzipSync(readFileSync(fileURLToPath(new URL("../scripts/dot-bench/carve-terralith-14.jsonl.gz", import.meta.url)))).toString("utf8");
66
+ const rec = readCarve(text);
67
+ const show = carveShow(rec, parentsOf(rec.roster));
68
+
69
+ it("replays on the recording's clock, with a break for each listing pause", () => {
70
+ const clock = replayClock(show);
71
+ expect(clock.recorded).toBe(true);
72
+ expect(clock.length).toBe(show.timeline.length);
73
+ expect(show.timeline.breaks.length).toBeGreaterThan(0);
74
+ for (const b of show.timeline.breaks) expect(b.skipped).toBeGreaterThan(0);
75
+ });
76
+
77
+ it("marks the first and last move and each keyframe, each naming its line and time", () => {
78
+ const marks = recordedMarks(show, show.timeline, "carve-terralith-14.jsonl");
79
+ expect(marks.find((m) => m.kind === "first").record).toMatch(/^carve-terralith-14\.jsonl line \d+ · 2026-09-22T/);
80
+ expect(marks.filter((m) => m.kind === "keyframe")).toHaveLength(rec.keyframes.length);
81
+ for (const m of marks) expect(m.p).toBeGreaterThanOrEqual(0);
82
+ });
83
+ });
@@ -0,0 +1,153 @@
1
+ // The tour on the dots layer (behold.tour/v1): the chapter's visuals mapped
2
+ // onto the scene's boxes and dots, and what the kiosk's caption says about
3
+ // them. Pure: the tour's state (web/tour-player.js), the scene's names and
4
+ // the dots' owners in, plain data out. web/dots.js draws it.
5
+ //
6
+ // Each visual stands on what the server read for it (src/terragucci-tour.ts):
7
+ // a light is a resource a run's plan.json planned, a pulse is a root a wave's
8
+ // plan named, a travel is a plan's read threads and the output's planned
9
+ // value, the state object is a migration record's source version, and a check
10
+ // is a root whose post-write plan changes nothing.
11
+
12
+ import { chapterAt, shownAt, railOf, chapterLines, cardRows, firedBy } from "./tour-player.js";
13
+
14
+ const fmt = (n) => Number(n).toLocaleString("en-US");
15
+
16
+ /** The tour's chapter and its visuals now, from the answer's events; null with no tour. */
17
+ export function tourNow(answer) {
18
+ const tour = answer && answer.tour;
19
+ if (!tour) return null;
20
+ const at = chapterAt(tour, tour.events, Infinity, tour.step);
21
+ return { tour, at, shown: at ? shownAt(at.chapter, tour.events) : [] };
22
+ }
23
+
24
+ /** The box an estate is drawn in: an adopted estate is drawn in its stock root's box (the answer's `adopted`). */
25
+ export function boxOfEstates(estates, names, adopted = []) {
26
+ const alias = new Map((adopted || []).map((a) => [a.to, a.from]));
27
+ const set = names instanceof Set ? names : new Set(names);
28
+ for (const e of estates || []) {
29
+ const b = alias.get(e) ?? e;
30
+ if (set.has(b)) return b;
31
+ }
32
+ return null;
33
+ }
34
+
35
+ /** What the chapter frames: the source box, all of them, or the box its lights are in. */
36
+ export function tourFocus(tn, names, adopted) {
37
+ const f = tn && tn.at && tn.at.chapter.focus ? tn.at.chapter.focus.boxes : "all";
38
+ if (f === "source") return { kind: "source" };
39
+ if (f === "lit") {
40
+ const light = tn.shown.find((x) => x.kind === "light");
41
+ const b = light && light.lit.length ? boxOfEstates(light.lit[0].estates, names, adopted) : null;
42
+ if (b) return { kind: "box", estate: b };
43
+ }
44
+ return { kind: "all" };
45
+ }
46
+
47
+ /**
48
+ * The chapter's visuals mapped onto the scene. `ids`: the dots' ids (an
49
+ * address, or an address with `#n` when two estates name it); `owners`: each
50
+ * dot's box now; `source`: the source box.
51
+ */
52
+ export function tourFx(tn, { ids, owners, names, adopted, source }) {
53
+ const fx = { lights: new Map(), pulses: [], travel: null, state: null, checks: new Map() };
54
+ if (!tn || !tn.at) return fx;
55
+ const byAddr = new Map();
56
+ for (const id of ids) {
57
+ const base = id.replace(/#\d+$/, "");
58
+ if (!byAddr.has(base)) byAddr.set(base, []);
59
+ byAddr.get(base).push(id);
60
+ }
61
+ const box = (es) => boxOfEstates(es, names, adopted);
62
+ const timed = tn.shown.filter((x) => x.at !== null);
63
+ for (const s of tn.shown) {
64
+ if (s.kind === "light") {
65
+ for (const l of s.lit) {
66
+ const b = box(l.estates);
67
+ const cands = byAddr.get(l.address) || [];
68
+ const id = cands.find((x) => (owners.get(x) ?? source) === b) ?? (cands.length === 1 ? cands[0] : null);
69
+ if (id) fx.lights.set(id, { changed: l.changed, at: s.at });
70
+ }
71
+ } else if (s.kind === "pulse") {
72
+ // A wave's pulse runs until the chapter's next visual fires.
73
+ const later = timed.some((x) => x !== s && x.at > (s.at ?? -Infinity));
74
+ if (!later) for (const es of s.estates) {
75
+ const b = box(es);
76
+ if (b && !fx.pulses.includes(b)) fx.pulses.push(b);
77
+ }
78
+ } else if (s.kind === "travel") {
79
+ const threads = [];
80
+ for (const th of s.threads) {
81
+ const from = box(th.from);
82
+ const to = box(th.to);
83
+ if (from && to && from !== to && !threads.some((x) => x.from === from && x.to === to)) threads.push({ from, to });
84
+ }
85
+ if (threads.length) fx.travel = { threads, value: s.value ?? null, output: s.output, at: s.at };
86
+ } else if (s.kind === "state") {
87
+ const last = firedBy({ migration: s.migration, line: "last" }, tn.tour.events);
88
+ fx.state = { box: box(s.estates) ?? source, version: s.version_id, unchanged: !!(last && s.finished) };
89
+ } else if (s.kind === "checks") {
90
+ for (const c of s.checks) {
91
+ const b = box(c.estates);
92
+ if (b) fx.checks.set(b, c.noChange);
93
+ }
94
+ }
95
+ }
96
+ return fx;
97
+ }
98
+
99
+ /** The key of what tourFx draws, so it is rebuilt only when that changes. */
100
+ export function fxKey(tn, extra = "") {
101
+ if (!tn || !tn.at) return "";
102
+ return `${tn.at.chapter.id}|${tn.shown.map((x) => `${x.kind}@${x.at}`).join(",")}|${extra}`;
103
+ }
104
+
105
+ /**
106
+ * The tour as the kiosk's caption says it: the rail, the chapter's heading
107
+ * and lines, a note for each visual naming the record it stands on, the
108
+ * epilogue's card and the follow-along links. `counts`: each box's dots now;
109
+ * `short(e)`: a box's name as the boxes show it.
110
+ */
111
+ export function tourMessage(tn, { counts, names, adopted, source, short = (e) => e }) {
112
+ const tour = tn.tour;
113
+ const ch = tn.at.chapter;
114
+ const facts = tour.facts || {};
115
+ const notes = [];
116
+ const box = (es) => boxOfEstates(es, names, adopted);
117
+ for (const s of tn.shown) {
118
+ const job = s.job ? `job #${s.job}` : null;
119
+ if (s.kind === "light") {
120
+ const what = s.stage === "tf-plan" ? (s.pull ? `pull request ${s.pull}'s plan` : "the plan") : s.wave ? `wave ${s.wave}'s plan` : "the plan";
121
+ notes.push(`lit: the ${fmt(s.lit.length)} resources in ${what}${s.changed && s.changed < s.lit.length ? `, ${fmt(s.changed)} of them changed` : ""}${job ? ` · ${job}` : ""}`);
122
+ } else if (s.kind === "state") {
123
+ const last = firedBy({ migration: s.migration, line: "last" }, tour.events);
124
+ notes.push(`state file version ${String(s.version_id).slice(0, 8)}${last && s.finished ? ", unchanged" : ""}`);
125
+ } else if (s.kind === "counts") {
126
+ const parts = [...counts].filter(([e, n]) => e !== source && n > 0).sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([e, n]) => `${short(e)} ${fmt(n)}`);
127
+ if (parts.length) notes.push(parts.join(" · "));
128
+ } else if (s.kind === "checks") {
129
+ const name = (c) => (c.root === "." ? short(box(c.estates) || "root") : c.root);
130
+ const ok = s.checks.filter((c) => c.noChange).map(name);
131
+ const not = s.checks.filter((c) => !c.noChange).map(name);
132
+ if (ok.length) notes.push(`after the write, ${ok.join(", ")} plan${ok.length === 1 ? "s" : ""} no change${job ? ` · ${job}` : ""}`);
133
+ if (not.length) notes.push(`${not.join(", ")} still plan${not.length === 1 ? "s" : ""} a change`);
134
+ } else if (s.kind === "travel" && s.value !== undefined) {
135
+ const readers = [...new Set(s.threads.map((t) => box(t.to)).filter(Boolean).map(short))];
136
+ notes.push(`${s.output} = ${s.value}, as the plan has it, read by ${readers.join(", ")}`);
137
+ } else if (s.kind === "pulse") notes.push(`wave ${s.wave || 1} plans ${s.estates.map((es) => short(box(es) || es[0] || "")).filter(Boolean).join(", ")}${job ? ` · ${job}` : ""}`);
138
+ }
139
+ const card = tn.shown.find((x) => x.kind === "card");
140
+ return {
141
+ name: tour.name,
142
+ title: tour.title,
143
+ rail: railOf(tour, tn.at),
144
+ n: tn.at.index + 1,
145
+ of: tour.chapters.length,
146
+ id: ch.id,
147
+ heading: ch.title,
148
+ lines: chapterLines(ch, facts),
149
+ notes,
150
+ card: card ? cardRows(card.card, facts) : null,
151
+ links: tour.links || { pull: null, job: null },
152
+ };
153
+ }