diff --git a/RELEASES.json b/RELEASES.json
index 5d46e2104153b5ab209ee0ea846571f7e122ca56..ad239fc58580b5f535689dd7ec1644f6bf768e55 100644
--- a/RELEASES.json
+++ b/RELEASES.json
@@ -1,6 +1,18 @@
{
- "current": "v11 (3126617)",
+ "current": "v13 (314c0e3)",
"releases": [
+ {
+ "version": "v13",
+ "sha": "314c0e3",
+ "date": "2026-08-06",
+ "subject": "release v13"
+ },
+ {
+ "version": "v12",
+ "sha": "4908f39",
+ "date": "2026-08-06",
+ "subject": "release v12"
+ },
{
"version": "v11",
"sha": "3126617",
diff --git a/VERSION b/VERSION
index ba8c682859242ccc42d979cac4c5ba4844b28105..6c1db79abe749cdfb8487a7a493a64957942e723 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-v11 (3126617)
+v13 (314c0e3)
diff --git a/api/ai_review.py b/api/ai_review.py
new file mode 100644
index 0000000000000000000000000000000000000000..312b7969e449e0ad71d727de4bb3e6b70f5c58db
--- /dev/null
+++ b/api/ai_review.py
@@ -0,0 +1,207 @@
+"""AI REVIEW — let a model decide which stage a card moves to (wave 23, owner ruling R4/R14).
+
+⭐ WHAT THIS IS. A review stage holds a record until somebody decides where it goes next. R4 made
+that somebody optionally a MODEL: the engine hands over the record's own values, the review's
+prompt, and the list of stages the review is allowed to send a card to, and gets back ONE of
+those stage labels plus a one-line reason. Every decision is written to the same `reviews` audit
+log a human click writes to, tagged `by: "ai"` with the provider and model that made it.
+
+⛔ FAIL-CLOSED IN EVERY DIRECTION, and this is the whole safety story. No key configured, a
+network failure, a slow answer, a malformed answer, or an answer naming a stage the review does
+not offer — all return `("", {...})`, and the caller leaves the card exactly where a human would
+have found it. The feature can be absent, broken or wrong and the worst outcome is a person doing
+the work. Nothing here can move a card somewhere the review does not already permit.
+
+⭐ CHEAP FIRST (owner R14, verbatim: *"Claude is a bit too expensive"*). The ladder is
+`groq → cerebras → openrouter → anthropic`; the first CONFIGURED provider wins, and Anthropic is
+last rather than absent — it is the quality backstop, not the default. `AIOS_AI_REVIEW_PROVIDER`
+pins one; `AIOS_AI_MODEL` overrides the model.
+
+⚠ WHY RAW HTTP RATHER THAN THE `anthropic` SDK, stated because it is a deliberate deviation from
+the /claude-api skill's default and not an oversight. Three of the four legs are OpenAI-chat-shaped
+endpoints with no shared SDK, so a ladder built on the SDK would be one SDK leg beside three
+hand-rolled ones — two implementations of the same call, the seam this repo keeps closing. And
+`aios-web/api/requirements.txt` is PINNED to what the verify battery proves ([[pin-deps-space-
+rebuilds]]): adding a dependency there rebuilds the container, which is a real deploy risk to take
+for one leg of an optional feature. `requests` is already a dependency and `harness/analyst.py`
+established per-provider raw HTTP as the house pattern. Booked as a DEBT line so the integrator
+can overturn it deliberately rather than by drift.
+
+The Messages shape below is the current one: `x-api-key` + `anthropic-version: 2023-06-01`, and
+`stop_reason: "refusal"` is checked BEFORE reading `content` — a refusal answers HTTP 200 with an
+empty content list, so code that indexes `content[0]` unconditionally breaks on it.
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+
+import requests
+
+#: The ladder. Order IS the policy (R14) — cheapest capable first, Anthropic last.
+PROVIDERS = [
+ {"name": "groq", "env": "GROQ_API_KEY", "shape": "openai",
+ "url": "https://api.groq.com/openai/v1/chat/completions",
+ "model": "llama-3.3-70b-versatile"},
+ {"name": "cerebras", "env": "CEREBRAS_API_KEY", "shape": "openai",
+ "url": "https://api.cerebras.ai/v1/chat/completions",
+ "model": "gpt-oss-120b"},
+ {"name": "openrouter", "env": "OPENROUTER_API_KEY", "shape": "openai",
+ "url": "https://openrouter.ai/api/v1/chat/completions",
+ "model": "openai/gpt-4o-mini"},
+ # ⚠ haiku-class DELIBERATELY, not the default Opus tier: R14 put Anthropic on this ladder as
+ # the backstop for a one-line classification, and this is the cheapest current Claude that
+ # does it well. A bigger model here would be spending the owner's money to pick between two
+ # labels it already has in front of it.
+ {"name": "anthropic", "env": "ANTHROPIC_API_KEY", "shape": "anthropic",
+ "url": "https://api.anthropic.com/v1/messages",
+ "model": "claude-haiku-4-5"},
+]
+ANTHROPIC_VERSION = "2023-06-01"
+TIMEOUT_SECONDS = float(os.environ.get("AIOS_AI_REVIEW_TIMEOUT") or 20)
+MAX_FIELD_CHARS = 200 # per value handed to the model
+MAX_FIELDS = 30 # columns handed to the model
+MAX_REASON = 200
+
+
+def ladder():
+ """The providers that are actually usable here, in order. Empty = the feature is off."""
+ pin = (os.environ.get("AIOS_AI_REVIEW_PROVIDER") or "").strip().lower()
+ live = [p for p in PROVIDERS if (os.environ.get(p["env"]) or "").strip()]
+ if pin:
+ live = [p for p in live if p["name"] == pin]
+ return live
+
+
+def configured():
+ return bool(ladder())
+
+
+def _record_text(row, fields):
+ """The record, as the model sees it. Values are truncated and the column set is bounded —
+ an automation table can carry a 32 KB JSON blob per row (C7) and a review decision does not
+ need it. Machine bookkeeping columns are dropped: a stage cell naming the stage the card is
+ sitting at would be the model reading its own question back."""
+ keys = [k for k in (fields or list((row or {}).keys()))
+ if not str(k).startswith("stage_")][:MAX_FIELDS]
+ lines = []
+ for k in keys:
+ v = (row or {}).get(k)
+ if v is None or str(v).strip() == "":
+ continue
+ lines.append(f"{k}: {str(v)[:MAX_FIELD_CHARS]}")
+ return "\n".join(lines) or "(this record has no filled-in values)"
+
+
+def _instruction(prompt, options, label):
+ return (
+ f"You are deciding what happens to one record waiting at a review step called "
+ f"{label!r} in a workflow.\n\n"
+ f"The person who built this workflow told you: {prompt}\n\n"
+ f"Choose EXACTLY ONE of these next steps, by its exact name:\n"
+ + "\n".join(f"- {o}" for o in options)
+ + "\n\nAnswer with one line of JSON and nothing else:\n"
+ '{"choice": "", "reason": ""}\n'
+ "If the record does not give you enough to decide, answer "
+ '{"choice": "", "reason": "why not"} and a person will decide instead.'
+ )
+
+
+def _parse(text, options):
+ """The model's line → `(choice, reason)`. A choice that is not one of the offered stages is
+ DISCARDED, not fuzzy-matched: the offered list is a permission boundary, and a near-miss
+ resolved by string distance is how a card ends up somewhere nobody authorised."""
+ raw = str(text or "").strip()
+ obj = None
+ m = re.search(r"\{.*\}", raw, re.S)
+ if m:
+ try:
+ obj = json.loads(m.group(0))
+ except (ValueError, TypeError):
+ obj = None
+ if not isinstance(obj, dict):
+ return "", ""
+ choice = str(obj.get("choice") or "").strip()
+ reason = str(obj.get("reason") or "").strip()[:MAX_REASON]
+ for opt in options:
+ if choice.lower() == str(opt).lower():
+ return str(opt), reason # the OFFERED spelling wins, never the model's
+ return "", reason
+
+
+def _call_openai(p, model, system, user, timeout):
+ r = requests.post(p["url"], timeout=timeout,
+ headers={"Authorization": f"Bearer {os.environ[p['env']].strip()}",
+ "Content-Type": "application/json"},
+ json={"model": model, "max_tokens": 300, "temperature": 0,
+ "messages": [{"role": "system", "content": system},
+ {"role": "user", "content": user}]})
+ if r.status_code >= 400:
+ return "", f"{p['name']} answered {r.status_code}"
+ body = r.json()
+ choices = body.get("choices") or []
+ if not choices:
+ return "", f"{p['name']} returned no choices"
+ return str(((choices[0] or {}).get("message") or {}).get("content") or ""), ""
+
+
+def _call_anthropic(p, model, system, user, timeout):
+ r = requests.post(p["url"], timeout=timeout,
+ headers={"x-api-key": os.environ[p["env"]].strip(),
+ "anthropic-version": ANTHROPIC_VERSION,
+ "content-type": "application/json"},
+ json={"model": model, "max_tokens": 300, "system": system,
+ "messages": [{"role": "user", "content": user}]})
+ if r.status_code >= 400:
+ return "", f"anthropic answered {r.status_code}"
+ body = r.json()
+ # ⛔ stop_reason FIRST. A safety refusal is a successful 200 with an EMPTY content list, so
+ # reading content[0] before this check turns a refusal into an IndexError inside a run.
+ if body.get("stop_reason") == "refusal":
+ return "", "anthropic declined to answer this record"
+ parts = [b.get("text") or "" for b in (body.get("content") or [])
+ if isinstance(b, dict) and b.get("type") == "text"]
+ if not parts:
+ return "", "anthropic returned no text"
+ return "".join(parts), ""
+
+
+def decide(*, prompt, options, row, fields=(), label="Review", timeout=None):
+ """Pick this record's next stage. Returns `(choice, meta)`.
+
+ `choice` is "" whenever a person should decide — which is every failure mode there is.
+ `meta` carries `provider`, `model`, `reason` on success, and `problem` on refusal to answer.
+ """
+ opts = [str(o) for o in (options or []) if str(o).strip()]
+ if not opts:
+ return "", {"problem": "the review offers no next stages"}
+ if not str(prompt or "").strip():
+ return "", {"problem": "the review has no prompt for the model to follow"}
+ live = ladder()
+ if not live:
+ return "", {"problem": "no AI provider is configured on this deployment"}
+ system = _instruction(prompt, opts, label)
+ user = "Here is the record:\n\n" + _record_text(row, fields)
+ tmo = float(timeout or TIMEOUT_SECONDS)
+ override = (os.environ.get("AIOS_AI_MODEL") or "").strip()
+ problems = []
+ for p in live:
+ model = override or p["model"]
+ try:
+ text, err = (_call_anthropic if p["shape"] == "anthropic" else _call_openai)(
+ p, model, system, user, tmo)
+ except Exception as e: # noqa: BLE001
+ text, err = "", f"{p['name']} failed: {type(e).__name__}"
+ if err:
+ problems.append(err)
+ continue # ladder: a dead provider degrades to the next one
+ choice, reason = _parse(text, opts)
+ if not choice:
+ # The provider ANSWERED and declined (or answered unusably). That is a decision about
+ # this record, not a fault in the provider, so it does NOT fall through to a more
+ # expensive one — the card goes to a human, which is what the model just asked for.
+ return "", {"provider": p["name"], "model": model,
+ "problem": reason or "the model did not choose one of the stages"}
+ return choice, {"provider": p["name"], "model": model, "reason": reason}
+ return "", {"problem": "; ".join(problems)[:300] or "no provider answered"}
diff --git a/api/automation_engine.py b/api/automation_engine.py
index d7b5fc43821353b8b855281dd72e13a02ea648fa..70d2264f9c821b32d7faa696e25a3c524671b192 100644
--- a/api/automation_engine.py
+++ b/api/automation_engine.py
@@ -24,6 +24,7 @@ the skill version takes a URL from a developer on a CLI; this takes one from a r
from __future__ import annotations
import datetime as _dt
+import hmac
import ipaddress
import json
import os
@@ -93,7 +94,29 @@ IG_TABLE_PREFIX = "ut_ig_"
#: that stays true when the next `ut_ig_*` table is not one.
APPEND_TABLES = frozenset({"ut_ig_snapshots", "ut_ig_post_snapshots"})
-KINDS = ("scrape_db", "field_instagram", "discover_instagram")
+#: ⭐ WAVE 24 (owner ruling R6) — `plain` IS WHAT AN AUTOMATION IS NOW, and it is the DEFAULT.
+#: The create wizard is deleted, so nobody picks a kind any more: a new automation is a trigger
+#: plus actions and NO machine step. The other three are MACHINE kinds — a scrape, an Instagram
+#: column, an Instagram search — and they survive on the automations that already use them
+#: (`discover_instagram` stays reachable through the `ig_profile_match` trigger; see C-TRIG).
+#:
+#: ⚠ ADDING A KIND HERE IS THE SMALL HALF, and the reason is worth reading before adding a fifth:
+#: TWO dispatches in this file used to end in a bare `else` that belonged to a SPECIFIC kind
+#: rather than to a default — `graph()`'s was `scrape_db`'s and `compose_sentence`'s was
+#: `discover_instagram`'s. A kind added here alone would have inherited another kind's whole
+#: description: three machine nodes it does not have, and a one-line summary about searching
+#: Instagram for up to 0 profiles. Both are explicit arms now, and neither has an `else`.
+KINDS = ("plain", "scrape_db", "field_instagram", "discover_instagram")
+#: What a definition with no kind becomes (C-TRIG law 2) — the shape `POST /automations` stores
+#: when the body names none, which after R6 is every create the client makes.
+DEFAULT_KIND = "plain"
+#: R6: no NEW automation may be either of these. They still RUN, still PATCH and still validate —
+#: the ruling retires the door, not the two automations behind it (see `create`).
+#: ⚠ `discover_instagram` is NOT here: it stays creatable, through the `ig_profile_match` trigger.
+RETIRED_KINDS = ("scrape_db", "field_instagram")
+KIND_LABELS = {"plain": "Automation", "scrape_db": "Web page to database",
+ "field_instagram": "Instagram profile column",
+ "discover_instagram": "Find Instagram profiles"}
EXTRACTS = ("table", "jsonld")
STATES = ("idle", "running", "ok", "error", "partial")
#: Which capture rung a `field_instagram` automation is allowed to reach for (R1's hybrid).
@@ -849,6 +872,25 @@ def clean_config(kind, raw, previous=None):
def flag(name):
return bool(raw[name]) if name in raw else bool(prev.get(name))
+ if kind == "plain":
+ # ⭐ WAVE 24 / R6 — a plain automation has no machine step, so it has almost no config:
+ # the database its records walk, and the board's lane router.
+ #
+ # ⚠ THE TARGET IS OPTIONAL ON PURPOSE. An automation triggered by `record_updated` on
+ # `ut_foo` already knows its table from the trigger — `_flow_table` resolves target-else-
+ # trigger — so requiring a second copy of that fact here would be a mandatory field with
+ # exactly one legal answer, and a Save that refuses until you retype what you just picked.
+ # There is no `dryRun`: dry-run means "run the machine step but do not write", and there
+ # is no machine step to run.
+ target = _s(raw.get("targetTable"), 60).strip()
+ if target and not target.startswith(UT_PREFIX):
+ target = UT_PREFIX + target
+ lanes, lerr = clean_lanes(raw.get("lanes") if "lanes" in raw else prev.get("lanes"))
+ if lerr:
+ return None, lerr
+ return {"targetTable": target,
+ "targetLabel": _s(raw.get("targetLabel"), 60).strip(),
+ "lanes": lanes}, None
if kind == "scrape_db":
url = _s(raw.get("url"), 2000).strip()
if not url:
@@ -916,7 +958,12 @@ def clean_config(kind, raw, previous=None):
"one shape the vendor refuses outright (NOT_ENOUGH_FUNDS)")
if limit > BD_MAX_RECORDS:
return None, f"a single discovery run may ask for at most {BD_MAX_RECORDS} profiles"
- preds, perr = clean_predicates(raw.get("predicates"))
+ # ⚠ THE JOIN IS RESOLVED BEFORE THE PREDICATES ARE JUDGED, because it is part of what
+ # makes them broad or narrow (see `narrowing_refusal`). Validating them first and reading
+ # the operator afterwards is how the OR hole survived: the guard was handed the branches
+ # and never told they were a union.
+ join = "or" if str(raw.get("operator") or "").lower() == "or" else "and"
+ preds, perr = clean_predicates(raw.get("predicates"), join)
if perr:
return None, perr
if raw.get("lanes") if "lanes" in raw else prev.get("lanes"):
@@ -928,7 +975,7 @@ def clean_config(kind, raw, previous=None):
if not target.startswith(UT_PREFIX):
target = UT_PREFIX + target
return {"recordsLimit": limit, "predicates": preds,
- "operator": "or" if str(raw.get("operator") or "").lower() == "or" else "and",
+ "operator": join,
"targetTable": target,
"targetLabel": _s(raw.get("targetLabel"), 60).strip() or "IG candidates",
"dryRun": flag("dryRun")}, None
@@ -949,34 +996,196 @@ def clean_schedule(raw, previous=None):
return out
+# ── WAVE 23 · C5 — the ENDING, and the cycle counter that makes a loop countable. ─────────────
+# The owner's words: "we can make this automation a loop, so the ending should always be defined,
+# either it ends somewhere deterministic like Closed/Failed, or it goes to reset automatically,
+# or the user have to click a button to reset, or after a certain amount of time it can
+# automatically reset to first cycle."
+#
+# ⛔ `terminal` IS THE DEFAULT and every existing automation gets it, because a stored definition
+# that predates this field must not start moving records on its own the day the code ships. A
+# loop is a thing somebody turns on.
+ENDING_MODES = ("terminal", "auto_reset", "manual_reset", "timed_reset")
+MAX_RESET_HOURS = 720 # 30 days; past that "it resets eventually" is a lie
+#: The per-record cycle counter's cell suffix, beside `stage_` and `stage__at`.
+CYCLES_SUFFIX = "_cycles"
+
+
+def cycles_field_key(auto_id):
+ return stage_field_key(auto_id) + CYCLES_SUFFIX
+
+
+def clean_ending(raw, previous=None):
+ """Validate `{mode, hours?}`. Returns `(ending, error)`."""
+ raw = raw if isinstance(raw, dict) else {}
+ prev = previous if isinstance(previous, dict) else {}
+ mode = _s(raw.get("mode") or prev.get("mode"), 20).strip() or "terminal"
+ if mode not in ENDING_MODES:
+ return None, f"{mode!r} is not one of: " + ", ".join(ENDING_MODES)
+ out = {"mode": mode}
+ if mode == "timed_reset":
+ try:
+ hours = int(raw.get("hours") if raw.get("hours") is not None else prev.get("hours")
+ or 24)
+ except (TypeError, ValueError):
+ return None, "the reset delay must be a whole number of hours"
+ if hours < 1 or hours > MAX_RESET_HOURS:
+ return None, f"the reset delay is between 1 and {MAX_RESET_HOURS} hours"
+ out["hours"] = hours
+ return out, None
+
+
+def clean_flow(raw, previous=None):
+ """Validate `{actions, ending}` — the builder's half of a definition. `(flow, error)`."""
+ raw = raw if isinstance(raw, dict) else {}
+ prev = previous if isinstance(previous, dict) else {}
+ actions, err = clean_actions(raw.get("actions") if "actions" in raw else prev.get("actions"))
+ if err:
+ return None, err
+ ending, err = clean_ending(raw.get("ending") if "ending" in raw else prev.get("ending"),
+ prev.get("ending"))
+ if err:
+ return None, err
+ return {"actions": actions, "ending": ending}, None
+
+
+#: AMENDMENT A1 — what the `ig_profile_match` kind-flip seeds as `recordsLimit` when the
+#: definition carries none.
+#:
+#: ⚠ 25 BECAUSE THE INPUT SAYS 25 (2026-08-06). It was 10 — the size wave 21 proved live at
+#: $0.15 — while `AutomationDetail` initialises its own box to 25, and the two never met: the
+#: flow node read "Up to 10 profiles · about $0.025" beside a field reading 25, on a freshly
+#: created automation. Two numbers for one fact, in the panel, before anybody had typed
+#: anything. **Read off the screenshot; every assertion in the battery was green.**
+#:
+#: This is the same species as the default-versus-guard split fixed the same day: a value
+#: decided in one file and a value decided in another, describing the same thing. Aligning the
+#: constants closes the only window in which they can disagree — the seed — because every later
+#: state comes from the stored config.
+DISCOVER_SEED_RECORDS = 25
+
+
+def _ensure_ig_action(flow_raw, table):
+ """Create record is PERMANENT step 1 on `ig_profile_match` — it cannot be deleted or moved.
+
+ ⭐ OWNER RULING 2026-08-06, AND IT REVERSES WAVE 24's LAW 3. That law seeded this action once,
+ on the edge into the trigger, and ended "deleting it is their call, not a refusal" — with a
+ comment warning that re-seeding on every clean would be "a control that will not take no for
+ an answer". The owner's answer: *"should ALWAYS have a 'Create record' Step 1, that can't be
+ deleted, because the nature of that automation is that it needs to first create a record in a
+ database somewhere from the list of profiles to fetch."*
+
+ Which is right, and the earlier reasoning had the category wrong: a flow whose TRIGGER
+ produces rows has nowhere to put them until something writes them, so an Instagram search
+ with no Create record is not a customised automation — it is a search whose results are
+ discarded. That is not a preference to respect.
+
+ ⚠ IT KEEPS THE USER'S EDITS. Presence and POSITION are guaranteed; the table it writes to and
+ the values it maps are theirs. An existing `create_record` further down is MOVED to the front
+ rather than duplicated — re-seeding a second one would quietly double every run's writes.
+ """
+ flow = dict(flow_raw or {}) if isinstance(flow_raw, dict) else {}
+ actions = [a for a in (flow.get("actions") or []) if isinstance(a, dict)]
+ if actions and actions[0].get("kind") == "create_record":
+ return flow_raw if isinstance(flow_raw, dict) else flow
+ at = next((i for i, a in enumerate(actions) if a.get("kind") == "create_record"), -1)
+ if at > 0:
+ actions.insert(0, actions.pop(at))
+ else:
+ # The seed must be a config `clean_actions` ACCEPTS, or the builder shows a red banner
+ # and no card: the wave-23 header records four kinds that shipped with illegal seeds and
+ # did exactly that. `create_record` needs a ut_-prefixed table and at least one value.
+ actions.insert(0, {
+ "id": "act_1", "kind": "create_record", "enabled": True, "when": None,
+ # `config.label` follows the `review` action's precedent in `_clean_action_config` —
+ # an action naming itself, inside the untyped config bag, so no shared TS type changes.
+ "config": {"table": str(table or DISCOVER_TABLE),
+ "label": "Save the profile",
+ "values": {"handle": "{{handle}}"}},
+ })
+ flow["actions"] = actions
+ return flow
+
+
+def ig_action_pinned(defn, index):
+ """Is this action the one that cannot be removed? Derived, never stored — a stored `pinned`
+ flag is a second copy of the rule, and the copy is what a hand-written PATCH omits."""
+ return (defn or {}).get("kind") == "discover_instagram" and index == 0
+
+
def clean_definition(raw, previous=None, username=""):
"""Whole-definition validation. Returns `(defn, error)`."""
raw = raw if isinstance(raw, dict) else {}
prev = previous or {}
- kind = _s(raw.get("kind") or prev.get("kind"), 40)
+ # ⭐ WAVE 24 · C-TRIG — THE TRIGGER IS RESOLVED FIRST NOW, because law 1 makes it the thing
+ # that CHOOSES the kind. Reading `raw["trigger"]["key"]` here instead would be a second
+ # reader of the trigger vocabulary, free to disagree with `clean_trigger` about which keys
+ # exist and which are refused. Gate-visible consequence, recorded in AMENDMENT A1: a payload
+ # invalid in BOTH its trigger and its config now answers with the trigger's sentence.
+ trigger, terr = clean_trigger(raw.get("trigger") if "trigger" in raw
+ else prev.get("trigger"), prev.get("trigger"))
+ if terr:
+ return None, terr
+ # C-TRIG law 2 (wave 24): a definition that names no kind is a `plain` one. Before R6 this
+ # refused with "unknown automation kind ''" — correct while a wizard always sent one, and a
+ # dead end the moment the wizard was deleted and the client's create body became {name}.
+ kind = _s(raw.get("kind") or prev.get("kind"), 40) or DEFAULT_KIND
+ if (trigger or {}).get("key") == "ig_profile_match":
+ # LAW 1: the trigger IS how `discover_instagram` gets chosen now. Unconditional rather
+ # than "when the kind is unset" — a definition whose trigger says Instagram-discovery and
+ # whose kind says something else is not a preference to respect, it is two halves of one
+ # answer disagreeing, and the trigger is the half the person actually picked.
+ kind = "discover_instagram"
if kind not in KINDS:
return None, f"unknown automation kind {kind!r}"
name = " ".join(_s(raw.get("name") or prev.get("name") or "", MAX_NAME).split())
if not name:
return None, "name the automation"
cfg_raw = raw.get("config") if isinstance(raw.get("config"), dict) else prev.get("config")
+ if kind == "discover_instagram" and prev.get("kind") != "discover_instagram":
+ # AMENDMENT A1: the kind FLIP seeds the one field `clean_config` insists on, or the very
+ # first Save after picking this trigger 400s — against the stored-inert-with-
+ # `configured:false` pattern the whole picker is built on (see `clean_trigger`'s A3 note).
+ # ⛔ THE REFUSAL ITSELF IS UNTOUCHED: an explicit 0 still gets its sentence. That guard
+ # exists because an unbounded query is the one shape the vendor refuses outright, and
+ # coercing a blank into a number would be exactly the silent widening it protects against.
+ # Seeding cannot spend — `clean_schedule` defaults `enabled` False, so nothing runs until
+ # a person presses Run now or arms the schedule.
+ cfg_raw = dict(cfg_raw or {})
+ if not _ig_int(cfg_raw.get("recordsLimit")):
+ cfg_raw["recordsLimit"] = DISCOVER_SEED_RECORDS
config, err = clean_config(kind, cfg_raw, prev.get("config"))
if err:
return None, err
+ if trigger:
+ # A2: re-ask completeness now that the config is validated — `ig_profile_match`'s own
+ # configuration IS the config, and `clean_trigger` could not see it.
+ trigger["configured"] = _trigger_configured(trigger, config)
try:
schedule = clean_schedule(
raw.get("schedule") if isinstance(raw.get("schedule"), dict)
else prev.get("schedule"), prev.get("schedule"))
except ValueError as e:
return None, str(e)
- trigger, terr = clean_trigger(raw.get("trigger") if "trigger" in raw
- else prev.get("trigger"), prev.get("trigger"))
- if terr:
- return None, terr
+ # (`clean_trigger` ran at the top — law 1 needs the trigger before the kind.)
+ flow_raw = raw.get("flow") if "flow" in raw else prev.get("flow")
+ # ⭐ EVERY CLEAN, NOT ONLY THE EDGE (owner ruling 6 — see `_ensure_ig_action`). The edge-only
+ # call was what made the action deletable; running it on every save is what makes step 1
+ # permanent, and it is deliberate rather than a widened condition nobody noticed.
+ if (trigger or {}).get("key") == "ig_profile_match":
+ flow_raw = _ensure_ig_action(flow_raw, config.get("targetTable") or DISCOVER_TABLE)
+ flow, ferr = clean_flow(flow_raw, prev.get("flow"))
+ if ferr:
+ return None, ferr
return {
"id": _s(prev.get("id") or raw.get("id"), 40),
"name": name, "kind": kind, "config": config, "schedule": schedule,
"trigger": trigger,
+ # WAVE 23 · C4/C5 — the BUILDER's half: the ordered actions a record walks and what
+ # happens when it reaches the end. Absent on every definition written before this wave,
+ # which is exactly why `clean_flow` defaults it to "no actions, terminal ending": the
+ # code shipping must not put existing automations into a loop.
+ "flow": flow,
"status": prev.get("status") or {"state": "idle", "lastRunAt": "", "lastSummary": ""},
"runs": list(prev.get("runs") or [])[:MAX_RUNS],
# C3-A2(5): the review-decision audit survives a Save the way `state` does — an
@@ -1027,13 +1236,108 @@ def _new_id(existing):
return f"auto_{n}"
+#: C2's three answers to "which database does this automation work on?" — the FIRST question the
+#: create wizard asks (owner item 3: the kind is not the first thing a person picks, the data is).
+TARGET_MODES = ("existing", "new", "automated")
+
+
+def resolve_target(rt, raw, username=""):
+ """C2: turn the wizard's `target` into a bound table key. Returns `(config_patch, error)`.
+
+ - `existing` — bind a database that is already there.
+ - `new` — mint a blank one now, so the automation has somewhere to write before its first
+ run instead of conjuring a table the person never agreed to.
+ - `automated` — leave it to the runner: a scraping automation MINTS its target on first run
+ (`ut_ensure`), stamped `source: "Automation"`, which is what makes it a machine database.
+ Nothing is created here, deliberately — an empty table created up front for a scrape that
+ never runs is litter nobody can explain.
+ """
+ if not isinstance(raw, dict) or not raw:
+ return {}, None # no target block = the pre-wizard shape
+ mode = _s(raw.get("mode"), 20).strip() or "existing"
+ if mode not in TARGET_MODES:
+ return None, f"{mode!r} is not one of: " + ", ".join(TARGET_MODES)
+ if mode == "automated":
+ label = " ".join(_s(raw.get("label"), 60).split())
+ return ({"targetLabel": label} if label else {}), None
+ if mode == "existing":
+ key = _s(raw.get("table"), 60).strip()
+ if not key:
+ return None, "choose the database this automation works on"
+ t = ut_get(rt, key)
+ if t is None:
+ return None, f"{key!r} is not a database in this workspace"
+ return {"targetTable": key, "targetLabel": t.get("label") or key}, None
+ label = " ".join(_s(raw.get("label"), 60).split())
+ if not label:
+ return None, "name the new database"
+ import core.user_tables as _ut_new
+ key = _ut_new.create(label, username or "automation", st=rt)
+ if not key:
+ return None, ("the database could not be created — this workspace may be at its table "
+ "limit")
+ return {"targetTable": key, "targetLabel": label}, None
+
+
+def _unmint(rt, key):
+ """Delete a database this call minted moments ago, because the call is refusing (D-50).
+
+ ⚠ FAIL-QUIET BY DESIGN. The caller is already returning a refusal with a sentence the user
+ needs to read; a rollback that raised would replace that sentence with a 500 and lose the
+ reason the create failed in the first place. The worst case of a swallowed failure here is
+ the orphan we had before — strictly no worse, and the refusal still reaches the person.
+ """
+ if not key:
+ return
+ try:
+ import core.user_tables as _ut_del
+ _ut_del.delete(key, st=rt)
+ except Exception: # noqa: BLE001
+ pass
+
+
def create(rt, raw, username=""):
existing = all_definitions(rt)
if len(existing) >= MAX_AUTOMATIONS:
return None, f"this workspace is at the {MAX_AUTOMATIONS}-automation limit"
+ raw = dict(raw or {})
+ # ⭐ WAVE 24 — DEBT D-50. `resolve_target` MINTS a database for `mode:"new"`, and validation
+ # happens after it, so a correct refusal ("a source URL is required") used to leave an
+ # orphaned `ut_*` table behind with no automation pointing at it. MEASURED at the W23 close:
+ # three refused creates, two orphaned databases, deleted by hand. A person mis-filling a form
+ # twice silently accumulated empty databases in their nav.
+ #
+ # ⛔ THE ROLLBACK IS DERIVED, NOT DECLARED, and that is the point of doing it this way. It
+ # does not test for `mode == "new"`; it asks "did the table this call's target resolved to
+ # exist BEFORE this call?" So it closes the hole for any future target mode that mints, and
+ # a fifth mode cannot reopen it by forgetting a branch. Scoped to THIS call's own target
+ # rather than "any table that appeared", so a concurrent create in another request is never
+ # collateral.
+ before = set(ut_all(rt) or {})
+ patch_cfg, terr = resolve_target(rt, raw.pop("target", None), username)
+ if terr:
+ return None, terr
+ minted = str((patch_cfg or {}).get("targetTable") or "")
+ minted = minted if minted and minted not in before else ""
+ if patch_cfg:
+ raw["config"] = {**(raw.get("config") or {}), **patch_cfg}
defn, err = clean_definition(raw, None, username)
if err:
+ _unmint(rt, minted)
return None, err
+ # ⭐ WAVE 24 · OWNER RULING R6 — "scrape_db and field_instagram survive on the automations
+ # that already use them and NO NEW ONE CAN BE CREATED."
+ #
+ # ⛔ HERE, IN `create`, AND NEVER IN `clean_definition`. A PATCH of one of the two live
+ # automations runs through `clean_definition` with `prev["kind"]` already set, so refusing
+ # the kind there would make both of them unsaveable — the ruling retires the door, not the
+ # automations behind it. Enforced on the server rather than left to the deleted wizard: a
+ # wall that holds only because the client stopped asking is a convention, not a wall.
+ if defn["kind"] in RETIRED_KINDS:
+ _unmint(rt, minted)
+ return None, (f"{KIND_LABELS.get(defn['kind'], defn['kind'])!r} automations are no "
+ f"longer created — the ones already using it keep working. Start a new "
+ f"automation and pick its trigger instead")
defn["id"] = _new_id(existing)
def _up(cur):
@@ -1054,7 +1358,12 @@ def patch(rt, auto_id, raw, username=""):
if prev is None:
return None, "no such automation"
merged = dict(prev)
- for k in ("name", "config", "schedule", "kind", "trigger"):
+ # ⚠ A HAND-MAINTAINED PATCHABLE-KEY LIST, and it is the silent-drop seat of this module: a
+ # key missing here is accepted by the route, validated by `clean_definition`, and then
+ # DISCARDED — the client shows a saved flow that the store never received, and nothing goes
+ # red. `flow` joined it in the same edit that created `flow` (wave 23), which is the only
+ # ordering that never has a window where the bug exists.
+ for k in ("name", "config", "schedule", "kind", "trigger", "flow"):
if k in (raw or {}):
merged[k] = raw[k]
defn, err = clean_definition(merged, prev, username)
@@ -1080,8 +1389,15 @@ def _stage_field_after_write(rt, defn, username):
"""C2's 'at automation create (or first bind)': when the target database already exists,
the stage field appears/refreshes with the definition write — a patch that adds a lane
grows the select's vocabulary in the same breath. A table that does not exist yet gets its
- field from the first RUN instead (the runner ensures after `ut_ensure`)."""
- tgt = str((defn.get("config") or {}).get("targetTable") or "")
+ field from the first RUN instead (the runner ensures after `ut_ensure`).
+
+ ⭐ WAVE 24 — resolved through `_flow_table` rather than reading `config.targetTable` directly,
+ because a `plain` automation is allowed to take its table from its TRIGGER (see `clean_config`
+ on why the target is optional). Reading the config alone left exactly those automations
+ without a stage field, so their board stayed permanently empty — `board()` answers
+ `cards: []` until the field is bound, which looks like "no records" rather than "no field".
+ """
+ tgt = str(_flow_table(defn) or "")
if tgt and ut_get(rt, tgt) is not None:
ensure_stage_field(rt, tgt, defn, username)
@@ -1142,6 +1458,12 @@ def _step(tenant, auto_id, text):
cur["step"] = text
+def _no_step(_text):
+ """The default `step` sink for a runner nobody gave a live slot to (a gate driving a runner
+ directly). A runner must never REQUIRE the slot — the slot is process state, and the runner
+ is the part a test is allowed to call on its own."""
+
+
def _release(tenant, auto_id):
with _RUN_LOCK:
_RUNNING.pop((tenant, str(auto_id)), None)
@@ -1484,23 +1806,23 @@ def bd_call(path, params=None, body=None):
headers=hdrs)
except Refused as e:
# The BASE was refused by the SSRF rail — a configuration fault, not a vendor outage.
- return None, f"the Bright Data base URL was refused by the URL rail: {e}"
+ return None, f"the profile source's address was refused by the URL rail: {e}"
except Exception as e: # noqa: BLE001
# ⚠ `type(e).__name__` only. A requests exception's str() can carry the full URL, and the
# Authorization header is one refactor away from being a query param; this line must not
# be what leaks it.
- return None, f"Bright Data did not answer ({type(e).__name__})"
+ return None, f"the profile source did not answer ({type(e).__name__})"
if status == 402:
- return None, "Bright Data answered 402 — the account is out of credit"
+ return None, "the profile search is out of credit"
if status in (401, 403):
- return None, f"Bright Data refused the key ({status})"
+ return None, f"the profile source refused our key ({status})"
if status == 429:
# ⚠ MEASURED during the discovery probe: `too_many_parallel_jobs`. The filter API has a
# concurrency cap and the probe's most important test died on it — hence every caller
# below is SERIAL by construction.
- return None, "Bright Data answered 429 — too many parallel jobs; the calls are serialised"
+ return None, "the profile source is busy with another search; they run one at a time"
if not (200 <= status < 300):
- return None, f"Bright Data answered {status}"
+ return None, f"the profile source answered {status}"
# ⛔ A BODY THAT REACHED THE READ CEILING IS A TRUNCATION, AND IT MUST SAY SO. `fetch` reads
# at most `max_kb` and returns what it got — silently. A truncated JSON document then fails
# `json.loads`, falls through to the NDJSON branch, and comes back as "answered with
@@ -1508,12 +1830,12 @@ def bd_call(path, params=None, body=None):
# looking for a fault that is OUR byte ceiling — after a result set that has already been
# paid for. Naming it here is the same no-silent-caps rule the row and table ceilings follow.
if len(raw) >= BD_MAX_KB * 1024:
- return None, (f"Bright Data's answer exceeded this client's {BD_MAX_KB // 1024} MB read "
+ return None, (f"the profile source's answer exceeded this client's {BD_MAX_KB // 1024} MB read "
f"ceiling and was TRUNCATED — ask for fewer records; nothing was parsed "
f"from a partial document")
text = raw.decode("utf-8", "replace").strip()
if not text:
- return None, f"Bright Data answered {status} with an empty body"
+ return None, f"the profile source answered {status} with an empty body"
try:
return json.loads(text), ""
except Exception: # noqa: BLE001
@@ -1528,8 +1850,8 @@ def bd_call(path, params=None, body=None):
try:
rows.append(json.loads(line))
except Exception: # noqa: BLE001
- return None, "Bright Data answered with something that is not JSON"
- return (rows, "") if rows else (None, "Bright Data answered with something that is not JSON")
+ return None, "the profile source answered with something we could not read"
+ return (rows, "") if rows else (None, "the profile source answered with something we could not read")
def _first(node, *names, default=None):
@@ -1844,7 +2166,7 @@ def bd_scrape(dataset_id, urls, wait=None):
waited += BD_SCRAPE_POLL
# ⛔ NAME THE SNAPSHOT. It has been paid for and it is still finishing; a note that said only
# "no rows" would throw away both the data and the way to get it.
- return [], (f"Bright Data deferred this batch to snapshot {sid} and it was not ready within "
+ return [], (f"the profile source deferred this batch to {sid} and it was not ready within "
f"{int(budget)}s — the records are collected, not lost; ask for a smaller batch "
f"or collect {sid} from the control panel")
@@ -1875,7 +2197,7 @@ def pull_profile_bd(url, max_posts=24, post_metrics=False, log=print):
# ⚠ `posts_count` is deliberately NOT part of this test: it arrives as a fabricated 0 and
# is discarded, so a row where it is the only "readable" field is a row we cannot read.
return {"state": "blocked", "profile": {}, "posts": [], "via": "brightdata",
- "note": "Bright Data answered, but no follower/following counts were readable in "
+ "note": "the profile source answered, but no follower/following counts were readable in "
"it (the field names may have moved — see instagram-capture.md)"}
posts = []
for p in (node.get("posts") or [])[:max_posts]:
@@ -1910,7 +2232,7 @@ def pull_profile_bd(url, max_posts=24, post_metrics=False, log=print):
# over a posts table that did not grow.
return {"state": "ok" if posts else "partial", "profile": profile, "posts": posts,
"via": "brightdata",
- "note": note or ("" if posts else "profile read; Bright Data returned no posts")}
+ "note": note or ("" if posts else "profile read; no posts were returned")}
# ---------------------------------------------------------------------------------------------
@@ -2014,6 +2336,147 @@ BD_POPULATED_FIELDS = frozenset({
"full_name", "profile_name", "highlights_count", "id", "fbid", "profile_url"})
BD_MIN_NARROWING = 1
+# ── THE FIELD SCHEMA — what a person sees, and what they are allowed to ask. ──────────────────
+# ⛔ THE SURFACE USED TO SHOW THE VENDOR'S OWN COLUMN NAMES AND ALL FOURTEEN OPERATORS ON EVERY
+# ROW. So `is_business_account` offered `>=`, `fbid` sat in the list with no explanation of what
+# it is, and `not_array_includes` was a thing a customer was expected to reason about. Owner:
+# *"look at each damn schema and only provide toggles operator that make sense"*.
+#
+# ⚠ THE LABEL IS NOW LOAD-BEARING IN BOTH DIRECTIONS. The old comment in `AutomationFind.tsx`
+# defended raw names on the grounds that a refusal names the field exactly as the row does — and
+# it was right, which is why `field_label()` is used by the REFUSALS too. Prettifying only the UI
+# is how you get an error message about `bio_hashtags` on a row labelled "Hashtags in bio".
+BD_FIELD_LABELS = {
+ "followers": "Followers", "following": "Following", "posts_count": "Posts",
+ "avg_engagement": "Engagement rate", "biography": "Bio", "category_name": "Category",
+ "business_category_name": "Business category", "is_business_account": "Business account",
+ "is_professional_account": "Professional account", "is_verified": "Verified",
+ "account": "Handle", "full_name": "Name", "profile_name": "Profile name",
+ "external_url": "Link in bio", "profile_url": "Profile link",
+ "bio_hashtags": "Hashtags in bio", "post_hashtags": "Hashtags in posts",
+ "related_accounts": "Related accounts", "id": "Instagram ID", "fbid": "Facebook ID",
+ "highlights_count": "Story highlights",
+}
+#: A one-line "what IS this" for the rows nobody can be expected to guess. Absent = self-evident;
+#: a hint on all 21 rows is a hint on none of them (the wave-24 chip lesson).
+BD_FIELD_HINTS = {
+ "account": "The @username",
+ "avg_engagement": "Likes and comments as a share of followers",
+ "id": "Instagram's internal number for the account — for matching a list you already have",
+ "fbid": "The linked Facebook id — for matching a list you already have",
+ "profile_name": "The name shown above the bio, when it differs from the account name",
+ "related_accounts": "Accounts Instagram suggests alongside this one",
+}
+#: The KIND decides the comparisons offered and the control drawn for the value.
+BD_FIELD_KINDS = {
+ **{n: "number" for n in ("followers", "following", "posts_count", "avg_engagement",
+ "highlights_count")},
+ **{n: "boolean" for n in ("is_business_account", "is_professional_account", "is_verified")},
+ **{n: "tags" for n in ("bio_hashtags", "post_hashtags", "related_accounts")},
+ **{n: "choice" for n in ("category_name", "business_category_name")},
+ **{n: "text" for n in ("biography", "account", "full_name", "profile_name", "external_url",
+ "profile_url", "id", "fbid")},
+}
+#: ⛔ ONLY WHAT MAKES SENSE, and the ORDER is the order they are offered in — the first entry of
+#: each list is what `default_operator` must agree with.
+BD_OPS_BY_KIND = {
+ # ⚠ `in`/`not_in` are DELIBERATELY ABSENT. "is any of" is what `=` becomes the moment a second
+ # value is typed (see `BD_MULTI_VALUE_OPS`), so offering both would be two controls for one
+ # idea — and the second one is the one written in vendor grammar.
+ "text": ("includes", "not_includes", "=", "is_not_null", "is_null"),
+ "choice": ("=", "!=", "is_not_null", "is_null"),
+ "number": (">=", "<=", "=", ">", "<"),
+ # A yes/no field has exactly one sensible comparison and a two-option value. `!=` on a boolean
+ # is `=` with the other value, written the confusing way.
+ "boolean": ("=",),
+ "tags": ("array_includes", "not_array_includes", "is_not_null", "is_null"),
+}
+#: Plain English for every comparison the surface can offer. The vendor's token stays on the wire
+#: (it is what the API accepts); nobody has to read it.
+BD_OP_LABELS = {
+ "includes": "contains", "not_includes": "does not contain",
+ "=": "is", "!=": "is not", "in": "is any of", "not_in": "is none of",
+ ">=": "at least", "<=": "at most", ">": "more than", "<": "less than",
+ "array_includes": "has any of", "not_array_includes": "does not have",
+ "is_null": "is empty", "is_not_null": "is not empty",
+}
+#: Yes/No, so a boolean is a two-item dropdown instead of a box you type `true` into.
+BD_BOOLEAN_OPTIONS = [{"value": "true", "label": "Yes"}, {"value": "false", "label": "No"}]
+
+#: ⭐ THE OPERATORS THAT MAY CARRY SEVERAL VALUES — owner item 3, "if i want to include many
+#: keywords like floral, flower, beauty". One condition row holds the list; `bd_filter_start`
+#: expands it into a NESTED OR group, so it composes with the other conditions instead of forcing
+#: the whole search to "match any" (which would also drag Followers into the union — the hole the
+#: OR guard closed the same day).
+#:
+#: ⛔ POSITIVE OPERATORS ONLY, and this is a correctness line rather than a scope line. "does not
+#: contain floral OR does not contain flower" matches nearly every account alive — a negative over
+#: a list is an AND (De Morgan), and quietly OR-ing it would build a filter that reads like a
+#: narrowing and behaves like the whole corpus. Negatives stay single-valued until someone needs
+#: them enough to write the AND branch.
+BD_MULTI_VALUE_OPS = frozenset({"includes", "=", "array_includes"})
+MAX_PREDICATE_VALUES = 12
+
+
+def field_label(name):
+ """The human name for a searchable field — used by the SURFACE and by every REFUSAL."""
+ return BD_FIELD_LABELS.get(name) or str(name or "that field")
+
+
+def field_kind(name):
+ return BD_FIELD_KINDS.get(name, "text")
+
+
+def ops_for(name):
+ """The comparisons this field may be asked. A tuple, in offer order."""
+ return BD_OPS_BY_KIND.get(field_kind(name), BD_OPS_BY_KIND["text"])
+
+#: ⭐ WHAT A **FRESH** CONDITION ON A FIELD STARTS AS — and it lives HERE, beside the narrowing
+#: law, because the two drifted apart and the drift cost a user their first automation.
+#:
+#: ⛔ THE SCAR, IN THREE WAVES. Wave 21 fixed a seeded condition the server refused for having no
+#: value by making a new condition NULLARY (`is_not_null` — "this field has any value"), and its
+#: comment called that "narrowing-in-the-right-direction". Wave 22 then wrote `BD_NARROWING_OPS`
+#: and `is_not_null` is NOT IN IT, which silently made that default a condition the save door
+#: always refuses. Wave 24 deleted the create wizard, so the Find panel became the ONLY way in —
+#: and the refusal moved from a corner case to the first thing a new user meets. Three waves, one
+#: sentence of drift, and nothing red anywhere at any point.
+#:
+#: So the rule is now DERIVED and ASSERTED (`verify_automation.py`): a fresh condition on a field
+#: that CAN narrow must narrow. The client asks for `defaultOperator` per field and never picks
+#: one itself — a client-side default is a second copy of this table, free to disagree with the
+#: guard that judges it, which is exactly what happened.
+BD_ARRAY_FIELDS = frozenset({"bio_hashtags", "post_hashtags", "related_accounts"})
+BD_BOOLEAN_FIELDS = frozenset({"is_business_account", "is_professional_account", "is_verified"})
+#: Narrowing fields whose values are IDENTIFIERS — a substring match on a handle or an id is a
+#: worse question than an equality, and both narrow.
+BD_EXACT_FIELDS = frozenset({"account", "id", "fbid", "profile_url"})
+
+
+def default_operator(name):
+ """The operator a NEW condition on `name` starts with.
+
+ Narrowing wherever the field can narrow, so a fresh condition is ONE step (type a value) from
+ saveable rather than two (change the comparison, then type a value) — with the second step
+ being one the surface never told anyone to take.
+ """
+ kind = field_kind(name)
+ if kind == "tags":
+ return "array_includes"
+ if kind in ("boolean", "choice"):
+ # ⚠ `choice` LANDS HERE AND NOT ON `includes`, which is the arm it used to fall through
+ # to (Category is a narrowing field). `includes` is not in `BD_OPS_BY_KIND["choice"]`, so
+ # the default would have been an operator the same module refuses to offer — the exact
+ # default-versus-guard split this function was written to close, reintroduced one commit
+ # later by adding a kind. Asserted per field in `verify_automation.py`.
+ return "="
+ if kind == "number":
+ # `>=` cannot narrow the scan and is not pretending to — it is the comparison a person
+ # reaching for Followers means, and the guard's sentence is the honest answer when it is
+ # the ONLY condition present.
+ return ">="
+ return "=" if name in BD_EXACT_FIELDS else "includes"
+
def predicate_narrows(p):
"""Does ONE predicate narrow the corpus scan? Content field + content op, nothing else."""
@@ -2021,23 +2484,65 @@ def predicate_narrows(p):
and str((p or {}).get("operator") or "") in BD_NARROWING_OPS)
-def narrowing_refusal(preds):
- """C4's server law: the sentence when a predicate set has ZERO narrowing predicates, else
- ''. One function so create/patch (via `clean_predicates`) and RUN (legacy stored configs
- predate the law) refuse in the same words."""
- if any(predicate_narrows(p) for p in preds or []):
+def narrowing_refusal(preds, operator="and"):
+ """C4's server law: the sentence when a predicate set does not narrow, else ''. One function
+ so create/patch (via `clean_predicates`) and RUN (legacy stored configs predate the law)
+ refuse in the same words.
+
+ ⭐ THE JOIN IS PART OF THE LAW, and it was missed for two waves. The guard asked "does ANY
+ predicate narrow?" — a question that is only correct under AND. Under **OR** the result is a
+ UNION, so the query is exactly as broad as its WIDEST branch: `biography includes "florist" OR
+ followers >= 10000` saved clean and asked the vendor for every account over ten thousand
+ followers, which is the measured 50-minute / NOT_ENOUGH_FUNDS shape the guard exists to stop.
+ A money wall that a dropdown three rows above it can walk through is not a wall.
+
+ So: under OR every branch must narrow; under AND one is enough. An EMPTY set never narrows
+ either way — `all([])` is True, which would have made "no conditions at all" the widest legal
+ query of the lot.
+ """
+ preds = list(preds or [])
+ if str(operator or "").lower() == "or":
+ if preds and all(predicate_narrows(p) for p in preds):
+ return ""
+ return ("with Match set to any, every condition has to describe the account itself "
+ "(Bio, Handle, Name, a hashtag). Matching any means the results are added "
+ "together, so one follower or yes/no condition widens the whole search. Narrow "
+ "every condition, or set Match to all")
+ if any(predicate_narrows(p) for p in preds):
return ""
- return ("add at least one CONTENT condition (biography includes …, account =, a hashtag) — "
- "number and yes/no filters alone make the vendor scan the whole 620-million-row "
- "corpus, and breadth is what costs: the measured `followers > 10000` search was "
- "still building 50 minutes in")
+ return ("add a condition that describes the account itself — Bio contains, Handle is, a "
+ "hashtag. Follower counts and yes/no conditions alone match too much of Instagram "
+ "to search")
def filter_meta():
- """C4's per-field flags for the Find surface: `[{name, populated, narrowing}]` over the
- same 21 names `BD_FILTER_FIELDS` offers (the 3 PII fields stay structurally absent, R3)."""
- return [{"name": n, "populated": n in BD_POPULATED_FIELDS,
- "narrowing": n in BD_NARROWING_FIELDS} for n in BD_FILTER_FIELDS]
+ """C4's per-field flags for the Find surface: `[{name, populated, narrowing, defaultOperator}]`
+ over the same 21 names `BD_FILTER_FIELDS` offers (the 3 PII fields stay structurally absent,
+ R3).
+
+ `defaultOperator` rides here rather than being a client constant for the reason written over
+ `default_operator`: the client's own default was `is_not_null` for every field, which the
+ narrowing guard refuses on every field.
+ """
+ return [{"name": n,
+ "label": field_label(n),
+ "hint": BD_FIELD_HINTS.get(n, ""),
+ "kind": field_kind(n),
+ "populated": n in BD_POPULATED_FIELDS,
+ "narrowing": n in BD_NARROWING_FIELDS,
+ "defaultOperator": default_operator(n),
+ # The comparisons THIS field may be asked, already in plain English and already in
+ # offer order. A client that filtered a global list by field kind would be a second
+ # copy of `BD_OPS_BY_KIND`, and the copy is what goes stale.
+ "operators": [{"value": o, "label": BD_OP_LABELS.get(o, o),
+ "nullary": o in BD_NULLARY_OPS,
+ # `in`/`is any of` and the tag operators take a LIST — the control
+ # has to know that, and deriving it from the token in the client is
+ # the same second-copy mistake one level down.
+ "multi": o in BD_MULTI_VALUE_OPS}
+ for o in ops_for(n)],
+ "options": BD_BOOLEAN_OPTIONS if field_kind(n) == "boolean" else []}
+ for n in BD_FILTER_FIELDS]
CANDIDATE_FIELDS = [
field_def("handle", "Handle"), field_def("profile_url", "Profile", "url"),
@@ -2059,7 +2564,7 @@ CANDIDATE_FIELDS = [
]
-def clean_predicates(raw):
+def clean_predicates(raw, operator="and"):
"""Validate a discovery filter into the vendor's shape. Returns `(predicates, error)`.
Refuses rather than coerces: a predicate naming a field the API rejects comes back as a
@@ -2073,23 +2578,76 @@ def clean_predicates(raw):
name = _s(p.get("name") or p.get("field"), 60).strip()
op = _s(p.get("operator") or p.get("op"), 20).strip()
if name not in BD_FILTER_FIELDS:
- return None, (f"{name or 'that field'!r} cannot be used to search — the searchable "
- f"fields are: {', '.join(BD_FILTER_FIELDS)}")
- if op not in BD_FILTER_OPS:
- return None, f"{op or 'that comparison'!r} is not one of: {', '.join(BD_FILTER_OPS)}"
+ return None, ("that field cannot be searched — the searchable ones are: "
+ + ", ".join(field_label(f) for f in BD_FILTER_FIELDS))
+ # ⭐ PER-FIELD, not the global list. `is_business_account >= 3` used to validate cleanly
+ # because every operator was legal on every field; a yes/no column offering "at least"
+ # is a question with no meaning that the vendor is nevertheless asked.
+ allowed = ops_for(name)
+ if op not in allowed:
+ return None, (f"{field_label(name)} cannot be asked {BD_OP_LABELS.get(op, op)!r} — "
+ "it takes: "
+ + ", ".join(BD_OP_LABELS.get(o, o) for o in allowed))
entry = {"name": name, "operator": op}
if op not in BD_NULLARY_OPS:
- v = p.get("value")
- if v is None or (isinstance(v, str) and not v.strip()):
- return None, f"give a value to compare {name!r} against"
- entry["value"] = v.strip() if isinstance(v, str) else v
+ raw_v = p.get("value")
+ # ONE value or SEVERAL — several is the "contains any of" shape (owner item 3), and
+ # it is stored as a list rather than as N sibling predicates so the row a person sees
+ # and the row that is stored are the same thing.
+ vals = raw_v if isinstance(raw_v, list) else [raw_v]
+ vals = [v.strip() if isinstance(v, str) else v for v in vals]
+ vals = [v for v in vals if not (v is None or (isinstance(v, str) and not v))]
+ if not vals:
+ return None, f"give {field_label(name)} something to compare against"
+ if len(vals) > 1 and op not in BD_MULTI_VALUE_OPS:
+ return None, (f"{BD_OP_LABELS.get(op, op)!r} takes one value — "
+ f"{field_label(name)} can only be given a list with "
+ + ", ".join(BD_OP_LABELS[o] for o in ops_for(name)
+ if o in BD_MULTI_VALUE_OPS))
+ if len(vals) > MAX_PREDICATE_VALUES:
+ return None, (f"{field_label(name)} takes at most {MAX_PREDICATE_VALUES} values "
+ "in one condition")
+ if field_kind(name) == "boolean":
+ ok = {o["value"] for o in BD_BOOLEAN_OPTIONS}
+ bad = [v for v in vals if str(v).lower() not in ok]
+ if bad:
+ return None, f"{field_label(name)} is answered Yes or No"
+ # ⛔ A REAL BOOLEAN, NOT THE STRING. MEASURED 2026-08-06: the filter API answers
+ # **400** to `{"name": "is_verified", "operator": "=", "value": "true"}` and
+ # accepts `True` (`snap_msh2rp4kh3v833q0u`). Nobody had ever sent one — the field
+ # was a free-text box until this wave, so the Yes/No dropdown that makes it easy
+ # to ask is also the thing that would have made every boolean condition fail.
+ # The dropdown's option VALUES stay "true"/"false" (a
) : null}
- {stripStages.length ? (
-
- {stripStages.map((st) => (
- /*
- ⚠ A WRAPPER, NOT ONE BUTTON, and the switch is the reason. `write` carries a
- toggle — it is the DRY-RUN control, the difference between a run that writes
- and a run that only reports what it would have written — and the strip is now
- the only place that stage appears. A chip that dropped it would have deleted a
- shipped control from the product while every gate stayed green. (Nesting the
- switch inside the chip's own button is not the fix: a button inside a button
- is invalid, and browsers un-nest it in ways that lose the inner click.)
- */
-
-
- {st.toggle ? (
-
- ) : null}
-
- ))}
-
- ) : null}
+ {/*
+ ⛔ THE PROCESS STRIP WAS RENDERED HERE AND IS DELETED (wave 24, owner item 9).
+ Capture / Bright Data / Anonymous / Post engagement / Write drew as chips above the
+ lanes. Their bodies AND their four switches now live in Properties > Configuration >
+ "How this fetches" (C-CFG); session B confirmed both R7 switches — Bright Data's paid
+ rung and Write's dry run — arrived there before this was removed, because the strip was
+ the ONLY surface either of them appeared on and deleting it first would have taken a
+ money control and a write-vs-report control out of the product with every gate green.
+ The `record === false` filter above survives and must: it still keeps those stages out
+ of the LANES.
+ */}
{cols.map((col) => (
diff --git a/web/src/automation/AutomationBuilder.tsx b/web/src/automation/AutomationBuilder.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..963c68966867bbf675f961b0e88454e6dc4eaccc
--- /dev/null
+++ b/web/src/automation/AutomationBuilder.tsx
@@ -0,0 +1,2097 @@
+// ---------------------------------------------------------------------------
+// automation/AutomationBuilder.tsx — the BUILDER (owner item 3b, contracts
+// C1/C2/C4, ruling R1: "exact layout, Loopable skin").
+//
+// THE ANATOMY IS AIRTABLE'S, 1:1, and it is the owner's reference (images 1-9):
+// a centre column of TRIGGER → ACTIONS with a spine down the left carrying each
+// step's status chip, dashed add-boxes at the end of each section, and a
+// Properties panel on the right whose sections are Trigger details /
+// Configuration / Test step. Every colour, size and weight is OURS (R1,
+// DESIGN.md) — no Airtable blue, no caps micro-labels (R6: "TRIGGER" is
+// "Trigger" here, and de-capping takes the letter-spacing with it).
+//
+// ⛔ IT RENDERS SYNCHRONOUSLY FROM WHAT IT WAS HANDED (C14 leg 1). No fetch, no
+// effect, no second frame: the trigger comes from `automation.trigger`, the
+// actions from `automation.flow`, the machine steps from `automation.graph` —
+// all three already on the list payload the rail used to draw the row you
+// clicked. THIS IS THE GHOST FIX. The old detail rendered Steps, then swapped to
+// the Board when `/board` answered, so switching automations painted the
+// PREVIOUS one's shape inside the new one's frame for as long as a fetch takes.
+// A view that cannot be in two shapes cannot show you the wrong one.
+//
+// ⛔ NO CLIENT UNION OVER A SERVER VOCABULARY, anywhere. Trigger keys, action
+// kinds, comparison operators, ending modes, review deciders and every ceiling
+// ride `GET /automations`. What this file owns is pixels and wording.
+//
+// WHAT PERSISTS WHEN. A discrete choice writes immediately — picking a trigger,
+// adding an action, flipping a switch — because a control you have to remember
+// to Save is not a control (R9). FREE TEXT does not: a value, a prompt or a name
+// commits on BLUR, or every keystroke would PATCH a half-typed condition and the
+// server would refuse most of them out loud (the cron-string precedent in
+// AutomationTrigger).
+// ---------------------------------------------------------------------------
+import type { ReactNode } from "react";
+import { useRef, useState } from "react";
+
+import type {
+ Action,
+ ActionCatalogRow,
+ Automation,
+ Cond,
+ FlowVocab,
+ GraphNode,
+ OAuthStatus,
+ TriggerOption,
+ UserTable,
+} from "./automationApi";
+import CondBuilder, { condComplete } from "./CondBuilder";
+import { groupBranches, groupByPanel, numberActions, reorderList } from "./steps";
+
+/**
+ * ⛔ A PRIVATE MIME, AND `text/plain` IS NEVER SET (owner item 11; the wave-13 C-LAYOUT scar).
+ * A drag carrying `text/plain` is a drag the whole operating system understands: drop it on any
+ * input, textarea or contenteditable — this builder is full of them — and the browser TYPES the
+ * payload in, so a mis-aimed reorder silently writes an action id into somebody's condition
+ * value. A private type is inert everywhere except the drop targets below, which is why the nav
+ * rail's own drag uses one (`Shell.tsx:90 NAV_DRAG_TYPE`).
+ * ⚠ The board's card drag still uses `text/plain` (`AutomationBoard.tsx:167`) — noted, not fixed
+ * here: that file belongs to another session this wave.
+ */
+const ACTION_DRAG_TYPE = "application/x-loopable-action";
+
+interface Props {
+ automation: Automation;
+ /**
+ * THE AUTOMATION'S NAME (item 15b, C-DETAIL) — it left the page header and Properties is where
+ * it went, at the top, above whatever step is selected. REQUIRED, all three: an optional prop
+ * degrades to "the field does not exist", which looks exactly like never having built it.
+ *
+ * ⚠ TEXT AND COMMIT ARE SEPARATE ON PURPOSE. This is the cron field's shape
+ * (`AutomationTrigger`'s `onCronText` / `onSchedule`): free text stays controlled while typing
+ * and writes ONCE on blur, because per-keystroke would PATCH a half-typed name. Folding them
+ * into one callback would force a choice between a laggy controlled input and a save per
+ * keystroke, and this file has already paid for both.
+ */
+ name: string;
+ onNameText: (v: string) => void;
+ onNameCommit: () => void;
+ /** The server's trigger vocabulary (C3). Absent is a state this file states, never fills in. */
+ triggers?: TriggerOption[];
+ catalog: ActionCatalogRow[];
+ vocab?: FlowVocab;
+ tables: UserTable[];
+ oauth: OAuthStatus | null;
+ /** True while a write is in flight — drives the "All changes saved" stamp and disables edits. */
+ busy: boolean;
+ /** Write a partial definition. The caller owns the request and prints the refusal verbatim. */
+ onPatch: (body: Record) => void;
+ onToggleNode: (nodeId: string) => void;
+ /**
+ * ⛔ CHOOSING A TRIGGER IS NOT A `{trigger:{key}}` PATCH, and getting that wrong is invisible.
+ * `schedule` is what today's engine actually READS, so a pick has to write BOTH halves or
+ * "At a scheduled time" would store a key and leave the cron switched off — a trigger that
+ * says it is scheduled and never fires. The detail already owns that two-write shape
+ * (`pickTrigger`); the builder calls it rather than composing a second copy of it.
+ */
+ onPickTrigger: (key: string) => void;
+ onRunNow: () => void;
+ /**
+ * The MACHINE steps' config bodies (source / columns / capture / find / write). They live in
+ * `AutomationDetail`, so they are passed IN rather than moved: a builder that re-implemented
+ * them would be a second copy of five panels whose only job is to agree with the engine.
+ *
+ * ⚠ IT TAKES A PANEL KEY, NOT A NODE (item 5, C-CFG). It used to be
+ * `(node: GraphNode) => ReactNode`, and the caller's whole body was `panelBody(node.panel)` —
+ * so the node was only ever a wrapper around the key. Now that Properties renders the panels
+ * GROUPED BY that key, taking a node would invite the caller to pass one node of a group and
+ * quietly imply the body belongs to it alone.
+ */
+ renderNodeBody: (panel: string) => ReactNode;
+ /**
+ * The SCHEDULE half of the trigger face (`AutomationTrigger` with its picker hidden). Passed
+ * in for the same reason the node panels are: the cron round-trip, the server's preset list
+ * and the tick-honesty note exist exactly once, and both this view and the board render the
+ * same element rather than two copies of three things that go wrong invisibly.
+ */
+ scheduleFace: ReactNode;
+ /**
+ * Does the cron drive the CURRENT trigger (owner item 7)? REQUIRED, and decided by the caller
+ * for the reason `AutomationTrigger.schedules` gives: which keys the cron drives is a per-key
+ * fact, and no component below the detail is entitled to name trigger keys.
+ */
+ schedules: boolean;
+ /**
+ * ⭐ THE DATABASE THE FLOW'S RECORDS WALK (owner item 12a) — the trigger's table, or the
+ * automation's own target, resolved by the caller the way `automation_engine._flow_table` does.
+ * REQUIRED: an absent one degrades to an empty field list, which is the exact defect this prop
+ * exists to fix and is indistinguishable from "this database has no columns".
+ */
+ walkTable: string;
+ /**
+ * Is there an edit the HEADER's Save still owns? REQUIRED, and it exists so the panel's
+ * "All changes saved" stamp can stop being a claim about fields it does not cover — the
+ * machine steps' panels moved into Properties this wave and they commit with Save, not on
+ * change.
+ */
+ dirty: boolean;
+}
+
+/*
+ * ⚠ `"node"` LEFT THIS UNION WITH THE MACHINE CARDS (item 5). It existed so a click on one of
+ * those cards could open its panel; with the cards gone nothing can set it, and a variant no
+ * code path can reach is a branch that reads as supported and is not.
+ */
+type Sel = { kind: "trigger" | "action"; id: string };
+
+/** Airtable phrases the empty state's shortcuts; ours come from the SERVER's own list (image 1). */
+const SUGGESTED = 6;
+
+/**
+ * A trigger's icon, PER KIND. Drawn, never an emoji (owner constant).
+ *
+ * ⚠ THE FIRST VERSION DREW ONE GLYPH FOR ALL ELEVEN, and reading the suggested list settled it:
+ * six identical arrows down the left edge is decoration, not information — the eye learns
+ * nothing and the column just gets wider. Airtable differentiates them (images 1/2) for the
+ * same reason. Unknown keys keep the neutral arrow, so a trigger the engine adds tomorrow
+ * renders plainly rather than not at all (the silent-drop rule, applied to icons).
+ */
+function TriggerMark({ kind = "" }: { kind?: string }) {
+ const common = {
+ width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
+ strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
+ "aria-hidden": true,
+ };
+ if (kind === "schedule")
+ return (
+
+ );
+ if (kind === "event_field")
+ return (
+
+ );
+ if (kind === "record_created")
+ return (
+
+ );
+ if (kind === "record_updated")
+ return (
+
+ );
+ if (kind === "enters_view")
+ return (
+
+ );
+ if (kind === "webhook")
+ return (
+
+ );
+ if (kind === "email")
+ return (
+
+ );
+ if (kind === "form_submitted")
+ return (
+
+ );
+ if (kind === "button_clicked")
+ return (
+
+ );
+ if (kind === "comment_added")
+ return (
+
+ );
+ /*
+ WAVE 24 — the only "Sources" trigger (C-TRIG). A magnifier with a PERSON inside it: this one
+ does not watch a database, it searches a corpus of profiles and makes rows out of what fits.
+ ⚠ Deliberately not the bare magnifier — `ActionMark`'s `find_records` already owns that shape
+ for "search a database", and two searches drawn identically would be the six-identical-arrows
+ problem this component's header talks itself out of.
+ */
+ if (kind === "ig_profile_match")
+ return (
+
+ );
+ return (
+
+ );
+}
+
+function ActionMark({ kind }: { kind: string }) {
+ const common = {
+ width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
+ strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
+ "aria-hidden": true,
+ };
+ if (kind === "group")
+ return (
+
+ );
+ if (kind === "review")
+ return (
+
+ );
+ if (kind === "create_record")
+ return (
+
+ );
+ if (kind === "find_records")
+ return (
+
+ );
+ /*
+ ⚠ THE MACHINE KINDS ARE HERE TOO, and leaving them out was a real defect for one render:
+ the engine's nodes are `source | capture | branch | write`, none of which matched above, so
+ "Write to the database" and "Fetch the page" both drew the PENCIL — an edit glyph on a step
+ that reads a web page and a step that writes a database. Caught by reading the screenshot,
+ not by a gate ([[ui-invisible-to-assertions]]): the icon was present, legible and wrong.
+ These are the shapes the retired `AutomationSteps.KindMark` used, kept with their meanings.
+ */
+ if (kind === "source")
+ return (
+
+ );
+ if (kind === "write")
+ return (
+
+ );
+ if (kind === "capture")
+ return (
+
+ );
+ if (kind === "branch")
+ return (
+
+ );
+ if (kind === "update_record")
+ return (
+
+ );
+ if (kind === "send_email")
+ return (
+
+ );
+ if (kind === "slack")
+ return (
+
+ );
+ if (kind === "run_script")
+ return (
+
+ );
+ if (kind === "generate_ai")
+ return (
+
+ );
+ if (kind === "repeating_group")
+ return (
+
+ );
+ /*
+ ⛔ THE FALLBACK IS NEUTRAL, and it was not the first time round. The default used to BE the
+ pencil — a real member of the set (`update_record`) — so every kind with no arm silently
+ borrowed "edit": `send_email`, `run_script` and `repeating_group` all drew it in the action
+ menu, which reads as three actions that modify a record. A fallback that is a real member
+ cannot be told apart from a match; this one can.
+ */
+ return (
+
+ );
+}
+
+/** The label a table key reads as. A raw `ut_9f3a…` on a card is a key, not a subtitle. */
+function tableLabel(tables: UserTable[], key: string): string {
+ if (!key) return "";
+ return tables.find((t) => t.key === key)?.label || key;
+}
+
+export default function AutomationBuilder({
+ automation,
+ name,
+ onNameText,
+ onNameCommit,
+ triggers,
+ catalog,
+ vocab,
+ tables,
+ oauth,
+ busy,
+ onPatch,
+ onToggleNode,
+ onPickTrigger,
+ onRunNow,
+ renderNodeBody,
+ scheduleFace,
+ schedules,
+ walkTable,
+ dirty,
+}: Props) {
+ const [sel, setSel] = useState({ kind: "trigger", id: "" });
+ const [picking, setPicking] = useState(false);
+ const [adding, setAdding] = useState(false);
+ /** The trigger key awaiting confirmation (image 6) — a change that can invalidate config. */
+ const [confirmKey, setConfirmKey] = useState("");
+ /** The card a reorder is hovering over (item 11). `""` = nothing is being dragged. */
+ const [dragOver, setDragOver] = useState("");
+ /**
+ * ⛔ ONE DRAG SUPPRESSES EXACTLY ONE CLICK (item 11; `AutomationBoard`'s trap 1, which this
+ * repo has already paid for once). Browsers can deliver a `click` after `dragend`, and the
+ * thing under the pointer here is the card's own selector — so a finished reorder would ALSO
+ * change which step the Properties panel is showing, which reads as the panel jumping on its
+ * own. A ref and not state, because the click arrives before a re-render would land.
+ */
+ const draggedRef = useRef(false);
+
+ const trigger = automation.trigger || null;
+ const triggerKey = trigger?.key || (automation.schedule?.enabled ? "schedule" : "manual");
+ const options = triggers || [];
+ const picked = options.find((t) => t.key === triggerKey) || null;
+ const actions = automation.flow?.actions || [];
+ const nodes = (automation.graph?.nodes || []).filter((n) => n.kind !== "trigger");
+ const ops = vocab?.condOps || [];
+ const nullaryOps = vocab?.nullaryCondOps || [];
+ const table = tables.find((t) => t.key === (trigger?.table || "")) || null;
+
+ /**
+ * ⛔ HAS ANYTHING BEEN CHOSEN? — and the first version of this line was wrong in a way only
+ * a screenshot showed.
+ *
+ * It read `!!trigger || key === "schedule" || key === "manual"`, and `triggerKey` DERIVES
+ * "manual" whenever nothing is stored — so it was true for every automation ever, and the
+ * Airtable empty state (image 1) was unreachable code that every gate was happy with.
+ *
+ * The honest test is what the DEFINITION holds, not what the picker displays: the engine
+ * deliberately stores no trigger for manual/schedule ("`schedule` already owns the cron"), so
+ * `trigger === null && !schedule.enabled` IS "nobody has decided yet". Manual is what that
+ * state DOES, not a thing you pick out of it — which is why the suggested list below omits
+ * it: an option whose selection stores nothing would bounce straight back to this state on
+ * the next reload, and a control that undoes itself is worse than no control.
+ */
+ const chosen = !!trigger || !!automation.schedule?.enabled;
+ const configured = !trigger || trigger.configured !== false;
+
+ /** Write one key of the trigger, keeping the rest — the engine merges against `previous`. */
+ const patchTrigger = (patch: Record) =>
+ onPatch({ trigger: { key: triggerKey, ...patch } });
+
+ const patchFlow = (next: Action[]) =>
+ onPatch({ flow: { actions: next, ending: automation.flow?.ending || { mode: "terminal" } } });
+
+ /**
+ * ⭐ ONE TREE WALKER (wave 24, C-FORK). Rewrite or drop any action anywhere, branches included:
+ * `f` returns a replacement, or `null` to remove it.
+ *
+ * ⛔ THIS REPLACED FOUR HAND-ROLLED WALKS, and they were four places to forget the same thing.
+ * A group's children moved from `config.actions` to `config.branches[].actions` this wave, so
+ * every one of them would have quietly stopped descending into a fork — editing, deleting or
+ * counting nothing inside it, with `tsc` perfectly happy because `config` is
+ * `Record` and an absent key is just `undefined`. The failure would have been
+ * "the card is there and the delete button does nothing", per action, per fork.
+ */
+ const mapTree = (list: Action[], f: (a: Action) => Action | null): Action[] =>
+ (list || [])
+ .map((a) => {
+ const next = f(a);
+ if (next === null) return null;
+ if (next.kind !== "group") return next;
+ const brs = groupBranches(next);
+ if (!brs.length) return next;
+ return {
+ ...next,
+ config: {
+ ...next.config,
+ branches: brs.map((br) => ({ ...br, actions: mapTree(br.actions || [], f) })),
+ },
+ };
+ })
+ .filter((a): a is Action => a !== null);
+
+ /** Replace one action anywhere in the tree, forks included — ids are stable server-side. */
+ const editAction = (id: string, change: (a: Action) => Action) =>
+ patchFlow(mapTree(actions, (a) => (a.id === id ? change(a) : a)));
+
+ const dropAction = (id: string) => {
+ // ⚠ REMOVING THE LAST ACTION IN A BRANCH IS REFUSED BY THE SERVER ("a branch with no actions
+ // inside it does nothing") and the refusal is printed verbatim, as every other one is. Not
+ // pre-empted here: a client that predicted it would be a second validator, and the honest
+ // repair — delete the branch, not its last child — is one the reader can act on.
+ patchFlow(mapTree(actions, (a) => (a.id === id ? null : a)));
+ if (sel.kind === "action" && sel.id === id) setSel({ kind: "trigger", id: "" });
+ };
+
+ /**
+ * REORDER (owner item 11). The whole `flow.actions` list goes back through `patchFlow` — the
+ * same door every other edit uses — rather than a bespoke move endpoint, because the engine
+ * already validates a whole flow and a second write path would be a second thing to keep
+ * agreeing with `clean_actions`.
+ *
+ * ⚠ TOP-LEVEL SIBLINGS ONLY, deliberately, and it is a SCOPE rather than an oversight: a card
+ * inside a conditional group is not `draggable` at all, so there is no affordance that quietly
+ * does nothing. Group children are about to stop living under `config.actions` and start living
+ * under `config.branches[].actions` (C-FORK), and building a tree-walking reorder against a
+ * shape this same wave replaces would be work done twice with a window of wrongness in between.
+ */
+ const moveAction = (dragId: string, dropId: string) => {
+ const next = reorderList(actions, dragId, dropId);
+ // `null` = same card, or one of them is not a top-level sibling. Nothing moved, so nothing
+ // is written — an aborted drag must not PATCH the flow back over itself.
+ if (next) patchFlow(next);
+ };
+
+ /**
+ * ⛔ A NEW ACTION'S CONFIG MUST BE ONE THE SERVER ACCEPTS — and the first version of this
+ * function got it wrong for FOUR of the five kinds, which is worth writing down because every
+ * gate was green and the harness could not see it (SSR renders no click).
+ *
+ * MEASURED against `clean_actions` itself (`python -c` over the engine module, no server):
+ * `{values:{"":""}}` -> "a value is written to a field with no name"
+ * `{table:"",values:…}` -> the same, twice
+ * `{table:""}` (find) -> "the find records action names no database"
+ * `{cond:…,actions:[]}` -> "a conditional group with no actions inside it does nothing"
+ * So clicking "Add → Update record" would have produced a red banner and NO CARD. This is the
+ * wave-22 discovery-predicate scar reproduced exactly ([[cg-condition-builder-items]] — every
+ * default must be one the server takes), in a file whose own comment cites it.
+ *
+ * The seeds below are built from data this component already holds, and `seedFor` returns
+ * NULL when it cannot build a legal one. A kind with no legal seed is offered DISABLED with
+ * the reason, rather than offered and refused: the two states look identical to a user and
+ * only one of them is honest.
+ */
+ /**
+ * ⭐ THE WALKING RECORD'S COLUMNS (item 12a). Read off `walkTable`, NOT off `table`.
+ *
+ * `table` is the TRIGGER's database and it answers a different question — which columns the
+ * trigger may watch or test. This one answers what the ACTIONS write to and what a branch's
+ * condition compares, and on any automation without an event trigger (manual, schedule,
+ * `ig_profile_match`) the two are not the same table at all: the first is empty and the second
+ * is where all the records are. Reading actions' fields off the trigger is why every condition
+ * inside a fork offered an empty picker.
+ */
+ const walkFields = (tables.find((t) => t.key === walkTable) || null)?.fields || [];
+ const firstField = walkFields[0]?.key || "";
+ const firstTable = tables[0] || null;
+ const firstTableField = firstTable?.fields?.[0]?.key || "";
+
+ const seedFor = (kind: string): Record | null => {
+ if (kind === "review")
+ return { decidedBy: "user", label: "Review", next: ["Approved", "Declined"], prompt: "" };
+ if (kind === "update_record")
+ return firstField ? { values: { [firstField]: "" } } : null;
+ if (kind === "create_record")
+ return firstTable && firstTableField
+ ? { table: firstTable.key, values: { [firstTableField]: "" } }
+ : null;
+ if (kind === "find_records")
+ return firstTable ? { table: firstTable.key, cond: null, limit: 25 } : null;
+ if (kind === "group")
+ /*
+ ⭐ RE-SEEDED FOR C-FORK, and the old seed would now be REFUSED. It was
+ `{cond: null, actions: [child]}` — the pre-wave-24 shape, which `clean_actions` no longer
+ accepts as a config: the fork's legs live under `branches` and `cond`/`actions` are gone
+ from the group's own config entirely. Clicking "If / then" would have produced a red
+ banner and no card, which is precisely the illegal-default-seed defect this function's
+ header was written about, reproduced by the wave that quotes it.
+
+ MEASURED against `clean_actions` rather than reasoned:
+ · a branch with no actions -> "a branch with no actions inside it does nothing"
+ · so the one branch is born with the cheapest legal child, exactly as before — not a
+ review, which would also mint a board stage nobody asked for by clicking "If / then".
+ ⛔ `label: ""` ON PURPOSE. The SERVER letters the branches by index and calls a null-cond
+ last leg "Otherwise", but it PRESERVES any label the client sends — so sending one would
+ freeze it, and a branch labelled "A" would still say "A" after the branch above it was
+ deleted. Sending nothing keeps the lettering correct by construction, and this fresh
+ single branch reads "Otherwise" until it is given a condition, which is what it is.
+ */
+ return firstField
+ ? {
+ branches: [
+ {
+ id: "b1",
+ label: "",
+ cond: null,
+ actions: [
+ { id: "", kind: "update_record", enabled: true, when: null,
+ config: { values: { [firstField]: "" } } },
+ ],
+ },
+ ],
+ }
+ : null;
+ return null;
+ };
+
+ /** Why a kind cannot be added yet — the server's own precondition, said before the click. */
+ const seedBlock = (kind: string): string => {
+ if (kind === "update_record" || kind === "group")
+ return "Name the trigger's database first — this needs a column to write.";
+ if (kind === "create_record" || kind === "find_records")
+ return "There is no blank database to point at yet.";
+ return "";
+ };
+
+ /**
+ * ⚠ `into` NAMES A BRANCH NOW, not just a group (C-FORK). A fork has several legs and "add an
+ * action to this group" stopped being a complete instruction the moment it did — putting it in
+ * the first branch by default would silently attach work to whichever leg happens to be first.
+ */
+ const addAction = (kind: string, into?: { actionId: string; branchId: string }) => {
+ const seed = seedFor(kind);
+ if (!seed) return;
+ const fresh: Action = { id: "", kind, enabled: true, when: null, config: seed };
+ if (!into) {
+ patchFlow([...actions, fresh]);
+ } else {
+ patchFlow(
+ mapTree(actions, (a) => {
+ if (a.id !== into.actionId) return a;
+ return {
+ ...a,
+ config: {
+ ...a.config,
+ branches: groupBranches(a).map((br) =>
+ br.id === into.branchId
+ ? { ...br, actions: [...(br.actions || []), fresh] }
+ : br
+ ),
+ },
+ };
+ })
+ );
+ }
+ setAdding(false);
+ };
+
+ /** Add an empty-conditioned leg to a fork. The server letters it and enforces the ceiling. */
+ const addBranch = (actionId: string) => {
+ const seedChild = seedFor("update_record");
+ if (!seedChild) return;
+ patchFlow(
+ mapTree(actions, (a) => {
+ if (a.id !== actionId) return a;
+ const brs = groupBranches(a);
+ return {
+ ...a,
+ config: {
+ ...a.config,
+ // ⚠ APPENDED LAST, and the server refuses a null-cond branch that is not last — so a
+ // fork that already ends in an Otherwise leg refuses this with its own sentence
+ // rather than silently burying the catch-all in the middle, where every branch below
+ // it would be dead code.
+ branches: [
+ ...brs,
+ { id: "", label: "", cond: null,
+ actions: [{ id: "", kind: "update_record", enabled: true, when: null,
+ config: seedChild }] },
+ ],
+ },
+ };
+ })
+ );
+ };
+
+ const dropBranch = (actionId: string, branchId: string) =>
+ patchFlow(
+ mapTree(actions, (a) => {
+ if (a.id !== actionId) return a;
+ const kept = groupBranches(a).filter((br) => br.id !== branchId);
+ // A fork with no legs at all "does nothing" — the server says so; do not send an empty
+ // list dressed up as an edit.
+ if (!kept.length) return a;
+ return { ...a, config: { ...a.config, branches: kept } };
+ })
+ );
+
+ /**
+ * R8's numbers for the whole flow, computed ONCE per render rather than per card — the map is
+ * built by walking the tree, so asking it per card would be quadratic in a deep fork, and more
+ * importantly a per-card computation could not see its siblings and would have to re-derive
+ * the position it is being told.
+ */
+ const stepNos = numberActions(actions);
+
+ /**
+ * ⭐ THE ACTION MENU'S GROUP ORDER, FROM THE SERVER (owner item 12b, contract C-ACT).
+ *
+ * ⛔ NEVER A LITERAL LIST OF GROUP NAMES HERE. The server ships `groupOrder` on every catalog
+ * row (1 Web action · 2 Database · 3 Connected · 4 Advanced logic, derived server-side from one
+ * table so two rows cannot disagree about their own group). A client
+ * `["Web action", "Database", …]` would be a second copy of the catalog's structure, and the
+ * day the engine adds or renames a group the client drops it off the end — or drops it
+ * entirely — without anything going red.
+ *
+ * ⚠ AN UNORDERED GROUP SORTS LAST, NOT FIRST, which the server's own gate asserts. `Infinity`
+ * and not `0`: a missing number meant "before everything" under a naive `|| 0`, so a server
+ * older than this client would have led its menu with whatever it had failed to classify.
+ * ⚠ The sort is STABLE over first appearance, so two groups sharing an order keep the payload's
+ * sequence rather than an arbitrary one.
+ */
+ const menuGroups = (() => {
+ const order = new Map();
+ const seen: string[] = [];
+ for (const c of catalog) {
+ if (!order.has(c.group)) {
+ order.set(c.group, typeof c.groupOrder === "number" ? c.groupOrder : Infinity);
+ seen.push(c.group);
+ }
+ }
+ return [...seen].sort(
+ (a, b) => (order.get(a) ?? Infinity) - (order.get(b) ?? Infinity)
+ );
+ })();
+
+ // ── the centre column ────────────────────────────────────────────────────────────────────
+ const chip = () => {
+ if (!chosen) return null;
+ if (!configured)
+ return (
+
+ Finish configuration
+
+ );
+ if (trigger?.paused)
+ return Paused;
+ if (picked && picked.ready === false)
+ return Not set up;
+ const last = automation.runs?.[0];
+ if (last)
+ return (
+
+ {last.ok ? "Last run succeeded" : "Last run failed"}
+
+ );
+ return null;
+ };
+
+ const actionCard = (a: Action, depth: number, hasNext = false): ReactNode => {
+ const row = catalog.find((c) => c.kind === a.kind);
+ const isGroup = a.kind === "group";
+ const branches = isGroup ? groupBranches(a) : [];
+ /**
+ * ⭐ THE PERMANENT FIRST STEP (owner ruling 2026-08-06). An Instagram search produces rows
+ * and has nowhere to put them until something writes them, so Create record is step 1 and
+ * stays. DERIVED from the same rule the server enforces (`ig_action_pinned`) rather than
+ * from a stored flag — and the control is HIDDEN rather than disabled, because the server
+ * re-inserts the action on the next save, so a delete button here would appear to work and
+ * then silently undo itself.
+ */
+ const pinned =
+ automation.kind === "discover_instagram" && depth === 0 && a.id === actions[0]?.id;
+ /** Only TOP-LEVEL cards reorder (see `moveAction`) — depth 0, and never while a write is up. */
+ const canDrag = depth === 0 && !busy && !pinned;
+ return (
+
+
{
+ draggedRef.current = true;
+ e.dataTransfer.effectAllowed = "move";
+ e.dataTransfer.setData(ACTION_DRAG_TYPE, a.id);
+ }
+ : undefined
+ }
+ onDragOver={
+ canDrag
+ ? (e) => {
+ // Somebody else's drag — a file, a nav row, selected text — is not ours to
+ // accept. Without this test the card would light up for anything dragged over
+ // it and then swallow the drop.
+ if (!e.dataTransfer.types.includes(ACTION_DRAG_TYPE)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "move";
+ setDragOver(a.id);
+ }
+ : undefined
+ }
+ onDragLeave={
+ canDrag
+ ? (e) => {
+ // Moving onto a CHILD of this card is not leaving it; without this the
+ // highlight flickers off every time the pointer crosses the title.
+ if (e.currentTarget.contains(e.relatedTarget as Node)) return;
+ setDragOver((cur) => (cur === a.id ? "" : cur));
+ }
+ : undefined
+ }
+ onDrop={
+ canDrag
+ ? (e) => {
+ const dragId = e.dataTransfer.getData(ACTION_DRAG_TYPE);
+ setDragOver("");
+ if (!dragId) return;
+ e.preventDefault();
+ moveAction(dragId, a.id);
+ }
+ : undefined
+ }
+ onDragEnd={() => {
+ setDragOver("");
+ // Cleared a tick later: the post-drag click arrives BEFORE this would run.
+ window.setTimeout(() => {
+ draggedRef.current = false;
+ }, 0);
+ }}
+ >
+
+ {pinned ? (
+
+ Always first
+
+ ) : (
+
+ )}
+
+
+ {/*
+ ⭐ THE FORK (owner item 12a, ruling R8, contract C-FORK). A group used to hold ONE
+ nested column; it now holds a LETTERED LANE PER BRANCH, because R8 rules that a fork
+ occupies one step number and its legs are alternatives rather than later steps.
+
+ THE LETTER AND THE "Otherwise" ARE THE SERVER'S WORDS — `br.label`, printed, never
+ composed. `clean_actions` letters by index and names a null-cond last leg "Otherwise",
+ so the lanes re-letter themselves correctly when one is deleted.
+ The nesting ceiling is still the SERVER's `maxGroupDepth`, so the add-here affordance
+ disappears at exactly the depth `clean_actions` refuses.
+ */}
+ {isGroup ? (
+
+ {branches.map((br) => (
+
+
+ {br.label}
+
+ {/* ⚠ NOT A RENDERED CONDITION — the tree is edited in Properties, and a
+ second editable copy here would be two controls for one fact. This says
+ only WHICH leg you are looking at. A null cond is the catch-all, and the
+ server has already labelled it, so this says nothing twice. */}
+ {br.cond ? "when its conditions match" : "everything else"}
+
+ {branches.length > 1 ? (
+
+ ) : null}
+
+ ) : null}
+
+ {/*
+ THE ARROW BACK INTO THE FLOW (item 12a). The lanes are alternatives and exactly one of
+ them runs — the engine takes the first matching branch and breaks — so they REJOIN, and
+ without a mark saying so a fork at the end of a column reads as several parallel endings.
+ Drawn only when there IS a next step to rejoin: an arrow into nothing is a promise the
+ flow does not keep.
+ */}
+ {isGroup && hasNext ? (
+
+ ) : (
+ /*
+ THE EMPTY STATE (image 1): a dashed add-box and the server's own suggested
+ triggers. One line of chrome, no tour (R13) — the list IS the explanation, and
+ it is the server's list so it cannot describe a trigger we removed.
+ */
+ <>
+
+ {options.length ? (
+
+ )}
+ {/* ONE LINE (R13), and it is what is TRUE of this state rather than a caption
+ for the box above it: with nothing chosen, Run now is the only thing that
+ starts this automation. Airtable's empty state means "it cannot run"; ours
+ does not, and saying so is the difference between a screen that is honest
+ and one that merely looks the same. */}
+
+ {actions.map((a, i) => actionCard(a, 0, i < actions.length - 1))}
+
+ {/*
+ ⛔ THE MACHINE STEPS ARE NOT CARDS ANY MORE (owner item 5, contract C-CFG). They
+ were engine-derived read-only cards sitting under the owner's own actions — "fetch
+ the page", "Bright Data", "Anonymous", "Write" — so the centre column mixed two
+ different things: what the AUTOMATION is, which nobody chose and nobody can reorder,
+ and what the OWNER added, which is the whole subject of this builder. Their
+ configuration and their switches moved to Properties → Configuration →
+ "How this fetches", one section per panel.
+
+ ⚠ THE ENGINE STILL RUNS THEM. `graph()` emits the same nodes; this surface simply
+ stops DRAWING them, which is why the switches had to move rather than go — R7 names
+ Bright Data (money) and Write's dry run (reads and reports without writing a row) as
+ controls that must survive the cards that carried them.
+ */}
+
+
+
+ {/* THE ACTION MENU (images 7/8): the server's catalog, grouped by its own `group`
+ key, with `ready:false` rows faded and carrying the server's reason. A shorter
+ menu would imply those actions do not exist — the owner asked to see all of
+ them, and `clean_actions` refuses the unready ones at the door, so faded is a
+ wall rather than a decoration. */}
+ {adding ? (
+
+
+ {/* ── PROPERTIES ──────────────────────────────────────────────────────────────────── */}
+
+
+ {/* THE CONFIRM (image 6). A trigger change can invalidate the configuration under it, so
+ it ASKS — and it says what it will cost rather than "are you sure". */}
+ {confirmKey ? (
+
+
Change the trigger?
+
+ Anything configured for {picked?.label || triggerKey} is dropped.
+
+
+
+
+
+
+ ) : null}
+
+ {/* The picker, opened from the empty state's dashed box (image 2). */}
+ {picking ? (
+
+ {options.map((t) => (
+
+ ))}
+
+ ) : null}
+ >
+ );
+}
+
+/** One action's subtitle — what it will DO, composed from its own config. */
+function actionSub(a: Action, tables: UserTable[]): string {
+ const cfg = a.config || {};
+ if (a.kind === "update_record") {
+ const keys = Object.keys((cfg as { values?: Record }).values || {})
+ .filter(Boolean);
+ return keys.length ? `Sets ${keys.join(", ")}` : "No values yet";
+ }
+ if (a.kind === "create_record") {
+ const t = String((cfg as { table?: string }).table || "");
+ return t ? `Into ${tableLabel(tables, t)}` : "No database yet";
+ }
+ if (a.kind === "find_records") {
+ const t = String((cfg as { table?: string }).table || "");
+ return t ? `In ${tableLabel(tables, t)}` : "No database yet";
+ }
+ if (a.kind === "review") {
+ const by = String((cfg as { decidedBy?: string }).decidedBy || "user");
+ return by === "ai" ? "Decided by AI" : "Decided by a person";
+ }
+ return "";
+}
+
+function findAction(list: Action[], id: string): Action | null {
+ for (const a of list) {
+ if (a.id === id) return a;
+ // ⚠ THROUGH THE BRANCHES (C-FORK). This read `config.actions`, which a fork no longer has —
+ // so selecting any action inside one would have found nothing and the Properties panel would
+ // have said "that action is no longer part of this flow" about a card visibly on screen.
+ if (a.kind === "group")
+ for (const br of groupBranches(a)) {
+ const hit = findAction(br.actions || [], id);
+ if (hit) return hit;
+ }
+ }
+ return null;
+}
+
+/*
+ * ⛔ `nodePanel()` IS GONE (item 5). It rendered ONE machine node's panel, chosen by the card the
+ * reader had clicked, and included a "that step is no longer part of this automation" branch for
+ * a selection the graph had since dropped. Both facts died with the cards: the panels are now
+ * rendered together under "How this fetches", keyed by PANEL rather than by node id, so there is
+ * no selection left to go stale.
+ */
+
+// ── the Properties panel's two faces ─────────────────────────────────────────────────────────
+
+function TriggerProps({
+ automation,
+ triggerKey,
+ options,
+ picked,
+ table,
+ tables,
+ ops,
+ nullaryOps,
+ vocab,
+ oauth,
+ busy,
+ nodes,
+ onToggleNode,
+ renderNodeBody,
+ onAskChange,
+ onPatchTrigger,
+ onPickTrigger,
+ onRunNow,
+ scheduleFace,
+ schedules,
+}: {
+ automation: Automation;
+ triggerKey: string;
+ options: TriggerOption[];
+ picked: TriggerOption | null;
+ table: UserTable | null;
+ tables: UserTable[];
+ ops: string[];
+ nullaryOps: string[];
+ vocab?: FlowVocab;
+ oauth: OAuthStatus | null;
+ busy: boolean;
+ /** The engine's machine steps (item 5) — their switches and bodies live under Configuration. */
+ nodes: GraphNode[];
+ onToggleNode: (nodeId: string) => void;
+ renderNodeBody: (panel: string) => ReactNode;
+ /** Ask before a trigger change that can invalidate the config under it (image 6). */
+ onAskChange: (key: string) => void;
+ onPatchTrigger: (patch: Record) => void;
+ onPickTrigger: (key: string) => void;
+ onRunNow: () => void;
+ scheduleFace: ReactNode;
+ schedules: boolean;
+}) {
+ const trigger = automation.trigger || null;
+ const provider = picked?.connect?.provider || "";
+ const connected = !!(provider && oauth?.[provider]?.connected);
+ const startUrl = picked?.connect?.startUrl || "";
+ const needsTable = !!trigger && "table" in trigger;
+ const last = automation.runs?.[0];
+
+ return (
+ <>
+
Trigger details
+
+
+
+
+ {/*
+ ⭐ THE DESCRIPTION IS THE SERVER'S, AND IT RIDES NOW (wave 24, C-TYPES). This block used
+ to be a comment explaining why there was NO paragraph here: Airtable prints two sentences
+ under this select (image 3), ours would have been a client paraphrase of a server
+ vocabulary, and the note said "when `detail` rides, it renders here and cannot disagree
+ with the engine". `TriggerOption.detail` landed this wave, so the paragraph is the
+ engine's own sentence, printed verbatim and never composed with anything.
+ */}
+ {picked?.detail ?
+
+ {connected
+ ? "Connected — this trigger is still being switched on for this deployment."
+ : "This trigger is not set up yet."}
+
+ {!connected && startUrl ? (
+
+ Connect
+
+ ) : null}
+
+ ) : null}
+
+
Configuration
+ {needsTable ? (
+
+
+
+
+ ) : null}
+
+ {triggerKey === "event_field" ? (
+ <>
+ {/*
+ ⛔ "WATCHED COLUMN" IS GONE (owner item 7, C-TRIG law 4). "When a record matches
+ conditions" is a FILTER, and a watched column was a second, different question
+ answered in the same box — the trigger fired on a column changing AND on the
+ conditions holding, which is two triggers wearing one name.
+ ⚠ THE SERVER WENT FIRST, and that ordering was the point: `clean_trigger` stopped
+ reading `field` (C posted law 4 done) BEFORE this control came out. Deleting the
+ control while the validator still read the key would have left a stored watched
+ column that nothing displays and nothing can clear — and deleting the key while the
+ control still showed it would have made every Save silently drop what the user
+ picked. The CONDITION is what completes this trigger now: with none, it rides
+ `configured:false` and says so.
+ */}
+
+
+ {/*
+ ⭐ FOUR STATES, AND THREE OF THEM ARE SENTENCES (owner item 8, C-TYPES).
+ `views` now rides `GET /automations/tables`, so this control is live — but "drop the
+ note" would have collapsed it to two states and rebuilt the exact defect the contract
+ forbids. Absent and empty are DIFFERENT FACTS:
+ · no database chosen -> choose one first
+ · `views` ABSENT -> the server offered nothing (a server older than this
+ client). Saying "no views" here would be a claim
+ nobody measured.
+ · `views` present and [] -> this database genuinely has none. That IS measured,
+ and it is the one that tells the reader to go and
+ make a view rather than to go and find an admin.
+ · non-empty -> the picker.
+ */}
+ {!table ? (
+
Choose a database first.
+ ) : !table.views ? (
+
This server did not offer a view list for that database.
+ ) : !table.views.length ? (
+
+ That database has no saved views yet — make one on its grid and it appears here.
+
Minted once. It survives every other change to this trigger.
+
+ ) : null}
+
+ {/* THE SCHEDULE, rendered by the one component that owns the cron round-trip.
+ ⚠ NOT `triggerKey === "schedule"` ANY MORE (item 7, C-TRIG). `ig_profile_match` watches
+ nothing — it MAKES rows, on the cron — so its Configuration carries these controls
+ "always", and the caller says which keys those are. */}
+ {schedules ? scheduleFace : null}
+ {triggerKey === "manual" ? (
+
+ It runs when you press Run once now, and nothing else starts it.
+
+ ) : null}
+
+ {/*
+ ⭐ HOW THIS FETCHES (owner item 5, contract C-CFG) — the machine steps' switches and
+ config bodies, below the trigger's own fields, under ONE sub-heading.
+
+ ⛔ ONE SECTION PER PANEL, NOT PER NODE (`groupByPanel`, and its note is the reason). Four
+ of `field_instagram`'s nodes share `panel: "capture"` and both of `discover_instagram`'s
+ share `panel: "find"`, so a section per node would print one body four times and mount the
+ discovery filter twice against a single `preds` array.
+
+ ⛔ AND THE SWITCHES ARE THE POINT, not a leftover. R7: Bright Data buys exact counts with
+ MONEY and Write's switch is the difference between a run that writes rows and one that
+ reads and reports. They were on the cards this wave deleted, so deleting the cards without
+ moving them would have retired two shipped controls silently. Each still posts to the
+ node-toggle door — the server decides what a switch means, this only says which node.
+
+ `plain` automations have no machine nodes at all, so the whole section is absent for them
+ rather than an empty heading (R6 makes that the common case from now on).
+ */}
+ {nodes.length ? (
+ <>
+
+ ))}
+ {/* The engine's own sentence about the step, where it wrote one — never a client
+ paraphrase of what a node does. */}
+ {g.nodes[0]?.detail ? (
+
{g.nodes[0].detail}
+ ) : null}
+ {renderNodeBody(g.panel)}
+
+ ))}
+ >
+ ) : null}
+
+
Test step
+ {/*
+ ⛔ HONEST TO OUR SEMANTICS, not to Airtable's. Airtable's "Test step" replays one step
+ against a chosen record. Ours has no step-replay: the engine runs a whole automation. So
+ the control says what it actually does — RUN IT — and the results below are the last
+ real run's, from the run log, rather than a rehearsal nobody performed.
+ */}
+
+ {last ? (
+ <>
+
+ {last.ok ? "Last run succeeded" : "Last run failed"}
+
+ )}
+ >
+ );
+}
+
+function ActionProps({
+ action,
+ catalog,
+ tables,
+ walkFields,
+ ops,
+ nullaryOps,
+ vocab,
+ busy,
+ onEdit,
+}: {
+ action: Action | null;
+ catalog: ActionCatalogRow[];
+ tables: UserTable[];
+ /**
+ * ⛔ THE WALKING RECORD'S COLUMNS — the trigger's database, resolved by the builder.
+ *
+ * These three surfaces were built with `fields={[]}` and it made R3's headline feature
+ * unauthorable: a conditional group's condition, an action's `when`, and `update_record`'s
+ * column picker all offered "Choose a field…" and nothing else. An empty list is not a
+ * neutral default here — it is a picker with no options, which reads as "this database has
+ * no columns".
+ */
+ walkFields: { key: string; label: string; type: string }[];
+ ops: string[];
+ nullaryOps: string[];
+ vocab?: FlowVocab;
+ busy: boolean;
+ onEdit: (change: (a: Action) => Action) => void;
+}) {
+ if (!action) return
+
+ {action.kind === "group" ? (
+ <>
+ {/*
+ ⭐ ONE CONDITION EDITOR PER BRANCH (C-FORK). The group's own `config.cond` is GONE —
+ a fork has a condition per leg, not one for the whole thing — so an editor bound to
+ `cfg.cond` would now write a key `clean_actions` drops on the floor: the tree would
+ look saved, survive a reload from local state, and be absent the next time anyone
+ opened the automation.
+ THE HEADING IS THE SERVER'S LABEL. The last leg may carry no condition, and the
+ server has already named it "Otherwise" — giving it one here turns it into a lettered
+ branch, which is a real thing to want and needs no separate control.
+ */}
+ {groupBranches(action).map((br, i) => (
+
+
+ {br.label}
+ {br.cond ? " — run these actions if…" : " — everything that reaches here"}
+
+ What it found opens from the run log. Piping the rows into a later step is not built
+ yet.
+
+ >
+ ) : null}
+
+ {action.kind === "review" ? (
+ }
+ vocab={vocab}
+ busy={busy}
+ setCfg={setCfg}
+ />
+ ) : null}
+
+ {/* EVERY action can be conditional, not just a group — `Action.when` is the engine's own
+ field and a card with no way to set it would be a stored value the UI cannot reach. */}
+
+ {/*
+ ⚠ `aiReady` IS A MEASUREMENT OF THIS DEPLOYMENT, and it is stated rather than styled
+ around. With no LLM key the engine holds every card for a human — so an AI review that
+ looked configured would promise a decision nothing will make (C6's fail-closed path).
+ */}
+ {by === "ai" && !aiReady ? (
+
+ No AI provider is configured here, so these cards wait for a person.
+
+ Each exit is a lane on the board. A card waits here until it is moved to one of them.
+
+ >
+ );
+}
diff --git a/web/src/automation/AutomationDetail.tsx b/web/src/automation/AutomationDetail.tsx
index ce0f48e4e3407108e32c1d9f74419b4d45986540..ccb0cf4d5bb772110aea7fee160c3b2e0830913a 100644
--- a/web/src/automation/AutomationDetail.tsx
+++ b/web/src/automation/AutomationDetail.tsx
@@ -23,14 +23,16 @@
import { useCallback, useEffect, useState } from "react";
import AutomationBoard from "./AutomationBoard";
+import AutomationBuilder from "./AutomationBuilder";
import AutomationFind from "./AutomationFind";
-import AutomationSteps from "./AutomationSteps";
import AutomationTrigger from "./AutomationTrigger";
import type {
+ ActionCatalogRow,
Automation,
AutomationKind,
Board,
BoardStage,
+ FlowVocab,
GraphNode,
OAuthStatus,
Predicate,
@@ -62,6 +64,13 @@ import {
interface Props {
automation: Automation;
+ /**
+ * ⚠ STILL REQUIRED, NO LONGER READ HERE (item 15b). `.auto-kindtag` was its only consumer and
+ * the header lost it, but the prop stays: `AutomationSurface` passes `kinds={data?.kinds || []}`
+ * and that file belongs to another session this wave, so deleting the field would turn an
+ * excess-property error on somebody else's call site into this session's problem. Retiring it
+ * is a two-file change, booked in the B mailbox rather than done unilaterally.
+ */
kinds: { key: AutomationKind; label: string }[];
/** The server's schedule vocabulary, forwarded to Step 1's Custom face. */
cronPresets: { cron: string; label: string }[];
@@ -70,30 +79,76 @@ interface Props {
discover?: DiscoverVocab;
/** The server's trigger vocabulary (C3). Absent until the engine ships it. */
triggers?: TriggerOption[];
+ /** The ACTION MENU and the builder's ceilings (C4). Same rule: absent is a state, not a gap. */
+ catalog?: ActionCatalogRow[];
+ vocab?: FlowVocab;
/**
* Can a schedule fire here? `null` = the server did not say (C6 amendment #1 is not live
* yet) — a REQUIRED key so an unmounted prop fails `tsc` rather than silently reading as
* "off", which would make Step 1 state a measurement nobody made.
*/
tick: TickState | null;
+ /**
+ * W23-W5 — the stage a review notification asked for, seeding the config panel's selection.
+ * Advisory by contract: a stage this automation does not have simply opens nothing, which is
+ * the same thing that happens when no stage is named. The surface remounts this component on
+ * every selection change (`key={active.id}`), so this is read once, at mount, by design.
+ */
+ initialStage?: string;
+ /**
+ * ⭐ W24-W1 — WHAT THE RUN IS DOING RIGHT NOW, and it is the honest half of owner item 6
+ * ("Run once now is laggy / looks stuck").
+ *
+ * MEASURED by the session that owns the surface: the engine work item 6 blamed is ~0.9 ms of a
+ * ~23 ms request, so there is no performance defect to fix. What IS true is that a
+ * `discover_instagram` run legitimately blocks up to `BD_FILTER_WAIT` = 120 s at the vendor,
+ * and the engine has been publishing a live step text the whole time that NOTHING has ever
+ * rendered — so a two-minute vendor wait and a genuinely hung thread have been pixel-identical.
+ * They are not the same thing and the server already knows which one it is.
+ *
+ * REQUIRED, not optional: an optional prop degrades to "the feature does not exist", which is
+ * exactly what shipped for the last four releases and is indistinguishable from never having
+ * built it. `""` while nothing is running is a real value and the honest one — a step text left
+ * over from a finished run is a worse answer than no answer.
+ * ⛔ Filled from `liveStepOf(a)`, never from `automation.liveStep`: there is no such field on
+ * the wire (C-TYPES amendment A2) and reading one would compile, type-check and be `undefined`
+ * forever.
+ */
+ liveStep: string;
onSaved: (id?: string) => void | Promise;
onDeleted: () => void | Promise;
}
+/*
+ * ⛔ `STATE_LABELS` IS GONE WITH THE HEADER CHIP IT WORDED (item 15b, C-DETAIL). It mapped the
+ * stored run enum to a sentence for `.auto-chip`, and the chip left the title row so that
+ * Builder/Board could have that space. The FACT it carried is not lost and was never only here:
+ * the builder's own `chip()` says "Last run succeeded / failed / Paused / Not set up / Finish
+ * configuration" on the trigger step, the header's Run-now button says "Running…", and the rail
+ * carries a status dot per automation. A second wording of the same enum in this file would have
+ * been a third place for the three to disagree.
+ */
+
/**
- * The run-state chip's WORDS. The chip printed the stored enum straight — a header
- * reading "ok" beside the automation's name, which is a value from a state machine
- * rather than a sentence anybody would write. Sentence case, and "Succeeded"/"Failed"
- * rather than "ok"/"error" so the chip agrees with the rail's own tooltip, which has
- * always said "Last run succeeded".
+ * ⚠ THE ONLY CLIENT-SIDE COPY OF A SERVER FACT IN THIS FILE, named so it can be deleted in one
+ * edit the day the wire carries it (asked of the engine session in the wave mailbox).
+ *
+ * WHICH TRIGGERS THE CRON DRIVES. `is_due` (`automation_engine.py:523`) reads `schedule.enabled`
+ * and the cron and NOTHING ELSE — it never looks at the trigger key — so any trigger the engine
+ * calls schedule-driven fires exactly this way. The engine's own set is `TRIGGER_SCHEDULE_KEYS`
+ * (`:5010`), and it is NOT the right thing to ship verbatim: it includes `manual`, which is in it
+ * only to decide which side the trigger node's switch flips, and a manual trigger showing a cron
+ * face would contradict its own sentence ("nothing else starts it").
+ *
+ * ⛔ SO THIS IS NOT A COPY OF THE TRIGGER VOCABULARY, which would be the forbidden thing — the
+ * LIST of what triggers exist still comes wholly from `triggers` on the payload, and an unknown
+ * key still renders. This names which of them wear the schedule controls, which is a per-key
+ * config decision this file already makes for `event_field`, `record_updated`, `enters_view`,
+ * `email` and `webhook`. It goes stale in exactly one way — a NEW cron-driven trigger would show
+ * no schedule face — which is visible on screen rather than silent, and is why it is one
+ * constant with one name instead of two inline comparisons.
*/
-const STATE_LABELS: Record = {
- idle: "Not run yet",
- running: "Running",
- ok: "Succeeded",
- partial: "Partial",
- error: "Failed",
-};
+const CRON_DRIVEN_TRIGGERS = ["schedule", "ig_profile_match"];
interface ColumnPlan {
column: string;
@@ -103,12 +158,15 @@ interface ColumnPlan {
export default function AutomationDetail({
automation,
- kinds,
cronPresets,
paidReady,
discover,
triggers,
+ catalog,
+ vocab,
tick,
+ initialStage,
+ liveStep,
onSaved,
onDeleted,
}: Props) {
@@ -123,7 +181,28 @@ export default function AutomationDetail({
const [touched, setTouched] = useState(false);
const [busyNode, setBusyNode] = useState("");
const [triggerBusy, setTriggerBusy] = useState(false);
- const [selected, setSelected] = useState("");
+ const [selected, setSelected] = useState(initialStage || "");
+
+ /**
+ * ⛔ WHICH VIEW (C1 + C14 leg 1) — and it is STATE, not a consequence of a fetch.
+ *
+ * The ghost this wave was called to kill lived exactly here. The detail used to render
+ * `{board ? : }`: the shape of the page was decided by
+ * whether a request had come back, so opening any automation drew the STEPS, then replaced
+ * them with the BOARD a fetch later. Click A then B and the frame showed A's shape while B
+ * loaded — a ghost of the previous automation, which is exactly what the owner reported.
+ *
+ * A view the reader CHOOSES cannot do that. The Builder renders synchronously from data the
+ * rail already had; the Board keeps a fixed-shape skeleton until its own fetch lands. Neither
+ * view ever changes shape twice, so there is no second shape to catch a glimpse of.
+ */
+ /**
+ * ⚠ A REVIEW NOTIFICATION OPENS THE BOARD (W23-W5). `initialStage` seeds the stage panel, and
+ * only the BOARD reads that — so defaulting to the Builder would have landed the reader on a
+ * view where the stage they were told about does not appear, with a selection nobody could
+ * see. The notification says "cards are waiting at Review"; the cards are on the board.
+ */
+ const [view, setView] = useState<"builder" | "board">(initialStage ? "board" : "builder");
// --- the board (C1)
const [board, setBoard] = useState(null);
@@ -161,11 +240,24 @@ export default function AutomationDetail({
// --- discover_instagram half (R7)
const [recordsLimit, setRecordsLimit] = useState(Number(cfg.recordsLimit || 25));
const [joinOp, setJoinOp] = useState(String(cfg.operator || "and"));
+ /**
+ * ⛔ NO SEEDED CONDITION, AND THAT IS THE FIX.
+ *
+ * This used to seed `{followers >= 10000}` when nothing was stored — a field the narrowing
+ * guard does not count and a comparison it does not count either. Every Save of a discovery
+ * automation therefore sent it and 400'd with "add at least one CONTENT condition…": renaming
+ * the automation, changing the cron, editing a step, all of it, on an automation whose filter
+ * the user had never touched. Wave 24 made it unmissable by deleting the wizard, so this seed
+ * became what every new Instagram automation carries from birth.
+ *
+ * ⚠ EMPTY IS LEGAL AND MEANS SOMETHING. `clean_predicates` stores `[]` inert (wave 24 A2) and
+ * `configured: false` rides the wire, so the surface says "finish setting this up" instead of
+ * refusing the save — while `run_discover_instagram` still refuses to SPEND on a filter that
+ * narrows nothing. Incomplete is a state; only the money door is a wall.
+ */
const [preds, setPreds] = useState(() => {
const stored = (automation.config as { predicates?: Predicate[] })?.predicates;
- return stored && stored.length
- ? stored.map((p) => ({ ...p }))
- : [{ name: "followers", operator: ">=", value: 10000 }];
+ return stored && stored.length ? stored.map((p) => ({ ...p })) : [];
});
const [estimate, setEstimate] = useState(null);
@@ -243,6 +335,30 @@ export default function AutomationDetail({
const table = tables.find((t) => t.key === targetTable) || null;
+ /**
+ * ⭐ THE WALKING RECORD'S DATABASE — the root cause of "the condition on the group names no
+ * field" (owner item 12a), and it was never a condition bug.
+ *
+ * `AutomationBuilder` resolved the field list from `trigger.table` ALONE. Every trigger without
+ * a table — manual, schedule, and the new `ig_profile_match`, which watches nothing because it
+ * MAKES rows — therefore handed `CondBuilder` an empty list, so the field picker offered
+ * "Choose a field…" and nothing else, and any condition saved against it named no field. The
+ * picker looked broken; the automation simply had no table for it to read.
+ *
+ * ⛔ MIRRORS `automation_engine._flow_table` (`:4319`) RATHER THAN INVENTING A SECOND RULE, and
+ * the ORDER is the part worth copying: the automation's own `targetTable` WINS over the
+ * trigger's table, not the other way round. A flow whose actions walk one database while its
+ * trigger watches another is a real shape, and getting the precedence backwards would offer the
+ * columns of the database the actions do not touch — a wrong list that looks authoritative,
+ * which this file already says is worse than no list.
+ * ⚠ The trigger's OWN pickers keep using the trigger's own table; these are two different
+ * questions and answering both from one variable is what produced the bug.
+ */
+ const walkTable =
+ kind === "discover_instagram"
+ ? String(cfg.targetTable || "") || String(discover?.table || "")
+ : String(cfg.targetTable || "") || String(automation.trigger?.table || "");
+
/**
* WHICH CONFIG PANEL IS OPEN — and the join is on `panel`, never on id equality.
*
@@ -330,6 +446,51 @@ export default function AutomationDetail({
* value for any flag a config omits — so a Save from here can never quietly
* turn the paid rung off. (`clean_config`'s `flag()`, asserted in section N.)
*/
+ /**
+ * The discovery conditions that are FINISHED enough to send.
+ *
+ * A condition is written in two gestures — pick the comparison, then type the value — and the
+ * server refuses a non-nullary comparison with no value ("give a value to compare 'biography'
+ * against"). Sending a half-written row therefore turned every Save between those two gestures
+ * into an error about a condition the user was still in the middle of writing. Held back
+ * instead: the row stays on screen and in state, it just is not claimed to the server yet.
+ *
+ * ⚠ HELD BACK IS SAID OUT LOUD (see `persist`) — a row that vanishes from the stored filter
+ * without a word is the silent-drop class this module refuses everywhere else.
+ *
+ * The nullary list comes off the wire; the literal is only for a server that did not send one,
+ * and it errs toward SENDING (the server then refuses, loudly) rather than toward dropping.
+ */
+ const completePreds = (): Predicate[] => {
+ const nullary = discover?.nullaryOperators || ["is_null", "is_not_null"];
+ return preds.filter((p) => {
+ if (!p.name || !p.operator) return false;
+ if (nullary.includes(p.operator)) return true;
+ return !(
+ p.value === undefined ||
+ p.value === null ||
+ (typeof p.value === "string" && !p.value.trim())
+ );
+ });
+ };
+
+ /**
+ * The sentence for whatever `completePreds` held back, or "" when it held nothing.
+ *
+ * ⚠ EVERY SAVE PATH SAYS IT, not just the Save button. The trigger picker and the cron control
+ * persist IMMEDIATELY (R9) and announce nothing on success — so without this, CLEARING a
+ * condition's value and then changing the trigger would drop that condition from the stored
+ * filter with the row still on screen and not a word anywhere. Holding a half-written row back
+ * is a courtesy; holding it back in silence is the drop class this module refuses everywhere.
+ */
+ const heldNote = (): string => {
+ if (kind !== "discover_instagram") return "";
+ const held = preds.length - completePreds().length;
+ if (held < 1) return "";
+ return `Saved — ${held} condition${held === 1 ? " was" : "s were"} not saved yet, `
+ + `${held === 1 ? "it needs" : "they need"} a value.`;
+ };
+
const buildConfig = (): Record => {
if (kind === "scrape_db") {
const fieldMap: Record = {};
@@ -348,11 +509,34 @@ export default function AutomationDetail({
return {
recordsLimit,
operator: joinOp,
- predicates: preds.filter((p) => p.name && p.operator),
+ predicates: completePreds(),
targetTable: String(cfg.targetTable || ""),
};
}
- return { targetTable, fieldKey, urlField, maxPosts };
+ if (kind === "field_instagram") {
+ return { targetTable, fieldKey, urlField, maxPosts };
+ }
+ /*
+ ⛔ EVERY ARM IS EXPLICIT AND THE FALL-THROUGH IS THE MINIMUM (wave 24, R6).
+ This used to END at `field_instagram`'s shape, as a bare `return` — so it was not a default,
+ it was a SILENT DEFAULT KIND, and R6 made `plain` the kind of every new automation. Picking
+ a trigger (the first thing anyone does now) called this and sent
+ `{targetTable, fieldKey, urlField, maxPosts}` for an automation that has no Instagram column
+ and no posts. It happens to be harmless today — `clean_config`'s `plain` arm reads only
+ `targetTable` and `lanes`, and falls back to the stored `lanes` — so nothing is lost and
+ nothing 400s. It is fixed anyway, because "harmless" here is luck rather than design: the
+ keys are dropped by a validator that was written independently, and the day `plain` grows a
+ key this shape happens to contain, a Save from any panel would write a value nobody chose.
+
+ This is the same defect C found twice in the engine on the same day — `graph()`'s final
+ `else` is `scrape_db`'s branch and `compose_sentence`'s is `discover_instagram`'s — so a new
+ kind silently inherited another kind's whole description. A last bare `else` is not a
+ default; it is whichever arm happened to be written last.
+
+ `targetTable` is the one key EVERY kind shares (it is what `_flow_table` resolves), so the
+ remaining fall-through carries that and nothing else.
+ */
+ return { targetTable };
};
const persist = async (announce = true, sched?: { cron: string; enabled: boolean }) => {
@@ -363,7 +547,7 @@ export default function AutomationDetail({
schedule: sched || { cron, enabled: !!automation.schedule?.enabled },
});
setTouched(false);
- if (announce) setMessage("Saved.");
+ if (announce) setMessage(heldNote() || "Saved.");
return res.automation.id;
};
@@ -391,6 +575,7 @@ export default function AutomationDetail({
schedule: { cron: next.cron, enabled: next.enabled },
});
setTouched(false);
+ setMessage(heldNote());
await onSaved(automation.id);
await loadBoard();
} catch (e) {
@@ -428,6 +613,7 @@ export default function AutomationDetail({
schedule: { cron, enabled: key === "schedule" },
});
setTouched(false);
+ setMessage(heldNote());
await onSaved(automation.id);
await loadBoard();
} catch (e) {
@@ -541,14 +727,18 @@ export default function AutomationDetail({
}
};
- const state = automation.running ? "running" : automation.status?.state || "idle";
-
/**
- * The trigger controls, built ONCE and rendered by whichever frame is mounted.
- * `AutomationTrigger` owns the vocabulary (C3), the cron round-trip and the tick
+ * The SCHEDULE half of the trigger face, built once and rendered by the Builder's Properties
+ * panel. `AutomationTrigger` owns the vocabulary (C3), the cron round-trip and the tick
* honesty note; this file owns only what a change should WRITE.
+ *
+ * ⛔ ONE FACE NOW, NOT TWO (item 10). There used to be a second copy with its picker SHOWN,
+ * rendered by the board's `.autob-triggerbar`. The board is for reading where records ARE —
+ * the trigger belongs to the Builder — so the bar is gone and with it the only caller that
+ * ever wanted the picker from this file. `hidePicker` survives because it is what makes ONE
+ * cron round-trip serve the Properties panel without a second trigger dropdown above it.
*/
- const triggerFace = (
+ const scheduleFace = (
);
+ /**
+ * The Builder's writer (C4). It PATCHES a PARTIAL definition — `{trigger}` or `{flow}` — and
+ * nothing else, which is what makes an immediate write safe here: `clean_trigger` and
+ * `clean_flow` merge against what is stored, so sending the one key that changed cannot
+ * blank the rest. (`persist()` above is the whole-form save the machine-step panels use; the
+ * two must not be confused, because that one DOES rewrite `config` from local state.)
+ */
+ const writeDefinition = async (body: Record) => {
+ setTriggerBusy(true);
+ setProblem("");
+ setMessage("");
+ try {
+ await patchAutomation(automation.id, body);
+ await onSaved(automation.id);
+ await loadBoard();
+ } catch (e) {
+ // ⛔ THE SERVER'S SENTENCE, VERBATIM. `clean_flow` refuses an empty group, an unready
+ // action kind, a valueless compare — each with a reason worth reading. A client that
+ // predicted those refusals would be a second validator free to disagree with the one
+ // that decides.
+ setProblem(e instanceof AutomationError ? e.message : "That change was not saved.");
+ } finally {
+ setTriggerBusy(false);
+ }
+ };
+
+ /**
+ * THE NAME, now that it lives at the top of Properties instead of in the page header
+ * (item 15b, C-DETAIL).
+ *
+ * ⛔ IT COMMITS ON BLUR AND WRITES IMMEDIATELY, like every other free-text field in that
+ * panel (the Gmail query, the review prompt, a value). That is not a style choice: the panel
+ * stamps "All changes saved", which is its receipt for the immediate-write discipline — a
+ * name sitting unsaved underneath it would make the stamp a lie. It is the cron field's exact
+ * shape (controlled while typing, one write on blur), because per-keystroke would PATCH a
+ * half-typed name.
+ *
+ * ⚠ A BLANK NAME IS NOT A NAME, and the header's Save has always refused one
+ * (`disabled={… || !name.trim()}`). Blurring an emptied box therefore RESTORES the stored
+ * name rather than writing an empty string or leaving the box contradicting the store — the
+ * two states a bare early-return would have left behind.
+ */
+ const commitName = async () => {
+ const next = name.trim();
+ const stored = automation.name || "";
+ if (!next) {
+ setName(stored);
+ return;
+ }
+ // Whitespace-only edits still normalise the box; they just have nothing to write.
+ if (next === stored) {
+ if (next !== name) setName(next);
+ return;
+ }
+ setName(next);
+ // ⚠ `{name}` ALONE IS A LEGAL PATCH — `engine.patch` merges by key over the stored
+ // definition (`automation_engine.py:1176` lists `name` among the patchable six), so this
+ // cannot blank the config, the schedule, the trigger or the flow.
+ await writeDefinition({ name: next });
+ };
+
+ /**
+ * THE MACHINE STEPS' CONFIG BODIES, joined on `panel` (C1 amendment 1) and rendered by
+ * BOTH views.
+ *
+ * ⚠ EXTRACTED, NOT COPIED, and the difference is the whole point. The Builder shows the
+ * same engine-derived steps the Board's process strip does, so a second copy of these
+ * five panels would be two surfaces that must agree with `clean_config` forever — and the
+ * way they would stop agreeing is silent: one of them keeps writing a key the engine
+ * renamed. One body, two callers.
+ */
+ const panelBody = (panelKey: string) => (
+ <>
+ {panelKey === "source" && kind === "scrape_db" ? (
+ <>
+
+ ) : null}
+ {/* "loopback and link-local addresses" is the SSRF rail describing itself.
+ The rail still refuses them, loudly, at the moment it happens. */}
+
Public web pages only.
+ >
+ ) : null}
+
+ {panelKey === "columns" ? (
+ plan.length ? (
+ <>
+ {/* The upsert rules, in full, to somebody choosing a column. What they
+ need is which column, and that rows are updated rather than duplicated. */}
+
+ Pick the column that identifies a row, so re-runs update it instead of
+ adding it again.
+
+
+ edit(setFieldKey)(e.target.value)}
+ >
+
+ {/*
+ ⚠ THE STORED VALUE IS ALWAYS AN OPTION, even when the list
+ below does not contain it. A whose `value` matches
+ no
+ ) : null}
+ {(table?.fields || [])
+ .filter((f) => f.type === "automation")
+ .map((f) => (
+
+ ))}
+
+
ESSAYS ON THE CAPTURE RUNGS lived here — the vendor by name,
+ datacenter egress, "204K not 204,312", which rung answers when. The
+ CHOICE a person makes is exact-or-estimated and what it costs; the rest
+ was the architecture explaining itself. DESIGN.md §4. */}
+
Exact counts
+
+ Real follower numbers and the account’s top posts, charged per profile.
+ {paidReady ? "" : " Not set up on this workspace yet."}
+
+
Post engagement
+
+ Likes and comments per post. Charged per post, so it is its own switch.
+
+
Estimated counts
+
+ Free, but rounded (204K rather than 204,312) and marked as estimates. Switch
+ it off to get exact numbers or nothing.
+
+ ) : kind === "discover_instagram" ? (
+ /*
+ ⛔ FOUR PARAGRAPHS LIVED HERE and the owner quoted every one of them back:
+ the upsert key, the Times-found counter, the never-un-ticked guarantee,
+ the dry-run definition, and "a row that stops appearing at the source is
+ counted and kept, never deleted". All TRUE, all engine internals, none of
+ them a thing a customer came here to learn. DESIGN.md §4.
+ What survives is the only sentence with a decision in it: results wait for
+ you. (Duplicates elsewhere are gone rather than reworded — the Find panel
+ already says nothing is picked automatically.)
+ */
+
+ Profiles you find are saved here for you to review. Nothing is picked
+ automatically.
+
+ ) : (
+
+ Each run adds a dated row, so you keep the history rather than just
+ today’s number.
+
+ )}
+
+ Switch this off to test the automation without saving anything.
+ {kind === "field_instagram" ? (
+ <>
+ {" "}
+ {/* "Writes nothing" and "costs nothing" are different claims and only
+ the first is true — the one place anybody finds out before the bill. */}
+ It still reads, so it still costs the same.
+ >
+ ) : null}
+
+ >
+ ) : null}
+ >
+ );
+
return (
+ {/*
+ ⭐ ITEM 15b — THE TITLE ROW IS THE VIEW SWITCH NOW. It held an editable name, a run-state
+ chip and a kind tag; all three left and Builder/Board took the space, left-aligned, with
+ Run now / Save / Delete still on the right.
+
+ WHERE EACH ONE WENT, because "removed" and "lost" are different claims:
+ · the NAME is the first field of the Builder's Properties panel, writing on blur;
+ · the STATE is the builder's own step chip, the Run-now button's "Running…", and the
+ rail's per-automation dot — three surfaces that were already saying it;
+ · the KIND stops being a user-facing fact at all this wave (R6: every new automation
+ is `plain`), and the two legacy machine kinds describe themselves in Properties →
+ Configuration → "How this fetches".
+
+ ⚠ AND THE PAGE TITLE IS NOT DRAWN HERE EITHER WAY. The shell's `DbHead` (W23-W1) draws
+ the SURFACE's name — the literal "Automation" off the nav payload — never this
+ automation's. See the dated amendment under C-DETAIL: the contract's premise was wrong
+ on that point and the consequence (no name in the Board view) is booked, not patched.
+ */}
- edit(setName)(e.target.value)}
- />
-
- {STATE_LABELS[state] || state}
-
-
- {kinds.find((k) => k.key === kind)?.label || kind}
-
+ {/* TWO VIEWS OF ONE AUTOMATION (C1): what it DOES, and where its records ARE. The
+ switch is a segmented control rather than a tab strip because the page below it
+ does not change identity — it is the same automation, read two ways. */}
+
+ {/*
+ ⭐ W24-W1 — WHAT IT IS DOING, beside the button that started it. This is the whole of
+ item 6's honest fix: "Running…" for two minutes is indistinguishable from a hung
+ thread, and the engine has been publishing the step text the entire time.
+ ⚠ IT IS A STATEMENT, NOT A CONTROL, and it renders only while there is something to
+ say — `liveStepOf` returns `""` unless the automation is running, so this never shows
+ a step left over from a run that finished.
+ */}
+ {liveStep ? (
+
+ {liveStep}
+
+ ) : null}
);
diff --git a/web/src/automation/AutomationFind.tsx b/web/src/automation/AutomationFind.tsx
index 09c13963bee69f4f2a25eaa0f1c779cdece29cd6..f8b90ef230cddfec04cc6805567acab6bfbdb047 100644
--- a/web/src/automation/AutomationFind.tsx
+++ b/web/src/automation/AutomationFind.tsx
@@ -34,6 +34,7 @@
import type {
DiscoverEstimate,
DiscoverFieldMeta,
+ DiscoverOperator,
DiscoverVocab,
Predicate,
} from "./automationApi";
@@ -51,9 +52,160 @@ interface Props {
onEstimate: () => void;
}
+/**
+ * A FILTER FIELD'S ICON (owner item 5). Drawn, `currentColor`, never an emoji — and in the
+ * existing `TriggerMark`/`ActionMark` language rather than a new one: same 16 viewBox, same 15px
+ * box, same 1.4 stroke, so a row here and a card in the builder read as one product.
+ *
+ * ⚠ SHARED SHAPES WHERE THE FIELDS SHARE A MEANING, distinct everywhere else. `TriggerMark`'s
+ * note settled the principle — a column of identical glyphs is decoration, the eye learns nothing
+ * — but its converse matters just as much here: `bio_hashtags` and `post_hashtags` ARE both
+ * hashtags, and drawing two different marks for them would invent a distinction the vendor does
+ * not make. Twenty-one contrived glyphs would be twenty-one things to misread.
+ *
+ * ⛔ THE FALLBACK IS NOT A MEMBER OF THE SET, which is the `ActionMark` scar exactly: its default
+ * used to BE the pencil, a real member, so every unmatched kind silently borrowed "edit" and a
+ * fallback could not be told from a match. The vocabulary is the SERVER's — it can grow a field
+ * tomorrow — so an unmatched name draws a neutral mark that is deliberately meaningless.
+ */
+function FilterMark({ name }: { name: string }) {
+ const common = {
+ width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
+ strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
+ "aria-hidden": true,
+ };
+ // Audience size — two figures, one behind the other.
+ if (name === "followers")
+ return (
+
+ );
+ // Who this account follows — a figure with an outbound arrow.
+ if (name === "following")
+ return (
+
+ );
+ if (name === "posts_count")
+ return (
+
+ );
+ // A story highlight — the ring Instagram draws around one.
+ if (name === "highlights_count")
+ return (
+
+ );
+ if (name === "avg_engagement")
+ return (
+
+ );
+ if (name === "biography")
+ return (
+
+ );
+ if (name === "category_name" || name === "business_category_name")
+ return (
+
+ );
+ if (name === "is_business_account" || name === "is_professional_account")
+ return (
+
+ );
+ if (name === "is_verified")
+ return (
+
+ );
+ // The handle, and the display name it is written under.
+ if (name === "account" || name === "profile_name")
+ return (
+
+ );
+ if (name === "full_name")
+ return (
+
+ );
+ if (name === "external_url" || name === "profile_url")
+ return (
+
+ );
+ if (name === "bio_hashtags" || name === "post_hashtags")
+ return (
+
+ );
+ if (name === "related_accounts")
+ return (
+
+ );
+ // The vendor's own record keys — the thing you hold to open exactly one row.
+ if (name === "id" || name === "fbid")
+ return (
+
+ );
+ return (
+
+ );
+}
+
/** One field's line in the list, with everything known about it. */
interface FieldRow {
name: string;
+ /** What the row is CALLED. Falls back to the raw name only if the server sent none. */
+ label: string;
+ hint: string;
+ kind: string;
+ operators: DiscoverOperator[];
+ options: { value: string; label: string }[];
/** Every stored condition naming this field, with its index in the saved array. */
at: number[];
/** MEASURED to carry values. `null` = the server has not said (C4 not shipped yet). */
@@ -62,24 +214,48 @@ interface FieldRow {
narrowing: boolean | null;
}
+/** A stored value → what the text box shows. A list is the "any of" shape. */
+function valueText(v: Predicate["value"]): string {
+ if (Array.isArray(v)) return v.join(", ");
+ return v === undefined || v === null ? "" : String(v);
+}
+
/**
- * A default operator that is VALID THE MOMENT THE SWITCH GOES ON.
+ * What the user typed → what is stored. Comma-separated becomes a LIST for the operators that
+ * accept one, and stays a plain string for the ones that do not.
*
- * ⚠ This is the wave-21 item-8 scar in a new shape. A new condition used to
- * arrive as `{biography includes ""}` — a comparison with no value, which
- * `clean_predicates` refuses outright — so adding one and pressing Save returned
- * "give a value to compare 'biography' against" for a condition the user had not
- * finished writing. A NULLARY operator needs no value, so a freshly toggled
- * field is a complete, saveable, narrowing-in-the-right-direction condition
- * ("this field has any value") from its first frame.
+ * ⚠ A single value stays a SCALAR rather than a one-element list — the server sends scalars
+ * flat and lists as a nested OR group, and a one-element group is a shape nothing has been
+ * billed against.
+ */
+function parseValue(text: string, multi: boolean): Predicate["value"] {
+ if (!multi) return text;
+ const parts = text.split(",").map((s) => s.trim()).filter(Boolean);
+ if (parts.length > 1) return parts;
+ // Keep the RAW text while it is still being typed — trimming here would fight the cursor on
+ // every keystroke, and the server trims anyway.
+ return text;
+}
+
+/**
+ * The comparison a freshly toggled field starts with — ASKED FOR, never chosen here.
*
- * Derived from the server's own lists rather than typed here, so it cannot name
- * an operator the API rejects.
+ * ⛔ THE THIRD COSTUME OF ONE SCAR, and the reason this function no longer has an opinion.
+ * Wave 21 made a new condition NULLARY (`is_not_null`) so it would be saveable without a
+ * value, and called that "narrowing-in-the-right-direction". Wave 22 then wrote the narrowing
+ * law server-side and `is_not_null` is not in it. From that moment, toggling ANY field on and
+ * pressing Save returned "add at least one CONTENT condition…" — the error told the user to do
+ * the exact thing they had just done. Wave 24 deleted the wizard and made this panel the only
+ * door, so it stopped being a corner case and became the first thing a new user hits.
+ *
+ * The fix is not a better guess. It is that the module owning the guard also names the default
+ * (`automation_engine.default_operator`, asserted against `predicate_narrows` in
+ * `verify_automation.py`), and this file looks it up per FIELD. An absent one falls back to the
+ * server's first operator — never to a nullary, which is the thing that could not narrow.
*/
-function firstOperator(v?: DiscoverVocab): string {
- const nullary = v?.nullaryOperators || [];
- const preferred = nullary.find((o) => o === "is_not_null");
- return preferred || nullary[0] || (v?.operators || [])[0] || "";
+function firstOperator(v: DiscoverVocab | undefined, name: string): string {
+ const meta = (v?.filterMeta || []).find((m) => m.name === name);
+ return meta?.defaultOperator || (v?.operators || [])[0] || "";
}
/**
@@ -107,6 +283,14 @@ function buildRows(preds: Predicate[], v?: DiscoverVocab): FieldRow[] {
const m = meta.get(name);
return {
name,
+ label: m?.label || name,
+ hint: m?.hint || "",
+ kind: m?.kind || "text",
+ // ⛔ NO FALLBACK TO THE GLOBAL OPERATOR LIST. An older server that sends no per-field list
+ // gets a row with no comparisons rather than all fourteen on every field — visibly
+ // unfinished beats quietly offering `at least` on a yes/no column.
+ operators: m?.operators || [],
+ options: m?.options || [],
at: byName.get(name) || [],
populated: m ? !!m.populated : lead.has(name) ? true : null,
narrowing: m ? !!m.narrowing : null,
@@ -131,8 +315,10 @@ export default function AutomationFind({
}: Props) {
const rows = buildRows(preds, discover);
const known = new Set(discover?.fields || []);
+ // The GLOBAL operator list is gone from this component: comparisons are per field now
+ // (`row.operators`). `nullary` survives for STRAYS only — a stored condition on a field the
+ // vendor dropped has no per-field row to read from, and it still has to render to be removable.
const nullary = new Set(discover?.nullaryOperators || []);
- const operators = discover?.operators || [];
const withValues = rows.filter((r) => r.populated === true);
const rest = rows.filter((r) => r.populated !== true);
const knownMeta = !!(discover?.filterMeta || []).length;
@@ -157,13 +343,20 @@ export default function AutomationFind({
onPreds(preds.filter((p) => p.name !== row.name));
return;
}
- onPreds([...preds, { name: row.name, operator: firstOperator(discover) }]);
+ onPreds([...preds, { name: row.name, operator: firstOperator(discover, row.name) }]);
};
/** One condition line — the comparison, its value, and a way out. */
- const condition = (i: number, label: string) => {
+ const condition = (i: number, label: string, row?: FieldRow) => {
const p = preds[i];
if (!p) return null;
+ // The field's OWN comparisons. `row` is absent only for a stray (a stored condition on a
+ // field the vendor no longer offers), which keeps the raw token so it stays removable.
+ const ops = row?.operators || [];
+ const cur = ops.find((o) => o.value === p.operator);
+ const isNullary = cur ? cur.nullary : nullary.has(p.operator);
+ const isMulti = !!cur?.multi;
+ const options = row?.options || [];
return (
o.value === p.operator) ? (
) : null}
- {operators.map((o) => (
-
))}
- {nullary.has(p.operator) ? (
-
- any value
-
+ {isNullary ? null : options.length ? (
+ // A fixed vocabulary gets a dropdown. Owner item 2: a yes/no column was a box you
+ // typed `true` into, beside a comparison list that offered "at least".
+ setAt(i, { value: e.target.value })}
+ >
+
+ {options.map((o) => (
+
+ ))}
+
) : (
setAt(i, { value: e.target.value })}
+ // ⭐ OWNER ITEM 3. Several comma-separated values become an "any of" condition, which
+ // the server sends as its own OR group — so it does NOT drag Followers into a union
+ // the way the Match dropdown would.
+ placeholder={isMulti ? "floral, flower, beauty" : ""}
+ value={valueText(p.value)}
+ onChange={(e) => setAt(i, { value: parseValue(e.target.value, isMulti) })}
/>
)}
+ {isMulti && Array.isArray(p.value) && p.value.length > 1 ? (
+
+ any of {p.value.length}
+
+ ) : null}
- {/* The VENDOR'S OWN NAME, verbatim. Not prettified: every refusal the
- server sends names the field exactly like this ("'x' cannot be used
- to search — the searchable fields are: …"), and a label that reads
- differently from the error makes the error unmatchable. */}
- {row.name}
+
+
+
+ {/* ⭐ THE HUMAN LABEL (owner item 1: "wtf is id/fbid").
+ This used to render the vendor's own column name verbatim, and the comment
+ defending it was RIGHT about the reason — a refusal names the field, and a label
+ that reads differently makes the error unmatchable. So the label did not move
+ alone: `field_label()` is what the SERVER's refusals use too, which is the only
+ version of this change that does not trade one confusion for another. */}
+
+ {row.label}
+
{/*
⚠ ONE CHIP, AND IT MARKS THE MINORITY. The first version chipped every
non-narrowing field "broad" AND every unpopulated one "no values seen" —
@@ -247,7 +469,7 @@ export default function AutomationFind({
{row.narrowing === true ? (
narrows
@@ -255,15 +477,16 @@ export default function AutomationFind({
- A search must be bounded — at most {maxRecords.toLocaleString()} profiles a run. An
- unbounded one matches a share of a corpus of hundreds of millions, and the vendor
- refuses it outright rather than delivering it.
-
+ {/* Owner item 5: "Stop at the 'A search must be at most 500 profiles a run'". The two
+ sentences that followed explained the vendor's billing model to somebody who wants a
+ list of florists. */}
+
At most {maxRecords.toLocaleString()} profiles a run.
Conditions
@@ -315,9 +537,9 @@ export default function AutomationFind({
- Has values
+ Usually filled in
{withValues.map(fieldRow)}
@@ -329,11 +551,11 @@ export default function AutomationFind({
className="autob-tglgroup-label"
title={
knownMeta
- ? "Filterable, but empty on every profile we have measured — a condition on one of these can return nothing at all."
- : "Whether these carry values has not been measured yet."
+ ? "Most accounts leave these blank, so a condition here can return nothing."
+ : "We have not measured how often these are filled in."
}
>
- {knownMeta ? "No values seen" : "Not measured"}
+ {knownMeta ? "Often blank" : "Not measured"}
{rest.map(fieldRow)}
@@ -345,6 +567,14 @@ export default function AutomationFind({
{strays.map(({ p, i }) => (
+ {/* A stray gets a mark too — "every filter row" includes the ones the vendor no
+ longer offers, and a row missing the icon its neighbours have would read as a
+ different KIND of thing rather than as a field that fell out of the list. It
+ draws the neutral fallback by construction: a stray is, by definition, not in
+ the vocabulary this component has arms for. */}
+
+
+ {p.name}
not searchable
@@ -356,14 +586,11 @@ export default function AutomationFind({
) : null}
+ {/* The consequence kept, the mechanism dropped: a condition on an often-blank field
+ returning nothing is a thing that will happen to somebody and confuse them. Why the
+ search is slow when broad is our problem, not theirs. */}
- {/* ONE consequence sentence, because it is the one that costs money. Which
- fields carry values is not trivia: a condition on an empty field returns
- nothing and looks exactly like an honest "no such accounts exist". */}
- A condition on a field with no values returns nothing while looking exactly like
- “no such accounts exist”. Narrow conditions matter more than a small limit
- — the search reads the whole corpus either way, so a broad one is slow and expensive
- however few rows you keep.
+ Conditions on often-blank fields can come back with nothing.
What it costs
diff --git a/web/src/automation/AutomationSurface.tsx b/web/src/automation/AutomationSurface.tsx
index 699a6b87693c33368325b9cd735ecba4488353a1..c547ba4403870718e3d002bc7c6634dd94085c96 100644
--- a/web/src/automation/AutomationSurface.tsx
+++ b/web/src/automation/AutomationSurface.tsx
@@ -16,20 +16,37 @@
import type { KeyboardEvent as ReactKeyboardEvent } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
-import AutomationCreate from "./AutomationCreate";
+import type { AutomationOpenDetail } from "../apiContract";
+import { AUTOMATION_CREATE_EVENT, AUTOMATION_OPEN_EVENT } from "../apiContract";
import AutomationDetail from "./AutomationDetail";
import type { Automation, AutomationList } from "./automationApi";
import {
AutomationError,
+ createAutomation,
listAutomations,
+ liveStepOf,
patchAutomation,
stateOf,
} from "./automationApi";
+/**
+ * The run poll's cadence (item 6). Named constants because they are a MEASURED trade-off, not a
+ * taste: `POLL_MAX_MS` is the longest a finished run can still look live, and it is the only
+ * cost the backoff has.
+ */
+const POLL_MIN_MS = 2500;
+const POLL_MAX_MS = 8000;
+
/** The status dot's title — the rail says WHY it is that colour, not just that it is. */
function stateTitle(a: Automation): string {
const s = stateOf(a);
- if (s === "running") return "Running now";
+ // ⭐ WAVE 24 (item 6). "Running now" was the whole answer for a run that can legitimately
+ // block 120 s at the vendor, so the tooltip said no more than the colour did. The step is
+ // the server's own word for what it is doing.
+ if (s === "running") {
+ const step = liveStepOf(a);
+ return step ? `Running now — ${step}` : "Running now";
+ }
if (s === "ok") return `Last run succeeded — ${a.status?.lastSummary || ""}`;
if (s === "partial") return `Last run was partial — ${a.status?.lastSummary || ""}`;
if (s === "error") return `Last run failed — ${a.status?.lastSummary || ""}`;
@@ -50,33 +67,188 @@ function stateTitle(a: Automation): string {
* its job. [[ui-invisible-to-assertions]] — judge the pixels even when everything is green.
*/
function railSubtitle(a: Automation): string {
+ /*
+ * ⭐ WAVE 24 (owner item 6, "Run once now is laggy / looks stuck") — WHILE IT IS RUNNING,
+ * THE ONE FACT WORTH THE LINE IS WHAT IT IS DOING.
+ *
+ * MEASURED, not guessed (`scratchpad/perf_automations.py`, mailbox D-5): the engine has been
+ * publishing a live step the whole time (`status.step`, `routes_automation.py:50-51`) and NO
+ * SURFACE HAS EVER RENDERED IT. So a `discover_instagram` run parked in its legitimate
+ * `BD_FILTER_WAIT = 120 s` vendor wait and a genuinely hung thread were pixel-identical: a
+ * pulsing blue dot and a subtitle still reciting the schedule. "Looks stuck" was not a
+ * performance problem — the poll costs 23 ms — it was the product declining to say.
+ *
+ * It takes the line rather than joining it, for the reason this function's note already
+ * gives: the rail is `--lp-rail-w` wide and two facts that both truncate are worth less than
+ * one that fits. The schedule is still one click away and the dot's `title` carries both.
+ */
+ const step = liveStepOf(a);
+ if (step) return step;
if (a.schedule?.enabled) return a.nextRunAt ? `Next ${a.nextRunAt}` : "Scheduled";
const last = a.status?.lastRunAt ? a.status.lastRunAt.replace("T", " ").slice(0, 16) : "";
return last ? `Last run ${last}` : "Manual only";
}
+/*
+ * ⛔ W23-W5's LISTENER IS AT MODULE SCOPE, AND THAT IS THE POINT — not a stylistic choice.
+ *
+ * The frame's click-through sets `window.location.hash = "#/automation"` and signals on the
+ * VERY NEXT LINE (Shell.tsx:1647-1650, and its comment is right that the order matters). But a
+ * hash write does not mount anything synchronously: `hashchange` is delivered as a task, the
+ * router state then updates, React renders, and only THEN does a component effect subscribe.
+ * A listener registered in `useEffect` therefore misses every click that arrives from another
+ * page — which is every click, since a reader looking at Alerts is by definition not already
+ * on this surface. The event would dispatch into nothing and every gate would stay green:
+ * exactly the wave-20 item-25 failure the contract's own note describes, reproduced one layer
+ * down.
+ *
+ * This module is imported statically by the shell, so this listener exists from app start. It
+ * LATCHES the request; the component consumes the latch when it mounts and hears live events
+ * while it is mounted. A request nobody claims is dropped on the next one — the latch is a
+ * one-slot mailbox, never a queue.
+ */
+let pendingOpen: AutomationOpenDetail | null = null;
+const openSubscribers = new Set<(detail: AutomationOpenDetail) => void>();
+
+if (typeof window !== "undefined") {
+ window.addEventListener(AUTOMATION_OPEN_EVENT, (event) => {
+ const detail = (event as CustomEvent).detail;
+ if (!detail?.autoId) return;
+ if (openSubscribers.size) {
+ for (const notify of openSubscribers) notify(detail);
+ return;
+ }
+ pendingOpen = detail;
+ });
+}
+
+/*
+ * ⭐⭐ WAVE 24 / C-CREATE (b) — `AUTOMATION_CREATE_EVENT` GETS ITS FIRST LISTENER, EVER.
+ *
+ * ⛔ THIS CLOSES A DEFECT THAT IS LIVE IN v12 TODAY, found while planning this wave and verified
+ * by grep rather than reasoned: the event is declared (`apiContract.ts:149`), imported and
+ * signalled (`Shell.tsx:1142`), and **nothing anywhere in `src/` consumed it.** So all THREE
+ * "Automated database" doors — the Database flyout's footer, Home's card, and the New-database
+ * dialog's third row — navigated to `#/automation` and then did nothing at all. An affordance
+ * that quietly does not exist, with every gate green: the wave-20 item-25 class exactly, which is
+ * the very failure the contract note above this file's OPEN listener was written about. It
+ * happened again anyway, one event over, because a declared event and a consumed one look
+ * identical from every direction except a grep for the listener.
+ *
+ * MODULE SCOPE WITH A LATCH, for the reason spelled out above and not as a style choice: a
+ * `useEffect` listener subscribes only after the hash write, the router update and a React
+ * render — so it misses EVERY click that arrives from another page, which is every real click.
+ *
+ * The event carries NO detail by contract ("open the create flow" is the whole message), so the
+ * latch is a boolean rather than a one-slot mailbox. Its meaning is now what all three doors
+ * always promised: **create a `plain` automation and select it.**
+ */
+let pendingCreate = false;
+const createSubscribers = new Set<() => void>();
+
+if (typeof window !== "undefined") {
+ window.addEventListener(AUTOMATION_CREATE_EVENT, () => {
+ if (createSubscribers.size) {
+ for (const notify of createSubscribers) notify();
+ return;
+ }
+ pendingCreate = true;
+ });
+}
+
+/**
+ * A default name for a brand-new automation, and it has to be one the server ACCEPTS.
+ *
+ * MEASURED against the live route rather than assumed (`scratchpad/probe_names.py`): a create
+ * with no name is a 400 (`name the automation`), and duplicate names are ALLOWED. So the name
+ * cannot be omitted, and a fixed literal would stack "New automation" three deep in a rail that
+ * sorts by name with nothing to tell the rows apart. Numbering from the existing list is a
+ * client-side convenience over a server that does not care: if two tabs race, the loser gets a
+ * duplicate name, which is legal, visible and renameable — never an error the user has to read.
+ */
+function nextAutomationName(existing: Automation[]): string {
+ const taken = new Set(existing.map((a) => (a.name || "").trim().toLowerCase()));
+ for (let n = existing.length + 1; ; n += 1) {
+ const candidate = `Automation ${n}`;
+ if (!taken.has(candidate.toLowerCase())) return candidate;
+ }
+}
+
export default function AutomationSurface() {
const [data, setData] = useState(null);
const [error, setError] = useState("");
const [activeId, setActiveId] = useState("");
- const [creating, setCreating] = useState(false);
const [railShut, setRailShut] = useState(false);
const [busy, setBusy] = useState("");
+ /**
+ * ⭐ WAVE 24 / C-CREATE — a create is now a ROUND TRIP, not a local wizard, so the door has to
+ * say it is busy. Without this a second click while the POST is in flight makes a second
+ * automation, and the server allows duplicate names, so the user gets two rows that look
+ * identical and no error to explain either of them.
+ */
+ const [creatingNow, setCreatingNow] = useState(false);
+ /** W23-W5's advisory half: which stage's panel the click-through asked for, if any. */
+ const [openStage, setOpenStage] = useState("");
+ /** An open request waiting for the list to arrive (see the resolver below). */
+ const [openRequest, setOpenRequest] = useState(null);
+ /** A CREATE request from outside this surface (C-CREATE b), waiting for the list to arrive. */
+ const [createRequest, setCreateRequest] = useState(false);
const listRef = useRef(null);
+ /**
+ * ⛔ C14 LEG 2 — THE ID THE USER LAST ASKED FOR, and it is a ref because it has to be
+ * written SYNCHRONOUSLY, inside the click, before any promise that was already in flight
+ * can resolve. State would not do: a resolution racing React's commit would read the
+ * previous value, which is the exact window this guard exists to close.
+ */
+ const wantedId = useRef("");
+
+ /**
+ * ⭐ THE ONLY PLACE THE RAIL'S SELECTION MOVES ON PURPOSE. Every deliberate change of
+ * automation — a rail click, a create, a delete — goes through here, so "what the user
+ * asked for" and "what is on screen" are written in one statement and cannot drift apart.
+ * A resolution that wants to steer the rail compares itself against `wantedId` instead.
+ */
+ const select = useCallback((id: string, stage = "") => {
+ wantedId.current = id;
+ setActiveId(id);
+ // The stage hint belongs to THIS selection and no other. Every ordinary caller passes
+ // nothing, which clears it — so a review notification cannot leave a stage open on the
+ // next automation the reader clicks by hand.
+ setOpenStage(stage);
+ }, []);
+
+ /**
+ * ⛔ C14 LEG 3 (the paint half) — A STALE READ MAY NOT REPAINT.
+ *
+ * Every call takes the next generation; only the newest one is allowed to `setData`. The
+ * defect this closes is not cosmetic: a poll issued BEFORE a delete resolves AFTER it, and
+ * a list that still contains the deleted automation puts a row back in the rail that the
+ * user has just watched disappear. Same for a toggle, and same for a create.
+ *
+ * ⚠ THE RETURN VALUE IS NOT GUARDED, deliberately. The caller asked a question and gets
+ * its own answer — coupling the two would mean a create whose `load()` was overtaken by a
+ * poll silently failed to select the automation it had just made.
+ */
+ const gen = useRef(0);
+
const load = useCallback(async (abort?: AbortSignal) => {
+ const mine = ++gen.current;
try {
const next = await listAutomations(abort);
- setData(next);
- setError("");
+ if (mine === gen.current) {
+ setData(next);
+ setError("");
+ }
return next;
} catch (e) {
if ((e as Error)?.name === "AbortError") return null;
- setError(
- e instanceof AutomationError
- ? e.message
- : "The automation service did not answer."
- );
+ if (mine === gen.current)
+ setError(
+ e instanceof AutomationError
+ ? e.message
+ : "The automation service did not answer."
+ );
return null;
}
}, []);
@@ -87,16 +259,169 @@ export default function AutomationSurface() {
return () => ac.abort();
}, [load]);
+ /**
+ * ⭐⭐ WAVE 24 / C-CREATE (a) — CREATE AND OPEN. This REPLACED the three-step wizard.
+ *
+ * R6 is what makes it possible: `plain` is a real kind with no machine graph nodes, and it is
+ * what `POST /automations` stores when the body names none. So "new automation" stopped being
+ * a question ("which of three kinds?" — two of which can no longer be created at all) and
+ * became what it says: a new automation, open, on its trigger picker. Choosing a SOURCE is now
+ * picking the `ig_profile_match` trigger, which is where that choice belongs.
+ *
+ * ⛔ THE GUARD IS A REF, not the `creatingNow` state, and this file already carries the scar
+ * that explains why (C14 leg 2): a state read inside a click closure is the value from the
+ * last render, so two fast clicks both see `false` and both POST. Duplicate names are legal
+ * server-side, so the user would get two identical rows and no error. The ref is written
+ * synchronously, inside the click, before anything can await.
+ */
+ const creatingRef = useRef(false);
+ const createAndOpen = useCallback(async () => {
+ if (creatingRef.current) return;
+ creatingRef.current = true;
+ setCreatingNow(true);
+ try {
+ const res = await createAutomation({
+ name: nextAutomationName(data?.automations || []),
+ });
+ const id = res?.automation?.id || "";
+ // The create flow is the one caller allowed to name a different id (C14 leg 2) — the
+ // automation did not exist when the click happened, so there is nothing to race with.
+ const next = await load();
+ if (id && next) select(id);
+ } catch (e) {
+ setError(
+ e instanceof AutomationError ? e.message : "The automation was not created."
+ );
+ } finally {
+ creatingRef.current = false;
+ setCreatingNow(false);
+ }
+ }, [data, load, select]);
+
// A run is a background thread on the server, so the surface has to ASK whether it
// finished. Polling only while something is actually running keeps an idle surface
// silent — a fixed interval would be a request every few seconds forever, for a page
// whose contents change a handful of times a day.
- const anyRunning = (data?.automations || []).some((a) => a.running);
+ //
+ // ⛔ C14 LEG 3 (the abort half). It used to call `load()` bare — no signal, nothing to
+ // cancel — so a request the interval had already issued kept going after the effect that
+ // owned it was gone. One controller per effect run, aborted with the interval, means a poll
+ // cannot outlive the condition that justified it. The generation guard inside `load` covers
+ // the rest: a response that survives the abort still cannot repaint over a newer one.
+ //
+ // ⭐ WAVE 24 (item 6, C-PERF) — THE INTERVAL BECAME A BACKOFF, and the measurement is why it is
+ // a SMALL change rather than the big one the contract's hypothesis 2 asked for.
+ //
+ // MEASURED (`scratchpad/perf_automations.py`, mailbox D-5): this poll costs ~23 ms and 24 KB
+ // for a ten-automation tenant, and the engine work the hypothesis blamed — a `graph()` rebuild
+ // per automation — is **41 µs each**, i.e. under 4% of the request. The payload was never the
+ // problem, so nothing here gets a cheaper endpoint.
+ //
+ // What the numbers DO indict is the aggregate: a discovery run legitimately blocks up to
+ // `BD_FILTER_WAIT` = 120 s, and two independent 2.5 s polls across this file and the detail
+ // spend ~96 requests and ~2.3 MB over that window — in the same single process the run itself
+ // is a thread in. So the delay grows 2.5 → 5 → 8 s and stops there.
+ //
+ // ⚠ NOT "to learn nothing", and the distinction is the whole justification. That WAS true when
+ // this file rendered no live step: the poll's only observable effect was a dot that had already
+ // been pulsing for two minutes. It stopped being true in this same change — `liveStepOf` now
+ // paints `status.step`, so a poll carries the one fact worth having. The backoff is therefore
+ // NOT "stop asking a pointless question"; it is FEWER ROUND TRIPS FOR THE SAME INFORMATION, on
+ // a step text that changes every few seconds at most, not every 2.5.
+ // The cap is deliberately low: it bounds how long a FINISHED run can still look live, which is
+ // the only thing a backoff can make worse, and 8 s of that is worth ~⅔ fewer requests.
+ //
+ // ⛔ THE KEY IS THE RUNNING SET, NOT A BOOLEAN, and that is what makes the reset correct: the
+ // effect re-runs — and the delay drops back to 2.5 s — the moment a run starts or finishes, so
+ // a user who clicks Run now gets the fast cadence again instead of inheriting the tail of the
+ // previous run's backoff. A bare `anyRunning` boolean cannot see the second run start.
+ // A step text changing does NOT re-key it, so the interval never thrashes.
+ //
+ // C14 LEG 3 (the abort half) is unchanged and still load-bearing: one controller per effect
+ // run, aborted with the timer, so a poll cannot outlive the condition that justified it. The
+ // generation guard inside `load` covers the rest.
+ const runningKey = (data?.automations || [])
+ .filter((a) => a.running)
+ .map((a) => a.id)
+ .sort()
+ .join(",");
+ useEffect(() => {
+ if (!runningKey) return undefined;
+ const ac = new AbortController();
+ let delay = POLL_MIN_MS;
+ let timer = 0;
+ const tick = () => {
+ void load(ac.signal);
+ delay = Math.min(delay * 2, POLL_MAX_MS);
+ timer = window.setTimeout(tick, delay);
+ };
+ timer = window.setTimeout(tick, delay);
+ return () => {
+ window.clearTimeout(timer);
+ ac.abort();
+ };
+ }, [runningKey, load]);
+
+ // ── W23-W5, the surface's half: hear the request, then answer it when we CAN ──────────
+ useEffect(() => {
+ const notify = (detail: AutomationOpenDetail) => setOpenRequest(detail);
+ openSubscribers.add(notify);
+ if (pendingOpen) {
+ const latched = pendingOpen;
+ pendingOpen = null;
+ setOpenRequest(latched);
+ }
+ return () => {
+ openSubscribers.delete(notify);
+ };
+ }, []);
+
+ // ── C-CREATE (b), the surface's half: hear the request, then answer it when we CAN ──────────
+ useEffect(() => {
+ const notify = () => setCreateRequest(true);
+ createSubscribers.add(notify);
+ if (pendingCreate) {
+ pendingCreate = false;
+ setCreateRequest(true);
+ }
+ return () => {
+ createSubscribers.delete(notify);
+ };
+ }, []);
+
+ /**
+ * ⚠ THE REQUEST WAITS FOR THE LIST, exactly as the open request does — and here it is not just
+ * symmetry: the default name is numbered off the current automations, so creating before the
+ * list has arrived would name every one of them "Automation 1".
+ *
+ * The flag is cleared BEFORE the await, not after it. `createAndOpen`'s identity changes on
+ * every poll (it closes over `data`), so this effect re-runs constantly; clearing first is what
+ * makes the second run a no-op instead of a second automation.
+ */
+ useEffect(() => {
+ if (!createRequest || !data) return;
+ setCreateRequest(false);
+ void createAndOpen();
+ }, [createRequest, data, createAndOpen]);
+
+ /**
+ * ⚠ THE REQUEST OUTLIVES THE FETCH, and it has to. The reader clicks a notification from
+ * another page, so this surface is mounting WITH AN EMPTY LIST — "select it if it is in the
+ * list" would drop every real click and keep only the one case where the reader was already
+ * here. So the request is held until `data` exists, and only then answered.
+ *
+ * An automation the reader can no longer open does NOTHING (the contract's own words): the
+ * request is cleared either way, so a stale id cannot sit here re-firing against every
+ * subsequent list.
+ */
useEffect(() => {
- if (!anyRunning) return undefined;
- const t = window.setInterval(() => void load(), 2500);
- return () => window.clearInterval(t);
- }, [anyRunning, load]);
+ if (!openRequest || !data) return;
+ const found = (data.automations || []).some((a) => a.id === openRequest.autoId);
+ if (found) {
+ select(openRequest.autoId, openRequest.stageId || "");
+ }
+ setOpenRequest(null);
+ }, [openRequest, data, select]);
const items = data?.automations || [];
const active = items.find((a) => a.id === activeId) || null;
@@ -160,10 +485,8 @@ export default function AutomationSurface() {
+ {/* ⭐ Wave-23 C7 — the document viewer, INSIDE this portal and therefore stacked above
+ this modal. `useOverlayLayer`'s stack is what makes that work: it registers on top, so
+ Escape closes the viewer and leaves the record open rather than dismissing both. */}
+ {jsonKey && (() => {
+ const field = fields.find((f) => f.key === jsonKey);
+ if (!field) return null;
+ return (
+ onNotesCommit(field.key, next)
+ : undefined
+ }
+ onClose={() => setJsonKey(null)}
+ />
+ );
+ })()}
);
}
diff --git a/web/src/customer-grid/cells.ts b/web/src/customer-grid/cells.ts
index af9fc5c0de354add6d9b190e7f0313b6f4a9e8ea..57ff946d01642dc54f64af30ad501c482e5e18cf 100644
--- a/web/src/customer-grid/cells.ts
+++ b/web/src/customer-grid/cells.ts
@@ -34,7 +34,7 @@ import type {
} from "@glideapps/glide-data-grid";
import { assetUrl } from "./catalogData";
import type { Field } from "./types";
-import { ratingMax } from "./types";
+import { isMachineOwned, ratingMax } from "./types";
import {
LP_BLUE_TEXT,
LP_BLUE_TINT,
@@ -44,6 +44,7 @@ import {
LP_RED_TINT,
LP_YELLOW_DEEP,
LP_YELLOW_TINT,
+ machineCellTheme,
STATUS_BUBBLE,
} from "./theme";
// ⚠ ALIASED: this module has its own `pickTint` (the bubble table above) and choiceColors has
@@ -51,7 +52,7 @@ import {
// distinguishable at the call site rather than one silently shadowing the other.
import { optionTint, pickTint as choicePickTint } from "./choiceColors";
import { automationState, avatarInitials, avatarSize, checkboxOn, dateTimeText, formulaIsBlank,
- formulaIsText, num, numberText, userCellPayload } from "./display";
+ formulaIsText, jsonPreview, num, numberText, userCellPayload } from "./display";
import type { AutomationState, CellValue, UserCellData } from "./display";
// Wave-7 (item W2): the pure display-string half moved to display.ts so the
@@ -66,6 +67,9 @@ export type { UserCellData } from "./display";
// gate can hold it); only the canvas tint table below needs this module.
export { automationDetail, automationState, automationStateLabel } from "./display";
export type { AutomationState } from "./display";
+// Wave-23 C7 — same arrangement again: the parse, the preview and the pretty-printer are pure
+// (`verify_grid_ux` drives them under node); only the canvas cell below needs this module.
+export { jsonParse, jsonPretty, jsonPreview, MAX_JSON_BYTES } from "./display";
/**
* Wave-18 C5-AUTOFIELD — the cell tint per automation state.
@@ -393,6 +397,37 @@ export function makeCell(
/** C-AVATAR — username → data URL, straight off `GridWorkspace.userAvatars`. Absent, or a
* username absent from it, paints the initials fallback. */
userAvatars?: Record
+): GridCell {
+ const cell = baseCell(field, v, editable, userAvatars);
+ return isMachineOwned(field) ? withMachineWash(cell) : cell;
+}
+
+/**
+ * ⭐ Wave-23 C8 (owner item 4 / R9) — the grey wash on a MACHINE-OWNED cell.
+ *
+ * A per-CELL override rather than a per-column one (`useGridColumns.columnTheme`), following the
+ * `AUTOMATION_TINT` precedent directly below: the column path returns one of three SHARED
+ * `COLUMN_TONE_THEME` references, so forking it per column would both break that sharing and put
+ * the wash on the HEADER, which R9 does not ask for — an involved column's filter/sort/group tone
+ * keeps winning its header.
+ *
+ * The PRECEDENCE (state tint over wash, bubble tint alongside it) is `theme.machineCellTheme` —
+ * it lives there because this module imports glide and therefore cannot be driven by a gate,
+ * and precedence is the half of this that can be silently wrong. Same split as `display.ts`.
+ *
+ * ⚠ Re-built rather than mutated: glide declares every cell key `readonly`, and `baseCell`
+ * returns a fresh literal on every branch anyway. The `as GridCell` is the union-spread widening,
+ * not a claim about the shape — the object is byte-identical to the branch's own plus one key.
+ */
+function withMachineWash(cell: GridCell): GridCell {
+ return { ...cell, themeOverride: machineCellTheme(cell.themeOverride) } as GridCell;
+}
+
+function baseCell(
+ field: Field,
+ v: CellValue,
+ editable: boolean,
+ userAvatars?: Record
): GridCell {
const ro = { allowOverlay: editable, readonly: !editable };
const blank = v == null || v === "";
@@ -508,6 +543,33 @@ export function makeCell(
allowOverlay: false,
};
}
+ case "json": {
+ // ⭐ Wave-23 C7 (owner item 5) — the compact preview; the DOCUMENT lives in the viewer.
+ //
+ // `allowOverlay: false` for the same reason `select` and `image` carry it: glide's text
+ // overlay is a one-line box, and a one-line box over a 32 KB document is an editor that
+ // can only damage the value — one keystroke in the wrong place and a well-formed payload
+ // becomes unparseable, saved. CustomerGrid opens the viewer on click instead (the same
+ // `onCellClicked` path the pickers use), and THAT is where the raw text is editable, with
+ // parse-on-save.
+ //
+ // ⚠ `readonly` is NOT set, and the difference matters: `allowOverlay:false` means "no
+ // inline editor", while `readonly` would tell glide the CELL cannot change — which would
+ // also block the paste path that legitimately writes a whole document into it.
+ //
+ // ⚠ `copyData` carries the RAW document, never the preview (the lesson the image cell
+ // booked in wave 19). Copy a json column and you get the payload; copy the preview and
+ // you get the sentence "{…} 5 keys", which is not data and cannot be pasted back.
+ const raw = String(v ?? "");
+ const text = jsonPreview(raw);
+ return {
+ kind: GridCellKind.Text,
+ data: text,
+ displayData: text,
+ copyData: raw,
+ allowOverlay: false,
+ };
+ }
case "rating": {
const max = ratingMax(field);
const n = Math.max(0, Math.min(max, Math.round(num(v))));
diff --git a/web/src/customer-grid/display.ts b/web/src/customer-grid/display.ts
index 73ac30ad1f238897ecf8187322af3086def66875..98b66d6f48c6a82aa5070d9f1be003e0c2268098 100644
--- a/web/src/customer-grid/display.ts
+++ b/web/src/customer-grid/display.ts
@@ -228,6 +228,92 @@ export function automationStateLabel(v: CellValue): string {
return s === "none" ? "Not run yet" : s[0].toUpperCase() + s.slice(1);
}
+/**
+ * ⭐ Wave-23 C7 (owner item 5) — THE JSON PREVIEW: what a 200px cell says about a document.
+ *
+ * `MAX_JSON_BYTES` is the contract's ceiling, mirrored from the host's write validation so the
+ * viewer can refuse a paste with the same number the server would (a client that lets you type
+ * 40 KB and then shows you a server refusal has wasted the edit).
+ *
+ * The four cases, and each one is a decision rather than a formatting preference:
+ * · **a single-pair object shows THE PAIR.** `{handle: "royalimports"}` is more useful than
+ * "1 key" and it is the shape most machine writes actually have. Past one pair the pairs
+ * stop fitting and the honest answer is the count.
+ * · **many keys / many items → `{…} N keys` / `[…] N items`.** Showing the FIRST pair of a
+ * twelve-key object would let a reader take one arbitrary value — whichever key the writer's
+ * serializer happened to emit first — for the cell's content.
+ * · **a bare scalar renders as itself.** `12`, `"ok"`, `true` and `null` are all valid JSON
+ * documents, and wrapping them in braces would describe a shape they do not have.
+ * · ⛔ **text that does not parse renders AS ITSELF, never as a shape.** The host validates on
+ * write, so this only happens to a value that predates the validation or arrived another
+ * way — and the one thing the preview must never do is claim a document is well-formed. The
+ * viewer's raw tab is where such a value gets read and repaired.
+ *
+ * Blank stays blank: an empty json cell is a document nobody has written, and `{}` is a document
+ * somebody wrote that is empty. Two different facts, two different cells.
+ */
+export const MAX_JSON_BYTES = 32 * 1024;
+
+/** Does this text parse as JSON? The ONE test, shared by the preview, the cell and the viewer's
+ * save — three copies of a try/catch is how they end up disagreeing about `""` or `NaN`. */
+export function jsonParse(v: CellValue): { ok: boolean; value?: unknown } {
+ const s = String(v ?? "").trim();
+ if (s === "") return { ok: false };
+ try {
+ return { ok: true, value: JSON.parse(s) as unknown };
+ } catch {
+ return { ok: false };
+ }
+}
+
+/** One compact line for a json cell. See the note above for why each case reads as it does. */
+export function jsonPreview(v: CellValue): string {
+ const raw = String(v ?? "").trim();
+ if (raw === "") return "";
+ const parsed = jsonParse(raw);
+ // ⚠ First line only, and clipped: an unparseable value is often a whole pasted response, and
+ // a cell is not where a 4 KB blob gets read. It is shown rather than hidden because the
+ // reader has to be able to see that the column holds something the app could not open.
+ if (!parsed.ok) return clip(raw.split("\n")[0], 60);
+ const value = parsed.value;
+ if (Array.isArray(value))
+ return value.length === 0 ? "[]" : `[…] ${value.length} item${value.length === 1 ? "" : "s"}`;
+ if (value !== null && typeof value === "object") {
+ const keys = Object.keys(value as Record);
+ if (keys.length === 0) return "{}";
+ if (keys.length === 1)
+ return clip(`{${keys[0]}: ${scalarText((value as Record)[keys[0]])}}`, 60);
+ return `{…} ${keys.length} keys`;
+ }
+ return clip(scalarText(value), 60);
+}
+
+/** A nested value, small enough to sit inside a one-pair preview. Objects and arrays collapse
+ * to their own marks rather than recursing — a preview that unfolds is not a preview. */
+function scalarText(v: unknown): string {
+ if (v === null) return "null";
+ if (Array.isArray(v)) return `[…] ${v.length}`;
+ if (typeof v === "object") return `{…} ${Object.keys(v as object).length}`;
+ return typeof v === "string" ? v : String(v);
+}
+
+/** ⚠ An ellipsis CHARACTER, not three dots: the grid's canvas measures text and three periods
+ * are three glyphs wide. Same mark the group-bar fitter uses. */
+function clip(s: string, n: number): string {
+ return s.length <= n ? s : s.slice(0, n - 1) + "…";
+}
+
+/**
+ * The document, indented for the viewer's pretty tab. Returns the RAW TEXT UNCHANGED when it
+ * does not parse — re-indenting is not repair, and handing a reader a "prettified" version of
+ * something the app could not read would hide the only thing they need to see.
+ */
+export function jsonPretty(v: CellValue): string {
+ const raw = String(v ?? "");
+ const parsed = jsonParse(raw);
+ return parsed.ok ? JSON.stringify(parsed.value, null, 2) : raw;
+}
+
export function formatDisplay(field: Field, v: CellValue): string {
switch (field.type) {
case "currency":
@@ -261,6 +347,12 @@ export function formatDisplay(field: Field, v: CellValue): string {
const n = num(v);
return n >= 1 ? `${Math.round(n)} of ${ratingMax(field)}` : "";
}
+ case "json":
+ // Wave-23 C7 — the SAME compact line the canvas cell paints. Explicit here rather than
+ // left to `default` for the reason the `formula` note above records: this function feeds
+ // ListView, KanbanView, the calendar, the record panel and all four EXPORT formats, and
+ // falling through would dump a whole 32 KB document into a CSV cell.
+ return jsonPreview(v);
case "automation":
// The machine-written line, verbatim. Explicit rather than left to the `default` branch
// below: `formula` fell through a default once and printed every text result as `0` for
diff --git a/web/src/customer-grid/iconShapes.ts b/web/src/customer-grid/iconShapes.ts
index 6fbe5f40b3001d8cc5d1ca13a2a1686f19ea2cdc..cae84f7e38b0246eda31f7e0e8a5165d135c6555 100644
--- a/web/src/customer-grid/iconShapes.ts
+++ b/web/src/customer-grid/iconShapes.ts
@@ -112,6 +112,17 @@ export const TYPE_SHAPES: Record = {
{ d: "M3.2 3.2v9.6h9.6" },
{ d: "M5 10.4l2.4-2.6 1.9 1.5 3.1-3.9" },
],
+ // Wave-23 C7 — TWO BRACES facing each other with a dot between them: the universal mark for
+ // "a structured document", and the one glyph in this table that draws its own SYNTAX rather
+ // than a picture of what the value means. Deliberately not a document page (nothing here owns
+ // that yet, but a page reads as a file/attachment, which a json cell is not) and not a tree
+ // of nodes (too fine to survive 16px). The centre dot is what keeps the two braces from
+ // reading as parentheses at small sizes.
+ json: [
+ { d: "M6.4 3.2c-1.5 0-1.5 3.4-1.5 3.4S4.8 8 3.4 8s1.5 1.4 1.5 1.4 0 3.4 1.5 3.4" },
+ { d: "M9.6 3.2c1.5 0 1.5 3.4 1.5 3.4s.1 1.4 1.5 1.4-1.5 1.4-1.5 1.4 0 3.4-1.5 3.4" },
+ { d: circle(8, 8, 0.85), fill: true },
+ ],
// Wave-19 R7 — a framed picture: the mount, a sun, and the hill line every photo glyph
// resolves to at 16px. Drawn on the same 16-unit grid as its neighbours.
image: [
@@ -168,6 +179,17 @@ export const MODE_SHAPES: Record = {
{ d: "M13.6 4.2H9a1.6 1.6 0 0 0-1 .4l0 8a1.6 1.6 0 0 1 1-.4h4.6z" },
{ d: "M3.9 6.4h2.3v2.8H3.9z" },
],
+ // Wave-23 C9 — a SHEET WITH A WRITING LINE: two filled answer bars and an empty rule beneath
+ // them. Every other mode here draws a way of ARRANGING records that already exist; this one
+ // has to read as a record being MADE, so it is the only mark whose bottom line is open.
+ // Deliberately not a clipboard (nothing else here has a frame with a tab) and not a pencil
+ // (an edit affordance means something else app-wide).
+ form: [
+ { d: "M3.4 2.8h9.2v10.4H3.4z" },
+ { d: "M5.6 5.6h4.8" },
+ { d: "M5.6 8h4.8" },
+ { d: "M5.6 10.6h2.6" },
+ ],
};
/**
@@ -330,6 +352,10 @@ export const MODE_LABELS: Record = {
map: "Map",
timeseries: "Time series",
catalog: "Catalog",
+ // Wave-23 C9 — the mode that COLLECTS records. "Form", the word the whole product uses for
+ // it (the public page, the share panel, the `form_submitted` trigger); a synonym here would
+ // be the one surface calling it something else.
+ form: "Form",
};
/**
@@ -388,6 +414,11 @@ export const MODE_TONE: Record = {
// analytical, yellow = board/date, red = spatial); a catalog arranges nothing — it is a
// published artifact. Giving it a colour would file it under a family it is not in.
catalog: "neutral",
+ // Wave-23 C9 — NEUTRAL, and for `catalog`'s reason rather than by elimination: the four tones
+ // name families of ways to ARRANGE records (blue tabular, green analytical, yellow
+ // board/date, red spatial). A form arranges nothing — it is a door records come in through —
+ // so giving it a colour would file it under a family it is not in.
+ form: "neutral",
};
/**
@@ -418,6 +449,10 @@ export const TYPE_LABELS: Record = {
metric: "Metric",
// Wave-19 R7 — the picture column.
image: "Image",
+ // Wave-23 C7 — the structured-document column. "JSON" rather than "Structured data": it is
+ // the word on the wire, in the viewer's raw tab and in every error the server can return, and
+ // a friendlier synonym would be the only place in the product using a different one.
+ json: "JSON",
status: "Lifecycle status (Odoo)", // never creatable; present so the map stays total
};
diff --git a/web/src/customer-grid/theme.ts b/web/src/customer-grid/theme.ts
index fb9d81b04a8c7751b4d87cc1b53989caad25190f..22eaa97d4d8fcafed17969633c4466e291e3c382 100644
--- a/web/src/customer-grid/theme.ts
+++ b/web/src/customer-grid/theme.ts
@@ -73,6 +73,30 @@ export const LP_PURPLE_DEEP = "#6B57A8"; // 5.17:1 on its own tint
*/
export const LP_VOID = "#F6F8FC";
+/**
+ * ⭐ Wave-23 C8 (owner item 4 / ruling R9) — **the MACHINE-OWNED column pair.**
+ *
+ * A sixth family, and neutral rather than a hue on purpose: the four C1 pastels each mean a
+ * STATE (green positive, red negative, yellow attention, blue interactive) and purple means
+ * GROUP. "A robot fills this column" is none of those — it is a property of the column's
+ * OWNERSHIP, so it takes the grey the palette had no name for. Deliberately NOT `LP_MUTED`
+ * (#6B7280): that is chrome ink, it is warmer, and re-using it would make "muted text" and
+ * "machine-owned" one token that two unrelated rules could then drag apart.
+ *
+ * `LP_MACHINE_TINT` the flat wash the DOM surfaces paint (`RecordDetail.css`'s
+ * `.cg-detail-field.is-machine .cg-detail-value`). It is exactly what the
+ * canvas wash below COMPOSITES TO over white, so the drawer's value slot
+ * and the grid cell are the same grey rather than two greys that were each
+ * picked to look right alone.
+ * `LP_MACHINE_DEEP` its ink — 5.35:1 on the tint, 6.32:1 on white (measured, not picked) —
+ * and the hue `MACHINE_CELL` derives the canvas wash from.
+ *
+ * Mirrors `--lp-machine-tint` / `--lp-machine-deep` in index.css; `verify_icons`' I7c parity
+ * diffs the two files, which is why both are plain hex strings here and neither is computed.
+ */
+export const LP_MACHINE_TINT = "#EBECEE";
+export const LP_MACHINE_DEEP = "#59606E";
+
export const LP_BLUE_DEEP = "#768FB6"; // 3.29:1 on white — rings, control borders
/* THE PRODUCT PRIMARY — the same #5B8FD9 the host's `.streamlit/config.toml`
paints on every primary button, so embed and standalone stop disagreeing
@@ -294,6 +318,57 @@ export const COLUMN_TONE_THEME: Record> = {
},
};
+/**
+ * ⭐ Wave-23 C8 — the wash a MACHINE-OWNED cell paints (`isMachineOwned`, types.ts).
+ *
+ * **ONE SHARED REFERENCE, and that is not a micro-optimisation.** glide has no theme-merge
+ * cache, so a fresh `{bgCell}` per cell costs a ~35-key spread on every cell of every frame —
+ * the same reasoning `STATUS_ROW_THEME` and `COLUMN_TONE_THEME` state, and it bites harder here
+ * because this override is returned for a whole COLUMN of cells rather than for the few rows
+ * that carry a status.
+ *
+ * **`rgba`, NOT a hex, and it is load-bearing** (the wave-15 R5 lesson, one surface down):
+ * `mergeAndRealizeTheme` alpha-BLENDS `bgCell` and hard-replaces every other key, so an opaque
+ * grey here would ERASE whatever it landed on — a colour-by row's status wash and the
+ * hover/active row wash both, leaving a machine column as a permanent gap through every tinted
+ * row. Blending means a hovered machine cell is darker than either alone, which is exactly the
+ * reading a person expects.
+ *
+ * ⚠ **0.12, chosen against a COLLISION rather than by eye.** `ROW_HIGHLIGHT_NEUTRAL` (the
+ * hover/active row) composites to ≈#F2F2F3 — a neutral grey wash already means something on
+ * this canvas. At 0.12 this composites to `LP_MACHINE_TINT` (#EBECEE), which is visibly the
+ * stronger of the two, so "a whole column is grey" and "the row under my pointer is grey" stay
+ * two different readings. Raising it is the one knob if a machine column reads as nothing; do
+ * not switch it to a hue (R9 is explicit that this is not a state).
+ */
+export const MACHINE_CELL: Partial = { bgCell: washOf(LP_MACHINE_DEEP, 0.12) };
+
+/**
+ * ⭐ Wave-23 C8 — a machine-owned cell's FINAL theme override, given whatever the cell already
+ * carried. **THE PRECEDENCE IS THE WHOLE FUNCTION**, so it lives here (node-reachable, under
+ * `verify_grid_ux`'s mutation harness) rather than inline in `cells.ts`, which imports glide and
+ * therefore cannot be driven by a gate at all.
+ *
+ * MERGED, with the CELL's own keys landing last — not "keep whichever exists", which was the
+ * first shape and is wrong in both directions:
+ * · an `automation` cell that HAS run carries `AUTOMATION_TINT[state]` — a green/red/yellow
+ * `bgCell` plus its ink. That is a STATE and it says something the wash does not, so it must
+ * win. (A cell that has never run carries no override at all — `AUTOMATION_TINT.none` is
+ * deliberately `undefined` — and takes the wash, which is the honest reading: machine-owned,
+ * nothing written yet.)
+ * · a machine-TAGGED `status`/`select`/`multiselect` cell — an automation-spawned column is an
+ * ordinary field TYPE wearing the tag — carries a BUBBLE tint (`bgBubble`/`textBubble`),
+ * which does not touch `bgCell` at all. "Keep whichever exists" would have silently cost
+ * every one of those columns its wash, and a column of pills is exactly where a reader is
+ * least able to tell who typed the value.
+ *
+ * The no-override case returns the SHARED `MACHINE_CELL` reference (see its note above); only
+ * the two merge cases allocate, and both already allocated a fresh override upstream.
+ */
+export function machineCellTheme(own: Partial | undefined): Partial {
+ return own ? { ...MACHINE_CELL, ...own } : MACHINE_CELL;
+}
+
/* wave17 GRID — item 2 / owner R5: **THE ALTERNATING ROW BANDS ARE DEAD.**
*
* `CONTROL_BAND_THEME` stood here: a faint wash on every other data row while any control was
diff --git a/web/src/customer-grid/types.ts b/web/src/customer-grid/types.ts
index 3c9fcbab93a40550c3e4cb40233c37e54b9f865c..667841f5b41b2ef1e059076f540e2eb76c77bda6 100644
--- a/web/src/customer-grid/types.ts
+++ b/web/src/customer-grid/types.ts
@@ -44,6 +44,14 @@ export type FieldType =
// menu (deliberately absent from CREATABLE_TYPES: the menu has no measure/window face yet —
// offering the type without its config would mint permanently blank columns).
| "metric"
+ // ⭐ Wave-23 C7 (owner item 5 / ruling R5) — `json` is a STRUCTURED DOCUMENT on a record: an
+ // API response, a webhook body, a scraped payload. The cell holds a STRING that must parse as
+ // JSON, ≤ 32 KB, validated host-side on write (refuse with a sentence, never truncate) — so
+ // the scalar `Row` contract (types.ts's Row, and `grid_events.py:1619`'s non-scalar refusal)
+ // is untouched. The grid shows a compact preview and the big viewer modal owns the document.
+ // It is NOT in `READONLY_CELL_TYPES`: the value is editable, just never through a 200px cell
+ // — the same "picked, not typed" reasoning `select` and `image` carry.
+ | "json"
// ⭐ Wave-19 R7 / C5 — `image` is a PICTURE on a record. The cell holds a STRING REFERENCE,
// never bytes (see `imageRef`): a SKU code, an `ed:` editorial slug, or a `rec:` upload. That
// is what lets Royal's 1,142 existing SKU masters appear with nothing uploaded, and it keeps
@@ -56,10 +64,26 @@ export type FieldSource = "odoo" | "overlay";
/** The types a user may create from the column menu. Odoo-sourced fields are not in this list —
* their type comes from the model, and `status` in particular is Odoo's lifecycle, not a
* user-defined set. */
+// ⚠ Wave-23 C7 — `json` is deliberately ABSENT from this list until SESSION A posts that
+// `aios_grid.CUSTOM_FIELD_TYPES` and `core.user_tables.UT_FIELD_TYPES` accept the name. It is
+// the field-kind twin of the CREATABLE_MODES hold (iconShapes.ts:344-364) and the failure is
+// worse here, because it is not a downgrade: `user_tables._clean_field` (:389) RETURNS NONE for
+// an unknown type, so a column created before the server knows the word simply does not exist
+// on the next read — created, named, configured, gone, with nothing anywhere going red. Every
+// OTHER json table below lands now, because reading a json field the server already sends is a
+// different question from offering to create one.
export const CREATABLE_TYPES: readonly FieldType[] = [
"text", "select", "multiselect", "user", "int", "currency", "pct", "date",
"checkbox", "phone", "email", "url", "rating", "created_time", "formula", "automation",
"image",
+ // ⭐ Wave-23 C7 (owner item 5) — ADDED AT THE CLOSE-OUT AUDIT, and its absence is the exact
+ // half-landing the fields contract exists to catch. `json` reached the `FieldType` union, the
+ // shape/label tables and the server's `CUSTOM_FIELD_TYPES`, but not this list — so the server
+ // would have accepted a json field that the client offered no way to create. The type would
+ // have shipped real, documented and unreachable.
+ // `verify_fields_contract` caught it by diffing the two lists; nothing else could have, because
+ // every individual file was internally consistent.
+ "json",
];
/**
@@ -237,8 +261,16 @@ export type FieldScope = "cohort" | "global";
// held OUT of CREATABLE_MODES until `aios_grid.DISPLAY_MODES` accepts the name, because
// `_clean_display` drops an unknown mode and offering it first would let a user build a whole
// catalogue that silently reverts to a grid on the next read with nothing going red.
+// ⭐ Wave-23 C9 (owner item 8): `form` joins the union — a view that COLLECTS records instead of
+// arranging them, published at a public `#/form/` link. Landed here (so the type, the
+// icon table, the label table and the tone table are total over it, and a stored `form` view
+// renders rather than blanking) and held OUT of `CREATABLE_MODES` until `aios_grid.DISPLAY_MODES`
+// accepts the name — the identical hold `timeseries` and `catalog` served, for the identical
+// reason: `_clean_display` DROPS an unknown mode, so offering it early would let somebody build
+// a whole form, share its link, and have the view silently revert to a grid on the next read.
export const DISPLAY_MODES = [
"grid", "chart", "dashboard", "list", "calendar", "kanban", "map", "timeseries", "catalog",
+ "form",
] as const;
export type DisplayMode = (typeof DISPLAY_MODES)[number];
@@ -946,6 +978,35 @@ export function mayEditField(field: Field, viewer: Viewer | undefined): boolean
return edit === "creator" && field.createdBy === viewer.name;
}
+/**
+ * ⭐ Wave-23 C8 (owner item 4 / ruling R9) — **is this column filled by a MACHINE?**
+ *
+ * Two clauses, and R9 is what makes it exactly two:
+ * · `field.automation` present — the TAG the engine stamps on everything it spawns or writes:
+ * the IG preset columns (`{flowId}`, automation_engine.py:757), the `stage_` board
+ * column and its cycles counter (`{flowId, stageField}`, :3600), and a user-configured
+ * `automation` column's own gear bag. Ordinary field TYPES, machine ownership, one marker.
+ * · `type ∈ {automation, metric}` — the two kinds that are machine-written BY DEFINITION even
+ * when no tag reached the client (an `automation` column created before the flow that fills
+ * it; a `metric`, which is computed server-side from the master series and never typed).
+ *
+ * ⛔ R9 DRAWS THE LINE HERE ON PURPOSE, and the two exclusions are the whole ruling: an
+ * ODOO-sourced column and a `formula`/`created_time` column **keep their current look**. All
+ * four are read-only, so "read-only" is NOT the predicate — a formula is written by the reader's
+ * own arithmetic and an Odoo column by the business, and greying either would say a robot owns
+ * a number the reader owns. This is why it is a separate function from `mayEditField` and not a
+ * branch of it.
+ *
+ * ⚠ **PAINT, NEVER PERMISSION.** `mayEditField` above stays the one edit wall (client courtesy;
+ * `grid_events.py:1608-1650` is the real one). A column can be machine-owned and editable
+ * (nothing is, today) or editable and machine-owned tomorrow, and this predicate must not be
+ * the reason a cell locks — two functions that agree today are exactly how one silently becomes
+ * the other's enforcement.
+ */
+export function isMachineOwned(field: Field): boolean {
+ return !!field.automation || field.type === "automation" || field.type === "metric";
+}
+
/**
* The NUMERIC and DATE families, for UI dispatch (operator lists, input kinds, sort-direction
* wording). ONE definition here; the ENGINE (useVisibleRows) keeps its own deliberately —
@@ -1081,16 +1142,32 @@ export interface Field {
* Wave-18 C5-AUTOFIELD — what this column's automation DOES. Absent = unconfigured (the cells
* render "Not configured" and no run ever targets the column). Written through the field's
* gear; validated host-side (`aios_grid._clean_automation`) exactly as `options`/`formula` are.
+ *
+ * ⭐ WIDENED wave-23 C8, because this interface described only ONE of the three writers and
+ * the other two have been shipping for a wave. `kind`/`source` are what the field GEAR writes
+ * (`_clean_automation`); the engine stamps two more bags that never carry either of them:
+ * · a SPAWNED preset column — `{flowId}` alone (`automation_engine.py:757`);
+ * · a STAGE column — `{flowId, stageField: true, …}` (`automation_engine.py:3600`).
+ * Nothing went red, because the wire arrives untyped: `field.automation.kind` on a stage
+ * column is a runtime `undefined` under a green `tsc`. C8 makes the TAG ITSELF load-bearing
+ * ("present ⇒ machine-owned", `isMachineOwned` above), so the shape it actually has is
+ * declared here rather than left to the one writer that happened to be typed first.
*/
automation?: {
- /** v1 vocabulary: 'instagram_profile'. Host-whitelisted; an unknown kind is dropped. */
- kind: string;
- /** where the run gets its subject. 'record_url_field' reads `urlField` off the row. */
- source: "record_url_field" | "self";
+ /** v1 vocabulary: 'instagram_profile'. Host-whitelisted; an unknown kind is dropped.
+ * Absent on engine-stamped bags (spawned presets, stage columns). */
+ kind?: string;
+ /** where the run gets its subject. 'record_url_field' reads `urlField` off the row.
+ * Absent on engine-stamped bags. */
+ source?: "record_url_field" | "self";
/** the row field holding the profile URL when source = 'record_url_field'. */
urlField?: string;
/** kind-specific knobs. Scalars only — the host clamps keys and value lengths. */
settings?: Record;
+ /** the automation definition that owns this column (engine-stamped; the machine marker). */
+ flowId?: string;
+ /** true on the `stage_` column an automation board walks its records through. */
+ stageField?: boolean;
};
/**
* Wave-22 C7 — a METRIC field's config bag, mirrored from `user_tables._clean_metric` (the
diff --git a/web/src/filter-kit/ops.ts b/web/src/filter-kit/ops.ts
index b693312330137ea7f1d3cbed583fc7a53d41bea9..221e19526b1d386068acd0e53958551a298a71e6 100644
--- a/web/src/filter-kit/ops.ts
+++ b/web/src/filter-kit/ops.ts
@@ -83,6 +83,20 @@ export function opsForType(t: FieldType): FilterOp[] {
// by the user's own choice list. `eq` reads "is exactly": the whole set is that one choice.
if (t === "multiselect")
return ["contains", "doesNotContain", "eq", "neq", "isEmpty", "isNotEmpty"];
+ // ⭐ Wave-23 C7 — `json` gets EXACTLY the two value-free ops, and the omissions are the
+ // decision. `contains` over a serialized document is a substring test against punctuation and
+ // key names: `contains "12"` would match a key `id_12`, a value 12, a timestamp and a
+ // fragment of 5120, and every one of those reads as a working filter. `eq` is worse — two
+ // documents that mean the same thing differ by key order and whitespace, so "is" would answer
+ // false for a record that plainly matches. "Has anything been captured here yet" is the
+ // question a json column can answer soundly, and it is the one people actually ask.
+ //
+ // ⚠ NO NEW OPERATOR ENTERS EITHER ENGINE. `isEmpty`/`isNotEmpty` already exist in
+ // `filter_sql.py` (:76, and :112's VALUE_FREE_OPS) and `filter_eval.py` (:260-262), and both
+ // are TYPE-INDEPENDENT — they test blankness before any type dispatch — so the lock-step is
+ // untouched and nothing on the server had to move for this line. (The contract's prose spells
+ // them `is_empty`/`is_not_empty`; the runtimes do not. The names come from the code.)
+ if (t === "json") return ["isNotEmpty", "isEmpty"];
// Wave-18 C5-AUTOFIELD — `automation` lands HERE, on the text ops, and that is the whole
// v1 answer. Its cell is one machine-written line (`ok · 2026-08-03 14:10 · 12 posts`), so
// `contains ok` and `contains error` are the two questions anyone actually asks of the
diff --git a/web/src/forms/FormPublic.tsx b/web/src/forms/FormPublic.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..8fab41faa82f62c1ac3f1b09f3455d2b1c4b80b4
--- /dev/null
+++ b/web/src/forms/FormPublic.tsx
@@ -0,0 +1,266 @@
+// ---------------------------------------------------------------------------
+// forms / FormPublic.tsx — ⭐ wave-23 item 8 (contract W23-C9).
+//
+// The page an ANONYMOUS person lands on at `#/form/`. E mounts it in the
+// Shell BEFORE the auth wall (wiring W23-W2); everything below assumes there is
+// no session, no workspace, no nav and no viewer.
+//
+// ⛔ IT IMPORTS NOTHING FROM `customer-grid/**`, AND THAT IS A REQUIREMENT, NOT
+// A PREFERENCE. The grid bundle drags glide-data-grid — hundreds of kilobytes
+// of canvas table — into whatever chunk touches it, and this page is the one
+// surface in the product that a stranger loads cold, once, probably on a phone,
+// probably on mobile data, to type four answers. One convenience import from
+// `types.ts` would put the whole spreadsheet engine on that wire. So the field
+// vocabulary below is DECLARED HERE as plain strings rather than imported: the
+// server sends `type` as a string and this page renders a control per string,
+// which is the same "no client union over a server vocabulary" rule the rest of
+// the wave follows, arriving here for a second reason.
+//
+// ⚠ Styling reuses `.lpf-*` rules in the D REGION of index.css — the shell's
+// stylesheet is one file and already loaded; a second stylesheet for one page
+// would be a second copy of the tokens.
+// ---------------------------------------------------------------------------
+
+import { useEffect, useState } from "react";
+
+/** One field, exactly as `routes_forms._public_form` builds it. Nothing here is
+ * optional-because-maybe: every key below is one the server always sends, and
+ * the three that are conditional say so. */
+interface FormField {
+ key: string;
+ label: string;
+ /** The server's own word. Deliberately `string`, not a union — an unknown
+ * type lands on the text input, which is the safe direction: a person can
+ * always type an answer, and a control this page has never heard of would
+ * otherwise render as nothing at all. */
+ type: string;
+ required: boolean;
+ options?: string[];
+ max?: number;
+}
+
+interface FormSpec {
+ title: string;
+ desc: string;
+ submitLabel: string;
+ fields: FormField[];
+ /** The honeypot's field name — planted, never shown. Server-named so the two
+ * halves cannot drift into a trap nobody checks. */
+ honeypot: string;
+}
+
+type Phase = "loading" | "ready" | "sent" | "gone";
+
+const LONG_TEXT_MIN = 0; // every text field gets a textarea when it is the only one
+
+export default function FormPublic({ token }: { token: string }) {
+ const [spec, setSpec] = useState(null);
+ const [phase, setPhase] = useState("loading");
+ const [values, setValues] = useState>({});
+ const [error, setError] = useState("");
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ let live = true;
+ setPhase("loading");
+ fetch(`/api/v1/forms/${encodeURIComponent(token)}`)
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
+ .then((data: FormSpec) => {
+ if (!live) return;
+ setSpec(data);
+ setPhase("ready");
+ })
+ // ⚠ ONE dead-end state for every failure, mirroring the server's uniform 403. Telling a
+ // visitor "this form is disabled" versus "no such form" would hand an enumerator the
+ // distinction the whole server-side refusal exists to withhold.
+ .catch(() => live && setPhase("gone"));
+ return () => {
+ live = false;
+ };
+ }, [token]);
+
+ const set = (key: string, v: string) =>
+ setValues((prev) => ({ ...prev, [key]: v }));
+
+ const submit = (event: React.FormEvent) => {
+ event.preventDefault();
+ if (busy) return;
+ setBusy(true);
+ setError("");
+ fetch(`/api/v1/forms/${encodeURIComponent(token)}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ values }),
+ })
+ .then(async (r) => {
+ if (r.ok) {
+ setPhase("sent");
+ return;
+ }
+ // The server's sentence, verbatim — it names the field by the label THIS PAGE showed,
+ // which is the only name the person has. A generic "something went wrong" here would
+ // discard the one useful thing the refusal carried.
+ const body = await r.json().catch(() => null);
+ setError(
+ String(body?.error?.message || "That could not be sent — check your answers and try again.")
+ );
+ })
+ .catch(() =>
+ setError("That could not be sent — check your connection and try again.")
+ )
+ .finally(() => setBusy(false));
+ };
+
+ if (phase === "loading")
+ return (
+
+
+
+ );
+
+ if (phase === "gone")
+ return (
+
+
+
This form is not available
+ {/* ONE line (DESIGN.md §4). There is nothing this person can do about it and no
+ detail we may safely give, so the page does not pretend otherwise. */}
+
The link may have expired or been turned off.
+
+
+ );
+
+ if (phase === "sent")
+ return (
+
+
+
Thank you
+
Your response has been recorded.
+
+
+
+ );
+
+ if (!spec) return null;
+
+ return (
+
+
+
+ );
+}
+
+/** One control per server type string. An unrecognised type falls through to text — see the
+ * `FormField.type` note: a stranger can always type an answer, and a blank where a control
+ * should be is the one failure they cannot work around. */
+function FieldControl({
+ field,
+ value,
+ onChange,
+}: {
+ field: FormField;
+ value: string;
+ onChange: (key: string, v: string) => void;
+}) {
+ const common = {
+ className: "lpf-input",
+ value,
+ required: field.required,
+ onChange: (e: { target: { value: string } }) => onChange(field.key, e.target.value),
+ };
+ switch (field.type) {
+ case "checkbox":
+ return (
+ onChange(field.key, e.target.checked ? "1" : "")}
+ />
+ );
+ case "select":
+ case "status":
+ return (
+
+ {/* An explicit empty option, always. A `` with no blank member has its first
+ choice pre-selected, so an untouched optional field silently submits a value the
+ person never picked. */}
+
+ {(field.options ?? []).map((o) => (
+
+ ))}
+
+ );
+ case "int":
+ case "currency":
+ case "pct":
+ case "rating":
+ return ;
+ case "date":
+ // ⚠ `type="date"` submits ISO (`YYYY-MM-DD`) whatever the browser DISPLAYS, which is
+ // exactly what the server's refuse-never-coerce date check demands. A text input here
+ // would send whatever the locale suggested and be refused on half the planet.
+ return ;
+ case "email":
+ return ;
+ case "phone":
+ return ;
+ case "url":
+ return ;
+ case "text":
+ return (
+
) : active ? (
- ) : nav.phase === "ready" || nav.phase === "error" ? (
- // ⚠ WAVE 17 ITEM 4 (R6) — THIS BRANCH IS ONLY REACHED HONESTLY ONCE
- // THE NAV HAS ANSWERED. `active` is resolved from `entries`, which is
- // empty while the nav is in flight, so every first login used to land
- // here and be told "This account has access to no surfaces yet" —
- // stating, as fact, the single worst thing this frame could say to a
- // new user, for as long as the round trip took. The sentence is
- // RIGHT for a nav that came back empty and WRONG for one that has not
- // come back, and those two were indistinguishable. They are not now.
- nav.phase === "ready" ? (
- // Wave 18 (C1-TENANT, R4): a READY nav with zero entries is a freshly provisioned
- // tenant (the server says so explicitly — a misconfigured account 403s and lands
- // on the error branch instead). The honest next step is the empty state's whole
- // content: create the first database.
-
-
Welcome
-
- {/* WAVE 19 R12 — the pointer follows the rename. A sentence naming a
- door by its old label is a wrong instruction, not a stale comment. */}
- This workspace has no databases yet. Create your first one below, or store a
- data source's keys under Settings → Keychains to connect one later.
-
- setNewDb({ name: "", busy: false, err: "" })}
- >
- Create your first database
-
-
- ) : (
-
-
Nothing to show
-
The navigation service did not answer. Reload to retry.
-
- )
+ ) : route === CONNECTORS_ROUTE ? (
+ // ⭐ WAVE 23 item 10 (R8, C11, wiring W23-W3) — the connectors directory.
+ //
+ // The one action the page cannot perform itself: a `manage: "keychain"` row opens
+ // Settings on the Keychains tab, and the Settings MODAL is the frame's. Same division
+ // as every other panel here — the page knows what it wants, the frame owns the door.
+ setSettings("keychains")} />
+ ) : nav.phase === "ready" ? (
+ // ⭐ WAVE 23 item 9 (R7, C10) — HOME, AND IT IS THE FALLBACK RATHER THAN A ROUTE MATCH.
+ //
+ // ⛔ WHY `!active` AND NOT `route === HOME_ROUTE`. Three states have to land here and
+ // only one of them is the literal hash: `#/home`, an EMPTY hash, and a route that no
+ // longer resolves (a deleted table, a stale bookmark, a hand-typed key). `resolveRoute`
+ // already funnels all three to "no entry" now that `defaultRoute` returns a chrome
+ // route, so testing the literal would have left the other two on the "Nothing to show"
+ // branch — a shell that looks broken as the reward for deleting a database, which is
+ // the exact failure `removeDatabase`'s own note warns about from the other side.
+ //
+ // ⚠ AND THIS BRANCH ABSORBED WAVE 18's TENANT HERO (R4), which used to live below.
+ // That hero said "Welcome — this workspace has no databases yet" plus one create
+ // button, on precisely the state Home now owns: a ready nav with zero entries. Leaving
+ // both reachable would put two welcome messages on one screen, which is the defect the
+ // rail's own note at the empty-nav line already documents. Home's four cards ARE the
+ // hero's create door, and its empty line carries the hero's sentence (HomePage's
+ // `home-empty`, which branches on `entries.length === 0` for exactly this reason).
+ // Booked as a dated amendment in the wave doc, since it moves an R4 surface.
+ setAssistOpen("templates")}
+ onNewDatabase={() => openNewDb("blank")}
+ onAutomated={openAutomated}
+ onConnectors={() => {
+ window.location.hash = `#/${CONNECTORS_ROUTE}`;
+ }}
+ // The same two-part move every click-through in this frame makes: the frame owns the
+ // hash, the surface owns which automation is selected. Route, then ASK.
+ onOpenAutomation={(autoId) => {
+ window.location.hash = "#/automation";
+ signal(AUTOMATION_OPEN_EVENT, { autoId });
+ }}
+ />
+ ) : nav.phase === "error" ? (
+ // ⚠ WAVE 17 ITEM 4 (R6) — THE ERROR AND THE EMPTY ARE DIFFERENT SENTENCES, and this
+ // branch is what keeps them apart. `active` resolves from `entries`, which is empty
+ // while the nav is IN FLIGHT, so every first login used to land on a pane stating the
+ // single worst thing this frame could say to a new user for as long as a round trip
+ // took. WAVE 23 keeps that separation and simplifies its shape: `ready` now goes to
+ // Home above (which welcomes an empty workspace properly), so this is only ever the
+ // nav that FAILED, and the nested ternary that used to sort the two is gone.
+
+
Nothing to show
+
The navigation service did not answer. Reload to retry.
+
) : (
// Still asking (`loading`, or the `idle` beat before the effect runs).
@@ -1485,16 +2087,28 @@ export default function Shell() {
e.stopPropagation()}
>
-
- AI assistant
-
-
- Under construction. The assistant is being trained on this workspace's data
- model and will open here in a later release.
-
+ {assistOpen === "templates" ? (
+ <>
+
Templates
+
+ Under construction. Curated template sets are being built and will open here in
+ a later release.
+
+ >
+ ) : (
+ <>
+
+ AI assistant
+
+
+ Under construction. The assistant is being trained on this workspace's data
+ model and will open here in a later release.
+
+ >
+ )}
setAssistOpen(false)}>
Close
@@ -1519,41 +2133,104 @@ export default function Shell() {
onClick={(e) => e.stopPropagation()}
>
New database
-
- A blank database in this workspace. Add fields and records once it opens —
- nothing here connects to a source.
-
+ {/* ⭐ WAVE 23 C10 — THE THREE-WAY CHOICE. Three one-line rows, not three paragraphs:
+ the explanation lives where the DECISION is made and stops there (R13). The
+ dialog's old sub-line ("a blank database… nothing here connects to a source")
+ said one of these three things as if it were the only one, so it moved onto the
+ row it actually describes. */}
+
+ setNewDb({ ...newDb, mode: "blank", err: "" })}
+ >
+ Blank
+
+ An empty database — add fields and records once it opens.
+
+ setNewDb(null)}
+ role="radio"
+ aria-checked={newDb.mode === "template"}
+ className={"shell-newdb-kind" + (newDb.mode === "template" ? " is-on" : "")}
disabled={newDb.busy}
+ onClick={() => setNewDb({ ...newDb, mode: "template", err: "" })}
>
- Cancel
+ From a template
+
+ Add a curated set of views to a database you already have.
+
+ {/* ⚠ NOT A RADIO — it LEAVES. Picking it hands off to the automation wizard
+ rather than selecting a state in this dialog, so it must not sit in the
+ radiogroup pretending to be a third selectable option (`role="radio"` with
+ `aria-checked` it can never wear is a control that lies to a screen reader). */}
void createDb()}
- disabled={newDb.busy || !newDb.name.trim()}
+ className="shell-newdb-kind"
+ disabled={newDb.busy}
+ onClick={openAutomated}
>
- {newDb.busy ? "Creating…" : "Create database"}
+
+ Automated
+
+
+
+ A database an automation creates and keeps up to date.
+
+ {newDb.mode === "template" ? (
+ // WAVE 23 C12 (wiring W23-W6) — the picker. It applies views to an EXISTING
+ // database rather than making one, which is what a platform-curated template is:
+ // a set of saved views, not a table (R10).
+ {
+ setNewDb(null);
+ window.location.hash = `#/${tableKey}`;
+ }}
+ />
+ ) : (
+ <>
+ setNewDb({ ...newDb, name: e.target.value })}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") void createDb();
+ if (e.key === "Escape" && !newDb.busy) setNewDb(null);
+ }}
+ />
+ {newDb.err ?
) : null}
@@ -1594,6 +2271,21 @@ export default function Shell() {
new CustomEvent("aios:view-open", { detail: { topic, viewId } })
);
}}
+ // ⭐ WAVE 23 C6 (wiring W23-W5) — the review notification's click-through.
+ //
+ // THE SAME TWO-PART MOVE the view click-through makes, and for the same reason: the
+ // frame owns the hash, the automation SURFACE owns which automation is selected
+ // (`activeId` is its own state, seeded from its own list — this frame cannot see it
+ // and must not learn to). So: route, then ASK.
+ //
+ // ⚠ THE ORDER IS LOAD-BEARING. The hash is set FIRST so the surface is mounting (or
+ // already mounted) when the event arrives; dispatching first would fire into a route
+ // that does not exist yet. `signal` is `apiContract`'s helper — the same channel the
+ // grid's own listeners use, rather than a second hand-rolled `dispatchEvent` here.
+ onOpenAutomation={(autoId, stageId) => {
+ window.location.hash = "#/automation";
+ signal(AUTOMATION_OPEN_EVENT, { autoId, ...(stageId ? { stageId } : {}) });
+ }}
/>
) : null}
diff --git a/web/src/shell/nav.ts b/web/src/shell/nav.ts
index e1ee7c27c5c501f20783e59583d3dafda3d959e2..d549f630b6ee1c07571dfa609ffa235c71ffb920 100644
--- a/web/src/shell/nav.ts
+++ b/web/src/shell/nav.ts
@@ -188,15 +188,70 @@ export function splitChrome(pages: NavPage[]): { main: NavPage[]; utility: NavPa
return { main, utility };
}
+/**
+ * WAVE 23 (C10 / R7) — one entry of the Home landing's recents.
+ *
+ * `at` is EPOCH SECONDS, and the type says so because the alternative bit this product once:
+ * a formatted naive-local stamp read by a browser in another zone (D-18). An integer instant
+ * has one reading everywhere, and the two things Home renders from it — "Opened N minutes ago"
+ * and the Today / Past 7 days / Older bucket — are both statements about THE READER'S OWN
+ * CLOCK, which is the one case where using it is correct rather than forbidden (contrast
+ * `alertsModel.stampText`, which must NOT touch a clock because it re-states a server event).
+ */
+export interface Recent {
+ key: string;
+ at: number;
+}
+
/** `empty` (wave 18): the SERVER's reason for an empty page list. `"no_databases"` means a
* freshly provisioned tenant with no modules and no databases YET — a legitimate starting
* state, not a broken account. Absent means "no reason given", which the shell reads as the
* misconfigured-account case it always did. Distinguishing them is what stops the rail saying
* "no surfaces are available" beside a hero saying "welcome, create your first database". */
export type NavResult =
- | { ok: true; pages: NavPage[]; empty?: string }
+ | { ok: true; pages: NavPage[]; recents: Recent[]; empty?: string }
| { ok: false; status: number };
+/**
+ * `{recents:[…]}` → the list, fail-closed. An entry with no key or an unreadable stamp is
+ * DROPPED rather than rendered at the epoch, which would file it under "Older" for ever and
+ * put a tile on Home for something nobody opened.
+ */
+export function parseRecents(body: unknown): Recent[] {
+ const raw = (body as { recents?: unknown } | null)?.recents;
+ if (!Array.isArray(raw)) return [];
+ const out: Recent[] = [];
+ for (const item of raw) {
+ if (!item || typeof item !== "object") continue;
+ const r = item as Record;
+ const key = typeof r.key === "string" ? r.key.trim() : "";
+ const at = typeof r.at === "number" && isFinite(r.at) ? Math.floor(r.at) : 0;
+ if (!key || at <= 0) continue;
+ out.push({ key, at });
+ }
+ return out;
+}
+
+/**
+ * WAVE 23 (C10) — stamp a page as opened. FIRE AND FORGET, by design.
+ *
+ * ⛔ IT RETURNS `void` AND SWALLOWS EVERYTHING. A recents stamp is the least important write in
+ * the product: it decorates a landing page. Nothing the user is doing may wait on it, and no
+ * failure of it may reach a screen — a toast saying "we could not record that you opened this
+ * table" is noise about a feature nobody asked for, printed over the table they successfully
+ * opened. The server answers 503 honestly when the store is down; this end simply does not
+ * care, which is the only correct posture for telemetry-shaped state.
+ */
+export function postOpened(key: string): void {
+ if (!key) return;
+ void fetch(`${API_V1}/nav/opened`, {
+ method: "POST",
+ credentials: CREDENTIALS,
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ key }),
+ }).catch(() => {});
+}
+
/**
* X2 `GET /api/v1/nav`. `status` rides the failure so the caller can tell the
* two apart that must not be conflated: **401 means the session is gone** (drop
@@ -210,7 +265,12 @@ export async function fetchNav(): Promise {
if (!res.ok) return { ok: false, status: res.status };
const body = await res.json();
const empty = typeof body?.empty === "string" ? body.empty : undefined;
- return { ok: true, pages: parsePages(body), ...(empty ? { empty } : {}) };
+ return {
+ ok: true,
+ pages: parsePages(body),
+ recents: parseRecents(body),
+ ...(empty ? { empty } : {}),
+ };
} catch {
return { ok: false, status: 0 };
}
@@ -702,10 +762,62 @@ export function shapeNav(pages: NavPage[], appBase: string): NavEntry[] {
* can read, not in whatever the registry happens to order first.
*/
// (`cohort` left the list with its NATIVE_KEYS exit, wave 16 — a landing must be drawable.)
-export const LANDING_PREFERENCE: readonly string[] = ["customer_data"];
+//
+// ⭐ WAVE 23 (contract C10, ruling R7) — THE LANDING IS NOW `#/home`.
+//
+// ⛔ CHROME ROUTES ARE NOT GRANTED PAGES, AND THE :1039 LAW SURVIVES INTACT. This shell's
+// oldest rule is that the nav is server-filtered and an undeclared surface is denied — which is
+// why Alerts is a PANEL and not a route. Home and Connectors are routes, and they do not
+// violate that rule for one reason that has to be true of every future member of this set:
+//
+// A CHROME ROUTE RENDERS NOTHING THE SERVER DID NOT ALREADY GRANT.
+//
+// Home shows the entries `/nav` returned (its recents are RESOLVED against those entries and a
+// key absent from them is dropped, `homeModel.groupRecents`) plus create affordances that were
+// already in the rail. Connectors renders a SERVER-COMPOSED directory (`GET /connectors/
+// directory`, session-gated) — it is a window onto a payload, not a surface with its own data.
+// Neither can show a database, a module or a connector this session may not see; adding a route
+// that could would be the hard-coded surface the frame refuses to have.
+export const HOME_ROUTE = "home";
+export const CONNECTORS_ROUTE = "connectors";
+export const CHROME_ROUTES: ReadonlySet = new Set([HOME_ROUTE, CONNECTORS_ROUTE]);
+
+export const LANDING_PREFERENCE: readonly string[] = [HOME_ROUTE];
+/**
+ * The surface the shell lands on.
+ *
+ * ⚠ THE THREE LANDING SITES MOVE TOGETHER OR LOGINS STRAND (C10's own warning): this function,
+ * `LANDING_PREFERENCE` above, and the post-login redirect in `Shell.tsx`. Half a move leaves a
+ * signed-in user on a hash nothing renders.
+ *
+ * A chrome route needs no entry to be reachable — that is what makes it chrome — so the loop
+ * below returns it without consulting `entries`, and the old preference chain survives beneath
+ * it for the day a granted page becomes the landing again. `entries` stays a parameter for the
+ * same reason: the fallback is still a real answer about a real payload.
+ */
export function defaultRoute(entries: NavEntry[]): string {
- for (const key of LANDING_PREFERENCE) {
+ return firstDestination(entries, LANDING_PREFERENCE);
+}
+
+/**
+ * The landing rule itself, over an arbitrary preference list.
+ *
+ * ⚠ EXTRACTED (wave 23) SO THE FALLBACK CHAIN STAYS UNDER TEST. Before C10 the chain WAS
+ * `defaultRoute`, so `shell.test.ts` asserted it by calling that. With `home` at the head of the
+ * preference the function now returns on its first line, and the whole "preferred native entry →
+ * any native entry → any destination" ladder became unreachable from the outside — three checks
+ * would have had to be deleted rather than retargeted, which is how a gate quietly stops
+ * asserting the thing it was written for ([[gate-can-report-green-on-nothing]]). It is one
+ * function called two ways instead.
+ */
+export function firstDestination(
+ entries: NavEntry[],
+ preference: readonly string[]
+): string {
+ for (const key of preference) {
+ // A chrome route needs no entry to be reachable — that is what makes it chrome.
+ if (CHROME_ROUTES.has(key)) return key;
const hit = entries.find((e) => e.key === key && e.kind === "native");
if (hit) return hit.key;
}
@@ -725,6 +837,13 @@ export function defaultRoute(entries: NavEntry[]): string {
* member"). An unknown route falls to the default. Both fall back rather than
* erroring, because a URL is something a person can type or a bookmark can
* outlive.
+ *
+ * ⭐ WAVE 23 (C10): the fallback is now `#/home`, which is CHROME and therefore matches no
+ * entry — so this returns `undefined` for an unknown route, and the frame reads "no entry" as
+ * "render Home". One behaviour change, stated plainly: `#/deleted_table` used to open the
+ * Customer grid and now opens Home. That is the better answer (the reader asked for something
+ * that is gone; the landing is where you choose again) and it is the SAME answer an empty hash
+ * gets — which is what "Home is the default" has to mean in order to be true.
*/
export function resolveRoute(entries: NavEntry[], route: string): NavEntry | undefined {
const i = entries.findIndex((e) => e.key === route);
diff --git a/web/src/viz/seriesData.ts b/web/src/viz/seriesData.ts
index 88db80aa28f0282ea7931cbf2fd8eba2ec5dc310..4312041b94a706a6a18facc694f8031111914f81 100644
--- a/web/src/viz/seriesData.ts
+++ b/web/src/viz/seriesData.ts
@@ -40,6 +40,11 @@ export const VIZ_FIELD_TYPES: ReadonlySet = new Set([
// report the column as `text`, and the one thing a viz field type decides is what the surface
// is allowed to claim about the column.
"image",
+ // Wave 23 C7 — `json`. THE BATCH LINE the union's own comment names: a `Set` is not a
+ // `Record`, so the compiler stays green when this goes stale and `asFields` silently reports
+ // a json column as `text`. Same reasoning as `image` — the type is categorical either way,
+ // and what listing it buys is that the surface stops mis-naming the column.
+ "json",
]);
/**
diff --git a/web/src/viz/types.ts b/web/src/viz/types.ts
index a475fc1c480f55052a16ef96c98c7bd426d1d688..3fbc4dc31696849b0078956b8fb600379367cda7 100644
--- a/web/src/viz/types.ts
+++ b/web/src/viz/types.ts
@@ -47,7 +47,15 @@ export type FieldType =
// picture (it is a reference string, so `isNumericFieldType` leaves it categorical and the
// shared formatter prints the ref) — the vocabulary has to know the word regardless, or the
// grid cannot hand its own fields to `` at all.
- | "image";
+ | "image"
+ // Wave-23 C7 — `json`, and it is COERCED TO TEXT for charting by construction rather than by
+ // a branch: `isNumericFieldType` does not name it, so the engine groups it as a category and
+ // the shared formatter prints the stored string. Grouping a table by a whole document is a
+ // question nobody asks, but the vocabulary has to know the word or the grid cannot hand its
+ // own fields to DashboardView at all — which is the alarm two rules below going off. KEEP
+ // THIS COMMENT FREE OF THE STATEMENT-TERMINATOR CHARACTER, exactly as the metric note above
+ // says: verify_ui parses this union up to the first one it meets
+ | "json";
export type FieldSource = "odoo" | "overlay";