diff --git a/.changeset/34770-formula-skill-router.md b/.changeset/34770-formula-skill-router.md new file mode 100644 index 00000000000..022abb82ece --- /dev/null +++ b/.changeset/34770-formula-skill-router.md @@ -0,0 +1,23 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the objectstack-formula entry file becomes a router + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-formula/SKILL.md` goes from 24.4 KB to 9.0 KB (485 lines to 135). It now holds five things: four first checks (the installed version wins over the `compatibility` line; read the object's declared fields and the contract of the key that takes the expression; bare CEL under the `F`, `P` or `cel` tag, never braces round a field reference; verify with `os validate`, `os build` or the `validate_expression` agent tool), one type-checked block that shows each tag once, the roots and the advertised function names as one list, eight traps, and a table that says where to go for the rest. No rule's teaching changes. This skill has no hand-written reference file, so no text moved: what left the entry was cut, and this entry says what now answers it. + +**What the entry keeps.** Every name of `CEL_STDLIB_FUNCTIONS`, as a call form with its parameters and without the per-function notes. The eight traps, each an expression that parses and then fails, or reads wrong, at run time or at the build: `has()` is not a null check on a server-evaluated predicate, where the guard is `!= null` and the build refuses an ordering or arithmetic operator on a nullable field without it, a flow condition's bare name included; action `visible` / `disabled` are client-side and sparse, so their guard is `has(record.x) && record.x != null`; a transition compares `previous`, which is per row on a bulk write and `null` on insert, and a hook `condition` that cannot evaluate aborts the write; a list field is never compared with a scalar (`list-equality`), with the membership form for a CEL site, a flow condition and a `SharingRule` `condition`; a `date` / `datetime` field is its ISO text (`date-text-call`), with the helpers that replace date arithmetic; `label()` and the working-day functions belong to a formula or a stored field's `expression`; a dynamic seed value is the `cel` tag, never a JavaScript date; a `template` is not CEL, and only an email template reads a currency code from the send's data. The routing table keeps three more facts beside the rows that send them elsewhere: a `formula` field is virtual, so a filter, a sort and a search refuse it; a view filter is a structured rule or a date macro, not CEL; a form-view `visibleWhen` is client-side and faults open, so it is never access control. + +**What left, and what answers it now.** + +- The per-function tables (what each function returns, `today()` as a calendar day at UTC midnight, `addMonths` clamping to the month end, `floor` and `ceil` rounding toward the infinities, the `rmbUpper` example, what `isBlank` and `isEmpty` count as empty), the date recipe for an inclusive span, and the working-day counting rules (the start day is not counted, the end day is): https://objectstack.ai/docs/data-modeling/formulas. An unknown or misspelled function fails `os build`, with a did-you-mean when an advertised name is close. +- The legacy translation table beyond the rows first check 3 keeps (`IF`, `CONCAT`, `TODAY()` / `NOW()`, `IN (…)`, `ISCHANGED`, the functions with no CEL counterpart): the same page, "Migration from the legacy formula DSL". Each legacy spelling fails the build. +- The table of surfaces that take an expression, the carriers of the `cron` and `template` dialects, the cron grammar and the refused `Object.titleFormat`: the contract, `node_modules/@objectstack/spec/src/shared/expression.zod.ts` and the schema of the key in hand. A save and `os validate` refuse the retired key. +- The table of where `previous` is bound, the rule that a `before*` handler's per-row rewrite must assign one key set on every row (`MULTI_UPDATE_HOOK_KEY_DIVERGENCE`): `skills/objectstack-data/references/data-hooks.md`, which the routing table names. +- The skill-boundary table: the frontmatter description and the routing table. +- Cut with no pointer, because nothing an author writes depends on them: the engine named behind each dialect, the receiver-method note and the four withheld primitives, the tenure-in-years recipe (a `daysBetween` divided by 365), and the sentence that a `SharingRule` whose condition does not lower is skipped at run time (the build fails first). + +**Anchors that no longer exist in `SKILL.md`.** Every section heading of the old file below its title: `#skill-boundaries`, `#core-contract`, `#cel-syntax-cheat-sheet`, `#has-is-not-a-null-check`, `#objectstack-cel-standard-library`, `#mandatory-patterns-for-ai-emission`, `#1-computed-text-formula--always-coalesce-nullable-operands`, `#2-conditional-numeric-formula--guard-divisor`, `#3-predicate-field-rules--visibility--validation`, `#4-dynamic-seed-value--use-cel-not-new-date`, `#5-update-hook-condition--previous-vs-record`, `#mechanical-translation-table-legacy--cel`, `#surfaces-that-take-an-expression`, `#cel-surfaces-predicates--computed-values`, `#cron-and-template-surfaces`, `#verify-your-work`, `#see-also`. The new ones are `#first-checks`, `#scope-and-functions`, `#traps` and `#where-to-go`; the title's anchor is unchanged. No file in this repository linked an anchor of the old entry. diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index a94d37689ff..c467caf3696 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -980,7 +980,24 @@ export const CEILINGS = new Map([ // 6090 -> 6088: the action `visible` / `disabled` paragraph says "a list row" where it wrote // the retired action location word `list_item` (-7 bytes); the row follows the measurement // down, 24384 bytes (24357 priced) -> 24377 (24350 priced) -> 6088 tokens. - ['skills/objectstack-formula/SKILL.md', 6088], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997), then +82 (was 6008), then -2 (was 6090) + // 6088 -> 2243 (#34770): the entry becomes a router. It keeps four first checks, one + // type-checked block of the three tags, the roots and the advertised function names as one + // list (`packages/formula/src/skill-catalog-sync.test.ts` reads them here), eight traps and a + // routing table. This skill has no hand-authored reference file, so nothing MOVED: the rest + // is CUT behind a pointer, to the contract (`shared/expression.zod.ts` and the key's own + // schema), to `os validate` / `os build` (syntax, unknown functions, `date-text-call`, + // `list-equality` and the nullable-operand refusal are errors there) or to the published + // formulas page. No row rises and no row is added. The router was first measured at 8974 + // bytes; the contract review of its PR then asked for two fixes, paid in the entry: the + // checked block's transition line gains its insert guard (`previous != null && `, +20) and + // the sentence on a condition that cannot evaluate names the hook again (+7), against one + // blank line and one comma (-2). The file is 24377 bytes (24350 priced) -> 8999 (8972 + // priced) -> 2243 tokens, pinned AT the measurement; the sum of all ceilings falls by the + // same 3845. + // Authority: the ruling of record that orders the entry file down to router size, decision + // record #34691 S3 = A. + // ceil(($(wc -c < skills/objectstack-formula/SKILL.md) - 27) / 4) == ceil(8972 / 4) + ['skills/objectstack-formula/SKILL.md', 2243], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997), then +82 (was 6008), then -2 (was 6090), then -3845 (was 6088) // 6333 -> 6315: the top-level group list gains `packages` (`name` / `description` by // `manifest.id`, the `os lint` warning `i18n/missing-package` and what clears it), and the // `_relatedLists` row's remedy names both routes under a `.custom` arrangement (the owner's diff --git a/skills/objectstack-formula/SKILL.md b/skills/objectstack-formula/SKILL.md index 4794b89d9a5..84ad622c4ed 100644 --- a/skills/objectstack-formula/SKILL.md +++ b/skills/objectstack-formula/SKILL.md @@ -18,468 +18,118 @@ metadata: # Expressions (CEL) — ObjectStack Formula Protocol -ObjectStack has **one** expression language across every domain that needs -computation or boolean predicates: **CEL** (Google Common Expression -Language). - -> **Predicates / formulas are bare CEL — never wrap field references in `{…}` -> braces.** The #1 authoring mistake is a condition like -> `{record.rating} >= 4`: in CEL, `{…}` is a **map literal**, so it is a parse -> error. Write bare CEL: `record.rating >= 4`. Braces are *only* for `{{ … }}` -> text templates (see Cron and template surfaces). - ---- - -## Skill Boundaries - -| Need | Use instead | -|:---|:---| -| Define a `type: 'formula'` field | objectstack-data (and embed CEL via `F\`...\``) | -| Define seed records | objectstack-data (use `cel\`...\`` for dynamic dates) | -| Author flow / automation step | objectstack-automation (use `P\`...\`` for `condition`) | -| Author L2 hook body (TS code) | objectstack-data | -| Cron schedule | objectstack-automation | -| SQL fragment | driver-native; not unified into the expression registry | - ---- - -## Core contract - -Every expression in metadata is the same envelope — `dialect` plus `source`, -with optional `ast` and `meta` — declared as `Expression` / `ExpressionInput` in -`shared/expression.zod.ts`. **Three registered dialects**: - -| Dialect | Engine | Purpose | Helper | Example | -|:-----------|:-----------------------|:--------------------------------------------------|:--------------|:---------------------------------------| -| `cel` | `@marcbachmann/cel-js` | Computed values + boolean predicates | `` cel`...` `` / `` F`...` `` / `` P`...` `` | `` cel`record.amount * 1.1` `` | -| `cron` | built-in validator | Recurring schedules | `` cron`...` `` | `` cron`0 6 * * MON` `` | -| `template` | built-in interpolator | `{{path}}` text interpolation (notif/prompt/title) | `` tmpl`...` `` | `` tmpl`Hello {{record.first_name}}` ``| - -There is **no `js` dialect** — it was retired. Procedural JavaScript is -the L2 `ScriptBody { language: 'js' }` authoring surface (hook bodies, mapping -transforms — see objectstack-data), not an expression dialect. - -> **AI authors:** when emitting structured-output JSON for metadata, always -> emit the full envelope `{ dialect, source }` — never a bare string. - ---- - -## CEL syntax cheat-sheet - -| Concept | CEL | -|:---|:---| -| Current record field | `record.first_name` | -| Previous record (update hooks, validation rules) | `previous.status` — §5 | -| Master-detail line item's header | `parent.status` — cell `readonlyWhen` / `requiredWhen` | -| Metadata-editing form row | `data` — the row under edit, repeater rows included | -| Hook input payload | `input.amount` | -| Identity context | `os.user.id`, `os.org.id`, `os.org.tier`, `os.env` | -| Equality | `==` / `!=` | -| Logical | `&&` / `\|\|` / `!` | -| Ternary | `cond ? a : b` | -| String literal | `'abc'` — CEL parses `"abc"` too | -| Membership | `record.region in ['us', 'eu']` | -| Key existence (NOT null-safety) | `has(record.foo)` | -| Null check | `record.foo == null` or `isBlank(record.foo)` | - -**`==` / `!=` between a list field and a scalar literal is refused** (`list-equality`, "list compared -with a scalar": one constant on every row) — `multiselect` / `checkboxes` / `tags`, or `select` / -`radio` / `lookup` / `user` / `file` / `image` with `multiple: true`. Test membership, null-guarded -(`in` faults on `null`) and parenthesised, per site — the `==` rewrite, then the `!=` one: - -```text -record.tags == 'vip' # REFUSED -# evaluated as CEL; has() covers a sparse action row and a null `previous` -(has(record.tags) && record.tags != null && 'vip' in record.tags) -(!has(record.tags) || record.tags == null || !('vip' in record.tags)) -# bare name in a flow condition (has() takes no bare name) -(tags != null && 'vip' in tags) -(tags == null || !('vip' in tags)) -# SharingRule `condition`: compiled to a query filter, where has() and a literal-first `in` do not lower -(record.tags != null && record.tags.contains('vip')) -(record.tags == null || !record.tags.contains('vip')) -``` - -The org context is `{ id, tier }` — there is no `os.org.slug` or `os.org.name`. -The evaluator also binds the current user as `current_user` (alias `user`) per -ADR-0068 — spec field docs write predicates like `current_user.positions`. - -### `has()` is NOT a null check - -Every server-evaluated predicate — validation rules, `requiredWhen`, option -`visibleWhen`, `readonlyWhen`, hook `condition`, the flow trigger record — -reads a `record` (and, where §5 binds it, a `previous`) that is **total over -the object's declared fields**: a declared column the driver never returned -reads as `null`, not as a fault. There `has(record.)` and -`has(previous.)` are uniformly `true`, and `!= null` is the -whole guard. The idiom that reads like a guard is not one: - -```text -# WRONG — both has() calls are true on a NULL row, so this reaches `null < null`, -# CEL has no overload, the predicate aborts and the write is rejected. -has(record.start_date) && has(record.end_date) && record.end_date < record.start_date - -# RIGHT -record.start_date != null && record.end_date != null && record.end_date < record.start_date -``` - -**This is a publish-time rejection, not advice.** `os build` / -`os validate` / `os lint` and the runtime publish gate reject any validation-rule -or hook predicate — and a record-triggered flow's (`triggerType: 'record-*'`) -start `config.condition`, edge `condition` (nested regions too) or `decision` -branch `expression` — that applies an ordering (`< <= > >=`) or arithmetic -(`+ - * / %`) operator to a **declared nullable** field — no `required: true`, -no `defaultValue`, no default option, not a `count` / `sum` roll-up (empty reads -`0`; `min` / `max` / `avg` stay nullable) — unless an explicit `!= null` / `== null` / -`!isBlank()` test dominates it in the same boolean branch. `has()` deliberately -does not satisfy that gate. `has()` over an **undeclared** key stays legal: that -is its use there — telling "absent from this PATCH" apart from "explicitly null". - -**The exception: action `visible` / `disabled` are client-side and sparse.** -They bind the row the client already holds, and that row — a list row -above all — lacks a key when the column is outside the view's projection, when -field-level security refuses it, or when it was never written (the mongo and -memory drivers). -Reading an absent key faults `No such key`: a `visible` predicate hides the -action, a `disabled` one leaves it refused, silently either way. -There the guard is `has(record.x) && record.x != null`; `has()` alone is enough -beside a literal `==` / `!=`; a nested path takes one `has()` per segment: - -```text -has(record.status) && record.status != 'resolved' -has(record.amount) && record.amount != null && record.amount > 1000 -has(record.viewer) && has(record.viewer.can_approve) && record.viewer.can_approve == true -``` - ---- - -## ObjectStack CEL standard library - -Registered automatically by `@objectstack/formula`, which ships `dist` only. Its exported -`CEL_STDLIB_FUNCTIONS` is the advertised bare-callable subset, pinned by two -tests: every entry resolves at runtime, and this table documents them all. - -**Dates** - -| Function | Returns | Notes | -|:---|:---|:---| -| `now()` | timestamp | Current instant. Pinned per evaluation run; deterministic in build | -| `today()` | timestamp | Reference-timezone **calendar day**, expressed as **UTC midnight** (not plain UTC start-of-day) | -| `daysFromNow(n)` | timestamp | Calendar-day: `today()` + `n` days, at **UTC midnight** (never carries time-of-day) | -| `daysAgo(n)` | timestamp | Calendar-day: `today()` − `n` days, at **UTC midnight** | -| `daysBetween(a, b)` | int | Whole days from `a` to `b` (negative if `b` precedes `a`). `daysBetween(today(), record.due)` = days remaining | -| `addDays(d, n)` | timestamp | Shift **any** date by `n` days (negative ok). `addDays(record.last_service, record.cycle_days)` = next due date | -| `addMonths(d, n)` | timestamp | Shift **any** date by `n` months; clamps to month-end (`addMonths(date('2026-01-31'), 1)` → Feb 28) | -| `date(s)` / `datetime(s)` | timestamp | Parse an ISO date / date-time string to a timestamp | -| `isoDate(t)` / `isoDatetime(t)` | string | Timestamp to UTC ISO text, `2026-10-08` / `2026-10-08T17:55:06.123Z` | - -> **A `date` / `datetime` field is its ISO text.** The build refuses it in a -> timestamp-only call or method (`date-text-call`); wrap it in `date()` first: -> `isoDate(date(record.start_at))`, `date(record.start_date).getFullYear()`. -> `+` with text and ordering against a text literal take the text as is. - -| Want | The build refuses `end - start`, `date + n`, `today() + 30` (they read `null` / `{}`); write | -|:---|:---| -| Inclusive span | `daysBetween(record.start_date, record.end_date) + 1` | -| Shift a date | `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` | -| Tenure in years | `daysBetween(record.hire_date, today()) / 365` | -| Hours between | `double((datetime(record.end_at) - datetime(record.start_at)).getMinutes()) / 60.0` | -| Sub-day offset | `now() + duration("3h")` | - -**Working days** (the organization's working calendar, holidays and make-up days included): -`addWorkingDays(d, n[, code])` is the day `n` working days after `d` (`d` not counted); -`workingDaysBetween(a, b[, code])` its inverse (`b` counted); `addWorkingHours(t, h[, code])` the -instant `h` working hours after `t`. No `code`: the default calendar; a `code` is a quoted literal. -Only in a formula or a stored field's `expression` (refused in rules, flows, defaults, seeds and -filters): to filter, store the due time in a `datetime` field. No default calendar, or a count past -its maintained span, reads null; a stored due time is then blank until the record's next write. - -**Numbers** - -| Function | Returns | Notes | -|:---|:---|:---| -| `abs(x)` | double | Absolute value | -| `round(x)` | int | Round to the nearest integer | -| `floor(x)` / `ceil(x)` | int | Round toward −∞ / +∞ (`floor(-1.2)` = −2, not −1) | -| `min(a, b)` / `max(a, b)` | dyn | Smaller / larger operand (numeric comparison) | -| `rmbUpper(x)` | string | Amount in Chinese capitals, rounded to 分: `rmbUpper(10500.5)` = `壹万零伍佰元伍角`; `''` for null | - -**Strings** - -| Function | Returns | Notes | -|:---|:---|:---| -| `upper(s)` / `lower(s)` | string | Case conversion | -| `trim(s)` | string | Strip surrounding whitespace (`''` for null) | -| `contains(s, sub)` | bool | Substring test | -| `startsWith(s, p)` / `endsWith(s, p)` | bool | Prefix / suffix test | -| `matches(s, re)` | bool | Regex test | -| `joinNonEmpty(list, sep)` | string | Join, dropping null/empty entries | - -**Collections / null-ish** - -| Function | Returns | Notes | -|:---|:---|:---| -| `isBlank(v)` | bool | true for `null`, `undefined`, `''`, `[]` | -| `isEmpty(v)` | bool | true for `null`, `undefined`, empty string / list / map | -| `coalesce(v, fallback)` | dyn | `v` when non-null, else `fallback` | -| `len(v)` | int | Length of a string / list / map | - -**Options** - -| Function | Returns | Notes | -|:---|:---|:---| -| `label(record.f)` | string | A select value's option label in the reader's locale: `'v' + string(record.version_no) + ' · ' + label(record.kind)` reads `v2 · 清稿` (zh-CN), `v2 · Clean` (en-US). Only `record.`; `''` for null or an empty selection. A multi-select (`multiple: true`) reads each selected label in stored order, joined with `, `. A stored (non-formula) field stores the declared label. Formula fields only: in a predicate (validation, visibility, hook) it faults, so compare the stored value | - -Plus CEL built-ins: `has(x)`, `size(x)`, `int(x)`, `string(x)`, `bool(x)`, -`double(x)`, `timestamp(s)` (a full ISO instant only; over a `date` field write -`isoDate(addDays(record.d, n))`, never `+ duration(…)`), `duration(s)`. - -> Receiver methods (`s.split(',')`, -> `list.map(...)`) are called on a value, never bare, and are not in this table; -> four bare primitives (`bytes`, `dyn`, `type`, `uint`) resolve but are withheld -> from the catalogue by an authoring decision — don't reach for them. An UNKNOWN -> function — `PRIOR()`, a legacy `ISBLANK()`, a typo'd `isBlnk()` — **fails -> `os build`** with a "no matching overload" type error, rather than silently -> no-op'ing the predicate at run time. Use `previous.x`, not `PRIOR()`; more in the table below. - ---- - -## Mandatory patterns for AI emission - -The ❌ blocks are wrong on purpose, so `check:skill-examples` skips them. - -### 1. Computed text formula — always coalesce nullable operands - -✅ **Correct** +Every expression in metadata is one envelope, `{ dialect, source }` (`Expression`, +`shared/expression.zod.ts`); a computed value or a condition is **CEL**. Dialects: `cel`, +`cron`, `template`; there is no `js`. + +## First checks + +1. **Version.** Where the installed `@objectstack/spec` version differs from this skill's + `compatibility` line, the installed contract is right. +2. **Read first**: the object's declared fields (every `record.` must be one, and whether + it is nullable decides its guard) and the contract of the key that takes the expression + ([references/_index.md](./references/_index.md)). Never recall a function: the list below + is the advertised bare-callable set; an unknown name fails `os build`. +3. **Bare CEL under a tag**: `F` for a formula field's `expression`, `P` for a predicate, + `cel` for a seed or default value. Never wrap a field reference in braces: `{…}` is a CEL + map literal, a parse error. Structured-output JSON carries the envelope, never a bare + string; a bare-string `defaultValue` is a literal. Salesforce spellings fail the build: + `AND` / `OR` / `NOT` are `&&` / `||` / `!`, `=` / `<>` are `==` / `!=`, `ISBLANK(x)` is + `isBlank(record.x)`, `OLD.x` / `NEW.x` are `previous.x` / `record.x`, a bare field is + `record.field`. +4. **Verify**: `os validate` and `os build` judge every expression in the stack; the + `validate_expression` agent tool judges one before it is saved. ```ts -import { F } from '@objectstack/spec'; -F`coalesce(record.salutation, '') + ' ' - + coalesce(record.first_name, '') + ' ' - + coalesce(record.last_name, '')` -``` - -❌ **Wrong** (CEL throws on null + string) - -```ts -F`record.salutation + ' ' + record.first_name + ' ' + record.last_name` -``` - -### 2. Conditional numeric formula — guard divisor - -✅ +import { F, P, cel } from '@objectstack/spec'; - -```ts -import { F } from '@objectstack/spec'; -F`coalesce(record.cost, 0) > 0 - ? ((coalesce(record.revenue, 0) - record.cost) * 100) / record.cost - : 0.0` -``` - -### 3. Predicate (field rules / visibility / validation) - -✅ - - -```ts -import { P } from '@objectstack/spec'; - -P`record.status == 'qualified'`; +F`coalesce(record.first_name, '') + ' ' + coalesce(record.last_name, '')`; // null + text throws +F`coalesce(record.cost, 0) > 0 ? ((coalesce(record.revenue, 0) - record.cost) * 100) / record.cost : 0.0`; +F`isoDate(date(record.start_at))`; +F`isoDate(addDays(record.due_date, 7))`; +F`'v' + string(record.version_no) + ' · ' + label(record.kind)`; P`record.amount != null && record.amount > 10000 && record.region in ['us', 'eu']`; -P`!isBlank(record.po_number)`; -``` - -Conditional requiredness: [objectstack-data](../objectstack-data/SKILL.md#conditional-field-rules). -Salesforce-flavor (`AND`, `IN (…)`, `NOT(ISBLANK(x))`) fails CEL compile: see the translation table. - -### 4. Dynamic seed value — use `cel\`\`` not `new Date()` - -✅ - - -```ts -import { cel } from '@objectstack/spec'; -const seed = { close_date: cel`daysFromNow(45)`, created_at: cel`now()` }; -``` - -❌ Compile-time evaluation — every customer gets the package author's clock: - -```ts -{ close_date: new Date(Date.now() + 45 * 86400000), created_at: new Date() } +P`previous != null && previous.status != 'escalated' && record.status == 'escalated'`; +const seed = { close_date: cel`daysFromNow(45)` }; ``` -This is the determinism gate: two consecutive `os build` runs produce -byte-identical `dist/objectstack.json` only when every dynamic seed value is -`` cel`...` `` — no `new Date()`, no `Date.now()`, no random or otherwise -impure source. - -### 5. Update hook condition — `previous` vs `record` - -✅ - - -```ts -import { P } from '@objectstack/spec'; -P`previous.status != 'escalated' && record.status == 'escalated'` -``` - -`record` is the record's **state**, not this write's diff: stored row ⊕ -payload, so `record.status == 'escalated'` is true on *every* update of an -already-escalated record. Comparing against `previous` is the only way to say -"just became". - -**Where `previous` is bound, and where it is not:** - -| Surface / event | `previous` | -|:---|:---| -| Update hook `condition` (single-record write), validation rule on update | the stored pre-write row | -| Insert events (`beforeInsert` / `afterInsert`), validation rule on insert | **`null`** — `previous == null \|\| …` judges an insert, `previous != null && …` skips one; a column read off it (`previous.x`) has no value and faults | -| A write to an existing row whose prior state is not in hand | **unbound** — fails closed, so `previous == null` never reads an update as an insert | -| **`after*` hook `condition` / record-change flow trigger on a predicate (`multi: true`) write** | **that row's pre-write row** — a bulk write fires after-hooks once PER MATCHED ROW | -| Validation rule on a predicate bulk update | that row's pre-write row — per row | -| `before*` hook `condition` on a predicate (`multi: true`) write | **that row's pre-write row** — `beforeUpdate` / `beforeDelete` dispatch once PER MATCHED ROW too, each on a single-record-shaped context whose `input.id` names the row (ADR-0058 Addendum II, D1/D2); `record` is that row's state, stored ⊕ payload, as on any update. Only the *payload* stays batch-scoped — see below the table | - -⚠️ **An unevaluable condition ABORTS the operation.** A column read off -`previous` on an insert — like -a typo'd key (`record.stauts`), a retired field, or a comparison CEL has no -overload for — does **not** degrade to "the hook did not fire": it **fails the -write**, with an error naming the hook and the key — `before*` and `after*` -alike, with no `onError` escape (`onError` governs a handler that throws, and -the condition is evaluated before any handler runs). - -**A transition condition needs no special handling for bulk writes.** -Write it once, on a `before*` or an `after*` event, and it means the same thing -whether the write carries an id or a predicate. - -A predicate (`multi: true`) write is N record changes, so every record-scoped -declaration on it is evaluated **per row** — `previous` is that row's own -pre-write state, `record` its real state, not the bare payload (ADR-0058, -bulk-write Addenda I and II). `before*` is no exception to the *condition*; the asymmetry is what a -`before*` handler WRITES: one `updateMany` takes one SET clause, so every row's -dispatch carries the one payload and a rewrite made on any row applies to every -matched row (D3). A rewrite *decided* per row must assign the same key set on -every row, in place — assigned onto the payload object, never a replaced one — -because the engine records the keys each row's chain wrote and refuses the -batch whole, before any write, when two rows disagree -(`MULTI_UPDATE_HOOK_KEY_DIVERGENCE`, status 400; ADR-0058 Amendment II.3). - -Above 10 000 matched rows the platform refuses a predicate write on an object -with per-row hooks in either phase — one ceiling for `before*` and `after*`, -checked before the first dispatch (ADR-0058 Addendum II, D6) — rather than fan -out that many handler runs inside one write; paginate the write. - ---- - -## Mechanical translation table (legacy → CEL) - -When migrating Salesforce-flavor metadata, apply these rules in order: - -| Legacy | CEL | -|:---|:---| -| `bare_field` | `record.bare_field` — except in a flow condition, below | -| `OLD.x` | `previous.x` | -| `NEW.x` | `record.x` | -| `=` (comparison) | `==` | -| `<>` | `!=` | -| `AND` | `&&` | -| `OR` | `\|\|` | -| `NOT(x)` | `!x` | -| `IF(c, a, b)` | `c ? a : b` | -| `ISBLANK(x)` | `isBlank(record.x)` | -| `CONCAT(a, b)` | `coalesce(a, '') + coalesce(b, '')` | -| `TODAY()` / `NOW()` | `today()` / `now()` | -| `IN (a, b, c)` | `in [a, b, c]` | -| `ISCHANGED(x)` | `previous.x != record.x` | -| `MONTH_DIFF`, `MID`, `LEFT`, `RIGHT`, `SUBSTITUTE` | _not in stdlib — propose addition_ | - -> ⚠️ **Flow conditions are the exception to row 1.** The engine spreads the -> trigger record's fields, nulls included, to top level wherever no flow variable -> or node id holds the name, so in a start, edge or `decision` condition a bare -> `budget` IS `record.budget`: `os validate` judges either spelling (bare names -> only while the flow's bound names are provable) and a guard on one guards both. -> What the start condition proves non-null is presumed at every edge and branch; -> spell that guard `record.budget != null` — the runtime publish gate judges the -> written flow alone and resolves no bare name. An unguarded null fails the -> **run** at that condition; the write that fired it still lands. - ---- - -## Surfaces that take an Expression - -All of these spec fields accept `string | Expression`. The build normalizes -to the envelope. - -### CEL surfaces (predicates + computed values) - -| Surface | Field | Dialect | -|:---|:---|:---| -| `Field` | `expression` (when `type: 'formula'`) | cel | -| `Field` | `visibleWhen` / `readonlyWhen` / `requiredWhen` | cel | -| `View` / `Page` | `visibleWhen` (form section/field, page component) | cel | -| `Field` | `defaultValue` (envelope only; bare string = literal) | cel | -| `ConditionalValidation` | `when` | cel | -| `Action` | `visible` / `disabled` — client-side, sparse | cel (or boolean) | -| `Hook` | `condition` | cel | -| `SharingRule` | `condition` | cel | -| `Flow.decision` | `expression` / edge `condition` | cel (use `vars..`) | -| `Seed.records[*]` | any value | cel (via `cel\`\``) | -| `audit` / `metrics` / `tracing` | `condition` / `successCriteria` | structured \| cel | - -⚠️ **A `formula` field is virtual — no driver materialises a column for it**, so -all three query axes refuse one at both doors: `where` and `searchableFields` -answer `400 INVALID_FIELD`, `orderBy` answers `400 INVALID_SORT`. It still READS -correctly, which is why refusing matters: a `where` on one used to answer -`200` with zero rows. Denormalise onto a stored field and query that. `summary` -and `autonumber` have real columns and need no such care. - -⚠️ **A form-view `visibleWhen` is the one predicate here that faults OPEN.** It -is CLIENT-SIDE only, and an unbound root falls back to `true`, so the control -renders for everyone — never use one as access control; that is permission-set -field-level security. Everywhere else on this table the opposite holds: an -unevaluable `Hook` `condition` or validation predicate **aborts the write** -(§5); a `SharingRule` `condition` that does not lower to a filter fails the -build, and at runtime the rule is skipped and grants nothing (one WARN). - -View list filters are **not** a CEL surface — they are structured JSON filter -rules (`ViewFilterRuleSchema`), so do not emit CEL there. For "last 30 days" -style windows use the **date macro tokens** (`data/date-macros.zod.ts`) — -objectstack-query `rules/filters.md` has the token list. - -### Cron and template surfaces - -Neither dialect is CEL; both take -a bare string (auto-wrapped) or their helper, and read the same variable scope. - -| Dialect | Helper | Grammar | Carriers | -|:---|:---|:---|:---| -| `cron` | `` cron`0 6 * * MON` `` | 5- or 6-field cron, or one of `@yearly` `@annually` `@monthly` `@weekly` `@daily` `@hourly` `@reboot` | `Job.schedule.expression` (canonical) | -| `template` | `` tmpl`Hello {{ record.first_name }}` `` | `{{ path }}` or `{{ path \| formatter[:arg] }}` — double braces only, no conditionals; the formatter whitelist is `TEMPLATE_FORMATTERS`, exported from `@objectstack/formula` | `system/email-template` `subject` / `bodyHtml` / `bodyText`, `ai/model-registry` `promptTemplate.system` / `.user`, `Object.titleFormat` (a save and `os validate` refuse it; move it to `nameField`, ADR-0079) | - -Missing template paths render as the empty string. Move logic into a CEL field. -A `currency` argument is a -literal code (`currency:EUR`); only an email template may read it from the send's -data instead, `{{ amount | currency:@currency_code }}`. - ---- - -## Verify your work - -A malformed expression does not fail silently (ADR-0032): `os validate` and -`os build` run the shared validator over every formula and predicate in the -stack — CEL syntax **plus** `record.` existence on the target object — -and fail non-zero with a located, did-you-mean message, while at runtime the -engine **throws** and the rule fails loudly. Use `os validate` as the fast -post-edit check (no artifact emitted; `npm run validate` in a scaffolded -project). To check a *single* expression before saving it, call the -`validate_expression` agent tool, which runs the same validator inline. - ---- - -## See also - -- [references/_index.md](./references/_index.md) — the Zod schemas behind every - surface above -- `node_modules/@objectstack/spec/src/shared/expression.zod.ts` — `Expression`, - `ExpressionInput`, `cel` / `F` / `P` +## Scope and functions + +Roots: `record`, `previous`, `input` (hook payload), `parent` (a line item's header), `data` (a +metadata-form row), `current_user` (alias `user`), `os.user.id`, `os.org.id`, `os.org.tier` (no +`slug` or `name`), `os.env`; in a flow, `vars..`. + +- Dates: `now()`, `today()`, `daysFromNow(n)`, `daysAgo(n)`, `daysBetween(a, b)`, `addDays(d, n)`, + `addMonths(d, n)`, `date(s)`, `datetime(s)`, `isoDate(t)`, `isoDatetime(t)`, + `addWorkingDays(d, n[, code])`, `workingDaysBetween(a, b[, code])`, `addWorkingHours(t, h[, code])` +- Numbers: `abs(x)`, `round(x)`, `floor(x)`, `ceil(x)`, `min(a, b)`, `max(a, b)`, `rmbUpper(x)` +- Text: `upper(s)`, `lower(s)`, `trim(s)`, `contains(s, sub)`, `startsWith(s, p)`, `endsWith(s, p)`, + `matches(s, re)`, `joinNonEmpty(list, sep)` +- Null-ish: `isBlank(v)`, `isEmpty(v)`, `coalesce(v, fallback)`, `len(v)`. Options: `label(record.f)` +- CEL built-ins: `has(x)`, `size(x)`, `int(x)`, `string(x)`, `bool(x)`, `double(x)`, + `timestamp(s)`, `duration(s)` + +## Traps + +1. **`has()` is not a null check.** A server-evaluated predicate (validation, `requiredWhen`, + `readonlyWhen`, option `visibleWhen`, hook `condition`, a record-triggered flow) reads a + record total over the declared fields: an empty one is `null`, `has(record.f)` is always + true, and the guard is `!= null` or `!isBlank()`: + `record.start_date != null && record.end_date != null && record.end_date < record.start_date`. + The build refuses a validation, hook or record-triggered flow predicate with an ordering or + arithmetic operator on a nullable field (no `required`, no default) and no such test in the + same branch. In a flow condition a bare `budget` is `record.budget` unless a flow variable + or node id holds it; spell the guard `record.budget != null && record.budget > 200000`, or + a null fails the run after the write that fired it has landed. +2. **Action `visible` / `disabled` are the exception.** They read the row the client holds, + where a key can be absent and reading it faults: the action is hidden, or left refused, + silently. Guard `has(record.x) && record.x != null`, one `has()` per segment of a nested + path; `has()` alone is enough beside a literal `==` / `!=`. +3. **A transition compares `previous`.** `record` is the state after the write, true on every + later update too. `previous` is that row's pre-write row, per row on a bulk + (`multi: true`) write (hooks in both phases, validation, record-change triggers); on + insert it is `null`, so `previous.x` faults: write `previous != null && …`. A hook + `condition` that cannot evaluate (a typo'd key, a read off a null `previous`) ABORTS the + write with no `onError` escape. Above 10 000 matched rows a predicate write on an object + with per-row hooks is refused: paginate. +4. **A list field never `==` a scalar.** `record.tags == 'vip'` is refused (`list-equality`) for + `multiselect` / `checkboxes` / `tags` and any `multiple: true` field. Test membership, + null-guarded and parenthesised, per site: + - evaluated as CEL (hook, validation, visibility): `(has(record.tags) && record.tags != null && 'vip' in record.tags)` + - a flow condition's bare name: `(tags != null && 'vip' in tags)` + - a `SharingRule` `condition`, compiled to a query filter where `has()` and a literal-first + `in` do not lower (the build fails): `(record.tags != null && record.tags.contains('vip'))` +5. **A `date` / `datetime` field is its ISO text.** The build refuses it in a timestamp-only + call or method (`date-text-call`); wrap it in `date()` first, as above and in + `date(record.start_date).getFullYear()`. `daysBetween`, `addDays` and `addMonths` take the + field as is. `timestamp(s)` parses a full instant only, never a `date` field. The build + refuses date arithmetic (`end - start`, `date + n`): days remaining is + `daysBetween(today(), record.due)`, `n` days ahead `daysFromNow(n)`, hours + `double((datetime(record.end_at) - datetime(record.start_at)).getMinutes()) / 60.0`, a + sub-day offset `now() + duration("3h")`. +6. **`label()` and the working-day functions are for a formula or a stored field's + `expression`.** `label(record.kind)` reads a select value's option label in the reader's + locale, `''` for null; on a `multiple: true` select, every selected label in stored order + joined with `, `; a stored field stores the declared label. In a predicate it faults: + compare the stored value. The working-day functions (calendar `code` a quoted literal) are + refused anywhere else; with no default calendar, or a count past its maintained span, they + read null. +7. **A dynamic seed value is `` cel`…` ``, never a JavaScript date**: that is evaluated at + build, so every customer gets the author's clock and two builds differ. +8. **A `template` is not CEL.** It is `{{ path }}` or `{{ path | formatter[:arg] }}`: double + braces only, no conditionals, a missing path renders empty; the formatters are + `TEMPLATE_FORMATTERS` (`@objectstack/formula`). `currency` takes a literal code + (`currency:EUR`); only an email template may read it from the send's data, + `{{ amount | currency:@currency_code }}`. + +## Where to go + +| Need | Open | +|:-|:-| +| The envelope and helpers; which keys take an expression | `node_modules/@objectstack/spec/src/shared/expression.zod.ts`, then the key's own schema | +| What a function returns, the cookbook, working days, the legacy table, formatters | https://objectstack.ai/docs/data-modeling/formulas | +| Filter, sort or search: a `formula` field is virtual and all three refuse it (`400`); a view filter is a structured rule or date macro, not CEL | **objectstack-query** | +| Fields, [conditional rules](../objectstack-data/SKILL.md#conditional-field-rules), validation, hooks (per-row rewrites), seeds, sharing | **objectstack-data** | +| Flow conditions, schedules | **objectstack-automation** | +| View and action predicates; a form-view `visibleWhen` is client-side and faults OPEN (it renders for everyone), never access control | **objectstack-ui** |