From 75b00bcc2d175f197e99bfeb1f25dca1cf8dc235 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 14:27:50 +0000 Subject: [PATCH 1/8] docs(skills): the objectstack-formula entry file becomes a router The entry keeps three first checks, one type-checked block of the three tags, the roots and the advertised function names, eight traps and a routing table. The rest is cut behind a pointer to the contract, to os validate / os build, or to the published formulas page. The ratchet row follows the measurement down: 6088 -> 2242. Claude-Session: https://claude.ai/code/session_01ADHkmSM46qymk97AyqPzoS Co-authored-by: Claude --- scripts/check-skills-token-ratchet.mjs | 15 +- skills/objectstack-formula/SKILL.md | 563 +++++-------------------- 2 files changed, 119 insertions(+), 459 deletions(-) diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 95419ecaa85..84425b48fc3 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -974,7 +974,20 @@ 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 -> 2242 (#34770): the entry becomes a router. It keeps three 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 file is 24377 bytes (24350 priced) -> + // 8995 (8968 priced) -> 2242 tokens, pinned AT the measurement; the sum of all ceilings falls + // by the same 3846. + // 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(8968 / 4) + ['skills/objectstack-formula/SKILL.md', 2242], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997), then +82 (was 6008), then -2 (was 6090), then -3846 (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..44fceaa7a63 100644 --- a/skills/objectstack-formula/SKILL.md +++ b/skills/objectstack-formula/SKILL.md @@ -16,470 +16,117 @@ metadata: tags: cel, formula, predicate, condition, validation, visibility, seed-dynamic --- -# 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** - - -```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 - -✅ - - -```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) +# Expressions (CEL) — ObjectStack Formula Protocol -✅ +Every computed value and condition in metadata is **CEL** in one envelope, +`{ dialect, source }` (`Expression`, `shared/expression.zod.ts`). Dialects: `cel`, `cron`, +`template`; there is no `js` (a hook body is objectstack-data). + +## First checks + +1. **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, and an unknown name fails `os build`. +2. **Bare CEL under a tag.** 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 `==` / `!=`, `IF` is `c ? a : b`, `ISBLANK(x)` is + `isBlank(record.x)`, `OLD.x` / `NEW.x` are `previous.x` / `record.x`, a bare field is + `record.field`. +3. **Verify**: `os validate` and `os build` judge every expression in the stack (syntax, field + existence, function names, the refusals below); the `validate_expression` agent tool judges + one before it is saved. ```ts -import { P } from '@objectstack/spec'; +import { F, P, cel } 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`; P`record.amount != null && record.amount > 10000 && record.region in ['us', 'eu']`; -P`!isBlank(record.po_number)`; +P`previous.status != 'escalated' && record.status == 'escalated'`; +const seed = { close_date: cel`daysFromNow(45)` }; ``` -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() } -``` - -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 rule, `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`; spell the guard + `record.budget != null && record.budget > 200000`, or a null fails the run after the write + that fired it has landed. +2. **Client-side predicates are the exception.** Action `visible` / `disabled` read the row the + client holds, where a key can be absent (outside the projection, behind field-level + security) 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 `==` / `!=`. A form-view `visibleWhen` is + client-side too and faults OPEN (the control renders for everyone): never access control. +3. **A transition compares `previous`.** `record` is the state after the write (stored row plus + payload), true on every later update too. `previous` is that row's pre-write row, per row + on a bulk (`multi: true`) write too (hooks in both phases, validation, record-change + triggers); on insert it is `null`, so `previous.x` faults: write `previous != null && …`. A + 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.** `daysBetween`, `addDays` and `addMonths` take + the field as is; `isoDate`, `isoDatetime` and timestamp methods take a timestamp, so the + build refuses the bare field there (`date-text-call`): `isoDate(date(record.start_at))`, + `date(record.start_date).getFullYear()`. `timestamp(s)` parses a full instant only: shift a + `date` field with `isoDate(addDays(record.d, 7))`. The build also refuses date arithmetic + (`end - start`, `date + n`): days remaining is `daysBetween(today(), record.due)`, a day + 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 (`'v' + string(record.version_no) + ' · ' + label(record.kind)`), `''` 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 clock value**: that is evaluated + at build, so every customer gets the author's clock and two builds differ. +8. **`template` and `cron` are not CEL.** A template 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 }}`. Cron is 5 or 6 fields, or an alias like `@daily`. + +## 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; view and action predicates | **objectstack-automation**; **objectstack-ui** | From b93fb9bf5a3c237ca8b50ed32f8b626f9e9630a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 14:34:54 +0000 Subject: [PATCH 2/8] docs(skills): the formula entry names which tag goes where and shows the date wraps as code The first head's eval round lost case 10: the answers gave the right formula and then quoted the refused form. The date trap reads as it did before (wrap in date() first), the wraps and the label formula are lines of the type-checked block, and first check 2 says which tag a formula, a predicate and a seed value take. Paid inside the entry; the row follows the measurement, 2242 -> 2237. Claude-Session: https://claude.ai/code/session_01ADHkmSM46qymk97AyqPzoS Co-authored-by: Claude --- scripts/check-skills-token-ratchet.mjs | 10 ++-- skills/objectstack-formula/SKILL.md | 68 ++++++++++++++------------ 2 files changed, 41 insertions(+), 37 deletions(-) diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 84425b48fc3..856b64dad22 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -974,7 +974,7 @@ 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. - // 6088 -> 2242 (#34770): the entry becomes a router. It keeps three first checks, one + // 6088 -> 2237 (#34770): the entry becomes a router. It keeps three 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 @@ -982,12 +982,12 @@ export const CEILINGS = new Map([ // 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 file is 24377 bytes (24350 priced) -> - // 8995 (8968 priced) -> 2242 tokens, pinned AT the measurement; the sum of all ceilings falls - // by the same 3846. + // 8972 (8945 priced) -> 2237 tokens, pinned AT the measurement; the sum of all ceilings falls + // by the same 3851. // 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(8968 / 4) - ['skills/objectstack-formula/SKILL.md', 2242], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997), then +82 (was 6008), then -2 (was 6090), then -3846 (was 6088) + // ceil(($(wc -c < skills/objectstack-formula/SKILL.md) - 27) / 4) == ceil(8945 / 4) + ['skills/objectstack-formula/SKILL.md', 2237], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997), then +82 (was 6008), then -2 (was 6090), then -3851 (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 44fceaa7a63..04a747066e8 100644 --- a/skills/objectstack-formula/SKILL.md +++ b/skills/objectstack-formula/SKILL.md @@ -29,15 +29,16 @@ Every computed value and condition in metadata is **CEL** in one envelope, 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, and an unknown name fails `os build`. -2. **Bare CEL under a tag.** 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 `==` / `!=`, `IF` is `c ? a : b`, `ISBLANK(x)` is +2. **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`. -3. **Verify**: `os validate` and `os build` judge every expression in the stack (syntax, field - existence, function names, the refusals below); the `validate_expression` agent tool judges - one before it is saved. +3. **Verify**: `os validate` and `os build` judge every expression in the stack (syntax, fields, + functions, the refusals below); the `validate_expression` agent tool judges one before it + is saved. ```ts @@ -45,6 +46,9 @@ import { F, P, cel } from '@objectstack/spec'; 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`previous.status != 'escalated' && record.status == 'escalated'`; const seed = { close_date: cel`daysFromNow(45)` }; @@ -79,17 +83,18 @@ metadata-form row), `current_user` (alias `user`), `os.user.id`, `os.org.id`, `o `record.budget != null && record.budget > 200000`, or a null fails the run after the write that fired it has landed. 2. **Client-side predicates are the exception.** Action `visible` / `disabled` read the row the - client holds, where a key can be absent (outside the projection, behind field-level - security) 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 `==` / `!=`. A form-view `visibleWhen` is - client-side too and faults OPEN (the control renders for everyone): never access control. -3. **A transition compares `previous`.** `record` is the state after the write (stored row plus - payload), true on every later update too. `previous` is that row's pre-write row, per row - on a bulk (`multi: true`) write too (hooks in both phases, validation, record-change - triggers); on insert it is `null`, so `previous.x` faults: write `previous != null && …`. A - 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. + 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 `==` / `!=`. A form-view + `visibleWhen` is client-side too and faults OPEN (the control renders for everyone): never + access control. +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 too (hooks in both phases, validation, record-change triggers); on + insert it is `null`, so `previous.x` faults: write `previous != null && …`. A 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: @@ -97,24 +102,23 @@ metadata-form row), `current_user` (alias `user`), `os.user.id`, `os.org.id`, `o - 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.** `daysBetween`, `addDays` and `addMonths` take - the field as is; `isoDate`, `isoDatetime` and timestamp methods take a timestamp, so the - build refuses the bare field there (`date-text-call`): `isoDate(date(record.start_at))`, - `date(record.start_date).getFullYear()`. `timestamp(s)` parses a full instant only: shift a - `date` field with `isoDate(addDays(record.d, 7))`. The build also refuses date arithmetic - (`end - start`, `date + n`): days remaining is `daysBetween(today(), record.due)`, a day - ahead `daysFromNow(n)`, hours +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 + also 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 (`'v' + string(record.version_no) + ' · ' + label(record.kind)`), `''` 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 clock value**: that is evaluated - at build, so every customer gets the author's clock and two builds differ. + 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. **`template` and `cron` are not CEL.** A template 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 From 9643441f5c7d0cfaa518e0c3ddcdd92cd3919d8f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 14:43:04 +0000 Subject: [PATCH 3/8] docs(skills): the formula entry gains the version check; its changeset records every cut First check 1 is the version check the other router entries open with, paid inside the entry by dropping the cron grammar sentence (the contract and the validator hold it) and two parentheticals. The row follows the measurement, 2237 -> 2238. The changeset lists what the entry keeps, what left and what answers it now, and every anchor that no longer exists. Claude-Session: https://claude.ai/code/session_01ADHkmSM46qymk97AyqPzoS Co-authored-by: Claude --- .changeset/34770-formula-skill-router.md | 23 ++++++++++++++++ scripts/check-skills-token-ratchet.mjs | 10 +++---- skills/objectstack-formula/SKILL.md | 35 ++++++++++++------------ 3 files changed, 46 insertions(+), 22 deletions(-) create mode 100644 .changeset/34770-formula-skill-router.md diff --git a/.changeset/34770-formula-skill-router.md b/.changeset/34770-formula-skill-router.md new file mode 100644 index 00000000000..ee040c2ef2c --- /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 137). 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`, and a form-view `visibleWhen` faults open; a transition compares `previous`, which is per row on a bulk write and `null` on insert, and a 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. + +**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 856b64dad22..86fe54a7814 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -974,7 +974,7 @@ 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. - // 6088 -> 2237 (#34770): the entry becomes a router. It keeps three first checks, one + // 6088 -> 2238 (#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 @@ -982,12 +982,12 @@ export const CEILINGS = new Map([ // 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 file is 24377 bytes (24350 priced) -> - // 8972 (8945 priced) -> 2237 tokens, pinned AT the measurement; the sum of all ceilings falls - // by the same 3851. + // 8977 (8950 priced) -> 2238 tokens, pinned AT the measurement; the sum of all ceilings falls + // by the same 3850. // 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(8945 / 4) - ['skills/objectstack-formula/SKILL.md', 2237], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997), then +82 (was 6008), then -2 (was 6090), then -3851 (was 6088) + // ceil(($(wc -c < skills/objectstack-formula/SKILL.md) - 27) / 4) == ceil(8950 / 4) + ['skills/objectstack-formula/SKILL.md', 2238], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997), then +82 (was 6008), then -2 (was 6090), then -3850 (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 04a747066e8..5f85fe433b2 100644 --- a/skills/objectstack-formula/SKILL.md +++ b/skills/objectstack-formula/SKILL.md @@ -19,26 +19,27 @@ metadata: # Expressions (CEL) — ObjectStack Formula Protocol -Every computed value and condition in metadata is **CEL** in one envelope, -`{ dialect, source }` (`Expression`, `shared/expression.zod.ts`). Dialects: `cel`, `cron`, -`template`; there is no `js` (a hook body is objectstack-data). +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. **Read first**: the object's declared fields (every `record.` must be one, and whether +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, and an unknown name fails `os build`. -2. **Bare CEL under a tag**: `F` for a formula field's `expression`, `P` for a predicate, +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`. -3. **Verify**: `os validate` and `os build` judge every expression in the stack (syntax, fields, - functions, the refusals below); the `validate_expression` agent tool judges one before it - is saved. +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 @@ -72,10 +73,10 @@ metadata-form row), `current_user` (alias `user`), `os.user.id`, `os.org.id`, `o ## Traps -1. **`has()` is not a null check.** A server-evaluated predicate (validation rule, `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()`: +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 @@ -119,11 +120,11 @@ metadata-form row), `current_user` (alias `user`), `os.user.id`, `os.org.id`, `o 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. **`template` and `cron` are not CEL.** A template 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 }}`. Cron is 5 or 6 fields, or an alias like `@daily`. +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 From 822cd547d1fcf1ff209faeece83b52f5523b76e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 15:28:34 +0000 Subject: [PATCH 4/8] docs(skills): the formula entry says when a flow condition's bare name is not the field A bare name in a flow condition reads the trigger record's field only where no flow variable or node id holds it, as the entry said before the cut. Paid inside the entry by five small trims; the row follows the measurement, 2238 -> 2243, and the file is 8998 bytes. Claude-Session: https://claude.ai/code/session_01ADHkmSM46qymk97AyqPzoS Co-authored-by: Claude --- scripts/check-skills-token-ratchet.mjs | 10 +++++----- skills/objectstack-formula/SKILL.md | 16 ++++++++-------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 86fe54a7814..3cea030001a 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -974,7 +974,7 @@ 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. - // 6088 -> 2238 (#34770): the entry becomes a router. It keeps four first checks, one + // 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 @@ -982,12 +982,12 @@ export const CEILINGS = new Map([ // 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 file is 24377 bytes (24350 priced) -> - // 8977 (8950 priced) -> 2238 tokens, pinned AT the measurement; the sum of all ceilings falls - // by the same 3850. + // 8998 (8971 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(8950 / 4) - ['skills/objectstack-formula/SKILL.md', 2238], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997), then +82 (was 6008), then -2 (was 6090), then -3850 (was 6088) + // ceil(($(wc -c < skills/objectstack-formula/SKILL.md) - 27) / 4) == ceil(8971 / 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 5f85fe433b2..ab2da5c3f50 100644 --- a/skills/objectstack-formula/SKILL.md +++ b/skills/objectstack-formula/SKILL.md @@ -30,7 +30,7 @@ Every expression in metadata is one envelope, `{ dialect, source }` (`Expression 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, and an unknown name fails `os build`. + 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 @@ -80,18 +80,18 @@ metadata-form row), `current_user` (alias `user`), `os.user.id`, `os.org.id`, `o `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`; spell the guard - `record.budget != null && record.budget > 200000`, or a null fails the run after the write - that fired it has landed. + 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. **Client-side predicates are the exception.** Action `visible` / `disabled` 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 `==` / `!=`. A form-view - `visibleWhen` is client-side too and faults OPEN (the control renders for everyone): never - access control. + `visibleWhen` is client-side too and faults OPEN (it renders for everyone): never access + control. 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 too (hooks in both phases, validation, record-change triggers); on + (`multi: true`) write (hooks in both phases, validation, record-change triggers); on insert it is `null`, so `previous.x` faults: write `previous != null && …`. A 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 @@ -107,7 +107,7 @@ metadata-form row), `current_user` (alias `user`), `os.user.id`, `os.org.id`, `o 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 - also refuses date arithmetic (`end - start`, `date + n`): days remaining is + 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")`. From 327903f60a9ac131794206bb07bf615ded2f8682 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 16:07:39 +0000 Subject: [PATCH 5/8] docs(skills): the formula entry keeps the has() guard to action predicates The final-head eval round showed an answer carrying the action guard over to a form-view visibleWhen, because one trap named both as client-side. The trap is about action visible / disabled alone again; the form-view fact (client-side, faults open, never access control) sits on the routing row that sends view predicates to objectstack-ui. The row follows the measurement, 2243 -> 2237; the file is 8974 bytes. Claude-Session: https://claude.ai/code/session_01ADHkmSM46qymk97AyqPzoS Co-authored-by: Claude --- scripts/check-skills-token-ratchet.mjs | 10 +++++----- skills/objectstack-formula/SKILL.md | 13 ++++++------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 3cea030001a..03ad89dcb10 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -974,7 +974,7 @@ 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. - // 6088 -> 2243 (#34770): the entry becomes a router. It keeps four first checks, one + // 6088 -> 2237 (#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 @@ -982,12 +982,12 @@ export const CEILINGS = new Map([ // 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 file is 24377 bytes (24350 priced) -> - // 8998 (8971 priced) -> 2243 tokens, pinned AT the measurement; the sum of all ceilings falls - // by the same 3845. + // 8974 (8947 priced) -> 2237 tokens, pinned AT the measurement; the sum of all ceilings falls + // by the same 3851. // 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(8971 / 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) + // ceil(($(wc -c < skills/objectstack-formula/SKILL.md) - 27) / 4) == ceil(8947 / 4) + ['skills/objectstack-formula/SKILL.md', 2237], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997), then +82 (was 6008), then -2 (was 6090), then -3851 (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 ab2da5c3f50..2a26e54598c 100644 --- a/skills/objectstack-formula/SKILL.md +++ b/skills/objectstack-formula/SKILL.md @@ -83,12 +83,10 @@ metadata-form row), `current_user` (alias `user`), `os.user.id`, `os.org.id`, `o 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. **Client-side predicates are the exception.** Action `visible` / `disabled` 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 `==` / `!=`. A form-view - `visibleWhen` is client-side too and faults OPEN (it renders for everyone): never access - control. +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 @@ -134,4 +132,5 @@ metadata-form row), `current_user` (alias `user`), `os.user.id`, `os.org.id`, `o | 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; view and action predicates | **objectstack-automation**; **objectstack-ui** | +| 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** | From 77804a7ae09334ca6edd7b6a331d14ef9650d920 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 16:40:46 +0000 Subject: [PATCH 6/8] docs(skills): the formula changeset follows the entry's last shape The entry is 136 lines, and the form-view visibleWhen fact sits on the routing table beside the formula-field and view-filter facts; the changeset says so. No skill text changes. Claude-Session: https://claude.ai/code/session_01ADHkmSM46qymk97AyqPzoS Co-authored-by: Claude --- .changeset/34770-formula-skill-router.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/34770-formula-skill-router.md b/.changeset/34770-formula-skill-router.md index ee040c2ef2c..3cee8f03e31 100644 --- a/.changeset/34770-formula-skill-router.md +++ b/.changeset/34770-formula-skill-router.md @@ -7,9 +7,9 @@ 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 137). 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. +`skills/objectstack-formula/SKILL.md` goes from 24.4 KB to 9.0 KB (485 lines to 136). 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`, and a form-view `visibleWhen` faults open; a transition compares `previous`, which is per row on a bulk write and `null` on insert, and a 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. +**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 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.** From 50530b6be4286c9debe9359350c303ea7f3b5208 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 17:31:53 +0000 Subject: [PATCH 7/8] docs(skills): guard the formula router's transition exemplar, scope its abort sentence Two should-fix items from the contract review of the router PR, paid inside the entry: - the checked block's transition line now carries `previous != null && `, the form trap 3 prescribes: unguarded it faults on insert, where `previous` is null, and the build does not refuse it; - trap 3's sentence on a condition that cannot evaluate names the hook again. A record-change trigger's run fails while the write lands, so "aborts the write" is a hook `condition`'s outcome, not every site's. The entry is 8999 bytes (was 8974), 135 lines; one blank line and one comma pay part of it. The CEILINGS row follows the measurement, 2237 -> 2243, zero headroom. The changeset's line count and its matching sentence are corrected. Claude-Session: https://claude.ai/code/session_01ADHkmSM46qymk97AyqPzoS Co-authored-by: Claude --- .changeset/34770-formula-skill-router.md | 4 ++-- scripts/check-skills-token-ratchet.mjs | 16 ++++++++++------ skills/objectstack-formula/SKILL.md | 11 +++++------ 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/.changeset/34770-formula-skill-router.md b/.changeset/34770-formula-skill-router.md index 3cee8f03e31..022abb82ece 100644 --- a/.changeset/34770-formula-skill-router.md +++ b/.changeset/34770-formula-skill-router.md @@ -7,9 +7,9 @@ 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 136). 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. +`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 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 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.** diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index cfa7ae2ebf8..c467caf3696 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -980,20 +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. - // 6088 -> 2237 (#34770): the entry becomes a router. It keeps four first checks, one + // 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 file is 24377 bytes (24350 priced) -> - // 8974 (8947 priced) -> 2237 tokens, pinned AT the measurement; the sum of all ceilings falls - // by the same 3851. + // 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(8947 / 4) - ['skills/objectstack-formula/SKILL.md', 2237], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997), then +82 (was 6008), then -2 (was 6090), then -3851 (was 6088) + // 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 2a26e54598c..84ad622c4ed 100644 --- a/skills/objectstack-formula/SKILL.md +++ b/skills/objectstack-formula/SKILL.md @@ -16,7 +16,6 @@ metadata: tags: cel, formula, predicate, condition, validation, visibility, seed-dynamic --- - # Expressions (CEL) — ObjectStack Formula Protocol Every expression in metadata is one envelope, `{ dialect, source }` (`Expression`, @@ -51,7 +50,7 @@ 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`previous.status != 'escalated' && record.status == 'escalated'`; +P`previous != null && previous.status != 'escalated' && record.status == 'escalated'`; const seed = { close_date: cel`daysFromNow(45)` }; ``` @@ -90,10 +89,10 @@ metadata-form row), `current_user` (alias `user`), `os.user.id`, `os.org.id`, `o 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 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. + 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: From 2b912f163ec8f9e4b5363f0f8d78d7d46a840620 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:11:28 +0000 Subject: [PATCH 8/8] docs(skills): the objectstack-api entry file becomes a router The entry goes from 21,359 to 8,986 bytes (438 lines to 151). It keeps four first checks, the generated routes with the metadata list's closed query set and an import mapping's applyOn, the apiMethods primitives and what derives from them, one type-checked declared endpoint, six traps and a routing table. The skill has no hand-written reference file, so nothing moved: the rest is cut behind a pointer to the contract, the publish gates or the published API pages. The changeset lists every cut and every anchor that left. The ratchet row is pinned at the measurement, 5333 to 2240 tokens, and the sum of all ceilings falls by the same 3093. Claude-Session: https://claude.ai/code/session_01ADHkmSM46qymk97AyqPzoS Co-authored-by: Claude --- .changeset/34770-api-skill-router.md | 27 ++ scripts/check-skills-token-ratchet.mjs | 17 +- skills/objectstack-api/SKILL.md | 489 +++++-------------------- 3 files changed, 144 insertions(+), 389 deletions(-) create mode 100644 .changeset/34770-api-skill-router.md diff --git a/.changeset/34770-api-skill-router.md b/.changeset/34770-api-skill-router.md new file mode 100644 index 00000000000..24a55dc63ea --- /dev/null +++ b/.changeset/34770-api-skill-router.md @@ -0,0 +1,27 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the objectstack-api entry file becomes a router + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-api/SKILL.md` goes from 21.4 KB to 9.0 KB (438 lines to 151). It now holds six things: four first checks (the installed version wins over the `compatibility` line, and an `apis:` block written before protocol 17 turns live; read the stack's `apis`, its `manifest.namespace` and the object's `apiMethods`; read the contract and never recall a key or a code; verify with `os validate` or `os build` and read a publish rejection), the generated routes, the `apiMethods` primitives and what derives from them, one type-checked declared endpoint, six 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.** The generated routes as one listing (the `data` routes, the two `batch` routes, import and export, the metadata read), with the two request contracts a client gets wrong: the metadata list reads a closed query set and narrows by `?names=`, and an import mapping's entry form, `{ sourceField, targetField, applyOn }`, is the only one that carries `applyOn`. The section `## API Methods (Operations)` keeps its heading and every one of the six authorable primitives, with the eight derived operations and what each derives from. The declared endpoint keeps its example: the path carve-out, `object_operation` with `objectParams`, `cacheTtlSeconds`. The six traps, each a declaration or a call that passes and then answers wrong at run time: `authRequired: false` needs `rateLimit.enabled: true`, because a budget with only `windowMs` / `maxRequests` meters nothing; an app never mounts on `http.server`, handler code runs in a flow's `script` or `connector_action` node, an inbound webhook is a `type: 'api'` flow verified by `x-objectstack-signature` or a declared `config.signature`, and three cases have no app surface; `DELETE` keeps a business object's rows in the recycle bin, with the restore door and its two grants; a `PATCH` with no version token skips the concurrency check; a public form answers `404 FORM_NOT_FOUND` unless its `sharing` declares `enabled`, `allowAnonymous` and `publicLink`, strips fields outside its sections, and is withheld on a walled posture with only a warning at save and publish; a person is shown `userMessage`, never `message`, on a batch publish's `probes.issues[]`, and a failed flow door renders `userMessage`, then `details.innerRefusal`, then `message`. + +**What left, and what answers it now.** + +- The publish gates one by one, and the mapping refusals beyond `transform` (`inputMapping` on a `find` / `get` / `delete` operation, two entries writing one target path): https://objectstack.ai/docs/api/declarative-endpoints, and the rejection itself, which names the endpoint, the key and the fix. `os validate` runs the same gates. +- The steps for an `apis:` block written before protocol 17 (move every `path` into the carve-out, review every `authRequired: false`): the `declarative-apis-endpoints-live` entry of the protocol upgrade guide, which the entry still names. +- The endpoint naming table: cut. Its two patterns (`/api/v1/{object}/:id/{action}`, `/api/v1/{domain}/{action}`) are not paths an app can declare: a declared path lives under `/api/v1/apps//`, and the endpoint vocabulary has no path-template syntax. +- The per-primitive route table, the four `RESTORE_*` refusals of a restore, the list, purge and empty doors of the recycle bin, the one metadata type whose list refuses `names`, and the discovery route: https://objectstack.ai/docs/protocol/kernel/http-protocol. The quoted-empty entity-tag refusal (`400 VALIDATION_FAILED`): https://objectstack.ai/docs/api/wire-format. The `ApiOperation` vocabulary: `data/object.zod.ts`. Each refusal among them is loud when hit. The health and readiness routes are cut: nothing in a stack declares them. +- The dispatcher's four codes, the two envelope shapes, the two-tier `error.code` vocabulary and the downstream-ledger recipe (`envelopeViolations`, `makeApiErrorSchema`): `api/errors.zod.ts`, `api/dispatcher.zod.ts`, `api/error-code-ledger.zod.ts` and `api/contract.zod.ts` under `node_modules/@objectstack/spec/src/`, and https://objectstack.ai/docs/api/error-catalog. The entry keeps that a code in no ledger fails CI. +- The realtime pointers (`api/realtime.zod.ts`, `api/websocket.zod.ts`): `references/_index.md`, which lists both. +- The login request's field list, and the flat `public` + `permissions` pair of `RestApiEndpointSchema` (the plugin route registry, `api/plugin-rest-api.zod.ts`): the contract. The entry keeps `AuthProvider` with its members, `LoginRequestSchema`, and that a declared endpoint has `authRequired` and no nested `auth` block (the strict endpoint shape refuses `auth` and names `authRequired`). +- A public form's file-field rule (`public-form-file-field`, an error at `os validate` and at publish) and the `guest_portal` name: https://objectstack.ai/docs/ui/forms. The form contracts: `ui/view.zod.ts` (`FormViewSchema`) and `ui/sharing.zod.ts` (`SharingConfigSchema`). +- The locale ladder's subtag steps, the `advisories[]` / 422 `issues[]` element (`RuntimeAuthoringIssueSchema`), and the `errorMessage` and `summary` keys of a failed flow's details: `api/protocol.zod.ts` and `api/automation-api.zod.ts`. An app-authored refusal having no `en` floor is in objectstack-i18n. +- The skill-boundaries table: the frontmatter description and the last routing row. + +**Anchors that no longer exist in `SKILL.md`.** `#skill-boundaries`, `#auto-generated-vs-custom-apis`, `#auto-generated-apis`, `#metadata-api-meta`, `#public-anonymous-form-endpoints`, `#declarative-endpoints-apis--no-handler-code`, `#choosing-between-apis-and-a-code-handler`, `#the-path-carve-out-adr-0121-d1d2`, `#five-publish-gates-each-with-a-prescription`, `#authrequired-and-the-d6-pairing`, `#mapping-keys-projection-only`, `#upgrading-a-pre-17-stack`, `#endpoint-naming-conventions`, `#discovery--health`, `#dispatcher-error-codes`, `#realtime-subscriptions`, `#authentication--authorization`, `#auth-configuration`, `#auth-providers`, `#error-envelopes--the-code-ledger-adr-0112`, `#best-practices`, `#common-pitfalls`, `#verify-your-work`, `#references`. `#api-methods-operations` stays. The new ones are `#first-checks`, `#generated-routes`, `#a-declared-endpoint`, `#traps` and `#where-to-go`. 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 1e3fc5acaca..ef087bcd731 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -578,7 +578,22 @@ export const CEILINGS = new Map([ // longer has. Lowered to the measurement, per the shrink-only discipline. // 6319 -> 6314: A2′ — the release-stamp line left the count (see // STAMP_LINE_REPIN); the file's count fell by the same 5, headroom unchanged. - ['skills/objectstack-api/SKILL.md', 5333], // -981 to the measurement (was 6314) + // 6314 -> 5333: lowered to the measurement (-981). + // 5333 -> 2240 (#34770): the entry becomes a router. It keeps four first checks, the + // generated routes with the two request contracts a client gets wrong (the closed query set + // of the metadata list, an import mapping's `applyOn`), the `apiMethods` primitives and what + // derives from them, one type-checked declared endpoint, six traps (each passes the build + // and then answers wrong at run time, or is refused only at publish with the form to write) + // 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 (`api/*.zod.ts`, whose strict endpoint shape + // refuses a wrong key with the key to write), to the publish gates (`os validate` runs them + // and each rejection carries its fix) or to the published API pages. No row rises and no + // row is added. The file is 21359 bytes (21332 priced) -> 8986 (8959 priced) -> 2240 + // tokens, pinned AT the measurement; the sum of all ceilings falls by the same 3093. + // Authority: the ruling of record that orders the entry file down to router size, decision + // record #34691 S3 = A. + // ceil(($(wc -c < skills/objectstack-api/SKILL.md) - 27) / 4) == ceil(8959 / 4) + ['skills/objectstack-api/SKILL.md', 2240], // 12511 -> 12643 (#11348): the flow value-expression section documented the // expression surface but not the function vocabulary (round/floor/ceil/abs/ // min/max); an unknown function fails at RUNTIME, not at flow-save, so the diff --git a/skills/objectstack-api/SKILL.md b/skills/objectstack-api/SKILL.md index c8bfc646021..9a5e3216c7b 100644 --- a/skills/objectstack-api/SKILL.md +++ b/skills/objectstack-api/SKILL.md @@ -21,418 +21,131 @@ metadata: # API Design — ObjectStack API Protocol -## Skill Boundaries +A custom endpoint is **metadata** (`defineStack({ apis })`), never a route an app mounts. -| Need | Use instead | -|:-----|:------------| -| Model objects, fields, permissions, or datasources (`rules/datasources.md`) | **objectstack-data** | -| Pick a driver package | **objectstack-platform** → Driver Selection Guide | -| Filter, sort, paginate, or aggregate a request | **objectstack-query** | -| Register a kernel service, or read one from a plugin | **objectstack-platform** | -| CEL in a route guard or auth predicate | **objectstack-formula** | +## First checks ---- - -## Auto-Generated vs Custom APIs +1. **Version.** Where the installed `@objectstack/spec` version differs from this skill's + `compatibility` line, the installed contract is right. Declared endpoints are live from + protocol 17: an older `apis:` block turns from inert text into an execution entry point + (the protocol upgrade guide's `declarative-apis-endpoints-live` entry). +2. **Read what exists**: the stack's `apis` and `manifest.namespace`, the object's + `apiMethods`. Prefer a generated route. +3. **Read the contract** ([references/_index.md](./references/_index.md)); an endpoint is + `node_modules/@objectstack/spec/src/api/endpoint.zod.ts`. Never recall a key or a code. +4. **Verify**: `os validate` or `os build`. A declaration this runtime cannot serve is + rejected one publish gate at a time: read the rejection, it carries the fix. -### Auto-Generated APIs +## Generated routes -Every ObjectStack object with `apiEnabled: true` (the default) automatically -gets a full REST API: +Served with nothing authored (`data`: an object with `apiEnabled: true`, the default): ``` -GET /api/v1/data/{object} # List records (with filter, sort, pagination) -GET /api/v1/data/{object}/:id # Get single record -POST /api/v1/data/{object} # Create record -PATCH /api/v1/data/{object}/:id # Update record -DELETE /api/v1/data/{object}/:id # Delete record (business-object rows → recycle bin) -POST /api/v1/data/{object}/query # Complex queries + aggregation (QueryAST in body) -POST /api/v1/data/{object}/batch # Per-object batch operations -POST /api/v1/batch # Cross-object atomic batch +GET|POST /api/v1/data/{object} # list | create +GET|PATCH|DELETE /api/v1/data/{object}/:id # get | update | delete (→ recycle bin) +POST /api/v1/data/{object}/query # QueryAST body, aggregation +POST /api/v1/data/{object}/batch # per-object batch +POST /api/v1/batch # cross-object atomic batch +POST /api/v1/data/{object}/import, GET …/export +GET /api/v1/meta/:type[/:name] # metadata read (object, view, flow, …) ``` -There is no `/bulk` route and no `GET .../aggregate` route — batch writes go -through the `batch` endpoints. - -> **Key rule:** If your object defines `apiMethods`, only those operations (and -> what derives from them) are exposed; `[]` means deny-all. - -### Metadata API (`/meta`) +There is no `/bulk` route and no `GET …/aggregate`. -The metadata read surface lives under `/api/v1/meta` (separate from the data -CRUD routes above): - -``` -GET /api/v1/meta/:type # List metadata items of a type (object, view, flow, doc, …) -GET /api/v1/meta/:type/:name # Read a single metadata item -``` - -The list reads a closed query set — `package`, `preview` (`draft`), `object`, -`include` (`content`, `grants`), `id`, `names`, `locale` — and refuses any other key with -`400 VALIDATION_ERROR` instead of ignoring it. `?names=a,b,c` (one -comma-separated value) narrows the list to the named items the caller may see: -an unknown name is simply absent, an empty value is refused `400`, and the -`package` list (keyed by id) refuses the key. These are **client** contracts — -nothing in a stack declares them. - -### Public (anonymous) Form Endpoints - -A `FormView` is served by the anonymous form endpoints only when its -`sharing` declares all three: `enabled: true` (the schema default is -`false`), `allowAnonymous: true` and a `publicLink` slug. Miss any one and -both endpoints answer `404 FORM_NOT_FOUND`. The form is then mounted at: - -``` -GET /api/v1/forms/:slug # returns form spec + restricted objectSchema -POST /api/v1/forms/:slug/submit # whitelist-filtered INSERT, no auth header -``` +- **`GET /api/v1/meta/:type` reads a closed query set** (`package`, `preview`, `object`, + `include`, `id`, `names`, `locale`) and refuses any other key with `400 VALIDATION_ERROR`. + `?names=a,b,c` (one comma-separated value) narrows the list to the named items the caller + may see: an unknown name is absent, an empty value is refused `400`. +- **An import** takes `mapping` as `{ Column: field }` or as `FieldMappingEntry[]` + (`api/export.zod.ts`). Only an entry, `{ sourceField, targetField, applyOn }`, carries + `applyOn` (default `'always'`): `'create'` writes the column only when the row is + created, so a re-run `upsert` keeps a value an admin set since. -These bypass `enforceAuth` (Web-to-Lead / Web-to-Case flows). The form's own -declaration authorizes the submit: a `publicFormGrant` on its target object -(create and read-back of its new row, nothing else), decided before any permission -set resolves. The submit context's `guest_portal` name admits nothing and needs -no set; a set so named only feeds the grant's result masker. The framework -strips fields outside the form's `sections[].fields[]` list; a -`beforeInsert` hook on the target object should stamp safe defaults -(`status='new'`, `lead_source='web'`, …) and `delete` privileged keys -(`owner`, `internal_notes`, …). On a walled posture (`group`/`isolated`), a -form on an object walled by an organization column is withheld too — both -endpoints `404`, and save / publish warn `public-form-intake-unavailable`; -declare `tenancy: { enabled: false }` on an object whose rows belong to no -organization to offer it again. For the full contract, read -`node_modules/@objectstack/spec/src/ui/view.zod.ts` (`FormViewSchema`) and -`node_modules/@objectstack/spec/src/ui/sharing.zod.ts` (`SharingConfigSchema` -with `enabled` / `allowAnonymous` / `publicLink`). - -A form open to anonymous intake declares no file field. A section field whose -object type is in `FILE_REFERENCE_TYPES` (`image`, `file`, `avatar`, `video`, -`audio`) is refused by the gating lint rule `public-form-file-field` — at -`os validate` / `os build` / `os lint`, and at the view's publish — because a -visitor has no upload door to mint a `sys_file` id. A form published before that -rule meets the same refusal at submit: a file value answers the flat `400 -VALIDATION_FAILED` with `fields[].code: 'invalid_value'`. Collect the file on a -signed-in form instead. - ---- - -## Declarative Endpoints (`apis:`) — no handler code - -`defineStack({ apis })` declares an HTTP endpoint as **metadata**. Declared -endpoints are **live from protocol 17**: the runtime matches -`METHOD` + `path`, runs the endpoint's policy keys, and delegates to the *same* -pipelines the built-in routes use — `object_operation` to the data pipeline -behind `/api/v1/data/{object}`, `flow` to the automation pipeline behind -`POST /api/v1/automation/{name}/trigger`. An endpoint is a stable URL plus a -policy layer over an existing pipeline, never a second execution dialect. +## API Methods (Operations) -### Choosing between `apis:` and a code handler +`apiMethods` whitelists the six authorable primitives (`ApiMethod`): `get`, `list`, +`create`, `update`, `delete`, `bulk` (the `/batch` route); unset is all, `[]` none. Every +other operation derives and is never declared (a declared one is stripped at parse, with a +warning): `aggregate`, `export` and, where `searchable`, `search` (the global +`GET /api/v1/search`) from `list`; `import` from `create` ∨ `update`; `history` from `get` +∧ `trackHistory`; `restore` and `purge` (trap 3) from `delete`; `upsert` from `create` ∧ +`update`, with no route: query by the external ID, then create or update through `/batch`. -| Use | When | -|:---|:---| -| **`defineStack({ apis })`** | The endpoint is a *projection* of something the platform already executes: query/return records, or trigger a flow. No code, no deploy artifact, publish-gated. **Prefer this.** | -| **A flow that runs your code** | The endpoint needs real handler CODE: point a `type: 'flow'` endpoint at a flow whose `script` node names a stack function (`defineStack({ functions })`; which one runs: [objectstack-automation](../objectstack-automation/SKILL.md#valid-but-silently-wrong-passes-build-fails-at-runtime) item 3), or whose `connector_action` node calls a declared connector (outbound). The URL stays declarative; the code runs where the automation surface already runs it. | +## A declared endpoint -An inbound webhook is a `type: 'api'` flow (objectstack-automation → -**Inbound webhook (`api`) triggers**): it verifies ObjectStack's own -`x-objectstack-signature`, or a vendor's own HMAC-SHA256 header its start node -declares as `config.signature` (DocuSign Connect, Stripe-style), enqueues, and -answers `202`. -**An app never mounts on `http.server`** — that service is the platform -plugins' own door-building primitive, and a code-mounted route gets no caller -identity, auth gate, rate limit, namespace carve-out or OpenAPI entry. Three -cases have no app surface today; say so rather than invent one: a third-party -callback signed in a form `config.signature` cannot declare (not HMAC-SHA256), -a streaming response (a declared endpoint answers one JSON envelope), and a -protocol the platform does not speak. +`type` is `object_operation` or `flow`, the pipelines of `/api/v1/data/{object}` and +`POST /api/v1/automation/{name}/trigger`; `script` and `proxy` are rejected at publish. ```typescript import type { ApiEndpoint } from '@objectstack/spec/api'; -// The stack declares `manifest: { namespace: 'acme', … }` — required, see below. +// `manifest: { namespace: 'acme', … }` is required, never derived from `id`. export const leadFeed: ApiEndpoint = { name: 'acme_lead_feed', path: '/api/v1/apps/acme/leads', // /api/v1/apps// method: 'GET', - summary: 'Lead feed', type: 'object_operation', objectParams: { object: 'acme_lead', operation: 'find' }, - cacheTtlSeconds: 30, // GET-only; rides success answers only + cacheTtlSeconds: 30, // GET-only }; ``` -### The path carve-out (ADR-0121 D1/D2) - -A declared path must be `/api/v1/apps//`. Only the -subpath is yours to name, and the ordinary naming rules below apply inside it. -`manifest.namespace` must be declared **explicitly** — it is never derived from -`manifest.id`. A path outside the carve-out is rejected at publish. - -### Five publish gates, each with a prescription - -A declaration this runtime cannot serve is **rejected at publish**, one gate at -a time. Do not memorise the gate texts; **read the rejection**, it carries the -fix. The five: **namespace** (the carve-out above), **supported target** -(`script` / `proxy` do not execute in 17.x; an `object_operation` needs both -`objectParams.object` and `.operation`; a `flow` needs a `target`), -**mapping** (below), **policy** (below), and **uniqueness** (one `METHOD` + -path claim per stack). - -### `authRequired` and the D6 pairing - -`authRequired` defaults to `true`, so **omitting it is safe**. An explicit -`false` is the only thing that opens an anonymous, unauthenticated execution -entry point — and ADR-0121 **D6** pairs it with an *armed* budget: - -```typescript -authRequired: false, -rateLimit: { enabled: true, windowMs: 60_000, maxRequests: 100 }, -``` - -The gate's predicate is `rateLimit.enabled === true`, **not** the key's presence: -`RateLimitConfigSchema.enabled` (`@objectstack/spec/shared`) itself defaults to `false`, so writing only -`windowMs` / `maxRequests` declares a budget that meters nothing. Endpoint -budgets are metered independently of the server-level `server.security.rateLimit`. - -### Mapping keys: projection only - -`inputMapping` / `outputMapping` **move and rename fields by dot path, and -nothing more**. `inputMapping` maps the REQUEST BODY, applied after the policy -chain and before delegation (so a mapping can never buy a caller past -`authRequired` or the rate limiter); `outputMapping` is applied to a **successful** -response body only. Three consequences worth knowing before you author one: - -- `transform` is rejected — there is no transformation-function registry. - Compute the value where it is produced (a flow, or a formula field). -- `inputMapping` is rejected on a `find` / `get` / `delete` `object_operation`, - which never reads a request body. -- Two entries cannot write the same target path, nor one inside the other - (`x` and `x.y`). - -### Upgrading a pre-17 stack - -An `apis:` block written against an older major **changes meaning without -changing a byte** — inert documentation becomes an execution entry point. Work -through the `declarative-apis-endpoints-live` entry of the protocol upgrade -guide before upgrading; it is a security review, not a rename. Its two -load-bearing steps: move every `path` into the carve-out, and grep every entry -for `authRequired: false`. - ---- - -## Endpoint Naming Conventions - -| Pattern | Use Case | Example | -|:--------|:---------|:--------| -| `/api/v1/{object}/:id/{action}` | Custom action on record | `/api/v1/cases/:id/close` | -| `/api/v1/{domain}/{action}` | Domain-level action | `/api/v1/ai/chat` | - -**Rules:** - -- Always use **plural nouns** for collection paths (`accounts`, not `account`). -- Use **snake_case** for multi-word paths (`project_tasks`, not `projectTasks`). -- Use **verbs** only for actions, not for CRUD (`/close`, `/approve`). - ---- - -## API Methods (Operations) - -The authorable `ApiMethod` enum is the SIX PRIMITIVES. The wider EFFECTIVE -vocabulary (`ApiOperation`, 14 values) is what gates and responses speak; its -eight extra verbs are never declared in `apiMethods`: - -**Authorable primitives:** - -| Method | HTTP surface today | Purpose | -|:-------|:-------------------|:--------| -| `get` | `GET /data/{object}/:id` | Retrieve a single record | -| `list` | `GET /data/{object}` | List records with filter/sort/pagination | -| `create` | `POST /data/{object}` | Create a new record | -| `update` | `PATCH /data/{object}/:id` | Update an existing record | -| `delete` | `DELETE /data/{object}/:id` | Delete a record | -| `bulk` | `POST /data/{object}/batch` | Batch create/update/delete (bulk ∧ child op) | - -**Derived operations (granted automatically, never authored):** - -| Operation | Derives from | HTTP surface today | -|:----------|:-------------|:-------------------| -| `upsert` | `create` ∧ `update` | none generated | -| `aggregate` | `list` | `POST /data/{object}/query` with `groupBy`/`aggregations` | -| `search` | `list` ∧ `searchable` | global `GET /api/v1/search`, not per-object | -| `import` | `create` ∨ `update` (writeMode-precise) | `POST /data/{object}/import` | -| `export` | `list` | `GET /data/{object}/export` | - -`history` (from `get` ∧ `trackHistory`) gates only. `restore` / `purge` derive -from `delete` and open the recycle-bin doors (pitfall 2). Declaring any -derived verb in `apiMethods` is stripped at parse with a FROM → TO warning. - -`POST /data/{object}/import` takes `mapping` as `{ Column: field }` or as -`FieldMappingEntry[]` (`api/export.zod.ts`); only the entry form carries -`applyOn`. `'always'` (default) writes the column on every row the import -creates or updates; `'create'` writes it only when the row is created, so a -re-run `upsert` refreshes the `always` columns and leaves a value an admin set -since (an owner, a stage) as it is. A create-only column is still read for -matching. Any other value is `400 INVALID_REQUEST`. - ---- - -## Discovery & Health - -`GET /api/v1/health`, `GET /ready` (200 running / 503 booting) and -`GET /api/v1/discovery` (per-service status) exist on **every** deployment. -All three are **response** surfaces — nothing to author. - ---- - -## Dispatcher Error Codes - -The **HttpDispatcher** is the central request router; it answers: - -| HTTP Status | Error Code | When | -|:------------|:-----------|:-----| -| 404 | `ROUTE_NOT_FOUND` | No route matches the path | -| 405 | `METHOD_NOT_ALLOWED` | Route exists but method not supported | -| 501 | `NOT_IMPLEMENTED` | Route declared but handler is a stub | -| 503 | `SERVICE_UNAVAILABLE` | Service is registered but not ready | - ---- - -## Realtime Subscriptions - -- `node_modules/@objectstack/spec/src/api/realtime.zod.ts` — `TransportProtocol` - (`websocket` | `sse` | `polling`), `SubscriptionSchema` (`id`, `events[]`, - `transport`, optional `channel`), `RealtimeEventSchema`, and - `RealtimeConfigSchema`. -- `node_modules/@objectstack/spec/src/api/websocket.zod.ts` — the WebSocket - message protocol: subscribe/unsubscribe messages, event delivery, presence, - cursor and collaborative-edit messages, and ack/error/ping/pong frames. - ---- - -## Authentication & Authorization - -### Auth Configuration - -There is no nested `auth` block on an endpoint, and no `name` / `request` / -`response` field: auth is the flat `public` + `permissions` pair on -`RestApiEndpointSchema`, and declarative `ApiEndpointSchema` endpoints (and the -dispatcher) use `authRequired: boolean` (D6 above). - -### Auth Providers - -Provider and login contracts live in -`node_modules/@objectstack/spec/src/api/auth.zod.ts`: `AuthProvider` is -`'local' | 'google' | 'github' | 'microsoft' | 'ldap' | 'saml'`, and -`LoginRequestSchema` carries `type` (login method), plus optional `email`, -`username`, `password`, `provider`, and `redirectTo`. Read that file for the -session and token response shapes before wiring an auth flow. - ---- - -## Error Envelopes & the Code Ledger (ADR-0112) - -`error.code` is **two-tier**: the closed `StandardErrorCode` catalog plus the -codes registered per owning package in `api/error-code-ledger.zod.ts`. -`ApiErrorSchema.code` validates the union, so an **unregistered code fails -parse → fails the envelope conformance suites → fails CI**. - -That ledger takes **framework packages only**. A downstream repo keeps its OWN -ledger and composes the two checks itself — `envelopeViolations(body)` for the -SHAPE, `makeApiErrorSchema(yourCodes)` for the VOCABULARY (both in -`api/contract.zod.ts`). What no repo may do is emit a code in no ledger at all. - -`userMessage` is producer-marked user-facing text in the REQUEST's locale; render it as -received and keep no per-code translation table. Platform-composed text follows one ladder -over the platform locale table (`PLATFORM_LOCALES`, `@objectstack/spec/system`): the locale -the request names (its `Accept-Language`, or `?locale` on the REST door), else the workspace -default, else `en`, each code read whole and then one subtag shorter at a time (`fr-FR` → -`fr`, `zh-Hant-US` → `zh-Hant`). App-authored text, such as a hook's catalogued refusal, is -not on this ladder: it is served in the caller's locale from the app's own translations, -otherwise as declared, with no `en` floor. The save / publish doors' `advisories[]` and the -422 `issues[]` share one element, `RuntimeAuthoringIssueSchema` (`api/protocol.zod.ts`): it -carries an optional `userMessage` beside the stable `rule`, while `message` / `hint` stay -developer-facing English; absent, render `message`. -A batch publish (`POST /api/v1/packages/:id/publish-drafts`) may answer `probes`, its runtime -findings (`BuildProbeReportSchema`, same file; ADR-0038). Each `issues[]` element -(`RuntimeBuildIssueSchema`) has two readers: `message` / `fix` are English for the agent that -built the app, the optional `userMessage` is the sentence for the person who published. Show -a person `userMessage`, never `message`; absent, show your own generic sentence. This door -reads the request's locale from `Accept-Language` alone. - -A flow door — `POST /api/v1/automation/{name}/trigger`, resume, `/actions`, a -declared `type: 'flow'` endpoint — answers a failed run with `400 FLOW_FAILED`; -its `error.details` is `FlowFailureDetailsSchema` (`api/automation-api.zod.ts`): -`errorMessage?` (the flow author's text), `summary?` (which node failed) and -`innerRefusal?`, the `{ code, message }` refusal a node met (a data node's read -or write, a `script` node's function name), `code` an `ErrorCode` member in wire -spelling (e.g. `UNIQUE_VIOLATION`, `PERMISSION_DENIED`, `RESOURCE_CONFLICT`). -Render it as a record form renders a refused save: -top-level `userMessage`, then `details.innerRefusal`, then `message`. Absent -keys mean the run produced none — never invent an empty. - ---- - -## Best Practices - -1. **Use auto-generated APIs** whenever possible. Only create custom endpoints - for business logic that cannot be expressed through CRUD + triggers. -2. **Return consistent error shapes.** The dispatcher envelope is - `DispatcherErrorResponseSchema`: `{ success: false, error: { code, message, - httpStatus?, route?, service?, hint? } }`, where `code` is the **semantic** - string and `code`/`message` are required. General API errors use - `ErrorResponseSchema` (`errors.zod.ts`). Be aware the shipped data routes - return flat `{ error, code }` bodies instead (e.g. `CONCURRENT_UPDATE` → - 409, `VALIDATION_FAILED` → 400). -3. **Design idempotent writes deliberately.** No upsert route is generated, so - an external integration queries by its unique external ID and branches to - create or update — group those writes through - `POST /api/v1/data/{object}/batch`. - ---- - -## Common Pitfalls - -1. **Not handling 409 Conflict.** The generated `PATCH /api/v1/data/{object}/:id` - route does optimistic concurrency with two spellings: the `If-Match` header - **or** an `expectedVersion` field in the JSON body — **the body wins** when - both are sent, and the token is typically the `updated_at` value the client - read. Sending neither skips the check; a mismatch answers **409 - `CONCURRENT_UPDATE`**; the quoted-empty entity-tag (`""`) is refused **400 - `VALIDATION_FAILED`**, not treated as omitted. -2. **Treating `DELETE` as final.** A by-id delete keeps a business object's - rows in the recycle bin (`sys_recycle_bin`, 30 days by default; not - `multi: true` deletes, platform rows or rows deleted before the bin existed) - and answers `recycleBinEntryId`. Under `/api/v1/data/{object}/recycle-bin`: - `POST /:entryId/restore` (`allowRestoreOwnDeleted` for your own deletes, - `manageRecycleBin` for others'); `GET` lists, `DELETE /:entryId` purges, - `DELETE` empties (`manageRecycleBin`). A refused restore answers `409` - `RESTORE_UNIQUE_VALUE_TAKEN`, `RESTORE_PARENT_PURGED`, - `RESTORE_PARENT_IN_RECYCLE_BIN` (restore that parent's entry first) or - `RESTORE_PACKAGE_UNINSTALLED`, and keeps the entry. No soft-delete. - ---- - -## Verify your work - -After adding a `*.endpoint.ts`, a custom route, or an auth provider, run the -author-time gate before reporting done: - -```bash -os validate # Zod schema + CEL predicate validation + bindings (no artifact) -# or: os build # the same gates, plus emits dist/ -``` - -Route-guard and auth predicates are CEL; the gate parses them and fails -non-zero with a located message instead of letting a malformed guard fall -through at runtime. In a scaffolded project the gate is `npm run validate`. See -objectstack-platform → **Verify your work** for the full gate list. - ---- - -## References - -See [references/_index.md](./references/_index.md) for the full list of Zod -schemas (with one-line descriptions) — pointers into -`node_modules/@objectstack/spec/src/`. Always `Read` the source for exact field -shapes; do not rely on memory of property names. - +`inputMapping` / `outputMapping` only move and rename fields by dot path; `transform` is +rejected: compute the value in a flow or a formula field. + +## Traps + +1. **`authRequired: false` needs an ARMED budget.** Omitting the key is safe (default + `true`); an explicit `false` opens an anonymous execution entry point and pairs with + `rateLimit: { enabled: true, windowMs: 60_000, maxRequests: 100 }`. The gate reads + `rateLimit.enabled === true`, not the key's presence: `enabled` defaults to `false`, so + `windowMs` / `maxRequests` alone meter nothing. Endpoint budgets are metered apart from + `server.security.rateLimit`. +2. **An app never mounts on `http.server`**, the platform plugins' own primitive: a + code-mounted route gets no caller identity, auth gate or rate limit. Handler code runs in + a flow: a `type: 'flow'` endpoint names it in `target`; its `script` node names a stack + function (`defineStack({ functions })`; which one runs: + [objectstack-automation](../objectstack-automation/SKILL.md)), or its `connector_action` + node calls a declared connector. An inbound webhook is a `type: 'api'` flow: it verifies + ObjectStack's own `x-objectstack-signature`, or a vendor's HMAC-SHA256 header its start + node declares as `config.signature` (DocuSign Connect, Stripe-style), enqueues, and + answers `202`. No app surface exists for a callback signed in a form `config.signature` + cannot declare, a streaming response or a protocol the platform does not speak: say so, + never invent one. +3. **`DELETE` is not final.** A by-id delete keeps a business object's rows in the recycle + bin (`sys_recycle_bin`, 30 days by default; not `multi: true` deletes or platform rows) + and answers `recycleBinEntryId`. `POST /api/v1/data/{object}/recycle-bin/:entryId/restore` + restores it (`allowRestoreOwnDeleted` for your own deletes, `manageRecycleBin` for + others'); listing, purging and emptying the bin need `manageRecycleBin`. No soft-delete. +4. **A `PATCH` with no version token skips the concurrency check.** Send `If-Match`, or + `expectedVersion` in the JSON body (the body wins; the token is typically the + `updated_at` the client read). A mismatch answers `409 CONCURRENT_UPDATE`. +5. **A public form answers `404 FORM_NOT_FOUND` unless its `sharing` declares all three**: + `enabled: true` (default `false`), `allowAnonymous: true` and a `publicLink` slug. Then + `GET /api/v1/forms/:slug` and `POST /api/v1/forms/:slug/submit` bypass auth; the + declaration grants only the create and read-back of its row. Fields outside + `sections[].fields[]` are stripped; write a `beforeInsert` hook that stamps safe defaults + and deletes privileged keys (`owner`, …). On a walled posture a form on an + organization-walled object is withheld too, and save and publish only warn + (`public-form-intake-unavailable`): declare `tenancy: { enabled: false }` where the rows + belong to no organization. +6. **`userMessage` is the sentence for a person**: render it as received and keep no + per-code translation table. It is in the REQUEST's locale (platform text: + `Accept-Language`, or `?locale` on the REST door, else the workspace default, else `en`). + On a batch publish's `probes.issues[]` (`POST /api/v1/packages/:id/publish-drafts`; + `RuntimeBuildIssueSchema`, `api/protocol.zod.ts`; `Accept-Language` alone) `message` / + `fix` are developer English: show `userMessage`, never `message`, and with none your own + generic sentence. A flow door's `400 FLOW_FAILED`: `userMessage`, then + `details.innerRefusal` (`api/automation-api.zod.ts`), then `message`. + +## Where to go + +| Need | Open | +|:-|:-| +| An endpoint key, a publish gate, a mapping refusal | `api/endpoint.zod.ts`; https://objectstack.ai/docs/api/declarative-endpoints | +| A generated route's request and answer; discovery | https://objectstack.ai/docs/protocol/kernel/http-protocol | +| An error code or envelope; a new `error.code` (one in no ledger fails CI) | `api/errors.zod.ts`, `api/dispatcher.zod.ts`, `api/error-code-ledger.zod.ts`; https://objectstack.ai/docs/api/error-catalog | +| Auth (an endpoint has no nested `auth` block: `authRequired`) | `api/auth.zod.ts`: `AuthProvider` (`local`, `google`, `github`, `microsoft`, `ldap`, `saml`), `LoginRequestSchema` | +| A public form | https://objectstack.ai/docs/ui/forms | +| Objects, permissions; filters; kernel services, drivers | **objectstack-data**; **objectstack-query**; **objectstack-platform** |