fsanyoto commited on
Commit
025eb38
·
verified ·
1 Parent(s): 0e1e0f3

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "fa06797",
3
  "releases": [
4
  {
5
  "version": "v74",
 
1
  {
2
+ "current": "46c17ee",
3
  "releases": [
4
  {
5
  "version": "v74",
VERSION CHANGED
@@ -1 +1 @@
1
- fa06797
 
1
+ 46c17ee
api/main.py CHANGED
@@ -20,6 +20,7 @@ session's tenant claim resolves through `harness.runtime.get_runtime`, which is
20
  is the rule the ~30–80 MB/tenant target depends on — EXIT-0 measured the alternative at a ~0.6 GB
21
  commit FLOOR per tenant, duplicated within 2% per tenant, nothing shared.
22
  """
 
23
  import os
24
  import sys
25
  from pathlib import Path
@@ -273,7 +274,7 @@ def _view_revision_unverifiable(request: Request, exc: view_audit.RevisionUnveri
273
 
274
 
275
  @app.get("/api/health")
276
- def health():
277
  """Unauthenticated LIVENESS only — it must answer before anyone can sign in, so it may not
278
  reveal anything about the deployment beyond "the process is up". No version, no tenant list,
279
  no config: a health endpoint is the one URL every scanner finds first.
@@ -282,7 +283,17 @@ def health():
282
  release and "what is LIVE running" needed an answer). A build identifier tells an unauthenticated
283
  caller exactly which commit's known issues apply. It rides `GET /api/v1/settings` instead, behind
284
  a session — and the authoritative copy is the `VERSION` file in the Space repo, which
285
- `deploy_web.space_version()` reads without needing the app to be up at all."""
 
 
 
 
 
 
 
 
 
 
286
  return {"ok": True}
287
 
288
 
 
20
  is the rule the ~30–80 MB/tenant target depends on — EXIT-0 measured the alternative at a ~0.6 GB
21
  commit FLOOR per tenant, duplicated within 2% per tenant, nothing shared.
22
  """
23
+ import hmac
24
  import os
25
  import sys
26
  from pathlib import Path
 
274
 
275
 
276
  @app.get("/api/health")
277
+ def health(challenge: str = ""):
278
  """Unauthenticated LIVENESS only — it must answer before anyone can sign in, so it may not
279
  reveal anything about the deployment beyond "the process is up". No version, no tenant list,
280
  no config: a health endpoint is the one URL every scanner finds first.
 
283
  release and "what is LIVE running" needed an answer). A build identifier tells an unauthenticated
284
  caller exactly which commit's known issues apply. It rides `GET /api/v1/settings` instead, behind
285
  a session — and the authoritative copy is the `VERSION` file in the Space repo, which
286
+ `deploy_web.space_version()` reads without needing the app to be up at all.
287
+
288
+ W-265 adds a possession challenge for the deployer. It reveals only whether this process was
289
+ born after one high-entropy, single-deploy nonce was stamped; it never returns the nonce,
290
+ version, Space id, or configuration. A normal liveness request keeps the exact
291
+ ``{"ok": true}`` response shape.
292
+ """
293
+ if challenge:
294
+ expected = os.environ.get("AIOS_DEPLOY_NONCE") or ""
295
+ return {"ok": True,
296
+ "deployReady": bool(expected and hmac.compare_digest(challenge, expected))}
297
  return {"ok": True}
298
 
299
 
api/routes_odoo_tables.py CHANGED
@@ -1619,6 +1619,12 @@ def _relation_leg_ids(session, source, source_ids, entry):
1619
  source_col, target_col = (inverse, "pid") if reverse else ("pid", inverse)
1620
  source_rows = _relation_rows(session, source, [source_col], ids=source_ids)
1621
  values = {str(row[source_col]) for row in source_rows if row.get(source_col) not in (None, "")}
 
 
 
 
 
 
1622
  if (manual and not reverse) or (inverse and reverse):
1623
  values = set().union(*(_relation_cell_ids(row.get(source_col)) for row in source_rows))
1624
  target_col = "pid"
@@ -1677,6 +1683,8 @@ def _relation_target_ids(session, target, related):
1677
  first, middle, last = _related_path_legs(session, source, entry, entries)
1678
  legs = [(source, first), (middle, last)]
1679
  for table, leg in legs:
 
 
1680
  if not _may_open(session, leg["target"]):
1681
  raise err(403, "forbidden_table",
1682
  f"the relation ends at '{_relation_label(leg['target'])}', which your account cannot open")
 
1619
  source_col, target_col = (inverse, "pid") if reverse else ("pid", inverse)
1620
  source_rows = _relation_rows(session, source, [source_col], ids=source_ids)
1621
  values = {str(row[source_col]) for row in source_rows if row.get(source_col) not in (None, "")}
1622
+ # A column-keyed edge cannot fall back to the wire record id. In particular,
1623
+ # product_data.pid is a stable hash while sale_order_line.product_id is an Odoo
1624
+ # identity. Treating a missing/hidden/blank source value as an empty match would
1625
+ # turn "the join input is unavailable" into the business claim "no related rows".
1626
+ if source_col != relations.IDENTITY_COL and not values:
1627
+ raise err(400, "unknown_relation", relations.unresolvable_source_refusal(source, entry))
1628
  if (manual and not reverse) or (inverse and reverse):
1629
  values = set().union(*(_relation_cell_ids(row.get(source_col)) for row in source_rows))
1630
  target_col = "pid"
 
1683
  first, middle, last = _related_path_legs(session, source, entry, entries)
1684
  legs = [(source, first), (middle, last)]
1685
  for table, leg in legs:
1686
+ if not leg.get("served"):
1687
+ raise err(409, "relation_not_served", relations.unserved_target_refusal(leg))
1688
  if not _may_open(session, leg["target"]):
1689
  raise err(403, "forbidden_table",
1690
  f"the relation ends at '{_relation_label(leg['target'])}', which your account cannot open")
platform/core/sheet_binding.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure document cleaners shared by Sheet storage and Sheet query resolution.
2
+
3
+ These functions decide only what binding metadata may be stored. They do not resolve data,
4
+ permissions, or SQL. Keeping them in core lets the workbook document validate view bindings
5
+ without importing the higher ``modules.sheet`` layer.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import datetime
11
+ import re
12
+
13
+ from core import windows as W
14
+
15
+
16
+ PERIOD_UNITS = ("day", "week", "month", "quarter", "year")
17
+ PERIOD_START = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
18
+ PERIOD_DAY = re.compile(r"^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$")
19
+ PERIOD_REF = re.compile(r"^[A-Z]{1,3}[1-9][0-9]{0,6}$")
20
+ DRAG_ACROSS = ("period", "none")
21
+ DRAG_DOWN_NONE = "none"
22
+
23
+ _MESSAGES = {
24
+ "period_invalid": "{subject} is not a period this cell can use. Choose a valid start for the selected period unit.",
25
+ "ending_invalid": "Ending {subject} cannot be used. Choose a valid ending date.",
26
+ "ending_not_supported": "{subject} does not support an Ending. Choose year to date, last year to date, this month or this quarter.",
27
+ "ending_cell_unreadable": "Ending from cell {subject} cannot be read. Use a cell containing a date in YYYY-MM-DD format.",
28
+ }
29
+
30
+
31
+ class BindingMetadataRefusal(Exception):
32
+ """A structured metadata refusal which each caller translates to its route exception."""
33
+
34
+ def __init__(self, code: str, subject: str = "", detail: str = ""):
35
+ super().__init__(code)
36
+ self.code = code
37
+ self.subject = str(subject or "")
38
+ self.detail = str(detail or "")
39
+ self.message = _MESSAGES.get(code, "{subject} could not be answered.").format(
40
+ subject=self.subject or "this database")
41
+ if code in ("ending_invalid", "ending_cell_unreadable") and self.detail:
42
+ verb = "used" if code == "ending_invalid" else "read"
43
+ self.message = self.message.replace(
44
+ f"cannot be {verb}.", f"cannot be {verb} because {self.detail}")
45
+
46
+
47
+ def clean_period(raw):
48
+ """Return one canonical Sheet period, or ``None`` when no window was named."""
49
+ if not isinstance(raw, dict):
50
+ return None
51
+ out = {}
52
+
53
+ if "ending" in raw:
54
+ window = W.normalize(raw.get("window"))
55
+ kind = (window or {}).get("kind")
56
+ if kind not in W.TO_DATE_KINDS:
57
+ raise BindingMetadataRefusal("ending_not_supported", kind or "This period")
58
+ ending = raw["ending"]
59
+ mode = ending.get("kind") if isinstance(ending, dict) else None
60
+ if mode not in W.ENDING_KINDS:
61
+ raise BindingMetadataRefusal("ending_invalid", str(mode or "selection"),
62
+ "the choice is unknown.")
63
+ step = raw.get("endingStep", W.ending_step_default(kind))
64
+ offset = raw.get("endingOffset", 0)
65
+ if (step not in W.ENDING_STEPS or isinstance(offset, bool)
66
+ or not isinstance(offset, int) or offset < 0):
67
+ raise BindingMetadataRefusal("ending_invalid", "step",
68
+ "its size or copy offset is invalid.")
69
+ out = {"window": window, "ending": {"kind": mode}, "endingStep": step}
70
+ if offset:
71
+ out["endingOffset"] = offset
72
+ if raw.get("locked") is True:
73
+ out["locked"] = True
74
+ if mode == "fixed":
75
+ day = W.ending_date(ending.get("date"))
76
+ if day is None:
77
+ raise BindingMetadataRefusal("ending_invalid", "fixed date",
78
+ "it is not a real ISO date.")
79
+ out["ending"]["date"] = day
80
+ if mode == "n_before_today":
81
+ n, unit = ending.get("n"), ending.get("unit")
82
+ if isinstance(n, bool) or not isinstance(n, int) or not 1 <= n <= W.MAX_N:
83
+ raise BindingMetadataRefusal(
84
+ "ending_invalid", "number", f"it must be a whole number from 1 to {W.MAX_N}.")
85
+ if unit not in W.ENDING_STEPS:
86
+ raise BindingMetadataRefusal("ending_invalid", "unit", "the unit is unknown.")
87
+ out["ending"].update({"n": n, "unit": unit})
88
+ if mode == "cell":
89
+ ref = str(raw.get("ref") or "").strip()
90
+ if not re.fullmatch(
91
+ r"(?:(?:'([^']|'')+'|[^'!]+)!)?\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6}", ref):
92
+ raise BindingMetadataRefusal("ending_cell_unreadable", ref or "(blank)",
93
+ "its reference is invalid.")
94
+ out["ref"] = ref
95
+ return out
96
+
97
+ unit = str(raw.get("unit") or "").strip().lower()
98
+ if unit:
99
+ if unit not in PERIOD_UNITS:
100
+ raise BindingMetadataRefusal("period_invalid", unit)
101
+ out["unit"] = unit
102
+
103
+ start = str(raw.get("start") or "").strip()
104
+ if start:
105
+ pattern = PERIOD_DAY if unit in ("day", "week") else PERIOD_START
106
+ if not pattern.fullmatch(start):
107
+ raise BindingMetadataRefusal("period_invalid", start)
108
+ if unit in ("day", "week"):
109
+ try:
110
+ day = datetime.date.fromisoformat(start)
111
+ except ValueError as exc:
112
+ raise BindingMetadataRefusal("period_invalid", start) from exc
113
+ if unit == "week":
114
+ start = (day - datetime.timedelta(days=day.weekday())).isoformat()
115
+ out["start"] = start
116
+
117
+ if raw.get("frozen") is True:
118
+ dates = {}
119
+ for key in ("from", "to"):
120
+ value = str(raw.get(key) or "").strip()
121
+ if not PERIOD_DAY.fullmatch(value):
122
+ raise BindingMetadataRefusal("period_invalid", value or key)
123
+ dates[key] = value
124
+ if dates["to"] < dates["from"]:
125
+ raise BindingMetadataRefusal("period_invalid", dates["to"])
126
+ out.update({"frozen": True, **dates})
127
+
128
+ if raw.get("locked") is True:
129
+ out["locked"] = True
130
+ ref = str(raw.get("ref") or "").strip().upper().replace("$", "")
131
+ if ref:
132
+ if not PERIOD_REF.match(ref):
133
+ raise BindingMetadataRefusal("period_invalid", ref)
134
+ if not out.get("frozen"):
135
+ out["ref"] = ref
136
+ if (raw.get("window") is not None and "unit" not in out and "start" not in out
137
+ and not out.get("frozen")):
138
+ out["window"] = raw["window"]
139
+ if not ({"start", "window", "ref", "frozen"} & set(out)):
140
+ return None
141
+ return out
142
+
143
+
144
+ def clean_on_drag(raw):
145
+ """Return canonical two-axis drag metadata, or ``None`` when absent."""
146
+ if not isinstance(raw, dict):
147
+ return None
148
+ across = str(raw.get("across") or "").strip().lower()
149
+ if across not in DRAG_ACROSS:
150
+ across = "period"
151
+ down = raw.get("down")
152
+ if isinstance(down, dict) and str(down.get("field") or "").strip():
153
+ out_down = {"field": str(down["field"]).strip()}
154
+ if down.get("mode") in ("value", "presence", "member"):
155
+ out_down["mode"] = down["mode"]
156
+ else:
157
+ out_down = DRAG_DOWN_NONE
158
+ if isinstance(raw.get("steps"), list):
159
+ steps = []
160
+ for step in raw["steps"]:
161
+ if not isinstance(step, dict):
162
+ continue
163
+ field = step.get("field")
164
+ if not isinstance(field, str) or not field.strip() or step.get("axis") not in ("across", "down"):
165
+ continue
166
+ if "size" in step and step["size"] not in ("day", "week", "month", "quarter", "year"):
167
+ continue
168
+ cleaned = {"field": field.strip(), "axis": step["axis"]}
169
+ if step.get("mode") in ("value", "presence", "member"):
170
+ cleaned["mode"] = step["mode"]
171
+ if "size" in step:
172
+ cleaned["size"] = step["size"]
173
+ steps.append(cleaned)
174
+ first_down = next((step for step in steps if step["axis"] == "down"), None)
175
+ out_down = ({key: first_down[key] for key in ("field", "mode") if key in first_down}
176
+ if first_down else DRAG_DOWN_NONE)
177
+ across = ("period" if any(step["axis"] == "across" and step["field"]
178
+ in ("__period", "__ending") for step in steps) else "none")
179
+ return {"across": across, "down": out_down, "steps": steps}
180
+ return {"across": across, "down": out_down}
platform/core/sheets.py CHANGED
@@ -63,6 +63,12 @@ import re
63
  import uuid
64
  from datetime import datetime, timezone
65
 
 
 
 
 
 
 
66
  #: C1's document key. `<id>` is the workbook id.
67
  WORKBOOK_KEY_PREFIX = "sheet_workbook_"
68
 
@@ -731,14 +737,13 @@ def clean_view_binding(raw):
731
  for key in ("filter", "block"):
732
  if key in raw:
733
  out[key] = _document_object(raw[key], "view_binding_" + key)
734
- # W62 C2: reuse only the existing pure metadata cleaners, never the metric binding validator.
735
  if "period" in raw or "onDrag" in raw:
736
- from modules import sheet as sheet_mod
737
- for key, cleaner in (("period", sheet_mod.clean_period), ("onDrag", sheet_mod.clean_on_drag)):
738
  if key in raw:
739
  try:
740
  value = cleaner(_json_safe(copy.deepcopy(raw[key]), "view binding " + key))
741
- except sheet_mod.SheetRefusal as exc:
742
  raise SheetRefusal(exc.code, exc.message) from exc
743
  if value is not None:
744
  out[key] = value
 
63
  import uuid
64
  from datetime import datetime, timezone
65
 
66
+ from core.sheet_binding import (
67
+ BindingMetadataRefusal,
68
+ clean_on_drag as clean_binding_on_drag,
69
+ clean_period as clean_binding_period,
70
+ )
71
+
72
  #: C1's document key. `<id>` is the workbook id.
73
  WORKBOOK_KEY_PREFIX = "sheet_workbook_"
74
 
 
737
  for key in ("filter", "block"):
738
  if key in raw:
739
  out[key] = _document_object(raw[key], "view_binding_" + key)
740
+ # W62 C2: one lower-layer metadata cleaner serves both view and metric bindings.
741
  if "period" in raw or "onDrag" in raw:
742
+ for key, cleaner in (("period", clean_binding_period), ("onDrag", clean_binding_on_drag)):
 
743
  if key in raw:
744
  try:
745
  value = cleaner(_json_safe(copy.deepcopy(raw[key]), "view binding " + key))
746
+ except BindingMetadataRefusal as exc:
747
  raise SheetRefusal(exc.code, exc.message) from exc
748
  if value is not None:
749
  out[key] = value
platform/core/windows.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """core/windows.py — the DATE WINDOW vocabulary (CG-7, owner item 2, 2026-07-26).
2
+
3
+ A filter condition on a measure reads:
4
+
5
+ Where [Sales] [in the last 90 days] [>] [5,000]
6
+
7
+ The middle bracket is this module. It turns a window SPEC — a small JSON object a saved view can
8
+ persist — into a concrete `(date_from, date_to)` pair of ISO dates.
9
+
10
+ WHY IT IS ITS OWN MODULE, AND WHY IT TAKES `today` AS AN ARGUMENT
11
+ -----------------------------------------------------------------------------------------------
12
+ Two engines must agree on what "this quarter" means: this one (which compiles the SQL) and
13
+ `customer-grid/windows.ts` (which renders the label the user reads and the bounds the client
14
+ engine would use). If they disagree by one day, the grid shows a number the label denies, and
15
+ nothing errors. `aios-web/verify_windows.py` holds them in lock-step over a fixed set of probe
16
+ dates, exactly as verify_filter_engine.py does for the filter tree.
17
+
18
+ `today` is a PARAMETER, never `date.today()` read inside. Three reasons, all learned:
19
+ - a gate cannot compare two engines on "now" — the two runs are milliseconds apart and land on
20
+ different sides of midnight roughly once every few thousand runs, which is the worst kind of
21
+ flake because it looks like a real divergence
22
+ - a window resolved during a request must not shift between the count query and the row query
23
+ - the tenant's day boundary is the tenant's, not the server's
24
+
25
+ DESIGN NOTES THAT ARE EASY TO GET WRONG
26
+ -----------------------------------------------------------------------------------------------
27
+ - Bounds are INCLUSIVE at both ends and are DATES, not timestamps. `store_query` casts both
28
+ sides to TIMESTAMP and appends 23:59:59 to the upper bound, so a bare date is correct there;
29
+ the client compares the 10-char ISO prefix, so a bare date is correct there too.
30
+ - "Last N days" INCLUDES today. Airtable's "the past week" means the last 7 days up to and
31
+ including now, not the 7 days before yesterday. Off-by-one here silently drops today's
32
+ orders from every "recent" filter — invisible until someone asks why a sale they just
33
+ entered is missing.
34
+ - Week starts MONDAY (ISO 8601). Stated rather than defaulted: Python's weekday() is
35
+ Monday=0 and JavaScript's getDay() is Sunday=0, so the two engines disagree unless one of
36
+ them is explicitly corrected. That correction is the single most likely divergence in this
37
+ file, and the gate probes a Sunday and a Monday for exactly that reason.
38
+ - A `custom` window with only one bound is legal and means open-ended on the other side.
39
+ - An UNRESOLVABLE window returns None rather than a default. A window that quietly becomes
40
+ "all time" would widen a filter while still reporting an authoritative count.
41
+ The historical ``harness.windows`` import remains a compatibility re-export. The vocabulary
42
+ lives in core because workbook document validation also consumes it and core must never import
43
+ upward from harness.
44
+ """
45
+ import datetime as _dt
46
+ import re
47
+ import math
48
+
49
+ #: Every window kind the UI may offer. Mirrors WINDOW_KINDS in customer-grid/windows.ts;
50
+ #: verify_windows.py asserts the two lists are identical, because a kind the client can emit and
51
+ #: the server cannot resolve is a filter that silently stops narrowing.
52
+ WINDOW_KINDS = (
53
+ "all_time",
54
+ "today",
55
+ "yesterday",
56
+ "this_week",
57
+ "last_week",
58
+ "this_month",
59
+ "last_month",
60
+ "this_quarter",
61
+ "last_quarter",
62
+ "this_year",
63
+ "last_year",
64
+ "ytd",
65
+ "ytd_last_year",
66
+ "ltm",
67
+ "past_week",
68
+ "past_month",
69
+ "past_year",
70
+ "last_n_days",
71
+ "next_n_days",
72
+ "custom",
73
+ )
74
+
75
+ #: Kinds that carry an integer `n`.
76
+ N_KINDS = frozenset({"last_n_days", "next_n_days"})
77
+
78
+ #: How each kind reads in a sentence. The UI renders these; they are here so the label and the
79
+ #: arithmetic cannot drift apart in the one place a user would never think to check.
80
+ WINDOW_LABELS = {
81
+ "all_time": "all time",
82
+ "today": "today",
83
+ "yesterday": "yesterday",
84
+ "this_week": "this week",
85
+ "last_week": "last week",
86
+ "this_month": "this month",
87
+ "last_month": "last month",
88
+ "this_quarter": "this quarter",
89
+ "last_quarter": "last quarter",
90
+ "this_year": "this year",
91
+ "last_year": "last year",
92
+ "ytd": "year to date",
93
+ # "last year to date" (LYTD), not "year to date, last year": the longer phrasing CLIPPED to
94
+ # "year to date, last ye" in the 146px window select — and this vocabulary is CLOSED, so
95
+ # the rule for it is that it stays readable rather than that it fits. Seen in a live
96
+ # screenshot of the owner's own comparison; every assertion in that run was green.
97
+ "ytd_last_year": "last year to date",
98
+ "ltm": "the last 12 months",
99
+ "past_week": "the past week",
100
+ "past_month": "the past month",
101
+ "past_year": "the past year",
102
+ "last_n_days": "the last {n} days",
103
+ "next_n_days": "the next {n} days",
104
+ "custom": "a custom range",
105
+ }
106
+
107
+ MAX_N = 3650 # ten years; a bound, not a business rule
108
+
109
+ # --- the DATE-VALUE anchors (owner item 3, 2026-07-26) ----------------------------------------
110
+ # The second half of a date CONDITION, as distinct from a measure's window:
111
+ #
112
+ # Where [Last order] [is before] [one month ago]
113
+ # ^ op ^ THIS
114
+ #
115
+ # A window answers "over what period do I sum"; an anchor answers "which single date am I
116
+ # comparing against". Both live in this module for one reason: they are the same two-engine
117
+ # contract, resolved from the same `today`, and a gate that holds one in lock-step and not the
118
+ # other would leave half the sentence free to drift.
119
+
120
+ #: Anchor modes, in the order the picker offers them. `exact` is the historical behaviour — a
121
+ #: rule with NO mode is an `exact` rule whose value is an ISO date, which is what every view
122
+ #: saved before this change carries.
123
+ ANCHOR_MODES = (
124
+ "today",
125
+ "yesterday",
126
+ "one_week_ago",
127
+ "one_month_ago",
128
+ "n_days_ago",
129
+ "exact",
130
+ )
131
+
132
+ #: Modes that carry NO value. ⚠ This set is load-bearing far outside this module: a rule whose
133
+ #: value is blank normally reads as INACTIVE, and an inactive rule is IGNORED — which WIDENS the
134
+ #: result under a count nobody would doubt. Every activeness check (`isRuleActive` in TS,
135
+ #: `filter_sql.is_rule_active`, and the validator's value handling) has to know these four are
136
+ #: active with an empty value.
137
+ ANCHOR_VALUE_FREE = frozenset({"today", "yesterday", "one_week_ago", "one_month_ago"})
138
+
139
+ ANCHOR_LABELS = {
140
+ "today": "today",
141
+ "yesterday": "yesterday",
142
+ "one_week_ago": "one week ago",
143
+ "one_month_ago": "one month ago",
144
+ "n_days_ago": "{n} days ago",
145
+ "exact": "an exact date",
146
+ }
147
+
148
+
149
+ def _iso(d):
150
+ return d.isoformat()
151
+
152
+
153
+ def _month_start(d):
154
+ return d.replace(day=1)
155
+
156
+
157
+ def _month_end(d):
158
+ return _next_month(d.replace(day=1)) - _dt.timedelta(days=1)
159
+
160
+
161
+ def _next_month(d):
162
+ return (d.replace(day=28) + _dt.timedelta(days=4)).replace(day=1)
163
+
164
+
165
+ def _quarter_start(d):
166
+ return _dt.date(d.year, 3 * ((d.month - 1) // 3) + 1, 1)
167
+
168
+
169
+ def _days_in_month(y, m):
170
+ return (_dt.date(y + (m == 12), 1 if m == 12 else m + 1, 1) - _dt.timedelta(days=1)).day
171
+
172
+
173
+ def _shift_months(d, n):
174
+ """`d` moved `n` months, CLAMPING the day to the target month's length.
175
+
176
+ Jan 31 back one month is Dec 31, but Mar 31 back one month is Feb 28 (or 29) — there is no
177
+ Feb 31 to land on. Both engines must clamp identically or "the past month" differs by up to
178
+ three days for a third of the calendar; the gate probes a 31st and a leap day for exactly it.
179
+ """
180
+ total = (d.year * 12 + (d.month - 1)) + n
181
+ y, m = divmod(total, 12)
182
+ m += 1
183
+ return _dt.date(y, m, min(d.day, _days_in_month(y, m)))
184
+
185
+
186
+ def _parse_date(v):
187
+ """Accept 'YYYY-MM-DD' (and tolerate a longer ISO timestamp by taking its date part)."""
188
+ if isinstance(v, _dt.date):
189
+ return v
190
+ s = str(v or "").strip()[:10]
191
+ if not s:
192
+ return None
193
+ try:
194
+ return _dt.date.fromisoformat(s)
195
+ except ValueError:
196
+ return None
197
+
198
+
199
+ # Sheet Ending metadata belongs to the binding period, never to a window spec.
200
+ ENDING_KINDS = ("today", "yesterday", "last_week", "last_month", "last_quarter",
201
+ "last_year", "fixed", "cell", "n_before_today")
202
+ ENDING_LABELS = dict(zip(ENDING_KINDS, ("Today (live)", "Yesterday", "End of last week",
203
+ "End of last month", "End of last quarter", "End of last year", "A fixed date", "From a cell",
204
+ "N periods before today")))
205
+ TO_DATE_KINDS = ("ytd", "ytd_last_year", "this_month", "this_quarter")
206
+ ENDING_STEPS = ("day", "week", "month", "quarter", "year")
207
+
208
+
209
+ def ending_step_default(kind):
210
+ return "quarter" if kind == "this_quarter" else "month"
211
+
212
+
213
+ def ending_date(value):
214
+ """A real ISO day only. No truncation, calendar rollover, or blank fallback."""
215
+ if not isinstance(value, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value.strip()):
216
+ return None
217
+ d = _parse_date(value)
218
+ return _iso(d) if d else None
219
+
220
+
221
+ def resolve_ending(mode, value, today, step="month", offset=0, n=0, unit="month"):
222
+ """Inclusive ending date; cell values are supplied by the caller's trusted read."""
223
+ d = _parse_date(today)
224
+ if d is None:
225
+ raise ValueError("Ending needs a valid today date")
226
+ if mode not in ENDING_KINDS or step not in ENDING_STEPS:
227
+ return None
228
+ if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:
229
+ return None
230
+ if mode in ("fixed", "cell"):
231
+ parsed = ending_date(value)
232
+ if parsed is None:
233
+ return None
234
+ end = _parse_date(parsed)
235
+ elif mode == "n_before_today":
236
+ if (isinstance(n, bool) or not isinstance(n, int) or not 1 <= n <= MAX_N
237
+ or unit not in ENDING_STEPS):
238
+ return None
239
+ try:
240
+ if unit in ("day", "week"):
241
+ end = d - _dt.timedelta(days=n * (7 if unit == "week" else 1))
242
+ else:
243
+ end = _shift_months(d, -n * {"month": 1, "quarter": 3, "year": 12}[unit])
244
+ except (ValueError, OverflowError):
245
+ return None
246
+ elif mode == "today":
247
+ end = d
248
+ elif mode == "yesterday":
249
+ end = d - _dt.timedelta(days=1)
250
+ elif mode == "last_week":
251
+ end = d - _dt.timedelta(days=d.weekday() + 1)
252
+ elif mode == "last_month":
253
+ end = _month_start(d) - _dt.timedelta(days=1)
254
+ elif mode == "last_quarter":
255
+ end = _quarter_start(d) - _dt.timedelta(days=1)
256
+ else:
257
+ end = _dt.date(d.year - 1, 12, 31)
258
+ try:
259
+ if step in ("day", "week"):
260
+ end += _dt.timedelta(days=offset * (7 if step == "week" else 1))
261
+ else:
262
+ end = _shift_months(end, offset * {"month": 1, "quarter": 3, "year": 12}[step])
263
+ return _iso(end)
264
+ except (ValueError, OverflowError):
265
+ return None
266
+
267
+
268
+ def ending_cell_date(value, date_system="1900"):
269
+ """Sheet dates may be ISO days or Excel serials in the workbook's declared epoch."""
270
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
271
+ return ending_date(value)
272
+ if not math.isfinite(value) or value < (0 if date_system == "1904" else 1):
273
+ return None
274
+ days = math.floor(value)
275
+ if date_system != "1904" and days == 60:
276
+ return None # Excel's fictional February 29, 1900 is not a calendar date.
277
+ epoch = (_dt.date(1904, 1, 1) if date_system == "1904" else
278
+ _dt.date(1899, 12, 31) if days < 60 else _dt.date(1899, 12, 30))
279
+ try:
280
+ return _iso(epoch + _dt.timedelta(days=days))
281
+ except (ValueError, OverflowError):
282
+ return None
283
+
284
+
285
+ def ending_bounds(kind, mode, value, today, step="month", offset=0, n=0, unit="month"):
286
+ """Keep the kind's own start. An ending before it refuses instead of reversing bounds."""
287
+ if kind not in TO_DATE_KINDS:
288
+ return None
289
+ end = resolve_ending(mode, value, today, step, offset, n, unit)
290
+ if end is None:
291
+ return None
292
+ start = resolve({"kind": kind}, today)[0]
293
+ return (start, end) if start <= end else None
294
+
295
+
296
+ def normalize(spec):
297
+ """Coerce an untrusted window spec to `{kind, n?, from?, to?}` or None.
298
+
299
+ Fail-closed on the KIND (an unknown kind is not a window), tolerant on the rest — the same
300
+ split `clean_filter_tree` uses, so one malformed window cannot cost a user their saved view.
301
+ """
302
+ if not isinstance(spec, dict):
303
+ return None
304
+ kind = spec.get("kind")
305
+ if kind not in WINDOW_KINDS:
306
+ return None
307
+ out = {"kind": kind}
308
+ if kind in N_KINDS:
309
+ try:
310
+ n = int(spec.get("n"))
311
+ except (TypeError, ValueError):
312
+ return None
313
+ if n < 1 or n > MAX_N:
314
+ return None
315
+ out["n"] = n
316
+ if kind == "custom":
317
+ f, t = _parse_date(spec.get("from")), _parse_date(spec.get("to"))
318
+ if f is None and t is None:
319
+ return None # a custom range with no bounds is not a window
320
+ if f is not None and t is not None and f > t:
321
+ f, t = t, f # the builder cannot enforce order; the engine can
322
+ if f is not None:
323
+ out["from"] = _iso(f)
324
+ if t is not None:
325
+ out["to"] = _iso(t)
326
+ return out
327
+
328
+
329
+ def resolve(spec, today):
330
+ """Window spec + the tenant's today -> `(date_from, date_to)`, both inclusive ISO dates.
331
+
332
+ Either side may be None, meaning open-ended. Returns None when the spec is not a window at
333
+ all — callers MUST treat that as "this condition cannot be evaluated" and refuse, never as
334
+ "no window", which would silently widen the result to all time.
335
+ """
336
+ spec = normalize(spec)
337
+ if spec is None:
338
+ return None
339
+ kind = spec["kind"]
340
+ d = _parse_date(today)
341
+ if d is None:
342
+ raise ValueError("resolve() needs an explicit `today`; see this module's docstring")
343
+
344
+ if kind == "all_time":
345
+ return (None, None)
346
+ if kind == "today":
347
+ return (_iso(d), _iso(d))
348
+ if kind == "yesterday":
349
+ y = d - _dt.timedelta(days=1)
350
+ return (_iso(y), _iso(y))
351
+
352
+ # ISO 8601: the week starts MONDAY. Python's weekday() is already Monday=0; the TS mirror
353
+ # has to correct getDay(), which is Sunday=0. The gate probes both a Sunday and a Monday.
354
+ if kind == "this_week":
355
+ start = d - _dt.timedelta(days=d.weekday())
356
+ return (_iso(start), _iso(start + _dt.timedelta(days=6)))
357
+ if kind == "last_week":
358
+ start = d - _dt.timedelta(days=d.weekday() + 7)
359
+ return (_iso(start), _iso(start + _dt.timedelta(days=6)))
360
+
361
+ if kind == "this_month":
362
+ return (_iso(_month_start(d)), _iso(_month_end(d)))
363
+ if kind == "last_month":
364
+ prev = _month_start(d) - _dt.timedelta(days=1)
365
+ return (_iso(_month_start(prev)), _iso(prev))
366
+
367
+ if kind == "this_quarter":
368
+ qs = _quarter_start(d)
369
+ qe = _month_end(_dt.date(qs.year, qs.month + 2, 1))
370
+ return (_iso(qs), _iso(qe))
371
+ if kind == "last_quarter":
372
+ prev_end = _quarter_start(d) - _dt.timedelta(days=1)
373
+ qs = _quarter_start(prev_end)
374
+ return (_iso(qs), _iso(prev_end))
375
+
376
+ if kind == "this_year":
377
+ return (_iso(_dt.date(d.year, 1, 1)), _iso(_dt.date(d.year, 12, 31)))
378
+ if kind == "last_year":
379
+ return (_iso(_dt.date(d.year - 1, 1, 1)), _iso(_dt.date(d.year - 1, 12, 31)))
380
+ if kind == "ytd":
381
+ # year-to-date ENDS TODAY, unlike this_year which runs to Dec 31. The distinction is the
382
+ # whole reason both exist: comparing "this year" against last year double-counts the
383
+ # months that have not happened yet.
384
+ return (_iso(_dt.date(d.year, 1, 1)), _iso(d))
385
+ if kind == "ytd_last_year":
386
+ # SAME PERIOD last year — Jan 1 LY through today's month/day LY. This is the honest
387
+ # partner of `ytd`, and it is not a nicety: it mirrors `core.periods.ytd_last_year`
388
+ # EXACTLY (including the Feb 29 -> Feb 28 clamp), which is what `pool()` computes the
389
+ # `revenue_ly` column from. `Sales[ytd] < Sales[ytd_last_year]` therefore reproduces the
390
+ # retired `at_risk > 0` condition rather than approximating it. Comparing `ytd` against
391
+ # `last_year` instead would pit seven months against twelve.
392
+ return (_iso(_dt.date(d.year - 1, 1, 1)), _iso(_shift_months(d, -12)))
393
+ if kind == "ltm":
394
+ # the last twelve months INCLUDING today: 365 days back, both ends inclusive
395
+ return (_iso(d - _dt.timedelta(days=364)), _iso(d))
396
+
397
+ # "The past week/month/year" are ROLLING and end TODAY — Airtable's wording, and NOT the
398
+ # calendar kinds above: `last_week` is the previous Monday-Sunday, `past_week` is the seven
399
+ # days ending today. Both are offered because a user means different things by them, and
400
+ # picking one to serve both would silently answer the other question.
401
+ # past_week = the same rule as last_n_days(7) — one period back, PLUS ONE DAY, so today
402
+ # is included and the span is exactly 7 days rather than 8.
403
+ # past_year agrees with `ltm` except across a leap day, where the calendar shift keeps the
404
+ # same month/day and the 364-day subtraction cannot.
405
+ if kind == "past_week":
406
+ return (_iso(d - _dt.timedelta(days=6)), _iso(d))
407
+ if kind == "past_month":
408
+ return (_iso(_shift_months(d, -1) + _dt.timedelta(days=1)), _iso(d))
409
+ if kind == "past_year":
410
+ return (_iso(_shift_months(d, -12) + _dt.timedelta(days=1)), _iso(d))
411
+
412
+ if kind == "last_n_days":
413
+ # INCLUSIVE of today — "the last 7 days" is today and the 6 before it, not the 7 before
414
+ # yesterday. Getting this wrong drops today's orders from every recent-activity filter.
415
+ return (_iso(d - _dt.timedelta(days=spec["n"] - 1)), _iso(d))
416
+ if kind == "next_n_days":
417
+ return (_iso(d), _iso(d + _dt.timedelta(days=spec["n"] - 1)))
418
+
419
+ if kind == "custom":
420
+ return (spec.get("from"), spec.get("to"))
421
+ raise AssertionError(f"unhandled window kind {kind!r}") # unreachable; WINDOW_KINDS is closed
422
+
423
+
424
+ def label(spec):
425
+ """How a window reads in the condition sentence ('in the last 90 days')."""
426
+ spec = normalize(spec)
427
+ if spec is None:
428
+ return "an invalid range"
429
+ return WINDOW_LABELS[spec["kind"]].format(n=spec.get("n"))
430
+
431
+
432
+ def resolve_anchor(mode, value, today):
433
+ """A date condition's right-hand side -> ONE inclusive ISO date, or None.
434
+
435
+ `mode` is an entry of ANCHOR_MODES; None/'' means `exact`, which is what every view saved
436
+ before anchors existed carries (op + an ISO date in `value`). `value` supplies the number for
437
+ `n_days_ago` and the date for `exact`, and is ignored by the four value-free modes.
438
+
439
+ Returns None when the anchor cannot be resolved — an unknown mode, a non-numeric N, a value
440
+ that is not a date. The caller must then treat the CONDITION as unanswerable and match
441
+ nothing. It must NOT fall through to "no condition": that widens the result while the count
442
+ beside it still looks authoritative, which is the whole reason this returns None rather than
443
+ a best guess (same contract as `resolve()` above).
444
+
445
+ `n_days_ago` accepts n = 0 where a WINDOW requires n >= 1. A zero-day window is empty and
446
+ could only be a mistake; "0 days ago" is today, which is a date a person can mean.
447
+ """
448
+ m = mode or "exact"
449
+ if m not in ANCHOR_MODES:
450
+ return None
451
+ d = _parse_date(today)
452
+ if d is None:
453
+ raise ValueError("resolve_anchor() needs an explicit `today`; see this module's "
454
+ "docstring on why the clock is never read here")
455
+ if m == "today":
456
+ return _iso(d)
457
+ if m == "yesterday":
458
+ return _iso(d - _dt.timedelta(days=1))
459
+ if m == "one_week_ago":
460
+ # A week ago is a DATE (today minus 7), not the past-week RANGE. The two read almost
461
+ # identically in English and mean different things in a comparison.
462
+ return _iso(d - _dt.timedelta(days=7))
463
+ if m == "one_month_ago":
464
+ return _iso(_shift_months(d, -1))
465
+ if m == "n_days_ago":
466
+ s = str("" if value is None else value).strip()
467
+ # `[0-9]` not `\d`: a Python \d matches every Unicode decimal digit, so a fullwidth
468
+ # '30' would resolve here and be rejected by the TS mirror's Number() — the exact
469
+ # two-engine divergence filter_sql.to_num was rewritten to avoid.
470
+ if not s or not all("0" <= ch <= "9" for ch in s):
471
+ return None
472
+ n = int(s)
473
+ # No `n < 0` guard: the digit test above already excludes a sign, so it would be
474
+ # unreachable. The negative control proved that — removing it changed nothing, which is
475
+ # how dead code hides in a defensive-looking line. The CAP is the live guard.
476
+ if n > MAX_N:
477
+ return None
478
+ return _iso(d - _dt.timedelta(days=n))
479
+ parsed = _parse_date(value) # exact
480
+ return None if parsed is None else _iso(parsed)
481
+
482
+
483
+ def _anchor_label(mode, value):
484
+ """How an anchor reads in the condition sentence ('one month ago', '30 days ago')."""
485
+ m = mode or "exact"
486
+ if m not in ANCHOR_MODES:
487
+ return "an invalid date"
488
+ if m == "n_days_ago":
489
+ return ANCHOR_LABELS[m].format(n=str("" if value is None else value).strip() or "N")
490
+ if m == "exact":
491
+ return str("" if value is None else value).strip() or ANCHOR_LABELS[m]
492
+ return ANCHOR_LABELS[m]
platform/harness/windows.py CHANGED
@@ -1,489 +1,11 @@
1
- """harness/windows.py — the DATE WINDOW vocabulary (CG-7, owner item 2, 2026-07-26).
2
 
3
- A filter condition on a measure reads:
4
-
5
- Where [Sales] [in the last 90 days] [>] [5,000]
6
-
7
- The middle bracket is this module. It turns a window SPEC — a small JSON object a saved view can
8
- persist — into a concrete `(date_from, date_to)` pair of ISO dates.
9
-
10
- WHY IT IS ITS OWN MODULE, AND WHY IT TAKES `today` AS AN ARGUMENT
11
- -----------------------------------------------------------------------------------------------
12
- Two engines must agree on what "this quarter" means: this one (which compiles the SQL) and
13
- `customer-grid/windows.ts` (which renders the label the user reads and the bounds the client
14
- engine would use). If they disagree by one day, the grid shows a number the label denies, and
15
- nothing errors. `aios-web/verify_windows.py` holds them in lock-step over a fixed set of probe
16
- dates, exactly as verify_filter_engine.py does for the filter tree.
17
-
18
- `today` is a PARAMETER, never `date.today()` read inside. Three reasons, all learned:
19
- - a gate cannot compare two engines on "now" — the two runs are milliseconds apart and land on
20
- different sides of midnight roughly once every few thousand runs, which is the worst kind of
21
- flake because it looks like a real divergence
22
- - a window resolved during a request must not shift between the count query and the row query
23
- - the tenant's day boundary is the tenant's, not the server's
24
-
25
- DESIGN NOTES THAT ARE EASY TO GET WRONG
26
- -----------------------------------------------------------------------------------------------
27
- - Bounds are INCLUSIVE at both ends and are DATES, not timestamps. `store_query` casts both
28
- sides to TIMESTAMP and appends 23:59:59 to the upper bound, so a bare date is correct there;
29
- the client compares the 10-char ISO prefix, so a bare date is correct there too.
30
- - "Last N days" INCLUDES today. Airtable's "the past week" means the last 7 days up to and
31
- including now, not the 7 days before yesterday. Off-by-one here silently drops today's
32
- orders from every "recent" filter — invisible until someone asks why a sale they just
33
- entered is missing.
34
- - Week starts MONDAY (ISO 8601). Stated rather than defaulted: Python's weekday() is
35
- Monday=0 and JavaScript's getDay() is Sunday=0, so the two engines disagree unless one of
36
- them is explicitly corrected. That correction is the single most likely divergence in this
37
- file, and the gate probes a Sunday and a Monday for exactly that reason.
38
- - A `custom` window with only one bound is legal and means open-ended on the other side.
39
- - An UNRESOLVABLE window returns None rather than a default. A window that quietly becomes
40
- "all time" would widen a filter while still reporting an authoritative count.
41
  """
42
- import datetime as _dt
43
- import re
44
- import math
45
-
46
- #: Every window kind the UI may offer. Mirrors WINDOW_KINDS in customer-grid/windows.ts;
47
- #: verify_windows.py asserts the two lists are identical, because a kind the client can emit and
48
- #: the server cannot resolve is a filter that silently stops narrowing.
49
- WINDOW_KINDS = (
50
- "all_time",
51
- "today",
52
- "yesterday",
53
- "this_week",
54
- "last_week",
55
- "this_month",
56
- "last_month",
57
- "this_quarter",
58
- "last_quarter",
59
- "this_year",
60
- "last_year",
61
- "ytd",
62
- "ytd_last_year",
63
- "ltm",
64
- "past_week",
65
- "past_month",
66
- "past_year",
67
- "last_n_days",
68
- "next_n_days",
69
- "custom",
70
- )
71
-
72
- #: Kinds that carry an integer `n`.
73
- N_KINDS = frozenset({"last_n_days", "next_n_days"})
74
-
75
- #: How each kind reads in a sentence. The UI renders these; they are here so the label and the
76
- #: arithmetic cannot drift apart in the one place a user would never think to check.
77
- WINDOW_LABELS = {
78
- "all_time": "all time",
79
- "today": "today",
80
- "yesterday": "yesterday",
81
- "this_week": "this week",
82
- "last_week": "last week",
83
- "this_month": "this month",
84
- "last_month": "last month",
85
- "this_quarter": "this quarter",
86
- "last_quarter": "last quarter",
87
- "this_year": "this year",
88
- "last_year": "last year",
89
- "ytd": "year to date",
90
- # "last year to date" (LYTD), not "year to date, last year": the longer phrasing CLIPPED to
91
- # "year to date, last ye" in the 146px window select — and this vocabulary is CLOSED, so
92
- # the rule for it is that it stays readable rather than that it fits. Seen in a live
93
- # screenshot of the owner's own comparison; every assertion in that run was green.
94
- "ytd_last_year": "last year to date",
95
- "ltm": "the last 12 months",
96
- "past_week": "the past week",
97
- "past_month": "the past month",
98
- "past_year": "the past year",
99
- "last_n_days": "the last {n} days",
100
- "next_n_days": "the next {n} days",
101
- "custom": "a custom range",
102
- }
103
-
104
- MAX_N = 3650 # ten years; a bound, not a business rule
105
-
106
- # --- the DATE-VALUE anchors (owner item 3, 2026-07-26) ----------------------------------------
107
- # The second half of a date CONDITION, as distinct from a measure's window:
108
- #
109
- # Where [Last order] [is before] [one month ago]
110
- # ^ op ^ THIS
111
- #
112
- # A window answers "over what period do I sum"; an anchor answers "which single date am I
113
- # comparing against". Both live in this module for one reason: they are the same two-engine
114
- # contract, resolved from the same `today`, and a gate that holds one in lock-step and not the
115
- # other would leave half the sentence free to drift.
116
-
117
- #: Anchor modes, in the order the picker offers them. `exact` is the historical behaviour — a
118
- #: rule with NO mode is an `exact` rule whose value is an ISO date, which is what every view
119
- #: saved before this change carries.
120
- ANCHOR_MODES = (
121
- "today",
122
- "yesterday",
123
- "one_week_ago",
124
- "one_month_ago",
125
- "n_days_ago",
126
- "exact",
127
- )
128
-
129
- #: Modes that carry NO value. ⚠ This set is load-bearing far outside this module: a rule whose
130
- #: value is blank normally reads as INACTIVE, and an inactive rule is IGNORED — which WIDENS the
131
- #: result under a count nobody would doubt. Every activeness check (`isRuleActive` in TS,
132
- #: `filter_sql.is_rule_active`, and the validator's value handling) has to know these four are
133
- #: active with an empty value.
134
- ANCHOR_VALUE_FREE = frozenset({"today", "yesterday", "one_week_ago", "one_month_ago"})
135
-
136
- ANCHOR_LABELS = {
137
- "today": "today",
138
- "yesterday": "yesterday",
139
- "one_week_ago": "one week ago",
140
- "one_month_ago": "one month ago",
141
- "n_days_ago": "{n} days ago",
142
- "exact": "an exact date",
143
- }
144
-
145
-
146
- def _iso(d):
147
- return d.isoformat()
148
-
149
-
150
- def _month_start(d):
151
- return d.replace(day=1)
152
-
153
-
154
- def _month_end(d):
155
- return _next_month(d.replace(day=1)) - _dt.timedelta(days=1)
156
-
157
-
158
- def _next_month(d):
159
- return (d.replace(day=28) + _dt.timedelta(days=4)).replace(day=1)
160
-
161
-
162
- def _quarter_start(d):
163
- return _dt.date(d.year, 3 * ((d.month - 1) // 3) + 1, 1)
164
-
165
-
166
- def _days_in_month(y, m):
167
- return (_dt.date(y + (m == 12), 1 if m == 12 else m + 1, 1) - _dt.timedelta(days=1)).day
168
-
169
-
170
- def _shift_months(d, n):
171
- """`d` moved `n` months, CLAMPING the day to the target month's length.
172
-
173
- Jan 31 back one month is Dec 31, but Mar 31 back one month is Feb 28 (or 29) — there is no
174
- Feb 31 to land on. Both engines must clamp identically or "the past month" differs by up to
175
- three days for a third of the calendar; the gate probes a 31st and a leap day for exactly it.
176
- """
177
- total = (d.year * 12 + (d.month - 1)) + n
178
- y, m = divmod(total, 12)
179
- m += 1
180
- return _dt.date(y, m, min(d.day, _days_in_month(y, m)))
181
-
182
-
183
- def _parse_date(v):
184
- """Accept 'YYYY-MM-DD' (and tolerate a longer ISO timestamp by taking its date part)."""
185
- if isinstance(v, _dt.date):
186
- return v
187
- s = str(v or "").strip()[:10]
188
- if not s:
189
- return None
190
- try:
191
- return _dt.date.fromisoformat(s)
192
- except ValueError:
193
- return None
194
-
195
-
196
- # Sheet Ending metadata belongs to the binding period, never to a window spec.
197
- ENDING_KINDS = ("today", "yesterday", "last_week", "last_month", "last_quarter",
198
- "last_year", "fixed", "cell", "n_before_today")
199
- ENDING_LABELS = dict(zip(ENDING_KINDS, ("Today (live)", "Yesterday", "End of last week",
200
- "End of last month", "End of last quarter", "End of last year", "A fixed date", "From a cell",
201
- "N periods before today")))
202
- TO_DATE_KINDS = ("ytd", "ytd_last_year", "this_month", "this_quarter")
203
- ENDING_STEPS = ("day", "week", "month", "quarter", "year")
204
-
205
-
206
- def ending_step_default(kind):
207
- return "quarter" if kind == "this_quarter" else "month"
208
-
209
-
210
- def ending_date(value):
211
- """A real ISO day only. No truncation, calendar rollover, or blank fallback."""
212
- if not isinstance(value, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value.strip()):
213
- return None
214
- d = _parse_date(value)
215
- return _iso(d) if d else None
216
-
217
-
218
- def resolve_ending(mode, value, today, step="month", offset=0, n=0, unit="month"):
219
- """Inclusive ending date; cell values are supplied by the caller's trusted read."""
220
- d = _parse_date(today)
221
- if d is None:
222
- raise ValueError("Ending needs a valid today date")
223
- if mode not in ENDING_KINDS or step not in ENDING_STEPS:
224
- return None
225
- if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:
226
- return None
227
- if mode in ("fixed", "cell"):
228
- parsed = ending_date(value)
229
- if parsed is None:
230
- return None
231
- end = _parse_date(parsed)
232
- elif mode == "n_before_today":
233
- if (isinstance(n, bool) or not isinstance(n, int) or not 1 <= n <= MAX_N
234
- or unit not in ENDING_STEPS):
235
- return None
236
- try:
237
- if unit in ("day", "week"):
238
- end = d - _dt.timedelta(days=n * (7 if unit == "week" else 1))
239
- else:
240
- end = _shift_months(d, -n * {"month": 1, "quarter": 3, "year": 12}[unit])
241
- except (ValueError, OverflowError):
242
- return None
243
- elif mode == "today":
244
- end = d
245
- elif mode == "yesterday":
246
- end = d - _dt.timedelta(days=1)
247
- elif mode == "last_week":
248
- end = d - _dt.timedelta(days=d.weekday() + 1)
249
- elif mode == "last_month":
250
- end = _month_start(d) - _dt.timedelta(days=1)
251
- elif mode == "last_quarter":
252
- end = _quarter_start(d) - _dt.timedelta(days=1)
253
- else:
254
- end = _dt.date(d.year - 1, 12, 31)
255
- try:
256
- if step in ("day", "week"):
257
- end += _dt.timedelta(days=offset * (7 if step == "week" else 1))
258
- else:
259
- end = _shift_months(end, offset * {"month": 1, "quarter": 3, "year": 12}[step])
260
- return _iso(end)
261
- except (ValueError, OverflowError):
262
- return None
263
-
264
-
265
- def ending_cell_date(value, date_system="1900"):
266
- """Sheet dates may be ISO days or Excel serials in the workbook's declared epoch."""
267
- if not isinstance(value, (int, float)) or isinstance(value, bool):
268
- return ending_date(value)
269
- if not math.isfinite(value) or value < (0 if date_system == "1904" else 1):
270
- return None
271
- days = math.floor(value)
272
- if date_system != "1904" and days == 60:
273
- return None # Excel's fictional February 29, 1900 is not a calendar date.
274
- epoch = (_dt.date(1904, 1, 1) if date_system == "1904" else
275
- _dt.date(1899, 12, 31) if days < 60 else _dt.date(1899, 12, 30))
276
- try:
277
- return _iso(epoch + _dt.timedelta(days=days))
278
- except (ValueError, OverflowError):
279
- return None
280
-
281
-
282
- def ending_bounds(kind, mode, value, today, step="month", offset=0, n=0, unit="month"):
283
- """Keep the kind's own start. An ending before it refuses instead of reversing bounds."""
284
- if kind not in TO_DATE_KINDS:
285
- return None
286
- end = resolve_ending(mode, value, today, step, offset, n, unit)
287
- if end is None:
288
- return None
289
- start = resolve({"kind": kind}, today)[0]
290
- return (start, end) if start <= end else None
291
-
292
-
293
- def normalize(spec):
294
- """Coerce an untrusted window spec to `{kind, n?, from?, to?}` or None.
295
-
296
- Fail-closed on the KIND (an unknown kind is not a window), tolerant on the rest — the same
297
- split `clean_filter_tree` uses, so one malformed window cannot cost a user their saved view.
298
- """
299
- if not isinstance(spec, dict):
300
- return None
301
- kind = spec.get("kind")
302
- if kind not in WINDOW_KINDS:
303
- return None
304
- out = {"kind": kind}
305
- if kind in N_KINDS:
306
- try:
307
- n = int(spec.get("n"))
308
- except (TypeError, ValueError):
309
- return None
310
- if n < 1 or n > MAX_N:
311
- return None
312
- out["n"] = n
313
- if kind == "custom":
314
- f, t = _parse_date(spec.get("from")), _parse_date(spec.get("to"))
315
- if f is None and t is None:
316
- return None # a custom range with no bounds is not a window
317
- if f is not None and t is not None and f > t:
318
- f, t = t, f # the builder cannot enforce order; the engine can
319
- if f is not None:
320
- out["from"] = _iso(f)
321
- if t is not None:
322
- out["to"] = _iso(t)
323
- return out
324
-
325
-
326
- def resolve(spec, today):
327
- """Window spec + the tenant's today -> `(date_from, date_to)`, both inclusive ISO dates.
328
-
329
- Either side may be None, meaning open-ended. Returns None when the spec is not a window at
330
- all — callers MUST treat that as "this condition cannot be evaluated" and refuse, never as
331
- "no window", which would silently widen the result to all time.
332
- """
333
- spec = normalize(spec)
334
- if spec is None:
335
- return None
336
- kind = spec["kind"]
337
- d = _parse_date(today)
338
- if d is None:
339
- raise ValueError("resolve() needs an explicit `today`; see this module's docstring")
340
-
341
- if kind == "all_time":
342
- return (None, None)
343
- if kind == "today":
344
- return (_iso(d), _iso(d))
345
- if kind == "yesterday":
346
- y = d - _dt.timedelta(days=1)
347
- return (_iso(y), _iso(y))
348
-
349
- # ISO 8601: the week starts MONDAY. Python's weekday() is already Monday=0; the TS mirror
350
- # has to correct getDay(), which is Sunday=0. The gate probes both a Sunday and a Monday.
351
- if kind == "this_week":
352
- start = d - _dt.timedelta(days=d.weekday())
353
- return (_iso(start), _iso(start + _dt.timedelta(days=6)))
354
- if kind == "last_week":
355
- start = d - _dt.timedelta(days=d.weekday() + 7)
356
- return (_iso(start), _iso(start + _dt.timedelta(days=6)))
357
-
358
- if kind == "this_month":
359
- return (_iso(_month_start(d)), _iso(_month_end(d)))
360
- if kind == "last_month":
361
- prev = _month_start(d) - _dt.timedelta(days=1)
362
- return (_iso(_month_start(prev)), _iso(prev))
363
-
364
- if kind == "this_quarter":
365
- qs = _quarter_start(d)
366
- qe = _month_end(_dt.date(qs.year, qs.month + 2, 1))
367
- return (_iso(qs), _iso(qe))
368
- if kind == "last_quarter":
369
- prev_end = _quarter_start(d) - _dt.timedelta(days=1)
370
- qs = _quarter_start(prev_end)
371
- return (_iso(qs), _iso(prev_end))
372
-
373
- if kind == "this_year":
374
- return (_iso(_dt.date(d.year, 1, 1)), _iso(_dt.date(d.year, 12, 31)))
375
- if kind == "last_year":
376
- return (_iso(_dt.date(d.year - 1, 1, 1)), _iso(_dt.date(d.year - 1, 12, 31)))
377
- if kind == "ytd":
378
- # year-to-date ENDS TODAY, unlike this_year which runs to Dec 31. The distinction is the
379
- # whole reason both exist: comparing "this year" against last year double-counts the
380
- # months that have not happened yet.
381
- return (_iso(_dt.date(d.year, 1, 1)), _iso(d))
382
- if kind == "ytd_last_year":
383
- # SAME PERIOD last year — Jan 1 LY through today's month/day LY. This is the honest
384
- # partner of `ytd`, and it is not a nicety: it mirrors `core.periods.ytd_last_year`
385
- # EXACTLY (including the Feb 29 -> Feb 28 clamp), which is what `pool()` computes the
386
- # `revenue_ly` column from. `Sales[ytd] < Sales[ytd_last_year]` therefore reproduces the
387
- # retired `at_risk > 0` condition rather than approximating it. Comparing `ytd` against
388
- # `last_year` instead would pit seven months against twelve.
389
- return (_iso(_dt.date(d.year - 1, 1, 1)), _iso(_shift_months(d, -12)))
390
- if kind == "ltm":
391
- # the last twelve months INCLUDING today: 365 days back, both ends inclusive
392
- return (_iso(d - _dt.timedelta(days=364)), _iso(d))
393
-
394
- # "The past week/month/year" are ROLLING and end TODAY — Airtable's wording, and NOT the
395
- # calendar kinds above: `last_week` is the previous Monday-Sunday, `past_week` is the seven
396
- # days ending today. Both are offered because a user means different things by them, and
397
- # picking one to serve both would silently answer the other question.
398
- # past_week = the same rule as last_n_days(7) — one period back, PLUS ONE DAY, so today
399
- # is included and the span is exactly 7 days rather than 8.
400
- # past_year agrees with `ltm` except across a leap day, where the calendar shift keeps the
401
- # same month/day and the 364-day subtraction cannot.
402
- if kind == "past_week":
403
- return (_iso(d - _dt.timedelta(days=6)), _iso(d))
404
- if kind == "past_month":
405
- return (_iso(_shift_months(d, -1) + _dt.timedelta(days=1)), _iso(d))
406
- if kind == "past_year":
407
- return (_iso(_shift_months(d, -12) + _dt.timedelta(days=1)), _iso(d))
408
-
409
- if kind == "last_n_days":
410
- # INCLUSIVE of today — "the last 7 days" is today and the 6 before it, not the 7 before
411
- # yesterday. Getting this wrong drops today's orders from every recent-activity filter.
412
- return (_iso(d - _dt.timedelta(days=spec["n"] - 1)), _iso(d))
413
- if kind == "next_n_days":
414
- return (_iso(d), _iso(d + _dt.timedelta(days=spec["n"] - 1)))
415
-
416
- if kind == "custom":
417
- return (spec.get("from"), spec.get("to"))
418
- raise AssertionError(f"unhandled window kind {kind!r}") # unreachable; WINDOW_KINDS is closed
419
-
420
-
421
- def label(spec):
422
- """How a window reads in the condition sentence ('in the last 90 days')."""
423
- spec = normalize(spec)
424
- if spec is None:
425
- return "an invalid range"
426
- return WINDOW_LABELS[spec["kind"]].format(n=spec.get("n"))
427
-
428
-
429
- def resolve_anchor(mode, value, today):
430
- """A date condition's right-hand side -> ONE inclusive ISO date, or None.
431
-
432
- `mode` is an entry of ANCHOR_MODES; None/'' means `exact`, which is what every view saved
433
- before anchors existed carries (op + an ISO date in `value`). `value` supplies the number for
434
- `n_days_ago` and the date for `exact`, and is ignored by the four value-free modes.
435
-
436
- Returns None when the anchor cannot be resolved — an unknown mode, a non-numeric N, a value
437
- that is not a date. The caller must then treat the CONDITION as unanswerable and match
438
- nothing. It must NOT fall through to "no condition": that widens the result while the count
439
- beside it still looks authoritative, which is the whole reason this returns None rather than
440
- a best guess (same contract as `resolve()` above).
441
-
442
- `n_days_ago` accepts n = 0 where a WINDOW requires n >= 1. A zero-day window is empty and
443
- could only be a mistake; "0 days ago" is today, which is a date a person can mean.
444
- """
445
- m = mode or "exact"
446
- if m not in ANCHOR_MODES:
447
- return None
448
- d = _parse_date(today)
449
- if d is None:
450
- raise ValueError("resolve_anchor() needs an explicit `today`; see this module's "
451
- "docstring on why the clock is never read here")
452
- if m == "today":
453
- return _iso(d)
454
- if m == "yesterday":
455
- return _iso(d - _dt.timedelta(days=1))
456
- if m == "one_week_ago":
457
- # A week ago is a DATE (today minus 7), not the past-week RANGE. The two read almost
458
- # identically in English and mean different things in a comparison.
459
- return _iso(d - _dt.timedelta(days=7))
460
- if m == "one_month_ago":
461
- return _iso(_shift_months(d, -1))
462
- if m == "n_days_ago":
463
- s = str("" if value is None else value).strip()
464
- # `[0-9]` not `\d`: a Python \d matches every Unicode decimal digit, so a fullwidth
465
- # '30' would resolve here and be rejected by the TS mirror's Number() — the exact
466
- # two-engine divergence filter_sql.to_num was rewritten to avoid.
467
- if not s or not all("0" <= ch <= "9" for ch in s):
468
- return None
469
- n = int(s)
470
- # No `n < 0` guard: the digit test above already excludes a sign, so it would be
471
- # unreachable. The negative control proved that — removing it changed nothing, which is
472
- # how dead code hides in a defensive-looking line. The CAP is the live guard.
473
- if n > MAX_N:
474
- return None
475
- return _iso(d - _dt.timedelta(days=n))
476
- parsed = _parse_date(value) # exact
477
- return None if parsed is None else _iso(parsed)
478
 
 
 
479
 
480
- def anchor_label(mode, value):
481
- """How an anchor reads in the condition sentence ('one month ago', '30 days ago')."""
482
- m = mode or "exact"
483
- if m not in ANCHOR_MODES:
484
- return "an invalid date"
485
- if m == "n_days_ago":
486
- return ANCHOR_LABELS[m].format(n=str("" if value is None else value).strip() or "N")
487
- if m == "exact":
488
- return str("" if value is None else value).strip() or ANCHOR_LABELS[m]
489
- return ANCHOR_LABELS[m]
 
1
+ """Compatibility import for the date-window vocabulary now owned by :mod:`core.windows`.
2
 
3
+ Keep this module so existing API and harness consumers retain their stable import path. New
4
+ lower-layer consumers import ``core.windows`` directly; the dependency direction stays downward.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ from core import windows as _windows
8
+ from core.windows import * # noqa: F401,F403
9
 
10
+ # Retain the historical public helper without making an otherwise-unused function public in core.
11
+ anchor_label = _windows._anchor_label
 
 
 
 
 
 
 
 
platform/modules/sheet.py CHANGED
@@ -36,29 +36,20 @@ import re
36
  from urllib.parse import urlencode
37
 
38
  from harness.filter_sql import NUMERIC_TYPES as MIRROR_NUMERIC_TYPES
 
 
 
 
 
 
 
39
 
40
  #: C2's aggregate vocabulary. W59-T14 resolves the `metric_key` arm through a Metric column,
41
  #: using only the catalogue's declared fold: see `metric_key_fold` and its additivity guard.
42
  AGGREGATE_FNS = ("sum", "count", "avg", "min", "max")
43
 
44
- #: Calendar units shared with `web/src/sheet/types.ts`; W60-T06 adds daily and weekly summaries.
45
- PERIOD_UNITS = ("day", "week", "month", "quarter", "year")
46
-
47
- #: Month, Quarter and Year keep their opening-month encoding unchanged.
48
- _PERIOD_START = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
49
-
50
- #: Day/Week starts and inclusive endpoints of a frozen period, spelled `YYYY-MM-DD`.
51
- _PERIOD_DAY = re.compile(r"^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$")
52
-
53
- #: A `period.ref` points at a cell that holds the period, so it is a plain A1 address with no `$`,
54
- #: exactly as `core/sheets.py::_ADDR` spells one.
55
- _PERIOD_REF = re.compile(r"^[A-Z]{1,3}[1-9][0-9]{0,6}$")
56
-
57
- #: ⭐ R10's DRAG, and it is TWO settings rather than one because the two axes answer different
58
- #: questions. Across columns a drag walks the PERIOD; down rows it walks the next value of a
59
- #: chosen field. Defaults: across "period", down "none".
60
- DRAG_ACROSS = ("period", "none")
61
- DRAG_DOWN_NONE = "none"
62
 
63
  #: C2's refusal codes, spelled once. ⚠ Each message reaches a screen, so none carries an em dash or
64
  #: an en dash (standing rule 2) and each names both the cause and the subject.
@@ -159,135 +150,12 @@ class SheetRefusal(Exception):
159
 
160
 
161
  def clean_period(raw):
162
- """R9's period, or None. `{unit, start, locked?, ref?}`, with `{ref}` / `{window}` still read.
163
-
164
- A frozen period is `{unit, start, locked?, frozen: true, from, to}`. `frozen` stores only
165
- True so freezing and unfreezing returns to the identical rolling period already stored.
166
-
167
- ⛔ AN UNKNOWN UNIT OR A MALFORMED START IS REFUSED BY NAME, and that is not the same call as
168
- the cosmetic keys next door. A period decides WHICH ROWS ARE COUNTED. Dropping `unit: "fortnight"`
169
- would answer for every row the binding can see and hand back a bigger number with nobody told,
170
- which is standing rule 1's second sentence turned into a defect.
171
-
172
- ⚠ `locked` STORES ONLY TRUE. R9's lock means "a copy of this cell keeps this period"; an
173
- unlocked period is what every cell already is, so storing `false` would make a cell that was
174
- locked and unlocked compare unequal to the cell it started as.
175
-
176
- ⛔⛔ D-660 (W53-T16) - A PERIOD THAT NAMES NO WINDOW IS NOT A PERIOD, AND STORING ONE IS THE
177
- WHOLE DEFECT. `{"unit": "month"}` with no `start`, or `{"locked": true}` on its own, used to be
178
- stored as a period. `period_window` reads either as None, so the CELL still answered all time -
179
- but the binding now carried a `period` key, and the editor reading it back sees a declared unit,
180
- fills the missing start with TODAY'S MONTH and shows it as a chosen period. The next save then
181
- stamps `{unit: "month", start: <this month>}` over a cell nobody meant to narrow: an all-time
182
- total silently becomes this month's, which is exactly what D-660 names. So a period must name a
183
- window - a `start`, validated frozen dates, the legacy `window`, or R14's `ref` - or it is
184
- dropped and the cell stays all time. ⚠ THE ORDER MATTERS: an unknown unit or a malformed
185
- start is still REFUSED BY NAME above, as are missing or malformed frozen dates, because a
186
- wrong period and an absent one are different answers.
187
- """
188
- if not isinstance(raw, dict):
189
- return None
190
- out = {}
191
-
192
- # An Ending is a period modifier. Validate before the legacy dialect can discard it.
193
- if "ending" in raw:
194
- from harness import windows as W
195
- window = W.normalize(raw.get("window"))
196
- kind = (window or {}).get("kind")
197
- if kind not in W.TO_DATE_KINDS:
198
- raise SheetRefusal("ending_not_supported", kind or "This period")
199
- ending = raw["ending"]
200
- mode = ending.get("kind") if isinstance(ending, dict) else None
201
- if mode not in W.ENDING_KINDS:
202
- raise SheetRefusal("ending_invalid", str(mode or "selection"), "the choice is unknown.")
203
- step = raw.get("endingStep", W.ending_step_default(kind))
204
- offset = raw.get("endingOffset", 0)
205
- if step not in W.ENDING_STEPS or isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:
206
- raise SheetRefusal("ending_invalid", "step", "its size or copy offset is invalid.")
207
- out = {"window": window, "ending": {"kind": mode}, "endingStep": step}
208
- if offset:
209
- out["endingOffset"] = offset
210
- if raw.get("locked") is True:
211
- out["locked"] = True
212
- if mode == "fixed":
213
- day = W.ending_date(ending.get("date"))
214
- if day is None:
215
- raise SheetRefusal("ending_invalid", "fixed date", "it is not a real ISO date.")
216
- out["ending"]["date"] = day
217
- if mode == "n_before_today":
218
- n, unit = ending.get("n"), ending.get("unit")
219
- if isinstance(n, bool) or not isinstance(n, int) or not 1 <= n <= W.MAX_N:
220
- raise SheetRefusal("ending_invalid", "number",
221
- f"it must be a whole number from 1 to {W.MAX_N}.")
222
- if unit not in W.ENDING_STEPS:
223
- raise SheetRefusal("ending_invalid", "unit", "the unit is unknown.")
224
- out["ending"].update({"n": n, "unit": unit})
225
- if mode == "cell":
226
- ref = str(raw.get("ref") or "").strip()
227
- # Preserve sheet names and dollar anchors. The read layer validates the target.
228
- if not re.fullmatch(r"(?:(?:'([^']|'')+'|[^'!]+)!)?\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6}", ref):
229
- raise SheetRefusal("ending_cell_unreadable", ref or "(blank)", "its reference is invalid.")
230
- out["ref"] = ref
231
- return out
232
-
233
- unit = str(raw.get("unit") or "").strip().lower()
234
- if unit:
235
- if unit not in PERIOD_UNITS:
236
- raise SheetRefusal("period_invalid", unit)
237
- out["unit"] = unit
238
-
239
- start = str(raw.get("start") or "").strip()
240
- if start:
241
- pattern = _PERIOD_DAY if unit in ("day", "week") else _PERIOD_START
242
- if not pattern.fullmatch(start):
243
- raise SheetRefusal("period_invalid", start)
244
- if unit in ("day", "week"):
245
- try:
246
- day = datetime.date.fromisoformat(start)
247
- except ValueError:
248
- raise SheetRefusal("period_invalid", start)
249
- if unit == "week":
250
- start = (day - datetime.timedelta(days=day.weekday())).isoformat()
251
- out["start"] = start
252
-
253
- if raw.get("frozen") is True:
254
- dates = {}
255
- for key in ("from", "to"):
256
- value = str(raw.get(key) or "").strip()
257
- # ⚠ `value or key` because a MISSING date has no value to name, and a refusal with an
258
- # empty subject reads as " is not a period this cell can use" - the same blank-subject
259
- # defect the Metric binding originally exposed.
260
- if not _PERIOD_DAY.fullmatch(value):
261
- raise SheetRefusal("period_invalid", value or key)
262
- dates[key] = value
263
- # ISO days have fixed-width year/month/day parts, so string order is date order.
264
- if dates["to"] < dates["from"]:
265
- raise SheetRefusal("period_invalid", dates["to"])
266
- out.update({"frozen": True, **dates})
267
-
268
- if raw.get("locked") is True:
269
- out["locked"] = True
270
-
271
- ref = str(raw.get("ref") or "").strip().upper().replace("$", "")
272
- if ref:
273
- if not _PERIOD_REF.match(ref):
274
- raise SheetRefusal("period_invalid", ref)
275
- if not out.get("frozen"):
276
- out["ref"] = ref
277
-
278
- #: ⚠ The wave-49 spelling, kept so a binding written before R9 still round trips. It is not a
279
- #: second dialect for the same thing: `window` is a raw relative window, `unit` + `start` is a
280
- #: named calendar period, and a document carrying the old one is not rewritten on read.
281
- if (raw.get("window") is not None and "unit" not in out and "start" not in out
282
- and not out.get("frozen")):
283
- out["window"] = raw["window"]
284
-
285
- #: ⛔ D-660: see the docstring. A unit on its own, a lock on its own, or the empty dict names no
286
- #: window, so it is not a period and the cell keeps its all-time answer. A frozen period
287
- #: names its window through the two literal dates already validated above.
288
- if not ({"start", "window", "ref", "frozen"} & set(out)):
289
- return None
290
- return out
291
 
292
 
293
  #: Month-based periods retain their existing arithmetic. Day/Week advance in calendar days.
@@ -573,49 +441,9 @@ def metric_window_limit(subject, cause):
573
 
574
 
575
  def clean_on_drag(raw):
576
- """R10's two directional drag settings, or None when the caller sent none.
577
-
578
- ⚠ BOTH KEYS COME OUT WHENEVER ONE WENT IN. The two axes are answered together or a drag has
579
- to guess one of them, and a guess is exactly what R10 replaced. The defaults are R10's own:
580
- across "period", down "none".
581
- """
582
- if not isinstance(raw, dict):
583
- return None
584
- across = str(raw.get("across") or "").strip().lower()
585
- if across not in DRAG_ACROSS:
586
- across = "period"
587
- down = raw.get("down")
588
- if isinstance(down, dict) and str(down.get("field") or "").strip():
589
- out_down = {"field": str(down["field"]).strip()}
590
- if down.get("mode") in ("value", "presence", "member"):
591
- out_down["mode"] = down["mode"]
592
- else:
593
- out_down = DRAG_DOWN_NONE
594
- if isinstance(raw.get("steps"), list):
595
- steps = []
596
- for step in raw["steps"]:
597
- if not isinstance(step, dict):
598
- continue
599
- field = step.get("field")
600
- if not isinstance(field, str) or not field.strip():
601
- continue
602
- if step.get("axis") not in ("across", "down"):
603
- continue
604
- if "size" in step and step["size"] not in ("day", "week", "month", "quarter", "year"):
605
- continue
606
- cleaned = {"field": field.strip(), "axis": step["axis"]}
607
- if step.get("mode") in ("value", "presence", "member"):
608
- cleaned["mode"] = step["mode"]
609
- if "size" in step:
610
- cleaned["size"] = step["size"]
611
- steps.append(cleaned)
612
- first_down = next((step for step in steps if step["axis"] == "down"), None)
613
- out_down = ({key: first_down[key] for key in ("field", "mode") if key in first_down}
614
- if first_down else DRAG_DOWN_NONE)
615
- across = "period" if any(step["axis"] == "across" and step["field"] in
616
- ("__period", "__ending") for step in steps) else "none"
617
- return {"across": across, "down": out_down, "steps": steps}
618
- return {"across": across, "down": out_down}
619
 
620
 
621
  def clean_adopted_from(raw):
 
36
  from urllib.parse import urlencode
37
 
38
  from harness.filter_sql import NUMERIC_TYPES as MIRROR_NUMERIC_TYPES
39
+ from core.sheet_binding import (
40
+ DRAG_ACROSS,
41
+ DRAG_DOWN_NONE,
42
+ PERIOD_REF as _PERIOD_REF,
43
+ PERIOD_START as _PERIOD_START,
44
+ PERIOD_UNITS,
45
+ )
46
 
47
  #: C2's aggregate vocabulary. W59-T14 resolves the `metric_key` arm through a Metric column,
48
  #: using only the catalogue's declared fold: see `metric_key_fold` and its additivity guard.
49
  AGGREGATE_FNS = ("sum", "count", "avg", "min", "max")
50
 
51
+ #: Calendar, reference, and drag vocabularies are re-exported from the lower document cleaner so
52
+ #: existing callers keep this module's public names without maintaining a second normalizer.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  #: C2's refusal codes, spelled once. ⚠ Each message reaches a screen, so none carries an em dash or
55
  #: an en dash (standing rule 2) and each names both the cause and the subject.
 
150
 
151
 
152
  def clean_period(raw):
153
+ """Normalize period metadata through the core document contract."""
154
+ from core.sheet_binding import BindingMetadataRefusal, clean_period as _clean
155
+ try:
156
+ return _clean(raw)
157
+ except BindingMetadataRefusal as exc:
158
+ raise SheetRefusal(exc.code, exc.subject, exc.detail) from exc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
 
161
  #: Month-based periods retain their existing arithmetic. Day/Week advance in calendar days.
 
441
 
442
 
443
  def clean_on_drag(raw):
444
+ """Normalize drag metadata through the core document contract."""
445
+ from core.sheet_binding import clean_on_drag as _clean
446
+ return _clean(raw)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
 
448
 
449
  def clean_adopted_from(raw):
web/public/AIOS_DEPLOY_RECEIPT ADDED
@@ -0,0 +1 @@
 
 
1
+ 185d760748361898f90d9291944befe8df51de2fb01d35585b2a6278b9605ec0
web/scripts/test-esm-loader.mjs ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Resolve TypeScript's extensionless ESM output for source-level Node gates.
2
+ // Production is bundled by Vite; this loader gives the gate the same ESM semantics without
3
+ // pretending the valid `import.meta.url` worker code is CommonJS.
4
+ export async function resolve(specifier, context, nextResolve) {
5
+ try {
6
+ return await nextResolve(specifier, context);
7
+ } catch (error) {
8
+ if (specifier.startsWith(".") && !/\.[cm]?js(?:[?#]|$)/.test(specifier)) {
9
+ return nextResolve(`${specifier}.js`, context);
10
+ }
11
+ throw error;
12
+ }
13
+ }
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -172,6 +172,7 @@ import RecordComments from "./RecordComments";
172
  import RecordRail from "./RecordRail";
173
  import { ModeSwitch, RECORD_DETAIL_MODES, RecordRelatedModeView } from "./viewModes";
174
  import { isStreamlitComponent } from "./hostBridge";
 
175
  // ⚠ ALIASED for the same reason `CustomerGrid` aliases it: `./Stars`'s `StarIcon` is the RATING
176
  // atom and this one is the record MARK. Two meanings, one noun, both reachable in this tree.
177
  import { StarIcon as RecordStarMark } from "../ui/icons";
@@ -3027,7 +3028,7 @@ export default function RecordDetail({
3027
  state (`tab`/`activeTab`/`setTab`) and clause 1 + clause 2's edge list (`tabs`)
3028
  are UNCHANGED; only the strip is gone, replaced by `RecordRail` on the left of
3029
  the modal (see the render tree below `.cg-record-modal`). */}
3030
- <div
3031
  className="cg-detail-body"
3032
  id={`${tabsId}-panel`}
3033
  aria-busy={recordNavigationBusy}
@@ -3264,7 +3265,7 @@ export default function RecordDetail({
3264
 
3265
  </>
3266
  )}
3267
- </div>
3268
  </main>
3269
  {/* ⭐ WAVE 19 (owner item 12) — the rail finally gets the SCOPE this modal has held
3270
  since wave 13 and never passed on. `scope != null` gates it for exactly the
 
172
  import RecordRail from "./RecordRail";
173
  import { ModeSwitch, RECORD_DETAIL_MODES, RecordRelatedModeView } from "./viewModes";
174
  import { isStreamlitComponent } from "./hostBridge";
175
+ import { OverlayScroll } from "../ui/OverlayScroll";
176
  // ⚠ ALIASED for the same reason `CustomerGrid` aliases it: `./Stars`'s `StarIcon` is the RATING
177
  // atom and this one is the record MARK. Two meanings, one noun, both reachable in this tree.
178
  import { StarIcon as RecordStarMark } from "../ui/icons";
 
3028
  state (`tab`/`activeTab`/`setTab`) and clause 1 + clause 2's edge list (`tabs`)
3029
  are UNCHANGED; only the strip is gone, replaced by `RecordRail` on the left of
3030
  the modal (see the render tree below `.cg-record-modal`). */}
3031
+ <OverlayScroll
3032
  className="cg-detail-body"
3033
  id={`${tabsId}-panel`}
3034
  aria-busy={recordNavigationBusy}
 
3265
 
3266
  </>
3267
  )}
3268
+ </OverlayScroll>
3269
  </main>
3270
  {/* ⭐ WAVE 19 (owner item 12) — the rail finally gets the SCOPE this modal has held
3271
  since wave 13 and never passed on. `scope != null` gates it for exactly the
web/src/sheet/Ribbon.tsx CHANGED
@@ -50,6 +50,7 @@ import { Children, cloneElement, createContext, isValidElement, useContext, useC
50
  import type { KeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";
51
  import type { Cell, CellStyle, CellStylePatch, SheetChartSpec, Workbook, SheetPrintSettings, SheetViewDoor } from "./types";
52
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
 
53
  import {
54
  EXPORT_FORMATS,
55
  runSheetExport,
@@ -795,9 +796,11 @@ export default function Ribbon({
795
  };
796
  const activeGroups = activeTab.groups(tabContext);
797
  const overflowContent = (
798
- <div className="sheet-ribbon-overflow-content" ref={overflowRef}>
799
- {partitionRibbonGroups(activeGroups, visibleGroupCount, true)}
800
- </div>
 
 
801
  );
802
 
803
  useLayoutEffect(() => {
 
50
  import type { KeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";
51
  import type { Cell, CellStyle, CellStylePatch, SheetChartSpec, Workbook, SheetPrintSettings, SheetViewDoor } from "./types";
52
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
53
+ import { OverlayScroll } from "../ui/OverlayScroll";
54
  import {
55
  EXPORT_FORMATS,
56
  runSheetExport,
 
796
  };
797
  const activeGroups = activeTab.groups(tabContext);
798
  const overflowContent = (
799
+ <OverlayScroll className="sheet-ribbon-overflow-scroll" tabIndex={-1}>
800
+ <div className="sheet-ribbon-overflow-content" ref={overflowRef}>
801
+ {partitionRibbonGroups(activeGroups, visibleGroupCount, true)}
802
+ </div>
803
+ </OverlayScroll>
804
  );
805
 
806
  useLayoutEffect(() => {
web/src/styles/wave52/ribbon.css CHANGED
@@ -207,6 +207,14 @@
207
  pointer-events: none;
208
  }
209
 
 
 
 
 
 
 
 
 
210
  .sheet-ribbon-overflow-content,
211
  .sheet-ribbon-overflow-content > fieldset {
212
  display: flex;
 
207
  pointer-events: none;
208
  }
209
 
210
+ /* W62-T33: the overflow gallery gets the same deferred, momentum-safe fade treatment as the
211
+ shell rail. The anchored panel owns the collision max-height; the scroll host inherits it. */
212
+ .sheet-ribbon-overflow-scroll {
213
+ min-width: 0;
214
+ max-width: 100%;
215
+ max-height: inherit;
216
+ }
217
+
218
  .sheet-ribbon-overflow-content,
219
  .sheet-ribbon-overflow-content > fieldset {
220
  display: flex;