@intentius/behold 0.29.39 → 0.29.41

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 (49) hide show
  1. package/AGENTS.md +148 -10
  2. package/README.md +6 -2
  3. package/dist/cli.js +15965 -13076
  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 +268 -0
  10. package/web/carve-narration.test.js +18 -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/index.html +29 -0
  34. package/web/kiosk-carve.js +219 -0
  35. package/web/kiosk-carve.test.js +26 -0
  36. package/web/kiosk-event-help-ui.js +6 -0
  37. package/web/kiosk.html +2 -1
  38. package/web/kiosk.js +21 -6
  39. package/web/operator.js +1 -1
  40. package/web/run-playhead.js +102 -19
  41. package/web/run-playhead.test.js +81 -11
  42. package/web/tour-player.js +204 -0
  43. package/web/tour-player.test.js +115 -0
  44. package/web/tours/behold.tour.v1.schema.json +182 -0
  45. package/web/tours/terralith.json +330 -0
  46. package/web/trunk-lane.js +254 -0
  47. package/web/trunk-lane.test.js +117 -0
  48. package/web/workspace-gates.js +29 -4
  49. package/web/workspace-gates.test.js +23 -2
@@ -0,0 +1,66 @@
1
+ // Points along an estate box's border, for the lights that run around it
2
+ // (#712): the draw-in head, the running light, the landing ripple and a
3
+ // failure's red segment. A box is {x, y, w, h}; a position on the border is
4
+ // its distance `s` clockwise from the top-left corner. Pure.
5
+
6
+ export function perimeter(b) {
7
+ return 2 * (Math.max(0, b.w) + Math.max(0, b.h));
8
+ }
9
+
10
+ /** The point at distance s (wrapped) clockwise from the top-left corner. */
11
+ export function pointAt(b, s) {
12
+ const P = perimeter(b);
13
+ if (!(P > 0)) return { x: b.x, y: b.y };
14
+ let d = ((s % P) + P) % P;
15
+ if (d <= b.w) return { x: b.x + d, y: b.y };
16
+ d -= b.w;
17
+ if (d <= b.h) return { x: b.x + b.w, y: b.y + d };
18
+ d -= b.h;
19
+ if (d <= b.w) return { x: b.x + b.w - d, y: b.y + b.h };
20
+ d -= b.w;
21
+ return { x: b.x, y: b.y + b.h - d };
22
+ }
23
+
24
+ /** The distance along the border of the border point nearest p. */
25
+ export function nearestS(b, p) {
26
+ const cx = Math.max(b.x, Math.min(b.x + b.w, p.x));
27
+ const cy = Math.max(b.y, Math.min(b.y + b.h, p.y));
28
+ const dl = Math.abs(cx - b.x);
29
+ const dr = Math.abs(b.x + b.w - cx);
30
+ const dt = Math.abs(cy - b.y);
31
+ const db = Math.abs(b.y + b.h - cy);
32
+ // Inside the box, project onto the nearest side; outside, the clamp is already on it.
33
+ const inside = p.x > b.x && p.x < b.x + b.w && p.y > b.y && p.y < b.y + b.h;
34
+ const m = inside ? Math.min(dl, dr, dt, db) : -1;
35
+ if ((inside && m === dt) || (!inside && cy === b.y)) return cx - b.x;
36
+ if ((inside && m === dr) || (!inside && cx === b.x + b.w)) return b.w + (cy - b.y);
37
+ if ((inside && m === db) || (!inside && cy === b.y + b.h)) return b.w + b.h + (b.x + b.w - cx);
38
+ return 2 * b.w + b.h + (b.y + b.h - cy);
39
+ }
40
+
41
+ /**
42
+ * A polyline along the border from s0 for `len` (negative runs anticlockwise),
43
+ * with a vertex at every corner it passes, so it bends where the box does.
44
+ */
45
+ export function segment(b, s0, len) {
46
+ const P = perimeter(b);
47
+ if (!(P > 0) || !len) return [];
48
+ const L = Math.max(-P, Math.min(P, len));
49
+ const corners = [0, b.w, b.w + b.h, 2 * b.w + b.h];
50
+ const pts = [pointAt(b, s0)];
51
+ const dir = Math.sign(L);
52
+ const a = s0;
53
+ const z = s0 + L;
54
+ // Every corner strictly between a and z, in travel order.
55
+ const between = [];
56
+ for (let k = Math.floor(Math.min(a, z) / P) - 1; k <= Math.ceil(Math.max(a, z) / P) + 1; k++) {
57
+ for (const c of corners) {
58
+ const s = c + k * P;
59
+ if ((dir > 0 && s > a && s < z) || (dir < 0 && s < a && s > z)) between.push(s);
60
+ }
61
+ }
62
+ between.sort((p, q) => (dir > 0 ? p - q : q - p));
63
+ for (const s of between) pts.push(pointAt(b, s));
64
+ pts.push(pointAt(b, z));
65
+ return pts;
66
+ }
@@ -0,0 +1,27 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { perimeter, pointAt, nearestS, segment } from "./dots-border.js";
3
+
4
+ const b = { x: 0, y: 0, w: 10, h: 4 };
5
+ describe("estate box borders (#712)", () => {
6
+ it("walks the border clockwise from the top-left corner", () => {
7
+ expect(perimeter(b)).toBe(28);
8
+ expect(pointAt(b, 0)).toEqual({ x: 0, y: 0 });
9
+ expect(pointAt(b, 10)).toEqual({ x: 10, y: 0 });
10
+ expect(pointAt(b, 12)).toEqual({ x: 10, y: 2 });
11
+ expect(pointAt(b, 19)).toEqual({ x: 5, y: 4 });
12
+ expect(pointAt(b, 26)).toEqual({ x: 0, y: 2 });
13
+ expect(pointAt(b, 28 + 12)).toEqual({ x: 10, y: 2 });
14
+ expect(pointAt(b, -2)).toEqual({ x: 0, y: 2 });
15
+ });
16
+ it("finds the nearest border point, inside or outside", () => {
17
+ expect(nearestS(b, { x: 5, y: -3 })).toBe(5);
18
+ expect(nearestS(b, { x: 9.5, y: 2 })).toBe(12);
19
+ expect(pointAt(b, nearestS(b, { x: 5, y: 3.8 }))).toEqual({ x: 5, y: 4 });
20
+ expect(pointAt(b, nearestS(b, { x: 0.2, y: 2 }))).toEqual({ x: 0, y: 2 });
21
+ });
22
+ it("bends a segment round the corners it passes, either way", () => {
23
+ expect(segment(b, 8, 4)).toEqual([{ x: 8, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 2 }]);
24
+ expect(segment(b, 2, -4)).toEqual([{ x: 2, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 2 }]);
25
+ expect(segment(b, 3, 0)).toEqual([]);
26
+ });
27
+ });
@@ -0,0 +1,279 @@
1
+ // The dots layer in the kiosk (#712, #715): what Watch says and frames as a carve
2
+ // replays. Every beat is read off the scene, which is the recording's moves
3
+ // flown by unit (web/dots-scene.js): who moved where, which landed, which
4
+ // were refused. Pure: scene and time in, words and a focus out.
5
+
6
+ /** The kiosk's loop: the replay plays, holds on its result, then starts again. */
7
+ export const LOOP = { holdMs: 10_000 };
8
+ /** How long a Tips bubble stays up, and the least time between two. */
9
+ export const TIP = { showMs: 4_200, gapMs: 1_200, staleMs: 9_000 };
10
+ /** The director changes what it frames at most this often. */
11
+ export const DIRECTOR = { holdMs: 2_600 };
12
+
13
+ const fmt = (n) => Number(n).toLocaleString("en-US");
14
+
15
+ export function shortName(e, source) {
16
+ return e !== source && e.startsWith(`${source}-`) ? e.slice(source.length + 1) : e;
17
+ }
18
+
19
+ /** The carve's facts, once per scene. */
20
+ export function carveStory(scene) {
21
+ const moves = scene.flights.filter((f) => !f.parent);
22
+ const landing = scene.flights.filter((f) => f.ok);
23
+ const refusals = moves.filter((f) => !f.ok);
24
+ const firstLanding = new Map();
25
+ for (const f of landing) if (!firstLanding.has(f.to) || f.end < firstLanding.get(f.to).end) firstLanding.set(f.to, f);
26
+ const dests = [...firstLanding.keys()].sort();
27
+ return {
28
+ source: scene.source,
29
+ moves,
30
+ dests,
31
+ firstLanding,
32
+ firstRefusal: refusals.reduce((a, f) => (!a || f.end < a.end ? f : a), null),
33
+ start: moves.length ? Math.min(...moves.map((f) => f.start)) : 0,
34
+ end: scene.flights.length ? Math.max(...scene.flights.map((f) => f.end)) : 0,
35
+ refused: refusals.length,
36
+ resourcesMoved: landing.length,
37
+ };
38
+ }
39
+
40
+ /** Each estate's count at t, a dot counted where it is until it lands. */
41
+ export function countsNow(scene, t) {
42
+ const owners = new Map(scene.show.owners0);
43
+ for (const f of scene.landing) if (f.end <= t) owners.set(f.address, f.to);
44
+ const c = new Map();
45
+ for (const e of owners.values()) c.set(e, (c.get(e) ?? 0) + 1);
46
+ return c;
47
+ }
48
+
49
+ /** The move flying most recently at t (not a child), or null. */
50
+ export function currentMove(story, t) {
51
+ let at = null;
52
+ for (const f of story.moves) if (f.start <= t && (!at || f.start > at.start)) at = f;
53
+ return at;
54
+ }
55
+
56
+ /**
57
+ * What Watch says at replay time t: the title, the line under it, how many
58
+ * moves are left, and what the director frames.
59
+ */
60
+ export function beatAt(story, scene, t) {
61
+ const src = story.source;
62
+ const n = story.dests.length;
63
+ const counts = countsNow(scene, t);
64
+ const left = story.moves.filter((f) => f.end > t).length;
65
+ const total = story.moves.length;
66
+ const next = { text: left ? `${fmt(left)} move${left === 1 ? "" : "s"} left` : "carve done", fraction: total ? (total - left) / total : 1 };
67
+ if (t < story.start) {
68
+ return {
69
+ phase: "start",
70
+ title: `Carving ${src} into ${n} team estates`,
71
+ line: { label: "now", text: `${fmt(counts.get(src) ?? 0)} resources in one estate, about to move by tag writes alone`, tone: "busy" },
72
+ next,
73
+ focus: { kind: "source" },
74
+ };
75
+ }
76
+ if (t >= story.end) {
77
+ const kept = counts.get(src) ?? 0;
78
+ return {
79
+ phase: "settled",
80
+ title: `Carved: ${n} estate${n === 1 ? "" : "s"}`,
81
+ line: {
82
+ label: "done",
83
+ text: `${fmt(story.resourcesMoved)} resources moved, nothing recreated` + (story.refused ? `; ${story.refused} moves refused, so ${fmt(kept)} stay in ${src}` : ""),
84
+ tone: "ok",
85
+ },
86
+ next,
87
+ focus: { kind: "all" },
88
+ };
89
+ }
90
+ const f = currentMove(story, t);
91
+ const refusedSoFar = story.moves.filter((m) => !m.ok && m.end <= t).length;
92
+ if (f && !f.ok) {
93
+ return {
94
+ phase: "carve",
95
+ title: `Carving ${src} into ${n} team estates`,
96
+ line: { label: "refused", text: `${f.address}: ${refusedSoFar > 1 ? `${refusedSoFar} moves refused` : "the move is refused"}; ${refusedSoFar > 1 ? "they stay" : "it stays"} in ${src}`, tone: "bad" },
97
+ next,
98
+ focus: { kind: "estate", estate: src },
99
+ };
100
+ }
101
+ const to = f ? f.to : src;
102
+ return {
103
+ phase: "carve",
104
+ title: `Carving ${src} into ${n} team estates`,
105
+ line: { label: "moving", text: `${shortName(to, src)}: ${fmt(counts.get(to) ?? 0)} resources moved, nothing recreated`, tone: "busy" },
106
+ next,
107
+ focus: { kind: "estate", estate: to },
108
+ };
109
+ }
110
+
111
+ /**
112
+ * The Tips bubbles that fire in (from, to]: each estate's first landing, the
113
+ * first refusal, and the end. Each has a key, so a loop shows it once.
114
+ */
115
+ export function tipsBetween(story, from, to) {
116
+ const src = story.source;
117
+ const out = [];
118
+ const inWin = (t) => t > from && t <= to;
119
+ for (const e of story.dests) {
120
+ const f = story.firstLanding.get(e);
121
+ if (f && inWin(f.end)) out.push({ key: `land:${e}`, at: f.end, recordedAt: f.at, estate: e, tone: "ok", title: `${shortName(e, src)}: the first landing`, text: `${shortName(e, src)}: its first resource lands. live-mv rewrote the ownership tags; nothing was recreated.` });
122
+ }
123
+ const r = story.firstRefusal;
124
+ if (r && inWin(r.end)) {
125
+ const why = r.refusalSummary ? r.refusalSummary.replace(/\.$/, "").toLowerCase() : r.refusal || "refused";
126
+ out.push({ key: "refused", at: r.end, recordedAt: r.at, estate: src, address: r.address, tone: "bad", title: "A move is refused", text: `${r.address} is refused: ${why}. Nothing was written, so it stays in ${src}.` });
127
+ }
128
+ if (inWin(story.end)) out.push({ key: "end", at: story.end, recordedAt: story.moves.reduce((m, f) => Math.max(m, f.at || 0), 0) || null, estate: null, tone: "ok", title: "Carved", text: `Carved into ${story.dests.length} estate${story.dests.length === 1 ? "" : "s"} by tag writes alone: ${fmt(story.resourcesMoved)} resources moved, none recreated.` });
129
+ return out.sort((a, b) => a.at - b.at);
130
+ }
131
+
132
+ /** What the director frames: a focus held at least DIRECTOR.holdMs before it changes. */
133
+ export function directorFocus(prev, want, wall) {
134
+ const same = prev && prev.focus.kind === want.kind && prev.focus.estate === want.estate;
135
+ if (same) return prev;
136
+ // The start and the end always take over; a move to another estate waits its turn.
137
+ if (prev && want.kind === "estate" && prev.focus.kind === "estate" && wall - prev.since < DIRECTOR.holdMs) return prev;
138
+ return { focus: want, since: wall };
139
+ }
140
+
141
+ // --- the live carve (#715) -------------------------------------------------------
142
+ // The same beats over a carve that is being written: the title and the next
143
+ // line come from demo.json while a migration runs ("carve: 36 of 79 moved"),
144
+ // the line under the title from the newest progress line, and the end is the
145
+ // migration's own finish, not the last flight.
146
+
147
+ /** After a live carve ends, Watch holds on the result this long before handing the camera back. */
148
+ export const LIVE_HOLD_MS = 12_000;
149
+
150
+ const lineWords = {
151
+ moved: "moving",
152
+ stamped: "adopting",
153
+ refused: "refused",
154
+ };
155
+
156
+ /** The newest event of the show that has started by replay time t: a write's flight, or an adoption. */
157
+ export function latestEvent(scene, t) {
158
+ let at = null;
159
+ for (const f of scene.flights) if (!f.parent && f.start <= t && (!at || f.start >= at.start)) at = { ...f, kind: f.ok ? "moved" : "refused" };
160
+ const t0 = scene.show.t0;
161
+ for (const e of scene.show.events) {
162
+ if (e.kind !== "adopt" || e.before) continue;
163
+ const s = e.start - t0;
164
+ if (s <= t && (!at || s >= at.start)) at = { kind: "stamped", address: e.address, start: s, to: null, from: null };
165
+ }
166
+ return at;
167
+ }
168
+
169
+ /**
170
+ * What Watch says over a live carve at replay time t. `ctx`: { demo, migration }
171
+ * from the route's answer (demo.json's fields, and the migration in view).
172
+ */
173
+ export function liveBeat(scene, t, ctx = {}) {
174
+ const src = scene.source;
175
+ const story = carveStory(scene);
176
+ const counts = countsNow(scene, t);
177
+ const m = ctx.migration || null;
178
+ const demo = ctx.demo || null;
179
+ // The counts as played (web/dots-live.js playedCounts): the caption and the next line say the same numbers.
180
+ const shown = ctx.shown || null;
181
+ const c = m ? (shown ? shown.counts : m.counts) : null;
182
+ const total = c ? c.moved + c.stamped + c.refused + c.skipped + (c.left ?? 0) : story.moves.length;
183
+ const doneN = c ? c.moved + c.stamped + c.refused + c.skipped : story.moves.filter((f) => f.end <= t).length;
184
+ // demo.json's next line names the migration with the driver's count, read when it last looked; the page's own count replaces it.
185
+ const named = demo && demo.next ? /^\s*([^:\s]+):\s+\d+\s+of\s+\d+\s+(?:moved|stamped)\b/.exec(demo.next) : null;
186
+ const ours = !!(shown && m && (!demo || !demo.next || (named && named[1] === m.name)));
187
+ const nextText = ours
188
+ ? `${m.name}: ${fmt(doneN)} of ${fmt(total)} ${c.stamped && !c.moved ? "stamped" : "moved"}`
189
+ : demo && demo.next
190
+ ? demo.next
191
+ : m
192
+ ? `${m.name}: ${fmt(c.moved + c.stamped)} of ${fmt(total)} ${c.stamped && !c.moved ? "stamped" : "moved"}`
193
+ : "no migration running";
194
+ const next = { text: nextText, fraction: total ? Math.min(1, doneN / total) : 0 };
195
+ const title = demo && demo.title ? demo.title : m ? `Carving ${src}: ${m.name}` : src;
196
+ const ev = latestEvent(scene, t);
197
+ const running = !!(m && (m.running || (shown && shown.playing)));
198
+ if (!ev) {
199
+ return {
200
+ phase: running ? "start" : "stock",
201
+ title,
202
+ line: { label: "now", text: `${fmt(counts.get(src) ?? 0)} resources in ${src}${running ? ", the migration is starting" : ""}`, tone: running ? "busy" : "idle" },
203
+ next,
204
+ focus: { kind: "source" },
205
+ };
206
+ }
207
+ if (!running && m) {
208
+ const kept = counts.get(src) ?? 0;
209
+ const r = resourceCounts(m);
210
+ const n = [...counts.entries()].filter(([e, v]) => v > 0 && e !== src).length;
211
+ return {
212
+ phase: "settled",
213
+ title,
214
+ line: {
215
+ label: "done",
216
+ text: `${m.name}: ${fmt(r.moved)} resources moved, ${fmt(r.stamped)} stamped, nothing recreated` + (r.refused ? `; ${r.refused} refused, so ${fmt(kept)} stay in ${src}` : "") + (n ? ` · ${n} estate${n === 1 ? "" : "s"} beside ${src}` : ""),
217
+ tone: r.refused ? "bad" : "ok",
218
+ },
219
+ next: { ...next, fraction: 1 },
220
+ focus: { kind: "all" },
221
+ };
222
+ }
223
+ if (ev.kind === "refused") {
224
+ return { phase: "carve", title, line: { label: "refused", text: `${ev.address}: ${ev.refusalSummary || "the move is refused"}; it stays in ${shortName(ev.from || src, src)}`, tone: "bad" }, next, focus: { kind: "estate", estate: ev.from || src } };
225
+ }
226
+ if (ev.kind === "stamped") {
227
+ return { phase: "carve", title, line: { label: lineWords.stamped, text: `${ev.address} wears its estate's tags now; nothing was recreated`, tone: "busy" }, next, focus: { kind: "source" } };
228
+ }
229
+ return { phase: "carve", title, line: { label: lineWords.moved, text: `${shortName(ev.to, src)}: ${fmt(counts.get(ev.to) ?? 0)} resources, moved by tag writes, nothing recreated`, tone: "busy" }, next, focus: { kind: "estate", estate: ev.to } };
230
+ }
231
+
232
+ /**
233
+ * The live carve's Tips that fire in (from, to]: each estate's first landing
234
+ * and the first refusal, from the flights. The end is told by the caller when
235
+ * the migration finishes ({@link liveEndTip}). Keys are stable across reads, so
236
+ * a bubble shows once however often the scene is rebuilt.
237
+ */
238
+ export function liveTipsBetween(scene, from, to) {
239
+ const story = carveStory(scene);
240
+ const src = story.source;
241
+ const out = [];
242
+ const inWin = (t) => t > from && t <= to;
243
+ for (const e of story.dests) {
244
+ const f = story.firstLanding.get(e);
245
+ if (f && inWin(f.end)) out.push({ key: `land:${e}`, at: f.end, recordedAt: f.at, estate: e, tone: "ok", title: `${shortName(e, src)}: the first landing`, text: `${shortName(e, src)}: its first resource lands. The migration rewrote the ownership tags; nothing was recreated.` });
246
+ }
247
+ const r = story.firstRefusal;
248
+ if (r && inWin(r.end)) {
249
+ const why = r.refusalSummary ? r.refusalSummary.replace(/\.$/, "") : r.refusal || "refused";
250
+ out.push({ key: "refused", at: r.end, recordedAt: r.at, estate: r.from || src, address: r.address, tone: "bad", title: "A move is refused", text: `${r.address} is refused: ${why}. Nothing was written, so it stays in ${shortName(r.from || src, src)}.` });
251
+ }
252
+ return out.sort((a, b) => a.at - b.at);
253
+ }
254
+
255
+ /**
256
+ * A migration's counts in resources, not lines: a follower of two parents has
257
+ * a moved line under each (terragucci#1146), so the record's line counts can
258
+ * say 45 where 39 resources moved. With no lines, the record's own counts.
259
+ */
260
+ export function resourceCounts(migration) {
261
+ const lines = (migration && migration.lines) || [];
262
+ if (!lines.length) return migration ? migration.counts : null;
263
+ const n = (o) => new Set(lines.filter((l) => l.outcome === o).map((l) => l.live_id || l.address)).size;
264
+ return { ...migration.counts, moved: n("moved"), stamped: n("stamped"), refused: n("refused"), skipped: n("skipped") };
265
+ }
266
+
267
+ /** The Tip for a migration that has just finished. */
268
+ export function liveEndTip(migration, t) {
269
+ const c = resourceCounts(migration);
270
+ return {
271
+ key: `end:${migration.name}`,
272
+ at: t,
273
+ recordedAt: null,
274
+ estate: null,
275
+ tone: c.refused ? "bad" : "ok",
276
+ title: `${migration.name}: done`,
277
+ text: `${migration.name} is done: ${fmt(c.moved)} resources moved and ${fmt(c.stamped)} stamped by tag writes alone, none recreated${c.refused ? `; ${c.refused} refused, left where they were` : ""}.`,
278
+ };
279
+ }
@@ -0,0 +1,60 @@
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 } from "./dots-layout.js";
7
+ import { buildScene } from "./dots-scene.js";
8
+ import { carveStory, beatAt, tipsBetween, directorFocus, DIRECTOR, shortName } from "./dots-kiosk.js";
9
+
10
+ const text = gunzipSync(readFileSync(fileURLToPath(new URL("../scripts/dot-bench/carve-terralith-14.jsonl.gz", import.meta.url)))).toString("utf8");
11
+ const rec = readCarve(text);
12
+ const scene = buildScene(carveShow(rec, parentsOf(rec.roster)));
13
+ const story = carveStory(scene);
14
+ const src = "behold-terralith-14";
15
+
16
+ describe("the kiosk's carve beats (#712)", () => {
17
+ it("reads the carve's facts off the recording", () => {
18
+ expect(story.moves).toHaveLength(463);
19
+ expect(story.refused).toBe(14);
20
+ expect(story.dests).toHaveLength(8);
21
+ expect(story.firstRefusal.ok).toBe(false);
22
+ });
23
+ it("starts on one estate, says what moves, and ends carved", () => {
24
+ const start = beatAt(story, scene, 0);
25
+ expect(start.phase).toBe("start");
26
+ expect(start.title).toBe(`Carving ${src} into 8 team estates`);
27
+ expect(start.next.text).toBe("463 moves left");
28
+ expect(start.focus).toEqual({ kind: "source" });
29
+ const mid = beatAt(story, scene, (story.start + story.end) / 2);
30
+ expect(mid.phase).toBe("carve");
31
+ expect(mid.line.text).toMatch(/^(\w+: \d+ resources moved, nothing recreated|.+refused.+)$/);
32
+ const end = beatAt(story, scene, story.end);
33
+ expect(end.title).toBe("Carved: 8 estates");
34
+ expect(end.line.text).toMatch(/14 moves refused, so \d+ stay in behold-terralith-14/);
35
+ expect(end.next.fraction).toBe(1);
36
+ expect(end.focus).toEqual({ kind: "all" });
37
+ });
38
+ it("names a refusal while it is the latest move", () => {
39
+ const r = story.firstRefusal;
40
+ const b = beatAt(story, scene, r.start + 1);
41
+ expect(b.line.tone).toBe("bad");
42
+ expect(b.line.text).toContain(r.address);
43
+ });
44
+ it("tips each estate's first landing, the first refusal and the end, once each", () => {
45
+ const all = tipsBetween(story, -1, story.end);
46
+ expect(all.filter((t) => t.key.startsWith("land:"))).toHaveLength(8);
47
+ expect(all.filter((t) => t.key === "refused")).toHaveLength(1);
48
+ expect(all.at(-1).key).toBe("end");
49
+ const halves = [...tipsBetween(story, -1, story.end / 2), ...tipsBetween(story, story.end / 2, story.end)];
50
+ expect(halves.map((t) => t.key).sort()).toEqual(all.map((t) => t.key).sort());
51
+ expect(all.find((t) => t.key === "refused").text).toMatch(/Nothing was written/);
52
+ });
53
+ it("holds a framing before moving to another estate, but not at the start or end", () => {
54
+ const a = directorFocus(null, { kind: "estate", estate: "x" }, 0);
55
+ expect(directorFocus(a, { kind: "estate", estate: "y" }, DIRECTOR.holdMs - 1)).toBe(a);
56
+ expect(directorFocus(a, { kind: "estate", estate: "y" }, DIRECTOR.holdMs + 1).focus.estate).toBe("y");
57
+ expect(directorFocus(a, { kind: "all" }, 10).focus.kind).toBe("all");
58
+ expect(shortName(`${src}-billing`, src)).toBe("billing");
59
+ });
60
+ });
@@ -0,0 +1,10 @@
1
+ // Types for src/dots-preview.ts, which orders the cards with the page's own layout (#712).
2
+ export function parseAddress(address: string): { module: string; type: string; name: string; index: string };
3
+ export function unitOf(address: string, type?: string): string;
4
+ export function unitsOf(roster: Array<{ address: string; type: string; taggable: boolean }>): any[];
5
+ export function parentsOf(roster: Array<{ address: string; type: string; taggable: boolean }>): Map<string, string>;
6
+ export function ringsOf(n: number, start?: number): Array<{ r: number; n: number }>;
7
+ export function unitCell(u: any): { rings: Array<{ r: number; n: number }>; shift: number; cell: number };
8
+ export function blockWidth(units: any[], aspect?: number): number;
9
+ export function packBlock(units: any[], opts?: { width?: number; fromEnd?: boolean }): any;
10
+ export function shelfPack(boxes: Array<{ key: string; w: number; h: number }>, opts: { width: number; gap?: number }): Map<string, { x: number; y: number }>;
@@ -0,0 +1,201 @@
1
+ // The dots layer's layout (#712, #715, after #457's scripts/dot-bench/layout.js).
2
+ //
3
+ // Inside an estate's box, a dot's slot is a function of what the resource is:
4
+ // its unit (module path, block stem without its role suffix, count index),
5
+ // with the unit's anchor in the middle, its other taggable members beside it
6
+ // and its untaggable members on rings round them. Which box a dot is in is its
7
+ // owner's (web/dots-scene.js places the boxes). Pure: roster in, positions out.
8
+
9
+ const ROLE_SUFFIXES = [
10
+ "_managed_attach", "_custom_attach", "_attach", "_inline", "_policy", "_profile", "_role",
11
+ "_exec", "_execution", "_task", "_taskdef", "_service", "_svc",
12
+ ];
13
+ const ANCHOR_TYPES = ["aws_iam_role", "aws_ecs_service", "aws_route53_zone", "aws_vpc"];
14
+
15
+ /** `module.team_pod["pod-a"].aws_iam_role.pod_role[3]` -> { module, type, name, index }. */
16
+ export function parseAddress(address) {
17
+ const parts = [];
18
+ let depth = 0;
19
+ let cur = "";
20
+ for (const ch of address) {
21
+ if (ch === "[") depth++;
22
+ if (ch === "]") depth--;
23
+ if (ch === "." && depth === 0) {
24
+ parts.push(cur);
25
+ cur = "";
26
+ } else cur += ch;
27
+ }
28
+ parts.push(cur);
29
+ const modules = [];
30
+ while (parts[0] === "module") {
31
+ modules.push(`module.${parts[1]}`);
32
+ parts.splice(0, 2);
33
+ }
34
+ if (parts[0] === "data") parts.shift();
35
+ const type = parts[0] ?? "";
36
+ const m = /^([^[]+)(\[.*\])?$/.exec(parts[1] ?? "");
37
+ return { module: modules.join("."), type, name: m ? m[1] : "", index: m && m[2] ? m[2] : "" };
38
+ }
39
+
40
+ /** The unit a resource belongs to: its module path, its block stem and its count index. */
41
+ export function unitOf(address, type) {
42
+ const a = parseAddress(address);
43
+ if (/^aws_route53_/.test(type || a.type)) return `${a.module}|dns`;
44
+ let stem = a.name;
45
+ for (const s of ROLE_SUFFIXES) {
46
+ if (stem.endsWith(s) && stem.length > s.length) {
47
+ stem = stem.slice(0, -s.length);
48
+ break;
49
+ }
50
+ }
51
+ if (/^pod(_|$)/.test(stem)) stem = "pod";
52
+ // A short numbered suffix (`team_a_0`, `team_a_2`: one team's log groups)
53
+ // is the same unit; a generated four-digit id (`svc_0007`) is its own.
54
+ stem = stem.replace(/_\d{1,2}$/, "");
55
+ // A for_each key on a resource (records["www"]) is not a unit of its own;
56
+ // a count index on a team block is, since each index is a whole team.
57
+ const index = /^\["/.test(a.index) ? "" : a.index;
58
+ return `${a.module}|${stem}${index}`;
59
+ }
60
+
61
+ const byAddress = (a, b) => (a.address < b.address ? -1 : a.address > b.address ? 1 : 0);
62
+
63
+ /** roster [{address, type, taggable}] -> [{key, anchor, others, children}] in key order. */
64
+ export function unitsOf(roster) {
65
+ const units = new Map();
66
+ for (const r of roster) {
67
+ const key = unitOf(r.address, r.type);
68
+ let u = units.get(key);
69
+ if (!u) units.set(key, (u = { key, members: [] }));
70
+ u.members.push(r);
71
+ }
72
+ return [...units.values()]
73
+ .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
74
+ .map((u) => {
75
+ const taggable = u.members.filter((m) => m.taggable).sort(byAddress);
76
+ const children = u.members.filter((m) => !m.taggable).sort(byAddress);
77
+ const anchor = taggable.find((m) => ANCHOR_TYPES.includes(m.type)) ?? taggable[0] ?? children.shift();
78
+ return { key: u.key, anchor, others: taggable.filter((m) => m !== anchor), children };
79
+ });
80
+ }
81
+
82
+ /** Address -> the anchor of its unit, for every untaggable member (a follower's parent). */
83
+ export function parentsOf(roster) {
84
+ const out = new Map();
85
+ for (const u of unitsOf(roster)) for (const c of u.children) out.set(c.address, u.anchor.address);
86
+ return out;
87
+ }
88
+
89
+ /**
90
+ * The rings a unit's untaggable members sit on: concentric, one pitch apart,
91
+ * each holding as many as fit at one pitch spacing, so a zone with 140
92
+ * records is a compact disc of rings rather than one huge ring.
93
+ */
94
+ export function ringsOf(n, start = 1.6) {
95
+ const rings = [];
96
+ let r = start;
97
+ let left = n;
98
+ while (left > 0) {
99
+ const cap = Math.max(4, Math.floor(2 * Math.PI * r));
100
+ const k = Math.min(cap, left);
101
+ rings.push({ r, n: k });
102
+ left -= k;
103
+ r += 1;
104
+ }
105
+ return rings;
106
+ }
107
+
108
+ /** A unit's square cell, in dot pitches: its anchor and taggable members in the middle, the rings around them. */
109
+ export function unitCell(u) {
110
+ // With taggable members round the anchor, the rings start outside them.
111
+ const rings = ringsOf(u.children.length, u.others.length ? 2.2 : 1.6);
112
+ const core = 1 + Math.ceil(u.others.length / 2);
113
+ // The core's members sit one pitch from the anchor; rings start outside them.
114
+ const shift = u.others.length > 6 ? Math.ceil(u.others.length / 6) : 0;
115
+ const outer = rings.length ? rings[rings.length - 1].r + shift : 0;
116
+ return { rings, shift, cell: 2 * Math.max(outer + 1, core) + 1 };
117
+ }
118
+
119
+ /** The row width (in pitches) that keeps a block of these units near `aspect` (width / height). */
120
+ export function blockWidth(units, aspect = 1.3) {
121
+ const cells = units.map((u) => unitCell(u).cell);
122
+ const area = cells.reduce((s, c) => s + c * c, 0);
123
+ return Math.max(Math.sqrt(area * aspect) * 1.04, ...cells, 1);
124
+ }
125
+
126
+ /**
127
+ * The dot slots of one block, in pitches. Units are packed into rows of a
128
+ * fixed `width`, so a box keeps its width as units come and go.
129
+ *
130
+ * `fromEnd` packs from the last unit backwards, right to left and bottom to
131
+ * top, with the bottom edge at y = 0 (slots have y <= 0). A unit's slot then
132
+ * depends only on the units after it, so units leaving from the front (the
133
+ * carve takes them in unit order) never move the ones that stay: the box just
134
+ * loses its top rows. Reading order is kept: the first unit is still top-left.
135
+ * Without it, units are packed from the top-left, and a unit appended at the
136
+ * end never moves the ones before it.
137
+ */
138
+ export function packBlock(units, { width = blockWidth(units), fromEnd = false } = {}) {
139
+ const list = fromEnd ? [...units].reverse() : units;
140
+ const slots = new Map();
141
+ let x = 0;
142
+ let y = 0;
143
+ let rowH = 0;
144
+ let maxX = 0;
145
+ for (const u of list) {
146
+ const { rings, shift, cell } = unitCell(u);
147
+ if (x + cell > width && x > 0) {
148
+ x = 0;
149
+ y += rowH;
150
+ rowH = 0;
151
+ }
152
+ const put = (a, px, py, parent) => {
153
+ const sx = fromEnd ? width - px : px;
154
+ const sy = fromEnd ? -py : py;
155
+ slots.set(a, parent ? { x: sx, y: sy, parent } : { x: sx, y: sy });
156
+ };
157
+ const cx = x + cell / 2;
158
+ const cy = y + cell / 2;
159
+ put(u.anchor.address, cx, cy);
160
+ u.others.forEach((m, i) => {
161
+ const a = (i / Math.max(1, u.others.length)) * Math.PI * 2;
162
+ const r = 1 + Math.floor(i / 6) * 0.9;
163
+ put(m.address, cx + Math.cos(a) * r, cy + Math.sin(a) * r);
164
+ });
165
+ let j = 0;
166
+ for (const ring of rings) {
167
+ for (let q = 0; q < ring.n; q++, j++) {
168
+ const a = (q / ring.n) * Math.PI * 2 - Math.PI / 2;
169
+ const r = ring.r + shift;
170
+ put(u.children[j].address, cx + Math.cos(a) * r, cy + Math.sin(a) * r, u.anchor.address);
171
+ }
172
+ }
173
+ x += cell;
174
+ maxX = Math.max(maxX, x);
175
+ rowH = Math.max(rowH, cell);
176
+ }
177
+ const h = y + rowH;
178
+ return { slots, w: fromEnd ? width : maxX, h, top: fromEnd ? -h : 0 };
179
+ }
180
+
181
+ /**
182
+ * Shelf-pack boxes (each {key, w, h}) in the given order into rows about
183
+ * `width` wide, with `gap` between them. Returns Map<key, {x, y}> (top-left).
184
+ */
185
+ export function shelfPack(boxes, { width, gap = 0 }) {
186
+ const out = new Map();
187
+ let x = 0;
188
+ let y = 0;
189
+ let rowH = 0;
190
+ for (const b of boxes) {
191
+ if (x > 0 && x + b.w > width) {
192
+ x = 0;
193
+ y += rowH + gap;
194
+ rowH = 0;
195
+ }
196
+ out.set(b.key, { x, y });
197
+ x += b.w + gap;
198
+ rowH = Math.max(rowH, b.h);
199
+ }
200
+ return out;
201
+ }