fsanyoto commited on
Commit
658edb3
·
verified ·
1 Parent(s): 76338e3

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "8735ed9",
3
  "releases": [
4
  {
5
  "version": "v75",
 
1
  {
2
+ "current": "805c8f2",
3
  "releases": [
4
  {
5
  "version": "v75",
VERSION CHANGED
@@ -1 +1 @@
1
- 8735ed9
 
1
+ 805c8f2
platform/core/daily_sales_repair.py CHANGED
@@ -166,6 +166,10 @@ def _validate_binding(name, binding, *, window_kind=None):
166
  _addr(slot["ref"])
167
  if node["op"] in {"gte", "lte"}:
168
  bounds.setdefault(node["colId"], set()).add(node["op"])
 
 
 
 
169
  if any(ops == {"gte", "lte"} for ops in bounds.values()):
170
  return
171
  window = W.normalize(copy.deepcopy(period.get("window") if isinstance(period, dict) else None))
@@ -544,15 +548,17 @@ def _build_summary_plan(current, request, resolve_binding, formula_check):
544
  if not str(request.get("refreshed_at") or "").strip():
545
  raise RepairRefusal("repair_timestamp_required", "The summary needs an explicit refresh timestamp.")
546
  cells = _tab(current, SUMMARY_TAB).get("cells") or {}
547
- # Allocate four fully empty rows inside the existing sheet dimensions. Never overwrite
548
- # authored content, add a tab, resize the sheet, or change hidden/print/visual metadata.
 
 
549
  tab_rows = int(_tab(current, SUMMARY_TAB).get("rows") or 0)
550
- helper_row = next((row for row in range(tab_rows - 3, 35, -1)
551
- if all((cells.get(col + str(r)) or {}).get("kind", "empty") == "empty"
552
- for r in range(row, row + 4) for col in SUMMARY_COLUMNS)), None)
553
  if helper_row is None:
554
  raise RepairRefusal("repair_summary_helper_space",
555
- "The summary needs four empty rows in its existing sheet for date and scope formulas.")
556
  edits = []
557
 
558
  def add(address, desired, kind):
@@ -564,26 +570,12 @@ def _build_summary_plan(current, request, resolve_binding, formula_check):
564
  def formula(address, text):
565
  add(address, {"kind": "formula", "state": "stale", "formula": text}, "derived")
566
 
567
- scope_ref = "F" + str(helper_row + 3)
568
  formula(scope_ref, '=IF($D$10="RI","Royal 1 (USD)",IF($D$10="FFS","Fisch (USD)",NA()))')
569
  windows = {}
570
  for col in SUMMARY_COLUMNS:
571
- end = _summary_date(_summary_value(current, col + "7"))
572
- year_refs = [addr for addr, cell in cells.items() if re.fullmatch(r"[A-Z]+2", addr)
573
- and str((cell or {}).get("value")) in {str(end.year), str(float(end.year))}]
574
- # The year can be one merged/shared header. Prefer this column, otherwise require
575
- # an unambiguous year cell; never guess between two independent calendar headers.
576
- year_ref = col + "2" if col + "2" in year_refs else year_refs[0] if len(year_refs) == 1 else None
577
- if not year_ref:
578
- raise RepairRefusal("repair_summary_year_ambiguous",
579
- "The summary needs an unambiguous year on row 2 for column " + col + ".")
580
- first, previous_first, previous_end = (col + str(helper_row + offset) for offset in range(3))
581
- # DATE/EDATE already return ISO dates. String concatenation preserves that value
582
- # without introducing an inferred date style on a previously blank helper cell.
583
- formula(first, '=DATE(' + year_ref + ',1,1)&""')
584
- formula(previous_first, '=DATE(' + year_ref + '-1,1,1)&""')
585
- formula(previous_end, '=EDATE(' + col + '7,-12)&""')
586
- windows[col] = ((first, col + "7"), (previous_first, previous_end))
587
  projected = _summary_formula_projection(_project(current, edits), edits, formula_check)
588
  if _summary_value(projected, scope_ref) != summary.get("pricelist"):
589
  raise RepairRefusal("repair_summary_partner_scope",
@@ -601,12 +593,12 @@ def _build_summary_plan(current, request, resolve_binding, formula_check):
601
  "scope": {"filter": {"conj": "and", "nodes": []}}},
602
  projected, resolve_binding))
603
  for col, ranges in windows.items():
604
- for row_number, (first, last) in zip((31, 32), ranges):
605
  binding = {"database": "ut_odoo_invoices",
606
  "aggregate": {"field": "amount_untaxed", "fn": "sum", "kind": "column"},
607
  "scope": {"filter": {"conj": "and", "nodes": [
608
- {"colId": "invoice_date", "op": "gte", "valueRef": {"ref": first}},
609
- {"colId": "invoice_date", "op": "lte", "valueRef": {"ref": last}},
610
  {"colId": "move_type", "op": "eq", "value": "out_invoice"}]}},
611
  "related": {"via": "customer_link", "filter": {"conj": "and", "nodes": [
612
  {"colId": "pricelist", "op": "eq", "valueRef": {"ref": scope_ref}}]}}}
@@ -637,7 +629,7 @@ def _build_summary_plan(current, request, resolve_binding, formula_check):
637
  checks = validate(projected, windows=windows, mirror_as_of=as_of.isoformat(),
638
  partner_ids=partners, invoice_validate=summary["validate_invoice"],
639
  formula_check=formula_check)
640
- return edits, {"before": summary["before"], "helper_rows": list(range(helper_row, helper_row + 4)),
641
  "pricelist_cell": scope_ref, "mirror_as_of": as_of.isoformat(),
642
  "partner_count": len(partners), "checks": checks,
643
  "ratio_repair": ratio_evidence}
@@ -653,9 +645,10 @@ def validate(book, *, windows, mirror_as_of, partner_ids, invoice_validate, form
653
  proof, checks = copy.deepcopy(book), []
654
  as_of = _summary_date(mirror_as_of)
655
  for col in SUMMARY_COLUMNS:
656
- for row_number, (first_ref, last_ref) in zip((31, 32), windows[col]):
657
- first = _summary_date(_summary_value(book, first_ref))
658
- last = min(_summary_date(_summary_value(book, last_ref)), as_of)
 
659
  if first > last:
660
  raise RepairRefusal("repair_summary_asof_before_window",
661
  "The invoice mirror ends before a summary window begins. Refresh it first.")
 
166
  _addr(slot["ref"])
167
  if node["op"] in {"gte", "lte"}:
168
  bounds.setdefault(node["colId"], set()).add(node["op"])
169
+ # Hotfix 2026-09-24: "year to date up to the date in F7" is bounded on both
170
+ # sides by ONE reference, so it needs no helper cell for its first day.
171
+ if node["op"] == "within" and (node.get("dateWindow") or {}).get("kind") not in (None, "custom"):
172
+ bounds.setdefault(node["colId"], set()).update({"gte", "lte"})
173
  if any(ops == {"gte", "lte"} for ops in bounds.values()):
174
  return
175
  window = W.normalize(copy.deepcopy(period.get("window") if isinstance(period, dict) else None))
 
548
  if not str(request.get("refreshed_at") or "").strip():
549
  raise RepairRefusal("repair_timestamp_required", "The summary needs an explicit refresh timestamp.")
550
  cells = _tab(current, SUMMARY_TAB).get("cells") or {}
551
+ # Allocate ONE fully empty row inside the existing sheet dimensions, for the pricelist scope.
552
+ # Never overwrite authored content, add a tab, resize the sheet, or change hidden/print/visual
553
+ # metadata. Hotfix 2026-09-24 (owner: "we use a proxy date Row in Row 9997 instead of using
554
+ # the one in Row 7 why?"): the dates need no helper rows; each window reads row 7 itself.
555
  tab_rows = int(_tab(current, SUMMARY_TAB).get("rows") or 0)
556
+ helper_row = next((row for row in range(tab_rows, 35, -1)
557
+ if all((cells.get(col + str(row)) or {}).get("kind", "empty") == "empty"
558
+ for col in SUMMARY_COLUMNS)), None)
559
  if helper_row is None:
560
  raise RepairRefusal("repair_summary_helper_space",
561
+ "The summary needs one empty row in its existing sheet for its scope formula.")
562
  edits = []
563
 
564
  def add(address, desired, kind):
 
570
  def formula(address, text):
571
  add(address, {"kind": "formula", "state": "stale", "formula": text}, "derived")
572
 
573
+ scope_ref = "F" + str(helper_row)
574
  formula(scope_ref, '=IF($D$10="RI","Royal 1 (USD)",IF($D$10="FFS","Fisch (USD)",NA()))')
575
  windows = {}
576
  for col in SUMMARY_COLUMNS:
577
+ _summary_date(_summary_value(current, col + "7")) # row 7 must hold a real date
578
+ windows[col] = (("ytd", col + "7"), ("ytd_last_year", col + "7"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579
  projected = _summary_formula_projection(_project(current, edits), edits, formula_check)
580
  if _summary_value(projected, scope_ref) != summary.get("pricelist"):
581
  raise RepairRefusal("repair_summary_partner_scope",
 
593
  "scope": {"filter": {"conj": "and", "nodes": []}}},
594
  projected, resolve_binding))
595
  for col, ranges in windows.items():
596
+ for row_number, (kind, end_ref) in zip((31, 32), ranges):
597
  binding = {"database": "ut_odoo_invoices",
598
  "aggregate": {"field": "amount_untaxed", "fn": "sum", "kind": "column"},
599
  "scope": {"filter": {"conj": "and", "nodes": [
600
+ {"colId": "invoice_date", "op": "within", "dateWindow": {"kind": kind},
601
+ "valueRef": {"ref": end_ref}},
602
  {"colId": "move_type", "op": "eq", "value": "out_invoice"}]}},
603
  "related": {"via": "customer_link", "filter": {"conj": "and", "nodes": [
604
  {"colId": "pricelist", "op": "eq", "valueRef": {"ref": scope_ref}}]}}}
 
629
  checks = validate(projected, windows=windows, mirror_as_of=as_of.isoformat(),
630
  partner_ids=partners, invoice_validate=summary["validate_invoice"],
631
  formula_check=formula_check)
632
+ return edits, {"before": summary["before"], "helper_rows": [helper_row],
633
  "pricelist_cell": scope_ref, "mirror_as_of": as_of.isoformat(),
634
  "partner_count": len(partners), "checks": checks,
635
  "ratio_repair": ratio_evidence}
 
645
  proof, checks = copy.deepcopy(book), []
646
  as_of = _summary_date(mirror_as_of)
647
  for col in SUMMARY_COLUMNS:
648
+ for row_number, (kind, end_ref) in zip((31, 32), windows[col]):
649
+ bounds = W.resolve({"kind": kind}, _summary_date(_summary_value(book, end_ref)).isoformat())
650
+ first = _summary_date(bounds[0])
651
+ last = min(_summary_date(bounds[1]), as_of)
652
  if first > last:
653
  raise RepairRefusal("repair_summary_asof_before_window",
654
  "The invoice mirror ends before a summary window begins. Refresh it first.")
platform/modules/sheet.py CHANGED
@@ -699,6 +699,12 @@ def resolve_filter_cells(nodes, read_cell):
699
  elif "valueRef" in node:
700
  slot = node["valueRef"]
701
  ref = str(slot.get("ref") or "").strip() if isinstance(slot, dict) else ""
 
 
 
 
 
 
702
  if (node.get("op") in VALUE_FREE_OPS or node.get("op") == "within"
703
  or node.get("dateMode") in ANCHOR_VALUE_FREE or node.get("rhs") is not None):
704
  raise SheetRefusal("filter_cell_unreadable", ref or "(blank)",
@@ -718,6 +724,27 @@ def resolve_filter_cells(nodes, read_cell):
718
  return out
719
 
720
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
721
  # W60-T40: explicit persisted identity, separate from both flat columns and cell value slots.
722
  LINKED_FILTER_PREFIX = "linked:"
723
 
 
699
  elif "valueRef" in node:
700
  slot = node["valueRef"]
701
  ref = str(slot.get("ref") or "").strip() if isinstance(slot, dict) else ""
702
+ if node.get("op") == "within" and node.get("rhs") is None:
703
+ # Hotfix 2026-09-24 (owner: "we only need 1 cell reference for the date move").
704
+ # A window read AS OF a cell: "year to date" through the date in F7, so one
705
+ # reference moves the whole range and no helper cell holds its first day.
706
+ out.append(_within_as_of_cell(node, ref, read_cell(ref)))
707
+ continue
708
  if (node.get("op") in VALUE_FREE_OPS or node.get("op") == "within"
709
  or node.get("dateMode") in ANCHOR_VALUE_FREE or node.get("rhs") is not None):
710
  raise SheetRefusal("filter_cell_unreadable", ref or "(blank)",
 
724
  return out
725
 
726
 
727
+ def _within_as_of_cell(node, ref, value):
728
+ """`within <window>` with the window's today taken from a cell, as a resolved custom range."""
729
+ from harness import windows as W
730
+ window = node.get("dateWindow") if isinstance(node.get("dateWindow"), dict) else {}
731
+ if window.get("kind") in (None, "custom"):
732
+ raise SheetRefusal("filter_cell_unreadable", ref or "(blank)",
733
+ "a fixed range cannot be read as of a cell.")
734
+ as_of = W.ending_cell_date(value)
735
+ bounds = W.resolve(window, as_of) if as_of else None
736
+ if not bounds or not bounds[0] or not bounds[1]:
737
+ raise SheetRefusal("filter_cell_unreadable", ref or "(blank)",
738
+ "its value is not a real date." if not as_of
739
+ else "this window has no end, so a cell cannot close it.")
740
+ # Two plain bounds, not a custom window: a window needs the tenant's today to compile, and
741
+ # the range is already fixed by the cell. Each bound keeps the reference it came from.
742
+ base = {key: value for key, value in node.items() if key not in ("op", "dateWindow", "value")}
743
+ return {"conj": "and", "children": [
744
+ {**base, "op": "gte", "value": bounds[0], "_cell_value_resolved": True},
745
+ {**base, "op": "lte", "value": bounds[1], "_cell_value_resolved": True}]}
746
+
747
+
748
  # W60-T40: explicit persisted identity, separate from both flat columns and cell value slots.
749
  LINKED_FILTER_PREFIX = "linked:"
750
 
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- b10a7604beda192e0010510d12ac13654a3f0e86b5ed86e4e1d9201748ee08a2
 
1
+ c692564ee7775979e360cd962f6f00d37f3cb23d0a719bb1a0001fbfb37b5c61
web/src/customer-grid/types.ts CHANGED
@@ -3374,6 +3374,12 @@ export interface FilterRule {
3374
  * and not a change to `value`.
3375
  */
3376
  dateMode?: AnchorMode;
 
 
 
 
 
 
3377
  /** CG-9 — compare against another attribute instead of a literal. See FilterRhs. */
3378
  rhs?: FilterRhs;
3379
  /**
 
3374
  * and not a change to `value`.
3375
  */
3376
  dateMode?: AnchorMode;
3377
+ /**
3378
+ * Hotfix 2026-09-24 (owner: "Where invoice date is on or after [a value/another field/a cell]").
3379
+ * Sheet only: the value, or for `within` the window's end date, is read from a workbook cell
3380
+ * when the binding resolves. `locked` keeps the reference fixed when the bound cell is copied.
3381
+ */
3382
+ valueRef?: { ref: string; locked?: boolean };
3383
  /** CG-9 — compare against another attribute instead of a literal. See FilterRhs. */
3384
  rhs?: FilterRhs;
3385
  /**
web/src/filter-kit/FilterBuilderPanel.tsx CHANGED
@@ -659,6 +659,65 @@ interface LevelContext {
659
  * string here would have put a Sheet sentence into three surfaces that did not ask for one.
660
  */
661
  fieldPickerTitle?: string;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662
  }
663
 
664
  /**
@@ -803,7 +862,7 @@ function LeafRow({
803
  onRemove: () => void;
804
  }) {
805
  const { fields, fieldByKey, measures, measureByKey, lists, viewChoices, choicesFor,
806
- fieldPickerTitle } = ctx;
807
  const isMeasure = isMeasureRule(rule);
808
  const isCohort = rule.colId === COHORT_FIELD;
809
  const hasCohorts = lists.length > 0;
@@ -881,9 +940,9 @@ function LeafRow({
881
  // comparand — "the top 10 compared with another field" is not a question.
882
  if (isRankOp(op as string))
883
  return onRule({ ...rule, op: op as FilterOp, value: rankDefault(op as FilterOp),
884
- value2: undefined, rhs: undefined, dateWindow: undefined });
885
  if (VALUE_FREE_OPS.has(op as FilterOp))
886
- return onRule({ ...rule, op, value: "", value2: undefined, rhs: undefined });
887
  if (op === "within")
888
  return onRule({ ...rule, op, value: "", value2: undefined, rhs: undefined,
889
  dateWindow: rule.dateWindow ?? DEFAULT_DATE_WINDOW });
@@ -924,6 +983,11 @@ function LeafRow({
924
  // (see `isTextComparable`).
925
  const usingStat = rule.rhs?.kind === "stat";
926
  const usingField = rule.rhs != null && !usingStat;
 
 
 
 
 
927
  // Explicitly widened: the cohort branch contributes a DISJOINT vocabulary, and without the
928
  // annotation `withCurrent`'s `T extends string` infers from the first branch alone.
929
  const opList: (FilterOp | CohortOp | string)[] = isMeasure
@@ -1050,15 +1114,21 @@ function LeafRow({
1050
  </optgroup>
1051
  )}
1052
  </select>
1053
- {canCompareField && (
1054
  // The switch between "a value I type" and "another attribute". Two options rather than
1055
  // a checkbox, because the row already reads as a sentence and this is the noun slot.
1056
  <select
1057
  className="cg-select cg-cond-mode"
1058
- value={usingStat ? "stat" : usingField ? "field" : "value"}
1059
  aria-label="Compare against"
1060
  onChange={(e) => {
1061
  const mode = e.target.value;
 
 
 
 
 
 
1062
  if (mode === "stat")
1063
  return patch({ rhs: { kind: "stat", stat: "median" },
1064
  value: "", value2: undefined,
@@ -1079,7 +1149,8 @@ function LeafRow({
1079
  }}
1080
  >
1081
  <option value="value">a value</option>
1082
- <option value="field">another field</option>
 
1083
  {/* Statistics are computed SERVER-SIDE over the caller's pool, so they are offered
1084
  for a MEASURE only. A column statistic would need a second percentile
1085
  implementation on the client and the lock-step gate that goes with it. */}
@@ -1089,6 +1160,18 @@ function LeafRow({
1089
  {/* value-free ops render NO value control (Airtable does the same) */}
1090
  {VALUE_FREE_OPS.has(rule.op as FilterOp) ? (
1091
  <span className="cg-cond-val cg-cond-noval" aria-hidden />
 
 
 
 
 
 
 
 
 
 
 
 
1092
  ) : usingStat ? (
1093
  <select
1094
  className="cg-select cg-cond-val cg-cond-stat"
@@ -1284,6 +1367,8 @@ export interface FilterBuilderPanelProps {
1284
  * The deleted-column note still wins on a row whose column is gone: see `LeafRow`.
1285
  */
1286
  fieldPickerTitle?: string;
 
 
1287
  /*
1288
  * ⛔ W47-T13 (owner instruction 15) DELETED `onClose` FROM THIS TYPE, and the deletion is the
1289
  * point. W38-T02 had added a header close button behind an optional `onClose`; the owner has
@@ -1306,6 +1391,7 @@ export function FilterBuilderPanel({
1306
  cohortLock,
1307
  footerExtra,
1308
  fieldPickerTitle,
 
1309
  }: FilterBuilderPanelProps) {
1310
  const nodes = filterTreeNodes(filters);
1311
  const conj = filterTreeConj(filters);
@@ -1336,9 +1422,9 @@ export function FilterBuilderPanel({
1336
  );
1337
  const ctx = useMemo<LevelContext>(
1338
  () => ({ fields: condFields, fieldByKey, measures, measureByKey, lists: cohorts,
1339
- viewChoices, choicesFor, fieldPickerTitle }),
1340
  [condFields, fieldByKey, measures, measureByKey, cohorts, viewChoices, choicesFor,
1341
- fieldPickerTitle]
1342
  );
1343
 
1344
  return (
 
659
  * string here would have put a Sheet sentence into three surfaces that did not ask for one.
660
  */
661
  fieldPickerTitle?: string;
662
+ /** Sheet only: what a workbook cell reads now. Present means a condition may take "a cell". */
663
+ readCell?: FilterCellReader;
664
+ }
665
+
666
+ /** What a referenced cell reads now, or null when the text is not a cell reference. */
667
+ export type FilterCellReader = (ref: string) => { value: string; problem?: string } | null;
668
+
669
+ const ISO_DAY = /^(\d{4})-(\d{2})-(\d{2})/;
670
+
671
+ /**
672
+ * Hotfix 2026-09-24 (owner: "make sure it errors or register correctly based on the cell's
673
+ * format too. The cell must be date if the field type is date"). The cell's CURRENT value, checked
674
+ * against the field it filters: `{ok, text}` where `text` is either what the cell reads or why it
675
+ * cannot be used.
676
+ */
677
+ export function readFilterCell(read: FilterCellReader, ref: string, type: FieldType,
678
+ asDate: boolean): { ok: boolean; text: string } {
679
+ const at = ref.trim();
680
+ if (!at) return { ok: false, text: "Type a cell, like F7." };
681
+ const got = read(at);
682
+ if (!got) return { ok: false, text: `${at} is not a cell. Type a cell, like F7.` };
683
+ if (got.problem) return { ok: false, text: got.problem };
684
+ const value = String(got.value ?? "").trim();
685
+ if (!value) return { ok: false, text: `Cell ${at} is blank.` };
686
+ if (asDate || isDateFamily(type)) {
687
+ const m = ISO_DAY.exec(value);
688
+ const day = m ? new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]))) : null;
689
+ if (!m || !day || day.getUTCDate() !== Number(m[3]))
690
+ return { ok: false, text: `Cell ${at} holds ${value}, which is not a date.` };
691
+ return { ok: true, text: `Cell ${at} reads ${day.toLocaleDateString(undefined,
692
+ { timeZone: "UTC", year: "numeric", month: "short", day: "numeric" })}` };
693
+ }
694
+ if (isNumericType(type) && !Number.isFinite(Number(value.replace(/,/g, ""))))
695
+ return { ok: false, text: `Cell ${at} holds ${value}, which is not a number.` };
696
+ return { ok: true, text: `Cell ${at} reads ${value}` };
697
+ }
698
+
699
+ /** The cell input a condition shows once it takes its value from a cell. */
700
+ function CellRefValue({ rule, read, type, onPatch }: {
701
+ rule: FilterRule; read: FilterCellReader; type: FieldType; onPatch: (p: Partial<FilterRule>) => void;
702
+ }) {
703
+ const ref = rule.valueRef?.ref ?? "";
704
+ const check = readFilterCell(read, ref, type, rule.op === "within");
705
+ return (
706
+ <span className="cg-cond-val cg-cond-cell">
707
+ <input
708
+ type="text"
709
+ className="cg-input"
710
+ aria-label="Cell"
711
+ placeholder="F7"
712
+ value={ref}
713
+ aria-invalid={ref.trim() !== "" && !check.ok}
714
+ onChange={(e) => onPatch({ valueRef: { ...rule.valueRef, ref: e.target.value }, value: "" })}
715
+ />
716
+ <span className={"cg-cond-cellread" + (check.ok ? "" : " is-error")} role={check.ok ? "status" : "alert"}>
717
+ {check.text}
718
+ </span>
719
+ </span>
720
+ );
721
  }
722
 
723
  /**
 
862
  onRemove: () => void;
863
  }) {
864
  const { fields, fieldByKey, measures, measureByKey, lists, viewChoices, choicesFor,
865
+ fieldPickerTitle, readCell } = ctx;
866
  const isMeasure = isMeasureRule(rule);
867
  const isCohort = rule.colId === COHORT_FIELD;
868
  const hasCohorts = lists.length > 0;
 
940
  // comparand — "the top 10 compared with another field" is not a question.
941
  if (isRankOp(op as string))
942
  return onRule({ ...rule, op: op as FilterOp, value: rankDefault(op as FilterOp),
943
+ value2: undefined, rhs: undefined, dateWindow: undefined, valueRef: undefined });
944
  if (VALUE_FREE_OPS.has(op as FilterOp))
945
+ return onRule({ ...rule, op, value: "", value2: undefined, rhs: undefined, valueRef: undefined });
946
  if (op === "within")
947
  return onRule({ ...rule, op, value: "", value2: undefined, rhs: undefined,
948
  dateWindow: rule.dateWindow ?? DEFAULT_DATE_WINDOW });
 
983
  // (see `isTextComparable`).
984
  const usingStat = rule.rhs?.kind === "stat";
985
  const usingField = rule.rhs != null && !usingStat;
986
+ // Sheet only: "a cell" beside "a value" and "another field". A `within` condition takes its END
987
+ // date from the cell, so one reference moves the whole range.
988
+ const canUseCell = !!readCell && !isMeasure && !isCohort && !isView
989
+ && !VALUE_FREE_OPS.has(rule.op as FilterOp) && !isRankOp(rule.op);
990
+ const usingCell = canUseCell && rule.valueRef != null && !usingField && !usingStat;
991
  // Explicitly widened: the cohort branch contributes a DISJOINT vocabulary, and without the
992
  // annotation `withCurrent`'s `T extends string` infers from the first branch alone.
993
  const opList: (FilterOp | CohortOp | string)[] = isMeasure
 
1114
  </optgroup>
1115
  )}
1116
  </select>
1117
+ {(canCompareField || canUseCell) && (
1118
  // The switch between "a value I type" and "another attribute". Two options rather than
1119
  // a checkbox, because the row already reads as a sentence and this is the noun slot.
1120
  <select
1121
  className="cg-select cg-cond-mode"
1122
+ value={usingCell ? "cell" : usingStat ? "stat" : usingField ? "field" : "value"}
1123
  aria-label="Compare against"
1124
  onChange={(e) => {
1125
  const mode = e.target.value;
1126
+ if (mode === "cell")
1127
+ return onRule({ ...rule, valueRef: { ref: rule.valueRef?.ref ?? "" }, rhs: undefined, value: "",
1128
+ value2: undefined, dateMode: undefined });
1129
+ // Leaving "a cell" drops the reference; the other modes then start from a plain rule.
1130
+ const { valueRef: _cell, ...plain } = rule;
1131
+ const patch = (p: Partial<FilterRule>) => onRule({ ...(plain as FilterRule), ...p });
1132
  if (mode === "stat")
1133
  return patch({ rhs: { kind: "stat", stat: "median" },
1134
  value: "", value2: undefined,
 
1149
  }}
1150
  >
1151
  <option value="value">a value</option>
1152
+ {canCompareField && <option value="field">another field</option>}
1153
+ {canUseCell && <option value="cell">a cell</option>}
1154
  {/* Statistics are computed SERVER-SIDE over the caller's pool, so they are offered
1155
  for a MEASURE only. A column statistic would need a second percentile
1156
  implementation on the client and the lock-step gate that goes with it. */}
 
1160
  {/* value-free ops render NO value control (Airtable does the same) */}
1161
  {VALUE_FREE_OPS.has(rule.op as FilterOp) ? (
1162
  <span className="cg-cond-val cg-cond-noval" aria-hidden />
1163
+ ) : usingCell && rule.op === "within" ? (
1164
+ <>
1165
+ <WindowPicker
1166
+ window={rule.dateWindow ?? DEFAULT_DATE_WINDOW}
1167
+ onWindow={(w) => patch({ dateWindow: w })}
1168
+ kinds={WITHIN_KINDS.filter((kind) => kind !== "custom")}
1169
+ />
1170
+ <span className="cg-cond-join">up to the date in</span>
1171
+ <CellRefValue rule={rule} read={readCell!} type={t} onPatch={patch} />
1172
+ </>
1173
+ ) : usingCell ? (
1174
+ <CellRefValue rule={rule} read={readCell!} type={t} onPatch={patch} />
1175
  ) : usingStat ? (
1176
  <select
1177
  className="cg-select cg-cond-val cg-cond-stat"
 
1367
  * The deleted-column note still wins on a row whose column is gone: see `LeafRow`.
1368
  */
1369
  fieldPickerTitle?: string;
1370
+ /** Sheet only: lets a condition read its value from a workbook cell ("a cell"). */
1371
+ readCell?: FilterCellReader;
1372
  /*
1373
  * ⛔ W47-T13 (owner instruction 15) DELETED `onClose` FROM THIS TYPE, and the deletion is the
1374
  * point. W38-T02 had added a header close button behind an optional `onClose`; the owner has
 
1391
  cohortLock,
1392
  footerExtra,
1393
  fieldPickerTitle,
1394
+ readCell,
1395
  }: FilterBuilderPanelProps) {
1396
  const nodes = filterTreeNodes(filters);
1397
  const conj = filterTreeConj(filters);
 
1422
  );
1423
  const ctx = useMemo<LevelContext>(
1424
  () => ({ fields: condFields, fieldByKey, measures, measureByKey, lists: cohorts,
1425
+ viewChoices, choicesFor, fieldPickerTitle, readCell }),
1426
  [condFields, fieldByKey, measures, measureByKey, cohorts, viewChoices, choicesFor,
1427
+ fieldPickerTitle, readCell]
1428
  );
1429
 
1430
  return (
web/src/filter-kit/SheetFilterPopup.tsx CHANGED
@@ -51,6 +51,7 @@ import type {
51
  import { filterTreeConj, filterTreeNodes, isFilterGroup, isRuleActive } from "../customer-grid/types";
52
  // Through the barrel, which is how every other consumer of this kit imports the panel.
53
  import { FilterBuilderPanel, countConditions } from "./index";
 
54
  // ⚠ DIRECT, NOT THROUGH THE BARREL, because `index.ts` re-exports four names from `ops.ts` and
55
  // `opLabel` is not one of them. Widening the barrel would change what every other consumer of
56
  // this kit can reach for a sentence only this file writes; a sibling import inside the same
@@ -68,6 +69,8 @@ export interface SheetFilterPopupProps {
68
  filters: FilterTree;
69
  onChange: (next: FilterTree) => void;
70
  statusValues?: Record<string, string[]>;
 
 
71
  }
72
 
73
  /** Sentence-case count for the dialog's caption. Zero reads as a sentence rather than a bare
@@ -172,7 +175,7 @@ export function filterSentence(
172
  * the Tab trap, and only for layers that can see each other.
173
  */
174
  export function SheetFilterDialog({
175
- addr, onClose, fields, filters, onChange, statusValues,
176
  }: SheetFilterPopupProps) {
177
  const panelRef = useRef<HTMLDivElement>(null);
178
  const titleId = useId();
@@ -251,6 +254,7 @@ export function SheetFilterDialog({
251
  filters={filters}
252
  onChange={onChange}
253
  statusValues={statusValues}
 
254
  fieldPickerTitle={`Fields to filter ${addr} by`}
255
  />
256
  </div>
 
51
  import { filterTreeConj, filterTreeNodes, isFilterGroup, isRuleActive } from "../customer-grid/types";
52
  // Through the barrel, which is how every other consumer of this kit imports the panel.
53
  import { FilterBuilderPanel, countConditions } from "./index";
54
+ import type { FilterCellReader } from "./FilterBuilderPanel";
55
  // ⚠ DIRECT, NOT THROUGH THE BARREL, because `index.ts` re-exports four names from `ops.ts` and
56
  // `opLabel` is not one of them. Widening the barrel would change what every other consumer of
57
  // this kit can reach for a sentence only this file writes; a sibling import inside the same
 
69
  filters: FilterTree;
70
  onChange: (next: FilterTree) => void;
71
  statusValues?: Record<string, string[]>;
72
+ /** Lets a condition take its value from a workbook cell, checked against the field's type. */
73
+ readCell?: FilterCellReader;
74
  }
75
 
76
  /** Sentence-case count for the dialog's caption. Zero reads as a sentence rather than a bare
 
175
  * the Tab trap, and only for layers that can see each other.
176
  */
177
  export function SheetFilterDialog({
178
+ addr, onClose, fields, filters, onChange, statusValues, readCell,
179
  }: SheetFilterPopupProps) {
180
  const panelRef = useRef<HTMLDivElement>(null);
181
  const titleId = useId();
 
254
  filters={filters}
255
  onChange={onChange}
256
  statusValues={statusValues}
257
+ readCell={readCell}
258
  fieldPickerTitle={`Fields to filter ${addr} by`}
259
  />
260
  </div>
web/src/index.css CHANGED
@@ -2655,6 +2655,25 @@ body > .cg-overlay {
2655
  .cg-cond-between .cg-cond-val {
2656
  flex: 1 1 0;
2657
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2658
  .cg-cond-and {
2659
  flex: 0 0 auto;
2660
  color: #8a8a96;
 
2655
  .cg-cond-between .cg-cond-val {
2656
  flex: 1 1 0;
2657
  }
2658
+ /* Hotfix 2026-09-24: a condition that reads a Sheet cell shows the reference and, under it, what
2659
+ the cell reads now, or why it cannot be used (a date field needs a date). */
2660
+ .cg-cond-cell {
2661
+ display: flex;
2662
+ flex-direction: column;
2663
+ gap: 2px;
2664
+ min-width: 96px;
2665
+ }
2666
+ .cg-cond-cellread {
2667
+ font-size: 12px;
2668
+ color: var(--cg-muted);
2669
+ }
2670
+ .cg-cond-cellread.is-error {
2671
+ color: var(--cg-danger);
2672
+ }
2673
+ .cg-cond-join {
2674
+ flex: 0 0 auto;
2675
+ color: var(--cg-muted);
2676
+ }
2677
  .cg-cond-and {
2678
  flex: 0 0 auto;
2679
  color: #8a8a96;
web/src/sheet/BindingEditor.tsx CHANGED
@@ -48,7 +48,7 @@ import type { Field, FilterTree, GridWorkspace, Measure, RelatedEntry, Row, Save
48
  import { choiceVocabulary, relatedEntries, relatedRefusals, topicForScope, MULTI_VALUE_OPS } from "../customer-grid/types";
49
  import type { WindowSpec } from "../customer-grid/windows";
50
  import { normalizeWindow, WINDOW_KINDS, ENDING_KINDS, ENDING_LABELS, ENDING_STEPS, TO_DATE_KINDS,
51
- endingBounds, endingStepDefault, MAX_N, ANCHOR_VALUE_FREE } from "../customer-grid/windows";
52
  import type { EndingKind, EndingStep } from "../customer-grid/windows";
53
  // ⭐⭐ W53-T15 (ruling R8) — THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED
54
  // `FilterBuilderPanel` the Data module also uses is untouched; `SheetFilterPopup` wraps it in the
@@ -68,6 +68,7 @@ import type { BindingAggregate, BindingDragStep, BindingOnDrag, BindingPeriod, B
68
  ViewBinding, DragAcross as SharedDragAcross } from "./types";
69
  // D-687: the drag arithmetic has ONE owner, and it is the file the drag path itself calls.
70
  import { shiftPeriodStart } from "./sheetState";
 
71
  import { bindingStepMode, bindingStepValues, resolveEndingCell, seedBindingStep,
72
  bindingRefSlots, filterValueLeaves, keepCellFilterValues, resolveFilterCell, showCellFilterValues,
73
  updateFilterValueLeaf } from "./bindingRefs";
@@ -1526,6 +1527,20 @@ export default function BindingEditor({
1526
  if (!years.includes(startYear)) years.push(startYear);
1527
  years.sort((a, b) => a - b);
1528
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1529
  // ⚠ W53-T16 - THESE NO LONGER RAISE A TOUCH FLAG, and that is the point of the switch: every
1530
  // period control below is rendered only while `periodOn`, so reaching one of them is already the
1531
  // decision the flag used to have to infer.
@@ -1815,61 +1830,6 @@ export default function BindingEditor({
1815
  : `Edit filter (${conditionCount === 1
1816
  ? "1 condition" : `${conditionCount} conditions`})`}
1817
  </button>
1818
- {filterValueLeaves(tree).map(({ node, indices }, index) => {
1819
- const title = filterFields.find((candidate) => candidate.key === node.colId)?.label || node.colId;
1820
- const supported = !["isEmpty", "isNotEmpty", "aboveAvg", "belowAvg", "within"].includes(node.op)
1821
- && !node.colId.startsWith("__") && !node.rhs && !ANCHOR_VALUE_FREE.has(node.dateMode ?? "");
1822
- if (!supported && !node.valueRef) return null;
1823
- return <div key={indices.join(".")} className="sheet-step-driver">
1824
- <label className="sheet-field">
1825
- <span>{`${title} value source`}</span>
1826
- <select aria-label={`Filter condition ${index + 1} value source`}
1827
- value={node.valueRef ? "cell" : "typed"}
1828
- onChange={(e) => {
1829
- setPreview("");
1830
- setTree(updateFilterValueLeaf(tree, indices, (leaf) => {
1831
- const { valueRef: _old, ...typed } = leaf;
1832
- return e.target.value === "cell"
1833
- ? { ...typed, valueRef: { ref: "" } } : typed;
1834
- }));
1835
- }}>
1836
- <option value="typed">Typed value</option>
1837
- <option value="cell">From a cell</option>
1838
- </select>
1839
- </label>
1840
- {node.valueRef && <>
1841
- <label className="sheet-field">
1842
- <span>Cell</span>
1843
- <input type="text" aria-label={`Filter condition ${index + 1} value cell`}
1844
- placeholder="Sheet1!$A$1" value={node.valueRef.ref}
1845
- onChange={(e) => {
1846
- setPreview("");
1847
- setTree(updateFilterValueLeaf(tree, indices, (leaf) => ({ ...leaf,
1848
- valueRef: { ...leaf.valueRef, ref: e.target.value } })));
1849
- }} />
1850
- </label>
1851
- <label className="sheet-radio">
1852
- <input type="checkbox" checked={node.valueRef.locked === true}
1853
- onChange={(e) => setTree(updateFilterValueLeaf(tree, indices, (leaf) => ({ ...leaf,
1854
- valueRef: { ...leaf.valueRef!, locked: e.target.checked } })))} />
1855
- <span>Keep this cell when copied</span>
1856
- </label>
1857
- {(() => {
1858
- // Say what the linked cell reads now, and how, so a helper row far
1859
- // down the sheet is not a bare address with no meaning.
1860
- const got = node.valueRef.ref.trim() ? readCell?.(node.valueRef.ref) : null;
1861
- if (!got) return null;
1862
- return <p className="sheet-period-note" role="status">
1863
- {got.value === ""
1864
- ? got.problem || `${node.valueRef.ref.trim()} is empty right now.`
1865
- : `${node.valueRef.ref.trim()} reads ${got.value} now`
1866
- + (got.formula ? `, from ${got.formula}` : "") + "."}
1867
- </p>;
1868
- })()}
1869
- <p className="sheet-period-note">Include the sheet name when this workbook has several sheets.</p>
1870
- </>}
1871
- </div>;
1872
- })}
1873
  {/* ⛔⛔ MOUNTED ONLY WHILE OPEN, and that is what orders Escape correctly rather
1874
  than a flag inside the dialog. `useOverlayLayer` claims Escape as soon as it
1875
  runs and `ui/useEscapeClose` gives the key to the LAST entry pushed, so a
@@ -1885,6 +1845,7 @@ export default function BindingEditor({
1885
  filters={showCellFilterValues(tree, readCell)}
1886
  onChange={(next) => setTree(keepCellFilterValues(next, readCell))}
1887
  statusValues={statusValues}
 
1888
  onClose={() => setFilterPopupOpen(false)}
1889
  />
1890
  )}
@@ -1962,6 +1923,7 @@ export default function BindingEditor({
1962
  addr={`${addr} through ${selectedRelationship.label}`}
1963
  fields={relatedFields} filters={showCellFilterValues(relatedTree, readCell)}
1964
  statusValues={relatedStatusValues}
 
1965
  onChange={(filter) => {
1966
  setRelated({ via: related.via, filter: keepCellFilterValues(filter, readCell) });
1967
  setPreview("");
@@ -2276,6 +2238,25 @@ export default function BindingEditor({
2276
  <fieldset className="sheet-scope sheet-drag">
2277
  <legend>When copied</legend>
2278
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2279
  {copySteps.map((step, index) => {
2280
  const isEnding = step.field === BINDING_ENDING_STEP;
2281
  const isPeriod = step.field === BINDING_PERIOD_STEP;
 
48
  import { choiceVocabulary, relatedEntries, relatedRefusals, topicForScope, MULTI_VALUE_OPS } from "../customer-grid/types";
49
  import type { WindowSpec } from "../customer-grid/windows";
50
  import { normalizeWindow, WINDOW_KINDS, ENDING_KINDS, ENDING_LABELS, ENDING_STEPS, TO_DATE_KINDS,
51
+ endingBounds, endingStepDefault, MAX_N, windowLabel } from "../customer-grid/windows";
52
  import type { EndingKind, EndingStep } from "../customer-grid/windows";
53
  // ⭐⭐ W53-T15 (ruling R8) — THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED
54
  // `FilterBuilderPanel` the Data module also uses is untouched; `SheetFilterPopup` wraps it in the
 
68
  ViewBinding, DragAcross as SharedDragAcross } from "./types";
69
  // D-687: the drag arithmetic has ONE owner, and it is the file the drag path itself calls.
70
  import { shiftPeriodStart } from "./sheetState";
71
+ import { useCellRefHighlight } from "./refHighlight";
72
  import { bindingStepMode, bindingStepValues, resolveEndingCell, seedBindingStep,
73
  bindingRefSlots, filterValueLeaves, keepCellFilterValues, resolveFilterCell, showCellFilterValues,
74
  updateFilterValueLeaf } from "./bindingRefs";
 
1527
  if (!years.includes(startYear)) years.push(startYear);
1528
  years.sort((a, b) => a - b);
1529
 
1530
+ // The filter conditions that read a cell. The cell is chosen inside the filter itself ("a cell");
1531
+ // When copied lists them because whether that reference moves is how this cell copies.
1532
+ const cellLeaves = filterValueLeaves(tree).flatMap(({ node, indices }, index) => node.valueRef?.ref
1533
+ ? [{ node, indices, index,
1534
+ title: filterFields.find((candidate) => candidate.key === node.colId)?.label || node.colId }] : []);
1535
+ // Every cell this panel names is outlined on the grid while the panel is open (refHighlight.ts).
1536
+ useCellRefHighlight([
1537
+ ...cellLeaves.map(({ node }) => node.valueRef?.ref ?? ""),
1538
+ ...filterValueLeaves(relatedTree).map(({ node }) => node.valueRef?.ref ?? ""),
1539
+ periodOn && (refOpen || ending === "cell") && periodRef
1540
+ ? (!parsedEndingRef?.sheet && ending === "cell" && endingSheet
1541
+ ? `'${endingSheet.replace(/'/g, "")}'!${periodRef.trim()}` : periodRef) : "",
1542
+ ]);
1543
+
1544
  // ⚠ W53-T16 - THESE NO LONGER RAISE A TOUCH FLAG, and that is the point of the switch: every
1545
  // period control below is rendered only while `periodOn`, so reaching one of them is already the
1546
  // decision the flag used to have to infer.
 
1830
  : `Edit filter (${conditionCount === 1
1831
  ? "1 condition" : `${conditionCount} conditions`})`}
1832
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1833
  {/* ⛔⛔ MOUNTED ONLY WHILE OPEN, and that is what orders Escape correctly rather
1834
  than a flag inside the dialog. `useOverlayLayer` claims Escape as soon as it
1835
  runs and `ui/useEscapeClose` gives the key to the LAST entry pushed, so a
 
1845
  filters={showCellFilterValues(tree, readCell)}
1846
  onChange={(next) => setTree(keepCellFilterValues(next, readCell))}
1847
  statusValues={statusValues}
1848
+ readCell={readCell}
1849
  onClose={() => setFilterPopupOpen(false)}
1850
  />
1851
  )}
 
1923
  addr={`${addr} through ${selectedRelationship.label}`}
1924
  fields={relatedFields} filters={showCellFilterValues(relatedTree, readCell)}
1925
  statusValues={relatedStatusValues}
1926
+ readCell={readCell}
1927
  onChange={(filter) => {
1928
  setRelated({ via: related.via, filter: keepCellFilterValues(filter, readCell) });
1929
  setPreview("");
 
2238
  <fieldset className="sheet-scope sheet-drag">
2239
  <legend>When copied</legend>
2240
 
2241
+ {/* Hotfix 2026-09-24 (owner: "the whole Filter section is so confusing, if we need
2242
+ it for copy, it should always just fall under the When copied section"). A
2243
+ condition that reads a cell is how this cell moves when copied, so the cell
2244
+ lives here, as ONE input: filled means "read this cell", blank means the
2245
+ value typed in the filter. There is no separate source switch. */}
2246
+ {cellLeaves.map(({ node, indices, title }) => (
2247
+ <div key={indices.join(".")} className="sheet-step-driver">
2248
+ <span>{node.op === "within"
2249
+ ? `${title}: ${windowLabel(node.dateWindow).toLowerCase()} up to the date in cell ${node.valueRef!.ref}`
2250
+ : `${title} reads cell ${node.valueRef!.ref}`}</span>
2251
+ <label className="sheet-radio">
2252
+ <input type="checkbox" checked={node.valueRef!.locked === true}
2253
+ onChange={(e) => setTree(updateFilterValueLeaf(tree, indices, (leaf) => ({ ...leaf,
2254
+ valueRef: { ...leaf.valueRef!, locked: e.target.checked } })))} />
2255
+ <span>Keep this cell when copied</span>
2256
+ </label>
2257
+ </div>
2258
+ ))}
2259
+
2260
  {copySteps.map((step, index) => {
2261
  const isEnding = step.field === BINDING_ENDING_STEP;
2262
  const isPeriod = step.field === BINDING_PERIOD_STEP;
web/src/sheet/SheetGrid.tsx CHANGED
@@ -135,6 +135,7 @@ import {
135
  ERROR_REF, ERROR_VALUE, autoCloseFormula, cycleAnchorAtCaret, workbookFormulaGetter,
136
  } from "./formulaEval";
137
  import { colorForSlot } from "./refColors";
 
138
  import "../styles/wave52/sheet-grid.css";
139
  import "../styles/wave61/sheet-grid.css";
140
  // ⛔⛔ CONTRACT C8: ONE ESCAPE ARBITER FOR THE WHOLE APP, topmost wins. Nothing in this tree adds
@@ -2715,14 +2716,23 @@ export default function SheetGrid({
2715
  * its text to this same engine. One source string, one border map, one paint path
2716
  * (`paintRefBorder` further down) - there is no second outline mechanism to keep in step.
2717
  */
 
2718
  const formulaRefCells = useMemo(() => {
2719
  const out = new Map<string, { color: string; ref: number }>();
2720
  const source = formulaEdit
2721
  ? formulaEdit.draft
2722
  : (selected?.cell?.kind === "formula" ? (selected.cell.formula ?? "") : "");
2723
- if (!source) return out;
 
 
 
 
 
 
2724
  let refOrdinal = 0;
2725
- for (const ref of refsIn(source)) {
 
 
2726
  const ordinal = refOrdinal++; // Count every reference, including ranges skipped by the cap.
2727
  let c0 = colToIndex(ref.start.col);
2728
  let c1 = colToIndex(ref.end.col);
@@ -2745,7 +2755,17 @@ export default function SheetGrid({
2745
  }
2746
  }
2747
  return out;
2748
- }, [formulaEdit, selected]);
 
 
 
 
 
 
 
 
 
 
2749
 
2750
  /**
2751
  * ⭐⭐ W53-T02 / INSTRUCTION 18, VERBATIM — THE LIVE POINT-MODE PROPOSAL, AND IT IS THE ONE
@@ -5734,10 +5754,17 @@ export default function SheetGrid({
5734
  // deferred paint or the run clips against whichever cell happened to paint last.
5735
  const rowTop = rect.y;
5736
  const rowHeight = rect.height;
 
 
 
 
 
 
5737
  // Glide paints gridlines after drawCell. Deduplicate every participating cell into one
5738
  // owner run, then mask only its interior separators and redraw the text in the next frame.
5739
  queueSpillPaint(`${row}:${ownerCol}`, () => {
5740
  ctx.save();
 
5741
  ctx.beginPath();
5742
  ctx.rect(runLeft + 1, rowTop + 1, Math.max(0, runRight - runLeft - 2), rowHeight - 2);
5743
  ctx.clip();
 
135
  ERROR_REF, ERROR_VALUE, autoCloseFormula, cycleAnchorAtCaret, workbookFormulaGetter,
136
  } from "./formulaEval";
137
  import { colorForSlot } from "./refColors";
138
+ import { useHighlightedCellRefs } from "./refHighlight";
139
  import "../styles/wave52/sheet-grid.css";
140
  import "../styles/wave61/sheet-grid.css";
141
  // ⛔⛔ CONTRACT C8: ONE ESCAPE ARBITER FOR THE WHOLE APP, topmost wins. Nothing in this tree adds
 
2716
  * its text to this same engine. One source string, one border map, one paint path
2717
  * (`paintRefBorder` further down) - there is no second outline mechanism to keep in step.
2718
  */
2719
+ const externalRefs = useHighlightedCellRefs();
2720
  const formulaRefCells = useMemo(() => {
2721
  const out = new Map<string, { color: string; ref: number }>();
2722
  const source = formulaEdit
2723
  ? formulaEdit.draft
2724
  : (selected?.cell?.kind === "formula" ? (selected.cell.formula ?? "") : "");
2725
+ // Hotfix 2026-09-24 (owner: "ANYWHERE in the app ... the cell must be highlighted"): every
2726
+ // reference a mounted panel is asking about (`refHighlight.ts`) joins the SAME map, after the
2727
+ // formula's own, so it gets the outline and the repaint this map already has. A reference
2728
+ // naming another tab outlines nothing here.
2729
+ const external = externalRefs.flatMap((text) => refsIn(text).filter((ref) =>
2730
+ !ref.start.sheet || ref.start.sheet.toLowerCase() === tab.name.toLowerCase()));
2731
+ if (!source && external.length === 0) return out;
2732
  let refOrdinal = 0;
2733
+ const formulaRefs = source ? refsIn(source) : [];
2734
+ const slotBase = formulaRefs.reduce((top, ref) => Math.max(top, ref.colorIndex + 1), 0);
2735
+ for (const ref of [...formulaRefs, ...external.map((ref, i) => ({ ...ref, colorIndex: slotBase + i }))]) {
2736
  const ordinal = refOrdinal++; // Count every reference, including ranges skipped by the cap.
2737
  let c0 = colToIndex(ref.start.col);
2738
  let c1 = colToIndex(ref.end.col);
 
2755
  }
2756
  }
2757
  return out;
2758
+ }, [externalRefs, formulaEdit, selected, tab.name]);
2759
+
2760
+ // The newest reference a panel names is scrolled to, so a cell typed far off screen (R9997) is
2761
+ // seen being outlined rather than outlined out of sight.
2762
+ const lastExternalRef = externalRefs[externalRefs.length - 1] ?? "";
2763
+ useEffect(() => {
2764
+ const ref = refsIn(lastExternalRef)[0];
2765
+ if (!ref || (ref.start.sheet && ref.start.sheet.toLowerCase() !== tab.name.toLowerCase())) return;
2766
+ const viewRow = viewRowOf(ref.start.row - 1);
2767
+ if (viewRow >= 0) gridRef.current?.scrollTo(viewIndexOf(visCols, colToIndex(ref.start.col) - 1), viewRow);
2768
+ }, [lastExternalRef, tab.name, viewRowOf, visCols]);
2769
 
2770
  /**
2771
  * ⭐⭐ W53-T02 / INSTRUCTION 18, VERBATIM — THE LIVE POINT-MODE PROPOSAL, AND IT IS THE ONE
 
5754
  // deferred paint or the run clips against whichever cell happened to paint last.
5755
  const rowTop = rect.y;
5756
  const rowHeight = rect.height;
5757
+ // Hotfix 2026-09-24 (owner: "weeks left to end of year" in small font floating in the sheet,
5758
+ // "it keeps appearing when i zoom in zoom out"). Glide scales the canvas by the device pixel
5759
+ // ratio only between its own save and restore, so a paint run a frame later drew in the
5760
+ // UNSCALED space: at any browser zoom but 100% the run landed shrunk and offset, a ghost of
5761
+ // the label. The border paint above already carries the transform; this run now does too.
5762
+ const spillTransform = ctx.getTransform();
5763
  // Glide paints gridlines after drawCell. Deduplicate every participating cell into one
5764
  // owner run, then mask only its interior separators and redraw the text in the next frame.
5765
  queueSpillPaint(`${row}:${ownerCol}`, () => {
5766
  ctx.save();
5767
+ ctx.setTransform(spillTransform);
5768
  ctx.beginPath();
5769
  ctx.rect(runLeft + 1, rowTop + 1, Math.max(0, runRight - runLeft - 2), rowHeight - 2);
5770
  ctx.clip();
web/src/sheet/refHighlight.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Hotfix 2026-09-24, owner: "when a user ANYWHERE in the app must reference a cell, the cell must
2
+ // be highlighted automatically ... This is the immutable rule everywhere a cell must be referenced."
3
+ //
4
+ // ONE store, so the rule is a property of the door rather than of each panel. Any surface that
5
+ // asks a person for a cell reference calls `useCellRefHighlight(texts)` while it is mounted; the
6
+ // grid reads `useHighlightedCellRefs()` and paints those cells through the SAME outline path a
7
+ // formula's references use (`SheetGrid.tsx::formulaRefCells`), so there is no second border
8
+ // mechanism to keep in step. Unmounting a panel takes its outlines off with it.
9
+ import { useEffect, useSyncExternalStore } from "react";
10
+
11
+ const owners = new Map<number, readonly string[]>();
12
+ const listeners = new Set<() => void>();
13
+ let snapshot: readonly string[] = [];
14
+ let nextOwner = 1;
15
+
16
+ const publish = () => {
17
+ const seen = new Set<string>();
18
+ for (const texts of owners.values()) for (const text of texts) seen.add(text);
19
+ snapshot = [...seen];
20
+ for (const listener of listeners) listener();
21
+ };
22
+
23
+ /** Every cell reference some mounted surface is asking about, as typed (bare or sheet-qualified). */
24
+ export const useHighlightedCellRefs = (): readonly string[] => useSyncExternalStore(
25
+ (listener) => { listeners.add(listener); return () => { listeners.delete(listener); }; },
26
+ () => snapshot,
27
+ () => snapshot,
28
+ );
29
+
30
+ /** Register the cell references a surface is showing. Blank or partial text is simply ignored
31
+ * by the grid, which only outlines what parses as a reference. */
32
+ export const useCellRefHighlight = (texts: readonly string[]): void => {
33
+ const key = texts.map((text) => String(text ?? "").trim()).filter(Boolean).join("\u0000");
34
+ useEffect(() => {
35
+ if (!key) return;
36
+ const id = nextOwner++;
37
+ owners.set(id, key.split("\u0000"));
38
+ publish();
39
+ return () => { owners.delete(id); publish(); };
40
+ }, [key]);
41
+ };
web/src/ui/numberFormat.ts CHANGED
@@ -944,6 +944,16 @@ export function formatWithCode(
944
  const sections = compiled.sections;
945
 
946
  if (numeric === null) {
 
 
 
 
 
 
 
 
 
 
947
  // R14.
948
  if (sections.length === 4) return { text: renderTextSection(sections[3], raw) };
949
  if (sections.length >= 1 && atOnly(sections[0]) && !sections[0].general) {
 
944
  const sections = compiled.sections;
945
 
946
  if (numeric === null) {
947
+ // Hotfix 2026-09-24 (owner: rows 6 and 7 must read as dates). A date the sheet computed or
948
+ // typed is ISO text, the form every formula and binding speaks. Under a DATE code it is that
949
+ // day, painted by the date section, not a string that falls through to the text section.
950
+ const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(raw.trim());
951
+ if (iso && sections[0]?.hasDate) {
952
+ const at = Date.UTC(Number(iso[1]), Number(iso[2]) - 1, Number(iso[3]));
953
+ const painted = new Date(at).getUTCDate() === Number(iso[3])
954
+ ? renderDateSection(sections[0], Math.round((at - Date.UTC(1899, 11, 30)) / DAY_MS)) : null;
955
+ if (painted !== null) return { text: painted };
956
+ }
957
  // R14.
958
  if (sections.length === 4) return { text: renderTextSection(sections[3], raw) };
959
  if (sections.length >= 1 && atOnly(sections[0]) && !sections[0].general) {