@tidal-ts/terminal 0.2.1 → 0.3.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.
@@ -181,7 +181,7 @@ export type TerminalEvent = {
181
181
  | {
182
182
  type: 'series.patch';
183
183
  id: string;
184
- patch: Partial<Omit<SeriesConfig, 'axis' | 'axisGroup'>>;
184
+ patch: Partial<Omit<SeriesConfig, 'axis' | 'axisGroup' | 'parentIds'>>;
185
185
  } | {
186
186
  type: 'series.toggleVisible';
187
187
  id: string;
@@ -410,8 +410,10 @@ export declare function columnLabel(scope: EditScope, column: string): string;
410
410
  *
411
411
  * It has to run the whole propagation, because an edit is refusable for a
412
412
  * reason that isn't visible on the study itself: re-speccing it rewrites
413
- * everything built on it, and one of THOSE can land on a column another config
414
- * already holds — two lines computing the same thing. Before this was exported,
413
+ * everything built on it, and one of THOSE rewrites can be a spec the registry
414
+ * rejects, or move a unit incoherently. (Landing on a column another config
415
+ * already computes used to be a reason too; it is not since `TDL-CMPDUP` — two
416
+ * configs may compute the same thing.) Before this was exported,
415
417
  * such an edit simply did nothing when clicked, with no way to find out why
416
418
  * (PR #140 review, MEDIUM).
417
419
  */
@@ -503,7 +505,7 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
503
505
  } | {
504
506
  type: "series.patch";
505
507
  id: string;
506
- patch: Partial<Omit<SeriesConfig, "axis" | "axisGroup">>;
508
+ patch: Partial<Omit<SeriesConfig, "axis" | "axisGroup" | "parentIds">>;
507
509
  } | {
508
510
  type: "series.toggleVisible";
509
511
  id: string;
@@ -1,5 +1,5 @@
1
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';
2
+ import { COMPARE_PREFIX, hasPairOp, usesCompare, deriveId, opParams, opInputs, opNeedsColumns, opIsBand, opIsMulti, TARGET_ROLES, opSharesSourceAxis, studyTag, inputNames, isPickedInput, isPairOp, isValidSpec, partStudyLabel, readPairParts, specUnit, studyInputOf, substituteInput, } from '@tidal-ts/core';
3
3
  /**
4
4
  * The bar columns each data SOURCE carries — the one fact that decides whether a
5
5
  * multi-column study is offerable on a series. Only the price series has bars;
@@ -31,7 +31,7 @@ function hidesPointer(context, toggledId, pointer) {
31
31
  : new Set([toggledId]);
32
32
  return cascade.has(pointer);
33
33
  }
34
- import { axisRangeIsEmpty, logAllowed } from '@tidal-ts/chart';
34
+ import { axisRangeIsEmpty, logAllowed, readsFrom, sourcesOf, } from '@tidal-ts/chart';
35
35
  import { configAxisId, seriesAxisId, sharedAxisId, } from '@tidal-ts/chart';
36
36
  import { axisForAdd, canAddUnit } from './axisPolicy.js';
37
37
  export const PRESET_SLOTS = 5;
@@ -114,19 +114,19 @@ const flatConfigs = (rows) => rows.flatMap((r) => r.configs);
114
114
  * raw series is removed. */
115
115
  function derivedClosure(configs, rootId) {
116
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]));
117
+ // The set holds IDS, because that is what callers filter configs and re-point
118
+ // pointers by — and the edges now resolve by id too (`sourcesOf`). They used
119
+ // to go through a `Map` keyed by column, which with a metric seated twice
120
+ // kept only the LAST config per column: removing one copy cascaded through
121
+ // the other's studies.
120
122
  for (let grew = true; grew;) {
121
123
  grew = false;
122
124
  for (const c of configs) {
123
125
  if (doomed.has(c.id) || !c.derive)
124
126
  continue;
125
127
  // 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));
128
+ // (PR #128 review, HIGH).
129
+ const srcs = sourcesOf(configs, c);
130
130
  if (srcs.some((src) => src?.derive && doomed.has(src.id))) {
131
131
  doomed.add(c.id); // derives from a doomed study ⇒ its source column will vanish
132
132
  grew = true;
@@ -164,10 +164,9 @@ function derivedClosure(configs, rootId) {
164
164
  * A study is subordinate to what it is built on; a leg is a peer of its partner.
165
165
  * Same graph, opposite rule, so they get their own walks.
166
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. */
167
+ /** Whether a study already has a study built on it — the no-branching test. */
169
168
  function hasStudyChild(configs, target) {
170
- return configs.some((c) => c.id !== target.id && c.derive && inputNames(c.derive).includes(target.column));
169
+ return configs.some((c) => c.id !== target.id && readsFrom(configs, c, target));
171
170
  }
172
171
  function studiesOn(configs, rootId, isCatalogColumn) {
173
172
  const set = new Set([rootId]);
@@ -176,7 +175,7 @@ function studiesOn(configs, rootId, isCatalogColumn) {
176
175
  for (const c of configs) {
177
176
  if (set.has(c.id) || !c.derive || isCatalogColumn(c.column))
178
177
  continue;
179
- if (configs.some((p) => set.has(p.id) && inputNames(c.derive).includes(p.column))) {
178
+ if (configs.some((p) => set.has(p.id) && readsFrom(configs, c, p))) {
180
179
  set.add(c.id);
181
180
  grew = true;
182
181
  }
@@ -202,9 +201,11 @@ function layeredOn(configs, rootId, isCatalogColumn) {
202
201
  }
203
202
  if (!c.derive || isCatalogColumn(c.column))
204
203
  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))) {
204
+ // A study's SPEC names its sources by column, which is the data; which
205
+ // CONFIG it travels with is its recorded parent (`sourcesOf`). With one
206
+ // config per column those were the same answer, and with a metric seated
207
+ // twice they are not.
208
+ if (configs.some((p) => set.has(p.id) && readsFrom(configs, c, p))) {
208
209
  set.add(c.id);
209
210
  grew = true;
210
211
  }
@@ -265,8 +266,7 @@ export function rowBlocks(configs) {
265
266
  // tunable op had one param called `period` (PR #181 review, MEDIUM).
266
267
  if (!c.derive || opParams(c.derive.op).length === 0)
267
268
  continue;
268
- const names = inputNames(c.derive);
269
- const parent = configs.find((x) => x.id !== c.id && names.includes(x.column));
269
+ const parent = sourcesOf(configs, c)[0];
270
270
  if (parent)
271
271
  parentOf.set(c.id, parent.id);
272
272
  }
@@ -330,7 +330,7 @@ export function studyChainTail(configs, rootId) {
330
330
  !seen.has(c.id) &&
331
331
  !!c.derive &&
332
332
  opParams(c.derive.op).length > 0 &&
333
- inputNames(c.derive).includes(cur.column));
333
+ readsFrom(configs, c, cur));
334
334
  if (!next)
335
335
  return cur.id;
336
336
  seen.add(next.id);
@@ -392,7 +392,10 @@ function toConfig(e, id, axis = e.axis) {
392
392
  /** The spec a study of `target` at `(op, period)` induces — reads the target's
393
393
  * DATA column, or **nests** the target's own spec when the target is derived
394
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). */
395
+ * content-addressing makes the seated copy and the nested copy one node). A
396
+ * MULTI-OUTPUT target is nested as one PICKED output, its primary
397
+ * (`studyInputOf`) — never bare, which would read whichever output it happens
398
+ * to declare first (TDL-STUDYCHAIN). */
396
399
  const studySpec = (target, op, period) => {
397
400
  // Params come from the REGISTRY, not from a list here: an op is tuned by
398
401
  // exactly what it declares, so a two-param study (a band's `period` +
@@ -420,7 +423,7 @@ const studySpec = (target, op, period) => {
420
423
  // and `deriveId` dedupes them. That is correct — ATR(14) of the bars is one
421
424
  // series — and it is why the picker has to refuse the op where its columns
422
425
  // are absent (`opNeedsColumns`) rather than let the fold skip it silently.
423
- const self = target.derive ?? target.column;
426
+ const self = studyInputOf(target.derive ?? target.column);
424
427
  const inputs = opInputs(op).map((r) =>
425
428
  // A target role takes the target; a bar role takes its own column. No
426
429
  // default and not a target role should be unreachable (a benchmark role is
@@ -430,7 +433,7 @@ const studySpec = (target, op, period) => {
430
433
  return {
431
434
  op,
432
435
  ...(declared.length > 0 ? { params } : {}),
433
- inputs: inputs.length > 0 ? inputs : [target.derive ?? target.column],
436
+ inputs: inputs.length > 0 ? inputs : [self],
434
437
  };
435
438
  };
436
439
  /** A study `SeriesConfig` layered on a target — same source, and the same axis
@@ -450,10 +453,17 @@ function studyConfig(target, op, period, id) {
450
453
  // group, keyed by its own id, and its own unit for the labels.
451
454
  const shares = opSharesSourceAxis(op);
452
455
  const own = specUnit(derive, (col) => (col === target.column ? (target.unit ?? '') : ''));
456
+ // Which output of a multi-output target this study reads, named in the label
457
+ // (`Price · DONCHIAN(20) · Middle · SMA(10)`) so the choice is never silent.
458
+ const picked = derive.inputs.find(isPickedInput);
453
459
  return {
454
460
  id,
455
- ...(shares ? {} : { axisGroup: id }),
456
- label: `${target.label} · ${studyTag(derive)}`, // legend chip
461
+ // Sharing means sharing the SOURCE's scale — which is the source's own axis
462
+ // group when it has one. An SMA of a MACD (or of an RSI) left out of that
463
+ // group landed on the row's shared axis instead, a line near zero drawn on
464
+ // the price's scale.
465
+ ...(shares ? (target.axisGroup ? { axisGroup: target.axisGroup } : {}) : { axisGroup: id }),
466
+ label: `${target.label}${picked ? ` · ${picked.output}` : ''} · ${studyTag(derive)}`, // legend chip
457
467
  family: target.family ?? target.label, // main line = the source's name
458
468
  tenor: target.tenor, // carry the source's tenor into the params sub-line
459
469
  // A study is the same reading, smoothed — so it takes its metric's COLOUR
@@ -473,6 +483,15 @@ function studyConfig(target, op, period, id) {
473
483
  value: null,
474
484
  unit: shares ? target.unit : own,
475
485
  derive,
486
+ // WHICH config this study is on — recorded now, because this is the one
487
+ // moment it is known for certain: the user pressed THIS config's button.
488
+ // The spec above names the target by column, which is the data; this
489
+ // names it by id, which is the graph (`sourcesOf`). Index-ALIGNED with the
490
+ // spec's inputs, and only where an input actually reads the target: an
491
+ // ATR's inputs are the bar's high/low/close, whatever it was added from,
492
+ // and recording the target there made an ATR added from an SMA read as
493
+ // that SMA's child (PR #16 review, MEDIUM).
494
+ ...recordParents(derive, [target]),
476
495
  };
477
496
  }
478
497
  /** Legend label per pair op — the spread reads as its construction. */
@@ -513,6 +532,7 @@ const resolveLeg = (context, id) => {
513
532
  const cfg = legSeat(context, id);
514
533
  if (cfg)
515
534
  return {
535
+ seatId: cfg.id,
516
536
  label: cfg.label,
517
537
  unit: cfg.unit ?? '',
518
538
  column: cfg.column,
@@ -540,7 +560,9 @@ const underCompare = (input) => typeof input === 'string'
540
560
  input.startsWith(COMPARE_PREFIX)
541
561
  ? input
542
562
  : `${COMPARE_PREFIX}${input}`
543
- : { ...input, inputs: input.inputs.map(underCompare) };
563
+ : isPickedInput(input)
564
+ ? { from: underCompare(input.from), output: input.output }
565
+ : { ...input, inputs: input.inputs.map(underCompare) };
544
566
  /** "Is this column a catalog metric's?" — {@link layeredOn}'s test for the
545
567
  * derived metrics that stand alone instead of travelling with a source. A
546
568
  * seated config's id no longer says where it came from, so catalog-ness is
@@ -575,7 +597,10 @@ const unitOfColumn = (scope) => columnUnits(scope.catalog, flatConfigs(scope.row
575
597
  * metric, then the compare rebind rewrites the LEAVES — so a compare-bound
576
598
  * studied leg computes the study over the compare columns. */
577
599
  const boundLeg = (leg, input) => {
578
- let graph = leg.spec ?? leg.column;
600
+ // A multi-output leg (a band) reads its PRIMARY output, picked, exactly as a
601
+ // study of it does — nested bare it read whichever output was declared first,
602
+ // so `Donchian − Price` was silently the TOP edge minus the price.
603
+ let graph = studyInputOf(leg.spec ?? leg.column);
579
604
  let label = leg.label;
580
605
  if (input.study) {
581
606
  graph = { op: input.study.op, params: { period: input.study.period }, inputs: [graph] };
@@ -636,8 +661,23 @@ palette = [], taken = [], spreadColor) {
636
661
  // diff keeps the unit, a ratio is unitless, a log-ratio reads `log`.
637
662
  unit: specUnit(derive, unitOf),
638
663
  derive,
664
+ // A leg that resolved to a seated config is that config's child. Only an
665
+ // input that reads the seat AS IS is recorded: a per-leg study or a compare
666
+ // rebind makes the input its own computation, which no seated config
667
+ // publishes.
668
+ ...recordParents(derive, [a, b].flatMap((l) => (l.seatId ? [{ id: l.seatId, column: l.column }] : []))),
639
669
  };
640
670
  }
671
+ /**
672
+ * `parentIds` for a derived config about to be minted: at each input position,
673
+ * the id of the `seat` that publishes that input's column, else nothing.
674
+ * Returns `{}` when nothing was recorded, so a config with no seated parents
675
+ * carries no empty array.
676
+ */
677
+ function recordParents(derive, seats) {
678
+ const parentIds = inputNames(derive).map((name) => seats.find((s) => s.column === name)?.id);
679
+ return parentIds.some((id) => id != null) ? { parentIds } : {};
680
+ }
641
681
  /**
642
682
  * A pair PART's display name, rebuilt from the spec — the same construction
643
683
  * `boundLeg` writes, read back the other way: the metric's catalog name, its
@@ -716,7 +756,8 @@ function pairSeats(context, event) {
716
756
  return !!pairRow(context, event);
717
757
  }
718
758
  /** The column a study takes if one of its params changes — its spec re-encoded.
719
- * The identity does NOT change with it; this guards column collisions only. */
759
+ * The identity does NOT change with it; this only tells a real edit from a
760
+ * no-op (the same column back). */
720
761
  const restudyColumn = (study, name, value) => deriveId({ ...study.derive, params: { ...study.derive.params, [name]: value } });
721
762
  /**
722
763
  * Whether a study's param `name` can move to `value` — shared by the guard and
@@ -725,8 +766,10 @@ const restudyColumn = (study, name, value) => deriveId({ ...study.derive, params
725
766
  *
726
767
  * It has to run the whole propagation, because an edit is refusable for a
727
768
  * reason that isn't visible on the study itself: re-speccing it rewrites
728
- * everything built on it, and one of THOSE can land on a column another config
729
- * already holds — two lines computing the same thing. Before this was exported,
769
+ * everything built on it, and one of THOSE rewrites can be a spec the registry
770
+ * rejects, or move a unit incoherently. (Landing on a column another config
771
+ * already computes used to be a reason too; it is not since `TDL-CMPDUP` — two
772
+ * configs may compute the same thing.) Before this was exported,
730
773
  * such an edit simply did nothing when clicked, with no way to find out why
731
774
  * (PR #140 review, MEDIUM).
732
775
  */
@@ -765,8 +808,14 @@ export function respecAllowed(scope, id, name, value) {
765
808
  // own colour, axis, eye and study pipeline, tied together by `SeriesGroup`.
766
809
  // Splitting and re-joining are one edit read in two directions.
767
810
  /** A leg's graph input as a seated config would carry it: a raw column has no
768
- * spec, a derived leg carries its own. */
769
- const legParts = (leg) => typeof leg === 'string' ? { column: leg } : { column: deriveId(leg), derive: leg };
811
+ * spec, a derived leg carries its own, and a PICKED leg is its source study —
812
+ * the config that publishes the output (a band leg splits out as the band). */
813
+ const legParts = (leg) => {
814
+ if (typeof leg === 'string')
815
+ return { column: leg };
816
+ const spec = isPickedInput(leg) ? leg.from : leg;
817
+ return { column: deriveId(spec), derive: spec };
818
+ };
770
819
  /** The colour leg B takes when a pair splits — the first palette key neither
771
820
  * leg A nor anything else in the row is already using, so two fresh lines are
772
821
  * never the same colour. Falls back to leg A's if the palette is exhausted. */
@@ -808,8 +857,12 @@ adding = false) {
808
857
  const { column, derive } = legParts(input);
809
858
  // Adoption looks only in the pair's OWN row: a group whose legs sit in two
810
859
  // rows has no single Pair node to render (the panel is per-row), so it
811
- // would draw as two one-legged pairs.
812
- const seated = row.find((c) => c.id !== pair.id && c.column === column);
860
+ // would draw as two one-legged pairs. The RECORDED leg first: with a metric
861
+ // seated twice in one row, a compare added from the second copy must adopt
862
+ // the second copy, not whichever the column finds first (PR #16 review).
863
+ const byId = pair.parentIds?.[i];
864
+ const seated = (byId != null ? row.find((c) => c.id === byId && c.column === column) : undefined) ??
865
+ row.find((c) => c.id !== pair.id && c.column === column);
813
866
  if (seated) {
814
867
  // …and never STEAL a leg from another pair. Two pairs sharing a leg
815
868
  // column would leave the first group with one member, which nothing can
@@ -820,14 +873,15 @@ adding = false) {
820
873
  plan.adopt.push({ id: seated.id, group: { id: pair.id, side } });
821
874
  return;
822
875
  }
823
- // The column is free in this row but taken in ANOTHER — creating here would
824
- // put two configs on one column, which every dependency walk resolves by.
825
- if (configs.some((c) => c.id !== pair.id && c.column === column))
826
- refuse = true;
876
+ // The column may be seated on ANOTHER row already, and a leg is created
877
+ // here regardless: two configs on one column is legal now that the walks
878
+ // resolve by recorded parent. This refusal is what made an unjoined
879
+ // compare from Bottom silently do nothing when its metric lived on Top
880
+ // (Peter, 2026-09-28: "why can't I add this compare?").
827
881
  const id = pairIdFree ? ((pairIdFree = false), pair.id) : mintId(seq++);
828
882
  if (id !== pair.id)
829
883
  plan.mints += 1;
830
- const unit = typeof input === 'string' ? unitOf(input) : specUnit(input, unitOf);
884
+ const unit = derive ? specUnit(derive, unitOf) : unitOf(column);
831
885
  // A spread arrives UNLINKED because it oscillates; its LEGS do not — they
832
886
  // are the raw metrics, and the whole point of drawing both is comparing
833
887
  // them, which needs ONE scale. So a created leg is placed like any new
@@ -848,6 +902,9 @@ adding = false) {
848
902
  unit,
849
903
  value: null,
850
904
  group: { id: pair.id, side },
905
+ // A leg is not a child of the pair's parents: they were the pair's
906
+ // inputs, and a leg's own inputs (if it is derived) are its spec's.
907
+ parentIds: undefined,
851
908
  });
852
909
  });
853
910
  // Both legs adopted ⇒ the pair's own config has nothing left to be, and
@@ -973,6 +1030,13 @@ function propagateRespec(configs, rootId, root, unitOf) {
973
1030
  const moved = dep.id === c.id ? undefined : next.get(dep.id);
974
1031
  if (!moved || moved.column === dep.column)
975
1032
  continue;
1033
+ // Only a config BUILT ON `dep` follows its retune. The substitution
1034
+ // itself is by column, and with a metric seated twice the other copy's
1035
+ // studies read that same column: without this, retuning one SMA
1036
+ // re-pointed the OTHER copy's children at it, silently changing what a
1037
+ // line the user never touched computes.
1038
+ if (!readsFrom(configs, c, dep))
1039
+ continue;
976
1040
  spec = substituteInput(spec, dep.column, moved.derive);
977
1041
  }
978
1042
  if (spec === before)
@@ -995,10 +1059,15 @@ function propagateRespec(configs, rootId, root, unitOf) {
995
1059
  // way through an edit. Refuse rather than apply it.
996
1060
  if (!settled)
997
1061
  return null;
998
- // One column, one config — including against the configs that did NOT move.
999
- const columns = configs.map((c) => next.get(c.id)?.column ?? c.column);
1000
- if (new Set(columns).size !== columns.length)
1001
- return null;
1062
+ // There used to be a check here that every column on the chart is unique
1063
+ // after the edit — "one column, one config". It encoded the model this
1064
+ // function no longer has, and it was wrong in the worst way: `canAdd` has
1065
+ // allowed a metric to be seated twice for a while, and the moment one was,
1066
+ // this refused EVERY retune on the chart, silently, including of studies with
1067
+ // nothing to do with the duplicate (verified against the released machine,
1068
+ // 2026-09-28). Two configs may share a column now; they are told apart by id
1069
+ // and by recorded parent (`sourcesOf`), and the substitution above only
1070
+ // follows a config's own children.
1002
1071
  return next;
1003
1072
  }
1004
1073
  /**
@@ -1299,10 +1368,9 @@ export const terminalMachine = setup({
1299
1368
  // Row cap (the control-panel spec: 1–3). The UI also gates on "current bottom has
1300
1369
  // content"; this is the hard invariant.
1301
1370
  canAddRow: ({ context }) => context.rows.length < MAX_ROWS,
1302
- // A study may be added if its target exists and the exact spec isn't already
1303
- // on the chart. One column, one config: a duplicate spec would fold to the
1304
- // same column, drawing one line twice and making the dependency walks
1305
- // (which resolve edges by column) ambiguous about which config owns it.
1371
+ // A study may be added if its target exists and can take it. The same spec
1372
+ // may already be on the chart — on another copy of the metric, or on this
1373
+ // one (see the end of the guard).
1306
1374
  canAddStudy: ({ context, event }) => {
1307
1375
  if (event.type !== 'series.addStudy')
1308
1376
  return false;
@@ -1318,18 +1386,11 @@ export const terminalMachine = setup({
1318
1386
  // live — the same move `b544480` made for multi-output targets.
1319
1387
  if (!studyOfferable(target.source, event.op))
1320
1388
  return false;
1321
- // A MULTI-OUTPUT study cannot be a study target. Its `column` is a spec id
1322
- // naming several columns and none of its own, so `sma(macd(...))` would
1323
- // read a column that does not exist: the spec is well-formed, `deriveId`
1324
- // names it happily, and the fold quietly produces nothing — a config
1325
- // sitting in the panel computing silence, which is the worst failure
1326
- // shape. Which output such a study should read is a real question the
1327
- // engine has no way to answer (a MACD's line? its histogram?), so refuse
1328
- // rather than guess. The `Add ▸ Study` menu hides on these too; this is
1329
- // the guard that covers the picker, which stays open across picks and
1330
- // appends to the chain TAIL.
1331
- if (target.derive && opIsMulti(target.derive.op))
1332
- return false;
1389
+ // A MULTI-OUTPUT target is fine: `studySpec` reads ONE of its outputs,
1390
+ // picked by name (its primary), so the study has a column to read and the
1391
+ // label says which. This used to refuse a MACD, because a bare nested
1392
+ // multi-output spec read "output 0" — and let a band through, where the
1393
+ // same rule silently smoothed a Donchian's top edge (TDL-STUDYCHAIN).
1333
1394
  // A study takes at most ONE study of its own: a metric may carry several
1334
1395
  // study CHAINS, but a chain never branches (Peter, 2026-09-12). The panel
1335
1396
  // reads a chain top-down as a pipeline, and a branch has no reading in
@@ -1343,17 +1404,20 @@ export const terminalMachine = setup({
1343
1404
  // errors the whole actor (PR #130 review, HIGH). The machine is
1344
1405
  // host-driven — this guard IS the validation.
1345
1406
  const spec = studySpec(target, event.op, event.period);
1346
- if (!isValidSpec(spec))
1347
- return false;
1348
- const column = deriveId(spec);
1349
- return !flatConfigs(context.rows).some((c) => c.column === column);
1407
+ // The same study may sit on two configs — an SMA on the price in each of
1408
+ // two rows, each copy then growing its own chain. That was refused
1409
+ // because every walk resolved by column and could not tell the two
1410
+ // apart; they resolve by recorded parent now (`sourcesOf`), so it is the
1411
+ // user's to decide whether two of something makes sense (Peter,
1412
+ // 2026-09-28: "It's up to them to make it make sense, not us").
1413
+ return isValidSpec(spec);
1350
1414
  },
1351
1415
  // A pair may be added if both legs exist, differ, and read the SAME data
1352
1416
  // source — the derive fold runs per series, so both columns must live on
1353
1417
  // one series (cross-source/cross-entity pairs need the join step; see
1354
1418
  // Tidal's pairs plan). The spread arrives UNLINKED (its own axis), so there is
1355
- // no unit gate — only a target row must exist and the exact spec must not
1356
- // already be on the chart.
1419
+ // no unit gate — only a target row must exist. The same spec may already be
1420
+ // on the chart (`TDL-CMPDUP`).
1357
1421
  canAddPair: ({ context, event }) => {
1358
1422
  if (event.type !== 'series.addPair')
1359
1423
  return false;
@@ -1382,7 +1446,11 @@ export const terminalMachine = setup({
1382
1446
  // whatever the bindings, and two legs drawing one line if unjoined. The
1383
1447
  // same metric ACROSS roles (or under different studies) differs after
1384
1448
  // binding, so George's canonical case passes.
1385
- const name = (i) => (typeof i === 'string' ? i : deriveId(i));
1449
+ const name = (i) => typeof i === 'string'
1450
+ ? i
1451
+ : isPickedInput(i)
1452
+ ? `${deriveId(i.from)}#${i.output}`
1453
+ : deriveId(i);
1386
1454
  if (name(spec.inputs[0]) === name(spec.inputs[1]))
1387
1455
  return false;
1388
1456
  // UNJOINED: no spread is ever seated, so the test is whether the two legs
@@ -1392,8 +1460,7 @@ export const terminalMachine = setup({
1392
1460
  const row = pairRow(context, event);
1393
1461
  return !!(row && planAddGroup(context, event, row));
1394
1462
  }
1395
- if (flatConfigs(context.rows).some((c) => c.column === deriveId(spec)))
1396
- return false;
1463
+ // The same spread may be seated twice, on two rows — see `canAddStudy`.
1397
1464
  // …and a row to land on. Delegated to `pairSeats` — which the sibling
1398
1465
  // assigners already use — so the guard, the rows assigner and the id
1399
1466
  // counter cannot disagree about where a spread goes (a named row, else
@@ -1806,7 +1873,11 @@ export const terminalMachine = setup({
1806
1873
  rows: ({ context, event }) => event.type === 'series.patch'
1807
1874
  ? context.rows.map((r) => ({
1808
1875
  ...r,
1809
- configs: r.configs.map((c) => (c.id === event.id ? { ...c, ...event.patch } : c)),
1876
+ configs: r.configs.map((c) =>
1877
+ // `parentIds` is the graph, not a presentation field: a patch
1878
+ // may not rewrite which config a study is on (an untyped host
1879
+ // could still send one).
1880
+ c.id === event.id ? { ...c, ...event.patch, parentIds: c.parentIds } : c),
1810
1881
  }))
1811
1882
  : context.rows,
1812
1883
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidal-ts/terminal",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "description": "The terminal machine — an XState v5 statechart that owns a chart's configuration (rows, series, studies, pairs, axes, presets) and never its data.",
6
6
  "license": "MIT",
@@ -36,8 +36,8 @@
36
36
  "xstate": "^5.28.0"
37
37
  },
38
38
  "dependencies": {
39
- "@tidal-ts/chart": "0.2.1",
40
- "@tidal-ts/core": "0.2.1"
39
+ "@tidal-ts/chart": "0.3.0",
40
+ "@tidal-ts/core": "0.3.0"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@pond-ts/charts": "^0.70.0",