@tidal-ts/core 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.
package/dist/derive.js ADDED
@@ -0,0 +1,740 @@
1
+ import { ADOPTED_STUDIES, BAND_OUTPUTS, catalogOp, OWN_AXIS_STUDIES, studyNeedsColumns, } from './studyCatalog.js';
2
+ import { bollinger, ema, sma } from '@pond-ts/financial';
3
+ import { bind, columnsOf, createRegistry, int, num, run, specId, explain, } from '@pond-ts/process';
4
+ /**
5
+ * Column prefix for the **compare role's** columns when the host joins the
6
+ * comparison ticker's series onto the primary (role-bound pair legs,
7
+ * TDL-PAIR stage 1): `cmp_iv21` is "the compare ticker's iv21". A ROLE, not
8
+ * an identity — the column keeps its name when the compare ticker changes,
9
+ * so a spread's id (and the user's overrides on it) survive the swap. This
10
+ * is the consumer-side stand-in for per-input source qualification
11
+ * (PND-PROCJOIN — position 5 on pond#543).
12
+ */
13
+ export const COMPARE_PREFIX = 'cmp_';
14
+ /** True if `op` takes a second input. */
15
+ export const isPairOp = (op) => op === 'diff' || op === 'ratio' || op === 'logRatio';
16
+ /** The default bar-count period a study uses when none is given. */
17
+ export const DEFAULT_PERIOD = 20;
18
+ /**
19
+ * A numeric column off a series by name, or `undefined` if it has none —
20
+ * pond's **columnar** read path (`series.column(name)`), which walks the packed
21
+ * typed array instead of materializing an object per bar. Prefer this to
22
+ * `toObjects()` for any per-bar fold (pond 0.52 made the same change inside its
23
+ * own study kernels; the guidance is "columns, not events").
24
+ */
25
+ export function readNumericColumn(series, name) {
26
+ // `column()` is schema-narrowed; Tidal renders in the erased schema, so reach it
27
+ // structurally (same trust boundary as the study-op casts below).
28
+ const s = series;
29
+ return s.column(name);
30
+ }
31
+ /** Trading days per year — the standard annualization for a daily variance. */
32
+ const ANNUALIZATION_DAYS = 252;
33
+ /** A corpus study (`sma`/`ema`) as a process op body: run the financial study
34
+ * over the op's (already-widened) series, then hand back the one column it
35
+ * wrote. Cast through `never`: Tidal computes in the erased schema, the
36
+ * corpus is column-name-typed over a concrete one. */
37
+ function corpusStudy(fn) {
38
+ return (ctx) => {
39
+ // No missing-column pre-check: since 0.62.0 the engine rejects an unknown
40
+ // raw input at COMPILE (`UnknownColumnError`, whole spec closure, re-run
41
+ // on the warm path too), so a gone-column spec skips before this op ever
42
+ // runs — the workaround this check was (pond#666 → #667) retired with the
43
+ // bump.
44
+ const out = fn(ctx.series, {
45
+ period: ctx.params.period,
46
+ column: ctx.inputs.input,
47
+ output: '__study',
48
+ });
49
+ const col = out.column('__study');
50
+ if (!col)
51
+ throw new Error(`${ctx.id}: corpus study produced no column`);
52
+ return col;
53
+ };
54
+ }
55
+ /** The output suffixes a band declares, in declaration order — also the order
56
+ * {@link bollingerRun} returns its columns in. Defined in `studyCatalog.ts`
57
+ * (the lower layer) so the adoption filter and the band style read ONE list;
58
+ * re-exported here because this is where consumers already import it from. */
59
+ export { BAND_OUTPUTS };
60
+ /** A private prefix for the corpus call: we read the three columns straight
61
+ * back out and hand them to the engine, which names the real ones from the
62
+ * spec id. Anything unlikely to collide with a feed column will do. */
63
+ const BB_PREFIX = '__bb';
64
+ /** **Bollinger Bands** — the corpus's `bollinger` (one rolling avg+stdev pass),
65
+ * surfaced as a THREE-output op. The engine names the columns `${id}Middle` /
66
+ * `Upper` / `Lower` from the suffixes declared below, which is the corpus's own
67
+ * `prefix` convention, so no mapping layer sits between them.
68
+ *
69
+ * Returned in {@link BAND_OUTPUTS} order — positional, per `OpResult`. */
70
+ function bollingerRun(ctx) {
71
+ const out = bollinger(ctx.series, {
72
+ period: ctx.params.period,
73
+ stdDev: ctx.params.stdDev,
74
+ column: ctx.inputs.input,
75
+ prefix: BB_PREFIX,
76
+ });
77
+ const read = out;
78
+ return BAND_OUTPUTS.map((suffix) => {
79
+ const col = read.column(`${BB_PREFIX}${suffix}`);
80
+ if (!col)
81
+ throw new Error(`${ctx.id}: bollinger produced no ${suffix} column`);
82
+ return col;
83
+ });
84
+ }
85
+ /** Annualized realized volatility from a **daily variance** column: √(var·252),
86
+ * scaled to a percent. Pointwise (no window); a non-finite or negative input
87
+ * reads as a gap, and the RESULT is guarded finite too (a huge-but-finite
88
+ * variance can overflow — that cell becomes a gap, not a dropped column). */
89
+ function realizedVolRun(ctx) {
90
+ const col = readNumericColumn(ctx.series, ctx.inputs.input);
91
+ if (!col)
92
+ throw new Error(`realizedVol: no such column "${ctx.inputs.input}"`);
93
+ const values = new Array(col.length);
94
+ for (let i = 0; i < col.length; i += 1) {
95
+ const v = col.read(i);
96
+ if (v == null || !Number.isFinite(v) || v < 0)
97
+ continue; // gap / negative → gap
98
+ const rv = Math.sqrt(v * ANNUALIZATION_DAYS) * 100;
99
+ if (Number.isFinite(rv))
100
+ values[i] = rv;
101
+ }
102
+ return values;
103
+ }
104
+ /** A pointwise pair transform: `output[i] = a[i] op b[i]`. Gap rules per op —
105
+ * a gap in either leg is a gap; `ratio` gaps on a zero denominator; `logRatio`
106
+ * gaps unless both legs are positive. Result guarded finite, like
107
+ * `realizedVol`. */
108
+ const pairRun = (op) => (ctx) => {
109
+ const colA = readNumericColumn(ctx.series, ctx.inputs.a);
110
+ const colB = readNumericColumn(ctx.series, ctx.inputs.b);
111
+ if (!colA || !colB)
112
+ throw new Error(`${op}: missing column "${!colA ? ctx.inputs.a : ctx.inputs.b}"`);
113
+ const n = Math.min(colA.length, colB.length);
114
+ const values = new Array(colA.length);
115
+ for (let i = 0; i < n; i += 1) {
116
+ const va = colA.read(i);
117
+ const vb = colB.read(i);
118
+ if (va == null || vb == null || !Number.isFinite(va) || !Number.isFinite(vb))
119
+ continue;
120
+ let v;
121
+ if (op === 'diff')
122
+ v = va - vb;
123
+ else if (op === 'ratio') {
124
+ if (vb === 0)
125
+ continue;
126
+ v = va / vb;
127
+ }
128
+ else {
129
+ if (va <= 0 || vb <= 0)
130
+ continue;
131
+ v = Math.log(va / vb);
132
+ }
133
+ if (Number.isFinite(v))
134
+ values[i] = v;
135
+ }
136
+ return values;
137
+ };
138
+ /** The study period's legal range — the SINGLE source both the registry param
139
+ * and every gate (machine guards, the UI period input) read, so no caller can
140
+ * mint a spec the registry will reject (`specId` THROWS on out-of-range
141
+ * params — an ungated value killed the terminal actor; PR #130 review). */
142
+ export const PERIOD_BOUNDS = { min: 2, max: 5000 };
143
+ /** The study period param, shared by the windowed ops. `suggest` is the
144
+ * picker's useful range. */
145
+ const PERIOD = int({ default: DEFAULT_PERIOD, ...PERIOD_BOUNDS, suggest: [5, 200] });
146
+ /** Band half-width in standard deviations. `num`, not `int` — 2.5 is an
147
+ * ordinary choice, and the corpus takes a float. `0` would collapse the bands
148
+ * onto the middle, so the legal floor is above it; the useful range is the
149
+ * 1–3 every chartist actually picks. */
150
+ const STD_DEV = num({ default: 2, min: 0.1, max: 10, suggest: [1, 3] });
151
+ /**
152
+ * Tidal's op vocabulary as a **process registry** — the single declaration the
153
+ * engine validates against, `specId` names from, `explain` derives lineage
154
+ * from, and (TDL-STUDYMENU) a picker will be generated from. Locally defined
155
+ * ops are citizens, per the RFC; the pair ops are the multi-input workload
156
+ * posted as position 5 on pond#543.
157
+ *
158
+ * Unit notes: `ratio` is unitless (`''`), `logRatio` is `'log'`. `diff`
159
+ * declares `'inherit'`, which reads input 0 unconditionally — WRONG when the
160
+ * legs' units differ, which is exactly the `'inheritCommon'` ask in position 2
161
+ * on pond#543. Until that lands the graph's unit answer for an unlike-unit
162
+ * diff is untrusted: the CONFIG layer computes the displayed unit itself
163
+ * (`pairConfig`: a like-unit diff keeps the unit, anything else reads `''`).
164
+ */
165
+ // `folds: false`: the standard folds (last/extremes/percentileRank/shape) stay
166
+ // out until Tidal consumes facts (TDL-GAUGE) — the registry IS the future study
167
+ // menu (`byFamily()`), and it should list exactly what the product exposes.
168
+ const HAND_OPS = createRegistry({ folds: false })
169
+ .define({
170
+ name: 'sma',
171
+ family: 'trend',
172
+ summary: 'Simple moving average',
173
+ params: { period: PERIOD },
174
+ inputs: [{ role: 'input' }],
175
+ outputs: [{ id: '', unit: 'inherit' }],
176
+ lookback: (p) => p.period - 1,
177
+ label: (p, inputs) => `SMA(${p.period}) of ${inputs}`,
178
+ run: corpusStudy(sma),
179
+ })
180
+ .define({
181
+ name: 'ema',
182
+ family: 'trend',
183
+ summary: 'Exponential moving average',
184
+ params: { period: PERIOD },
185
+ inputs: [{ role: 'input' }],
186
+ outputs: [{ id: '', unit: 'inherit' }],
187
+ // An IIR has no exact finite warm-up; 4·period is the standard engineering
188
+ // answer (and the multiplier is OUR claim about acceptable error).
189
+ lookback: (p) => 4 * p.period,
190
+ label: (p, inputs) => `EMA(${p.period}) of ${inputs}`,
191
+ run: corpusStudy(ema),
192
+ })
193
+ .define({
194
+ name: 'bollinger',
195
+ family: 'trend',
196
+ summary: 'Bollinger Bands — an SMA with bands at ±k standard deviations',
197
+ params: { period: PERIOD, stdDev: STD_DEV },
198
+ inputs: [{ role: 'input' }],
199
+ // THREE outputs, one spec. The suffixes name the columns off the spec id,
200
+ // so the band moves, hides, recolours and deletes as a unit — which is what
201
+ // it is. `inherit` throughout: a band is in its input's unit.
202
+ outputs: BAND_OUTPUTS.map((id) => ({ id, unit: 'inherit' })),
203
+ // Same finite window as SMA — the middle band IS an SMA, and the stdev is
204
+ // taken over the same bars.
205
+ lookback: (p) => p.period - 1,
206
+ label: (p, inputs) => `BB(${p.period}, ${p.stdDev}) of ${inputs}`,
207
+ run: bollingerRun,
208
+ })
209
+ .define({
210
+ name: 'realizedVol',
211
+ family: 'volatility',
212
+ summary: 'Annualized realized vol from a daily variance: √(var·252), in percent',
213
+ params: {},
214
+ inputs: [{ role: 'input' }],
215
+ outputs: [{ id: '', unit: '%' }],
216
+ lookback: () => 0,
217
+ label: (_p, inputs) => `Realized vol of ${inputs}`,
218
+ run: realizedVolRun,
219
+ })
220
+ .define({
221
+ name: 'diff',
222
+ family: 'pair',
223
+ summary: 'A − B, pointwise',
224
+ params: {},
225
+ inputs: [{ role: 'a' }, { role: 'b' }],
226
+ outputs: [{ id: '', unit: 'inherit' }],
227
+ lookback: () => 0,
228
+ label: (_p, inputs) => `Spread of ${inputs}`,
229
+ run: pairRun('diff'),
230
+ })
231
+ .define({
232
+ name: 'ratio',
233
+ family: 'pair',
234
+ summary: 'A / B, pointwise (gaps on a zero denominator)',
235
+ params: {},
236
+ inputs: [{ role: 'a' }, { role: 'b' }],
237
+ outputs: [{ id: '', unit: '' }],
238
+ lookback: () => 0,
239
+ label: (_p, inputs) => `Ratio of ${inputs}`,
240
+ run: pairRun('ratio'),
241
+ })
242
+ .define({
243
+ name: 'logRatio',
244
+ family: 'pair',
245
+ summary: 'log(A / B), pointwise (gaps unless both legs are positive)',
246
+ params: {},
247
+ inputs: [{ role: 'a' }, { role: 'b' }],
248
+ outputs: [{ id: '', unit: 'log' }],
249
+ lookback: () => 0,
250
+ label: (_p, inputs) => `Log ratio of ${inputs}`,
251
+ run: pairRun('logRatio'),
252
+ });
253
+ /**
254
+ * Tidal's op vocabulary: the hand-declared ops above, then **the corpus**,
255
+ * folded in from `@pond-ts/financial`'s runtime catalog rather than transcribed
256
+ * (F-charts-25, asked for and delivered).
257
+ *
258
+ * `ADOPTED_STUDIES` is narrow on purpose. A study that reaches this registry
259
+ * reaches the picker, the param controls, the labels and band detection — all
260
+ * of which generate themselves from here — so the filter is the only gate, and
261
+ * `adoptable` says why for each exclusion. TDL-STUDYCAT.
262
+ */
263
+ export const TIDAL_OPS = ADOPTED_STUDIES.reduce((reg, d) => reg.define(catalogOp(d)), HAND_OPS);
264
+ /** The prefix the engine puts on the id of a spec that FAILS validation
265
+ * (`specId` under `validate: false`, 0.62.0) — a valid spec's id is
266
+ * byte-identical to the strict form, so nothing persisted moves. Treat ids as
267
+ * opaque otherwise; this prefix is the one sanctioned peek (the cheap
268
+ * "compilable?" test, and 4b's broken-chip discriminator). */
269
+ const BROKEN_ID_PREFIX = 'p1?:';
270
+ /** True if an id names a spec the registry REJECTS (bad params, wrong shape —
271
+ * a persisted-garbage spec). Such a spec can never fold, anywhere — distinct
272
+ * from a valid spec whose column merely isn't in the current feed. */
273
+ export const isBrokenId = (id) => id.startsWith(BROKEN_ID_PREFIX);
274
+ /**
275
+ * Deterministic id / output-column name for a spec — the engine's
276
+ * content-addressed `specId` (`p1:op(inputs;params)`: versioned, params
277
+ * defaulted + key-sorted, separators escaped, nested inputs inlined by their
278
+ * own id). It doubles as the chart theme id, tracker label key, and selection
279
+ * id (every role `SeriesConfig.id` plays), and it is a stable **persisted**
280
+ * key: a preset spec and a freshly composed one land on the same identity by
281
+ * construction.
282
+ *
283
+ * TOTAL since 0.62.0 (`validate: false`): a spec the registry rejects gets a
284
+ * distinct `p1?:`-prefixed id (type-preserving param encoding) instead of a
285
+ * throw — a broken persisted spec can no longer name (and key onto) the
286
+ * working node, and naming never kills a caller (the old guard-totality
287
+ * hazard). Validity itself is {@link isValidSpec}.
288
+ */
289
+ export function deriveId(spec) {
290
+ return specId(TIDAL_OPS, spec, { validate: false });
291
+ }
292
+ /** Human lineage for a spec, derived from the registry (`explain`) — never
293
+ * hand-built, so `ema(sma(x))` keeps its inner study. The `TDL-LINEAGE`
294
+ * sub-line reads this. */
295
+ export function deriveLineage(spec) {
296
+ return explain(TIDAL_OPS, spec);
297
+ }
298
+ /** The **column names** a spec's top-level inputs resolve to: a string input
299
+ * is a raw column, a nested spec's column is its id. The machine's dependency
300
+ * walks (removal closure, travel sets) match configs against these. */
301
+ export function inputNames(spec) {
302
+ // `?? []`: persisted state is untyped at this boundary — an old-shape spec
303
+ // (pre-`inputs`) must degrade to "no edges", never a TypeError mid-render.
304
+ return (spec.inputs ?? []).map((i) => (typeof i === 'string' ? i : deriveId(i)));
305
+ }
306
+ /**
307
+ * Rewrite every reference to the column `from`, at any depth, to `to` — the
308
+ * substitution behind **edit propagation**: when a config's spec changes, the
309
+ * column it publishes moves, and everything built on it must be re-pointed at
310
+ * the new computation rather than left naming a column that no longer folds.
311
+ *
312
+ * Both ways a spec can name another are handled: a raw string input, and a
313
+ * NESTED spec (composition nests, so a seated dependent carries a copy of its
314
+ * source's spec — matched by its id, which is that source's column).
315
+ *
316
+ * Returns the SAME object when nothing matched, so callers can use identity as
317
+ * a cheap "did this change" test.
318
+ */
319
+ export function substituteInput(spec, from, to) {
320
+ let changed = false;
321
+ const inputs = (spec.inputs ?? []).map((i) => {
322
+ if (typeof i === 'string') {
323
+ if (i !== from)
324
+ return i;
325
+ changed = true;
326
+ return to;
327
+ }
328
+ if (deriveId(i) === from) {
329
+ changed = true;
330
+ return to;
331
+ }
332
+ const sub = substituteInput(i, from, to);
333
+ if (sub !== i)
334
+ changed = true;
335
+ return sub;
336
+ });
337
+ return changed ? { ...spec, inputs } : spec;
338
+ }
339
+ /**
340
+ * True if the registry accepts this spec — the op exists, the shape is sound,
341
+ * and every param is in range. Since 0.62.0 this reads the lenient id's
342
+ * `p1?:` marker ({@link deriveId} is total), so it can never throw — but the
343
+ * machine's guards still gate on it before ACTING: an invalid spec must be
344
+ * refused, not seated (the try/catch stays as a belt for pathological
345
+ * persisted shapes the totality claim was never made about).
346
+ */
347
+ export function isValidSpec(spec) {
348
+ try {
349
+ return !isBrokenId(deriveId(spec));
350
+ }
351
+ catch {
352
+ return false;
353
+ }
354
+ }
355
+ /**
356
+ * True if the value is a readable spec node — an object naming an op.
357
+ *
358
+ * **Every reader below is TOTAL over persisted state**, and this is how. A spec
359
+ * arrives from localStorage with no shape validation (`storedConfig` spreads it
360
+ * straight through), so `inputs: [null]`, a missing `inputs`, and a non-object
361
+ * where a node should be are all reachable. These readers run inside XState
362
+ * GUARDS, where a throw kills the whole terminal actor — the hazard
363
+ * `propagateRespec` belts with a try/catch (PR #130 review, and again in #141
364
+ * for the readers that run *before* it).
365
+ */
366
+ function isSpecLike(i) {
367
+ return typeof i === 'object' && i !== null && typeof i.op === 'string';
368
+ }
369
+ /**
370
+ * True if a spec is, or is built on, a **pair** — the test for "this series
371
+ * states its own symbols".
372
+ *
373
+ * A pair names a symbol per leg, so the blanket compare counterpart (a dashed
374
+ * second copy of every series on the comparison symbol) is meaningless for it:
375
+ * `A − B` on the primary does not imply you wanted `A − B` on the comparison —
376
+ * that is a different pair, and the grammar says to ask for it as one. Recursive
377
+ * because a STUDY of a spread inherits the same argument (Peter, 2026-08-18).
378
+ */
379
+ export function hasPairOp(spec) {
380
+ if (!isSpecLike(spec))
381
+ return false;
382
+ return (isPairOp(spec.op) ||
383
+ (spec.inputs ?? []).some((i) => typeof i !== 'string' && hasPairOp(i)));
384
+ }
385
+ /** True if any input (recursively) reads a compare-role column — the host
386
+ * must join the comparison series on before folding such a spec. */
387
+ export function usesCompare(spec) {
388
+ if (!isSpecLike(spec))
389
+ return false;
390
+ return (spec.inputs ?? []).some((i) => typeof i === 'string' ? i.startsWith(COMPARE_PREFIX) : usesCompare(i));
391
+ }
392
+ /** Strip the compare rebind from an input's leaves — the inverse of the host's
393
+ * `underCompare`, used to name a leg independently of the role it reads. */
394
+ function unCompare(input) {
395
+ if (typeof input === 'string')
396
+ return input.startsWith(COMPARE_PREFIX) ? input.slice(COMPARE_PREFIX.length) : input;
397
+ if (!isSpecLike(input))
398
+ return input; // pathological persisted node — leave it
399
+ return { ...input, inputs: (input.inputs ?? []).map(unCompare) };
400
+ }
401
+ /**
402
+ * Decompose one pair leg into metric + binding + study chain, or **null** when
403
+ * the leg isn't that shape — a leg can be any graph input, including a nested
404
+ * PAIR (a spread of spreads is legal: `resolveLeg` accepts a seated spread).
405
+ * Such a leg has no single metric to name, so the panel degrades to rendering
406
+ * it flat rather than inventing a decomposition.
407
+ *
408
+ * "Study" here means a WINDOWED op ({@link opHasPeriod}) — the same
409
+ * discriminator the config layer uses (`isStudySeries`). A single-input op with
410
+ * no period (`realizedVol`) is a derived METRIC and terminates the walk, so
411
+ * `RV · SMA(20)` reads as one metric with one study rather than two studies.
412
+ */
413
+ export function readPart(input) {
414
+ const studies = [];
415
+ let cur = input;
416
+ while (isSpecLike(cur) && opHasPeriod(cur.op)) {
417
+ const inputs = cur.inputs ?? [];
418
+ if (inputs.length !== 1)
419
+ return null; // windowed but multi-input: not a chain
420
+ studies.unshift({ op: cur.op, params: cur.params });
421
+ cur = inputs[0];
422
+ }
423
+ // Anything that isn't a plain column or a single-input metric node has no
424
+ // name to give: a nested pair, the wrong arity, or a pathological persisted
425
+ // node (`null`). Refuse rather than guess — or throw.
426
+ if (typeof cur !== 'string') {
427
+ if (!isSpecLike(cur) || isPairOp(cur.op) || (cur.inputs ?? []).length !== 1)
428
+ return null;
429
+ }
430
+ const bare = unCompare(cur);
431
+ const compare = typeof cur === 'string' ? cur !== bare : usesCompare(cur);
432
+ return {
433
+ metric: cur,
434
+ base: typeof bare === 'string' ? bare : deriveId(bare),
435
+ entity: compare ? 'compare' : 'primary',
436
+ studies,
437
+ };
438
+ }
439
+ /**
440
+ * How a part's study prints — `SMA(20)`.
441
+ *
442
+ * An OMITTED period is the default, not an absent one: `deriveId` defaults and
443
+ * key-sorts params, so `sma(x)` and `sma(x;period=20)` are one identity. Printed
444
+ * naively that spec read `SMA(undefined)` (PR #141 review, LOW). One helper so
445
+ * the pair's label and the panel's part row can't spell it differently.
446
+ */
447
+ export const partStudyLabel = (st) =>
448
+ // `studyTag`, which reads the op's DECLARED params in order and defaults each
449
+ // — so a band leg reads `BOLLINGER(20, 2)`. Hand-built off `params.period` it
450
+ // read `BOLLINGER(20)`, and two bands differing only in `stdDev` produced
451
+ // identical leg rows (PR #181 review, HIGH).
452
+ studyTag({ op: st.op, inputs: [], params: st.params });
453
+ /** A pair spec's two legs as parts, or **null** if this isn't a pair op or
454
+ * either leg doesn't decompose. Pairs are strictly binary, so anything else
455
+ * is a shape we didn't write. */
456
+ export function readPairParts(spec) {
457
+ if (!isSpecLike(spec) || !isPairOp(spec.op))
458
+ return null;
459
+ const inputs = spec.inputs ?? [];
460
+ if (inputs.length !== 2)
461
+ return null;
462
+ const a = readPart(inputs[0]);
463
+ const b = readPart(inputs[1]);
464
+ return a && b ? [a, b] : null;
465
+ }
466
+ /**
467
+ * The unit a spec's output reads in, from the registry's own declaration —
468
+ * `unitOf` resolves a RAW column's unit (the host's catalog).
469
+ *
470
+ * `'inherit'` is resolved as **inheritCommon**: the shared unit of the inputs,
471
+ * else unitless. That distinction only bites on a pair — `diff` declares
472
+ * `inherit` and the engine reads input 0 unconditionally, which is wrong for
473
+ * unlike legs (`%` − `$` is not `%`). Computing it here is the local stand-in
474
+ * for the `inheritCommon` ask on pond#543 position 2; when the engine gains it
475
+ * this collapses to reading the graph's answer.
476
+ */
477
+ export function specUnit(spec, unitOf) {
478
+ if (!isSpecLike(spec))
479
+ return ''; // total over persisted garbage — see isSpecLike
480
+ const declared = TIDAL_OPS.describe().find((d) => d.name === spec.op)?.outputs?.[0]?.unit;
481
+ if (declared == null)
482
+ return '';
483
+ if (declared !== 'inherit')
484
+ return declared;
485
+ const units = (spec.inputs ?? []).map((i) => typeof i === 'string' ? unitOf(i) : specUnit(i, unitOf));
486
+ const first = units[0];
487
+ return first != null && units.every((u) => u === first) ? first : '';
488
+ }
489
+ /**
490
+ * Fold a set of derive specs onto a series, appending each spec's output
491
+ * column (`deriveId(spec)`) and REPORTING what didn't fold — `bind` + `run`
492
+ * over {@link TIDAL_OPS} with `onError: 'skip'`: a spec that can't resolve
493
+ * (unknown column, bad params — a preset can reference a column that no
494
+ * longer exists) is skipped rather than thrown, its dependents skip with it,
495
+ * and each lands in `skipped` exactly once (the engine reports a failing spec
496
+ * per pass — plan + selector — so entries dedupe on the spec's id). Since
497
+ * 0.62.0 nothing is pre-filtered: broken specs flow through and report, which
498
+ * is what the chip UI reads (Tidal's pairs plan, the ghost-spread debt).
499
+ * Duplicate specs in the set are one node by content-addressing. Pure +
500
+ * deterministic (memo-friendly).
501
+ *
502
+ * Deliberately a **cold bind per fold** for now — same cost shape as the local
503
+ * fold it replaced, kept simple while semantics settle. The warm long-lived
504
+ * graph (a `Host` keyed by source, `setSourceFrom` on live appends, ranged
505
+ * recompute) is the follow-up where the engine's caching starts paying.
506
+ */
507
+ export function applyDerivedReport(series, specs, units) {
508
+ if (specs.length === 0)
509
+ return { series, skipped: [] };
510
+ // NOT idempotent over an already-folded series: an output column that
511
+ // already exists collides at assembly, that spec skips, and any spec
512
+ // NESTING it skips with it (pinned by test). No render path refolds today
513
+ // (sources are raw/joined); the warm-Host stage binds raw sources only,
514
+ // which retires the hazard. Fold RAW series.
515
+ const graph = bind(series, { registry: TIDAL_OPS, units });
516
+ const result = run(graph, {
517
+ plan: [...specs],
518
+ select: specs.map((s) => ({ on: s })),
519
+ onError: 'skip',
520
+ });
521
+ const skipped = new Map();
522
+ for (const s of result.skipped) {
523
+ // The plan pass echoes `spec`; the selector pass carries it as the
524
+ // select's `on`. Either names the same node — the id dedupes the pair.
525
+ const spec = (s.spec ?? s.select?.on);
526
+ if (!spec)
527
+ continue;
528
+ // BELT: even lenient `specId` still TypeErrors on pathological persisted
529
+ // shapes (`params: null`, `inputs: [null]`) that the ENGINE itself
530
+ // survives under skip — naming the report entry must not out-crash the
531
+ // fold it reports on (PR #133 review, MEDIUM). Such a shape gets a
532
+ // synthetic broken-prefixed key; identical echoes still dedupe. (Known
533
+ // upstream wrinkle, reported: the PLAN pass normalizes `params: null` to
534
+ // `{}` in its echo, so that shape's entry can key onto the DEFAULTED
535
+ // spec's valid id — inert until chip states consume `skipped`.)
536
+ let id;
537
+ try {
538
+ id = deriveId(spec);
539
+ }
540
+ catch {
541
+ id = `${BROKEN_ID_PREFIX}${JSON.stringify(spec) ?? 'unnameable'}`;
542
+ }
543
+ if (!skipped.has(id))
544
+ skipped.set(id, { id, code: s.code, reason: s.reason });
545
+ }
546
+ return { series: result.series ?? series, skipped: [...skipped.values()] };
547
+ }
548
+ /** {@link applyDerivedReport} without the report — the fold most render paths
549
+ * want (the chart's column-absence handling is the render half of the skip
550
+ * contract). */
551
+ export function applyDerived(series, specs, units) {
552
+ return applyDerivedReport(series, specs, units).series;
553
+ }
554
+ /** Whether an op declares a `period` param — i.e. whether it is WINDOWED, and
555
+ * so whether a study of it should carry one. Stamping `{period}` onto an op
556
+ * that declares no params mints a spec the registry rejects, and the machine's
557
+ * guard then refuses the add with no feedback (PR #137 review, MEDIUM). */
558
+ export function opHasPeriod(op) {
559
+ return TIDAL_OPS.describe().some((d) => d.name === op && 'period' in d.params);
560
+ }
561
+ /**
562
+ * An op's numeric params, in declaration order.
563
+ *
564
+ * The registry is the single source of truth for what a study can be tuned by
565
+ * — `sma` has one param, a band has two — so anything that offers those knobs
566
+ * reads them from here. Non-numeric params (none today) are skipped rather
567
+ * than coerced.
568
+ */
569
+ export function opParams(op) {
570
+ const def = TIDAL_OPS.describe().find((d) => d.name === op);
571
+ if (!def)
572
+ return [];
573
+ const out = [];
574
+ for (const [name, p] of Object.entries(def.params)) {
575
+ if (p.kind !== 'number' && p.kind !== 'integer')
576
+ continue;
577
+ out.push({
578
+ name,
579
+ kind: p.kind,
580
+ default: p.default,
581
+ ...(p.min === undefined ? {} : { min: p.min }),
582
+ ...(p.max === undefined ? {} : { max: p.max }),
583
+ ...(p.suggest === undefined ? {} : { suggest: p.suggest }),
584
+ });
585
+ }
586
+ return out;
587
+ }
588
+ /**
589
+ * How a study names itself — the op, then the params it was actually tuned
590
+ * with, in the registry's declared order: `SMA(20)`, `BOLLINGER(20, 2)`.
591
+ *
592
+ * Read off the spec against the registry rather than off a known field, so a
593
+ * study with a second param cannot lose half its name to a reader that only
594
+ * knew about `period`.
595
+ */
596
+ export function studyTag(spec) {
597
+ const vals = opParams(spec.op).map((p) => spec.params?.[p.name] ?? p.default);
598
+ return vals.length === 0 ? spec.op.toUpperCase() : `${spec.op.toUpperCase()}(${vals.join(', ')})`;
599
+ }
600
+ /**
601
+ * Whether a study of this op may draw on its SOURCE's axis.
602
+ *
603
+ * Pond's rule, shipped with the catalog's `unit` field: only `'inherit'` may
604
+ * share. A study that reads in its own units needs its own scale, or it
605
+ * stretches the axis it landed on — an RSI (0..100) beside a vol reading (~20)
606
+ * is the case that made this visible.
607
+ *
608
+ * The hand-declared ops answer from the registry (`sma`/`ema`/`bollinger` are
609
+ * `inherit` and do share); the corpus answers from the catalog, because the
610
+ * registry holds a TRANSLATED unit in which `delta` reads as `inherit` — it
611
+ * formats like its source but must not sit on its axis.
612
+ */
613
+ export function opSharesSourceAxis(op) {
614
+ if (OWN_AXIS_STUDIES.has(op))
615
+ return false;
616
+ const def = TIDAL_OPS.describe().find((d) => d.name === op);
617
+ return (def?.outputs ?? []).every((o) => o.unit === 'inherit');
618
+ }
619
+ /**
620
+ * An op's declared input ROLES, in declaration order — what a spec's `inputs`
621
+ * array must line up with positionally.
622
+ *
623
+ * `[{ role: 'column' }]` for a study of one column, which is what composes (an
624
+ * SMA of an SMA nests). A multi-input study names bar columns instead
625
+ * (`high`/`low`/`close`), because it is a study of a SERIES rather than of a
626
+ * column, and its `default` is the column to bind.
627
+ */
628
+ export function opInputs(op) {
629
+ // From the CATALOG, not the registry: `@pond-ts/process`'s `InputDef` is
630
+ // `{ role, unit? }` and has nowhere to carry a default, so `catalogOp` cannot
631
+ // round-trip one. Reading the registry back gave every role
632
+ // `default: undefined`, which bound an ATR's `high` to nothing and threw
633
+ // inside `specId` — caught by the fold test, which is exactly what it is for.
634
+ const d = ADOPTED_STUDIES.find((x) => x.name === op);
635
+ if (d) {
636
+ return d.inputs.map((i) => ({
637
+ role: i.role,
638
+ ...(typeof i.default === 'string' ? { default: i.default } : {}),
639
+ }));
640
+ }
641
+ const def = TIDAL_OPS.describe().find((x) => x.name === op);
642
+ return (def?.inputs ?? []).map((i) => ({ role: i.role }));
643
+ }
644
+ /**
645
+ * Input roles that bind to the study's TARGET rather than to a bar column.
646
+ *
647
+ * Two spellings for one idea: the corpus calls it `column` and Tidal's
648
+ * hand-declared ops call it `input`. Everything else names the bar column it
649
+ * wants (`high`, `low`, `close`, `volume`), and a multi-input study has no
650
+ * target role at all — an ATR is of a SERIES, not of a column.
651
+ */
652
+ export const TARGET_ROLES = new Set(['column', 'input']);
653
+ /**
654
+ * The raw bar columns a study of this op needs beyond its target's own column
655
+ * — empty for a single-column study.
656
+ *
657
+ * The picker asks this to decide whether an op is offerable on a given series:
658
+ * only the PRICE series carries bars, so an ATR is offerable there and not on a
659
+ * vol series, where `high` names nothing and the fold would skip the spec.
660
+ */
661
+ export function opNeedsColumns(op) {
662
+ const d = ADOPTED_STUDIES.find((x) => x.name === op);
663
+ if (d)
664
+ return studyNeedsColumns(d);
665
+ // Hand-declared ops: their roles are `input`/`a`/`b`, bound by the caller.
666
+ return [];
667
+ }
668
+ /**
669
+ * An op's declared output SUFFIXES, in declaration order — the engine names one
670
+ * column per entry off the spec id, and a runner returns them in this order.
671
+ *
672
+ * `['']` for a single-output op, whose column IS the id. More than one entry
673
+ * makes the config's `column` a PREFIX rather than a readable column, which is
674
+ * the thing every data scanner has to go through `configColumns` for.
675
+ */
676
+ export function opOutputs(op) {
677
+ const def = TIDAL_OPS.describe().find((d) => d.name === op);
678
+ // `suffix` on the way OUT, `id` on the way in: `define`'s `OutputDef` calls it
679
+ // `id` and `describe`'s descriptor renames it `suffix`. Nothing read the field
680
+ // until now — `specUnit` reads `unit` and `opIsBand` read `length` — so the
681
+ // divergence surfaced here first.
682
+ if (!def)
683
+ return [''];
684
+ return def.outputs.map((o) => o.suffix);
685
+ }
686
+ /**
687
+ * Whether an op's outputs are a BAND — the exact `Middle`/`Upper`/`Lower`
688
+ * triple, in any order.
689
+ *
690
+ * This was "more than one output", which was true only while a band was the
691
+ * only wide mark Tidal could draw. It is not any more: a MACD is three outputs
692
+ * and no band, and `bandColumns` would have looked for a `…Middle` column that
693
+ * does not exist. The shape is the test, and it agrees with the adoption
694
+ * filter's by reading the same {@link BAND_OUTPUTS} list.
695
+ */
696
+ export function opIsBand(op) {
697
+ const ids = opOutputs(op);
698
+ return ids.length === BAND_OUTPUTS.length && BAND_OUTPUTS.every((b) => ids.includes(b));
699
+ }
700
+ /** Whether an op produces SEVERAL columns that are not a band — drawn as N
701
+ * lines off one spec (`style: 'lines'`), one per declared output. */
702
+ export function opIsMulti(op) {
703
+ return opOutputs(op).length > 1 && !opIsBand(op);
704
+ }
705
+ /** `sma` → `SMA`; `realizedVol` → `Realized vol`. Acronym-ish short names go
706
+ * upper, longer camelCase names read as a sentence. */
707
+ function opLabel(name) {
708
+ if (name.length <= 4 && name === name.toLowerCase())
709
+ return name.toUpperCase();
710
+ const spaced = name.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();
711
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
712
+ }
713
+ /**
714
+ * The ops offerable as a **study** of one series: every single-input,
715
+ * column-producing op in {@link TIDAL_OPS}. Generated from the registry's own
716
+ * descriptors (`describe()`), which is the point of declaring a vocabulary —
717
+ * the picker's names, groups and descriptions cannot drift from what the
718
+ * engine will actually run (`TDL-STUDYMENU`).
719
+ *
720
+ * Pair ops are excluded by arity (they take two inputs and are built through
721
+ * the pair picker instead). NOTE: the registry cannot yet declare what UNIT an
722
+ * input expects, so a domain transform like `realizedVol` (which wants a
723
+ * variance) is offered on any series — see the unit-expectation ask logged in
724
+ * CHARTS_FRICTION.
725
+ */
726
+ export function studyCatalog() {
727
+ return (TIDAL_OPS.describe()
728
+ // Arity used to be the discriminator ("one input ⇒ a study"), which stopped
729
+ // working the moment a study could read high/low/close. The PAIR ops are
730
+ // what this excludes, and they are excluded by being pair ops — they take
731
+ // two SUBJECTS and are built through the pair picker, where a multi-input
732
+ // study takes one subject and several of its columns.
733
+ .filter((d) => d.kind === 'op' && !isPairOp(d.name))
734
+ .map((d) => ({
735
+ op: d.name,
736
+ label: opLabel(d.name),
737
+ summary: d.summary,
738
+ family: d.family,
739
+ })));
740
+ }