@tidal-ts/terminal 0.1.0

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.
@@ -0,0 +1,2229 @@
1
+ import { assign, enqueueActions, setup } from 'xstate';
2
+ import { COMPARE_PREFIX, hasPairOp, usesCompare, deriveId, opParams, opInputs, opNeedsColumns, opIsBand, opIsMulti, TARGET_ROLES, opSharesSourceAxis, studyTag, inputNames, isPairOp, isValidSpec, partStudyLabel, readPairParts, specUnit, substituteInput, } from '@tidal-ts/core';
3
+ /**
4
+ * The bar columns each data SOURCE carries — the one fact that decides whether a
5
+ * multi-column study is offerable on a series. Only the price series has bars;
6
+ * 54 of the adopted studies read high/low/close/volume, and on a vol series
7
+ * those columns name nothing. Held here, in the config-only machine, because
8
+ * it is a fact about the vocabulary (what a source key means), not about data —
9
+ * and because the menu AND the guard must agree, so there is exactly one copy.
10
+ */
11
+ export const SOURCE_COLUMNS = {
12
+ price: ['open', 'high', 'low', 'close', 'volume'],
13
+ };
14
+ /** Whether `op` can run on `source` — every bar column it needs is carried.
15
+ * The menu filters on it; `canAddStudy` refuses on it. */
16
+ export function studyOfferable(source, op) {
17
+ const have = new Set(SOURCE_COLUMNS[source ?? ''] ?? []);
18
+ return opNeedsColumns(op).every((c) => have.has(c));
19
+ }
20
+ /** Whether toggling `toggledId`'s eye is about to HIDE the series `pointer`
21
+ * names — itself, or a study the cascade carries. Showing never clears. */
22
+ function hidesPointer(context, toggledId, pointer) {
23
+ if (pointer === null)
24
+ return false;
25
+ const target = flatConfigs(context.rows).find((c) => c.id === toggledId);
26
+ if (!target?.visible)
27
+ return false; // hidden → about to show
28
+ const row = context.rows.find((r) => r.configs.some((c) => c.id === toggledId));
29
+ const cascade = row
30
+ ? studiesOn(row.configs, toggledId, isCatalogColumn(context))
31
+ : new Set([toggledId]);
32
+ return cascade.has(pointer);
33
+ }
34
+ import { axisRangeIsEmpty, logAllowed } from '@tidal-ts/chart';
35
+ import { configAxisId, seriesAxisId, sharedAxisId, } from '@tidal-ts/chart';
36
+ import { axisForAdd, canAddUnit } from './axisPolicy.js';
37
+ export const PRESET_SLOTS = 5;
38
+ /** Max viewport rows (the control-panel spec: 1–3, capped at 3 for now). */
39
+ export const MAX_ROWS = 3;
40
+ /** Committed height (px) a freshly added row gets — a **fixed** strip, not a flex
41
+ * remainder row (`height: 0`). Exactly one remainder row is kept (the seed's
42
+ * top/vol panel, which absorbs slack); a second would make dragging any seam
43
+ * redistribute space to the far panel too, not just its two neighbours. */
44
+ const NEW_ROW_HEIGHT = 150;
45
+ /**
46
+ * Guarantee EXACTLY-ONE remainder row (`height: 0`) — the row that absorbs slack.
47
+ *
48
+ * The layout has always assumed one; nothing enforced it. `removeRow` could drop
49
+ * the only remainder row, and `addRow` always adds a FIXED row, so
50
+ * remove-the-top-row-then-add-a-row left a stack with none. The renderer's
51
+ * resolver silently promotes the LAST row in that case, while the splitter reads
52
+ * `height === 0` to decide which side of a seam is elastic — so the two
53
+ * disagreed about which row was flexible, and a drag budgeted against a row the
54
+ * resolver was ignoring. Symptom: the seam refused to travel more than
55
+ * `NEW_ROW_HEIGHT − MIN_FIXED` (60px) before it stopped moving.
56
+ *
57
+ * The FIRST row is promoted, matching the seed (the vol panel absorbs slack) and
58
+ * keeping "the big chart is on top" true after any sequence of adds and removes.
59
+ * Applied wherever the row LIST changes shape — add, remove, and preset apply,
60
+ * since a preset saved before this existed can carry a stack with no remainder.
61
+ */
62
+ function withRemainder(rows) {
63
+ if (rows.length === 0 || rows.some((r) => r.height === 0))
64
+ return rows;
65
+ return rows.map((r, i) => (i === 0 ? { ...r, height: 0 } : r));
66
+ }
67
+ /**
68
+ * Config identity. A seated config's `id` is minted here and never derived from
69
+ * what it computes: `s-3` keys selection, expansion, the chart theme, axis
70
+ * membership and the user's overrides, and it survives every edit to the
71
+ * config's spec. What the config *computes* lives in `column`
72
+ * (`deriveId(derive)`), which is recomputed on each edit.
73
+ *
74
+ * The prefix is deliberately un-column-like. Nothing may parse an id, and an id
75
+ * used as a column name resolves to nothing — loudly — rather than reading some
76
+ * other series' data (see {@link SeriesConfig}).
77
+ */
78
+ const CONFIG_ID_PREFIX = 's-';
79
+ export const mintId = (seq) => `${CONFIG_ID_PREFIX}${seq}`;
80
+ /** Generated ROW ids share the same monotonic-counter rule (`row-2`). */
81
+ const ROW_ID_PREFIX = 'row-';
82
+ const mintRowId = (seq) => `${ROW_ID_PREFIX}${seq}`;
83
+ /**
84
+ * One past the highest `<prefix><n>` id in `ids` — where a monotonic counter has
85
+ * to restart so it can't re-issue an id that arrived **pre-minted**: a persisted
86
+ * preset was minted in an earlier session and can carry ids well above a fresh
87
+ * actor's counter.
88
+ *
89
+ * Strict digits, capped: `Number('')` is 0 and `Number('1e21')` is enormous, and
90
+ * neither is an id we minted — accepting them would move the counter on
91
+ * something arbitrary, in the second case far enough that `mintId` starts
92
+ * returning the same string every time.
93
+ */
94
+ function seqAfter(ids, prefix) {
95
+ const re = new RegExp(`^${prefix}(\\d{1,9})$`);
96
+ let max = -1;
97
+ for (const id of ids) {
98
+ const m = re.exec(id);
99
+ if (m)
100
+ max = Math.max(max, Number(m[1]));
101
+ }
102
+ return max + 1;
103
+ }
104
+ const configIds = (rows) => flatConfigs(rows).map((c) => c.id);
105
+ const cfgSeqAfter = (rows) => seqAfter(configIds(rows), CONFIG_ID_PREFIX);
106
+ const rowSeqAfter = (rows) => seqAfter(rows.map((r) => r.id), ROW_ID_PREFIX);
107
+ // --- pure helpers (shared with selectors; exported for tests) ----------------
108
+ const flatConfigs = (rows) => rows.flatMap((r) => r.configs);
109
+ /** `rootId` plus every **study** that (transitively) derives from it — so removing
110
+ * a series cascades to its dependent studies. Only follows STUDY sources: a
111
+ * study's output column is folded per-config and vanishes when the study is
112
+ * removed (its dependents would strand invisible + unremovable), whereas a raw
113
+ * data column persists, so a study of a raw column keeps resolving after that
114
+ * raw series is removed. */
115
+ function derivedClosure(configs, rootId) {
116
+ const doomed = new Set([rootId]);
117
+ // Edges resolve by COLUMN (what a spec input names); the set itself holds
118
+ // IDS, because that is what callers filter configs and re-point pointers by.
119
+ const byColumn = new Map(configs.map((c) => [c.column, c]));
120
+ for (let grew = true; grew;) {
121
+ grew = false;
122
+ for (const c of configs) {
123
+ if (doomed.has(c.id) || !c.derive)
124
+ continue;
125
+ // EVERY input is an edge — a pair's B leg is as load-bearing as its A leg
126
+ // (PR #128 review, HIGH). An input names a raw feed column or a nested
127
+ // spec, and either way the config that produces it carries that name as
128
+ // its `column`.
129
+ const srcs = inputNames(c.derive).map((n) => byColumn.get(n));
130
+ if (srcs.some((src) => src?.derive && doomed.has(src.id))) {
131
+ doomed.add(c.id); // derives from a doomed study ⇒ its source column will vanish
132
+ grew = true;
133
+ }
134
+ }
135
+ }
136
+ return doomed;
137
+ }
138
+ /**
139
+ * `rootId` plus the **studies layered on it** within this row — the travel set for
140
+ * a cross-row move. `addStudy` co-locates a study with its target, so moving the
141
+ * target takes its studies along rather than leaving `Price · SMA(20)` behind.
142
+ *
143
+ * Only **studies** travel, never a derived **catalog** metric (`isCatalogId`): a
144
+ * study exists solely as a layer on the series it was added to, whereas the
145
+ * realized-vol line is added independently and merely happens to read `ccVar`'s
146
+ * column — dragging it along when the user moved ccVar was a surprise, and since
147
+ * their units differ it could demand two axes the target row didn't have (PR #119
148
+ * review). Every study inherits its target's unit, so a travel set is single-unit
149
+ * by construction.
150
+ *
151
+ * Distinct from {@link derivedClosure} (removal), which follows only study→study
152
+ * edges because a raw data column outlives the config that displayed it.
153
+ */
154
+ /**
155
+ * `rootId` plus the **studies built on it** — the set an eye cascades over.
156
+ *
157
+ * Deliberately NOT {@link layeredOn}, which is the travel set and also carries a
158
+ * leg's GROUP SIBLINGS, because a pair must move whole. Visibility is the one
159
+ * case where that rule inverts: a pair's own eye hides both legs
160
+ * (`group.toggleVisible`), but a LEG's eye must leave its partner alone — each
161
+ * leg keeps its own state, which is the point of the pair eye being a separate
162
+ * control. Sharing `layeredOn` here made one leg's eye hide the other.
163
+ *
164
+ * A study is subordinate to what it is built on; a leg is a peer of its partner.
165
+ * Same graph, opposite rule, so they get their own walks.
166
+ */
167
+ /** Whether a study already has a study built on it — the no-branching test.
168
+ * Edges resolve by COLUMN, which is what a spec input names. */
169
+ function hasStudyChild(configs, target) {
170
+ return configs.some((c) => c.id !== target.id && c.derive && inputNames(c.derive).includes(target.column));
171
+ }
172
+ function studiesOn(configs, rootId, isCatalogColumn) {
173
+ const set = new Set([rootId]);
174
+ for (let grew = true; grew;) {
175
+ grew = false;
176
+ for (const c of configs) {
177
+ if (set.has(c.id) || !c.derive || isCatalogColumn(c.column))
178
+ continue;
179
+ if (configs.some((p) => set.has(p.id) && inputNames(c.derive).includes(p.column))) {
180
+ set.add(c.id);
181
+ grew = true;
182
+ }
183
+ }
184
+ }
185
+ return set;
186
+ }
187
+ function layeredOn(configs, rootId, isCatalogColumn) {
188
+ const set = new Set([rootId]);
189
+ for (let grew = true; grew;) {
190
+ grew = false;
191
+ for (const c of configs) {
192
+ if (set.has(c.id))
193
+ continue;
194
+ // A LEG GROUP travels whole: the panel renders it per row, so a group
195
+ // with a leg in each row would draw as two one-legged pairs that nothing
196
+ // can re-join (PR #144 review, MEDIUM).
197
+ const sibling = !!c.group && configs.some((p) => set.has(p.id) && p.group?.id === c.group.id);
198
+ if (sibling) {
199
+ set.add(c.id);
200
+ grew = true;
201
+ continue;
202
+ }
203
+ if (!c.derive || isCatalogColumn(c.column))
204
+ continue;
205
+ // A study names its sources by COLUMN — never by the id of the config
206
+ // that happens to display them.
207
+ if (configs.some((p) => set.has(p.id) && inputNames(c.derive).includes(p.column))) {
208
+ set.add(c.id);
209
+ grew = true;
210
+ }
211
+ }
212
+ }
213
+ return set;
214
+ }
215
+ /**
216
+ * Place a whole travelling set onto a target row's axes, or `null` if ANY of them
217
+ * can't go. Members are folded **incrementally** — each mover is placed against
218
+ * the target's configs *plus the movers already placed* — so a `%` study
219
+ * following a `variance` source can't silently land on the same side as its
220
+ * source and strand the row with two units on one axis (originally: both L/R
221
+ * chips then read disabled and the row was unrecoverable through the UI —
222
+ * PR #119 review; the chip is gone, but a mixed-unit shared axis is still a
223
+ * state nothing should be able to create). All-or-nothing, so the guard and
224
+ * the action can never disagree.
225
+ */
226
+ function placeOnRow(target, movers) {
227
+ const seated = members(target);
228
+ const placed = [];
229
+ for (const c of movers) {
230
+ // An UNLINKED mover brings its own axis: it keeps its side, binds no unit,
231
+ // and can never fail to seat (the whole point of "arrives unlinked").
232
+ if (c.axisGroup) {
233
+ placed.push({ ...c });
234
+ continue;
235
+ }
236
+ const axis = axisForAdd(seated, c.unit ?? '', c.axis);
237
+ if (!axis)
238
+ return null;
239
+ seated.push({ unit: c.unit ?? '', axis });
240
+ placed.push({ ...c, axis });
241
+ }
242
+ return placed;
243
+ }
244
+ /**
245
+ * The row's configs as **blocks** — each root with the studies layered on it,
246
+ * studies FIRST (a study paints over its source, and index 0 is the top).
247
+ *
248
+ * Draw order is a sequence of blocks, not of loose configs, because that is
249
+ * what the control tree shows: a study is a child of the metric it derives
250
+ * from, so moving the metric must carry its studies. Before this, ordering
251
+ * stepped the flat list — and since a study sits directly in front of its
252
+ * target, "move higher" on a metric that owned one swapped it with its own
253
+ * hidden study: nothing moved on screen, and the study silently fell behind
254
+ * its source on the canvas (PR #137 review, HIGH).
255
+ *
256
+ * A study whose target is elsewhere (another row, or removed) heads its own
257
+ * block, so every config appears exactly once.
258
+ */
259
+ export function rowBlocks(configs) {
260
+ const parentOf = new Map();
261
+ for (const c of configs) {
262
+ // Only a tunable STUDY attaches to a parent; a derived catalog metric and a
263
+ // pair stand alone (the same rule `layeredOn` travels by). Asked of the
264
+ // registry — a period-shaped test was the same question only while every
265
+ // tunable op had one param called `period` (PR #181 review, MEDIUM).
266
+ if (!c.derive || opParams(c.derive.op).length === 0)
267
+ continue;
268
+ const names = inputNames(c.derive);
269
+ const parent = configs.find((x) => x.id !== c.id && names.includes(x.column));
270
+ if (parent)
271
+ parentOf.set(c.id, parent.id);
272
+ }
273
+ // A block is keyed by the chain's ROOT, not the immediate parent: studies are
274
+ // a PIPELINE (metric → first → second → …), so the whole chain travels as one
275
+ // block. Keying on the parent put a 2-deep study in a block of its own,
276
+ // appended last — so one "Move lower" on the metric sent the EMA from the
277
+ // front of the row to the back, behind the SMA it derives from (PR #143
278
+ // review, MEDIUM; the panel-side half of this was fixed in #137).
279
+ const rootOf = (id) => {
280
+ const seen = new Set([id]);
281
+ let cur = id;
282
+ for (;;) {
283
+ const parent = parentOf.get(cur);
284
+ // No parent, or a cycle from corrupt persisted state: stop where we are.
285
+ if (parent == null || seen.has(parent))
286
+ return cur;
287
+ seen.add(parent);
288
+ cur = parent;
289
+ }
290
+ };
291
+ // ONE pass in list order, so a block's members keep the positions they
292
+ // already had — grouping must not silently reorder the row. (Placing roots
293
+ // first and unshifting children onto them reverses a 2-deep chain.) A chain
294
+ // whose root isn't in this row has no parent HERE, so it heads its own block
295
+ // and is never dropped.
296
+ const at = new Map();
297
+ const out = [];
298
+ for (const c of configs) {
299
+ const root = rootOf(c.id);
300
+ let bi = at.get(root);
301
+ if (bi == null) {
302
+ bi = out.length;
303
+ at.set(root, bi);
304
+ out.push([]);
305
+ }
306
+ out[bi].push(c);
307
+ }
308
+ return out;
309
+ }
310
+ /**
311
+ * The END of `rootId`'s study chain — what `+ Study` extends.
312
+ *
313
+ * Studies are a pipeline the panel renders as a flat list, so adding one must
314
+ * APPEND (read the current output) rather than branch off the root. The host
315
+ * resolves the tail at PICK time rather than at open time: the study picker
316
+ * stays open across picks, and a target captured when it opened is stale the
317
+ * moment the first study lands — which silently built a branch the panel then
318
+ * printed as a pipeline (PR #143 review, HIGH).
319
+ *
320
+ * Follows the same edge the panel groups by: a study's spec input names its
321
+ * target's column. Returns `rootId` itself when nothing is layered on it.
322
+ */
323
+ export function studyChainTail(configs, rootId) {
324
+ const seen = new Set([rootId]);
325
+ let cur = configs.find((c) => c.id === rootId);
326
+ if (!cur)
327
+ return rootId;
328
+ for (;;) {
329
+ const next = configs.find((c) => c.id !== cur.id &&
330
+ !seen.has(c.id) &&
331
+ !!c.derive &&
332
+ opParams(c.derive.op).length > 0 &&
333
+ inputNames(c.derive).includes(cur.column));
334
+ if (!next)
335
+ return cur.id;
336
+ seen.add(next.id);
337
+ cur = next;
338
+ }
339
+ }
340
+ /** Move `from` to `to` in a copy of `list` (a splice-move, not a swap — so the
341
+ * items in between shift by one, which is what a layers list does). */
342
+ function reindex(list, from, to) {
343
+ const out = [...list];
344
+ const [item] = out.splice(from, 1);
345
+ out.splice(Math.max(0, Math.min(to, out.length)), 0, item);
346
+ return out;
347
+ }
348
+ /** The target index for an `order` step within a row of `n` items. Clamped, so
349
+ * an already-front item's `up` is a no-op rather than a wrap. */
350
+ function orderTarget(i, n, to) {
351
+ if (to === 'front')
352
+ return 0;
353
+ if (to === 'back')
354
+ return n - 1;
355
+ return to === 'up' ? Math.max(0, i - 1) : Math.min(n - 1, i + 1);
356
+ }
357
+ /** The row a config with `source` belongs to: the one already holding that
358
+ * source, else an **empty** row (a viewport with no series is a natural home —
359
+ * this is what returns a re-added vol series to the emptied vol row instead of
360
+ * dumping it in the price row), else the last row. Wave A keeps the two-row
361
+ * shape, so a vol metric lands in the vol row and a price metric in the price. */
362
+ function rowForSource(rows, source) {
363
+ return (rows.find((r) => r.configs.some((c) => c.source === source)) ??
364
+ rows.find((r) => r.configs.length === 0) ??
365
+ rows.at(-1));
366
+ }
367
+ /** The data column a catalog entry reads. Unlike a seated config, a catalog
368
+ * entry IS its computation — so its id doubles as its column name when it
369
+ * doesn't name one (`iv21`), and a derived entry names its folded output. */
370
+ export const entryColumn = (e) => e.column ?? e.id;
371
+ /** A config from a catalog entry — present + visible, on its preferred axis.
372
+ * `id` is the freshly minted identity; the catalog id survives as the
373
+ * `column`, which is what the entry actually contributed. */
374
+ function toConfig(e, id, axis = e.axis) {
375
+ return {
376
+ id,
377
+ label: e.label,
378
+ color: e.color,
379
+ axis,
380
+ style: e.style,
381
+ visible: true,
382
+ column: entryColumn(e),
383
+ source: e.source,
384
+ value: null,
385
+ unit: e.unit,
386
+ family: e.family,
387
+ tenor: e.tenor,
388
+ censor: e.censor,
389
+ derive: e.derive,
390
+ };
391
+ }
392
+ /** The spec a study of `target` at `(op, period)` induces — reads the target's
393
+ * DATA column, or **nests** the target's own spec when the target is derived
394
+ * (the engine reads a string input as a raw column, so composition nests;
395
+ * content-addressing makes the seated copy and the nested copy one node). */
396
+ const studySpec = (target, op, period) => {
397
+ // Params come from the REGISTRY, not from a list here: an op is tuned by
398
+ // exactly what it declares, so a two-param study (a band's `period` +
399
+ // `stdDev`) is complete on arrival without this function knowing it exists.
400
+ // `period` is the one the picker sends; every other param seeds from its
401
+ // declared default and is tuned afterwards in the controls.
402
+ //
403
+ // Stamping a param onto an op that declares none mints a spec the registry
404
+ // rejects, and the guard then refuses the add with no feedback (PR #137
405
+ // review, MEDIUM) — which is why this is a filter over declared params and
406
+ // not a spread of whatever the caller had.
407
+ const declared = opParams(op);
408
+ const params = {};
409
+ for (const p of declared)
410
+ params[p.name] = p.name === 'period' ? period : p.default;
411
+ // Inputs are bound POSITIONALLY against the op's declared roles. The single
412
+ // `column` role takes the target — which is what makes composition nest (an
413
+ // SMA of an SMA embeds its parent's spec). Every other role names a bar
414
+ // column and binds to its own declared default, because a multi-input study
415
+ // is a study of a SERIES rather than of a column: an ATR reads high, low and
416
+ // close directly, and its target only decides which row it lands in.
417
+ //
418
+ // A consequence worth knowing: two ATR(14)s added from different targets on
419
+ // the same source resolve to the SAME spec, so the engine folds one column
420
+ // and `deriveId` dedupes them. That is correct — ATR(14) of the bars is one
421
+ // series — and it is why the picker has to refuse the op where its columns
422
+ // are absent (`opNeedsColumns`) rather than let the fold skip it silently.
423
+ const self = target.derive ?? target.column;
424
+ const inputs = opInputs(op).map((r) =>
425
+ // A target role takes the target; a bar role takes its own column. No
426
+ // default and not a target role should be unreachable (a benchmark role is
427
+ // refused at adoption), so fall back to the target rather than emit an
428
+ // `undefined` input that throws inside `specId`.
429
+ TARGET_ROLES.has(r.role) ? self : (r.default ?? self));
430
+ return {
431
+ op,
432
+ ...(declared.length > 0 ? { params } : {}),
433
+ inputs: inputs.length > 0 ? inputs : [target.derive ?? target.column],
434
+ };
435
+ };
436
+ /** A study `SeriesConfig` layered on a target — same source, and the same axis
437
+ * and unit WHEN the op reads in its source's units; its
438
+ * column is induced by `applyDerived` from the spec, so `column ===
439
+ * deriveId(spec)` while `id` is minted. It reads as **its source** (name + the
440
+ * source's params) with the op·period appended — e.g. `Price · SMA · 20`,
441
+ * `ATM Vol · 21D · SMA · 20` — so the lineage is legible. Warm default colour so
442
+ * it reads over its source; the user recolours. */
443
+ function studyConfig(target, op, period, id) {
444
+ const derive = studySpec(target, op, period);
445
+ // Only an `inherit` op may share its source's scale (pond's rule, shipped
446
+ // with the catalog's `unit`). An RSI is bounded 0..100 and a vol reading is
447
+ // ~20, so sharing stretches the axis five times and squashes the very series
448
+ // the study was added to explain — which is exactly what it did on a running
449
+ // render before this. A study that reads in its own units gets its own axis
450
+ // group, keyed by its own id, and its own unit for the labels.
451
+ const shares = opSharesSourceAxis(op);
452
+ const own = specUnit(derive, (col) => (col === target.column ? (target.unit ?? '') : ''));
453
+ return {
454
+ id,
455
+ ...(shares ? {} : { axisGroup: id }),
456
+ label: `${target.label} · ${studyTag(derive)}`, // legend chip
457
+ family: target.family ?? target.label, // main line = the source's name
458
+ tenor: target.tenor, // carry the source's tenor into the params sub-line
459
+ // A study is the same reading, smoothed — so it takes its metric's COLOUR
460
+ // and is told apart by its STYLE (weight/dash from `settings.derived`).
461
+ // A fixed amber made every study on the chart one colour, which said
462
+ // nothing about which metric it belonged to (Peter, 2026-08-18).
463
+ color: target.color,
464
+ axis: target.axis,
465
+ // A multi-output op can only draw as a multi-output style: its `column` is
466
+ // a spec id naming SEVERAL columns, so every single-column style would read
467
+ // nothing and draw an empty layer. A band is the Middle/Upper/Lower wash;
468
+ // anything else is N lines off one spec, one per declared output.
469
+ style: opIsBand(op) ? 'band' : opIsMulti(op) ? 'lines' : 'line',
470
+ visible: true,
471
+ source: target.source,
472
+ column: deriveId(derive),
473
+ value: null,
474
+ unit: shares ? target.unit : own,
475
+ derive,
476
+ };
477
+ }
478
+ /** Legend label per pair op — the spread reads as its construction. */
479
+ const PAIR_LABEL = {
480
+ diff: (a, b) => `${a} \u2212 ${b}`,
481
+ ratio: (a, b) => `${a} / ${b}`,
482
+ logRatio: (a, b) => `log(${a} / ${b})`,
483
+ };
484
+ /**
485
+ * The seated config a leg names — **the one lookup for "is this leg on the
486
+ * chart"**, because the picker names a leg two different ways: a seated derived
487
+ * series by its config id, and a raw metric by its CATALOG id (a raw leg needn't
488
+ * be seated at all, so the catalog entry is what the menu lists).
489
+ *
490
+ * A catalog id therefore has to resolve to the seat when one exists. Before the
491
+ * identity split that was automatic — a seated raw config's id WAS the catalog
492
+ * id — and matching only on `c.id` afterwards silently stopped finding those
493
+ * seats, which sent every raw-leg spread to `rowForSource`'s row instead of in
494
+ * front of its leg A (PR #139 review, HIGH).
495
+ */
496
+ function legSeat(context, metricId) {
497
+ const all = flatConfigs(context.rows);
498
+ const byId = all.find((c) => c.id === metricId);
499
+ if (byId)
500
+ return byId;
501
+ const entry = context.catalog.find((e) => e.id === metricId);
502
+ return entry ? all.find((c) => c.column === entryColumn(entry)) : undefined;
503
+ }
504
+ /**
505
+ * Resolve a pair-leg id: a SEATED config first (so studies and spreads
506
+ * compose, and so a seated metric contributes its own label + overrides), else
507
+ * a CATALOG metric — a leg does not need to be on the chart, because every raw
508
+ * catalog column is already carried by its source series (Peter's call,
509
+ * 2026-08-16). An unseated DERIVED catalog metric is refused: its column exists
510
+ * only once its spec is folded, and specs are config-borne.
511
+ */
512
+ const resolveLeg = (context, id) => {
513
+ const cfg = legSeat(context, id);
514
+ if (cfg)
515
+ return {
516
+ label: cfg.label,
517
+ unit: cfg.unit ?? '',
518
+ column: cfg.column,
519
+ source: cfg.source ?? '',
520
+ spec: cfg.derive,
521
+ };
522
+ const entry = context.catalog.find((e) => e.id === id);
523
+ if (entry && !entry.derive)
524
+ return {
525
+ label: entry.label,
526
+ unit: entry.unit,
527
+ column: entryColumn(entry),
528
+ source: entry.source,
529
+ };
530
+ return null;
531
+ };
532
+ /** Rebind an input to the **compare role**: the prefix lands on the raw-column
533
+ * LEAVES (a nested spec keeps its shape but reads `cmp_` columns), so a
534
+ * derived compare-bound leg folds against the joined series like any other —
535
+ * the role is column-addressed all the way down. */
536
+ const underCompare = (input) => typeof input === 'string'
537
+ ? // IDEMPOTENT at the leaf: in a two-entity world "the compare of a
538
+ // compare-reading leg" is the compare — double-prefixing minted a
539
+ // `cmp_cmp_*` column no join ever carries (PR #131 review).
540
+ input.startsWith(COMPARE_PREFIX)
541
+ ? input
542
+ : `${COMPARE_PREFIX}${input}`
543
+ : { ...input, inputs: input.inputs.map(underCompare) };
544
+ /** "Is this column a catalog metric's?" — {@link layeredOn}'s test for the
545
+ * derived metrics that stand alone instead of travelling with a source. A
546
+ * seated config's id no longer says where it came from, so catalog-ness is
547
+ * read off what it computes. */
548
+ const isCatalogColumn = (context) => {
549
+ const cols = new Set(context.catalog.map(entryColumn));
550
+ return (column) => cols.has(column);
551
+ };
552
+ /**
553
+ * What unit a RAW column reads in — {@link specUnit}'s leaf resolver, so a
554
+ * spec's unit can be recomputed from its structure alone.
555
+ *
556
+ * The catalog is the authority (it declares each metric's unit); seated configs
557
+ * fill in anything folded rather than fed. A `cmp_`-prefixed leaf is the same
558
+ * metric read for the comparison symbol, so it falls back to the bare column
559
+ * rather than reading unitless.
560
+ */
561
+ export const columnUnits = (catalog, configs = []) => {
562
+ const units = new Map();
563
+ for (const c of configs)
564
+ units.set(c.column, c.unit ?? '');
565
+ for (const e of catalog)
566
+ units.set(entryColumn(e), e.unit);
567
+ return (column) => units.get(column) ??
568
+ (column.startsWith(COMPARE_PREFIX)
569
+ ? (units.get(column.slice(COMPARE_PREFIX.length)) ?? '')
570
+ : '');
571
+ };
572
+ const unitOfColumn = (scope) => columnUnits(scope.catalog, flatConfigs(scope.rows));
573
+ /** A resolved+bound leg: the graph input the pair spec takes, and the
574
+ * decorated label the spread reads by. Order matters: the study wraps the
575
+ * metric, then the compare rebind rewrites the LEAVES — so a compare-bound
576
+ * studied leg computes the study over the compare columns. */
577
+ const boundLeg = (leg, input) => {
578
+ let graph = leg.spec ?? leg.column;
579
+ let label = leg.label;
580
+ if (input.study) {
581
+ graph = { op: input.study.op, params: { period: input.study.period }, inputs: [graph] };
582
+ label = `${label} · ${input.study.op.toUpperCase()}(${input.study.period})`;
583
+ }
584
+ if (input.entity === 'compare') {
585
+ graph = underCompare(graph);
586
+ // Role-bound legs print the ROLE, never a ticker — a ticker in a chip is
587
+ // reserved for a PINNED leg (the binding-legibility rule, Tidal's pairs plan).
588
+ label = `${label} (cmp)`;
589
+ }
590
+ return { graph, label };
591
+ };
592
+ /** The spec a pair induces — a two-input node whose legs are bound graph
593
+ * inputs (raw columns, nested leg specs, per-leg studies, compare rebinds). */
594
+ const pairSpec = (a, aIn, b, bIn, op) => {
595
+ const spec = { op, inputs: [boundLeg(a, aIn).graph, boundLeg(b, bIn).graph] };
596
+ return spec;
597
+ };
598
+ /** A pair `SeriesConfig` — the A-vs-B spread (TDL-PAIR). The derived line is
599
+ * the signal (George's gauge feedback: the diff/ratio is more stable than
600
+ * either leg), so it inserts IN FRONT of leg A on A's row. **A spread arrives
601
+ * UNLINKED** (its own `axisGroup`, on the right side): its regime differs by
602
+ * construction (oscillates about 0 or 1), so it starts on its own scale and
603
+ * binds no side's unit — one re-link click away from sharing if wanted (the
604
+ * axis panel). Unit rules still matter for that re-link: a diff of like units
605
+ * reads in that unit; a ratio/log-ratio is unitless. Purple default so a
606
+ * spread reads distinctly from studies (amber); the user recolours. */
607
+ /** The spread's colour when the host supplies no palette — a plain CSS colour
608
+ * (a soft violet) any `resolveColor` passes through unchanged. */
609
+ export const DEFAULT_SPREAD_COLOR = '#8b7cf6';
610
+ function pairConfig(a, aIn, b, bIn, op, id, unitOf,
611
+ /** The host's colour keys, and the colours already drawn — the spread takes
612
+ * the first key not in use, else the palette's first, else
613
+ * {@link DEFAULT_SPREAD_COLOR}: a config needs SOME colour, and a host that
614
+ * supplies no palette gets a plain CSS one its resolver passes through. */
615
+ palette = [], taken = []) {
616
+ const la = boundLeg(a, aIn);
617
+ const lb = boundLeg(b, bIn);
618
+ const derive = { op, inputs: [la.graph, lb.graph] };
619
+ return {
620
+ id,
621
+ label: PAIR_LABEL[op](la.label, lb.label),
622
+ color: palette.find((k) => !taken.includes(k)) ?? palette[0] ?? DEFAULT_SPREAD_COLOR,
623
+ axis: 'R',
624
+ axisGroup: id, // its own scale — the key IS its id, so the axis id is stable
625
+ style: 'line',
626
+ visible: true,
627
+ source: a.source,
628
+ column: deriveId(derive),
629
+ value: null,
630
+ // From the registry's declared output unit, so the lens and the add path
631
+ // can never disagree about what a spread reads in (`specUnit`): a like-unit
632
+ // diff keeps the unit, a ratio is unitless, a log-ratio reads `log`.
633
+ unit: specUnit(derive, unitOf),
634
+ derive,
635
+ };
636
+ }
637
+ /**
638
+ * A pair PART's display name, rebuilt from the spec — the same construction
639
+ * `boundLeg` writes, read back the other way: the metric's catalog name, its
640
+ * studies in application order, and `(cmp)` for a compare-bound leg (never a
641
+ * ticker; a ticker in a label is reserved for a pinned leg — the
642
+ * binding-legibility rule in Tidal's pairs plan).
643
+ */
644
+ function partLabel(scope, part) {
645
+ const studied = part.studies.reduce((acc, st) => `${acc} · ${partStudyLabel(st)}`, columnLabel(scope, part.base));
646
+ return part.entity === 'compare' ? `${studied} (cmp)` : studied;
647
+ }
648
+ /** The display name of a column — its catalog entry's, else a seated config's,
649
+ * else the raw column. Exported because the PANEL names pair parts too (it
650
+ * renders each leg as its own row), and two spellings of "what is this column
651
+ * called" would drift. */
652
+ export function columnLabel(scope, column) {
653
+ return (scope.catalog.find((e) => entryColumn(e) === column)?.label ??
654
+ flatConfigs(scope.rows).find((c) => c.column === column)?.label ??
655
+ column);
656
+ }
657
+ /**
658
+ * The label a pair reads by, **rebuilt from its spec** rather than patched.
659
+ *
660
+ * This is the scoped answer to the label problem propagation ran into: a
661
+ * composed label can't be edited textually (a leg's label is routinely a
662
+ * substring of its sibling's — PR #140 review), but it CAN be regenerated,
663
+ * because the spec says exactly what the pair is. Returns undefined when the
664
+ * spec doesn't decompose into two named parts (a spread of spreads), in which
665
+ * case the caller keeps the existing label rather than inventing one. The
666
+ * general version of this is `TDL-LINEAGE`.
667
+ */
668
+ function pairLabel(scope, spec) {
669
+ const parts = readPairParts(spec);
670
+ if (!parts || !isPairOp(spec.op))
671
+ return undefined;
672
+ return PAIR_LABEL[spec.op](partLabel(scope, parts[0]), partLabel(scope, parts[1]));
673
+ }
674
+ /**
675
+ * An `addPair` whose fn() is `Unjoined` — the pair is a LEG GROUP from the
676
+ * start, so no spread is ever seated and immediately taken apart.
677
+ *
678
+ * Composed from the same `planSplit` the fn() lens runs, against the pair
679
+ * config the join path WOULD have built: one description of "what are this
680
+ * pair's legs, and which of them already exist", not two.
681
+ */
682
+ function planAddGroup(context, event, row) {
683
+ const a = resolveLeg(context, event.a.metricId);
684
+ const b = resolveLeg(context, event.b.metricId);
685
+ if (!a || !b)
686
+ return null;
687
+ // `planSplit` is written against a join, so an unjoined pair still needs one
688
+ // to build its plan with. It is scaffolding, not memory: f() is fixed at
689
+ // creation, and nothing reads this back or restores it.
690
+ const join = event.op === 'none' ? 'diff' : event.op;
691
+ const pair = pairConfig(a, event.a, b, event.b, join, mintId(context.cfgSeq), unitOfColumn(context), context.palette, row.configs.map((c) => c.color));
692
+ return planSplit(context, pair, row.configs, context.cfgSeq + 1, true);
693
+ }
694
+ /** Whether an `addPair` will actually seat a config — the same early returns the
695
+ * `rows` assigner makes. Its sibling assigners (`expanded`, `cfgSeq`) must
696
+ * agree with it about whether an id was consumed, or the counter drifts and
697
+ * the expansion points at a config that was never created. */
698
+ /** The row an `addPair` lands on — a named one, else leg A's, else A's source
699
+ * row. ONE chooser, read by the guard and every assigner, so they cannot
700
+ * disagree about whether (and where) a pair was created. */
701
+ function pairRow(context, event) {
702
+ const a = resolveLeg(context, event.a.metricId);
703
+ if (!a || !resolveLeg(context, event.b.metricId))
704
+ return undefined;
705
+ if (event.rowId)
706
+ return context.rows.find((r) => r.id === event.rowId);
707
+ const seat = legSeat(context, event.a.metricId);
708
+ return ((seat && context.rows.find((r) => r.configs.some((c) => c.id === seat.id))) ??
709
+ rowForSource(context.rows, a.source));
710
+ }
711
+ function pairSeats(context, event) {
712
+ return !!pairRow(context, event);
713
+ }
714
+ /** The column a study takes if one of its params changes — its spec re-encoded.
715
+ * The identity does NOT change with it; this guards column collisions only. */
716
+ const restudyColumn = (study, name, value) => deriveId({ ...study.derive, params: { ...study.derive.params, [name]: value } });
717
+ /**
718
+ * Whether a study's param `name` can move to `value` — shared by the guard and
719
+ * the host, so a refused edit renders **disabled** instead of dead-clicking (the
720
+ * same contract as `linkToggleAllowed` / `swapAllowed`).
721
+ *
722
+ * It has to run the whole propagation, because an edit is refusable for a
723
+ * reason that isn't visible on the study itself: re-speccing it rewrites
724
+ * everything built on it, and one of THOSE can land on a column another config
725
+ * already holds — two lines computing the same thing. Before this was exported,
726
+ * such an edit simply did nothing when clicked, with no way to find out why
727
+ * (PR #140 review, MEDIUM).
728
+ */
729
+ export function respecAllowed(scope, id, name, value) {
730
+ const configs = flatConfigs(scope.rows);
731
+ const target = configs.find((c) => c.id === id);
732
+ if (!target?.derive)
733
+ return false;
734
+ // The op must actually DECLARE this param — a `stdDev` sent to an `sma` is
735
+ // not a narrow edit, it is a spec the registry rejects.
736
+ if (!opParams(target.derive.op).some((p) => p.name === name))
737
+ return false;
738
+ // Bounds and integer-ness come from the REGISTRY, via the spec it would mint,
739
+ // rather than from a `period`-shaped test here. A band's `stdDev` is
740
+ // fractional and legal; the old `Number.isInteger` would have refused every
741
+ // value of it.
742
+ const candidate = {
743
+ ...target.derive,
744
+ params: { ...target.derive.params, [name]: value },
745
+ };
746
+ if (!isValidSpec(candidate))
747
+ return false;
748
+ if (restudyColumn(target, name, value) === target.column)
749
+ return false;
750
+ const next = propagateRespec(configs, id, respecParam(target, name, value), unitOfColumn(scope));
751
+ // A period can't change a unit by itself — but the apply path RECOMPUTES
752
+ // units structurally, so a config whose stored unit had drifted from its spec
753
+ // (a preset written before an op's declared unit changed) moves on the first
754
+ // edit that touches it. Same coherence gate as the lens, or the two paths
755
+ // could disagree about the very thing they now both write (PR #141 review).
756
+ return next !== null && unitsStayCoherent(scope.rows, next);
757
+ }
758
+ // --- fn() = None: the LEG GROUP ----------------------------------------------
759
+ // With no transform a pair has no single line and therefore no single ink, so
760
+ // it stops being one config and becomes TWO — each an ordinary series with its
761
+ // own colour, axis, eye and study pipeline, tied together by `SeriesGroup`.
762
+ // Splitting and re-joining are one edit read in two directions.
763
+ /** A leg's graph input as a seated config would carry it: a raw column has no
764
+ * spec, a derived leg carries its own. */
765
+ const legParts = (leg) => typeof leg === 'string' ? { column: leg } : { column: deriveId(leg), derive: leg };
766
+ /** The colour leg B takes when a pair splits — the first palette key neither
767
+ * leg A nor anything else in the row is already using, so two fresh lines are
768
+ * never the same colour. Falls back to leg A's if the palette is exhausted. */
769
+ function freeColor(row, taken, palette) {
770
+ const used = new Set([taken, ...row.map((c) => c.color)]);
771
+ return palette.find((k) => !used.has(k)) ?? taken;
772
+ }
773
+ function planSplit(scope, pair, row, nextSeq,
774
+ /** ADD path: the pair isn't seated yet, so there is no identity to strand
775
+ * and "both legs already drawn" is a fine outcome — it just groups them. */
776
+ adding = false) {
777
+ const spec = pair.derive;
778
+ if (!spec || !isPairOp(spec.op))
779
+ return null;
780
+ const parts = readPairParts(spec);
781
+ const inputs = spec.inputs ?? [];
782
+ if (!parts || inputs.length !== 2)
783
+ return null;
784
+ // A study built ON the spread has nowhere to point once the spread stops
785
+ // being a single line, so splitting would strand it — configured, computing a
786
+ // column nothing folds. Refuse rather than delete the user's work silently
787
+ // (PR #144 review, MEDIUM).
788
+ if (derivedClosure(flatConfigs(scope.rows), pair.id).size > 1)
789
+ return null;
790
+ const legCols = inputs.map((i) => legParts(i).column);
791
+ // Two legs computing the same thing is a constant, not a pair — and would be
792
+ // one config either way. (`canAddPair` refuses to build one; a persisted
793
+ // preset could still carry it.)
794
+ if (legCols[0] === legCols[1])
795
+ return null;
796
+ const configs = flatConfigs(scope.rows);
797
+ const unitOf = unitOfColumn(scope);
798
+ const plan = { create: [], adopt: [], mints: 0 };
799
+ let seq = nextSeq;
800
+ let pairIdFree = true;
801
+ let refuse = false;
802
+ inputs.forEach((input, i) => {
803
+ const side = i === 0 ? 'A' : 'B';
804
+ const { column, derive } = legParts(input);
805
+ // Adoption looks only in the pair's OWN row: a group whose legs sit in two
806
+ // rows has no single Pair node to render (the panel is per-row), so it
807
+ // would draw as two one-legged pairs.
808
+ const seated = row.find((c) => c.id !== pair.id && c.column === column);
809
+ if (seated) {
810
+ // …and never STEAL a leg from another pair. Two pairs sharing a leg
811
+ // column would leave the first group with one member, which nothing can
812
+ // re-join and nothing can un-group (PR #144 review, HIGH).
813
+ if (seated.group)
814
+ refuse = true;
815
+ else
816
+ plan.adopt.push({ id: seated.id, group: { id: pair.id, side } });
817
+ return;
818
+ }
819
+ // The column is free in this row but taken in ANOTHER — creating here would
820
+ // put two configs on one column, which every dependency walk resolves by.
821
+ if (configs.some((c) => c.id !== pair.id && c.column === column))
822
+ refuse = true;
823
+ const id = pairIdFree ? ((pairIdFree = false), pair.id) : mintId(seq++);
824
+ if (id !== pair.id)
825
+ plan.mints += 1;
826
+ const unit = typeof input === 'string' ? unitOf(input) : specUnit(input, unitOf);
827
+ // A spread arrives UNLINKED because it oscillates; its LEGS do not — they
828
+ // are the raw metrics, and the whole point of drawing both is comparing
829
+ // them, which needs ONE scale. So a created leg is placed like any new
830
+ // metric (`axisForAdd`), and only falls back to its own axis when no side
831
+ // can take its unit. Inheriting the pair's own axis put the two legs of an
832
+ // AAPL/MSFT price compare on two separately-fitted axes — two lines you
833
+ // cannot read against each other, which is the one thing they are for.
834
+ const side2 = axisForAdd(members(row), unit, pair.axis);
835
+ plan.create.push({
836
+ ...pair,
837
+ id,
838
+ column,
839
+ derive,
840
+ axis: side2 ?? pair.axis,
841
+ axisGroup: side2 == null ? id : undefined,
842
+ color: id === pair.id ? pair.color : freeColor(row, pair.color, scope.palette ?? []),
843
+ label: partLabel(scope, parts[i]),
844
+ unit,
845
+ value: null,
846
+ group: { id: pair.id, side },
847
+ });
848
+ });
849
+ // Both legs adopted ⇒ the pair's own config has nothing left to be, and
850
+ // dropping it would take its identity with it. Refuse: there is nothing to
851
+ // split that isn't already drawn.
852
+ return refuse || (!adding && plan.create.length === 0) ? null : plan;
853
+ }
854
+ /** A pointer (selection / expansion) after a re-join: a config the merge
855
+ * ABSORBS is gone, so anything aimed at it must land on the pair it became
856
+ * rather than dangle. */
857
+ /** Every config a `group.remove` takes: both legs and everything layered on
858
+ * them — the same cascade a single remove does, run over the pair. */
859
+ function groupDoomed(rows, groupId) {
860
+ const all = flatConfigs(rows);
861
+ const doomed = new Set();
862
+ for (const m of groupMembers(all, groupId))
863
+ for (const id of derivedClosure(all, m.id))
864
+ doomed.add(id);
865
+ return doomed;
866
+ }
867
+ export const groupMembers = (configs, groupId) => configs
868
+ .filter((c) => c.group?.id === groupId)
869
+ .sort((a, b) => (a.group.side === b.group.side ? 0 : a.group.side === 'A' ? -1 : 1));
870
+ /**
871
+ * Re-join a leg group into one pair — fn() leaving `None`.
872
+ *
873
+ * Each leg contributes the output of its own PIPELINE, not its metric: a study
874
+ * seated on a leg while the pair was split folds INTO the join, which is what
875
+ * "each part is a pipeline, the combined parts are then a final pipeline" means.
876
+ * Those study configs are absorbed (they become nested spec, exactly as a
877
+ * per-leg study from the picker always has been) — the computation is preserved
878
+ * exactly; what it loses is the study's own row and ink.
879
+ *
880
+ * The joined pair keeps **leg A's identity**, so a split/join round-trip returns
881
+ * the ink and axis you started with.
882
+ */
883
+ /**
884
+ * Whether a side's SHARED axis would be left holding two different units — the
885
+ * axis policy, re-checked after an edit that moves units.
886
+ *
887
+ * A lens change is the first edit that can do this: `diff` of two `%` legs
888
+ * reads `%`, its ratio reads unitless, and a study of that spread inherits
889
+ * whatever it now is. Only a side we would BREAK counts — a side already
890
+ * holding mixed units (an old preset, say) is not made worse by this edit, and
891
+ * refusing there would strand the user with no way to change the lens at all.
892
+ */
893
+ function unitsStayCoherent(rows, next) {
894
+ const unitsOn = (configs, side, after) => new Set(configs
895
+ .filter((c) => !c.axisGroup && c.axis === side)
896
+ .map((c) => (after ? (next.get(c.id)?.unit ?? c.unit ?? '') : (c.unit ?? ''))));
897
+ for (const row of rows) {
898
+ for (const side of ['L', 'R']) {
899
+ if (unitsOn(row.configs, side, true).size > 1 && unitsOn(row.configs, side, false).size <= 1)
900
+ return false;
901
+ }
902
+ }
903
+ return true;
904
+ }
905
+ /** Re-spec a study to a new period **in place**. The period is baked into the
906
+ * spec, so the COLUMN moves — the identity stands still, which is what keeps
907
+ * the user's colour, axis, pins, selection and expansion across the edit. */
908
+ function respecParam(study, name, value) {
909
+ const prev = study.derive;
910
+ const derive = { ...prev, params: { ...prev.params, [name]: value } };
911
+ // Swap only the study's OWN trailing ` · OP(params)` on its current label, so a
912
+ // nested study keeps its parent's segment (which `studyConfig` folded into
913
+ // `target.label`) rather than collapsing to the root identity.
914
+ //
915
+ // BOTH halves go through `studyTag`, which is what `studyConfig` wrote the
916
+ // label with. Built by hand off `params.period` the suffix read
917
+ // `BOLLINGER(20)` where the label says `BOLLINGER(20, 2)` — so it matched
918
+ // nothing, `base` fell back to the root identity, and a param edit both
919
+ // dropped `stdDev` and collapsed the parent's pipeline segment. The existing
920
+ // nested-label test never caught it because every op it uses has one param.
921
+ const suffix = ` · ${studyTag(prev)}`;
922
+ const base = study.label.endsWith(suffix)
923
+ ? study.label.slice(0, -suffix.length)
924
+ : (study.family ?? study.label);
925
+ return {
926
+ ...study,
927
+ column: deriveId(derive),
928
+ derive,
929
+ label: `${base} · ${studyTag(derive)}`,
930
+ };
931
+ }
932
+ function propagateRespec(configs, rootId, root, unitOf) {
933
+ const rootCfg = configs.find((c) => c.id === rootId);
934
+ if (!rootCfg?.derive || !root.derive)
935
+ return null;
936
+ if (!isValidSpec(root.derive))
937
+ return null;
938
+ const next = new Map([
939
+ [
940
+ rootId,
941
+ {
942
+ derive: root.derive,
943
+ column: deriveId(root.derive),
944
+ unit: specUnit(root.derive, unitOf),
945
+ label: root.label,
946
+ },
947
+ ],
948
+ ]);
949
+ // Fixpoint: each pass re-points every config at whatever has moved so far. A
950
+ // config can depend on more than one changed source (a pair whose legs both
951
+ // moved), so this can't be a single walk. It settles because a substitution
952
+ // replaces a name with a dependent's CURRENT spec — which may itself still be
953
+ // intermediate, but each pass heals one more level and no name comes back
954
+ // once every level has.
955
+ let settled = false;
956
+ // `substituteInput` walks persisted spec shapes, and a pathological one
957
+ // (`inputs: [null]`, the case `applyDerivedReport` already belts) throws. This
958
+ // runs inside a GUARD, where a throw kills the actor — so it is total, like
959
+ // every other naming call on this path (PR #130 review).
960
+ try {
961
+ for (let pass = 0; pass <= configs.length && !settled; pass++) {
962
+ settled = true;
963
+ for (const c of configs) {
964
+ if (!c.derive)
965
+ continue;
966
+ const before = next.get(c.id)?.derive ?? c.derive;
967
+ let spec = before;
968
+ for (const dep of configs) {
969
+ const moved = dep.id === c.id ? undefined : next.get(dep.id);
970
+ if (!moved || moved.column === dep.column)
971
+ continue;
972
+ spec = substituteInput(spec, dep.column, moved.derive);
973
+ }
974
+ if (spec === before)
975
+ continue;
976
+ if (!isValidSpec(spec))
977
+ return null;
978
+ // The UNIT travels with the spec: a lens change can turn a `%` spread
979
+ // unitless, and a study of that spread reads in whatever its source
980
+ // now does. Recomputed structurally (`specUnit`), never inherited from
981
+ // the stale config, so it is right at any depth.
982
+ next.set(c.id, { derive: spec, column: deriveId(spec), unit: specUnit(spec, unitOf) });
983
+ settled = false;
984
+ }
985
+ }
986
+ }
987
+ catch {
988
+ return null;
989
+ }
990
+ // Out of passes with rewrites still landing: the result would be a graph part
991
+ // way through an edit. Refuse rather than apply it.
992
+ if (!settled)
993
+ return null;
994
+ // One column, one config — including against the configs that did NOT move.
995
+ const columns = configs.map((c) => next.get(c.id)?.column ?? c.column);
996
+ if (new Set(columns).size !== columns.length)
997
+ return null;
998
+ return next;
999
+ }
1000
+ /**
1001
+ * Run a re-spec and write it into the rows — the one apply path, shared by
1002
+ * every edit that rewrites a spec in place (a study's period, a pair's lens).
1003
+ *
1004
+ * Returns the rows UNCHANGED when the propagation refuses, so an action can
1005
+ * never half-apply what its guard proved coherent. Only the fields the edit
1006
+ * actually moves are written: nothing here touches `axis`/`axisGroup`/colour, and
1007
+ * an absent label is not spread (only the root carries one — see
1008
+ * {@link propagateRespec} — and `label: undefined` would blank a chip).
1009
+ */
1010
+ function applyRespec(context, rootId, root) {
1011
+ const rows = context.rows;
1012
+ const next = propagateRespec(flatConfigs(rows), rootId, root, unitOfColumn(context));
1013
+ if (!next)
1014
+ return rows;
1015
+ return rows.map((r) => ({
1016
+ ...r,
1017
+ configs: r.configs.map((c) => {
1018
+ const re = next.get(c.id);
1019
+ return re
1020
+ ? {
1021
+ ...c,
1022
+ derive: re.derive,
1023
+ column: re.column,
1024
+ unit: re.unit,
1025
+ ...(re.label ? { label: re.label } : {}),
1026
+ }
1027
+ : c;
1028
+ }),
1029
+ }));
1030
+ }
1031
+ /** The SHARED-axis members of a row — the unit gate's input. An unlinked
1032
+ * (non-shared) config scales on its own axis and binds no side, so it is
1033
+ * invisible to axis compatibility (it still costs gutter width, which is the
1034
+ * panel's pressure to re-link, not a hard gate). */
1035
+ const members = (configs) => configs.filter((c) => !c.axisGroup).map((c) => ({ unit: c.unit ?? '', axis: c.axis }));
1036
+ /**
1037
+ * Whether `id` can move onto the axis keyed by `axisGroup` (undefined = the
1038
+ * side's shared axis) — the panel's drag, gated exactly like every other
1039
+ * membership change.
1040
+ *
1041
+ * A destination that already carries series must read in the SAME unit: an
1042
+ * axis is one scale, and two units on one scale is the thing the whole axis
1043
+ * policy exists to prevent. An EMPTY destination (or one holding only the
1044
+ * mover) is always fine — that is just the mover keeping its own scale.
1045
+ */
1046
+ export function axisMoveAllowed(configs, id, axisGroup) {
1047
+ const c = configs.find((x) => x.id === id);
1048
+ if (!c)
1049
+ return false;
1050
+ if ((c.axisGroup ?? undefined) === (axisGroup ?? undefined))
1051
+ return false; // already there
1052
+ // The destination is drawn from the MOVER'S SIDE only. An axis id is
1053
+ // side-qualified (`row:side` / `row:side:group`), so the same key on the other
1054
+ // side is a different axis and none of its members belong to this decision.
1055
+ // Testing them was worse than redundant for the SHARED destination, where the
1056
+ // key is `undefined`: both sides' shared members carry it, so one series on
1057
+ // the far side refused every drop onto this side's shared axis — while the
1058
+ // chain toggle allowed the identical move (PR #149 review, MEDIUM).
1059
+ const into = configs.filter((x) => x.id !== id && x.axis === c.axis && (x.axisGroup ?? undefined) === axisGroup);
1060
+ const unit = c.unit ?? '';
1061
+ return into.every((x) => (x.unit ?? '') === unit);
1062
+ }
1063
+ /**
1064
+ * Whether the panel's chain toggle can act on `id` — shared by the guard and the
1065
+ * host (the panel renders a refused toggle disabled). The semantics follow the
1066
+ * icon exactly:
1067
+ *
1068
+ * - **On the side's shared axis** (LINKED, with or without company): unlink to
1069
+ * an own axis — **always allowed**. Alone on the shared axis this is a
1070
+ * visual no-op, but it is not a semantic one: an own axis binds no unit, so
1071
+ * it can always ⇄ to the other side, and a later same-unit arrival joins the
1072
+ * *shared* axis rather than silently merging with it. Refusing it here
1073
+ * stranded a lone member whose far side was occupied — both controls
1074
+ * disabled, no way out but delete-and-re-add (PR #136 review, HIGH).
1075
+ * - **On an own axis** (BLINK): JOIN — allowed only when a same-unit companion
1076
+ * exists on the side, and no different-unit series holds the side's shared
1077
+ * axis (the axis policy, applied at link time). Joining needs something to
1078
+ * join, so a lone series can never bind a FREE side by toggling and a spread
1079
+ * can't accidentally claim a side's unit.
1080
+ */
1081
+ export function linkToggleAllowed(configs, id) {
1082
+ const c = configs.find((x) => x.id === id);
1083
+ if (!c)
1084
+ return false;
1085
+ if (!c.axisGroup)
1086
+ return true; // LINKED → unlink, company or not
1087
+ const side = configs.filter((x) => x.id !== id && x.axis === c.axis);
1088
+ const unit = c.unit ?? '';
1089
+ const shared = side.filter((x) => !x.axisGroup);
1090
+ if (shared.some((x) => (x.unit ?? '') !== unit))
1091
+ return false; // side bound elsewhere
1092
+ return side.some((x) => (x.unit ?? '') === unit); // something to join
1093
+ }
1094
+ /**
1095
+ * Point axis id `to` at whatever `from` held, and vacate `from`. With no
1096
+ * `from`, the destination is a **newly formed** axis and must start clean.
1097
+ *
1098
+ * The invariant every axis operation preserves: **an id's range entry
1099
+ * describes the axis occupying that id now, or there is no entry.** Entries
1100
+ * are otherwise never pruned (a stale id is inert), but membership and side
1101
+ * changes make stale ids live again — so an arriving axis with no pin must
1102
+ * CLEAR its destination rather than inherit whatever scale used to sit there
1103
+ * (PR #133/#135 reviews).
1104
+ */
1105
+ function moveRange(ranges, to, from) {
1106
+ const next = { ...ranges };
1107
+ const entry = from ? next[from] : undefined;
1108
+ if (from)
1109
+ delete next[from];
1110
+ if (entry)
1111
+ next[to] = entry;
1112
+ else
1113
+ delete next[to];
1114
+ return next;
1115
+ }
1116
+ /** The configs sharing ONE axis with `id`: just itself when it is unlinked,
1117
+ * else every shared-axis config on its side. The unit of travel for a
1118
+ * side swap — an axis moves as a scale, not as loose series. */
1119
+ function axisMembers(configs, id) {
1120
+ const c = configs.find((x) => x.id === id);
1121
+ if (!c)
1122
+ return [];
1123
+ return c.axisGroup
1124
+ ? configs.filter((x) => x.axisGroup === c.axisGroup && x.axis === c.axis)
1125
+ : configs.filter((x) => !x.axisGroup && x.axis === c.axis);
1126
+ }
1127
+ /**
1128
+ * Whether the panel's ⇄ can move `id`'s axis to the other side — shared by the
1129
+ * guard and the host (a refused swap renders disabled).
1130
+ *
1131
+ * An UNLINKED axis may always swap: it binds no unit, so it just changes which
1132
+ * gutter it occupies. A SHARED axis may swap only when the other side has **no
1133
+ * shared axis** — otherwise the move would silently merge two scales (possibly
1134
+ * of different units) into one, which is a link operation, and linking has its
1135
+ * own control. Own axes already on the far side never block: they are separate
1136
+ * gutters.
1137
+ */
1138
+ export function swapAllowed(configs, id) {
1139
+ const c = configs.find((x) => x.id === id);
1140
+ if (!c)
1141
+ return false;
1142
+ if (c.axisGroup)
1143
+ return true;
1144
+ const other = c.axis === 'R' ? 'L' : 'R';
1145
+ return !configs.some((x) => !x.axisGroup && x.axis === other);
1146
+ }
1147
+ /** Apply the chain toggle to a row's configs (see {@link linkToggleAllowed} —
1148
+ * the guard has already vetted it). */
1149
+ function toggleLink(configs, id) {
1150
+ const c = configs.find((x) => x.id === id);
1151
+ if (!c)
1152
+ return [...configs];
1153
+ // UNLINK — the LINKED icon always means "leave the shared scale".
1154
+ if (!c.axisGroup)
1155
+ return configs.map((x) => (x.id === id ? { ...x, axisGroup: id } : x));
1156
+ // JOIN. With a shared scale present, the clicked series joins it alone
1157
+ // (other own axes were unlinked deliberately — they stay). With none, every
1158
+ // same-unit lone axis on the side merges into one (the sketch's
1159
+ // two-lone-axes state: clicking a broken chain re-joins them).
1160
+ const side = configs.filter((x) => x.id !== id && x.axis === c.axis);
1161
+ const unit = c.unit ?? '';
1162
+ if (side.some((x) => !x.axisGroup))
1163
+ return configs.map((x) => (x.id === id ? { ...x, axisGroup: undefined } : x));
1164
+ return configs.map((x) => x.axis === c.axis && (x.unit ?? '') === unit && (x.id === id || x.axisGroup)
1165
+ ? { ...x, axisGroup: undefined }
1166
+ : x);
1167
+ }
1168
+ /**
1169
+ * Value-free projection of the rows for deep comparison (live `value` excluded —
1170
+ * it's data, so a ticking quote must not make an applied preset read "custom").
1171
+ *
1172
+ * **The config `id` is excluded on purpose**, even though it is now persisted:
1173
+ * a preset is a *look*, and identity is per-instance bookkeeping. `column`
1174
+ * carries everything the id used to contribute here (it is the computation),
1175
+ * so this comparison means exactly what it meant before the identity split —
1176
+ * whereas folding in a minted counter would make a hand-rebuilt copy of a saved
1177
+ * preset read as "custom" purely because its configs were minted later.
1178
+ */
1179
+ /**
1180
+ * Whether a seated config is a plain metric that could be paired against the
1181
+ * comparison — the bulk gesture's target test. Mirrors the panel's per-row
1182
+ * `canCompare` MINUS the "is there a comparison at all" check, which is
1183
+ * workspace state the terminal cannot see: the caller offers the action only
1184
+ * when a comparison is named.
1185
+ *
1186
+ * Excluded: a hidden series (the gesture says *visible*), a leg already in a
1187
+ * group, a spread, and anything already reading the comparison — each of those
1188
+ * states its symbols already.
1189
+ */
1190
+ function comparableMetric(c) {
1191
+ if (!c.visible || c.group)
1192
+ return false;
1193
+ if (c.derive ? hasPairOp(c.derive) || usesCompare(c.derive) : false)
1194
+ return false;
1195
+ // A multi-output study cannot be a leg (see `canAddPair`), so "Pair all
1196
+ // visible" must not try — it would raise an `addPair` the guard then refuses,
1197
+ // which reads as the button silently skipping things.
1198
+ if (c.derive && opIsMulti(c.derive.op))
1199
+ return false;
1200
+ return !c.column.startsWith(COMPARE_PREFIX);
1201
+ }
1202
+ export function canonRows(rows) {
1203
+ return JSON.stringify(rows.map((r) => {
1204
+ // Axis membership is preset identity — but `axisGroup` is a MINTED config
1205
+ // id, and hashing it would make a hand-rebuilt copy of a saved preset read
1206
+ // as "custom" purely because its configs were minted later: exactly the
1207
+ // trap the `id` exclusion above exists to avoid. So hash the SHAPE. Each
1208
+ // distinct non-shared axis becomes its position in the row, and the shared
1209
+ // axis stays `null`, so "these two share a scale, that one is alone"
1210
+ // compares equal across mints (PR #149 review, LOW).
1211
+ // Both keys below are MINTED ids, so both get slotted, not hashed.
1212
+ const slotter = () => {
1213
+ const keys = [];
1214
+ return (g) => {
1215
+ if (!g)
1216
+ return null;
1217
+ const i = keys.indexOf(g);
1218
+ return i >= 0 ? i : keys.push(g) - 1;
1219
+ };
1220
+ };
1221
+ const axisSlot = slotter();
1222
+ const groupSlot = slotter();
1223
+ return [
1224
+ r.id,
1225
+ r.configs.map((c) => [
1226
+ c.column,
1227
+ c.label,
1228
+ c.color,
1229
+ c.axis,
1230
+ axisSlot(c.axisGroup),
1231
+ c.style,
1232
+ c.window ?? null,
1233
+ c.candleVariant ?? null,
1234
+ c.candleColorBy ?? null,
1235
+ c.visible,
1236
+ c.source ?? null,
1237
+ c.unit ?? null,
1238
+ c.lineWidth ?? null,
1239
+ c.colorMode ?? null,
1240
+ c.riseColor ?? null,
1241
+ c.fallColor ?? null,
1242
+ // A leg group is composition, not decoration: two legs with no join are
1243
+ // a different preset from the same two joined, or from two unrelated
1244
+ // metrics that happen to be seated together.
1245
+ c.group ? [groupSlot(c.group.id), c.group.side, c.group.hidden ?? false] : null,
1246
+ ]),
1247
+ ];
1248
+ }));
1249
+ }
1250
+ /** The active slot: first saved preset whose rows deep-equal the live rows, else
1251
+ * null (custom). The single derivation behind the filled circle + the seed. */
1252
+ export function activeSlot(presets, rows) {
1253
+ const live = canonRows(rows);
1254
+ const i = presets.findIndex((p) => p != null && canonRows(p.rows) === live);
1255
+ return i === -1 ? null : i;
1256
+ }
1257
+ const cloneRows = (rows) => rows.map((r) => ({ ...r, configs: r.configs.map((c) => ({ ...c, value: null })) }));
1258
+ // --- the machine -------------------------------------------------------------
1259
+ export const terminalMachine = setup({
1260
+ types: {
1261
+ context: {},
1262
+ events: {},
1263
+ input: {},
1264
+ },
1265
+ guards: {
1266
+ // A series may be added only if its unit fits a free or matching axis in its
1267
+ // target row (the two-axis policy). That is now the ONLY gate.
1268
+ //
1269
+ // **The add-once rule was dropped on 2026-08-25** (Peter). It refused a second
1270
+ // config reading a column already on the chart, reasoning that "two configs
1271
+ // reading one column are the same line twice" — true while a seated series had
1272
+ // nothing you could change about it. It no longer is: a series carries editable
1273
+ // params (the censor) and an appendable study chain, so a second copy of ATM
1274
+ // Vol 21D is the *starting point* for the comparison you actually want —
1275
+ // censored against uncensored, raw against its own moving average. The rule was
1276
+ // forbidding the reason to do it.
1277
+ //
1278
+ // Nothing downstream assumed uniqueness: a config's `id` is minted and opaque,
1279
+ // and the render, axis policy and study chain all key on it rather than on the
1280
+ // column (`entryColumn` exists precisely because a seated config's id does not
1281
+ // say what it reads).
1282
+ canAdd: ({ context, event }) => {
1283
+ if (event.type !== 'series.add')
1284
+ return false;
1285
+ const entry = context.catalog.find((e) => e.id === event.catalogId);
1286
+ if (!entry)
1287
+ return false;
1288
+ // A row's own `[+] Metric` targets that row (`rowId`); the bare add routes
1289
+ // by source (its row, else an empty row, else the last).
1290
+ const row = event.rowId
1291
+ ? context.rows.find((r) => r.id === event.rowId)
1292
+ : rowForSource(context.rows, entry.source);
1293
+ return !!row && canAddUnit(members(row.configs), entry.unit);
1294
+ },
1295
+ // Row cap (the control-panel spec: 1–3). The UI also gates on "current bottom has
1296
+ // content"; this is the hard invariant.
1297
+ canAddRow: ({ context }) => context.rows.length < MAX_ROWS,
1298
+ // A study may be added if its target exists and the exact spec isn't already
1299
+ // on the chart. One column, one config: a duplicate spec would fold to the
1300
+ // same column, drawing one line twice and making the dependency walks
1301
+ // (which resolve edges by column) ambiguous about which config owns it.
1302
+ canAddStudy: ({ context, event }) => {
1303
+ if (event.type !== 'series.addStudy')
1304
+ return false;
1305
+ const target = flatConfigs(context.rows).find((c) => c.id === event.targetId);
1306
+ if (!target)
1307
+ return false;
1308
+ // The op's bar columns must exist on the target's SOURCE. An ATR on a vol
1309
+ // series names `high`/`low`/`close` that the series does not carry: the
1310
+ // spec is well-formed, the engine rejects it at compile, the fold skips
1311
+ // it, and the config sits in the panel computing silence. The menu hides
1312
+ // such ops (`studyOfferable`), but the picker stays open across picks and
1313
+ // a preset can replay an add, so the machine is where the refusal has to
1314
+ // live — the same move `b544480` made for multi-output targets.
1315
+ if (!studyOfferable(target.source, event.op))
1316
+ return false;
1317
+ // A MULTI-OUTPUT study cannot be a study target. Its `column` is a spec id
1318
+ // naming several columns and none of its own, so `sma(macd(...))` would
1319
+ // read a column that does not exist: the spec is well-formed, `deriveId`
1320
+ // names it happily, and the fold quietly produces nothing — a config
1321
+ // sitting in the panel computing silence, which is the worst failure
1322
+ // shape. Which output such a study should read is a real question the
1323
+ // engine has no way to answer (a MACD's line? its histogram?), so refuse
1324
+ // rather than guess. The `Add ▸ Study` menu hides on these too; this is
1325
+ // the guard that covers the picker, which stays open across picks and
1326
+ // appends to the chain TAIL.
1327
+ if (target.derive && opIsMulti(target.derive.op))
1328
+ return false;
1329
+ // A study takes at most ONE study of its own: a metric may carry several
1330
+ // study CHAINS, but a chain never branches (Peter, 2026-09-12). The panel
1331
+ // reads a chain top-down as a pipeline, and a branch has no reading in
1332
+ // that grammar — two studies of one study are two pipelines claiming the
1333
+ // same middle. Adding from the metric starts a new chain instead, which is
1334
+ // what the metric's own study button does.
1335
+ if (target.derive && hasStudyChild(flatConfigs(context.rows), target))
1336
+ return false;
1337
+ // Gate BEFORE naming: `deriveId` throws on a spec the registry rejects
1338
+ // (out-of-range period, malformed nested input), and a guard that throws
1339
+ // errors the whole actor (PR #130 review, HIGH). The machine is
1340
+ // host-driven — this guard IS the validation.
1341
+ const spec = studySpec(target, event.op, event.period);
1342
+ if (!isValidSpec(spec))
1343
+ return false;
1344
+ const column = deriveId(spec);
1345
+ return !flatConfigs(context.rows).some((c) => c.column === column);
1346
+ },
1347
+ // A pair may be added if both legs exist, differ, and read the SAME data
1348
+ // source — the derive fold runs per series, so both columns must live on
1349
+ // one series (cross-source/cross-entity pairs need the join step; see
1350
+ // Tidal's pairs plan). The spread arrives UNLINKED (its own axis), so there is
1351
+ // no unit gate — only a target row must exist and the exact spec must not
1352
+ // already be on the chart.
1353
+ canAddPair: ({ context, event }) => {
1354
+ if (event.type !== 'series.addPair')
1355
+ return false;
1356
+ const a = resolveLeg(context, event.a.metricId);
1357
+ const b = resolveLeg(context, event.b.metricId);
1358
+ if (!a || !b)
1359
+ return false;
1360
+ if (a.source !== b.source)
1361
+ return false;
1362
+ // A MULTI-OUTPUT study cannot be a pair LEG either, and for the same
1363
+ // reason it cannot be a study target: its column is a spec id naming none
1364
+ // of its own columns, so the spread would read nothing. Refusing here is
1365
+ // what takes `+Compare` off a MACD — the verb was offered and meant
1366
+ // nothing, which is worse than it being absent.
1367
+ if ((a.spec && opIsMulti(a.spec.op)) || (b.spec && opIsMulti(b.spec.op)))
1368
+ return false;
1369
+ // A leg's nested spec can arrive from persisted state, and a study's
1370
+ // period from the picker — gate before naming (throwing guard = dead
1371
+ // actor; PR #130 review).
1372
+ // Name the legs with SOME join — an unjoined pair still has to have two
1373
+ // distinct, valid legs, and `pairSpec` is where that is decided.
1374
+ const spec = pairSpec(a, event.a, b, event.b, event.op === 'none' ? 'diff' : event.op);
1375
+ if (!isValidSpec(spec))
1376
+ return false;
1377
+ // IDENTICAL bound inputs are a constant (ratio 1 / diff 0) — meaningless
1378
+ // whatever the bindings, and two legs drawing one line if unjoined. The
1379
+ // same metric ACROSS roles (or under different studies) differs after
1380
+ // binding, so George's canonical case passes.
1381
+ const name = (i) => (typeof i === 'string' ? i : deriveId(i));
1382
+ if (name(spec.inputs[0]) === name(spec.inputs[1]))
1383
+ return false;
1384
+ // UNJOINED: no spread is ever seated, so the test is whether the two legs
1385
+ // can be — `planAddGroup` answers that (a leg already in another group
1386
+ // refuses, one already drawn is adopted).
1387
+ if (event.op === 'none') {
1388
+ const row = pairRow(context, event);
1389
+ return !!(row && planAddGroup(context, event, row));
1390
+ }
1391
+ if (flatConfigs(context.rows).some((c) => c.column === deriveId(spec)))
1392
+ return false;
1393
+ // …and a row to land on. Delegated to `pairSeats` — which the sibling
1394
+ // assigners already use — so the guard, the rows assigner and the id
1395
+ // counter cannot disagree about where a spread goes (a named row, else
1396
+ // leg A's, else A's source row).
1397
+ return pairSeats(context, event);
1398
+ },
1399
+ // A study's period may change if the target is a study, the period is a
1400
+ // valid bar count (≥2), it actually changes, and the whole PROPAGATED
1401
+ // rewrite is coherent — the target's dependents move with it, so the guard
1402
+ // has to vet the subtree, not just the target's own column.
1403
+ // Delegated to the shared pure helper so the panel's disabled state and the
1404
+ // guard can never disagree. `respecAllowed` is total — it validates every
1405
+ // rewritten spec and returns false rather than throwing — which also covers
1406
+ // the actor-killing hazard `canAddStudy` guards (a throwing guard kills the
1407
+ // actor, and the `>= 2` pre-check does not cover the registry's max).
1408
+ canSetStudyParam: ({ context, event }) => event.type === 'series.setStudyParam' &&
1409
+ respecAllowed(context, event.id, event.name, event.value),
1410
+ // The chain toggle — delegated to the shared pure helper so the panel's
1411
+ // disabled state and the guard can never disagree.
1412
+ canToggleLink: ({ context, event }) => {
1413
+ if (event.type !== 'axis.toggleLink')
1414
+ return false;
1415
+ const row = context.rows.find((r) => r.configs.some((c) => c.id === event.id));
1416
+ return !!row && linkToggleAllowed(row.configs, event.id);
1417
+ },
1418
+ // The ⇄ — delegated to the shared pure helper, like the chain.
1419
+ canMoveAxis: ({ context, event }) => {
1420
+ if (event.type !== 'axis.moveTo')
1421
+ return false;
1422
+ const row = context.rows.find((r) => r.configs.some((c) => c.id === event.id));
1423
+ return !!row && axisMoveAllowed(row.configs, event.id, event.axisGroup);
1424
+ },
1425
+ canSwapSide: ({ context, event }) => {
1426
+ if (event.type !== 'axis.swapSide')
1427
+ return false;
1428
+ const row = context.rows.find((r) => r.configs.some((c) => c.id === event.memberId));
1429
+ return !!row && swapAllowed(row.configs, event.memberId);
1430
+ },
1431
+ // A manual range must be a real, ordered interval (the panel's fields can
1432
+ // transiently hold anything).
1433
+ canSetAxisRange: ({ event }) => event.type === 'axis.setRange' &&
1434
+ Number.isFinite(event.min) &&
1435
+ Number.isFinite(event.max) &&
1436
+ event.min < event.max,
1437
+ // A cross-row move needs the target row to exist, to not already be the
1438
+ // series' row, and to have axes for EVERY travelling config (the series plus
1439
+ // any studies layered on it — each may carry a different unit). Same policy as
1440
+ // Add, folded across the set by `placeOnRow`.
1441
+ canMoveToRow: ({ context, event }) => {
1442
+ if (event.type !== 'series.moveToRow')
1443
+ return false;
1444
+ const from = context.rows.find((r) => r.configs.some((c) => c.id === event.id));
1445
+ const to = context.rows.find((r) => r.id === event.rowId);
1446
+ if (!from || !to || from.id === to.id)
1447
+ return false;
1448
+ const travelling = layeredOn(from.configs, event.id, isCatalogColumn(context));
1449
+ const movers = from.configs.filter((c) => travelling.has(c.id));
1450
+ return placeOnRow(to.configs, movers) !== null;
1451
+ },
1452
+ },
1453
+ actions: {
1454
+ addStudy: assign({
1455
+ rows: ({ context, event }) => {
1456
+ if (event.type !== 'series.addStudy')
1457
+ return context.rows;
1458
+ const target = flatConfigs(context.rows).find((c) => c.id === event.targetId);
1459
+ if (!target)
1460
+ return context.rows;
1461
+ // Every assigner in this `assign` sees the SAME pre-update context, so
1462
+ // the id minted here and the one `expanded`/`cfgSeq` compute below all
1463
+ // agree without threading a value between them.
1464
+ const cfg = studyConfig(target, event.op, event.period, mintId(context.cfgSeq));
1465
+ // Overlay on the target's row (own-row oscillators are a later step),
1466
+ // inserted directly IN FRONT of its target — the list is front→back, so
1467
+ // that's the target's own index. A study must read over its source (see
1468
+ // `studyConfig`); appending would bury it at the very back.
1469
+ return context.rows.map((r) => {
1470
+ const at = r.configs.findIndex((c) => c.id === target.id);
1471
+ return at < 0 ? r : { ...r, configs: reindex([...r.configs, cfg], r.configs.length, at) };
1472
+ });
1473
+ },
1474
+ // Expand the new study so its controls (period, colour) open for tuning.
1475
+ expanded: ({ context, event }) => {
1476
+ if (event.type !== 'series.addStudy')
1477
+ return context.expanded;
1478
+ const target = flatConfigs(context.rows).find((c) => c.id === event.targetId);
1479
+ return target ? mintId(context.cfgSeq) : context.expanded;
1480
+ },
1481
+ cfgSeq: ({ context, event }) => {
1482
+ if (event.type !== 'series.addStudy')
1483
+ return context.cfgSeq;
1484
+ return flatConfigs(context.rows).some((c) => c.id === event.targetId)
1485
+ ? context.cfgSeq + 1
1486
+ : context.cfgSeq;
1487
+ },
1488
+ }),
1489
+ addPair: assign({
1490
+ rows: ({ context, event }) => {
1491
+ if (event.type !== 'series.addPair')
1492
+ return context.rows;
1493
+ const a = resolveLeg(context, event.a.metricId);
1494
+ const b = resolveLeg(context, event.b.metricId);
1495
+ if (!a || !b)
1496
+ return context.rows;
1497
+ // A named row is the user pointing at one (the per-row `+Pair`), so it
1498
+ // beats the leg-A default outright — including its "in front of leg A"
1499
+ // placement, which is a guess about where the spread belongs.
1500
+ const asked = event.rowId ? context.rows.find((r) => r.id === event.rowId) : undefined;
1501
+ // A named row that doesn't exist is a REFUSAL, not a reason to fall
1502
+ // back to leg A's row — `pairSeats` says so, and the two must agree
1503
+ // even where the guard makes it unreachable (PR #142 review, LOW).
1504
+ if (event.rowId && !asked)
1505
+ return context.rows;
1506
+ const seat = asked ? undefined : legSeat(context, event.a.metricId);
1507
+ const seatedAt = seat && context.rows.find((r) => r.configs.some((c) => c.id === seat.id));
1508
+ const row = asked ?? seatedAt ?? rowForSource(context.rows, a.source);
1509
+ if (!row)
1510
+ return context.rows;
1511
+ // UNJOINED: seat the two LEGS, never a spread. `Unjoined` is a
1512
+ // first-class fn() choice (Peter, 2026-08-18), so two lines under one
1513
+ // pair no longer means adding a transform you did not want and taking
1514
+ // it straight off again.
1515
+ if (event.op === 'none') {
1516
+ const plan = planAddGroup(context, event, row);
1517
+ if (!plan)
1518
+ return context.rows;
1519
+ const tag = new Map(plan.adopt.map((x) => [x.id, x.group]));
1520
+ return context.rows.map((r) => ({
1521
+ ...r,
1522
+ configs: (r.id === row.id ? [...plan.create, ...r.configs] : r.configs).map((c) => {
1523
+ const group = tag.get(c.id);
1524
+ return group ? { ...c, group } : c;
1525
+ }),
1526
+ }));
1527
+ }
1528
+ // No axis seating: the spread arrives UNLINKED on its own right-side
1529
+ // axis (pairConfig), binding no unit — the old `axisForAdd` dance (and
1530
+ // its guard/action-agreement hazard, PR #128) retires with it.
1531
+ const cfg = pairConfig(a, event.a, b, event.b, event.op, // 'none' returned above
1532
+ mintId(context.cfgSeq), unitOfColumn(context), context.palette, flatConfigs(context.rows).map((c) => c.color));
1533
+ // In front of leg A when it is seated — the spread is the signal and
1534
+ // must read over its legs (a study's insertion rule). An UNSEATED leg
1535
+ // adds nothing: the spread lands alone at the front of A's source row.
1536
+ if (seatedAt) {
1537
+ return context.rows.map((r) => {
1538
+ const at = r.configs.findIndex((c) => c.id === seat.id);
1539
+ return at < 0
1540
+ ? r
1541
+ : { ...r, configs: reindex([...r.configs, cfg], r.configs.length, at) };
1542
+ });
1543
+ }
1544
+ return context.rows.map((r) => r.id === row.id ? { ...r, configs: [cfg, ...r.configs] } : r);
1545
+ },
1546
+ // Expand the new node so its controls open for tuning — the spread, or
1547
+ // (unjoined) whichever leg took the group's first minted id. Nothing to
1548
+ // expand when BOTH legs were adopted: no config was created.
1549
+ expanded: ({ context, event }) => {
1550
+ if (event.type !== 'series.addPair' || !pairSeats(context, event))
1551
+ return context.expanded;
1552
+ if (event.op !== 'none')
1553
+ return mintId(context.cfgSeq);
1554
+ const row = pairRow(context, event);
1555
+ return planAddGroup(context, event, row)?.create[0]?.id ?? context.expanded;
1556
+ },
1557
+ // A joined add consumes one id. An UNJOINED one consumes the group's key
1558
+ // plus whatever legs it had to create.
1559
+ cfgSeq: ({ context, event }) => {
1560
+ if (event.type !== 'series.addPair' || !pairSeats(context, event))
1561
+ return context.cfgSeq;
1562
+ if (event.op !== 'none')
1563
+ return context.cfgSeq + 1;
1564
+ const row = pairRow(context, event);
1565
+ return context.cfgSeq + 1 + (planAddGroup(context, event, row)?.mints ?? 0);
1566
+ },
1567
+ }),
1568
+ // A period change re-specs the study AND everything built on it — the guard
1569
+ // has already proved the whole rewrite is coherent. Nothing is removed and
1570
+ // no pointer moves: every config keeps its identity, so selection,
1571
+ // expansion, ink, axis membership and range pins all survive (they used to
1572
+ // be destroyed, and the dependents deleted outright).
1573
+ setStudyParam: assign({
1574
+ rows: ({ context, event }) => {
1575
+ if (event.type !== 'series.setStudyParam')
1576
+ return context.rows;
1577
+ const target = flatConfigs(context.rows).find((c) => c.id === event.id);
1578
+ if (!target?.derive)
1579
+ return context.rows;
1580
+ return applyRespec(context, event.id, respecParam(target, event.name, event.value));
1581
+ },
1582
+ }),
1583
+ addSeries: assign({
1584
+ rows: ({ context, event }) => {
1585
+ if (event.type !== 'series.add')
1586
+ return context.rows;
1587
+ const entry = context.catalog.find((e) => e.id === event.catalogId);
1588
+ const row = event.rowId
1589
+ ? context.rows.find((r) => r.id === event.rowId)
1590
+ : rowForSource(context.rows, entry?.source ?? '');
1591
+ if (!entry || !row)
1592
+ return context.rows;
1593
+ const axis = axisForAdd(members(row.configs), entry.unit, entry.axis) ?? entry.axis;
1594
+ const cfg = toConfig(entry, mintId(context.cfgSeq), axis);
1595
+ // A metric may now be added twice (see `canAdd`), and the second copy
1596
+ // would otherwise arrive in the first's colour — two identical lines,
1597
+ // identically labelled, exactly on top of each other, which reads as a
1598
+ // no-op rather than as the thing you just asked for. Take a free palette
1599
+ // key instead, the same rule a splitting pair's leg B follows.
1600
+ if (row.configs.some((c) => c.color === cfg.color)) {
1601
+ cfg.color = freeColor(row.configs, cfg.color, context.palette);
1602
+ }
1603
+ // PREPEND: the list is front→back, so a freshly added metric lands on top
1604
+ // where the user can see what they just asked for (appending would bury it
1605
+ // behind everything already on the row).
1606
+ return context.rows.map((r) => r.id === row.id ? { ...r, configs: [cfg, ...r.configs] } : r);
1607
+ },
1608
+ // Expand the freshly added series so its controls open for immediate
1609
+ // tuning — at its MINTED id, not the catalog id it was added from. This is
1610
+ // a control-panel expansion, not the app selection: the emphasised series
1611
+ // survives the add.
1612
+ expanded: ({ context, event }) => event.type === 'series.add' ? mintId(context.cfgSeq) : null,
1613
+ cfgSeq: ({ context, event }) => event.type === 'series.add' ? context.cfgSeq + 1 : context.cfgSeq,
1614
+ }),
1615
+ toggleGroupVisible: assign({
1616
+ rows: ({ context, event }) => {
1617
+ if (event.type !== 'group.toggleVisible')
1618
+ return context.rows;
1619
+ const members = groupMembers(flatConfigs(context.rows), event.groupId);
1620
+ const hidden = !members.some((m) => m.group?.hidden);
1621
+ return context.rows.map((r) => ({
1622
+ ...r,
1623
+ configs: r.configs.map((c) => c.group?.id === event.groupId ? { ...c, group: { ...c.group, hidden } } : c),
1624
+ }));
1625
+ },
1626
+ }),
1627
+ removeGroup: assign({
1628
+ rows: ({ context, event }) => {
1629
+ if (event.type !== 'group.remove')
1630
+ return context.rows;
1631
+ const doomed = groupDoomed(context.rows, event.groupId);
1632
+ const mapped = context.rows.map((r) => ({
1633
+ ...r,
1634
+ configs: r.configs.filter((c) => !doomed.has(c.id)),
1635
+ }));
1636
+ return mapped.some((r) => r.configs.length === 0) && mapped.length > 1
1637
+ ? mapped.filter((r) => r.configs.length > 0)
1638
+ : mapped;
1639
+ },
1640
+ // The same invariant `removeSeries` states: neither pointer may point at a
1641
+ // removed series. Sibling assigners read the PRE-update context, so both
1642
+ // recompute the doomed set rather than reading the new rows (PR #149
1643
+ // review, LOW).
1644
+ selected: ({ context, event }) => event.type === 'group.remove' &&
1645
+ context.selected != null &&
1646
+ groupDoomed(context.rows, event.groupId).has(context.selected)
1647
+ ? null
1648
+ : context.selected,
1649
+ expanded: ({ context, event }) => event.type === 'group.remove' &&
1650
+ context.expanded != null &&
1651
+ groupDoomed(context.rows, event.groupId).has(context.expanded)
1652
+ ? null
1653
+ : context.expanded,
1654
+ }),
1655
+ moveAxis: assign({
1656
+ rows: ({ context, event }) => {
1657
+ if (event.type !== 'axis.moveTo')
1658
+ return context.rows;
1659
+ return context.rows.map((r) => ({
1660
+ ...r,
1661
+ configs: r.configs.map((c) => c.id === event.id ? { ...c, axisGroup: event.axisGroup } : c),
1662
+ }));
1663
+ },
1664
+ /**
1665
+ * `moveRange`'s invariant, which every other axis op honours: an id's
1666
+ * range entry describes the axis occupying that id NOW, or there is no
1667
+ * entry. This one moves a MEMBER between axes rather than moving an axis,
1668
+ * so it is the two ends that matter, not a single hand-off:
1669
+ *
1670
+ * - the source id is cleaned only if the mover was its LAST member;
1671
+ * - an arriving member joins an EXISTING axis untouched — that axis's pin
1672
+ * is still true of it;
1673
+ * - forming a NEW axis carries the mover's own pin when it vacated one,
1674
+ * and otherwise starts CLEAN, because a stale id going live must never
1675
+ * inherit whatever scale used to sit there (PR #133/#135 reviews).
1676
+ */
1677
+ axisRanges: ({ context, event }) => {
1678
+ if (event.type !== 'axis.moveTo')
1679
+ return context.axisRanges;
1680
+ const row = context.rows.find((r) => r.configs.some((x) => x.id === event.id));
1681
+ const c = row?.configs.find((x) => x.id === event.id);
1682
+ if (!row || !c)
1683
+ return context.axisRanges;
1684
+ const from = configAxisId(row.id, c);
1685
+ const to = configAxisId(row.id, { axis: c.axis, axisGroup: event.axisGroup });
1686
+ if (from === to)
1687
+ return context.axisRanges;
1688
+ const others = row.configs.filter((x) => x.id !== c.id);
1689
+ const sourceKeeps = others.some((x) => configAxisId(row.id, x) === from);
1690
+ const destHas = others.some((x) => configAxisId(row.id, x) === to);
1691
+ const next = { ...context.axisRanges };
1692
+ if (!sourceKeeps)
1693
+ delete next[from];
1694
+ if (!destHas) {
1695
+ const carried = sourceKeeps ? undefined : context.axisRanges[from];
1696
+ if (carried)
1697
+ next[to] = carried;
1698
+ else
1699
+ delete next[to];
1700
+ }
1701
+ return next;
1702
+ },
1703
+ }),
1704
+ removeSeries: assign({
1705
+ rows: ({ context, event }) => {
1706
+ if (event.type !== 'series.remove')
1707
+ return context.rows;
1708
+ // Cascade to dependent studies so a nested study can't strand invisible +
1709
+ // unremovable when its source study is removed.
1710
+ const doomed = derivedClosure(flatConfigs(context.rows), event.id);
1711
+ // Removing one leg of a group leaves the other standing ALONE, which is
1712
+ // no longer a pair — it becomes an ordinary metric rather than a
1713
+ // one-legged group nothing can re-join.
1714
+ const orphaned = new Set(flatConfigs(context.rows)
1715
+ .filter((c) => c.group && doomed.has(c.id))
1716
+ .map((c) => c.group.id));
1717
+ const mapped = context.rows.map((r) => ({
1718
+ ...r,
1719
+ configs: r.configs
1720
+ .filter((c) => !doomed.has(c.id))
1721
+ .map((c) => (c.group && orphaned.has(c.group.id) ? { ...c, group: undefined } : c)),
1722
+ }));
1723
+ // Removing a row's last metric removes the row (the control-panel spec: no empty
1724
+ // rows) — keep at least one.
1725
+ const host = context.rows.find((r) => r.configs.some((c) => c.id === event.id));
1726
+ const hostNow = host && mapped.find((r) => r.id === host.id);
1727
+ return hostNow && hostNow.configs.length === 0 && mapped.length > 1
1728
+ ? mapped.filter((r) => r.id !== host.id)
1729
+ : mapped;
1730
+ },
1731
+ // Neither pointer may point at a removed series (or a cascaded dependent).
1732
+ selected: ({ context, event }) => event.type === 'series.remove' &&
1733
+ context.selected != null &&
1734
+ derivedClosure(flatConfigs(context.rows), event.id).has(context.selected)
1735
+ ? null
1736
+ : context.selected,
1737
+ expanded: ({ context, event }) => event.type === 'series.remove' &&
1738
+ context.expanded != null &&
1739
+ derivedClosure(flatConfigs(context.rows), event.id).has(context.expanded)
1740
+ ? null
1741
+ : context.expanded,
1742
+ }),
1743
+ // Draw order within a row: `order` steps (front/up/down/back) and `reindex`
1744
+ // (a drag's absolute drop). Both splice-move within the series' own row; the
1745
+ // list is front→back, so index 0 is topmost on the canvas.
1746
+ orderSeries: assign({
1747
+ rows: ({ context, event }) => {
1748
+ if (event.type !== 'series.order' && event.type !== 'series.reindex')
1749
+ return context.rows;
1750
+ return context.rows.map((r) => {
1751
+ if (!r.configs.some((c) => c.id === event.id))
1752
+ return r;
1753
+ // Order is over BLOCKS (a metric with its studies) — the unit the
1754
+ // control tree shows and the user therefore aims at. `index` on a
1755
+ // reindex is a block index for the same reason: the panel lists
1756
+ // roots, so the slot the user dropped on IS the block.
1757
+ const blocks = rowBlocks(r.configs);
1758
+ const i = blocks.findIndex((b) => b.some((c) => c.id === event.id));
1759
+ if (i < 0)
1760
+ return r;
1761
+ const to = event.type === 'series.order'
1762
+ ? orderTarget(i, blocks.length, event.to)
1763
+ : Math.max(0, Math.min(event.index, blocks.length - 1));
1764
+ return to === i ? r : { ...r, configs: reindex(blocks, i, to).flat() };
1765
+ });
1766
+ },
1767
+ }),
1768
+ // Cross-row move: the series leaves its row (pruned if that empties it, as
1769
+ // with remove) and lands at the FRONT of the target row, on an axis its unit
1770
+ // can take there (the guard already proved one exists). Studies layered on it
1771
+ // travel with it, so a study can't strand on a row without its source.
1772
+ moveSeriesToRow: assign({
1773
+ rows: ({ context, event }) => {
1774
+ if (event.type !== 'series.moveToRow')
1775
+ return context.rows;
1776
+ const from = context.rows.find((r) => r.configs.some((c) => c.id === event.id));
1777
+ const to = context.rows.find((r) => r.id === event.rowId);
1778
+ if (!from || !to || from.id === to.id)
1779
+ return context.rows;
1780
+ const travelling = layeredOn(from.configs, event.id, isCatalogColumn(context));
1781
+ const moving = from.configs.filter((c) => travelling.has(c.id));
1782
+ const movingIds = new Set(moving.map((c) => c.id));
1783
+ // All-or-nothing placement (the guard already proved it fits; bail rather
1784
+ // than half-move if it somehow doesn't).
1785
+ const placed = placeOnRow(to.configs, moving);
1786
+ if (!placed)
1787
+ return context.rows;
1788
+ const mapped = context.rows.map((r) => {
1789
+ if (r.id === from.id)
1790
+ return { ...r, configs: r.configs.filter((c) => !movingIds.has(c.id)) };
1791
+ if (r.id === to.id)
1792
+ return { ...r, configs: [...placed, ...r.configs] };
1793
+ return r;
1794
+ });
1795
+ // An emptied source row goes away (the control-panel spec: no empty rows) —
1796
+ // keep at least one.
1797
+ const emptied = mapped.find((r) => r.id === from.id && r.configs.length === 0);
1798
+ return emptied && mapped.length > 1 ? mapped.filter((r) => r.id !== from.id) : mapped;
1799
+ },
1800
+ }),
1801
+ patchSeries: assign({
1802
+ rows: ({ context, event }) => event.type === 'series.patch'
1803
+ ? context.rows.map((r) => ({
1804
+ ...r,
1805
+ configs: r.configs.map((c) => (c.id === event.id ? { ...c, ...event.patch } : c)),
1806
+ }))
1807
+ : context.rows,
1808
+ }),
1809
+ toggleVisible: assign({
1810
+ rows: ({ context, event }) => {
1811
+ if (event.type !== 'series.toggleVisible')
1812
+ return context.rows;
1813
+ const target = flatConfigs(context.rows).find((c) => c.id === event.id);
1814
+ if (!target)
1815
+ return context.rows;
1816
+ const next = !target.visible;
1817
+ // Hiding a metric hides what is BUILT ON it (Peter, 2026-09-12): a
1818
+ // `Price · MACD` left drawing over a hidden Price read as the eye not
1819
+ // working. `layeredOn` is the same set a cross-row move carries, which
1820
+ // is the right one — studies only, never a derived catalog metric that
1821
+ // merely happens to read the same column.
1822
+ //
1823
+ // It WRITES each study's `visible` rather than gating on the parent,
1824
+ // and that is the difference that matters: a gate would make the
1825
+ // parent's state final, where the point is that you can then click a
1826
+ // study back on underneath a hidden parent. The cost is that showing a
1827
+ // parent also shows a study you had hidden individually — the opposite
1828
+ // trade from the pair eye, which keeps each leg's own state behind a
1829
+ // separate `group.hidden` flag. A pair's legs are peers; a study is
1830
+ // subordinate, so following its parent is the better default.
1831
+ const row = context.rows.find((r) => r.configs.some((c) => c.id === event.id));
1832
+ const cascade = row
1833
+ ? studiesOn(row.configs, event.id, isCatalogColumn(context))
1834
+ : new Set();
1835
+ return context.rows.map((r) => ({
1836
+ ...r,
1837
+ configs: r.configs.map((c) => (cascade.has(c.id) ? { ...c, visible: next } : c)),
1838
+ }));
1839
+ },
1840
+ // A hidden series can't stay emphasised/expanded — its legend chip is gone,
1841
+ // so nothing could re-select it and the chart would strand others dimmed.
1842
+ // The SAME cascade as `rows`: hiding a metric hides its studies, and a
1843
+ // study that was the selected/expanded one goes with it (#182 re-cut
1844
+ // review, M1 — the pointers used to clear on `event.id` alone, leaving a
1845
+ // hidden study selected and expanded in the panel).
1846
+ selected: ({ context, event }) => event.type === 'series.toggleVisible' && hidesPointer(context, event.id, context.selected)
1847
+ ? null
1848
+ : context.selected,
1849
+ expanded: ({ context, event }) => event.type === 'series.toggleVisible' && hidesPointer(context, event.id, context.expanded)
1850
+ ? null
1851
+ : context.expanded,
1852
+ }),
1853
+ setSelected: assign({
1854
+ selected: ({ event }) => (event.type === 'select' ? event.id : null),
1855
+ }),
1856
+ setExpanded: assign({
1857
+ expanded: ({ event }) => (event.type === 'expand' ? event.id : null),
1858
+ }),
1859
+ openControls: assign({ controlsOpen: true }),
1860
+ // Closing the panel drops the expansion (emphasis falls back to the app
1861
+ // selection) and prunes any empty row left by a "+ Add row" — keep ≥1.
1862
+ closeControls: assign({
1863
+ controlsOpen: false,
1864
+ expanded: null,
1865
+ rows: ({ context }) => {
1866
+ const nonEmpty = context.rows.filter((r) => r.configs.length > 0);
1867
+ return nonEmpty.length ? nonEmpty : context.rows.slice(0, 1);
1868
+ },
1869
+ }),
1870
+ applyPreset: assign({
1871
+ rows: ({ context, event }) => {
1872
+ if (event.type !== 'preset.select')
1873
+ return context.rows;
1874
+ const p = context.presets[event.slot];
1875
+ // A preset saved before the invariant existed can carry a stack with no
1876
+ // remainder row, which would reproduce the stuck-seam bug on apply.
1877
+ return p ? withRemainder(cloneRows(p.rows)) : context.rows;
1878
+ },
1879
+ // The applied rows are a fresh config — neither pointer necessarily survives.
1880
+ selected: null,
1881
+ expanded: null,
1882
+ // A preset restores MINTED ids, so BOTH counters must move above them or
1883
+ // the next add would hand out an id the applied preset already occupies —
1884
+ // two configs (or two rows) sharing one identity. The row counter has the
1885
+ // same hole and it predates the config one (PR #139 review, MEDIUM):
1886
+ // duplicate row ids collide in `setRowHeights`, in `configAxisId`, and in
1887
+ // every find-by-rowId.
1888
+ cfgSeq: ({ context, event }) => {
1889
+ const p = event.type === 'preset.select' ? context.presets[event.slot] : null;
1890
+ return p ? Math.max(context.cfgSeq, cfgSeqAfter(p.rows)) : context.cfgSeq;
1891
+ },
1892
+ rowSeq: ({ context, event }) => {
1893
+ const p = event.type === 'preset.select' ? context.presets[event.slot] : null;
1894
+ return p ? Math.max(context.rowSeq, rowSeqAfter(p.rows)) : context.rowSeq;
1895
+ },
1896
+ // Presets are COMPOSITION; per-axis ranges are ARRANGEMENT and aren't
1897
+ // saved in them (yet — TDL-VIEWS serializes both). Reset rather than
1898
+ // leak: a manual range pinned under different rows reads as a broken
1899
+ // chart with no visible cause. Membership (`axisGroup`) DOES restore — it
1900
+ // lives on the configs.
1901
+ axisRanges: ({ context, event }) => event.type === 'preset.select' && context.presets[event.slot] ? {} : context.axisRanges,
1902
+ }),
1903
+ savePreset: assign({
1904
+ presets: ({ context, event }) => {
1905
+ if (event.type !== 'preset.save')
1906
+ return context.presets;
1907
+ const next = context.presets.slice();
1908
+ next[event.slot] = { rows: cloneRows(context.rows) };
1909
+ context.storage.savePresets(next);
1910
+ return next;
1911
+ },
1912
+ }),
1913
+ setRowHeights: assign({
1914
+ rows: ({ context, event }) => event.type === 'layout.setRowHeights'
1915
+ ? // `withRemainder` because a commit is a full height map: a drag that
1916
+ // gave every row a fixed height would strand the stack with nothing
1917
+ // to absorb slack, which is the state the seam gets stuck in.
1918
+ withRemainder(context.rows.map((r) => ({ ...r, height: event.heights[r.id] ?? r.height })))
1919
+ : context.rows,
1920
+ }),
1921
+ addRow: assign({
1922
+ rows: ({ context }) => withRemainder([
1923
+ ...context.rows,
1924
+ { id: mintRowId(context.rowSeq), height: NEW_ROW_HEIGHT, configs: [] },
1925
+ ]),
1926
+ rowSeq: ({ context }) => context.rowSeq + 1,
1927
+ }),
1928
+ toggleAxisLink: assign({
1929
+ rows: ({ context, event }) => event.type === 'axis.toggleLink'
1930
+ ? context.rows.map((r) => r.configs.some((c) => c.id === event.id)
1931
+ ? { ...r, configs: toggleLink(r.configs, event.id) }
1932
+ : r)
1933
+ : context.rows,
1934
+ // Membership changes which axis ids EXIST, so the pins follow (see
1935
+ // `moveRange`'s invariant).
1936
+ axisRanges: ({ context, event }) => {
1937
+ if (event.type !== 'axis.toggleLink')
1938
+ return context.axisRanges;
1939
+ const row = context.rows.find((r) => r.configs.some((c) => c.id === event.id));
1940
+ const c = row?.configs.find((x) => x.id === event.id);
1941
+ if (!row || !c)
1942
+ return context.axisRanges;
1943
+ const sharedId = sharedAxisId(row.id, c.axis);
1944
+ const ownId = seriesAxisId(row.id, c.axis, c.id);
1945
+ const sideShared = row.configs.filter((x) => x.id !== c.id && !x.axisGroup && x.axis === c.axis);
1946
+ if (!c.axisGroup) {
1947
+ // UNLINK. Alone, the shared axis CEASES — same single-member scale,
1948
+ // new id, so its pin travels. With company it persists and keeps
1949
+ // its pin, while the fresh own axis starts clean.
1950
+ return moveRange(context.axisRanges, ownId, sideShared.length ? undefined : sharedId);
1951
+ }
1952
+ // JOIN. This own axis ceases; its pin does not follow — it is joining
1953
+ // a scale that owns its own range.
1954
+ const next = { ...context.axisRanges };
1955
+ delete next[ownId];
1956
+ if (sideShared.length === 0) {
1957
+ // A MERGE forms a new shared scale here out of the same-unit lone
1958
+ // axes: every one of them ceases, and the destination starts clean.
1959
+ for (const x of row.configs)
1960
+ if (x.axisGroup && x.axis === c.axis && (x.unit ?? '') === (c.unit ?? ''))
1961
+ delete next[seriesAxisId(row.id, x.axis, x.id)];
1962
+ delete next[sharedId];
1963
+ }
1964
+ return next;
1965
+ },
1966
+ }),
1967
+ // ⇄: the whole axis changes side — every member flips together, so the
1968
+ // scale keeps its membership and only its gutter moves.
1969
+ swapAxisSide: assign({
1970
+ rows: ({ context, event }) => {
1971
+ if (event.type !== 'axis.swapSide')
1972
+ return context.rows;
1973
+ const row = context.rows.find((r) => r.configs.some((c) => c.id === event.memberId));
1974
+ if (!row)
1975
+ return context.rows;
1976
+ const moving = new Set(axisMembers(row.configs, event.memberId).map((c) => c.id));
1977
+ return context.rows.map((r) => r.id !== row.id
1978
+ ? r
1979
+ : {
1980
+ ...r,
1981
+ configs: r.configs.map((c) => moving.has(c.id) ? { ...c, axis: c.axis === 'R' ? 'L' : 'R' } : c),
1982
+ });
1983
+ },
1984
+ // The axis id embeds the side, so a swap RE-KEYS the range state — a
1985
+ // pin belongs to the scale, not to the gutter it happens to occupy.
1986
+ axisRanges: ({ context, event }) => {
1987
+ if (event.type !== 'axis.swapSide')
1988
+ return context.axisRanges;
1989
+ const row = context.rows.find((r) => r.configs.some((c) => c.id === event.memberId));
1990
+ const member = row?.configs.find((c) => c.id === event.memberId);
1991
+ if (!row || !member)
1992
+ return context.axisRanges;
1993
+ const from = configAxisId(row.id, member);
1994
+ const to = configAxisId(row.id, { ...member, axis: member.axis === 'R' ? 'L' : 'R' });
1995
+ // BOTH ends move, always — see `moveRange`'s invariant (an arriving
1996
+ // axis with no pin CLEARS its destination rather than inheriting a
1997
+ // stale one; PR #135 review, MEDIUM).
1998
+ return moveRange(context.axisRanges, to, from);
1999
+ },
2000
+ }),
2001
+ setAxisRange: assign({
2002
+ axisRanges: ({ context, event }) => event.type === 'axis.setRange'
2003
+ ? {
2004
+ ...context.axisRanges,
2005
+ [event.axisId]: {
2006
+ // CARRY THE LOCKS. A pin sets the manual range; it does not
2007
+ // repeal the axis's hard limits. Rebuilding the entry from
2008
+ // scratch here silently dropped a bar's zero floor on the first
2009
+ // gesture, so the floor held for exactly one wheel notch and
2010
+ // drifted from then on.
2011
+ ...context.axisRanges[event.axisId],
2012
+ mode: 'manual',
2013
+ min: event.min,
2014
+ max: event.max,
2015
+ unit: event.unit,
2016
+ },
2017
+ }
2018
+ : context.axisRanges,
2019
+ }),
2020
+ // Hard bound locks. Replacement semantics (see the event): the pair given
2021
+ // IS the axis's locks afterwards. Returns the SAME map when nothing changed,
2022
+ // because the host re-seeds these from a membership signature and an
2023
+ // identity change there would loop the memoized chart.
2024
+ setAxisLocks: assign({
2025
+ axisRanges: ({ context, event }) => {
2026
+ if (event.type !== 'axis.setLocks')
2027
+ return context.axisRanges;
2028
+ const cur = context.axisRanges[event.axisId];
2029
+ if (cur?.lockMin === event.lockMin && cur?.lockMax === event.lockMax)
2030
+ return context.axisRanges;
2031
+ const next = {
2032
+ mode: cur?.mode ?? 'auto',
2033
+ min: cur?.min,
2034
+ max: cur?.max,
2035
+ unit: cur?.unit ?? event.unit,
2036
+ lockMin: event.lockMin,
2037
+ lockMax: event.lockMax,
2038
+ autoBasis: cur?.autoBasis,
2039
+ centerZero: cur?.centerZero,
2040
+ precision: cur?.precision,
2041
+ scaleType: cur?.scaleType,
2042
+ };
2043
+ // An entry holding neither a lock nor a pin nor a memory says nothing —
2044
+ // drop it rather than accumulate empties keyed by every axis ever seen.
2045
+ if (axisRangeIsEmpty(next)) {
2046
+ if (!cur)
2047
+ return context.axisRanges;
2048
+ const { [event.axisId]: _drop, ...rest } = context.axisRanges;
2049
+ return rest;
2050
+ }
2051
+ return { ...context.axisRanges, [event.axisId]: next };
2052
+ },
2053
+ }),
2054
+ setAxisAutoOpts: assign({
2055
+ axisRanges: ({ context, event }) => {
2056
+ if (event.type !== 'axis.setAutoOpts')
2057
+ return context.axisRanges;
2058
+ const cur = context.axisRanges[event.axisId];
2059
+ // Store only what differs from the defaults, so an untouched axis keeps
2060
+ // no entry at all and a preset round-trips to the same shape.
2061
+ const autoBasis = event.autoBasis === 'metric' ? 'metric' : undefined;
2062
+ const centerZero = event.centerZero ? true : undefined;
2063
+ if (cur?.autoBasis === autoBasis && cur?.centerZero === centerZero)
2064
+ return context.axisRanges;
2065
+ const next = {
2066
+ mode: cur?.mode ?? 'auto',
2067
+ min: cur?.min,
2068
+ max: cur?.max,
2069
+ unit: cur?.unit ?? event.unit,
2070
+ lockMin: cur?.lockMin,
2071
+ lockMax: cur?.lockMax,
2072
+ autoBasis,
2073
+ centerZero,
2074
+ precision: cur?.precision,
2075
+ scaleType: cur?.scaleType,
2076
+ };
2077
+ if (axisRangeIsEmpty(next)) {
2078
+ if (!cur)
2079
+ return context.axisRanges;
2080
+ const { [event.axisId]: _drop, ...rest } = context.axisRanges;
2081
+ return rest;
2082
+ }
2083
+ return { ...context.axisRanges, [event.axisId]: next };
2084
+ },
2085
+ }),
2086
+ setAxisFormat: assign({
2087
+ axisRanges: ({ context, event }) => {
2088
+ if (event.type !== 'axis.setFormat')
2089
+ return context.axisRanges;
2090
+ const cur = context.axisRanges[event.axisId];
2091
+ // Clamp to the offered 0–4, and refuse anything that is not one of them:
2092
+ // `NaN` used to pass the clamp untouched and reach
2093
+ // `Intl.NumberFormat({ maximumFractionDigits: NaN })`, which throws (PR
2094
+ // #173 review).
2095
+ const precision = event.precision === undefined || !Number.isInteger(event.precision)
2096
+ ? undefined
2097
+ : Math.max(0, Math.min(4, event.precision));
2098
+ const scaleType = event.scaleType === 'log' ? 'log' : undefined;
2099
+ // Belt and braces behind the panel's own guard, using the SAME rule the
2100
+ // panel greys the control with — a log axis cannot reach zero, so never
2101
+ // store the pair even if something asks for it.
2102
+ const scale = logAllowed(cur)[0] ? scaleType : undefined;
2103
+ if (cur?.precision === precision && cur?.scaleType === scale)
2104
+ return context.axisRanges;
2105
+ const next = {
2106
+ mode: cur?.mode ?? 'auto',
2107
+ min: cur?.min,
2108
+ max: cur?.max,
2109
+ unit: cur?.unit ?? event.unit,
2110
+ lockMin: cur?.lockMin,
2111
+ lockMax: cur?.lockMax,
2112
+ autoBasis: cur?.autoBasis,
2113
+ centerZero: cur?.centerZero,
2114
+ precision,
2115
+ scaleType: scale,
2116
+ };
2117
+ if (axisRangeIsEmpty(next)) {
2118
+ if (!cur)
2119
+ return context.axisRanges;
2120
+ const { [event.axisId]: _drop, ...rest } = context.axisRanges;
2121
+ return rest;
2122
+ }
2123
+ return { ...context.axisRanges, [event.axisId]: next };
2124
+ },
2125
+ }),
2126
+ // Back to auto KEEPS the values (the preserved-manual memory) — a later
2127
+ // re-manual restores them. A never-touched axis has no entry to flip.
2128
+ setAxisAuto: assign({
2129
+ axisRanges: ({ context, event }) => {
2130
+ if (event.type !== 'axis.setAuto')
2131
+ return context.axisRanges;
2132
+ const cur = context.axisRanges[event.axisId];
2133
+ if (!cur || cur.mode === 'auto')
2134
+ return context.axisRanges;
2135
+ return { ...context.axisRanges, [event.axisId]: { ...cur, mode: 'auto' } };
2136
+ },
2137
+ }),
2138
+ removeRow: assign({
2139
+ rows: ({ context, event }) => event.type === 'row.remove' && context.rows.length > 1
2140
+ ? // Removing the remainder row would leave the stack with none, so the
2141
+ // first survivor takes over as the one that absorbs slack.
2142
+ withRemainder(context.rows.filter((r) => r.id !== event.id))
2143
+ : context.rows,
2144
+ // Removing a row drops its series for good, so a pointer into it can't return
2145
+ // (unlike a ticker switch) — clear both (mirrors removeSeries).
2146
+ selected: ({ context, event }) => {
2147
+ if (event.type !== 'row.remove' || context.rows.length <= 1)
2148
+ return context.selected;
2149
+ const row = context.rows.find((r) => r.id === event.id);
2150
+ return row?.configs.some((c) => c.id === context.selected) ? null : context.selected;
2151
+ },
2152
+ expanded: ({ context, event }) => {
2153
+ if (event.type !== 'row.remove' || context.rows.length <= 1)
2154
+ return context.expanded;
2155
+ const row = context.rows.find((r) => r.id === event.id);
2156
+ return row?.configs.some((c) => c.id === context.expanded) ? null : context.expanded;
2157
+ },
2158
+ }),
2159
+ },
2160
+ }).createMachine({
2161
+ id: 'terminal',
2162
+ context: ({ input }) => ({
2163
+ // Seeded rows go through the invariant too. The host builds them (and on a
2164
+ // reload re-seeds from the stored ACTIVE preset), so a blob written before
2165
+ // `withRemainder` existed — or any future host that forgets — would boot
2166
+ // straight into the stuck-seam state rather than being healed on first edit.
2167
+ rows: withRemainder(input.initialRows),
2168
+ palette: input.palette ?? [],
2169
+ axisRanges: {},
2170
+ rowSeq: input.initialRows.length,
2171
+ cfgSeq: cfgSeqAfter(input.initialRows),
2172
+ selected: null,
2173
+ expanded: null,
2174
+ controlsOpen: false,
2175
+ presets: input.storage.loadPresets(),
2176
+ catalog: input.catalog,
2177
+ storage: input.storage,
2178
+ }),
2179
+ on: {
2180
+ 'series.add': { guard: 'canAdd', actions: 'addSeries' },
2181
+ 'series.addStudy': { guard: 'canAddStudy', actions: 'addStudy' },
2182
+ 'series.addPair': { guard: 'canAddPair', actions: 'addPair' },
2183
+ 'series.compareAll': {
2184
+ actions: enqueueActions(({ context, enqueue }) => {
2185
+ // Targets are read from the context as it stands NOW, before any add
2186
+ // lands — "pair all visible" means the metrics visible when you asked.
2187
+ for (const row of context.rows) {
2188
+ for (const c of row.configs) {
2189
+ if (!comparableMetric(c))
2190
+ continue;
2191
+ enqueue.raise({
2192
+ type: 'series.addPair',
2193
+ a: { metricId: c.id, entity: 'primary' },
2194
+ b: { metricId: c.id, entity: 'compare' },
2195
+ op: 'none',
2196
+ rowId: row.id,
2197
+ });
2198
+ }
2199
+ }
2200
+ }),
2201
+ },
2202
+ 'series.setStudyParam': { guard: 'canSetStudyParam', actions: 'setStudyParam' },
2203
+ 'series.order': { actions: 'orderSeries' },
2204
+ 'series.reindex': { actions: 'orderSeries' },
2205
+ 'series.moveToRow': { guard: 'canMoveToRow', actions: 'moveSeriesToRow' },
2206
+ 'series.remove': { actions: 'removeSeries' },
2207
+ 'series.patch': { actions: 'patchSeries' },
2208
+ 'series.toggleVisible': { actions: 'toggleVisible' },
2209
+ 'group.toggleVisible': { actions: 'toggleGroupVisible' },
2210
+ 'group.remove': { actions: 'removeGroup' },
2211
+ select: { actions: 'setSelected' },
2212
+ expand: { actions: 'setExpanded' },
2213
+ 'controls.open': { actions: 'openControls' },
2214
+ 'controls.close': { actions: 'closeControls' },
2215
+ 'preset.select': { actions: 'applyPreset' },
2216
+ 'preset.save': { actions: 'savePreset' },
2217
+ 'layout.setRowHeights': { actions: 'setRowHeights' },
2218
+ 'row.add': { guard: 'canAddRow', actions: 'addRow' },
2219
+ 'row.remove': { actions: 'removeRow' },
2220
+ 'axis.toggleLink': { guard: 'canToggleLink', actions: 'toggleAxisLink' },
2221
+ 'axis.swapSide': { guard: 'canSwapSide', actions: 'swapAxisSide' },
2222
+ 'axis.moveTo': { guard: 'canMoveAxis', actions: 'moveAxis' },
2223
+ 'axis.setLocks': { actions: 'setAxisLocks' },
2224
+ 'axis.setAutoOpts': { actions: 'setAxisAutoOpts' },
2225
+ 'axis.setFormat': { actions: 'setAxisFormat' },
2226
+ 'axis.setRange': { guard: 'canSetAxisRange', actions: 'setAxisRange' },
2227
+ 'axis.setAuto': { actions: 'setAxisAuto' },
2228
+ },
2229
+ });