@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
@@ -13,7 +13,11 @@
13
13
  * - the pending gate as a first-class card (#234): who is waiting, since when,
14
14
  * what it holds back, and an Approve button that POSTs the EXISTING
15
15
  * op-signal route. behold never signals on its own initiative.
16
- * - the settled steps, in the order they settled.
16
+ * - the run's steps as chant's run events report them (#679): running,
17
+ * then how each settled (ok, failed, skipped with chant's reason, cached,
18
+ * gated, waiting), in the order they started.
19
+ * - where the steps came from, so a degraded run (a chant older than the
20
+ * run-events floor) says so.
17
21
  */
18
22
 
19
23
  /** Settled-step tones, in the same token vocabulary the apply progress panel
@@ -22,8 +26,12 @@
22
26
  import { barVarFor } from "./theme.js";
23
27
 
24
28
  export const RUN_STEP_COLOR = {
29
+ running: "var(--pending)",
25
30
  ok: "var(--managed)",
26
- fail: "var(--degraded)",
31
+ cached: "var(--managed)",
32
+ failed: "var(--degraded)",
33
+ gated: "var(--pending)",
34
+ waiting: "var(--pending)",
27
35
  skipped: "var(--muted)",
28
36
  };
29
37
 
@@ -35,10 +43,12 @@ export const RUN_STATUS_COLOR = {
35
43
  running: "var(--pending)",
36
44
  ok: "var(--managed)",
37
45
  failed: "var(--degraded)",
46
+ gated: "var(--pending)",
47
+ waiting: "var(--pending)",
38
48
  lost: "var(--foreign)",
39
49
  };
40
50
 
41
- /** `1062` → `1.1s`. */
51
+ /** `1062` is `1.1s`. */
42
52
  export function took(ms) {
43
53
  return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`;
44
54
  }
@@ -67,33 +77,95 @@ export function waitingFor(since, now = Date.now()) {
67
77
  */
68
78
  export function runVerdict(run) {
69
79
  if (!run || !run.op) return null;
70
- const n = (run.records || []).length;
80
+ const n = (run.steps || []).filter((s) => s.state !== "running").length;
71
81
  const settled = `${n} step${n === 1 ? "" : "s"} settled`;
72
82
  if (run.status === "idle") {
73
- return { text: `${run.op}: no per-step records — this session didn't start the run`, tone: "idle" };
83
+ return { text: `${run.op}: no per-step events; this session didn't start the run`, tone: "idle" };
74
84
  }
75
85
  if (run.status === "running") {
76
86
  return {
77
- text: `${run.op}: running — ${settled}`,
87
+ text: `${run.op}: ${run.following ? "running (followed)" : "running"}, ${settled}`,
78
88
  tone: "running",
79
89
  };
80
90
  }
81
- if (run.status === "ok") return { text: `${run.op}: exited cleanly — ${settled}`, tone: "ok" };
82
- if (run.status === "failed") return { text: `${run.op}: a step failed — ${settled}`, tone: "failed" };
83
- if (run.status === "gated") return { text: `${run.op}: stopped at a gate — ${settled}; approve it, then run the Op again`, tone: "running" };
84
- return { text: `${run.op}: stream lost — frozen at ${settled}`, tone: "lost" };
91
+ if (run.status === "ok") return { text: `${run.op}: settled ok, ${settled}`, tone: "ok" };
92
+ if (run.status === "failed") return { text: `${run.op}: a step failed, ${settled}`, tone: "failed" };
93
+ if (run.status === "gated") return { text: `${run.op}: stopped at a gate, ${settled}; approve it, then run the Op again`, tone: "gated" };
94
+ if (run.status === "waiting") return { text: `${run.op}: waiting on a decision point, ${settled}; answer it, then run the Op again`, tone: "waiting" };
95
+ return { text: `${run.op}: stream lost, frozen at ${settled}`, tone: "lost" };
85
96
  }
86
97
 
87
- /** The settled steps, in arrival order, as rows. */
98
+ /**
99
+ * How one step reads in its row: `running`, a duration, `skipped (receipt)`,
100
+ * `cached`, `gated`, `waiting`. chant's skip reasons are said in words a
101
+ * person reads, with chant's own term kept in brackets.
102
+ */
103
+ export const SKIP_WORDS = {
104
+ receipt: "already applied (receipt)",
105
+ resumed: "carried from an earlier run (resumed)",
106
+ refused: "refused (refused)",
107
+ "not-run": "not run: an earlier step stopped the run (not-run)",
108
+ };
109
+ export function stepTook(s) {
110
+ if (s.state === "running") return "running";
111
+ if (s.state === "skipped") return s.skip ? `skipped: ${SKIP_WORDS[s.skip] || s.skip}` : "skipped";
112
+ if (s.state === "cached" || s.state === "gated" || s.state === "waiting") return s.state;
113
+ return typeof s.durationMs === "number" ? took(s.durationMs) : s.state;
114
+ }
115
+
116
+ /** The run's steps, in the order they started (or settled), as rows. */
88
117
  export function stepRows(run) {
89
- return (run?.records || []).map((r) => ({
90
- label: `${r.phase} · ${r.fn}`,
91
- status: r.status,
92
- took: r.status === "skipped" ? "skipped" : took(r.durationMs),
93
- error: r.error || null,
118
+ return (run?.steps || []).map((s) => ({
119
+ label: `${s.component ? `${s.component} · ` : ""}${s.phase} · ${s.step}`,
120
+ status: s.state,
121
+ took: stepTook(s),
122
+ error: s.error || s.message || null,
123
+ approvedBy: s.approvedBy || null,
94
124
  }));
95
125
  }
96
126
 
127
+ /**
128
+ * Where a run's progress came from, as one line beside it (#679), or null
129
+ * when there is nothing to qualify. `source` is the server's: `events`
130
+ * (chant's run events), `progress` (an older chant, degraded), `classifier`
131
+ * (a pipeline chant did not run, read from its log), `forge` (a forge's own
132
+ * job states). `note` is the server's own reason when it gave one.
133
+ */
134
+ export function sourceLabel(source, note) {
135
+ if (source === "events") return { text: "from chant's run events", tone: "ok" };
136
+ if (source === "progress") return { text: note || "degraded: an older chant's progress stream, with no step starts, skip reasons, cache hits or gate events", tone: "lost" };
137
+ if (source === "classifier") {
138
+ return { text: "best-effort: chant did not run this pipeline, so its steps are read from the runner's log; only the exit code is certain", tone: "lost" };
139
+ }
140
+ if (source === "forge") return { text: "job states from the forge, not chant's run events", tone: "idle" };
141
+ return note ? { text: note, tone: "idle" } : null;
142
+ }
143
+
144
+ /**
145
+ * One component's chip on the dial (#679): its name, the step it is on and
146
+ * how that step stands, then the component's own state. `c` is the server's
147
+ * ApplyComponentState (src/apply.ts).
148
+ */
149
+ export function applyChipText(name, c) {
150
+ const where = [c.phase, c.step].filter(Boolean).join(" · ");
151
+ const how = c.stepState ? stepTook({ state: c.stepState, skip: c.skip, durationMs: null }) : null;
152
+ const detail = where ? ` · ${where}${how && how !== c.status ? ` ${how}` : ""}` : "";
153
+ return `${name}${detail} (${c.status})`;
154
+ }
155
+
156
+ /** What a component run waits on, from chant's `gate-waiting`, or null. */
157
+ export function waitingLine(w) {
158
+ if (!w) return null;
159
+ const on = w.gate ? `gate ${w.gate}` : `decision point ${w.point}`;
160
+ return `waiting on ${on}${w.component ? ` (${w.component})` : ""} since ${w.since}${w.message ? `: ${w.message}` : ""}`;
161
+ }
162
+
163
+ /** The decision point a run waits on, as a line, or null. */
164
+ export function pointLine(run) {
165
+ if (!run || !run.point) return null;
166
+ return `waiting on decision point ${run.point.id} since ${run.point.since}${run.point.message ? `: ${run.point.message}` : ""}; answer it with chant workspace points answer ${run.point.id}`;
167
+ }
168
+
97
169
  /**
98
170
  * The pending gate card (#234), from the run state alone.
99
171
  *
@@ -119,7 +191,7 @@ export function gateCardFrom(run) {
119
191
 
120
192
  /** Does the panel have anything to show at all? */
121
193
  export function hasPlayhead(run) {
122
- return Boolean(run && (run.op || (run.records && run.records.length)));
194
+ return Boolean(run && (run.op || (run.steps && run.steps.length)));
123
195
  }
124
196
 
125
197
  // ── the DOM half ─────────────────────────────────────────────────────────────
@@ -147,8 +219,19 @@ export function renderPlayhead(host, run, card, actions = {}) {
147
219
  line.style.color = RUN_STATUS_COLOR[verdict.tone] || "var(--muted)";
148
220
  host.appendChild(line);
149
221
 
222
+ // #679: where the steps came from; a degraded run's reason is its label,
223
+ // and any other reason (a steward run, a run with no kept events) follows it.
224
+ const from = sourceLabel(run.source, run.source === "progress" ? run.sourceNote : null);
225
+ if (from) {
226
+ const src = el("div", "run-source", from.text);
227
+ src.style.color = RUN_STATUS_COLOR[from.tone] || "var(--muted)";
228
+ host.appendChild(src);
229
+ }
230
+ if (run.sourceNote && run.source !== "progress") host.appendChild(el("div", "run-source", run.sourceNote));
150
231
  if (run.lost) host.appendChild(el("div", "run-lost", run.lost));
151
- if (run.gateNote) host.appendChild(el("div", "run-lost", `Gate state unavailable — ${run.gateNote}`));
232
+ if (run.gateNote) host.appendChild(el("div", "run-lost", `Gate state unavailable: ${run.gateNote}`));
233
+ const point = pointLine(run);
234
+ if (point) host.appendChild(el("div", "run-gate-meta", point));
152
235
 
153
236
  const gate = card || gateCardFrom(run);
154
237
  if (gate) host.appendChild(renderGateCard(gate, actions));
@@ -165,7 +248,7 @@ export function renderPlayhead(host, run, card, actions = {}) {
165
248
  row.appendChild(dot);
166
249
  row.appendChild(el("span", "grow", r.label));
167
250
  row.appendChild(el("span", "run-took", r.took));
168
- if (r.error) row.title = r.error;
251
+ if (r.error || r.approvedBy) row.title = [r.error, r.approvedBy ? `approved by ${r.approvedBy}` : null].filter(Boolean).join("; ");
169
252
  list.appendChild(row);
170
253
  }
171
254
  host.appendChild(list);
@@ -5,13 +5,13 @@
5
5
  // approve button POSTs) is a function from data to data; the DOM half is
6
6
  // smoke/ui-smoke.mjs's job.
7
7
  import { describe, it, expect } from "vitest";
8
- import { runVerdict, stepRows, gateCardFrom, hasPlayhead, took, waitingFor } from "./run-playhead.js";
8
+ import { runVerdict, stepRows, gateCardFrom, hasPlayhead, took, waitingFor, stepTook, sourceLabel, pointLine, applyChipText, waitingLine } from "./run-playhead.js";
9
9
 
10
10
  const base = {
11
11
  op: "playhead-probe",
12
12
  mode: "temporal",
13
13
  status: "running",
14
- records: [],
14
+ steps: [],
15
15
  gate: null,
16
16
  gateNote: null,
17
17
  startedAt: "2026-08-29T18:00:00.000Z",
@@ -20,7 +20,7 @@ const base = {
20
20
  };
21
21
  const withRecords = (n) => ({
22
22
  ...base,
23
- records: Array.from({ length: n }, (_, i) => ({ phase: "P", fn: `f${i}`, status: "ok", durationMs: 1000 })),
23
+ steps: Array.from({ length: n }, (_, i) => ({ component: null, phase: "P", step: `f${i}`, state: "ok", durationMs: 1000 })),
24
24
  });
25
25
 
26
26
  describe("took", () => {
@@ -48,7 +48,7 @@ describe("waitingFor", () => {
48
48
  describe("runVerdict", () => {
49
49
  it("has nothing to say before anything has run", () => {
50
50
  expect(runVerdict(null)).toBeNull();
51
- expect(runVerdict({ op: null, status: "idle", records: [] })).toBeNull();
51
+ expect(runVerdict({ op: null, status: "idle", steps: [] })).toBeNull();
52
52
  });
53
53
 
54
54
  it("never calls a lost stream finished", () => {
@@ -63,8 +63,16 @@ describe("runVerdict", () => {
63
63
  expect(runVerdict({ ...withRecords(2), status: "failed" }).text).toContain("a step failed");
64
64
  });
65
65
 
66
- it("counts settled steps while a local run streams them (#459: --progress-json)", () => {
67
- expect(runVerdict({ ...withRecords(1), mode: "local" }).text).toContain("running — 1 step settled");
66
+ it("counts settled steps while a local run streams them, not the one running (#679)", () => {
67
+ const run = { ...withRecords(1), steps: [...withRecords(1).steps, { component: null, phase: "P", step: "g", state: "running" }] };
68
+ expect(runVerdict(run).text).toContain("running, 1 step settled");
69
+ expect(runVerdict({ ...run, following: true }).text).toContain("running (followed)");
70
+ });
71
+
72
+ it("says a run waiting on a decision point waits on a person, not that it failed (#679)", () => {
73
+ const v = runVerdict({ ...withRecords(1), status: "waiting" });
74
+ expect(v.text).toContain("waiting on a decision point");
75
+ expect(v.tone).toBe("waiting");
68
76
  });
69
77
 
70
78
  it("says a gated run stopped at its gate and runs again after approval (#459)", () => {
@@ -84,10 +92,10 @@ describe("runVerdict", () => {
84
92
  describe("stepRows", () => {
85
93
  it("keeps arrival order and labels a skip as a skip, not a duration", () => {
86
94
  const rows = stepRows({
87
- records: [
88
- { phase: "Build", fn: "chantBuild", status: "ok", durationMs: 1062 },
89
- { phase: "Verify", fn: "httpCheck", status: "fail", durationMs: 15164, error: "fetch failed" },
90
- { phase: "Never", fn: "httpCheck", status: "skipped", durationMs: 0 },
95
+ steps: [
96
+ { component: null, phase: "Build", step: "chantBuild", state: "ok", durationMs: 1062 },
97
+ { component: null, phase: "Verify", step: "httpCheck", state: "failed", durationMs: 15164, error: "fetch failed" },
98
+ { component: null, phase: "Never", step: "httpCheck", state: "skipped", durationMs: 0 },
91
99
  ],
92
100
  });
93
101
  expect(rows.map((r) => `${r.label} ${r.took}`)).toEqual([
@@ -135,7 +143,69 @@ describe("gateCardFrom", () => {
135
143
  describe("hasPlayhead", () => {
136
144
  it("is false on a fresh session and true once an Op is being watched", () => {
137
145
  expect(hasPlayhead(null)).toBe(false);
138
- expect(hasPlayhead({ op: null, records: [] })).toBe(false);
146
+ expect(hasPlayhead({ op: null, steps: [] })).toBe(false);
139
147
  expect(hasPlayhead(base)).toBe(true);
140
148
  });
141
149
  });
150
+
151
+ // #679: every state chant's run events report, as it happens.
152
+ describe("stepTook", () => {
153
+ it("reads each state chant reports, and says why a step skipped", () => {
154
+ expect(stepTook({ state: "running" })).toBe("running");
155
+ expect(stepTook({ state: "ok", durationMs: 6 })).toBe("6ms");
156
+ expect(stepTook({ state: "skipped", skip: "receipt" })).toBe("skipped: already applied (receipt)");
157
+ expect(stepTook({ state: "skipped", skip: "not-run" })).toBe("skipped: not run: an earlier step stopped the run (not-run)");
158
+ expect(stepTook({ state: "skipped", skip: null })).toBe("skipped");
159
+ expect(stepTook({ state: "cached", durationMs: 3 })).toBe("cached");
160
+ expect(stepTook({ state: "gated", durationMs: 680 })).toBe("gated");
161
+ expect(stepTook({ state: "waiting" })).toBe("waiting");
162
+ // The older stream's component steps carry no timing.
163
+ expect(stepTook({ state: "ok", durationMs: null })).toBe("ok");
164
+ });
165
+
166
+ it("names the component and who approved a gate on a row", () => {
167
+ const [row] = stepRows({ steps: [{ component: "db", phase: "Apply", step: "gate:approve-db", state: "ok", durationMs: 40, approvedBy: "alex" }] });
168
+ expect(row.label).toBe("db · Apply · gate:approve-db");
169
+ expect(row.approvedBy).toBe("alex");
170
+ });
171
+ });
172
+
173
+ describe("sourceLabel", () => {
174
+ it("labels the classifier path best-effort, and a degraded run with the server's reason", () => {
175
+ expect(sourceLabel("classifier").text).toMatch(/^best-effort: chant did not run this pipeline/);
176
+ expect(sourceLabel("classifier").text).toContain("only the exit code is certain");
177
+ expect(sourceLabel("progress", "degraded: this project's chant (0.124.24) is older than 0.124.28").text).toContain("0.124.24");
178
+ expect(sourceLabel("progress").text).toMatch(/^degraded/);
179
+ expect(sourceLabel("events").text).toBe("from chant's run events");
180
+ expect(sourceLabel("forge").text).toContain("forge");
181
+ expect(sourceLabel(undefined)).toBeNull();
182
+ expect(sourceLabel(null, "a steward run keeps no events on this host").text).toContain("steward");
183
+ });
184
+ });
185
+
186
+ describe("pointLine", () => {
187
+ it("names a decision point and the command that answers it", () => {
188
+ expect(pointLine({ point: { id: "pt-1", since: "2026-10-17T04:24:48.329Z" } })).toBe(
189
+ "waiting on decision point pt-1 since 2026-10-17T04:24:48.329Z; answer it with chant workspace points answer pt-1",
190
+ );
191
+ expect(pointLine({ point: null })).toBeNull();
192
+ });
193
+ });
194
+
195
+ describe("applyChipText", () => {
196
+ it("shows the step a component is on and how it stands, as it happens", () => {
197
+ expect(applyChipText("loom-db", { status: "running", phase: "Apply", step: "cfn-deploy", stepState: "running" })).toBe("loom-db · Apply · cfn-deploy (running)");
198
+ expect(applyChipText("sf", { status: "ok", phase: "Apply", step: "cfn-deploy", stepState: "skipped", skip: "receipt" })).toBe("sf · Apply · cfn-deploy skipped: already applied (receipt) (ok)");
199
+ expect(applyChipText("sf", { status: "running", phase: "Apply", step: "cfn-outputs", stepState: "cached" })).toBe("sf · Apply · cfn-outputs cached (running)");
200
+ expect(applyChipText("db", { status: "gated", phase: "Apply", step: "gate:approve-db", stepState: "gated" })).toBe("db · Apply · gate:approve-db (gated)");
201
+ expect(applyChipText("db", { status: "pending" })).toBe("db (pending)");
202
+ });
203
+ });
204
+
205
+ describe("waitingLine", () => {
206
+ it("names the gate or decision point a component run waits on", () => {
207
+ expect(waitingLine({ gate: "approve-db", point: null, component: "loom-db", since: "t" })).toBe("waiting on gate approve-db (loom-db) since t");
208
+ expect(waitingLine({ gate: null, point: "pt-1", component: null, since: "t", message: "which region?" })).toBe("waiting on decision point pt-1 since t: which region?");
209
+ expect(waitingLine(null)).toBeNull();
210
+ });
211
+ });
@@ -0,0 +1,204 @@
1
+ // The tour player (behold.tour/v1): which chapter of a tour a cycle is in,
2
+ // and which of its visuals are on, from the events that have happened. Pure:
3
+ // the tour and an event stream in, plain data out, so the live carve and a
4
+ // recorded cycle or bundle can feed it the same way.
5
+ //
6
+ // An event is one of:
7
+ // { kind: "beat", beat, step, at } demo.json's beat and step
8
+ // { kind: "line", migration, line, at } a migration's first or last progress line
9
+ // { kind: "wave", wave, edge, at } a wave's job starting or ending
10
+ // `at` is a time in ms. A trigger matches an event of its kind whose fields
11
+ // equal the trigger's; `after_at` (a named run's finish, which the server
12
+ // resolves) keeps out an event at or before it, and `blocked` (the named run
13
+ // does not exist yet) matches nothing.
14
+ //
15
+ // The current chapter is the last chapter, in the file's order, whose trigger
16
+ // has fired by `t`: a cycle's beats only go forward, so a later chapter that
17
+ // fired wins over an earlier one that fired since.
18
+
19
+ const has = (o, k) => o && Object.prototype.hasOwnProperty.call(o, k);
20
+
21
+ /** The first event at or before `t` that `trigger` matches, or null. */
22
+ export function firedBy(trigger, events, t = Infinity) {
23
+ if (!trigger || trigger.blocked) return null;
24
+ if (Array.isArray(trigger.any)) {
25
+ let best = null;
26
+ for (const tr of trigger.any) {
27
+ const e = firedBy(tr, events, t);
28
+ if (e && (!best || e.at < best.at)) best = e;
29
+ }
30
+ return best;
31
+ }
32
+ let best = null;
33
+ for (const e of events || []) {
34
+ if (!(e.at <= t)) continue;
35
+ if (!matches(trigger, e)) continue;
36
+ if (!best || e.at < best.at) best = e;
37
+ }
38
+ return best;
39
+ }
40
+
41
+ function matches(tr, e) {
42
+ if (has(tr, "migration")) {
43
+ if (e.kind !== "line" || e.migration !== tr.migration || e.line !== tr.line) return false;
44
+ } else if (has(tr, "wave")) {
45
+ if (e.kind !== "wave" || e.wave !== tr.wave || e.edge !== tr.edge) return false;
46
+ } else {
47
+ if (e.kind !== "beat") return false;
48
+ if (has(tr, "beat") && e.beat !== tr.beat) return false;
49
+ if (has(tr, "step") && e.step !== tr.step) return false;
50
+ }
51
+ if (typeof tr.after_at === "number" && !(e.at > tr.after_at)) return false;
52
+ return true;
53
+ }
54
+
55
+ /**
56
+ * The chapter at `t`: `{ index, chapter, at, progress }`, or null before the
57
+ * first chapter's trigger. `step`: demo.json's step now, for how far a chapter
58
+ * that a beat started has got along the tour's `steps`.
59
+ */
60
+ export function chapterAt(tour, events, t = Infinity, step = null) {
61
+ const chapters = (tour && tour.chapters) || [];
62
+ for (let i = chapters.length - 1; i >= 0; i--) {
63
+ const e = firedBy(chapters[i].trigger, events, t);
64
+ if (e) return { index: i, chapter: chapters[i], at: e.at, progress: progressOf(tour, i, step) };
65
+ }
66
+ return null;
67
+ }
68
+
69
+ /** How far chapter `i` has got, 0..1: the step's place in the tour's steps; the last chapter is whole once reached. */
70
+ export function progressOf(tour, i, step) {
71
+ const chapters = (tour && tour.chapters) || [];
72
+ if (i >= chapters.length - 1) return 1;
73
+ const steps = (tour && tour.steps) || [];
74
+ const k = step ? steps.indexOf(step) : -1;
75
+ if (k < 0 || steps.length < 2) return 0;
76
+ return k / (steps.length - 1);
77
+ }
78
+
79
+ /** Each chapter's place on the rail: done, current (with its progress) or ahead. */
80
+ export function railOf(tour, at) {
81
+ return ((tour && tour.chapters) || []).map((c, i) => ({
82
+ n: i + 1,
83
+ id: c.id,
84
+ title: c.title,
85
+ state: !at ? "ahead" : i < at.index ? "done" : i === at.index ? "current" : "ahead",
86
+ progress: !at ? 0 : i < at.index ? 1 : i === at.index ? at.progress : 0,
87
+ }));
88
+ }
89
+
90
+ /** A chapter's visuals that are on at `t`: those with no `when`, and those whose `when` has fired. Each with `at`, when it fired. */
91
+ export function shownAt(chapter, events, t = Infinity) {
92
+ const out = [];
93
+ for (const s of (chapter && chapter.show) || []) {
94
+ if (!s.when) {
95
+ out.push({ ...s, at: null });
96
+ continue;
97
+ }
98
+ const e = firedBy(s.when, events, t);
99
+ if (e) out.push({ ...s, at: e.at });
100
+ }
101
+ return out;
102
+ }
103
+
104
+ /**
105
+ * A line of text with its facts filled in, or null when a fact it names has
106
+ * no value: a fact with no record behind it is left out, never shown as 0.
107
+ */
108
+ export function fill(text, facts) {
109
+ if (typeof text !== "string") return null;
110
+ let missing = false;
111
+ const out = text.replace(/\{([A-Za-z][A-Za-z0-9]*)\}/g, (_, k) => {
112
+ const v = facts ? facts[k] : undefined;
113
+ if (v === undefined || v === null || v === "") {
114
+ missing = true;
115
+ return "";
116
+ }
117
+ return typeof v === "number" ? v.toLocaleString("en-US") : String(v);
118
+ });
119
+ return missing ? null : out;
120
+ }
121
+
122
+ /** A chapter's lines, filled; a line naming a fact with no record is dropped. */
123
+ export function chapterLines(chapter, facts) {
124
+ return ((chapter && chapter.text) || []).map((l) => fill(l, facts)).filter((l) => l !== null);
125
+ }
126
+
127
+ /** The card's rows, filled; a row with no record is dropped. */
128
+ export function cardRows(card, facts) {
129
+ return (card || []).map((r) => ({ label: r.label, text: fill(r.text, facts) })).filter((r) => r.text !== null);
130
+ }
131
+
132
+ // --- the live badge's lag (faithfulness 3) -----------------------------------
133
+
134
+ /** After this long with no write while a migration runs, the badge says it is waiting for the job. */
135
+ export const LAG_WAIT_MS = 60_000;
136
+
137
+ /**
138
+ * The words beside LIVE: "last write N s ago", from the newest progress
139
+ * line's `at` and the page's clock; "waiting for the job" once the gap passes
140
+ * a minute while a migration runs; null with no write to measure from.
141
+ */
142
+ export function lagText(newestAt, now, running) {
143
+ const at = typeof newestAt === "number" ? newestAt : Date.parse(newestAt || "");
144
+ if (!Number.isFinite(at)) return null;
145
+ const gap = Math.max(0, now - at);
146
+ if (running && gap > LAG_WAIT_MS) return "waiting for the job";
147
+ const s = Math.floor(gap / 1000);
148
+ if (s < 60) return `last write ${s} s ago`;
149
+ const m = Math.floor(s / 60);
150
+ if (m < 60) return `last write ${m} min ago`;
151
+ return `last write ${Math.floor(m / 60)} h ago`;
152
+ }
153
+
154
+ // --- a landed dot's provenance (faithfulness 2) --------------------------------
155
+
156
+ /** A line's time as a reader reads it: UTC, to the millisecond. */
157
+ export function clockOf(at) {
158
+ const d = new Date(typeof at === "number" ? at : Date.parse(at || ""));
159
+ if (Number.isNaN(d.getTime())) return null;
160
+ return `${d.toISOString().slice(11, 23)} UTC`;
161
+ }
162
+
163
+ /**
164
+ * What happened to a landed dot, from its progress line and the migration
165
+ * that wrote it: "live-mv retagged aws_iam_role.x from tl1-terralith to
166
+ * tl1-team-a at 16:57:49.668 UTC · job #3655". `w`: { outcome, address, from,
167
+ * to, at, tool, job, reason }.
168
+ */
169
+ export function provenanceText(w) {
170
+ if (!w || !w.address) return null;
171
+ const when = clockOf(w.at);
172
+ const at = when ? ` at ${when}` : "";
173
+ const job = w.job ? ` · job #${w.job}` : "";
174
+ if (w.outcome === "stamped") return `${w.tool || "live-import"} stamped ${w.address} into ${w.to}${at}${job}`;
175
+ if (w.outcome === "refused") return `${w.tool || "live-mv"} refused to retag ${w.address} from ${w.from} to ${w.to}${w.reason ? `: ${w.reason}` : ""}${at}${job}`;
176
+ return `${w.tool || "live-mv"} retagged ${w.address} from ${w.from} to ${w.to}${at}${job}`;
177
+ }
178
+
179
+ /** The choudoufu command a migration ran, from its record's `change`: an adoption stamps with live-import, a retag moves with live-mv. */
180
+ export function migrationTool(change) {
181
+ return change === "adopt" ? "live-import" : "live-mv";
182
+ }
183
+
184
+ /** The job number in a job's URL (Forgejo/GitHub `/actions/runs/<n>`, GitLab `/-/jobs/<n>`), or null. */
185
+ export function jobNumber(url) {
186
+ const m = typeof url === "string" ? /\/(?:actions\/runs|-\/jobs|jobs)\/(\d+)(?:[/?#]|$)/.exec(url) : null;
187
+ return m ? Number(m[1]) : null;
188
+ }
189
+
190
+ // --- slowed playback (faithfulness 1) -------------------------------------------
191
+
192
+ /** The slowed control's choices: off is real time; each other is how far apart one read's lines are drawn. */
193
+ export const SLOWED = [
194
+ { n: 1, words: "real time", stepMs: 0 },
195
+ { n: 2, words: "slowed ×2", stepMs: 25 },
196
+ { n: 4, words: "slowed ×4", stepMs: 50 },
197
+ { n: 8, words: "slowed ×8", stepMs: 100 },
198
+ ];
199
+
200
+ /** The pacing of one read's lines for a slowed factor: 0 (real time) unless a person chose to slow it. */
201
+ export function stepMsFor(n) {
202
+ const s = SLOWED.find((x) => x.n === n);
203
+ return s ? s.stepMs : 0;
204
+ }
@@ -0,0 +1,115 @@
1
+ // The tour player (behold.tour/v1): the chapter a cycle is in from its events,
2
+ // the facts filled into a chapter's lines (a fact with no record is left out),
3
+ // the live badge's lag, and a landed dot's provenance.
4
+ import { describe, it, expect } from "vitest";
5
+ import { readFileSync } from "node:fs";
6
+ import { chapterAt, firedBy, shownAt, railOf, fill, chapterLines, cardRows, lagText, LAG_WAIT_MS, provenanceText, jobNumber, stepMsFor, SLOWED, migrationTool } from "./tour-player.js";
7
+
8
+ const tour = JSON.parse(readFileSync(new URL("./tours/terralith.json", import.meta.url), "utf8"));
9
+ const beat = (b, step = "applying", at = 1_000) => ({ kind: "beat", beat: b, step, at });
10
+
11
+ describe("the chapter from demo.json's beat", () => {
12
+ it("maps each beat to its chapter, in the tour's order", () => {
13
+ const ids = ["stock", "adopt", "split", "team", "cross"].map((b) => chapterAt(tour, [beat(b)]).chapter.id);
14
+ expect(ids).toEqual(["stock", "adopt", "split", "team", "cross"]);
15
+ });
16
+
17
+ it("is the epilogue once the cross beat applied, and through the reset", () => {
18
+ expect(chapterAt(tour, [beat("cross", "applied")]).chapter.id).toBe("epilogue");
19
+ expect(chapterAt(tour, [{ kind: "beat", beat: null, step: "reset", at: 5 }]).chapter.id).toBe("epilogue");
20
+ });
21
+
22
+ it("is no chapter before any trigger fires", () => {
23
+ expect(chapterAt(tour, [])).toBeNull();
24
+ expect(chapterAt(tour, [beat("stock", "applying", 50)], 10)).toBeNull();
25
+ });
26
+
27
+ it("says how far a chapter has got from the step, and the rail marks done, current and ahead", () => {
28
+ const at = chapterAt(tour, [beat("split", "applied")], Infinity, "applied");
29
+ expect(at.progress).toBe(1);
30
+ expect(chapterAt(tour, [beat("split", "planned")], Infinity, "planned").progress).toBeCloseTo(1 / 7);
31
+ expect(railOf(tour, at).map((c) => c.state)).toEqual(["done", "done", "current", "ahead", "ahead", "ahead"]);
32
+ });
33
+ });
34
+
35
+ describe("triggers on lines and waves", () => {
36
+ it("fires on a migration's last line, and on a wave only after the named run's finish", () => {
37
+ const events = [
38
+ { kind: "line", migration: "split", line: "first", at: 10 },
39
+ { kind: "wave", wave: 1, edge: "start", at: 20 },
40
+ { kind: "wave", wave: 1, edge: "start", at: 40 },
41
+ ];
42
+ expect(firedBy({ migration: "split", line: "last" }, events)).toBeNull();
43
+ expect(firedBy({ migration: "split", line: "first" }, events).at).toBe(10);
44
+ expect(firedBy({ wave: 1, edge: "start", after_at: 30 }, events).at).toBe(40);
45
+ expect(firedBy({ wave: 1, edge: "start", blocked: true }, events)).toBeNull();
46
+ });
47
+
48
+ it("shows a visual with no `when` at once, and one with a `when` once it fires", () => {
49
+ const ch = { show: [{ kind: "light" }, { kind: "checks", when: { migration: "split", line: "last" } }] };
50
+ expect(shownAt(ch, []).map((s) => s.kind)).toEqual(["light"]);
51
+ expect(shownAt(ch, [{ kind: "line", migration: "split", line: "last", at: 7 }]).map((s) => s.kind)).toEqual(["light", "checks"]);
52
+ });
53
+ });
54
+
55
+ describe("facts in a chapter's lines", () => {
56
+ const team = tour.chapters.find((c) => c.id === "team");
57
+
58
+ it("fills the contrast from both plans' numbers", () => {
59
+ expect(chapterLines(team, { teamPlanned: 3, planned: 82, of: 82 })).toEqual(["Team B changes one policy, and only team B is planned.", "Planned 3 of 82 · chapter 1: 82 of 82"]);
60
+ });
61
+
62
+ it("leaves a line out when a fact it names has no record, never showing 0", () => {
63
+ expect(chapterLines(team, { planned: 82, of: 82 })).toEqual(["Team B changes one policy, and only team B is planned."]);
64
+ expect(fill("{n} moved", {})).toBeNull();
65
+ expect(fill("{n} refused", { n: 0 })).toBe("0 refused");
66
+ });
67
+
68
+ it("drops an epilogue row whose record is missing", () => {
69
+ const rows = cardRows([{ label: "tag writes", text: "{writes}" }, { label: "recreated", text: "{recreated}" }], { writes: 86 });
70
+ expect(rows).toEqual([{ label: "tag writes", text: "86" }]);
71
+ });
72
+ });
73
+
74
+ describe("the live badge's lag", () => {
75
+ const now = Date.parse("2026-10-17T17:00:00Z");
76
+ it("counts from the newest line's time", () => {
77
+ expect(lagText("2026-10-17T16:59:48Z", now, true)).toBe("last write 12 s ago");
78
+ expect(lagText(now - 5 * 60_000, now, false)).toBe("last write 5 min ago");
79
+ });
80
+ it("says it waits for the job once the gap passes a minute while a migration runs", () => {
81
+ expect(lagText(now - LAG_WAIT_MS - 1, now, true)).toBe("waiting for the job");
82
+ expect(lagText(now - LAG_WAIT_MS - 1, now, false)).toBe("last write 1 min ago");
83
+ });
84
+ it("says nothing with no write to count from", () => {
85
+ expect(lagText(null, now, true)).toBeNull();
86
+ });
87
+ });
88
+
89
+ describe("a landed dot's provenance", () => {
90
+ it("names the write, its time and its job", () => {
91
+ expect(provenanceText({ outcome: "moved", tool: "live-mv", address: "aws_iam_role.team_0000_role", from: "tl54-terralith", to: "tl54-team-a", at: "2026-10-17T16:57:49.66896996Z", job: 3655 })).toBe(
92
+ "live-mv retagged aws_iam_role.team_0000_role from tl54-terralith to tl54-team-a at 16:57:49.668 UTC · job #3655",
93
+ );
94
+ });
95
+ it("names a stamp and a refusal in their own words, and leaves out a job no run names", () => {
96
+ expect(provenanceText({ outcome: "stamped", tool: "live-import", address: "aws_ecs_cluster.main", to: "tl54-terralith", at: "2026-10-17T16:54:06.283Z" })).toBe("live-import stamped aws_ecs_cluster.main into tl54-terralith at 16:54:06.283 UTC");
97
+ expect(provenanceText({ outcome: "refused", address: "aws_ecs_service.a", from: "x", to: "y", reason: "marker rewrite", at: "bad" })).toBe("live-mv refused to retag aws_ecs_service.a from x to y: marker rewrite");
98
+ });
99
+ it("reads the job number from a run's URL, and the tool from the record's change", () => {
100
+ expect(jobNumber("http://forgejo:3000/a/b/actions/runs/3655")).toBe(3655);
101
+ expect(jobNumber("https://gitlab.example/a/-/jobs/12")).toBe(12);
102
+ expect(jobNumber(null)).toBeNull();
103
+ expect(migrationTool("adopt")).toBe("live-import");
104
+ expect(migrationTool("retag")).toBe("live-mv");
105
+ });
106
+ });
107
+
108
+ describe("slowed playback", () => {
109
+ it("is real time unless a person picks a slowed factor", () => {
110
+ expect(SLOWED[0]).toEqual({ n: 1, words: "real time", stepMs: 0 });
111
+ expect(stepMsFor(1)).toBe(0);
112
+ expect(stepMsFor(4)).toBe(50);
113
+ expect(SLOWED.slice(1).every((s) => s.words.startsWith("slowed ×"))).toBe(true);
114
+ });
115
+ });