@intentius/behold 0.29.40 → 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 (48) 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.js +21 -6
  38. package/web/operator.js +1 -1
  39. package/web/run-playhead.js +102 -19
  40. package/web/run-playhead.test.js +81 -11
  41. package/web/tour-player.js +204 -0
  42. package/web/tour-player.test.js +115 -0
  43. package/web/tours/behold.tour.v1.schema.json +182 -0
  44. package/web/tours/terralith.json +330 -0
  45. package/web/trunk-lane.js +254 -0
  46. package/web/trunk-lane.test.js +117 -0
  47. package/web/workspace-gates.js +29 -4
  48. package/web/workspace-gates.test.js +23 -2
@@ -0,0 +1,142 @@
1
+ // The static carve export's page (#712): `npm run export:carve` bundles this
2
+ // with the dots layer and the theme into one HTML file, with the card SVG and
3
+ // the recording inlined, so it opens from a web host or straight from disk
4
+ // with no behold server behind it.
5
+ //
6
+ // It replays the recording by itself and loops, holding on the result. The
7
+ // camera follows the flock until a person takes it (pinch, scroll, drag);
8
+ // zooming works as in the app's preview: cards, then dots, then discs.
9
+
10
+ import { initTheme, mountThemePicker, KIOSK_THEME } from "./theme.js";
11
+ import { mountDots, dotsCamera, dotsZoomOutFactor } from "./dots.js";
12
+ import { createNarration } from "./carve-narration.js";
13
+
14
+ async function gunzipBase64(b64) {
15
+ const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
16
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
17
+ return new Response(stream).text();
18
+ }
19
+
20
+ async function main() {
21
+ initTheme(KIOSK_THEME);
22
+ mountThemePicker(document.getElementById("cx-theme"));
23
+ const data = JSON.parse(document.getElementById("cx-data").textContent);
24
+ const source = data.kind === "carve" ? { kind: "carve", name: data.name, text: await gunzipBase64(data.gz) } : { kind: "walkthrough", name: data.name, model: data.model };
25
+
26
+ const host = document.getElementById("graph");
27
+ const svg = host.querySelector("svg");
28
+ svg.removeAttribute("width");
29
+ svg.removeAttribute("height");
30
+ svg.setAttribute("preserveAspectRatio", "xMidYMid meet");
31
+ const vbInit = svg.getAttribute("viewBox").split(/\s+/).map(Number);
32
+ // The fit: the whole card graph, at the pane's own aspect, so the pane maps to the viewBox at one scale.
33
+ const fitted = () => {
34
+ const r = host.getBoundingClientRect();
35
+ const s = Math.min(r.width / vbInit[2], r.height / vbInit[3]);
36
+ const w = r.width / s;
37
+ const h = r.height / s;
38
+ return [vbInit[0] - (w - vbInit[2]) / 2, vbInit[1] - (h - vbInit[3]) / 2, w, h];
39
+ };
40
+ let vb = fitted();
41
+ const apply = () => {
42
+ svg.setAttribute("viewBox", vb.join(" "));
43
+ dotsCamera();
44
+ };
45
+ apply();
46
+
47
+ // The camera by hand: scroll or pinch zooms at the pointer, a drag pans.
48
+ // The SVG may be out of layout at the dot level; it always fills the host.
49
+ const zoomAt = (cx, cy, f) => {
50
+ const r = host.getBoundingClientRect();
51
+ const px = vb[0] + ((cx - r.left) / r.width) * vb[2];
52
+ const py = vb[1] + ((cy - r.top) / r.height) * vb[3];
53
+ const nw = Math.min(vbInit[2] * (dotsZoomOutFactor() ?? 3), Math.max(vbInit[2] / 60, vb[2] * f));
54
+ const nh = nw * (vb[3] / vb[2]);
55
+ vb = [px - ((px - vb[0]) * nw) / vb[2], py - ((py - vb[1]) * nh) / vb[3], nw, nh];
56
+ apply();
57
+ };
58
+ host.addEventListener(
59
+ "wheel",
60
+ (e) => {
61
+ e.preventDefault();
62
+ zoomAt(e.clientX, e.clientY, Math.exp(e.deltaY * (e.ctrlKey ? 0.01 : 0.0025)));
63
+ },
64
+ { passive: false },
65
+ );
66
+ let drag = null;
67
+ host.addEventListener("mousedown", (e) => {
68
+ if (e.target.closest && e.target.closest("button, select, input")) return;
69
+ drag = { x: e.clientX, y: e.clientY };
70
+ });
71
+ window.addEventListener("mousemove", (e) => {
72
+ if (!drag) return;
73
+ const r = host.getBoundingClientRect();
74
+ vb[0] -= ((e.clientX - drag.x) / r.width) * vb[2];
75
+ vb[1] -= ((e.clientY - drag.y) / r.height) * vb[3];
76
+ drag = { x: e.clientX, y: e.clientY };
77
+ apply();
78
+ });
79
+ window.addEventListener("mouseup", () => (drag = null));
80
+ let touch = null;
81
+ const pts = (e) => [...e.touches].map((t) => ({ x: t.clientX, y: t.clientY }));
82
+ host.addEventListener("touchstart", (e) => (touch = pts(e)), { passive: true });
83
+ host.addEventListener(
84
+ "touchmove",
85
+ (e) => {
86
+ if (!touch) return;
87
+ e.preventDefault();
88
+ const p = pts(e);
89
+ const r = host.getBoundingClientRect();
90
+ if (p.length >= 2 && touch.length >= 2) {
91
+ const d = (q) => Math.hypot(q[0].x - q[1].x, q[0].y - q[1].y) || 1;
92
+ zoomAt((p[0].x + p[1].x) / 2, (p[0].y + p[1].y) / 2, d(touch) / d(p));
93
+ } else if (p.length === 1 && touch.length === 1) {
94
+ vb[0] -= ((p[0].x - touch[0].x) / r.width) * vb[2];
95
+ vb[1] -= ((p[0].y - touch[0].y) / r.height) * vb[3];
96
+ apply();
97
+ }
98
+ touch = p;
99
+ },
100
+ { passive: false },
101
+ );
102
+ host.addEventListener("touchend", (e) => (touch = e.touches.length ? pts(e) : null));
103
+
104
+ const caption = document.getElementById("cx-caption");
105
+ const narration = createNarration({
106
+ bar: document.getElementById("cx-bar"),
107
+ caption,
108
+ tipsHost: document.getElementById("eh-tips"),
109
+ modalHost: document.getElementById("eh-modals"),
110
+ origin: () => host.getBoundingClientRect(),
111
+ });
112
+ await mountDots({
113
+ host,
114
+ svg,
115
+ meta: { dots: { source: data.name } },
116
+ vbInit,
117
+ getVB: () => vb,
118
+ setVB: (a) => {
119
+ vb = a.slice();
120
+ apply();
121
+ },
122
+ source,
123
+ auto: { narrate: (msg) => narration.update(msg), bar: true },
124
+ });
125
+ // The director keeps the boxes clear of the caption over the graph's foot.
126
+ const insets = () => {
127
+ const g = host.getBoundingClientRect();
128
+ const c = caption.getBoundingClientRect();
129
+ const over = c.height && c.top < g.bottom && c.bottom > g.top ? g.bottom - c.top : 0;
130
+ if (window.__dots) window.__dots.setInsets({ top: 0, bottom: Math.max(0, Math.round(over)) });
131
+ };
132
+ insets();
133
+ if (typeof ResizeObserver === "function") new ResizeObserver(insets).observe(caption);
134
+ window.addEventListener("resize", insets);
135
+ }
136
+
137
+ main().catch((err) => {
138
+ const p = document.createElement("p");
139
+ p.className = "cx-error";
140
+ p.textContent = `This page could not start: ${err && err.message ? err.message : err}`;
141
+ document.body.appendChild(p);
142
+ });
@@ -0,0 +1,268 @@
1
+ // The narration around a carve (#712, #715): the header, the Watch-style
2
+ // caption with its next line and progress bar, and the Tips bubbles on the
3
+ // boxes. The static export narrates a recording with it, under a "recorded"
4
+ // badge; the kiosk narrates the live carve with it (web/kiosk-carve.js), under
5
+ // a "live" badge. The dots layer (web/dots.js, in its `auto` mode)
6
+ // replays the recording, directs the camera, and hands this a state twice a
7
+ // second: the beat (web/dots-kiosk.js), the counts, and where each estate's
8
+ // box is on the page. A click on a bubble opens it in Tips' replay modal.
9
+
10
+ import { tipSpot, tipsStyle, TIPS_STYLE_ID } from "./kiosk-event-help-ui.js";
11
+ import { openEventModal } from "./event-help-modal.js";
12
+ import { TIP } from "./dots-kiosk.js";
13
+ import { lagText } from "./tour-player.js";
14
+
15
+ const fmt = (n) => Number(n).toLocaleString("en-US");
16
+
17
+ function el(tag, cls, text) {
18
+ const n = document.createElement(tag);
19
+ if (cls) n.className = cls;
20
+ if (text !== undefined && text !== null) n.textContent = text;
21
+ return n;
22
+ }
23
+
24
+ const STOPS = [
25
+ { id: "start", words: "one estate" },
26
+ { id: "carve", words: "carving" },
27
+ { id: "settled", words: "carved" },
28
+ ];
29
+
30
+ /** The badge: "live" over a carve being written (#715), "recorded" over a replay. */
31
+ export function badgeText(state) {
32
+ return state.recording && state.recording.kind === "live" ? "live" : "recorded";
33
+ }
34
+
35
+ /** The badge's tooltip: what the recording is, or where the live carve is read from. */
36
+ export function recordedWords(state) {
37
+ const r = state.recording || {};
38
+ if (r.kind === "live") {
39
+ const n = r.resources ? `, ${fmt(r.resources)} resources` : "";
40
+ const m = r.migration ? `; migration ${r.migration}` : "";
41
+ return `live carve of ${state.src}${n}, drawn from the estate rosters and the migration's progress as terragucci writes them${r.from ? ` to ${r.from}` : ""}${m}`;
42
+ }
43
+ const what = r.kind === "walkthrough" ? "recorded walkthrough" : "recorded carve";
44
+ const n = r.resources ? `, ${fmt(r.resources)} resources` : "";
45
+ const when = r.recordedAt ? `, recorded ${new Date(r.recordedAt).toISOString().slice(0, 10)}` : "";
46
+ return `${what} of ${state.src}${n}${when}, replayed`;
47
+ }
48
+
49
+ /** First landings that queue up together become one bubble, on the newest box. */
50
+ export function mergeLandings(tips, names = {}) {
51
+ if (tips.length < 2) return tips[0] || null;
52
+ const list = tips.map((x) => names[x.estate] || x.estate);
53
+ const last = tips[tips.length - 1];
54
+ return { ...last, text: `${list.slice(0, -1).join(", ")} and ${list[list.length - 1]}: their first resources land. live-mv rewrote the ownership tags; nothing was recreated.` };
55
+ }
56
+
57
+ /**
58
+ * bar, caption: elements to draw into; tipsHost, modalHost: where bubbles and
59
+ * modals go; origin(): the page offset of the layer the state's box rects are in.
60
+ */
61
+ export function createNarration({ bar, caption, tipsHost, modalHost, origin }) {
62
+ if (!document.getElementById(TIPS_STYLE_ID)) {
63
+ const st = el("style");
64
+ st.id = TIPS_STYLE_ID;
65
+ st.textContent = tipsStyle();
66
+ document.head.appendChild(st);
67
+ }
68
+ const queue = [];
69
+ const shown = new Set();
70
+ let tip = null;
71
+ let lastTipAt = 0;
72
+ let last = null;
73
+
74
+ const anchorOf = (t, state) => {
75
+ const o = origin();
76
+ const r = t.estate && state.rects[t.estate];
77
+ if (r) return { left: o.left + r.left, top: o.top + r.top, width: r.width, height: r.height };
78
+ return { left: o.left + o.width / 2 - 60, top: o.top + o.height * 0.35, width: 120, height: 10 };
79
+ };
80
+ const placeTip = (state) => {
81
+ if (!tip) return;
82
+ const size = { w: tip.node.offsetWidth, h: tip.node.offsetHeight };
83
+ const win = { w: window.innerWidth, h: window.innerHeight };
84
+ let p;
85
+ // The other boxes are what the bubble keeps off: it points at one estate, never sits on another's box or the source's.
86
+ const o = origin();
87
+ const others = Object.entries(state.rects || {})
88
+ .filter(([e]) => e !== tip.t.estate)
89
+ .map(([, r]) => ({ x: o.left + r.left, y: o.top + r.top, w: r.width, h: r.height }));
90
+ try {
91
+ p = tipSpot(anchorOf(tip.t, state), size, win, others);
92
+ } catch {
93
+ // A box off the page has no spot beside it: the bubble goes over the middle.
94
+ p = tipSpot({ left: o.left + o.width / 2 - 60, top: o.top + o.height / 2, width: 120, height: 10 }, size, win);
95
+ }
96
+ tip.node.style.setProperty("--eh-at", `translate(${p.x}px, ${p.y}px)`);
97
+ tip.node.style.transform = `translate(${p.x}px, ${p.y}px)`;
98
+ tip.node.style.setProperty("--eh-arrow", `${p.arrow}px`);
99
+ tip.node.classList.toggle("eh-below", p.below);
100
+ };
101
+ const tickTips = (state) => {
102
+ const now = Date.now();
103
+ if (tip && now - tip.at > TIP.showMs) {
104
+ const n = tip.node;
105
+ n.classList.add("eh-out");
106
+ setTimeout(() => n.remove(), 700);
107
+ tip = null;
108
+ lastTipAt = now;
109
+ }
110
+ // A bubble about something long past, or not yet reached after a seek back, is dropped.
111
+ while (queue.length && (queue[0].at > state.t || state.t - queue[0].at > TIP.staleMs)) queue.shift();
112
+ if (!tip && queue.length && now - lastTipAt > TIP.gapMs && tipsHost) {
113
+ let t = queue.shift();
114
+ if (t.key.startsWith("land:")) {
115
+ const group = [t];
116
+ while (queue.length && queue[0].key.startsWith("land:")) group.push(queue.shift());
117
+ t = mergeLandings(group, state.names);
118
+ }
119
+ const node = el("div", "eh-tip eh-tip-go", t.text);
120
+ node.dataset.ehTone = t.tone;
121
+ node.setAttribute("role", "status");
122
+ node.title = "Open it";
123
+ node.addEventListener("click", () => {
124
+ if (!modalHost) return;
125
+ openEventModal(modalHost, {
126
+ mode: "replay",
127
+ kind: t.tone === "bad" ? "failed" : "applied",
128
+ data: { title: t.title || "The carve", lines: [{ text: t.text, lit: true }, { text: recordedWords(last || state) }], ...(t.recordedAt ? { replayAt: t.recordedAt } : {}) },
129
+ });
130
+ });
131
+ tipsHost.appendChild(node);
132
+ tip = { t, node, at: now };
133
+ }
134
+ placeTip(state);
135
+ };
136
+
137
+ let lastChapter = null;
138
+ const draw = (state) => {
139
+ if (caption && state.tour) return drawTour(state);
140
+ if (caption) caption.classList.remove("cx-tour");
141
+ const b = state.beat;
142
+ if (bar) {
143
+ bar.replaceChildren();
144
+ const place = el("div", "cx-place");
145
+ const rec = el("span", `cx-rec cx-badge-${badgeText(state)}`, badgeText(state));
146
+ rec.title = recordedWords(state);
147
+ place.append(rec, el("span", "cx-src", state.src));
148
+ bar.appendChild(place);
149
+ const strip = el("ol", "cx-strip");
150
+ const at = STOPS.findIndex((s) => s.id === b.phase);
151
+ STOPS.forEach((s, i) => strip.appendChild(el("li", `cx-stop cx-${i < at ? "done" : i === at ? "current" : "ahead"}`, s.words)));
152
+ bar.appendChild(strip);
153
+ }
154
+ if (caption) {
155
+ caption.replaceChildren();
156
+ const top = el("div", "cx-top");
157
+ const h = el("h1", "cx-title");
158
+ const rec = el("span", `cx-rec cx-badge-${badgeText(state)}`, badgeText(state));
159
+ rec.title = recordedWords(state);
160
+ h.append(rec);
161
+ const lag = badgeText(state) === "live" ? lagText(state.lastWriteAt, Date.now(), state.running) : null;
162
+ if (lag) h.append(el("span", `cx-lag${lag === "waiting for the job" ? " cx-lag-wait" : ""}`, lag));
163
+ h.append(el("span", null, b.title));
164
+ top.appendChild(h);
165
+ const hold = state.holdLeft !== null && state.holdLeft !== undefined;
166
+ const nx = el("p", "cx-next");
167
+ if (!b.next) b.next = { text: "", fraction: 0 };
168
+ nx.append(el("span", null, hold ? `starting again in ${state.holdLeft} s` : b.next.text));
169
+ const nbar = el("span", `cx-nbar cx-tone-${hold ? "idle" : b.phase === "settled" ? "ok" : "busy"}`);
170
+ const fill = el("span", "cx-nbar-in");
171
+ fill.style.width = `${Math.round((hold ? 1 - state.holdLeft / 10 : b.next.fraction) * 1000) / 10}%`;
172
+ nbar.appendChild(fill);
173
+ nx.appendChild(nbar);
174
+ top.appendChild(nx);
175
+ caption.appendChild(top);
176
+ const line = el("p", `cx-row cx-tone-${b.line.tone}`);
177
+ line.append(el("span", "cx-label", b.line.label), el("span", "cx-text cx-lead", b.line.text));
178
+ caption.appendChild(line);
179
+ const tot = state.totals;
180
+ const tally = el("p", "cx-row cx-tone-idle");
181
+ const estatesN = Object.values(state.counts).filter((n) => n > 0).length;
182
+ const estatesW = `${estatesN} estate${estatesN === 1 ? "" : "s"}`;
183
+ const tallyText =
184
+ state.recording && state.recording.kind === "live" && tot.moved !== undefined
185
+ ? `${fmt(tot.moved)} moved · ${fmt(tot.stamped)} stamped · ${tot.refused} refused${tot.skipped ? ` · ${tot.skipped} skipped` : ""} · ${estatesW}`
186
+ : `${fmt(tot.done)} of ${fmt(tot.moves)} flown · ${tot.refused} refused · ${estatesW}`;
187
+ tally.append(el("span", "cx-label", "moves"), el("span", "cx-text", tallyText));
188
+ caption.appendChild(tally);
189
+ }
190
+ };
191
+
192
+ /** The tour's caption: the live badge and its lag, the chapter rail, the chapter's card, what each visual stands on, the links. */
193
+ const drawTour = (state) => {
194
+ const tr = state.tour;
195
+ caption.replaceChildren();
196
+ caption.classList.add("cx-tour");
197
+ const top = el("div", "cx-top cx-tour-top");
198
+ const rec = el("span", "cx-rec cx-badge-live", "live");
199
+ rec.title = recordedWords(state);
200
+ top.appendChild(rec);
201
+ const lag = lagText(state.lastWriteAt, Date.now(), state.running);
202
+ if (lag) top.appendChild(el("span", `cx-lag${lag === "waiting for the job" ? " cx-lag-wait" : ""}`, lag));
203
+ const rail = el("ol", "cx-rail");
204
+ rail.setAttribute("aria-label", `${tr.title || "The tour"}: chapter ${tr.n} of ${tr.of}`);
205
+ for (const c of tr.rail) {
206
+ const li = el("li", `cx-ch cx-ch-${c.state}`);
207
+ li.title = `${c.n}. ${c.title}`;
208
+ li.appendChild(el("span", "cx-ch-n", String(c.n)));
209
+ if (c.state === "current") li.appendChild(el("span", "cx-ch-name", c.title));
210
+ const bar = el("i", "cx-ch-bar");
211
+ bar.style.setProperty("--p", String(c.progress));
212
+ li.appendChild(bar);
213
+ if (c.state === "current") li.setAttribute("aria-current", "step");
214
+ rail.appendChild(li);
215
+ }
216
+ top.appendChild(rail);
217
+ const links = el("p", "cx-follow");
218
+ const l = tr.links || {};
219
+ if (l.pull || l.job) {
220
+ links.appendChild(el("span", "cx-follow-label", "follow along"));
221
+ if (l.pull) links.appendChild(Object.assign(el("a", null, `pull request #${l.pull.n}`), { href: l.pull.url, target: "_blank", rel: "noopener" }));
222
+ if (l.job) links.appendChild(Object.assign(el("a", null, `job #${l.job.n}`), { href: l.job.url, target: "_blank", rel: "noopener" }));
223
+ top.appendChild(links);
224
+ }
225
+ caption.appendChild(top);
226
+ // The chapter's card, docked in the caption: it slides in when the chapter changes.
227
+ const card = el("div", `cx-card${lastChapter !== tr.id ? " cx-enter" : ""}`);
228
+ lastChapter = tr.id;
229
+ const h = el("h1", "cx-title cx-card-title");
230
+ h.append(el("span", "cx-ch-kicker", `${tr.n} of ${tr.of}`), el("span", null, tr.heading));
231
+ card.appendChild(h);
232
+ for (const line of tr.lines) card.appendChild(el("p", "cx-card-line", line));
233
+ caption.appendChild(card);
234
+ if (tr.card && tr.card.length) {
235
+ const grid = el("dl", "cx-numbers");
236
+ for (const r of tr.card) {
237
+ const d = el("div", "cx-num");
238
+ d.append(el("dt", null, r.label), el("dd", null, r.text));
239
+ grid.appendChild(d);
240
+ }
241
+ caption.appendChild(grid);
242
+ }
243
+ if (tr.notes.length) {
244
+ const notes = el("p", "cx-notes");
245
+ notes.textContent = tr.notes.join(" · ");
246
+ caption.appendChild(notes);
247
+ }
248
+ };
249
+
250
+ return {
251
+ update(state) {
252
+ if (state.type !== "behold:dots-state") {
253
+ if (state.type === "behold:dots-ready") shown.clear();
254
+ return;
255
+ }
256
+ // A new loop shows its Tips again.
257
+ if (last && state.t < last.t) shown.clear();
258
+ for (const t of state.tips || []) {
259
+ if (shown.has(t.key)) continue;
260
+ shown.add(t.key);
261
+ queue.push(t);
262
+ }
263
+ last = state;
264
+ draw(state);
265
+ tickTips(state);
266
+ },
267
+ };
268
+ }
@@ -0,0 +1,18 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { recordedWords, mergeLandings } from "./carve-narration.js";
3
+
4
+ describe("the carve export's narration (#712)", () => {
5
+ it("says what the recording is", () => {
6
+ expect(recordedWords({ src: "behold-terralith-14", recording: { kind: "carve", resources: 1041, recordedAt: Date.parse("2026-09-22T16:37:26Z") } })).toBe(
7
+ "recorded carve of behold-terralith-14, 1,041 resources, recorded 2026-09-22, replayed",
8
+ );
9
+ expect(recordedWords({ src: "terralith", recording: { kind: "walkthrough" } })).toBe("recorded walkthrough of terralith, replayed");
10
+ });
11
+ it("puts first landings that queue together in one bubble, on the newest box", () => {
12
+ const t = (e, at) => ({ key: `land:${e}`, estate: e, at, text: e });
13
+ expect(mergeLandings([t("a", 1)])).toEqual(t("a", 1));
14
+ const m = mergeLandings([t("x-a", 1), t("x-b", 2), t("x-c", 3)], { "x-a": "a", "x-b": "b", "x-c": "c" });
15
+ expect(m.estate).toBe("x-c");
16
+ expect(m.text).toMatch(/^a, b and c: their first resources land/);
17
+ });
18
+ });
@@ -0,0 +1,147 @@
1
+ // #681: a waiting gate's change set, drawn on the graph as a preview. Pure
2
+ // words and colours from /api/workspace/change-set; app.js draws them.
3
+ //
4
+ // The colours are the graph's own (the drift legend's tokens): a card the
5
+ // change set creates is outlined in the managed green, one it updates or
6
+ // replaces in the foreign yellow, one it deletes or forgets in the degraded
7
+ // red. A card with entries of several kinds takes the one that destroys most.
8
+ // The outline and a tag above the card are the marks; the fill stays the
9
+ // live-status channel, so a preview never reads as what is live.
10
+
11
+ /** The legend's buckets, in order, with the token each is drawn in. */
12
+ export const BUCKETS = [
13
+ { bucket: "create", color: "var(--managed)", label: "create", title: "The change set creates these." },
14
+ { bucket: "change", color: "var(--foreign)", label: "update or replace", title: "The change set updates these in place, or replaces them (a new object for the old one)." },
15
+ { bucket: "delete", color: "var(--degraded)", label: "delete or forget", title: "The change set deletes these, or forgets them (chant stops managing the object and leaves it standing)." },
16
+ ];
17
+ const COLOR = Object.fromEntries(BUCKETS.map((b) => [b.bucket, b.color]));
18
+
19
+ /** The colour a bucket is drawn in. */
20
+ export const bucketColor = (bucket) => COLOR[bucket] || "var(--muted)";
21
+
22
+ const short = (s) => (s ? String(s).replace(/^(jcs1-)?sha256:/, "").slice(0, 12) : "");
23
+ const sha7 = (s) => (s ? String(s).slice(0, 7) : "");
24
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
25
+
26
+ /** The note under the overlay's legend: it is a preview. */
27
+ export const PREVIEW_NOTE = "A preview of what approving this gate lets chant apply. Nothing on the graph has changed yet.";
28
+
29
+ /** The overlay's first lines: the change set, the gate and commit it belongs to, or why it wasn't read. */
30
+ export function overlayHeader(a) {
31
+ if (!a || a.error) return { lines: [`change set not read${a && a.error ? `: ${a.error}` : ""}`], tone: "refusal", title: "" };
32
+ if (a.refusal) return { lines: [`change set not read: ${a.refusal.error}`], tone: "refusal", title: a.refusal.remedy || "" };
33
+ const g = a.gate;
34
+ const lines = [`change set ${short(a.digest)} · gate ${g.key}${g.env ? ` in ${g.env}` : ""}`];
35
+ const facts = [];
36
+ const commit = g.gitSha || (a.graph && a.graph.at);
37
+ facts.push(commit ? `commit ${sha7(commit)}` : "commit unknown");
38
+ if (g.runId) facts.push(`run ${g.runId}`);
39
+ if (a.planned) facts.push(`release ${short(a.planned.releaseDigest)} planned for ${a.planned.environment}`);
40
+ lines.push(facts.join(" · "));
41
+ const title = [
42
+ `change set ${a.digest}`,
43
+ commit ? `commit ${commit}${g.gitSha ? "" : " (the commit chant read the graph at)"}` : "",
44
+ a.planned ? `release ${a.planned.releaseDigest}` : "",
45
+ a.graph ? `nodes from the graph of ${a.graph.member || "the project"}${a.graph.at ? ` at ${sha7(a.graph.at)}` : ""}` : "chant read no graph, so no entry has a node",
46
+ g.approve,
47
+ ]
48
+ .filter(Boolean)
49
+ .join("\n");
50
+ return { lines, tone: "quiet", title };
51
+ }
52
+
53
+ /** The legend: one row per bucket with its colour and how many entries it holds, and the entries that change nothing. */
54
+ export function overlayLegend(a) {
55
+ if (!a || a.error || a.refusal) return [];
56
+ const rows = BUCKETS.map((b) => ({ bucket: b.bucket, color: b.color, label: b.label, count: (a.counts && a.counts[b.bucket]) || 0, title: b.title }));
57
+ if (a.unchanged) rows.push({ bucket: "unchanged", color: "var(--muted)", label: "no change (not drawn)", count: a.unchanged, title: "Entries the plan reads or leaves as they are." });
58
+ return rows;
59
+ }
60
+
61
+ /** The tag above a card: its actions in words, "update", "2 create, delete". */
62
+ export function actionWords(actions) {
63
+ const order = ["create", "update", "replace", "delete", "forget"];
64
+ return order.filter((k) => actions && actions[k]).map((k) => (actions[k] === 1 ? k : `${actions[k]} ${k}`)).join(", ");
65
+ }
66
+
67
+ /** The marks to draw: per node id, its colour, its tag and its tooltip. */
68
+ export function nodeMarks(a) {
69
+ const out = {};
70
+ if (!a || a.error || a.refusal || !a.nodes) return out;
71
+ for (const [id, n] of Object.entries(a.nodes)) {
72
+ const entries = a.entries.filter((e) => e.node === id);
73
+ out[id] = {
74
+ bucket: n.bucket,
75
+ color: bucketColor(n.bucket),
76
+ tag: actionWords(n.actions),
77
+ title: [`change set ${short(a.digest)} (preview, not applied):`, ...entries.map((e) => `${e.action} ${e.address}`)].join("\n"),
78
+ };
79
+ }
80
+ return out;
81
+ }
82
+
83
+ const MAX_VALUE = 80;
84
+ /** One value as JSON, cut to a line. */
85
+ export function valueWords(v) {
86
+ let s;
87
+ try {
88
+ s = JSON.stringify(v);
89
+ } catch {
90
+ s = String(v);
91
+ }
92
+ if (s === undefined) s = String(v);
93
+ return s.length > MAX_VALUE ? `${s.slice(0, MAX_VALUE - 3)}...` : s;
94
+ }
95
+
96
+ /** One attribute in words: "Versioning: before {...}, after {...}". */
97
+ export function attributeWords(t) {
98
+ let what;
99
+ if (t.sensitive) what = "sensitive, not shown";
100
+ else {
101
+ const parts = [];
102
+ if ("before" in t) parts.push(`before ${valueWords(t.before)}`);
103
+ if (t.unknown) parts.push("after: known after apply");
104
+ else if ("after" in t) parts.push(`after ${valueWords(t.after)}`);
105
+ what = parts.join(", ") || "changes";
106
+ }
107
+ return `${t.path}: ${what}${t.forcesReplacement ? " (forces replacement)" : ""}`;
108
+ }
109
+
110
+ /** One entry as lines: its action and address, then its type, disruption and fields where present. */
111
+ export function entryLines(e) {
112
+ const facts = [e.type, e.disruption ? `disruption ${e.disruption}` : "", e.deposed ? `deposed ${e.deposed}` : ""].filter(Boolean).join(" · ");
113
+ return { head: `${e.action} ${e.address}`, bucket: e.bucket, color: bucketColor(e.bucket), facts, fields: (e.attributes || []).map(attributeWords) };
114
+ }
115
+
116
+ /** The entries on one card, for the inspect pane. */
117
+ export function entriesFor(a, id) {
118
+ if (!a || a.error || a.refusal || !a.entries) return [];
119
+ return a.entries.filter((e) => e.node === id).map(entryLines);
120
+ }
121
+
122
+ /**
123
+ * The entries a reader would not see on the graph: those chant mapped to no
124
+ * node, and those whose node this view does not draw (another lens, or a
125
+ * member not on screen). `drawn` is the set of node ids on the canvas.
126
+ */
127
+ export function offGraph(a, drawn) {
128
+ if (!a || a.error || a.refusal || !a.entries) return { noNode: [], notDrawn: [] };
129
+ return {
130
+ noNode: a.entries.filter((e) => !e.node).map(entryLines),
131
+ notDrawn: a.entries.filter((e) => e.node && drawn && !drawn.has(e.node)).map((e) => ({ ...entryLines(e), node: e.node })),
132
+ };
133
+ }
134
+
135
+ /** What the change set leaves out: members that failed to plan, and holes. */
136
+ export function gapLines(a) {
137
+ if (!a || a.error || a.refusal || !a.gaps) return [];
138
+ return a.gaps.map((m) => {
139
+ if (m.status !== "planned") return { text: `${m.member} did not plan${m.error ? `: ${m.error}` : ""}, so its changes are not drawn`, title: "" };
140
+ return { text: `${m.member}: ${plural(m.holes.length, "address", "addresses")} the plan could not read`, title: m.holes.map((h) => `${h.address}: ${h.reason}`).join("\n") };
141
+ });
142
+ }
143
+
144
+ /** The heading over a card's entries in the inspect pane. */
145
+ export function inspectHeading(a) {
146
+ return `change set ${short(a.digest)} (preview, not applied)`;
147
+ }
@@ -0,0 +1,83 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { describe, expect, it } from "vitest";
4
+ import { overlayFrom } from "../src/change-set-overlay.ts";
5
+ import { gatesFromStatus } from "../src/workspace-gates.ts";
6
+ import { actionWords, attributeWords, BUCKETS, entriesFor, gapLines, nodeMarks, offGraph, overlayHeader, overlayLegend, valueWords } from "./change-set-overlay.js";
7
+
8
+ // #681: the overlay drawn from the stored change set chant printed for the
9
+ // fixture workspace (src/__fixtures__/change-set-overlay), as the route
10
+ // answers it: the release gate waiting in prod and its change set.
11
+ const FIX = join(import.meta.dirname, "..", "src", "__fixtures__", "change-set-overlay");
12
+ const fixture = (name) => JSON.parse(readFileSync(join(FIX, name), "utf8"));
13
+ const gates = gatesFromStatus(fixture("status-prod.json"), "/ws");
14
+ const { dir: _dir, ...gate } = gates.gates[0];
15
+ const answer = { workspace: true, chant: "0.124.28", ...overlayFrom(gate, fixture("change-set-show.json"), new Date("2026-10-16T00:00:00Z")) };
16
+
17
+ describe("the overlay's colours (#681)", () => {
18
+ it("draws create, change and delete in the drift legend's tokens", () => {
19
+ expect(BUCKETS.map((b) => [b.bucket, b.color])).toEqual([
20
+ ["create", "var(--managed)"],
21
+ ["change", "var(--foreign)"],
22
+ ["delete", "var(--degraded)"],
23
+ ]);
24
+ });
25
+ it("gives a legend row per bucket with its count, and counts what changes nothing", () => {
26
+ expect(overlayLegend(answer).map((r) => [r.label, r.count])).toEqual([
27
+ ["create", 1],
28
+ ["update or replace", 2],
29
+ ["delete or forget", 1],
30
+ ["no change (not drawn)", 1],
31
+ ]);
32
+ });
33
+ });
34
+
35
+ describe("the overlay on the graph (#681)", () => {
36
+ it("marks each node the change set touches, with its colour and its actions", () => {
37
+ const marks = nodeMarks(answer);
38
+ expect(Object.keys(marks).sort()).toEqual(["web/AppBucket", "web/AppFunction", "web/AppQueue"]);
39
+ expect(marks["web/AppQueue"]).toMatchObject({ bucket: "create", color: "var(--managed)", tag: "create" });
40
+ expect(marks["web/AppFunction"]).toMatchObject({ bucket: "change", color: "var(--foreign)", tag: "replace" });
41
+ expect(marks["web/AppBucket"].title).toBe("change set 9cf74a6fee02 (preview, not applied):\nupdate AppBucket");
42
+ });
43
+ it("names the commit, gate and release it belongs to", () => {
44
+ expect(overlayHeader(answer)).toMatchObject({
45
+ lines: ["change set 9cf74a6fee02 · gate web/release/promote in prod", "commit a14610e · run run-9 · release 1a23268fa8b1 planned for prod"],
46
+ tone: "quiet",
47
+ });
48
+ expect(overlayHeader(answer).title).toContain("chant approve release promote --env prod");
49
+ });
50
+ it("says why when the change set wasn't read", () => {
51
+ const refusal = { error: "Change set needs chant 0.124.28 or newer. This project has chant 0.124.24.", code: "chant-too-old", remedy: "Upgrade" };
52
+ expect(overlayHeader({ workspace: true, refusal })).toEqual({ lines: [`change set not read: ${refusal.error}`], tone: "refusal", title: "Upgrade" });
53
+ expect(nodeMarks({ refusal })).toEqual({});
54
+ });
55
+ });
56
+
57
+ describe("a node's entries (#681)", () => {
58
+ it("lists address, action and fields when a node is clicked", () => {
59
+ expect(entriesFor(answer, "web/AppFunction")).toEqual([
60
+ {
61
+ head: "replace AppFunction",
62
+ bucket: "change",
63
+ color: "var(--foreign)",
64
+ facts: "AWS::Lambda::Function · disruption replace",
65
+ fields: ['FunctionName: before "cart-v1", after "cart-v2" (forces replacement)', "Environment: sensitive, not shown"],
66
+ },
67
+ ]);
68
+ expect(entriesFor(answer, "web/AppBucket")[0].fields).toEqual(['VersioningConfiguration: before {"Status":"Suspended"}, after {"Status":"Enabled"}', 'Tags: before [{"Key":"team","Value":"cart"}], after: known after apply']);
69
+ expect(entriesFor(answer, "web/AppRole")).toEqual([]);
70
+ });
71
+ it("keeps the entries with no node in the side list, and those this view does not draw", () => {
72
+ const off = offGraph(answer, new Set(["web/AppQueue", "web/AppBucket"]));
73
+ expect(off.noNode.map((e) => e.head)).toEqual(["delete LegacyTopic"]);
74
+ expect(off.noNode[0].color).toBe("var(--degraded)");
75
+ expect(off.notDrawn.map((e) => [e.head, e.node])).toEqual([["replace AppFunction", "web/AppFunction"]]);
76
+ });
77
+ it("words the small things plainly", () => {
78
+ expect(actionWords({ create: 2, delete: 1 })).toBe("2 create, delete");
79
+ expect(attributeWords({ path: "a", after: 1 })).toBe("a: after 1");
80
+ expect(valueWords("x".repeat(200))).toHaveLength(80);
81
+ expect(gapLines({ ...answer, gaps: [{ member: "api", status: "failed", error: "no credentials", holes: [] }] })).toEqual([{ text: "api did not plan: no credentials, so its changes are not drawn", title: "" }]);
82
+ });
83
+ });