fsanyoto commited on
Commit
31e8186
Β·
verified Β·
1 Parent(s): 6ec9d3b

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
api/automation_engine.py CHANGED
@@ -800,7 +800,7 @@ def retire_automation_stage_fields(rt):
800
  for key in (row or {}):
801
  text = str(key)
802
  if text.startswith("stage_auto_"):
803
- stage_keys.add(text.removesuffix("_at").removesuffix(CYCLES_SUFFIX))
804
  stage_keys.discard("")
805
  if not stage_keys:
806
  return {"tables": 0, "fields": 0, "cells": 0}
@@ -829,7 +829,7 @@ def retire_automation_stage_fields(rt):
829
  if not isinstance(row, dict):
830
  continue
831
  for stage_key in stage_keys:
832
- for key in (stage_key, stage_key + "_at", stage_key + CYCLES_SUFFIX):
833
  if key in row:
834
  row.pop(key, None)
835
  changed["cells"] += 1
@@ -1212,8 +1212,7 @@ def clean_config(kind, raw, previous=None):
1212
  def flag(name):
1213
  return bool(raw[name]) if name in raw else bool(prev.get(name))
1214
  if kind == "plain":
1215
- # ⭐ WAVE 24 / R6 β€” a plain automation has no machine step, so it has almost no config:
1216
- # the database its records walk, and the board's lane router.
1217
  #
1218
  # ⚠ THE TARGET IS OPTIONAL ON PURPOSE. An automation triggered by `record_updated` on
1219
  # `ut_foo` already knows its table from the trigger β€” `_flow_table` resolves target-else-
@@ -1224,12 +1223,8 @@ def clean_config(kind, raw, previous=None):
1224
  target = _s(raw.get("targetTable"), 60).strip()
1225
  if target and not target.startswith(UT_PREFIX):
1226
  target = UT_PREFIX + target
1227
- lanes, lerr = clean_lanes(raw.get("lanes") if "lanes" in raw else prev.get("lanes"))
1228
- if lerr:
1229
- return None, lerr
1230
- return {"targetTable": target,
1231
- "targetLabel": _s(raw.get("targetLabel"), 60).strip(),
1232
- "lanes": lanes}, None
1233
  if kind == "scrape_db":
1234
  url = _s(raw.get("url"), 2000).strip()
1235
  if not url:
@@ -1252,16 +1247,12 @@ def clean_config(kind, raw, previous=None):
1252
  target = _s(raw.get("targetTable"), 60).strip()
1253
  if target and not target.startswith(UT_PREFIX):
1254
  target = UT_PREFIX + target
1255
- lanes, lerr = clean_lanes(raw.get("lanes") if "lanes" in raw else prev.get("lanes"))
1256
- if lerr:
1257
- return None, lerr
1258
- return {"url": url, "extract": extract,
1259
  "tableIndex": max(0, min(int(raw.get("tableIndex") or 0), 50)),
1260
  "fieldMap": fmap, "keyField": key_field,
1261
  "targetTable": target,
1262
- "dryRun": flag("dryRun"),
1263
- "lanes": lanes,
1264
- "targetLabel": _s(raw.get("targetLabel"), 60).strip() or "Scraped table"}, None
1265
  if kind == "field_instagram":
1266
  table = _s(raw.get("targetTable"), 60).strip()
1267
  if not table.startswith(UT_PREFIX):
@@ -1276,9 +1267,6 @@ def clean_config(kind, raw, previous=None):
1276
  tier = clean_tier(raw["tier"]) if "tier" in raw else ""
1277
  if not tier and "tier" not in raw:
1278
  tier = clean_tier(prev.get("tier"))
1279
- lanes, lerr = clean_lanes(raw.get("lanes") if "lanes" in raw else prev.get("lanes"))
1280
- if lerr:
1281
- return None, lerr
1282
  # C5: absent β‡’ keep whatever is stored, like every other switch in this branch β€” a panel
1283
  # that does not edit the post count must not reset it to the default on Save. And an
1284
  # INHERITED value is clamped rather than refused; see `clean_max_posts`.
@@ -1299,8 +1287,7 @@ def clean_config(kind, raw, previous=None):
1299
  # independent opt-in and never follows the per-post switch automatically.
1300
  "commentMetrics": flag("commentMetrics"),
1301
  "dryRun": flag("dryRun"),
1302
- "lanes": lanes,
1303
- "maxPosts": max_posts}, None
1304
  if kind == "discover_instagram":
1305
  limit = int(raw.get("recordsLimit") or 0)
1306
  if limit < 1:
@@ -1316,12 +1303,7 @@ def clean_config(kind, raw, previous=None):
1316
  preds, perr = clean_predicates(raw.get("predicates"), join)
1317
  if perr:
1318
  return None, perr
1319
- if raw.get("lanes") if "lanes" in raw else prev.get("lanes"):
1320
- # R6: discovery's one path is the human gate β€” Review, then Tracked. A lane after
1321
- # the gate would be a second router over a set a person is already routing.
1322
- return None, ("a discovery automation routes through Review β€” its path is the "
1323
- "human gate; lanes belong on scrape and column automations")
1324
- target = _s(raw.get("targetTable"), 60).strip() or DISCOVER_TABLE
1325
  if not target.startswith(UT_PREFIX):
1326
  target = UT_PREFIX + target
1327
  seed, serr = clean_seed(raw.get("seed") if "seed" in raw else prev.get("seed"))
@@ -1398,48 +1380,14 @@ def clean_schedule(raw, previous=None):
1398
  # β›” `terminal` IS THE DEFAULT and every existing automation gets it, because a stored definition
1399
  # that predates this field must not start moving records on its own the day the code ships. A
1400
  # loop is a thing somebody turns on.
1401
- ENDING_MODES = ("terminal", "auto_reset", "manual_reset", "timed_reset")
1402
- MAX_RESET_HOURS = 720 # 30 days; past that "it resets eventually" is a lie
1403
- #: The per-record cycle counter's cell suffix, beside `stage_<id>` and `stage_<id>_at`.
1404
- CYCLES_SUFFIX = "_cycles"
1405
-
1406
-
1407
- def cycles_field_key(auto_id):
1408
- return stage_field_key(auto_id) + CYCLES_SUFFIX
1409
-
1410
-
1411
- def clean_ending(raw, previous=None):
1412
- """Validate `{mode, hours?}`. Returns `(ending, error)`."""
1413
- raw = raw if isinstance(raw, dict) else {}
1414
- prev = previous if isinstance(previous, dict) else {}
1415
- mode = _s(raw.get("mode") or prev.get("mode"), 20).strip() or "terminal"
1416
- if mode not in ENDING_MODES:
1417
- return None, f"{mode!r} is not one of: " + ", ".join(ENDING_MODES)
1418
- out = {"mode": mode}
1419
- if mode == "timed_reset":
1420
- try:
1421
- hours = int(raw.get("hours") if raw.get("hours") is not None else prev.get("hours")
1422
- or 24)
1423
- except (TypeError, ValueError):
1424
- return None, "the reset delay must be a whole number of hours"
1425
- if hours < 1 or hours > MAX_RESET_HOURS:
1426
- return None, f"the reset delay is between 1 and {MAX_RESET_HOURS} hours"
1427
- out["hours"] = hours
1428
- return out, None
1429
-
1430
-
1431
- def clean_flow(raw, previous=None):
1432
- """Validate `{actions, ending}` β€” the builder's half of a definition. `(flow, error)`."""
1433
  raw = raw if isinstance(raw, dict) else {}
1434
  prev = previous if isinstance(previous, dict) else {}
1435
  actions, err = clean_actions(raw.get("actions") if "actions" in raw else prev.get("actions"))
1436
  if err:
1437
  return None, err
1438
- ending, err = clean_ending(raw.get("ending") if "ending" in raw else prev.get("ending"),
1439
- prev.get("ending"))
1440
- if err:
1441
- return None, err
1442
- return {"actions": actions, "ending": ending}, None
1443
 
1444
 
1445
  #: AMENDMENT A1 β€” what the `ig_profile_match` kind-flip seeds as `recordsLimit` when the
@@ -1726,16 +1674,10 @@ def clean_definition(raw, previous=None, username=""):
1726
  "id": _s(prev.get("id") or raw.get("id"), 40),
1727
  "name": name, "kind": kind, "config": config, "schedule": schedule,
1728
  "trigger": trigger,
1729
- # WAVE 23 Β· C4/C5 β€” the BUILDER's half: the ordered actions a record walks and what
1730
- # happens when it reaches the end. Absent on every definition written before this wave,
1731
- # which is exactly why `clean_flow` defaults it to "no actions, terminal ending": the
1732
- # code shipping must not put existing automations into a loop.
1733
- "flow": flow,
1734
- "status": prev.get("status") or {"state": "idle", "lastRunAt": "", "lastSummary": ""},
1735
- "runs": list(prev.get("runs") or [])[:MAX_RUNS],
1736
- # C3-A2(5): the review-decision audit survives a Save the way `state` does β€” an
1737
- # ordinary patch must not amnesty every recorded approve/decline.
1738
- "reviews": list(prev.get("reviews") or [])[:100],
1739
  # ⚠ ENGINE-OWNED CONTINUATION STATE, and it is NOT config. A discovery snapshot takes ~20
1740
  # minutes to build, so a run persists its id here and the NEXT run collects it. It is
1741
  # carried through `patch` untouched because a user pressing Save must not silently orphan
@@ -1767,11 +1709,111 @@ def set_state(rt, auto_id, patch_state):
1767
  rt.update(STORE_KEY, _up, flush="sync")
1768
 
1769
 
1770
- def all_definitions(rt):
1771
- try:
1772
- return dict(rt.get(STORE_KEY) or {})
1773
- except Exception:
1774
- return {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1775
 
1776
 
1777
  def _new_id(existing):
@@ -6438,18 +6480,7 @@ def toggle_node(rt, auto_id, node_id):
6438
  # `auto` = the engine advances. Today reviewβ‡’strict and everything elseβ‡’auto BY DERIVATION β€”
6439
  # the vocabulary is on the wire so a later wave can flip a stage without a client change.
6440
 
6441
- STAGE_FIELD_PREFIX = "stage_"
6442
- STAGE_KINDS = ("trigger", "action", "review", "branch")
6443
- POSTURES = ("auto", "strict")
6444
- #: One board answer carries at most this many cards PER STAGE; `counts` always carries the
6445
- #: true totals and `truncated` names the stages that overflowed β€” a cap nobody can see is the
6446
- #: silent-[:N] defect ([[no-unverifiable-aggregates]]), so this one is disclosed on the wire.
6447
- BOARD_CARD_CAP = 200
6448
-
6449
- #: R5 lanes β€” the per-record IF-routing vocabulary. Enumerated HERE (and shipped on the wire)
6450
- #: so the client can never grow its own union of operators (the wave-9 silent-drop class).
6451
- MAX_LANES = 6
6452
- LANE_OPS = ("=", "!=", ">", ">=", "<", "<=", "includes", "not_includes",
6453
  "is_empty", "is_not_empty")
6454
  LANE_NULLARY_OPS = ("is_empty", "is_not_empty")
6455
 
@@ -6548,56 +6579,7 @@ def cond_fields(cond):
6548
  # ⚠ `tracked` / `declined` STAY RESERVED even though R6 deleted the stages that used them: the
6549
  # labels still sit in boards stored before this wave, and a user lane named "Tracked" beside a
6550
  # legacy stamped cell would read as the same lane while behaving as a different one.
6551
- _RESERVED_STAGE_LABELS = frozenset({"review", "tracked", "declined", "write", "profile set",
6552
- "schedule", "stage"})
6553
-
6554
-
6555
- def stage_field_key(auto_id):
6556
- """The stage field's key on the target database. Derived, never chosen β€” two automations on
6557
- one table must mint two distinct fields, and a rename must never move the key."""
6558
- return STAGE_FIELD_PREFIX + re.sub(r"[^a-z0-9_]+", "_", str(auto_id or "").lower())[:40]
6559
-
6560
-
6561
- def clean_lanes(raw):
6562
- """Validate the R5 lane list. Returns `(lanes, error)` β€” refuses, never coerces
6563
- (the `clean_predicates` discipline: a condition we cannot answer is refused at WRITE time
6564
- with the reason named, because dropping or bending it would route records nobody asked to
6565
- route)."""
6566
- if raw in (None, ""):
6567
- return [], None
6568
- if not isinstance(raw, list):
6569
- return None, "lanes must be a list"
6570
- if len(raw) > MAX_LANES:
6571
- return None, f"an automation may have at most {MAX_LANES} lanes"
6572
- out, seen_ids, defaults = [], set(), 0
6573
- for entry in raw:
6574
- if not isinstance(entry, dict):
6575
- return None, "each lane must be an object with a label and an optional condition"
6576
- label = " ".join(_s(entry.get("label"), 60).split())
6577
- if not label:
6578
- return None, "every lane needs a label"
6579
- if label.strip().lower() in _RESERVED_STAGE_LABELS:
6580
- return None, (f"{label!r} is the name of a fixed stage β€” pick another label for "
6581
- f"the lane")
6582
- lid = "lane_" + (re.sub(r"[^a-z0-9]+", "_", label.lower()).strip("_") or "x")[:40]
6583
- base, n = lid, 2
6584
- while lid in seen_ids:
6585
- lid = f"{base}_{n}"
6586
- n += 1
6587
- seen_ids.add(lid)
6588
- cond, cerr = clean_cond(entry.get("when"), where=repr(label))
6589
- if cerr:
6590
- return None, cerr
6591
- if cond is None:
6592
- defaults += 1
6593
- if defaults > 1:
6594
- return None, ("only one lane may have no condition β€” it is the catch-all, "
6595
- "and two catch-alls would race for every record")
6596
- out.append({"id": lid, "label": label, "when": cond})
6597
- return out, None
6598
-
6599
-
6600
- def _lane_num(v):
6601
  try:
6602
  return float(str(v).replace(",", ""))
6603
  except (TypeError, ValueError):
@@ -6645,20 +6627,7 @@ def lane_match(cond, row):
6645
  return same if op == "=" else (not same) if op == "!=" else False
6646
 
6647
 
6648
- def route_record(lanes, row):
6649
- """The winning lane's LABEL for one record, or '' when nothing matches.
6650
-
6651
- First declared match wins β€” declaration order is the priority order, the same rule every
6652
- rule engine the owner has used applies, and the catch-all (condition None) is simply the
6653
- first lane nothing above it beat.
6654
- """
6655
- for lane in lanes or []:
6656
- if lane_match(lane.get("when"), row):
6657
- return lane["label"]
6658
- return ""
6659
-
6660
-
6661
- # ─────────────────────────────────────────────────────────────────────────────────────────────
6662
  # WAVE 23 Β· C4 β€” ACTIONS (owner ruling R3). The half of the Airtable builder that DOES things.
6663
  #
6664
  # `flow.actions` is an ordered list walked per RECORD, after the flow's machine steps have run.
@@ -6672,13 +6641,9 @@ def route_record(lanes, row):
6672
  # Run script / Generate with AI faded with a reason instead of omitting them β€” the same honesty
6673
  # rule the trigger list follows, and the same enforcement: `clean_actions` REFUSES an unready
6674
  # kind with a sentence, so the faded state is a wall and not a styling choice.
6675
- MAX_ACTIONS = 20 # per automation, counting nested ones
6676
- MAX_GROUP_DEPTH = 2 # a group inside a group inside a group is a flowchart, not a flow
6677
- #: ⭐ WAVE 24 Β· C-FORK β€” branches per If / then. The SAME number as `MAX_LANES` and deliberately
6678
- #: so: a lane and a branch are the same act (route this record by condition), on two surfaces,
6679
- #: and two different ceilings for one act would be a difference a person has to learn for no
6680
- #: reason. Named separately so they can diverge on evidence rather than by accident.
6681
- MAX_BRANCHES = MAX_LANES
6682
  MAX_ACTION_VALUES = 20 # cells one update/create action may write
6683
  FIND_LIMIT_MAX = 100
6684
  #: ⭐ WAVE 24 Β· C-ACT β€” THE MENU'S GROUP ORDER IS THE SERVER'S. The client sorts by `groupOrder`
@@ -6739,11 +6704,9 @@ ACTION_CATALOG = [
6739
  "ready": False, "detail": "Run the same actions on every item in a list"},
6740
  {"kind": "run_script", "label": "Run script", "group": "Advanced logic", "ready": False,
6741
  "detail": "Not built β€” a sandbox is its own decision"},
6742
- {"kind": "generate_ai", "label": "Generate with AI", "group": "Advanced logic",
6743
- "ready": False, "detail": "Review stages can already be decided by AI"},
6744
- ]
6745
- REVIEW_DECIDERS = ("user", "ai")
6746
- MAX_AI_PROMPT = 600
6747
 
6748
 
6749
  def action_catalog():
@@ -7019,28 +6982,7 @@ def _clean_action_config(kind, cfg, depth, seen, count):
7019
  if limit < 1 or limit > FIND_LIMIT_MAX:
7020
  return None, f"the find records limit is between 1 and {FIND_LIMIT_MAX}"
7021
  return {"table": table, "cond": cond, "limit": limit}, None
7022
- if kind == "review":
7023
- by = _s(cfg.get("decidedBy"), 10).strip() or "user"
7024
- if by not in REVIEW_DECIDERS:
7025
- return None, f"a review is decided by one of: {', '.join(REVIEW_DECIDERS)}"
7026
- label = " ".join(_s(cfg.get("label"), 60).split()) or "Review"
7027
- if label.strip().lower() in _RESERVED_STAGE_LABELS and label != "Review":
7028
- return None, f"{label!r} is the name of a fixed stage β€” name the review something else"
7029
- nxt = cfg.get("next")
7030
- outs = []
7031
- if isinstance(nxt, list):
7032
- for entry in nxt[:MAX_LANES]:
7033
- lbl = " ".join(_s(entry, 60).split())
7034
- if lbl and lbl not in outs:
7035
- outs.append(lbl)
7036
- if not outs:
7037
- outs = ["Approved", "Declined"]
7038
- prompt = _s(cfg.get("prompt"), MAX_AI_PROMPT).strip()
7039
- if by == "ai" and not prompt:
7040
- return None, ("an AI review needs a prompt β€” tell it what to decide, or set the "
7041
- "review back to a person")
7042
- return {"decidedBy": by, "label": label, "next": outs, "prompt": prompt}, None
7043
- return {}, None
7044
 
7045
 
7046
  def _branch_letter(i):
@@ -7084,19 +7026,7 @@ def walk_actions(actions):
7084
  yield kid
7085
 
7086
 
7087
- def review_actions(defn):
7088
- """The review actions of one definition, in flow order β€” the stages a card can REST at."""
7089
- flow = (defn or {}).get("flow") or {}
7090
- return [a for a in walk_actions(flow.get("actions")) if a.get("kind") == "review"
7091
- and a.get("enabled", True)]
7092
-
7093
-
7094
- #: Every action kind's board label, from the ONE catalog the menu is built from β€” so a stage can
7095
- #: never be named something the builder does not call the step it came from.
7096
- _ACTION_LABELS = {r["kind"]: r["label"] for r in ACTION_CATALOG}
7097
-
7098
-
7099
- def board_actions(defn):
7100
  """⭐ OWNER ITEM 1 (2026-08-06) β€” the actions a card WALKS, in flow order.
7101
 
7102
  Owner, verbatim: *"the stages should always be based on the Automation Actions path, so we
@@ -7613,7 +7543,7 @@ def _actions_of_kind(actions, kind):
7613
  return out
7614
 
7615
 
7616
- def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print):
7617
  """Walk `flow.actions` for each of `row_ids`, then apply the ENDING. Returns the run counts.
7618
 
7619
  ⚠ The ending runs even when there are NO actions, and that is not a detail: a discovery
@@ -7622,7 +7552,8 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
7622
  feature on the flagship flow β€” the one kind most likely to want `auto_reset`. Caught in
7623
  review; the tests all happened to pass a non-empty action list, which is why it was green.
7624
  """
7625
- flow = (defn or {}).get("flow") or {}
 
7626
  actions = flow.get("actions") or []
7627
  # β›” THE PINNED STEP IS A PICTURE OF THE ENGINE'S OWN WRITE, NOT A SECOND ONE.
7628
  #
@@ -7638,11 +7569,7 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
7638
  # server still refuses to let it be removed.
7639
  if ig_action_pinned(defn, 0) and actions:
7640
  actions = actions[1:]
7641
- if _actions_of_kind(actions, "review"):
7642
- raise Refused("Manual review was retired with the automation Board β€” remove that action "
7643
- "from this automation before running it again")
7644
- counts = {"actionsRun": 0, "updated": 0, "created": 0, "found": 0, "review": 0,
7645
- "aiDecided": 0, "cycles": 0}
7646
  # ⭐ C4 β€” THE ENRICH ACCUMULATOR. Every append row the enrich action produces is collected
7647
  # across the WHOLE walk and written once at the end, for the reason the module header states
7648
  # and `run_field_instagram` learned the hard way: `upsert_rows` rebuilds the row dict on
@@ -7719,8 +7646,7 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
7719
  return counts
7720
  # Board-stage tracking was deliberately removed. The flow still runs its actions in order;
7721
  # the run log is now the single operational record of what happened.
7722
- stage_label_by_action = {}
7723
- patches, creates, ai_budget = {}, {}, [AI_DECISIONS_PER_RUN]
7724
 
7725
  # ⭐ OWNER ITEM 1 (2026-08-06) β€” WHERE EACH CARD GOT TO. `stages_for` now makes every action a
7726
  # board column; this is what puts cards in them. Keyed by row id, holding the LABEL of the
@@ -7745,9 +7671,7 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
7745
  kind = act.get("kind")
7746
  cfg = act.get("config") or {}
7747
  counts["actionsRun"] += 1
7748
- if kind != "group" and act.get("id") in stage_label_by_action:
7749
- reached[rid] = stage_label_by_action[act["id"]]
7750
- if kind == "group":
7751
  # ⭐ WAVE 24 Β· C-FORK β€” FIRST MATCHING BRANCH WINS, and only that one runs.
7752
  # Declaration order is priority order, the same rule `route_record` applies to
7753
  # the board's lanes, and the Otherwise leg (`cond: null`) is simply the branch
@@ -7900,15 +7824,12 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
7900
  _act_row_patch(patches, table, str(rid),
7901
  {skey: landed, skey + "_at": stamp})
7902
  counts.update(_enrich_flush(rt, defn, username, enrich, log))
7903
- counts["cycles"] = 0
7904
  # ⭐ C5: the REALIZED numbers overwrite the walk's attempt count. `counts["created"]` was
7905
  # incremented once per create the flow decided to make; what landed is what the store says,
7906
  # and with `uniqueOn` on they are routinely different (a re-run of a scheduled flow matches
7907
  # every row it made last time β€” which is the whole point of the feature).
7908
  counts.update(_commit_action_writes(rt, table, patches, creates, username, log))
7909
- if held:
7910
- notify_review(rt, defn, held, log=log)
7911
- return counts
7912
 
7913
 
7914
  def migrate_field_instagram(rt, defn):
@@ -7960,13 +7881,9 @@ def migrate_field_instagram(rt, defn):
7960
  out["kind"] = DEFAULT_KIND
7961
  # The enrich step goes FIRST β€” it is what the automation was, and every action the owner
7962
  # added afterwards was written expecting the capture to have happened.
7963
- out["flow"] = {"actions": [act] + list(flow.get("actions") or []),
7964
- "ending": flow.get("ending") or {"mode": "terminal"}}
7965
- # `plain`'s config is the table its records walk plus the board's lanes; the capture switches
7966
- # have moved onto the action, which is where a person now edits them.
7967
- out["config"] = {"targetTable": target,
7968
- "targetLabel": str(cfg.get("targetLabel") or ""),
7969
- "lanes": list(cfg.get("lanes") or [])}
7970
  return out, True
7971
 
7972
 
@@ -10271,11 +10188,7 @@ def email_poll(rt, tenant, auto_id, defn, log=print, _list=None, _read=None):
10271
  "target database", {}, False)
10272
  ut_ensure(rt, (defn.get("config") or {}).get("targetLabel") or defn.get("name") or "Inbox",
10273
  EMAIL_FIELDS, username=str(defn.get("createdBy") or "automation"), key=table_key)
10274
- skey = stage_field_key(auto_id)
10275
- stamp = _iso()
10276
- for r in rows_in:
10277
- r[skey + "_at"] = stamp
10278
- existing = dict((ut_get(rt, table_key) or {}).get("rows") or {})
10279
  merged, counts = upsert_rows(existing, rows_in, "email_id", cap=row_cap(table_key))
10280
  ut_write_rows(rt, table_key, merged)
10281
  new_seen = (list(seen) + fresh)[-EMAIL_SEEN_CAP:]
 
800
  for key in (row or {}):
801
  text = str(key)
802
  if text.startswith("stage_auto_"):
803
+ stage_keys.add(text.removesuffix("_at").removesuffix("_cycles"))
804
  stage_keys.discard("")
805
  if not stage_keys:
806
  return {"tables": 0, "fields": 0, "cells": 0}
 
829
  if not isinstance(row, dict):
830
  continue
831
  for stage_key in stage_keys:
832
+ for key in (stage_key, stage_key + "_at", stage_key + "_cycles"):
833
  if key in row:
834
  row.pop(key, None)
835
  changed["cells"] += 1
 
1212
  def flag(name):
1213
  return bool(raw[name]) if name in raw else bool(prev.get(name))
1214
  if kind == "plain":
1215
+ # A plain automation has no machine step, so it only needs the database its records walk.
 
1216
  #
1217
  # ⚠ THE TARGET IS OPTIONAL ON PURPOSE. An automation triggered by `record_updated` on
1218
  # `ut_foo` already knows its table from the trigger β€” `_flow_table` resolves target-else-
 
1223
  target = _s(raw.get("targetTable"), 60).strip()
1224
  if target and not target.startswith(UT_PREFIX):
1225
  target = UT_PREFIX + target
1226
+ return {"targetTable": target,
1227
+ "targetLabel": _s(raw.get("targetLabel"), 60).strip()}, None
 
 
 
 
1228
  if kind == "scrape_db":
1229
  url = _s(raw.get("url"), 2000).strip()
1230
  if not url:
 
1247
  target = _s(raw.get("targetTable"), 60).strip()
1248
  if target and not target.startswith(UT_PREFIX):
1249
  target = UT_PREFIX + target
1250
+ return {"url": url, "extract": extract,
 
 
 
1251
  "tableIndex": max(0, min(int(raw.get("tableIndex") or 0), 50)),
1252
  "fieldMap": fmap, "keyField": key_field,
1253
  "targetTable": target,
1254
+ "dryRun": flag("dryRun"),
1255
+ "targetLabel": _s(raw.get("targetLabel"), 60).strip() or "Scraped table"}, None
 
1256
  if kind == "field_instagram":
1257
  table = _s(raw.get("targetTable"), 60).strip()
1258
  if not table.startswith(UT_PREFIX):
 
1267
  tier = clean_tier(raw["tier"]) if "tier" in raw else ""
1268
  if not tier and "tier" not in raw:
1269
  tier = clean_tier(prev.get("tier"))
 
 
 
1270
  # C5: absent β‡’ keep whatever is stored, like every other switch in this branch β€” a panel
1271
  # that does not edit the post count must not reset it to the default on Save. And an
1272
  # INHERITED value is clamped rather than refused; see `clean_max_posts`.
 
1287
  # independent opt-in and never follows the per-post switch automatically.
1288
  "commentMetrics": flag("commentMetrics"),
1289
  "dryRun": flag("dryRun"),
1290
+ "maxPosts": max_posts}, None
 
1291
  if kind == "discover_instagram":
1292
  limit = int(raw.get("recordsLimit") or 0)
1293
  if limit < 1:
 
1303
  preds, perr = clean_predicates(raw.get("predicates"), join)
1304
  if perr:
1305
  return None, perr
1306
+ target = _s(raw.get("targetTable"), 60).strip() or DISCOVER_TABLE
 
 
 
 
 
1307
  if not target.startswith(UT_PREFIX):
1308
  target = UT_PREFIX + target
1309
  seed, serr = clean_seed(raw.get("seed") if "seed" in raw else prev.get("seed"))
 
1380
  # β›” `terminal` IS THE DEFAULT and every existing automation gets it, because a stored definition
1381
  # that predates this field must not start moving records on its own the day the code ships. A
1382
  # loop is a thing somebody turns on.
1383
+ def clean_flow(raw, previous=None):
1384
+ """Validate the builder's ordered action list. `(flow, error)`."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1385
  raw = raw if isinstance(raw, dict) else {}
1386
  prev = previous if isinstance(previous, dict) else {}
1387
  actions, err = clean_actions(raw.get("actions") if "actions" in raw else prev.get("actions"))
1388
  if err:
1389
  return None, err
1390
+ return {"actions": actions}, None
 
 
 
 
1391
 
1392
 
1393
  #: AMENDMENT A1 β€” what the `ig_profile_match` kind-flip seeds as `recordsLimit` when the
 
1674
  "id": _s(prev.get("id") or raw.get("id"), 40),
1675
  "name": name, "kind": kind, "config": config, "schedule": schedule,
1676
  "trigger": trigger,
1677
+ # The Builder's ordered actions. An absent flow is simply an automation with no actions.
1678
+ "flow": flow,
1679
+ "status": prev.get("status") or {"state": "idle", "lastRunAt": "", "lastSummary": ""},
1680
+ "runs": list(prev.get("runs") or [])[:MAX_RUNS],
 
 
 
 
 
 
1681
  # ⚠ ENGINE-OWNED CONTINUATION STATE, and it is NOT config. A discovery snapshot takes ~20
1682
  # minutes to build, so a run persists its id here and the NEXT run collects it. It is
1683
  # carried through `patch` untouched because a user pressing Save must not silently orphan
 
1709
  rt.update(STORE_KEY, _up, flush="sync")
1710
 
1711
 
1712
+ def _without_retired_board(definition):
1713
+ """Return a definition with retired Board-only state removed, without mutating the store.
1714
+
1715
+ This protects scheduled/manual execution before the next UI list request persists the
1716
+ migration. It removes only the former Board configuration, actions, and audit trail; normal
1717
+ actions and all user data remain intact.
1718
+ """
1719
+ if not isinstance(definition, dict):
1720
+ return definition, False
1721
+ out, changed = dict(definition), False
1722
+ cfg = out.get("config")
1723
+ if isinstance(cfg, dict) and "lanes" in cfg:
1724
+ cfg = dict(cfg)
1725
+ cfg.pop("lanes", None)
1726
+ out["config"] = cfg
1727
+ changed = True
1728
+
1729
+ def _actions(actions):
1730
+ nonlocal changed
1731
+ clean = []
1732
+ for action in actions if isinstance(actions, list) else []:
1733
+ if not isinstance(action, dict):
1734
+ clean.append(action)
1735
+ continue
1736
+ if action.get("kind") == "review":
1737
+ changed = True
1738
+ continue
1739
+ item = dict(action)
1740
+ if item.get("kind") == "group" and isinstance(item.get("config"), dict):
1741
+ group_cfg = dict(item["config"])
1742
+ branches = group_cfg.get("branches")
1743
+ if isinstance(branches, list):
1744
+ kept = []
1745
+ for branch in branches:
1746
+ if not isinstance(branch, dict):
1747
+ changed = True
1748
+ continue
1749
+ next_actions = _actions(branch.get("actions"))
1750
+ if not next_actions:
1751
+ changed = True
1752
+ continue
1753
+ kept.append({**branch, "actions": next_actions})
1754
+ if not kept:
1755
+ changed = True
1756
+ continue
1757
+ if kept != branches:
1758
+ changed = True
1759
+ group_cfg["branches"] = kept
1760
+ item["config"] = group_cfg
1761
+ elif isinstance(group_cfg.get("actions"), list):
1762
+ nested = _actions(group_cfg["actions"])
1763
+ if not nested:
1764
+ changed = True
1765
+ continue
1766
+ if nested != group_cfg["actions"]:
1767
+ group_cfg["actions"] = nested
1768
+ item["config"] = group_cfg
1769
+ clean.append(item)
1770
+ return clean
1771
+
1772
+ flow = out.get("flow")
1773
+ if isinstance(flow, dict):
1774
+ next_flow = dict(flow)
1775
+ actions = _actions(flow.get("actions"))
1776
+ if actions != flow.get("actions"):
1777
+ next_flow["actions"] = actions
1778
+ if "ending" in next_flow:
1779
+ next_flow.pop("ending", None)
1780
+ changed = True
1781
+ out["flow"] = next_flow
1782
+ if "reviews" in out:
1783
+ out.pop("reviews", None)
1784
+ changed = True
1785
+ return out, changed
1786
+
1787
+
1788
+ def retire_automation_board_state(rt):
1789
+ """Persist the idempotent Board retirement, then remove its generated table fields."""
1790
+ fields = retire_automation_stage_fields(rt)
1791
+ try:
1792
+ stored = dict(rt.get(STORE_KEY) or {})
1793
+ except Exception:
1794
+ return {"definitions": 0, **fields}
1795
+ plan = {str(aid): cleaned for aid, raw in stored.items()
1796
+ for cleaned, changed in [_without_retired_board(raw)] if changed}
1797
+ if not plan:
1798
+ return {"definitions": 0, **fields}
1799
+
1800
+ def _up(cur):
1801
+ cur = cur if isinstance(cur, dict) else {}
1802
+ for aid, cleaned in plan.items():
1803
+ if aid in cur:
1804
+ cur[aid] = cleaned
1805
+ return cur
1806
+
1807
+ rt.update(STORE_KEY, _up, flush="sync")
1808
+ return {"definitions": len(plan), **fields}
1809
+
1810
+
1811
+ def all_definitions(rt):
1812
+ try:
1813
+ raw = dict(rt.get(STORE_KEY) or {})
1814
+ except Exception:
1815
+ return {}
1816
+ return {str(aid): _without_retired_board(defn)[0] for aid, defn in raw.items()}
1817
 
1818
 
1819
  def _new_id(existing):
 
6480
  # `auto` = the engine advances. Today reviewβ‡’strict and everything elseβ‡’auto BY DERIVATION β€”
6481
  # the vocabulary is on the wire so a later wave can flip a stage without a client change.
6482
 
6483
+ LANE_OPS = ("=", "!=", ">", ">=", "<", "<=", "includes", "not_includes",
 
 
 
 
 
 
 
 
 
 
 
6484
  "is_empty", "is_not_empty")
6485
  LANE_NULLARY_OPS = ("is_empty", "is_not_empty")
6486
 
 
6579
  # ⚠ `tracked` / `declined` STAY RESERVED even though R6 deleted the stages that used them: the
6580
  # labels still sit in boards stored before this wave, and a user lane named "Tracked" beside a
6581
  # legacy stamped cell would read as the same lane while behaving as a different one.
6582
+ def _lane_num(v):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6583
  try:
6584
  return float(str(v).replace(",", ""))
6585
  except (TypeError, ValueError):
 
6627
  return same if op == "=" else (not same) if op == "!=" else False
6628
 
6629
 
6630
+ # ─────────────────────────────────────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
6631
  # WAVE 23 Β· C4 β€” ACTIONS (owner ruling R3). The half of the Airtable builder that DOES things.
6632
  #
6633
  # `flow.actions` is an ordered list walked per RECORD, after the flow's machine steps have run.
 
6641
  # Run script / Generate with AI faded with a reason instead of omitting them β€” the same honesty
6642
  # rule the trigger list follows, and the same enforcement: `clean_actions` REFUSES an unready
6643
  # kind with a sentence, so the faded state is a wall and not a styling choice.
6644
+ MAX_ACTIONS = 20 # per automation, counting nested ones
6645
+ MAX_GROUP_DEPTH = 2 # a group inside a group inside a group is a flowchart, not a flow
6646
+ MAX_BRANCHES = 6 # per If / then
 
 
 
 
6647
  MAX_ACTION_VALUES = 20 # cells one update/create action may write
6648
  FIND_LIMIT_MAX = 100
6649
  #: ⭐ WAVE 24 Β· C-ACT β€” THE MENU'S GROUP ORDER IS THE SERVER'S. The client sorts by `groupOrder`
 
6704
  "ready": False, "detail": "Run the same actions on every item in a list"},
6705
  {"kind": "run_script", "label": "Run script", "group": "Advanced logic", "ready": False,
6706
  "detail": "Not built β€” a sandbox is its own decision"},
6707
+ {"kind": "generate_ai", "label": "Generate with AI", "group": "Advanced logic",
6708
+ "ready": False, "detail": "Needs an AI action implementation"},
6709
+ ]
 
 
6710
 
6711
 
6712
  def action_catalog():
 
6982
  if limit < 1 or limit > FIND_LIMIT_MAX:
6983
  return None, f"the find records limit is between 1 and {FIND_LIMIT_MAX}"
6984
  return {"table": table, "cond": cond, "limit": limit}, None
6985
+ return {}, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6986
 
6987
 
6988
  def _branch_letter(i):
 
7026
  yield kid
7027
 
7028
 
7029
+ def board_actions(defn):
 
 
 
 
 
 
 
 
 
 
 
 
7030
  """⭐ OWNER ITEM 1 (2026-08-06) β€” the actions a card WALKS, in flow order.
7031
 
7032
  Owner, verbatim: *"the stages should always be based on the Automation Actions path, so we
 
7543
  return out
7544
 
7545
 
7546
+ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print):
7547
  """Walk `flow.actions` for each of `row_ids`, then apply the ENDING. Returns the run counts.
7548
 
7549
  ⚠ The ending runs even when there are NO actions, and that is not a detail: a discovery
 
7552
  feature on the flagship flow β€” the one kind most likely to want `auto_reset`. Caught in
7553
  review; the tests all happened to pass a non-empty action list, which is why it was green.
7554
  """
7555
+ defn, _retired = _without_retired_board(defn)
7556
+ flow = (defn or {}).get("flow") or {}
7557
  actions = flow.get("actions") or []
7558
  # β›” THE PINNED STEP IS A PICTURE OF THE ENGINE'S OWN WRITE, NOT A SECOND ONE.
7559
  #
 
7569
  # server still refuses to let it be removed.
7570
  if ig_action_pinned(defn, 0) and actions:
7571
  actions = actions[1:]
7572
+ counts = {"actionsRun": 0, "updated": 0, "created": 0, "found": 0}
 
 
 
 
7573
  # ⭐ C4 β€” THE ENRICH ACCUMULATOR. Every append row the enrich action produces is collected
7574
  # across the WHOLE walk and written once at the end, for the reason the module header states
7575
  # and `run_field_instagram` learned the hard way: `upsert_rows` rebuilds the row dict on
 
7646
  return counts
7647
  # Board-stage tracking was deliberately removed. The flow still runs its actions in order;
7648
  # the run log is now the single operational record of what happened.
7649
+ patches, creates = {}, {}
 
7650
 
7651
  # ⭐ OWNER ITEM 1 (2026-08-06) β€” WHERE EACH CARD GOT TO. `stages_for` now makes every action a
7652
  # board column; this is what puts cards in them. Keyed by row id, holding the LABEL of the
 
7671
  kind = act.get("kind")
7672
  cfg = act.get("config") or {}
7673
  counts["actionsRun"] += 1
7674
+ if kind == "group":
 
 
7675
  # ⭐ WAVE 24 Β· C-FORK β€” FIRST MATCHING BRANCH WINS, and only that one runs.
7676
  # Declaration order is priority order, the same rule `route_record` applies to
7677
  # the board's lanes, and the Otherwise leg (`cond: null`) is simply the branch
 
7824
  _act_row_patch(patches, table, str(rid),
7825
  {skey: landed, skey + "_at": stamp})
7826
  counts.update(_enrich_flush(rt, defn, username, enrich, log))
 
7827
  # ⭐ C5: the REALIZED numbers overwrite the walk's attempt count. `counts["created"]` was
7828
  # incremented once per create the flow decided to make; what landed is what the store says,
7829
  # and with `uniqueOn` on they are routinely different (a re-run of a scheduled flow matches
7830
  # every row it made last time β€” which is the whole point of the feature).
7831
  counts.update(_commit_action_writes(rt, table, patches, creates, username, log))
7832
+ return counts
 
 
7833
 
7834
 
7835
  def migrate_field_instagram(rt, defn):
 
7881
  out["kind"] = DEFAULT_KIND
7882
  # The enrich step goes FIRST β€” it is what the automation was, and every action the owner
7883
  # added afterwards was written expecting the capture to have happened.
7884
+ out["flow"] = {"actions": [act] + list(flow.get("actions") or [])}
7885
+ out["config"] = {"targetTable": target,
7886
+ "targetLabel": str(cfg.get("targetLabel") or "")}
 
 
 
 
7887
  return out, True
7888
 
7889
 
 
10188
  "target database", {}, False)
10189
  ut_ensure(rt, (defn.get("config") or {}).get("targetLabel") or defn.get("name") or "Inbox",
10190
  EMAIL_FIELDS, username=str(defn.get("createdBy") or "automation"), key=table_key)
10191
+ existing = dict((ut_get(rt, table_key) or {}).get("rows") or {})
 
 
 
 
10192
  merged, counts = upsert_rows(existing, rows_in, "email_id", cap=row_cap(table_key))
10193
  ut_write_rows(rt, table_key, merged)
10194
  new_seen = (list(seen) + fresh)[-EMAIL_SEEN_CAP:]
api/routes_automation.py CHANGED
@@ -53,9 +53,6 @@ def _wire(defn, tenant):
53
  "id": defn.get("id"), "name": defn.get("name"), "kind": defn.get("kind"),
54
  "config": defn.get("config") or {}, "schedule": sched, "status": status,
55
  "runs": list(defn.get("runs") or [])[:engine.MAX_RUNS],
56
- # C3-A2(5): the review-decision audit (who moved which card where, when) β€” newest
57
- # first, bounded server-side; both doors (board move + kanban drag) write it.
58
- "reviews": list(defn.get("reviews") or [])[:engine.MAX_REVIEWS],
59
  "created": defn.get("created"), "createdBy": defn.get("createdBy"),
60
  "nextRunAt": nxt.strftime("%Y-%m-%d %H:%M") if nxt else "",
61
  "running": bool(live),
@@ -75,9 +72,7 @@ def _wire(defn, tenant):
75
  # bug caught in review rather than by a gate: `flow` was stored, patchable and validated,
76
  # but never sent back. B would have saved a flow through PATCH, got a 200, and watched
77
  # every action vanish on reload β€” the classic "it didn't save" with nothing red anywhere.
78
- # Defaulted rather than conditional so a pre-wave definition reads as an empty flow with
79
- # a terminal ending instead of `undefined`, which the client would have to special-case.
80
- "flow": defn.get("flow") or {"actions": [], "ending": {"mode": "terminal"}},
81
  }
82
 
83
 
@@ -184,17 +179,6 @@ def _triggers_vocab(session):
184
  return out
185
 
186
 
187
- def _ai_ready():
188
- """Can an AI review actually decide on this deployment? (C6/R14.) A boolean, never the
189
- provider list and never a key β€” the surface needs to say "not configured" honestly, and that
190
- needs exactly one bit."""
191
- try:
192
- import ai_review
193
- return bool(ai_review.configured())
194
- except Exception: # noqa: BLE001
195
- return False
196
-
197
-
198
  def _tick_state():
199
  """⭐ WAVE 21 (C6 amendment A1) β€” can a SCHEDULE fire on this deployment?
200
 
@@ -217,10 +201,10 @@ def list_automations(session: Session = Depends(_GATE)):
217
  The vocabularies ride WITH the list rather than sitting in a client constant: the cron
218
  presets and the kind list are the server's, and a client copy of either is a thing that goes
219
  stale silently (the editor would offer a preset the parser rejects)."""
220
- # One idempotent tenant migration at the Automation entry point. It removes only fields the
221
- # retired Board engine itself marked, so user-created Status/Stage columns remain intact.
222
  if session.runtime.available():
223
- engine.retire_automation_stage_fields(session.runtime)
224
  defs = engine.all_definitions(session.runtime)
225
  items = [_wire(d, session.tenant) for _, d in
226
  sorted(defs.items(), key=lambda kv: (kv[1].get("name") or "").lower())]
@@ -288,15 +272,8 @@ def list_automations(session: Session = Depends(_GATE)):
288
  "nullaryCondOps": list(engine.LANE_NULLARY_OPS),
289
  "maxCondDepth": engine.MAX_COND_DEPTH,
290
  "maxCondChildren": engine.MAX_COND_CHILDREN,
291
- "maxGroupDepth": engine.MAX_GROUP_DEPTH,
292
- "maxActions": engine.MAX_ACTIONS,
293
- "endingModes": list(engine.ENDING_MODES),
294
- "maxResetHours": engine.MAX_RESET_HOURS,
295
- "reviewDeciders": list(engine.REVIEW_DECIDERS),
296
- # Honest, per-deployment: with no LLM key configured the AI-review option
297
- # renders as not-configured rather than as a control that silently holds
298
- # every card for a human (C6's fail-closed path, made visible).
299
- "aiReady": _ai_ready()},
300
  # Wave 21 C6-A1: {"enabled": bool, "source": "in-process"|"external"|""} β€” see
301
  # `_tick_state` for why one boolean off AIOS_AUTOMATIONS alone would lie.
302
  "tick": _tick_state()}
 
53
  "id": defn.get("id"), "name": defn.get("name"), "kind": defn.get("kind"),
54
  "config": defn.get("config") or {}, "schedule": sched, "status": status,
55
  "runs": list(defn.get("runs") or [])[:engine.MAX_RUNS],
 
 
 
56
  "created": defn.get("created"), "createdBy": defn.get("createdBy"),
57
  "nextRunAt": nxt.strftime("%Y-%m-%d %H:%M") if nxt else "",
58
  "running": bool(live),
 
72
  # bug caught in review rather than by a gate: `flow` was stored, patchable and validated,
73
  # but never sent back. B would have saved a flow through PATCH, got a 200, and watched
74
  # every action vanish on reload β€” the classic "it didn't save" with nothing red anywhere.
75
+ "flow": defn.get("flow") or {"actions": []},
 
 
76
  }
77
 
78
 
 
179
  return out
180
 
181
 
 
 
 
 
 
 
 
 
 
 
 
182
  def _tick_state():
183
  """⭐ WAVE 21 (C6 amendment A1) β€” can a SCHEDULE fire on this deployment?
184
 
 
201
  The vocabularies ride WITH the list rather than sitting in a client constant: the cron
202
  presets and the kind list are the server's, and a client copy of either is a thing that goes
203
  stale silently (the editor would offer a preset the parser rejects)."""
204
+ # Idempotent Board retirement removes only engine-marked stage fields and legacy Board state.
205
+ # User-created Status/Stage columns remain intact.
206
  if session.runtime.available():
207
+ engine.retire_automation_board_state(session.runtime)
208
  defs = engine.all_definitions(session.runtime)
209
  items = [_wire(d, session.tenant) for _, d in
210
  sorted(defs.items(), key=lambda kv: (kv[1].get("name") or "").lower())]
 
272
  "nullaryCondOps": list(engine.LANE_NULLARY_OPS),
273
  "maxCondDepth": engine.MAX_COND_DEPTH,
274
  "maxCondChildren": engine.MAX_COND_CHILDREN,
275
+ "maxGroupDepth": engine.MAX_GROUP_DEPTH,
276
+ "maxActions": engine.MAX_ACTIONS},
 
 
 
 
 
 
 
277
  # Wave 21 C6-A1: {"enabled": bool, "source": "in-process"|"external"|""} β€” see
278
  # `_tick_state` for why one boolean off AIOS_AUTOMATIONS alone would lie.
279
  "tick": _tick_state()}
platform/core/grid_events.py CHANGED
@@ -1768,41 +1768,6 @@ def handle_one(event, ctx):
1768
  refused = True
1769
  row_events.append((key, _linked))
1770
  continue
1771
- if isinstance(_auto, dict) and _auto.get('stageField'):
1772
- _row = ((_tdef or {}).get('rows') or {}).get(str(pid)) or {}
1773
- _cur = str(_row.get(key) or '').strip()
1774
- _want = str(value).strip()
1775
- if _want in ((_auto.get('humanMoves') or {}).get(_cur) or []):
1776
- import datetime as _dt_sf
1777
- _stamp_sf = _dt_sf.datetime.now().astimezone().isoformat(
1778
- timespec='seconds')
1779
- _ut_mod.patch_cells(
1780
- ctx.scope_key, pid,
1781
- {key: _want, key + '_at': _stamp_sf,
1782
- **(((_auto.get('arrive') or {}).get(_want)) or {})},
1783
- st=ctx.table.st)
1784
- # C3-A2(5): the decision is AUDITED from this door too β€” same shape
1785
- # `move_card` writes, appended mechanically off the field's flowId.
1786
- _flow = str(_auto.get('flowId') or '')
1787
-
1788
- def _audit_sf(cur_a, _f=_flow, _e={'ts': _stamp_sf, 'user': uname,
1789
- 'rowId': str(pid), 'from': _cur,
1790
- 'to': _want}):
1791
- cur_a = cur_a if isinstance(cur_a, dict) else {}
1792
- d = cur_a.get(_f)
1793
- if isinstance(d, dict):
1794
- d['reviews'] = ([_e] + list(d.get('reviews') or []))[:100]
1795
- return cur_a
1796
- if _flow:
1797
- try:
1798
- ctx.table.st.update('automations', _audit_sf, flush='async')
1799
- except Exception:
1800
- pass # the move stands; a lost audit line is not a veto
1801
- stage_moved = True
1802
- row_events.append((key, _want))
1803
- else:
1804
- refused = True
1805
- continue
1806
  # ⭐ WAVE 25 (C3 + amendment C3-A1, owner rulings R7/R6) β€” THE PROFILE CELL.
1807
  # Two things happen here and neither can live anywhere else:
1808
  #
 
1768
  refused = True
1769
  row_events.append((key, _linked))
1770
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1771
  # ⭐ WAVE 25 (C3 + amendment C3-A1, owner rulings R7/R6) β€” THE PROFILE CELL.
1772
  # Two things happen here and neither can live anywhere else:
1773
  #
platform/core/user_tables.py CHANGED
@@ -122,14 +122,9 @@ _IG_HANDLE_RE = re.compile(r'^[A-Za-z0-9._]{1,30}$')
122
  #: boot-path reason) as `METRIC_MEASURES` below; the pair is held in step by a parity check
123
  #: rather than by an import, because `core/` must stay importable without the API layer.
124
  #:
125
- #: β›” HUMAN-WRITTEN COLUMNS ARE DELIBERATELY ABSENT, AND THAT IS THE WHOLE CARE IN THIS LIST.
126
- #: `ut_ensure` stamps `automation: {flowId}` on every field it spawns, so "carries an automation
127
- #: tag" would ALSO catch every `stage_<id>` column, whose value is a board position somebody
128
- #: moved. Clearing one would destroy a person's decision because a machine happened to declare the
129
- #: column. The rule is therefore an INTERSECTION (tagged AND named here), never the tag alone.
130
- #: ⚠ This note used to cite `tracked` as its second example; wave 26 (R6) deleted that column β€”
131
- #: the stage field is the one progress column now. The RULE is unchanged and still load-bearing:
132
- #: `stage_<id>` alone is enough to need the intersection.
133
  PROFILE_PRESET_KEYS = (
134
  # the profile facts themselves (CANDIDATE_FIELDS + the enrichment run_field_instagram pulls)
135
  'full_name', 'followers', 'following', 'posts_count', 'avg_engagement', 'bio',
@@ -1219,12 +1214,7 @@ def rename_choice_values(table_key, fkey, renames, st=None):
1219
 
1220
 
1221
  def patch_cells(table_key, row_id, values, st=None):
1222
- """Write cells into the DEFINITION row β€” the shared truth every viewer and the automation
1223
- engine read (wave 22, C2). Exists for the stage-field door in `core.grid_events`: a stage
1224
- position written into the editor's personal overlay stratum would be a board only its
1225
- author could see. Values are stringified; keys are taken as given because the CALLER is the
1226
- wall (grid_events admits exactly the transition the field's own `automation.humanMoves`
1227
- law allows, plus its `arrive` side-effects). Returns True when the row existed."""
1228
  if not is_user_table(table_key, st):
1229
  return False
1230
  rows = (get(table_key, st) or {}).get('rows') or {}
@@ -1326,9 +1316,8 @@ def patch_profile_cell(table_key, row_id, fkey, value, st=None):
1326
  handle, ok = normalize_profile(value, fdef['profile'].get('source'))
1327
  if not ok:
1328
  return None # refused with a sentence at the route
1329
- # THE INTERSECTION, and it is the careful half: a key named in the C1 preset set AND a field
1330
- # the machine declared. `ut_ensure` tags every column it spawns, so the tag alone would also
1331
- # catch every `stage_<id>` (a human's board move).
1332
  cleared = []
1333
  if not handle:
1334
  cleared = [f['key'] for f in fields
 
122
  #: boot-path reason) as `METRIC_MEASURES` below; the pair is held in step by a parity check
123
  #: rather than by an import, because `core/` must stay importable without the API layer.
124
  #:
125
+ #: Human-written columns are deliberately absent. `ut_ensure` stamps automation provenance on
126
+ #: generated fields, so clearing by that tag alone would erase unrelated machine-owned columns.
127
+ #: This is therefore an intersection of the known Instagram preset keys and the provenance tag.
 
 
 
 
 
128
  PROFILE_PRESET_KEYS = (
129
  # the profile facts themselves (CANDIDATE_FIELDS + the enrichment run_field_instagram pulls)
130
  'full_name', 'followers', 'following', 'posts_count', 'avg_engagement', 'bio',
 
1214
 
1215
 
1216
  def patch_cells(table_key, row_id, values, st=None):
1217
+ """Write shared definition-row cells for trusted server-side writers."""
 
 
 
 
 
1218
  if not is_user_table(table_key, st):
1219
  return False
1220
  rows = (get(table_key, st) or {}).get('rows') or {}
 
1316
  handle, ok = normalize_profile(value, fdef['profile'].get('source'))
1317
  if not ok:
1318
  return None # refused with a sentence at the route
1319
+ # Clear only the known Instagram presets that the automation declared, never every field with
1320
+ # automation provenance.
 
1321
  cleared = []
1322
  if not handle:
1323
  cleared = [f['key'] for f in fields
web/src/automation/AutomationBuilder.tsx CHANGED
@@ -183,13 +183,6 @@ function ActionMark({ kind }: { kind: string }) {
183
  <path d="M11.6 2.6 13.4 4.4 11.6 6.2M11.6 9.8l1.8 1.8-1.8 1.8" />
184
  </svg>
185
  );
186
- if (kind === "review")
187
- return (
188
- <svg {...common}>
189
- <circle cx="8" cy="5.6" r="2.6" />
190
- <path d="M3 13.4c.7-2.3 2.6-3.6 5-3.6s4.3 1.3 5 3.6" />
191
- </svg>
192
- );
193
  if (kind === "create_record")
194
  return (
195
  <svg {...common}>
@@ -445,8 +438,7 @@ export default function AutomationBuilder({
445
  const patchConfig = (patch: Record<string, unknown>) =>
446
  onPatch({ config: { ...((automation.config as Record<string, unknown>) || {}), ...patch } });
447
 
448
- const patchFlow = (next: Action[]) =>
449
- onPatch({ flow: { actions: next, ending: automation.flow?.ending || { mode: "terminal" } } });
450
 
451
  /**
452
  * ⭐ ONE TREE WALKER (wave 24, C-FORK). Rewrite or drop any action anywhere, branches included:
@@ -544,8 +536,6 @@ export default function AutomationBuilder({
544
  const firstTableField = firstTable?.fields?.[0]?.key || "";
545
 
546
  const seedFor = (kind: string): Record<string, unknown> | null => {
547
- if (kind === "review")
548
- return { decidedBy: "user", label: "Review", next: ["Approved", "Declined"], prompt: "" };
549
  if (kind === "update_record")
550
  return firstField ? { values: { [firstField]: "" } } : null;
551
  if (kind === "create_record")
@@ -1352,10 +1342,6 @@ function actionSub(a: Action, tables: UserTable[]): string {
1352
  const t = String((cfg as { table?: string }).table || "");
1353
  return t ? `In ${tableLabel(tables, t)}` : "No database yet";
1354
  }
1355
- if (a.kind === "review") {
1356
- const by = String((cfg as { decidedBy?: string }).decidedBy || "user");
1357
- return by === "ai" ? "Decided by AI" : "Decided by a person";
1358
- }
1359
  return "";
1360
  }
1361
 
@@ -2669,15 +2655,6 @@ function ActionProps({
2669
  </>
2670
  ) : null}
2671
 
2672
- {action.kind === "review" ? (
2673
- <ReviewProps
2674
- cfg={cfg as Record<string, unknown>}
2675
- vocab={vocab}
2676
- busy={busy}
2677
- setCfg={setCfg}
2678
- />
2679
- ) : null}
2680
-
2681
  {/*
2682
  ⭐ WAVE 26 Β· ITEM 5 β€” OWNER RULINGS R9 AND R10, and they are two different fixes to one
2683
  symptom (*"the condition on action act_1 names no field"*).
@@ -2732,7 +2709,7 @@ function ActionProps({
2732
  );
2733
  }
2734
 
2735
- function ReviewProps({
2736
  cfg,
2737
  vocab,
2738
  busy,
 
183
  <path d="M11.6 2.6 13.4 4.4 11.6 6.2M11.6 9.8l1.8 1.8-1.8 1.8" />
184
  </svg>
185
  );
 
 
 
 
 
 
 
186
  if (kind === "create_record")
187
  return (
188
  <svg {...common}>
 
438
  const patchConfig = (patch: Record<string, unknown>) =>
439
  onPatch({ config: { ...((automation.config as Record<string, unknown>) || {}), ...patch } });
440
 
441
+ const patchFlow = (next: Action[]) => onPatch({ flow: { actions: next } });
 
442
 
443
  /**
444
  * ⭐ ONE TREE WALKER (wave 24, C-FORK). Rewrite or drop any action anywhere, branches included:
 
536
  const firstTableField = firstTable?.fields?.[0]?.key || "";
537
 
538
  const seedFor = (kind: string): Record<string, unknown> | null => {
 
 
539
  if (kind === "update_record")
540
  return firstField ? { values: { [firstField]: "" } } : null;
541
  if (kind === "create_record")
 
1342
  const t = String((cfg as { table?: string }).table || "");
1343
  return t ? `In ${tableLabel(tables, t)}` : "No database yet";
1344
  }
 
 
 
 
1345
  return "";
1346
  }
1347
 
 
2655
  </>
2656
  ) : null}
2657
 
 
 
 
 
 
 
 
 
 
2658
  {/*
2659
  ⭐ WAVE 26 Β· ITEM 5 β€” OWNER RULINGS R9 AND R10, and they are two different fixes to one
2660
  symptom (*"the condition on action act_1 names no field"*).
 
2709
  );
2710
  }
2711
 
2712
+ export function ReviewProps({
2713
  cfg,
2714
  vocab,
2715
  busy,
web/src/automation/AutomationDetail.tsx CHANGED
@@ -1216,7 +1216,7 @@ export default function AutomationDetail({
1216
  <aside className="auto-panel" aria-label="Run log">
1217
  <>
1218
  <div className="auto-panel-head">
1219
- <h2>Run history</h2>
1220
  </div>
1221
  {!automation.runs?.length ? (
1222
  <p className="auto-note">
 
1216
  <aside className="auto-panel" aria-label="Run log">
1217
  <>
1218
  <div className="auto-panel-head">
1219
+ <h2>Log</h2>
1220
  </div>
1221
  {!automation.runs?.length ? (
1222
  <p className="auto-note">
web/src/automation/automationApi.ts CHANGED
@@ -181,7 +181,6 @@ export interface Automation {
181
  * judgement written into a record, so it says WHO β€” the same reason every count in
182
  * this product drills to its rows.
183
  */
184
- reviews?: ReviewEntry[];
185
  }
186
 
187
  export interface AutomationList {
@@ -410,14 +409,8 @@ export interface Action {
410
  }
411
 
412
  /** `flow.ending` (C5) β€” what happens to a record that reaches the end. */
413
- export interface FlowEnding {
414
- mode: string;
415
- hours?: number;
416
- }
417
-
418
- export interface Flow {
419
- actions: Action[];
420
- ending: FlowEnding;
421
  }
422
 
423
  /**
@@ -444,23 +437,23 @@ export interface ActionCatalogRow {
444
  }
445
 
446
  /** The builder's own ceilings, server-declared so the client never hard-codes the same numbers. */
447
- export interface FlowVocab {
448
  condOps: string[];
449
  nullaryCondOps: string[];
450
  maxCondDepth: number;
451
  maxCondChildren: number;
452
  maxGroupDepth: number;
453
- maxActions: number;
454
- endingModes: string[];
455
- maxResetHours: number;
456
- reviewDeciders: string[];
 
457
  /**
458
  * ⚠ PER-DEPLOYMENT, AND HONEST RATHER THAN DECORATIVE. With no LLM key configured the engine
459
  * holds every card for a human β€” so an enabled-looking "decided by AI" control would promise
460
  * a decision nothing will make. False renders it as not-configured (C6's fail-closed path,
461
  * made visible).
462
  */
463
- aiReady: boolean;
464
  }
465
 
466
  export interface OAuthConnection {
 
181
  * judgement written into a record, so it says WHO β€” the same reason every count in
182
  * this product drills to its rows.
183
  */
 
184
  }
185
 
186
  export interface AutomationList {
 
409
  }
410
 
411
  /** `flow.ending` (C5) β€” what happens to a record that reaches the end. */
412
+ export interface Flow {
413
+ actions: Action[];
 
 
 
 
 
 
414
  }
415
 
416
  /**
 
437
  }
438
 
439
  /** The builder's own ceilings, server-declared so the client never hard-codes the same numbers. */
440
+ export interface FlowVocab {
441
  condOps: string[];
442
  nullaryCondOps: string[];
443
  maxCondDepth: number;
444
  maxCondChildren: number;
445
  maxGroupDepth: number;
446
+ maxActions: number;
447
+ /** Legacy read compatibility only; the server no longer sends Board review vocabulary. */
448
+ reviewDeciders?: string[];
449
+ /** Legacy read compatibility only; the server no longer sends Board review readiness. */
450
+ aiReady?: boolean;
451
  /**
452
  * ⚠ PER-DEPLOYMENT, AND HONEST RATHER THAN DECORATIVE. With no LLM key configured the engine
453
  * holds every card for a human β€” so an enabled-looking "decided by AI" control would promise
454
  * a decision nothing will make. False renders it as not-configured (C6's fail-closed path,
455
  * made visible).
456
  */
 
457
  }
458
 
459
  export interface OAuthConnection {