diff --git a/.changeset/34770-skills-data-automation-router.md b/.changeset/34770-skills-data-automation-router.md new file mode 100644 index 00000000000..9934a6ee04c --- /dev/null +++ b/.changeset/34770-skills-data-automation-router.md @@ -0,0 +1,31 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the objectstack-data and objectstack-automation entry files become routers + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-data/SKILL.md` goes from 26.9 KB to 9.0 KB and `skills/objectstack-automation/SKILL.md` from 28.2 KB to 10.7 KB. Each now holds three things: four first checks (the installed `@objectstack/spec` version, what the project already has, the type's contract, `os validate`) and what to do when there is nothing to read yet (say so, and still give the whole definition as code), the traps that parse and then fail at run time, and a table that says which file to open for what you are writing. No rule's teaching changes. Text moved, and this entry says where it went. The ten skill files the move touches are 1.6 KB larger together (161.5 KB to 163.0 KB): objectstack-data is 2.3 KB smaller, objectstack-automation 3.9 KB larger. + +**objectstack-data.** The entry keeps `Conditional Field Rules`, `Object Definition`, `Field Type Selection`, `Relationship Patterns`, `Validation Patterns` and `Access depth` under their headings, each cut to the rules that fail silently. What left: + +- The object key table (the `color` row among it), the `enable` table (`fieldHistory`, `trackHistory`), `Search Fields (searchableFields)` and `Object Extension Model` (an extension's `place`, the paired `.custom` package's `fieldGroups` / `relatedLists` / `actionLayout`) are in `references/examples-objects.md` (`#object-keys`, `#search-fields-searchablefields`, `#object-extension-model`). +- `Schema evolution on an existing database` is `rules/field-types.md#changing-a-field-that-has-data`, and objectstack-project points there now. The detail of choosing a type (a box that must be checked, the seeded-row default, why a person stays optional) is `rules/field-types.md#choosing-a-type`. +- The `Conditional Field Rules` example and its bullets (`showOnCreate` among them), and what a bare field ref does at run time, are `rules/validation.md#conditional-field-rules`. The note that an omitted optional field reads as `null` on insert is `rules/validation.md#script-validation`. +- `Ownership queues` and the mechanics of `readScope` / `writeScope` are in `rules/security.md`. +- A handler named apart from the record owner is `rules/relationships.md#record-owner-and-other-people-on-a-record`. +- Anchors that no longer exist in `SKILL.md`: `#skill-boundaries`, `#quick-reference--detailed-rules`, `#object-capabilities-enable`, `#search-fields-searchablefields`, `#schema-evolution-on-an-existing-database`, `#common-patterns`, `#naming-rules-summary`, `#index-patterns`, `#object-extension-model`, `#security--access-control`, `#ownership-queues--park-a-record-for-a-team-to-claim`, `#verify-your-work`, `#references`. `#conditional-field-rules`, `#object-definition`, `#field-type-selection`, `#relationship-patterns` and `#validation-patterns` still do. + +**objectstack-automation.** The entry keeps `Data Operations`, `External Integration`, `notify`, `Failure routing & runAs`, `Filter operands (config.filter)`, `Valid-but-silently-wrong (passes build, fails at runtime)` and `Integrations are declared, not coded` under their headings, each cut to the rules that fail silently. Beside them it states the facts of a flow's shape an answer needs before it opens a second file: a project flow is `defineFlow` in a `*.flow.ts`, the five flow `type`s (`type: 'schedule'` and where its cadence sits), `variables`, the trigger on the start node, the `approval` node, the option label of a notice (evaluated once per run), and `Assignment rules` (`defineAssignmentRule`, beside the approval node for the same queue). What left: + +- `references/examples-flows.md` now also holds `Flow Types`, packaged flows (`.custom` overrides, `defaultActive`), the control-flow node table, the detail of the `http`, `connector_action` and `screen` nodes, `Triggers` (the `requires` tokens, the trigger types) and `Assignment rules` in full (ordered entries, `least_loaded`, a packaged rule's queue). For `notify`, failure routing and `runAs`, filter operands and value slots, a section titled "the rest" holds what the entry's section no longer says. Of the option-label trap, the entry keeps the rule and its outcome (a label is refused at publish where the options are inline, else it matches no row or fails the run); the example, and the filter operand for rows that still hold a label, are in the rest section. +- `references/integration-recipes.md` now also holds `Inbound webhook (api) triggers` and the list of cases that are platform code. +- Anchors that no longer exist in `SKILL.md`: `#when-to-use-this-skill`, `#flows--visual-logic-orchestration` (now `#flows`), `#flow-types`, `#control-flow`, `#human-decision`, `#flow-variables`, `#assignment-rules--route-a-new-record-to-a-queue-or-a-person` (now `#assignment-rules`), `#triggers--event-driven-automation` and its four subsections, `#verify-your-work`, `#references`. + +**Not carried over, because the contract or a check already says it.** From objectstack-data: the `label`, `datasource`, `displayNameField`, `searchable`, `apiEnabled`, `files` and `clone` rows (their defaults are in `data/object.zod.ts`, which the entry's third check points at), the `titleFormat` row (a save and `os validate` refuse the key by name), the four-row `sharingModel` table (the four values are one bullet of `Object Definition`), the `Skill Boundaries` table (it listed the neighbouring skills, which the description still names), and the sections that only listed the other files (the rules list, `Naming Rules Summary`, `Index Patterns`). + +**One correction.** The multi-value lookup note in objectstack-data showed a `{record.tags.0}` token "in flow values". A flow value slot refuses that token, as objectstack-automation teaches. The note, now in `rules/relationships.md`, shows the CEL spelling `record.tags[0]`. objectstack-automation's value-slot rule likewise shows the CEL spelling (`has(record.owner) ? record.owner : null`, `record.tags[0]`) and no longer prints the refused token beside it: the refusal names the spelling. + +**Three eval cases accept the spellings the bundles teach.** Each failed correct answers on a literal: `flows-triggers-approvals` case 1 now forbids `values: {`, the key form a node carries, where it forbade the bare word `values:` that a prose heading also spells; `hooks-security-seeds-datasources` case 7 takes the refusal's translation as the nested `hooks: {` literal, as its JSON spelling, or as the dotted key `hooks..refusals.CREDIT_LIMIT.message` that `references/data-hooks.md` teaches; `objects-fields-relationships` case 10 takes the yes/no field as `type: 'boolean'` or as `Field.boolean(`. A recorded round regrades the three as changed cases, outside its pass rates. diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index cc9de5425b2..91a55a0b6a7 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -775,7 +775,45 @@ export const CEILINGS = new Map([ // went with it. The file is 27988 -> 28199 bytes (27968 -> 28179 priced); the row // moves +53, the measured remainder, pinned AT the measurement. // ceil(($(wc -c < skills/objectstack-automation/SKILL.md) - 20) / 4) == ceil(28179 / 4) - ['skills/objectstack-automation/SKILL.md', 7045], + // 7045 -> 2239 (#34770, the entry file becomes a router; decision record 6943107981, S3 = A, + // "a router-sized `SKILL.md` (6–9 KB, at most 500 lines)"): LOWERED. The entry keeps four + // first checks, the routing table, the trigger-on-the-start-node rule, and the seven sections + // the hosted door serves by exact heading, each cut to what fails silently: `#### Data + // Operations` (whole), `#### External Integration`, the `notify` section (its JSON node), `### + // Failure routing & runAs`, `### Filter operands (config.filter)`, `## + // Valid-but-silently-wrong (passes build, fails at runtime)` (its JSON node pair and its + // TypeScript registration) and `## Integrations are declared, not coded`. What left, and its + // home: Flow Types, the packaged-flow paragraphs, the Control Flow table, the remainder of + // each served section, Flow Variables, Triggers and Assignment rules -> + // `references/examples-flows.md`; the inbound-webhook section and the platform-code list of § + // Integrations -> `references/integration-recipes.md`. 28198 bytes (28178 priced) -> 8973 + // (8953 priced) -> 2239 tokens; the ceiling follows the file down to the measurement, the + // ratchet's ordinary direction, which also pins the 9 KB budget from here on. + // ceil(($(wc -c < skills/objectstack-automation/SKILL.md) - 20) / 4) == ceil(8953 / 4) + // 2239 -> 2670 (#34770, ruling record 7168461386, letter A): RAISED, and the one row that + // ruling authorises. The eval round on the router head lost six objectstack-automation cases on + // flow-shape facts the split had moved to `references/examples-flows.md`; the ruling orders + // them back into the entry, this row rising "by exactly the measured bytes restored, with zero + // headroom". Back in the entry: a flow's project form and its `type` list (`type: 'schedule'`, + // and where its cadence sits), `variables`, the human sign-off node (`type: 'approval'`), the + // option label evaluated once per run (§ notify), the refusal of a `{…}` token beside its CEL + // envelope (item 1 of § Valid-but-silently-wrong), where a flow's start is gated (§ Failure + // routing & runAs) and `## Assignment rules` (`defineAssignmentRule` beside its approval node); + // `## First checks` gains the line the objectstack-data entry gains, on the same reading. What + // stood in `references/examples-flows.md` in the same words left that file, whose row falls. + // The file is 8973 -> 10699 bytes (8953 -> 10679 priced), +1726, -> 2670 tokens, pinned AT the + // measurement. The entry is over the 9 KB the row above pinned, by this ruling and by no more + // than it. + // ceil(($(wc -c < skills/objectstack-automation/SKILL.md) - 20) / 4) == ceil(10679 / 4) + // 2670 -> 2669 (#34770, the merge of `main`): LOWERED. Item 4 of § Valid-but-silently-wrong + // follows the correction `main` made to it while this change was open (an option label in a + // `filter` or an edge `condition` is refused at publish where the options are inline; it is no + // longer "never checked"), in the entry's shorter words; the sentence `main` wrote stands whole + // in `references/examples-flows.md`. 10703 bytes (10676 priced; the stamp line is 27 bytes on + // this tree) -> 2669 tokens; the row follows the measurement down, inside the 2670 that ruling + // record 7168461386 authorises and ruling record 7176941587 keeps. + // ceil(($(wc -c < skills/objectstack-automation/SKILL.md) - 27) / 4) == ceil(10676 / 4) + ['skills/objectstack-automation/SKILL.md', 2669], // 13783 -> 13892 (2026-08-31 app-repo-principles raise, see the block above). // The invariant-vs-transition-gate choice, placed in the field-conditional-rule // bullet list where the tool is actually picked. Both wrong picks are silent: @@ -832,7 +870,39 @@ export const CEILINGS = new Map([ // clause and `name` example, which the JSON now shows. 26678 -> 26859 bytes (26658 // -> 26839 priced); the row moves +45, the measured remainder, pinned AT it. // ceil(($(wc -c < skills/objectstack-data/SKILL.md) - 20) / 4) == ceil(26839 / 4) - ['skills/objectstack-data/SKILL.md', 6709], // -1 to the measurement (was 6710) + // 6710 -> 2221 (#34770, the entry file becomes a router; decision record 6943107981, S3 = A): + // LOWERED. The entry keeps four first checks, three run-time traps, the routing table, `## + // Conditional Field Rules` (the anchor two other skills link), the four sections the hosted + // door serves by exact heading (`### Object Definition` with its JSON object, `### Field Type + // Selection`, `### Relationship Patterns`, `### Validation Patterns`), each cut to what fails + // silently, and the Leg 2 enumeration `check-skill-identifier-liveness` binds to this file + // (`### Access depth …`). What left, and its home: the object key and `enable` tables, Search + // Fields and the Object Extension Model -> `references/examples-objects.md`; Schema evolution + // and the type-choice detail -> `rules/field-types.md`; the Conditional Field Rules example + // and bullets -> `rules/validation.md`; Ownership queues and the access-depth mechanics -> + // `rules/security.md`; the handler-beside-the-owner rule -> `rules/relationships.md`. Gone, + // each restating a file the routing table now names: Skill Boundaries, the Detailed Rules + // list, Naming Rules Summary, Index Patterns, the required-properties table, the four-value + // `sharingModel` table (the values stay as one bullet). 26854 bytes (26834 priced) -> 8902 + // (8882 priced) -> 2221 tokens; the ceiling follows the file down to the measurement, which + // also pins the 9 KB budget from here on. + // ceil(($(wc -c < skills/objectstack-data/SKILL.md) - 20) / 4) == ceil(8882 / 4) + // 2221 -> 2239 (#34770, the parity round): the routing table's seed row names again what + // `references/seeds.md` holds (`defineSeed()`, import modes, `externalId`, relationship + // references, CEL values), the words the entry carried before the split; without the factory's + // name a seed request was answered without it. `## First checks` gains one line (with nothing + // to read yet, say so and still give the whole definition as code), paid inside the file by the + // sentence that defined an object under `### Object Definition` and by words of the routing + // table's lead. 8902 -> 8976 bytes (8882 -> 8956 priced), +74, -> 2239 tokens, pinned AT the + // measurement. Ruling record 7128031203, fork 4 = A: the row equals its measurement and the sum + // of ceilings does not rise (the accounting is on the `references/examples-flows.md` row). + // ceil(($(wc -c < skills/objectstack-data/SKILL.md) - 20) / 4) == ceil(8956 / 4) + // 2239, unchanged by the merge of `main`: the two edits `main` made to this file while the + // change was open are carried where their text now lives (the `actionLayout` sentence in + // `references/examples-objects.md` § Object Extension Model; the rule list `main` trimmed is + // the routing table here). 8983 bytes on this tree, whose stamp line is 27 bytes: 8956 priced. + // ceil(($(wc -c < skills/objectstack-data/SKILL.md) - 27) / 4) == ceil(8956 / 4) + ['skills/objectstack-data/SKILL.md', 2239], // 5997 -> 6008 (the formula skills follow-ups of PRs #34443 and #34447): the // `label(record.f)` row teaches a multi-select (`multiple: true`) reading each // selected label in stored order, joined with `, `, and the built-ins line @@ -1321,7 +1391,25 @@ export const CEILINGS = new Map([ // block and the time-zone / country sentence landed, paid by four same-file // restatement cuts that over-paid by 12 tokens; the row is lowered to the // measurement so the headroom is banked, not spent later. Shrink-only. - ['skills/objectstack-data/rules/field-types.md', 3540], // -1 to the measurement (was 3541) + // 3541 -> 4187 (#34770): RECEIVES from SKILL.md, no new teaching, § Schema evolution on an + // existing database as `## Changing a field that has data` (its opening paragraph is one line + // pointing at the entry's trap 1, which states it), and under `## Choosing a type` the detail + // the entry's Field Type Selection no longer spells (the must-be-checked rule, the seeded-row + // default, why a person stays optional, the other dynamic defaults). The file is 14156 -> + // 16748 bytes (+2592) -> 4187 tokens, the row's 2 tokens of headroom + // absorbed, ceiling +646, pinned AT the measurement. Authority as the + // `references/examples-objects.md` row. + // ceil($(wc -c < skills/objectstack-data/rules/field-types.md) / 4) == ceil(16748 / 4) + // 4187 -> 4199 (#34770, the parity round): under `## Choosing a type` the yes/no bullet carries + // the literal the entry gives it (`{ type: 'boolean', defaultValue: false }`), beside the rule + // that explains it. 16748 -> 16795 bytes (+47) -> 4199 tokens, pinned AT the measurement; + // authority as the `skills/objectstack-data/SKILL.md` row. + // ceil($(wc -c < skills/objectstack-data/rules/field-types.md) / 4) == ceil(16795 / 4) + // 4199 -> 4200 (#34770, the merge of `main`): `main` moved this file 14156 -> 14160 bytes + // while the change was open (its row 3541 -> 3540); the same two sections arrive on top of it, + // 2639 bytes as before. 14160 -> 16799 bytes -> 4200 tokens, pinned AT the measurement. + // ceil($(wc -c < skills/objectstack-data/rules/field-types.md) / 4) == ceil(16799 / 4) + ['skills/objectstack-data/rules/field-types.md', 4200], ['skills/objectstack-data/rules/indexing.md', 2495], // -746 to the measurement (was 3241) // 1590 -> 1909 (#32364, 2026-11-11): § Sealing (`seal`) teaches `lifecycle.seal` // (+1574 B). PAID DOWN FIRST by three same-file restatements (-296 B): the ❌ @@ -1423,7 +1511,20 @@ export const CEILINGS = new Map([ // in the inline-entry example's comment (the prose above it says so). 16724 -> 16714 bytes; // the row follows the measurement down. // ceil($(wc -c < skills/objectstack-data/rules/relationships.md) / 4) == ceil(16714 / 4) - ['skills/objectstack-data/rules/relationships.md', 4179], // -2 to the measurement (was 4203), then -2 (was 4181) + // 4203 -> 4332 (#34770): RECEIVES from SKILL.md § Relationship Patterns, as `## Record owner, + // and other people on a record`, the half of the Record owner row the entry no longer carries + // (a handler named apart from the owner, the injected labels it must not repeat, when + // `ownership: 'none'` fits) and the positional read of a multi-value lookup, whose example is + // now the CEL spelling `record.tags[0]`: the `{record.tags.0}` token it showed is the one + // objectstack-automation teaches as refused. The file is 16765 -> 17325 bytes (+560) -> 4332 tokens, the row's 11 tokens of headroom absorbed, ceiling +129, + // pinned AT the measurement. Authority as the `references/examples-objects.md` row. + // ceil($(wc -c < skills/objectstack-data/rules/relationships.md) / 4) == ceil(17325 / 4) + // 4332 -> 4319 (#34770, the merge of `main`): LOWERED. `main` took this file 16765 -> 16714 + // bytes while the change was open (the two entries above; its row 4203 -> 4179); the same + // section arrives on top of it, 560 bytes as before. 16714 -> 17274 bytes -> 4319 tokens, + // pinned AT the measurement. + // ceil($(wc -c < skills/objectstack-data/rules/relationships.md) / 4) == ceil(17274 / 4) + ['skills/objectstack-data/rules/relationships.md', 4319], // NEW FILE (#14296 item 1 = A, condition (b)): the entry's Security & Access // Control block moved here whole. Pinned at its landed count — no headroom, // because a split that arrives with budget is a raise wearing a new path. @@ -1571,7 +1672,22 @@ export const CEILINGS = new Map([ // 4340 -> 4334: the `requiredPermissions` sentence no longer lists View All and Modify All // beside the field votes it beats (19: they cast none). 17357 -> 17335 bytes. // ceil($(wc -c < skills/objectstack-data/rules/security.md) / 4) == ceil(17335 / 4) - ['skills/objectstack-data/rules/security.md', 4334], + // 4292 -> 4781 (#34770): RECEIVES from SKILL.md, no new teaching, § Ownership queues whole (as + // `##`; the sharing bullet that pointed at it in SKILL.md now points inside this file) and, as + // `## Access depth — readScope / writeScope`, the mechanics the entry's bound Access depth + // section no longer spells (the `owner_id IN (…)` resolution, the two ADR citations, the + // `defineStack` error in the entry's own clause, what the CLI reports). The sharing bullet's + // three `RESOURCE_CONFLICT` glosses are untouched; the position bullet says "the two closure + // refusals" for the two reason names that bullet glosses. The file is 17168 -> 19123 bytes + // (+1955) -> 4781 tokens, zero headroom before, ceiling +489, pinned AT the measurement. + // Authority as the `references/examples-objects.md` row. + // ceil($(wc -c < skills/objectstack-data/rules/security.md) / 4) == ceil(19123 / 4) + // 4781 -> 4823 (#34770, the merge of `main`): `main` took this file 17168 -> 17335 bytes + // while the change was open (the 4340 and 4334 entries above; its row 4292 -> 4334); the + // same two sections arrive on top of it, 1955 bytes as before. 17335 -> 19290 bytes -> 4823 + // tokens, pinned AT the measurement: the row is `main`'s 4334 plus the 489 the move brings. + // ceil($(wc -c < skills/objectstack-data/rules/security.md) / 4) == ceil(19290 / 4) + ['skills/objectstack-data/rules/security.md', 4823], // 3024 -> 3109 (2026-08-31 app-repo-principles raise, see the block above). // Severity Levels listed the three values and left the CHOICE unstated: a // block rests on a judgement a person made, so a machine-inferred signal — a @@ -1591,7 +1707,19 @@ export const CEILINGS = new Map([ // measurement. Same authority as the three rows above: cloud#3659 letter A // (ruling comment 6682024726); raise path 「A:先削重复,余额按实测提高」 // (ruling record 6513306068). - ['skills/objectstack-data/rules/validation.md', 2758], // -3 to the measurement (was 2761) + // 2761 -> 3466 (#34770): RECEIVES SKILL.md § Conditional Field Rules (the checked example and + // its bullets, `showOnCreate` among them) and the run-time half of § Verify your work (what a + // bare field ref does in each predicate), and into § State Machine Validation the clause of + // the entry's Validation Patterns that `transitions` keys and values are option values, never + // labels; no new teaching. PAID DOWN FIRST by restatement cut + // on the way in: the invariant-or-transition-gate bullet is one line pointing at this file's + // own Script Validation, Tool choice, which says the same; the `readonly: true` bullet keeps + // only what the entry's bullet does not; the `visibleWhen` one-liner is gone. The file is + // 11031 -> 13861 bytes (+2830) -> 3466 tokens, the row's 3 tokens of + // headroom absorbed, ceiling +705, pinned AT the measurement. Authority as the + // `references/examples-objects.md` row. + // ceil($(wc -c < skills/objectstack-data/rules/validation.md) / 4) == ceil(13861 / 4) + ['skills/objectstack-data/rules/validation.md', 3466], // objectstack-platform ['skills/objectstack-platform/references/plugin-hooks.md', 2413], // -215 to the measurement (was 2628) @@ -1968,7 +2096,56 @@ export const CEILINGS = new Map([ // each bound being a CEL envelope). 5957 -> 6170 bytes; the row moves +49, the // measured remainder, pinned AT the measurement. // ceil($(wc -c < skills/objectstack-automation/references/examples-flows.md) / 4) == ceil(6170 / 4) - ['skills/objectstack-automation/references/examples-flows.md', 1543], + // 1543 -> 6551 (#34770): RECEIVES what the router split moved out of SKILL.md, no new + // teaching: the CEL-envelope note, `## Flow Types`, `## A flow an installed package ships`, + // `## Flow Node Types` (the Control Flow table whole; of the External Integration rows only + // what the entry's rows no longer say), the remainder of § notify, § Failure routing & runAs, + // § Filter operands and § Valid-but-silently-wrong under `… — the rest` headings, `## Flow + // Variables`, `## Triggers — Event-Driven Automation` (the prerequisite table whole; the + // trigger-type table as one sentence) and `## Assignment rules`. The two existing examples sit + // under a new `## Long examples`, byte-identical, the hosted-served `### Time-relative + // triggers — scheduled per-record date sweep` among them. PAID DOWN FIRST: each moved section + // was cut to the complement of its SKILL.md section before it landed, so nothing is stated + // twice (the full-section copies measured 29784 bytes). The file is 6170 -> 26203 bytes + // (+20033) -> 6551 tokens, zero headroom before, ceiling +5008, pinned AT the measurement; the + // three objectstack-automation files this change touches are 3899 bytes larger together (44755 + // -> 48654), the cost of the entry's first checks and routing table and of what ruling record + // 7168461386 orders back into the entry. + // Authority: the ruling of record that orders the entry file down to router size, decision + // record 6943107981 S3 = A (this header: a ruling of record that orders text into a file + // authorises its own measured delta), and the maintainer's ruling of 2026-11-24 on the seven + // receiving rows of this change (ruling record 7128031203, fork 4 = A): a ceiling raised + // because text MOVED between files is accepted when each raised row equals the measured bytes + // moved in, with zero headroom, and the sum of ceilings does not rise. Both hold here: every + // row is pinned AT its measurement, and the nine rows this change moves sum to 34386, + // under the 34426 before it, the +430 ruling record 7168461386 orders into the + // objectstack-automation entry set aside. Beside the standing 2026-10-27 ruling 「A:先削重复,余额按实测提高」 (record 6513306068); + // as the objectstack-ui rows of part 1. + // ceil($(wc -c < skills/objectstack-automation/references/examples-flows.md) / 4) == ceil(26203 / 4) + // 6551 -> 6409 (#34770, ruling record 7168461386, letter A): LOWERED. What the ruling moves + // back into SKILL.md leaves this file where it stood here in the same words: the option-label + // sentence of `## notify — the rest`, `## Flow Variables`, and the refusal clause of the + // value-slot item, which keeps the CEL spellings a refused token is given and shows them + // without the token. 26203 -> 25633 bytes (-570) -> 6409 tokens, pinned AT the measurement. + // Accounting for ruling record 7128031203, fork 4 = A, over this change: its rows other than + // `skills/objectstack-automation/SKILL.md` sum 112 under their sum before the ruling (this row + // -142, `skills/objectstack-data/SKILL.md` +18, `rules/field-types.md` +12); that one row rises + // 431 on ruling record 7168461386. + // ceil($(wc -c < skills/objectstack-automation/references/examples-flows.md) / 4) == ceil(25633 / 4) + // 6409 -> 6433 (#34770, the merge of `main`): while the change was open `main` corrected + // item 4 of the entry's § Valid-but-silently-wrong (a label in a start or edge `condition`, a + // `filter` or `fields` is refused at publish where the options are inline; a filter for rows + // still holding the label takes a CEL envelope operand). The detail of that item lives here + // now, as item 3 of `## Value slots and the other silent traps — the rest`, so `main`'s + // sentence replaces it here, verbatim: +96 bytes of text `main` had already landed in the + // entry. 25633 -> 25729 bytes -> 6433 tokens, pinned AT the measurement. + // Accounting for ruling record 7128031203, fork 4 = A, on this tree: the rows this change + // moves, `skills/objectstack-automation/SKILL.md` set aside, sum 40 under their sum on the + // `main` it merges (34386 against 34426); that one row is 430 over its router size on ruling + // record 7168461386. `references/state-machines-and-approvals.md` keeps `main`'s row: its one + // re-pointed reference is paid inside the file. + // ceil($(wc -c < skills/objectstack-automation/references/examples-flows.md) / 4) == ceil(25729 / 4) + ['skills/objectstack-automation/references/examples-flows.md', 6433], // NEW FILE (card #27223): one recipe per integration archetype — OpenAPI with // a static key, remote MCP with a static header, plain REST, the vendor // callback, a hand-written document for a spec-less vendor — plus the two @@ -2041,7 +2218,13 @@ export const CEILINGS = new Map([ // tap A verbatim and untranslated: 「A:先削重复,余额按实测提高」 — the // standing path of ruling record 6513306068 on #27847. // ceil($(wc -c < skills/objectstack-automation/references/integration-recipes.md) / 4) == ceil(10377 / 4) - ['skills/objectstack-automation/references/integration-recipes.md', 2595], + // 2595 -> 3056 (#34770): RECEIVES, no new teaching, SKILL.md § Inbound webhook (`api`) + // triggers whole (the section recipe 4 already leaned on; its pointer to the Signature bullet + // now stays inside this file) and the platform-code list of § Integrations are declared, not + // coded, as `## When the answer is platform code`. The file is 10379 -> 12222 bytes (+1843) -> 3056 tokens, zero headroom before, ceiling +461, pinned AT the + // measurement. Authority as the `references/examples-objects.md` row. + // ceil($(wc -c < skills/objectstack-automation/references/integration-recipes.md) / 4) == ceil(12222 / 4) + ['skills/objectstack-automation/references/integration-recipes.md', 3056], // 5569 -> 5587 (card #26298, audit #26184 row A2): the approval config table // gains `excludeSubmitter` (refused beside `onEmptyApprovers: 'auto_approve'`), // +105 tokens. Paid down first: Best Practices 1 and 4 restated the Branching @@ -2115,7 +2298,38 @@ export const CEILINGS = new Map([ // rename that dropped its intro line (-14) and left headroom, then the // review's module pointer paid by the custom-Page aside (the ui skill's // rule); the row follows the measurement down, zero headroom. - ['skills/objectstack-data/references/examples-objects.md', 1723], // -5 to the measurement (was 1728) + // 1728 -> 3585 (#34770): RECEIVES what the router split moved out of SKILL.md, no new + // teaching: `## Object keys` (of the optional-properties table the rows the entry's Object + // Definition no longer carries: `color`, `highlightFields`, `nameField`, `ownership`; of the + // `enable` table `fieldHistory`, `trackHistory`, `apiMethods`, `feeds`, `activities`, + // `aiReadable`), `## Search Fields (searchableFields)` and `## Object Extension Model` + // (`place` and the paired `.custom` package's arrangement among it), each whole but for the + // one sentence the entry's trap 2 and trap 3 now state. Not carried over, each a row the + // contract `data/object.zod.ts` states and the section now points at: `label`, `datasource`, + // `displayNameField`, `enable`, `fieldGroups`, `lifecycle`, `searchable`, `apiEnabled`, + // `files`, `clone`; and `titleFormat`, which a save and `os validate` refuse by name. The file + // is 6892 -> 14338 bytes (+7446) -> 3585 tokens, the row's 5 tokens of headroom absorbed, + // ceiling +1857, pinned AT the measurement; the six objectstack-data files this change touches + // are 2344 bytes smaller together (92992 -> 90648). + // Authority: the ruling of record that orders the entry file down to router size, decision + // record 6943107981 S3 = A (this header: a ruling of record that orders text into a file + // authorises its own measured delta), and the maintainer's ruling of 2026-11-24 on the seven + // receiving rows of this change (ruling record 7128031203, fork 4 = A): a ceiling raised + // because text MOVED between files is accepted when each raised row equals the measured bytes + // moved in, with zero headroom, and the sum of ceilings does not rise. Both hold here: every + // row is pinned AT its measurement, and the nine rows this change moves sum to 34386, + // under the 34426 before it, the +430 ruling record 7168461386 orders into the + // objectstack-automation entry set aside. Beside the standing 2026-10-27 ruling 「A:先削重复,余额按实测提高」 (record 6513306068); + // as the objectstack-ui rows of part 1. + // ceil($(wc -c < skills/objectstack-data/references/examples-objects.md) / 4) == ceil(14338 / 4) + // 3585 -> 3611 (#34770, the merge of `main`): while the change was open `main` rewrote the + // entry's sentence on what the paired `.custom` extension alone writes (`actionLayout` beside + // `fieldGroups` and `relatedLists`, and where an action's own `locations` and `order` go). That + // sentence lives here now, in § Object Extension Model, so `main`'s words replace it here, + // verbatim: +103 bytes of text `main` had already landed in the entry. 14338 -> 14441 bytes -> + // 3611 tokens, pinned AT the measurement; authority as the block above. + // ceil($(wc -c < skills/objectstack-data/references/examples-objects.md) / 4) == ceil(14441 / 4) + ['skills/objectstack-data/references/examples-objects.md', 3611], // 970 -> 934: one row for `relationship/inline-edit-needs-bulk`, and the closing "target a // lint-clean model" paragraph cut — it restated the table's rows one by one. 3829 -> 3735 // bytes -> ceil(3735 / 4) = 934; the row follows the measurement down, zero headroom. diff --git a/skills/objectstack-automation/SKILL.md b/skills/objectstack-automation/SKILL.md index 97b3e32af34..bf116e8be69 100644 --- a/skills/objectstack-automation/SKILL.md +++ b/skills/objectstack-automation/SKILL.md @@ -18,68 +18,60 @@ metadata: # Automation Design — ObjectStack Automation Protocol -## When to Use This Skill - -Also vendor-integration callbacks and **assignment rules**. - -> **Predicates and conditions are CEL** — every `condition` / `guard` / -> `entryCondition` / filter `value` is an **Expression** envelope: a plain CEL -> string, or the `P\`...\`` / `cel\`...\`` tag (author-time validation); pick one -> per file. +## First checks + +1. **Version.** Read the installed `@objectstack/spec` + (`node_modules/@objectstack/spec/package.json`); where it differs from this + skill's `compatibility` line, the installed contract is right. +2. **Read what exists.** Read the object's fields and option `value`s, the + flows already bound to it, and the functions, queues and connectors the + stack declares. +3. **Read the type's contract.** [references/_index.md](./references/_index.md) + points at each type's Zod source in `node_modules/@objectstack/spec/src/`. + `Read` it for exact keys, never from memory. + A running environment serves the parsed shape (`GET /api/v1/meta/types`): + a defaulted key reads as required. +4. **Verify before reporting done.** `os validate`; CEL checks: + **objectstack-formula** § Verify your work. Most traps below pass it. + +**Nothing to read yet?** Say so in a line, then still give the whole +definition as code. + +## Where to go + +Open the file for what you are writing before you write it. + +| Authoring | Open first | +|:--|:--| +| Each flow type's use, control-flow nodes, an installed package's flow, and the rest of each section below | [examples-flows.md](./references/examples-flows.md) | +| Triggers (record change, schedule, date sweep, inbound webhook), `requires` capabilities | [Triggers](./references/examples-flows.md#triggers--event-driven-automation) | +| Routing a new record to a queue or a person | [Assignment rules](./references/examples-flows.md#assignment-rules) | +| An approval, a send-back, an escalation, a state machine | [state-machines-and-approvals.md](./references/state-machines-and-approvals.md) — its state-introspection route is `GET /api/v1/meta/object/:name/state/:field?from=:state` | +| A vendor integration or callback | [integration-recipes.md](./references/integration-recipes.md) | ---- +## Flows -## Flows — Visual Logic Orchestration +**In a project a flow is `defineFlow({ … })` in a `*.flow.ts`**; a JSON block +is that literal. Its `type`: `autolaunched` (no user interaction: started by +events, APIs or other flows), `screen`, `record_change`, `api` (inbound +webhook), or `type: 'schedule'`: a cron / interval cadence on the **start +node's `config.schedule`**, or a per-record date sweep (`config.timeRelative`). -### Flow Types +`variables` is an **array**; a variable has no `label`: `variables: [{ name: 'case_id', +type: 'text', isInput: true }, { name: 'approval_result', type: 'boolean', isOutput: true }]`. -| Type | When to Use | -|:--|:--| -| `autolaunched` | No user interaction: started by events, APIs or other flows | -| `screen` | Shows UI screens | -| `schedule` | Runs on a cron/interval cadence declared on the **start node's `config.schedule`**, or a **per-record date sweep** via `config.timeRelative` | -| `record_change` | Fires on record create/update/delete. `autolaunched` + the same `record-*` binding behaves identically; `record_change` also opts into the trigger-readiness lint | -| `api` | Inbound **webhook** (*Inbound webhook triggers*); a flow only ever started explicitly is `autolaunched` | - -**A stepped form over one object that never branches** is no flow: an **objectstack-ui** named form view (`type: 'wizard'`) a `type: 'form'` action opens. - -**A flow an installed package ships** is read-only. To change what it does, save -a same-named flow in the base's paired `.custom` package declaring -`overrides: { package: '', basedOn: '' }` -(**objectstack-platform** § Customizing an installed package): it is armed in the -base's place, keeps the base's name and its one activation switch -(`POST /api/v1/automation/:name/toggle`, `{ enabled: false }` = off for this -deployment), and a run suspended on the old body finishes on that body. An -undeclared same-named flow in the pair or in a dependent is refused at publish. -A flow *beside* it is "new similar": `POST /api/v1/automation/:name/clone` -`{ name, label, package? }` lands the copy switched off in the pair, never -package-less; a flow holding a `secret` / `signingSecret` is refused (`409`): author -it anew. - -A package ships a flow **switched off** with `defaultActive: false` (beside -`status: 'active'`): unarmed (`_status` `enabled: false`) until an administrator -turns that switch on, which then outlives restart, upgrade and reinstall. -`status: 'obsolete'` disarms past the switch; a flow authored in the deployment -is refused the key (its switch is `status`). +**A trigger is the start node's `config`**; there is no top-level `trigger`, +`event` or `schedule` key. A record change: +`{ objectName: 'support_case', triggerType: 'record-after-update', condition: "previous.status != 'escalated' && record.status == 'escalated'" }`. +Guard a flow that writes its own object, or +it re-triggers itself. `defineStack({ requires })` +lists `automation` and `triggers`. ### Flow Node Types -Built-in (plugins register more; a `type` none runs is refused at a server's publish, `flow-node-type-no-executor`): - -#### Control Flow - -| Node | Purpose | -|:--|:--| -| `start` | Entry point: exactly one per flow | -| `end` | Exit point: one or more | -| `decision` | Branch by **edge `condition` predicates**, not node config | -| `loop` | Iterate a **nested `config.body` region** once per item of `config.collection` — a CEL value envelope or an inline list, never a string; `iteratorVariable` (default `item`) and optional `indexVariable` bind inside it, `maxIterations` caps it | -| `parallel` | Fan out into `config.branches[]` (≥ 2 regions) run concurrently, **joined implicitly** at block end | -| `try_catch` | Run `config.try`; on failure run `config.catch` with the error in `errorVariable` (default `$error`); `config.retry` re-runs `try` with backoff first; in a `record-after-*` flow it (or `errorHandling.strategy: 'retry'`) may not reach an inline `http` / `connector_action`: the save would wait out every attempt. Inside a `subflow` / `map` child, retried by either flow, that is **silent**: the flow saves but never arms (`GET /api/v1/automation/_status`: `bound: false`, `unboundCause: retried_callout_in_subflow`) until the child's `http` is `durable: true` or nothing retries the call. **No `finally`** — the container's ordinary out-edges are the continuation | -| `map` | Sequential multi-instance — invoke the `config.flowName` flow (named as `subflow`'s) per item of `config.collection` (shaped as `loop`'s); each may pause (batch approvals); a refused name fails it at the first item | -| `wait` | Pause for a timer or a named signal | -| `subflow` | Invoke the flow bare `config.flowName` names: a package's flow gets its own, else the one holder in its `dependencies` closure plus `sys`; a package-less flow, the environment's, else the one package holder. Else the node fails at run time (`subflow 'X' failed: …` naming every candidate; no `code`): `outside-closure` — held only by an undeclared package (declare it) or the environment; `ambiguous-in-closure` / `ambiguous-in-environment` — two packages hold it (package / package-less caller). `os validate` warns `flow-subflow-unknown` on any name this stack lacks, a correct cross-package call included | -| `parallel_gateway` / `join_gateway` / `boundary_event` | BPMN-interop forms a `parallel` / `try_catch` container lowers into; author the container | +Control flow and every node's `config`: +[Flow Node Types](./references/examples-flows.md#flow-node-types). A human +sign-off is an `approval` node (`type: 'approval'`). #### Data Operations @@ -96,31 +88,21 @@ Built-in (plugins register more; a `type` none runs is refused at a server's pub | Node | Purpose | |:--|:--| -| `http` | Call an HTTP API — set `timeoutMs`, or it has no timeout and warns (`flow-http-timeout-missing`). `url` and `headers` are served as written with the definition to every member who can read flows — only `signingSecret` and a start node's `secret` are withheld — so never a credential there: use a declared connector via `connector_action`. Retried after a record change: `durable: true` (outbox-queued, else sent once in the background, unretried; no response) | +| `http` | Call an HTTP API. Set `timeoutMs`. `url` and `headers` are served to every member who can read flows: never a credential there, use a declared connector. Retried after a record change: `durable: true` | | `notify` | Send a notification (below) | -| `connector_action` | Dispatch an action of a declared connector (§ *Integrations are declared, not coded*) or a plugin's. `connectorConfig.input` is a value-slot map like `subflow` `input`. Evaluated, it is judged against the action's `inputSchema` (`required`, `type`, `items`, a key outside listed `properties`) before dispatch: a breach fails the step `VALIDATION_ERROR` (`fault`-routable); `os validate` does not judge that fit yet. Retried after a record change: drop the retry, or run the flow on demand / on a schedule | +| `connector_action` | Dispatch an action of a declared connector (§ *Integrations are declared, not coded*). `connectorConfig.input` is a value-slot map, judged against the action's `inputSchema` only at dispatch | | `script` | Call a **registered** function (*Valid-but-silently-wrong* #3) | -| `screen` | Display a UI form (screen flows only). `config.fields[]`: `{ name, label, type, required, options, defaultValue }`, `type` an open widget hint; `'file'` renders the upload widget and resumes with the `sys_file` id bound to `name` — a later `create_record` / `update_record` writes it into a `file` field, which claims the file: collect first, write after the last screen. `'record_link'` (never `'record'`, an object field type) takes no input — it shows the `reference` record whose id `defaultValue` evaluates to, by display name, as a link to its record page: the result screen of a flow that created records, `{ name: 'account_link', type: 'record_link', reference: 'crm_account', defaultValue: { dialect: 'cel', source: 'account.id' } }` over a `create_record` `outputVariable: 'account'`. Both keys required; `required` / `options` / `placeholder` / `min` / `max` refused; a resume value under its name refused (`400 INVALID_SCREEN_INPUT`). A completed `end` `message` is refused and a markdown link in a screen `description` renders literally. Next / Submit and "Step N of M" are not authored: the engine reads the graph when the screen pauses and serves `progress`, which alone labels the button and draws the counter. A `decision`, `fault` edge, loop back, non-screen pause (`approval`, `wait`) or `subflow` after a screen means "Next", no count. `progress` in a node `config` is refused | - -#### Human Decision - -| Node | Purpose | -|:--|:--| -| `approval` | Route a record for human sign-off | +| `screen` | Display a UI form (screen flows only): `config.fields[]`. An upload is `type: 'file'`, a link to a created record `type: 'record_link'`; Next / Submit is never authored | ### `notify` -An undeclared key is a named parse error. **RAW** keys are read as written: -a `{token}` in one is refused. As JSON (TypeScript: the same -literal, a `FlowNode`): +As JSON (TypeScript: the same literal, a `FlowNode`): ```json { "id": "tell_owner", "type": "notify", "label": "Notify Owner", "config": { "recipients": { "dialect": "cel", "source": "record.owner_id" }, "title": "Done: {{ record.title }}", "message": "Closed {{ record.closed_at | date:long }}", - "topic": "task", - "severity": "warning", "channels": ["inbox"], "sourceObject": "task", "sourceId": { "dialect": "cel", "source": "record.id" }, @@ -128,181 +110,72 @@ literal, a `FlowNode`): } } ``` -- `recipients` — REQUIRED: id, list, or envelope; a CSV is ONE id. 4th form - `{ "emailField": "applicant_email" }`: an `email` field of the trigger record, - for a non-user — then `channels: 'email'` alone. An envelope must yield USER - ids: an address no user holds fails the node. -- `title` — inline; XOR `template` (RAW, localizable). `message` — body; only - with inline `title`. -- RAW: `topic` (default `'notify'`), `severity` (CLOSED enum - `info` | `warning` | `critical`), `channels` (default inbox). -- `sourceObject` + `sourceId` — the link: a PAIR, else dropped; none of the 3 ⇒ - the trigger record (not on delete/before-create), if any. `actionUrl` - overrides the pair. - -A recipient string, written or evaluated, may be an audience selector: - -- `team:ID` — that team's members. -- `owner_of:OBJECT:ID` — that record's owner; a computed id: `source: "'owner_of:crm_case:' + record.case_id"`. -- `org:members` — every member of the run's organization, else that of the record the notification is about, else nobody (`single` posture: a `schedule` flow declaring no `organization`, no record). Any other `org:` value reaches nobody too. Each warns in the server log only; the node succeeds. +- `recipients` — REQUIRED: id, list, or envelope yielding USER ids. A non-user + is `{ "emailField": "applicant_email" }` with `channels: 'email'` alone; an + audience is a selector string (`team:ID`, `owner_of:OBJECT:ID`, + `org:members`). +- `title` is inline XOR `template`. `sourceObject` + `sourceId` are a PAIR; + with neither and no `actionUrl` the notice links to the trigger record. An option label in a notice: `{{ stage | option:opportunity.stage }}` in the mail `template` (each recipient's language; mail-only, refused in inline `title` / `message`) — never `label()` in `templateData`, evaluated once per run, before fan-out. -### Flow Variables - -`variables` is an **array**; a variable has no `label`: `variables: [{ name: 'case_id', -type: 'text', isInput: true }, { name: 'approval_result', type: 'boolean', isOutput: true }]`. - -→ [references/examples-flows.md](./references/examples-flows.md) § Flow Example — Auto-Escalate Overdue Cases. - ### Failure routing & `runAs` -> **Handling a failed node: a `fault` edge.** `{ source, target, type: 'fault' }` -> routes a failed node to a handler instead of ending the run. **A -> `label: 'error'` alone does nothing:** an ordinary edge -> traverses on SUCCESS (`objectstack validate` reports `flow-error-label-not-fault`). -> A handled failure does not consume the flow-level retry -> (`errorHandling.strategy: 'retry'`), which replays from the start — prefer a fault edge for a local failure. The handler -> reads `{{ .error }}` (run-wide `{{ $error.message }}`; in CEL, -> `vars["$error"]`); the run then reports success and the failed step stays in the trace. - -| ROUTES (runtime failure) | Does NOT route (fatal either way) | -|:--|:--| -| 404, rate-limit, rejected write, failed subflow | missing required config key (`objectName`, `url`, `flowName`, `connectorId`/`actionId`); filter operand that evaluated to `null` or a non-value; graph past the nesting ceiling; unscoped run | - -> **Writing a `readonly` field? Set `runAs: 'system'`** (approval stamps, SLA -> markers, rollups). Under the default -> `runAs: 'user'` the engine **strips** it from `create_record` / `update_record` -> — the step succeeds, the drop is named in the step's -> warnings; `os validate` / `os build` fail a `runAs:'user'` -> `update_record` writing one (`readonlyWhen`: a warning). -> A button, an action, an endpoint or the trigger route does not let a user -> start an `autolaunched`, `record_change` or `schedule` flow declared -> `runAs: 'system'` (403 `PERMISSION_DENIED`), so for a flow a user starts from a -> button the elevated routes are a `screen` or `api` flow declared -> `runAs: 'system'`, or a user-run flow whose `subflow` node calls the elevated flow. - -> **Elevate the write, not the flow.** Prefer the `subflow` route — raising a -> whole `screen` flow silently elevates every other write in it, and an `api` -> flow adds a webhook secret and an inbound endpoint a button never uses. -> -> **Elevation stops at identity assignment.** A `runAs: 'system'` write (insert -> through purge) of `sys_user_position`, `sys_user_permission_set`, -> `sys_invitation` or `sys_member` is refused `PERMISSION_DENIED`, a system -> subflow included. Grant positions and permission sets from a `runAs: 'user'` -> flow — the delegated-administration gate judges that user and records them as -> `granted_by`; invitations and memberships change through the organization -> endpoints (row 1b, https://objectstack.ai/docs/permissions/system-context#1-authorization-and-scoping). -> -> **A `runAs: 'system'` sweep must pin its organization.** System context has no -> trigger user, so a scan or rollup with no organization predicate reads and -> writes across every tenant; filter on the platform-injected tenant column, never -> re-declare it per object. - -> **Who may START a flow: `requiredPermissions: ['…']` on the flow** — the -> four entrances above refuse a non-system caller missing any named capability -> with `403 PERMISSION_DENIED`; an action starting it inherits the list, a -> `subflow` node is not an entrance. Gate an elevated `screen` / `api` flow -> here, never on `current_user.positions` inside it. - -> **A hook elevates itself with `runAs`, never with `sudo`.** An object hook -> (objectstack-data) declares its own `runAs: 'system' | 'user' | 'inherit'` — -> default `'inherit'`, the context of the write that fired it — scoping that -> hook's `ctx.api` data operations only, on the in-process `handler` and the -> sandboxed `body` alike. A `'user'` hook whose trigger resolved no user has -> nothing to scope to: its `ctx.api` data operations are refused -> (`HOOK_UNSCOPED_DATA_ACCESS`, 403) rather than run unscoped. +- **A failed node is routed by a `fault` edge**, `{ source, target, type: 'fault' }`. + A `label: 'error'` alone does nothing: an ordinary edge traverses on SUCCESS. +- **Writing a `readonly` field? Set `runAs: 'system'`.** Under the default + `runAs: 'user'` the engine **strips** it and the step succeeds. A button + cannot start a `runAs: 'system'` `autolaunched`, `record_change` or + `schedule` flow: elevate the write, not the flow, through a `subflow` + node. +- **Elevation stops at identity assignment**: a `runAs: 'system'` write of + `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or + `sys_member` is refused `PERMISSION_DENIED`: grant from a `runAs: 'user'` + flow. +- **A `runAs: 'system'` sweep must pin its organization**, or it reads and + writes across every tenant. +- **Who may START a flow: `requiredPermissions: ['…']` on the flow.** Gate an + elevated `screen` / `api` flow here, never on `current_user.positions` + inside it. ### Filter operands (`config.filter`) -- **Each operand is a value slot**, evaluated - before the query. - A whole-string **query placeholder** (`{current_user_id}`, `{today}`, - `{current_year_start}`) passes through verbatim for the query engine; a flow - variable never shadows it, and only `filter` gets this hand-off. -- **An operand that evaluates to `null` refuses the node**: a dropped condition - does not narrow a query, it widens it, so a routed `delete_record` would empty - the object while the run reports success. Where the value may be absent, - route around the node with a `decision`; to match an empty field, write the - literal `null`. A relation hop (`record.owner.email`) needs the start node's - `config.expand` to list the field — else the fault names the missing hop, not - the remedy. -- **A computed operand is a value, never a query operator**: a string, number, - bigint, boolean or date, or at an `$in` / `$nin` / `$between` comparand a list - of them with no empty entry. Anything else fails the node as a guard. - Make the expression evaluate to the compared value (for a record, - its `id`), and write conditions in the filter itself. - ---- +Each operand is a value slot, evaluated before the query; a whole-string query +placeholder (`{today}`) passes through verbatim. **An +operand that evaluates to `null` refuses the node** (a dropped condition +widens a query). Route around the node with a `decision`; to match an empty +field, write the literal `null`. A computed operand is a value, never a query +operator. ## Valid-but-silently-wrong (passes build, fails at runtime) Most are caught by `objectstack build`: 1. **A value slot takes a literal or a CEL envelope — never a `{…}` token.** - In `assignments.*`, `fields.*`, `subflow` / `map` `input.*`, `script` - `inputs.*`, `loop` / `map` `collection`, notify `recipients` / - `templateData.*` / `sourceId`, `http` `body` and every CRUD `filter` - operand, a string is the literal text it spells, and a `{…}` token is - **refused** — at `objectstack validate` (`expression-invalid`), - `registerFlow` and the executor — naming its CEL spelling. Compute with - `{ dialect: 'cel', source: '…' }`: - - `'{record.owner}'` → `source: 'has(record.owner) ? record.owner : null'` — - CEL refuses an absent key where the template wrote nothing, so nothing / - `null` / a default is now YOUR call; `'{record.tags.0}'` → `'record.tags[0]'`; - a deep path guards each step: `has(vars.source) && has(vars.source.id) ? vars.source.id : null` - - run user: `{$User.Id}` → `current_user.id`; a flow that can run without a - user guards it, `current_user != null ? current_user.id : null`. - `current_user` holds `id`, `positions`, `organizationId`, `isPlatformAdmin` - only — an email or a name is a `sys_user` read by that id - - Text slots (notify `title` / `message` / `actionUrl`, screen `title` / - `description`, end `message`, `http` `url` / `headers`) render `{{ }}` - holes — a variable path, optional formatter (a `default:` argument is - literal text, never a path), no logic; a `{…}` token there - is refused with its `{{ }}` spelling. A date or the run user has no hole: - assign it first (`assignments: { v: { dialect: 'cel', source: - 'current_user.id' } }`), then write `{{ v }}`. - `create_record` / `update_record` `fields` also take a text slot, marked - `{ dialect: 'template', source }`, for a sentence people read. It is written - in the organization's language (Localization setting if set, else - `i18n.defaultLocale`; key: **objectstack-i18n**), never the run starter's; - untranslated, the authored text; an unreadable setting fails the node. A - bare string stays a literal, never translated. - + In `assignments.*`, `fields.*`, `input.*`, `inputs.*`, `collection`, notify + `recipients`, `http` `body` and every `filter` operand a string is the + literal text it spells, and a `{…}` token is **refused** — at + `objectstack validate` (`expression-invalid`), `registerFlow` and the + executor — naming its CEL spelling. Compute with + `{ dialect: 'cel', source: '…' }`: a field that may be empty is + `source: 'has(record.owner) ? record.owner : null'`, the run user + `current_user.id`. Text slots (notify `title` / `message`, `http` `url`) + render `{{ }}` holes. 2. **`create_record`'s `outputVariable` holds the created RECORD, not its id.** - ❌ `fields: { ref: { dialect: 'cel', source: 'newRec' } }` ✅ `source: 'newRec.id'` - -3. **`script` nodes call a registered function — nothing else.** `config.function` - (**required**: an empty node refuses at execute, an unregistered name fails - loudly) names one registered in `defineStack({ functions })`. - - **The name resolves from the flow's package, as `subflow`'s `flowName` - does**, the platform's ownerless function in every flow's reach; a - `.custom` override reads as a package-less flow. Packages of two - `namespace`s each run their own `normalize_phone`. One namespace (or - none): both held at boot warn `Bare-name conflict at boot`; a later one - installs but binds NONE of its functions or hooks (error `Failed to bind - declarative hooks`): rename, or another namespace. If the flow's package - holds none, two holders in reach or one only outside its `dependencies` - closure fail the step as a guard (no `fault` edge; `$error.code: - 'RESOURCE_CONFLICT'` in a `try_catch`); a flow door's `innerRefusal` names - each holder. Fix: declare the dependency, or rename. - - **A flow `function` is a PURE compute step — it does NOT read/write the - database.** It receives `ctx.input` and **returns** a value; a later - **declarative** node persists its `outputVariable`: +3. **`script` nodes call a registered function — nothing else.** + `config.function` names one registered in `defineStack({ functions })`: a + PURE compute step that receives `ctx.input` and **returns** a value. A + later **declarative** node persists its `outputVariable`: ```json [ { "id": "ai", "type": "script", "label": "AI Triage", "config": { - "function": "helpdesk.aiTriageStub", - "inputs": { "ticketId": { "dialect": "cel", "source": "record.id" } }, - "outputVariable": "ai" } }, + "function": "helpdesk.aiTriageStub", "outputVariable": "ai", + "inputs": { "ticketId": { "dialect": "cel", "source": "record.id" } } } }, { "id": "apply", "type": "update_record", "label": "Apply Category", "config": { "objectName": "helpdesk_ticket", "filter": { "id": { "dialect": "cel", "source": "record.id" } }, @@ -310,171 +183,33 @@ Most are caught by `objectstack build`: ] ``` - A function that writes where the platform cannot see **declares** it, so the - run reports "cannot say" rather than `acted: 0` (project code — a function - has no JSON form): + A function that writes where the platform cannot see declares it (project + code, no JSON form): ```ts - defineStack({ functions: { - 'billing.sync': { handler: syncBilling, effect: 'writes' }, - } }); + defineStack({ functions: { 'billing.sync': { handler: syncBilling, effect: 'writes' } } }); ``` -4. **A `select` is compared and written by its option `value`, never its label.** - The request says "Lost"; the row stores `lost`. - A start or edge `condition: "record.status == 'Lost'"`, or `filter` / - `fields: { status: 'Lost' }`, is refused at publish (inline options), else - matches no row or fails the run (`invalid_option`); a filter for rows still - holding the label takes a CEL envelope operand. Read the field's `options`. - ---- - -→ State Machines & Approvals: [references/state-machines-and-approvals.md](./references/state-machines-and-approvals.md) — its state-introspection route is `GET /api/v1/meta/object/:name/state/:field?from=:state`. +4. **A `select` is compared and written by its option `value`, never its + label.** A label is refused at publish (inline options), else it matches + no row or fails the run. ---- - -## Assignment rules — route a new record to a queue or a person - -`assignmentRules` on the stack routes each inserted -row of an `ownership: 'user'` object whose `owner_id` and `queue` are both still -empty — once, after every `beforeInsert` hook, never on update, never refusing the -insert. Entries are ordered; the first whose `criteria` (CEL over -`record.*`) match decides: - - -```typescript -import { defineAssignmentRule } from '@objectstack/spec/automation'; - -export const caseIntake = defineAssignmentRule({ - name: 'crm_case_intake', - object: 'crm_case', - entries: [ - { name: 'urgent', criteria: 'record.priority == "urgent"', - assignTo: { type: 'queue', value: 'crm_escalations' } }, // no strategy: parked for a claim - { name: 'rest', assignTo: { type: 'queue', value: 'crm_support_intake' }, - strategy: 'least_loaded', load: 'record.status != "closed"' }, // or 'round_robin'; `load` only with least_loaded - ], -}); -``` - -`strategy` is for a queue target only; `assignTo: { type: 'user', value: '' }` -names one owner, who holds the row only while an active member of its organization -(else ownerless). Queues are declared in `queues` (objectstack-data); an approval -for the same people is a `queue` approver ([Approver Types](./references/state-machines-and-approvals.md#approver-types)). -⛔ Never a `beforeInsert` hook that picks an owner, nor a round-robin counter field. - -**A packaged rule's queue** is its package's own, else the one holder -in its `dependencies` closure plus `sys`: `acme.helpdesk` naming `acme.crm`'s queue -declares `dependencies: { 'acme.crm': '^1.0.0' }`. Else refused — `outside-closure` -(an undeclared package's or environment-only queue), `ambiguous-in-closure` (two -in it) — the row is written ownerless, in no queue, and the server log warns once -(`… does not resolve … from the rule's package`). An organization's -`sys_assignment_rule` row and a rule no package ships read environment-wide (two -package holders: `ambiguous-in-environment`). A name no `queues` entry declares -reads the organization's `sys_queue` row. - ---- - -## Triggers — Event-Driven Automation - -There is **no standalone trigger -object and no top-level `trigger` / `event` key**. +## Assignment rules -### Prerequisite — declare the capabilities your nodes need +Routing a new record to a queue or a person is a stack `assignmentRules` +entry, ⛔ never a `beforeInsert` hook that picks an owner, nor a round-robin +counter field: -Metadata registers without its `defineStack({ requires })` token. Two pairs are -instead **refused** at `os validate` / `build` / `dev` / `serve` (422); neither -token implies the other: +`defineAssignmentRule({ name: 'crm_case_intake', object: 'crm_case', entries: [{ name: 'rest', assignTo: { type: 'queue', value: 'crm_support_intake' }, strategy: 'round_robin' }] })` -| `requires` token | Turns on | Absent ⇒ | -|:--|:--|:--| -| `automation` | the flow engine + node executors | flows never execute | -| `triggers` + `automation` | `record-*` / schedule / `api` start bindings | auto-launched flow refused: `STACK_TRIGGER_CAPABILITY_REQUIRED` | -| `job`° | cron cadence + the `timeRelative` sweep | scheduled flows never launch | -| `queue`° | the inbound-webhook consumer | inbound POST answers **503** | -| `approvals` | `approval` / `approval_revise` (`plugin-approvals`) | no executor for the node type | -| `messaging`° | `notify` delivery to inbox (`sys_inbox_message`) | **silent:** success with `skipped: true` | -| `webhooks` + `realtime` | `defineStack({ webhooks })` outbound dispatch | declared webhook refused: `STACK_WEBHOOK_CAPABILITY_REQUIRED` | - -° Always-on, so list it only under `--preset minimal` (**objectstack-platform** § `requires:`). - -### Inbound webhook (`api`) triggers (ADR-0041 Tier 1) - -`POST /api/v1/automation/hooks/:flowName/:hookId`, configured on the -**start node `config`**: - -| `config` key | Purpose | -|:--|:--| -| `hookId` | URL path token (default `'default'`). **Rotate it to revoke** a leaked endpoint | -| `secretRef` / `secret` | HMAC-SHA256 secret, **one required** (else refused at registration and `os validate`). Ship `secretRef: 'NAME'`: an env var the deployment fills, not `OS_*`; unfilled ⇒ `503`. Never a literal | - -- **Signature:** `x-objectstack-signature: t=,v1=` — HMAC of `.`; `t` within 300 s. Vendor-signed: `config.signature` replaces it (recipe 4). -- **Idempotency:** `x-idempotency-key` dedupes retries — delivery is at-least-once: author the flow idempotent. -- **Queue-backed:** it ACKs `202` and enqueues; the flow runs on the consumer. -- The JSON body is the flow's trigger record (`record.*` / bare fields) plus `params`. -- **A flow name two packages hold:** the bare hook answers `401 INVALID_SIGNATURE` whatever the signature (cause: server log only). Each package's flow answers only at `…/hooks/:namespace/:flowName/:hookId`, by its `manifest.namespace` (`_env`: a flow no package ships). -- **A disabled package's flow:** that `401` at both addresses, nothing enqueued; once enabled, a sender's retry gets `202`. - -### Trigger Types (start-node `config.triggerType`) - -| `triggerType` | ObjectQL hook | -|:--|:--| -| `record-before-create` (can modify/reject) | `beforeInsert` | -| `record-after-create` | `afterInsert` | -| `record-before-update` | `beforeUpdate` | -| `record-after-update` | `afterUpdate` | -| `record-before-delete` | `beforeDelete` | -| `record-after-delete` | `afterDelete` | -| `record-before-write` / `record-after-write` — one flow, both events | insert + update hooks | - -### Trigger Configuration — on the `start` node - -```typescript -{ - id: 'start', - type: 'start', - label: 'On Case Escalated', - config: { - objectName: 'support_case', - triggerType: 'record-after-update', - condition: "previous.status != 'escalated' && record.status == 'escalated'", - }, -} -``` - -> **Prefer `record-after-*`**; **guard** one that writes its own object, or it re-triggers itself. A -> `record-before-*` flow that throws silently blocks the write — give it a -> user-facing message. - -→ [references/examples-flows.md](./references/examples-flows.md) § Time-relative triggers. - ---- +It routes each inserted row whose `owner_id` and `queue` are both still empty, +once, never on update. An approval for the same people is an `approval` node +with `approvers: [{ type: 'queue', value: 'crm_support_leads' }]`. ## Integrations are declared, not coded -A vendor system reachable over HTTP is a -`connectors:` entry inside the app — `provider: 'openapi' | 'mcp' | 'rest'`, a -packaged spec, `auth.credentialRef` (the customer's administrator supplies the -value) — dispatched by `connector_action`. Never a plugin. Recipes, -credential hand-off, loader limits: [references/integration-recipes.md](./references/integration-recipes.md). -Platform code only when one holds — and then it is the platform's, filed as a -card, the app still writing none: the protocol is not HTTP; the work writes -identity objects (users, units, positions); it processes files locally; one fixed -action contract spans several vendors; the callback is signed in no form -`config.signature` declares. A document the loader cannot take yet (YAML, Swagger 2.0, -`$ref`) is a gap named against its platform card. - ---- - -## Verify your work - -`os validate` (`os build` also emits `dist/`); CEL checks: **objectstack-formula** -§ Verify your work. - ---- - -## References - -See [references/_index.md](./references/_index.md) for pointers to the Zod -schemas in `node_modules/@objectstack/spec/src/`. - +A vendor system reachable over HTTP is a `connectors:` entry inside the app +(`provider: 'openapi' | 'mcp' | 'rest'`, a packaged spec, +`auth.credentialRef`), dispatched by `connector_action`. Never a plugin. +Recipes, credential hand-off, loader limits and the few cases that are +platform code: [references/integration-recipes.md](./references/integration-recipes.md). diff --git a/skills/objectstack-automation/evals/flows-triggers-approvals.json b/skills/objectstack-automation/evals/flows-triggers-approvals.json index 242d43f6ff2..fa026622e75 100644 --- a/skills/objectstack-automation/evals/flows-triggers-approvals.json +++ b/skills/objectstack-automation/evals/flows-triggers-approvals.json @@ -16,7 +16,7 @@ ], "must_not_contain": [ "next:", - "values:", + "values: {", "cron`" ] } diff --git a/skills/objectstack-automation/references/examples-flows.md b/skills/objectstack-automation/references/examples-flows.md index 335d57b4170..fa54e1e73db 100644 --- a/skills/objectstack-automation/references/examples-flows.md +++ b/skills/objectstack-automation/references/examples-flows.md @@ -1,4 +1,291 @@ -# Automation — long flow examples +# Automation — flows, triggers and assignment rules + +> **Predicates and conditions are CEL** — every `condition` / `guard` / +> `entryCondition` / filter `value` is an **Expression** envelope: a plain CEL +> string, or the `P\`...\`` / `cel\`...\`` tag (author-time validation); pick one +> per file. + +## Flow Types + +| Type | When to Use | +|:--|:--| +| `autolaunched` | No user interaction: started by events, APIs or other flows | +| `screen` | Shows UI screens | +| `schedule` | Runs on a cron/interval cadence declared on the **start node's `config.schedule`**, or a **per-record date sweep** via `config.timeRelative` | +| `record_change` | Fires on record create/update/delete. `autolaunched` + the same `record-*` binding behaves identically; `record_change` also opts into the trigger-readiness lint | +| `api` | Inbound **webhook** (*Inbound webhook triggers*); a flow only ever started explicitly is `autolaunched` | + +**A stepped form over one object that never branches** is no flow: an **objectstack-ui** named form view (`type: 'wizard'`) a `type: 'form'` action opens. + +## A flow an installed package ships + +It is read-only. To change what it does, save +a same-named flow in the base's paired `.custom` package declaring +`overrides: { package: '', basedOn: '' }` +(**objectstack-platform** § Customizing an installed package): it is armed in the +base's place, keeps the base's name and its one activation switch +(`POST /api/v1/automation/:name/toggle`, `{ enabled: false }` = off for this +deployment), and a run suspended on the old body finishes on that body. An +undeclared same-named flow in the pair or in a dependent is refused at publish. +A flow *beside* it is "new similar": `POST /api/v1/automation/:name/clone` +`{ name, label, package? }` lands the copy switched off in the pair, never +package-less; a flow holding a `secret` / `signingSecret` is refused (`409`): author +it anew. + +A package ships a flow **switched off** with `defaultActive: false` (beside +`status: 'active'`): unarmed (`_status` `enabled: false`) until an administrator +turns that switch on, which then outlives restart, upgrade and reinstall. +`status: 'obsolete'` disarms past the switch; a flow authored in the deployment +is refused the key (its switch is `status`). + +## Flow Node Types + +Built-in (plugins register more; a `type` none runs is refused at a server's publish, `flow-node-type-no-executor`): + +### Control Flow + +| Node | Purpose | +|:--|:--| +| `start` | Entry point: exactly one per flow | +| `end` | Exit point: one or more | +| `decision` | Branch by **edge `condition` predicates**, not node config | +| `loop` | Iterate a **nested `config.body` region** once per item of `config.collection` — a CEL value envelope or an inline list, never a string; `iteratorVariable` (default `item`) and optional `indexVariable` bind inside it, `maxIterations` caps it | +| `parallel` | Fan out into `config.branches[]` (≥ 2 regions) run concurrently, **joined implicitly** at block end | +| `try_catch` | Run `config.try`; on failure run `config.catch` with the error in `errorVariable` (default `$error`); `config.retry` re-runs `try` with backoff first; in a `record-after-*` flow it (or `errorHandling.strategy: 'retry'`) may not reach an inline `http` / `connector_action`: the save would wait out every attempt. Inside a `subflow` / `map` child, retried by either flow, that is **silent**: the flow saves but never arms (`GET /api/v1/automation/_status`: `bound: false`, `unboundCause: retried_callout_in_subflow`) until the child's `http` is `durable: true` or nothing retries the call. **No `finally`** — the container's ordinary out-edges are the continuation | +| `map` | Sequential multi-instance — invoke the `config.flowName` flow (named as `subflow`'s) per item of `config.collection` (shaped as `loop`'s); each may pause (batch approvals); a refused name fails it at the first item | +| `wait` | Pause for a timer or a named signal | +| `subflow` | Invoke the flow bare `config.flowName` names: a package's flow gets its own, else the one holder in its `dependencies` closure plus `sys`; a package-less flow, the environment's, else the one package holder. Else the node fails at run time (`subflow 'X' failed: …` naming every candidate; no `code`): `outside-closure` — held only by an undeclared package (declare it) or the environment; `ambiguous-in-closure` / `ambiguous-in-environment` — two packages hold it (package / package-less caller). `os validate` warns `flow-subflow-unknown` on any name this stack lacks, a correct cross-package call included | +| `parallel_gateway` / `join_gateway` / `boundary_event` | BPMN-interop forms a `parallel` / `try_catch` container lowers into; author the container | + +### External Integration — the rest + +| Node | Beyond its `SKILL.md` row | +|:--|:--| +| `http` | Without `timeoutMs` it has no timeout and warns (`flow-http-timeout-missing`). `url` and `headers` are served as written with the definition — only `signingSecret` and a start node's `secret` are withheld. `durable: true` is outbox-queued, else sent once in the background, unretried; no response | +| `connector_action` | A declared connector's action or a plugin's. `connectorConfig.input` is a value-slot map like `subflow` `input`. Evaluated, it is judged against the action's `inputSchema` (`required`, `type`, `items`, a key outside listed `properties`) before dispatch: a breach fails the step `VALIDATION_ERROR` (`fault`-routable); `os validate` does not judge that fit yet. Retried after a record change: drop the retry, or run the flow on demand / on a schedule | +| `screen` | `config.fields[]`: `{ name, label, type, required, options, defaultValue }`, `type` an open widget hint; `'file'` renders the upload widget and resumes with the `sys_file` id bound to `name` — a later `create_record` / `update_record` writes it into a `file` field, which claims the file: collect first, write after the last screen. `'record_link'` (never `'record'`, an object field type) takes no input — it shows the `reference` record whose id `defaultValue` evaluates to, by display name, as a link to its record page: the result screen of a flow that created records, `{ name: 'account_link', type: 'record_link', reference: 'crm_account', defaultValue: { dialect: 'cel', source: 'account.id' } }` over a `create_record` `outputVariable: 'account'`. Both keys required; `required` / `options` / `placeholder` / `min` / `max` refused; a resume value under its name refused (`400 INVALID_SCREEN_INPUT`). A completed `end` `message` is refused and a markdown link in a screen `description` renders literally. Next / Submit and "Step N of M" are not authored: the engine reads the graph when the screen pauses and serves `progress`, which alone labels the button and draws the counter. A `decision`, `fault` edge, loop back, non-screen pause (`approval`, `wait`) or `subflow` after a screen means "Next", no count. `progress` in a node `config` is refused | + +`approval` routes a record for human sign-off: +[state-machines-and-approvals.md](./state-machines-and-approvals.md). + +## `notify` — the rest + +An undeclared key is a named parse error. **RAW** keys are read as written: +a `{token}` in one is refused. + +- `recipients` — a CSV is ONE id. `emailField` names an `email` field of the + trigger record. An envelope yielding an address no user holds fails the node. +- `template` is RAW and localizable. `message` — body; only with inline `title`. +- RAW: `topic` (default `'notify'`), `severity` (CLOSED enum + `info` | `warning` | `critical`), `channels` (default inbox). +- `sourceObject` + `sourceId` — one without the other is dropped. The trigger + record is the link only when there is one (not on delete/before-create). + `actionUrl` overrides the pair. + +A recipient string, written or evaluated, may be an audience selector: + +- `team:ID` — that team's members. +- `owner_of:OBJECT:ID` — that record's owner; a computed id: `source: "'owner_of:crm_case:' + record.case_id"`. +- `org:members` — every member of the run's organization, else that of the record the notification is about, else nobody (`single` posture: a `schedule` flow declaring no `organization`, no record). Any other `org:` value reaches nobody too. Each warns in the server log only; the node succeeds. + +## Failure routing & `runAs` — the rest + +> **A `fault` edge**: `objectstack validate` reports an `error`-labelled +> ordinary edge (`flow-error-label-not-fault`). A handled failure does not consume the +> flow-level retry (`errorHandling.strategy: 'retry'`), which replays from the +> start — prefer a fault edge for a local failure. The handler reads +> `{{ .error }}` (run-wide `{{ $error.message }}`; in CEL, +> `vars["$error"]`); the run then reports success and the failed step stays in +> the trace. + +| ROUTES (runtime failure) | Does NOT route (fatal either way) | +|:--|:--| +| 404, rate-limit, rejected write, failed subflow | missing required config key (`objectName`, `url`, `flowName`, `connectorId`/`actionId`); filter operand that evaluated to `null` or a non-value; graph past the nesting ceiling; unscoped run | + +> **A `readonly` field** (approval stamps, SLA markers, rollups): the strip from +> `create_record` / `update_record` is named in the step's warnings; +> `os validate` / `os build` fail a `runAs:'user'` `update_record` writing one +> (`readonlyWhen`: a warning). A button, an action, an endpoint or the trigger +> route does not let a user start an `autolaunched`, `record_change` or +> `schedule` flow declared `runAs: 'system'` (403 `PERMISSION_DENIED`), so for a +> flow a user starts from a button the elevated routes are a `screen` or `api` +> flow declared `runAs: 'system'`, or a user-run flow whose `subflow` node calls +> the elevated flow. + +> **Elevate the write, not the flow.** Prefer the `subflow` route — raising a +> whole `screen` flow silently elevates every other write in it, and an `api` +> flow adds a webhook secret and an inbound endpoint a button never uses. +> +> **A `runAs: 'system'` identity write** is refused on every operation, insert +> through purge, a system subflow included. Positions and permission sets granted from a +> `runAs: 'user'` flow are judged by the delegated-administration gate as that +> user, who is recorded as `granted_by`; invitations and memberships change +> through the organization endpoints (row 1b, https://objectstack.ai/docs/permissions/system-context#1-authorization-and-scoping). +> +> **A `runAs: 'system'` sweep**: system context has no trigger user; filter on +> the platform-injected tenant column, never re-declare it per object. + +> **`requiredPermissions`**: the four entrances above refuse a non-system caller +> missing any named capability with `403 PERMISSION_DENIED`; an action starting +> the flow inherits the list, a `subflow` node is not an entrance. Gate an +> elevated `screen` / `api` flow here. + +> **A hook elevates itself with `runAs`, never with `sudo`.** An object hook +> (objectstack-data) declares its own `runAs: 'system' | 'user' | 'inherit'` — +> default `'inherit'`, the context of the write that fired it — scoping that +> hook's `ctx.api` data operations only, on the in-process `handler` and the +> sandboxed `body` alike. A `'user'` hook whose trigger resolved no user has +> nothing to scope to: its `ctx.api` data operations are refused +> (`HOOK_UNSCOPED_DATA_ACCESS`, 403) rather than run unscoped. + +## Filter operands — the rest + +- **Query placeholders** (`{current_user_id}`, `{current_year_start}`, …) are handed to the + query engine; a flow variable never shadows one, and only `filter` gets this + hand-off. +- **A `null` operand**: the dropped condition would let a routed `delete_record` + empty the object while the run reports success. A relation hop + (`record.owner.email`) needs the start node's `config.expand` to list the + field — else the fault names the missing hop, not the remedy. +- **A computed operand** is a string, number, bigint, boolean or date, or at an + `$in` / `$nin` / `$between` comparand a list of them with no empty entry. + Anything else fails the node as a guard. Make the expression evaluate to the + compared value (for a record, its `id`), and write conditions in the filter + itself. + +## Value slots and the other silent traps — the rest + +1. **Value slots** also: notify `templateData.*` / `sourceId`; `input.*` is + `subflow` / `map`'s, `inputs.*` `script`'s, `collection` `loop` / `map`'s, + `filter` a CRUD node's. The spellings a refused `{…}` token is given: + - CEL refuses an absent key where the template wrote nothing, so nothing / + `null` / a default is now YOUR call; an indexed path is `'record.tags[0]'`; + a deep path guards each step: `has(vars.source) && has(vars.source.id) ? vars.source.id : null` + - run user: `{$User.Id}` → `current_user.id`; a flow that can run without a + user guards it, `current_user != null ? current_user.id : null`. + `current_user` holds `id`, `positions`, `organizationId`, `isPlatformAdmin` + only — an email or a name is a `sys_user` read by that id + + Text slots also: notify `actionUrl`, screen `title` / `description`, end + `message`, `http` `headers`. A hole is a variable path, optional formatter + (a `default:` argument is literal text, never a path), no logic; a `{…}` token there + is refused with its `{{ }}` spelling. A date or the run user has no hole: + assign it first (`assignments: { v: { dialect: 'cel', source: + 'current_user.id' } }`), then write `{{ v }}`. + `create_record` / `update_record` `fields` also take a text slot, marked + `{ dialect: 'template', source }`, for a sentence people read. It is written + in the organization's language (Localization setting if set, else + `i18n.defaultLocale`; key: **objectstack-i18n**), never the run starter's; + untranslated, the authored text; an unreadable setting fails the node. A + bare string stays a literal, never translated. + +2. **`script`** (item 3). `config.function` is **required**: an empty node refuses at + execute, an unregistered name fails loudly. + + **The name resolves from the flow's package, as `subflow`'s `flowName` + does**, the platform's ownerless function in every flow's reach; a + `.custom` override reads as a package-less flow. Packages of two + `namespace`s each run their own `normalize_phone`. One namespace (or + none): both held at boot warn `Bare-name conflict at boot`; a later one + installs but binds NONE of its functions or hooks (error `Failed to bind + declarative hooks`): rename, or another namespace. If the flow's package + holds none, two holders in reach or one only outside its `dependencies` + closure fail the step as a guard (no `fault` edge; `$error.code: + 'RESOURCE_CONFLICT'` in a `try_catch`); a flow door's `innerRefusal` names + each holder. Fix: declare the dependency, or rename. + + **A flow `function` does NOT read/write the database.** One that writes + where the platform cannot see declares `effect: 'writes'`, so the run + reports "cannot say" rather than `acted: 0`. + +3. **`select`** (item 4). The request says "Lost"; the row stores `lost`. + A start or edge `condition: "record.status == 'Lost'"`, or `filter` / + `fields: { status: 'Lost' }`, is refused at publish (inline options), else + matches no row or fails the run (`invalid_option`); a filter for rows still + holding the label takes a CEL envelope operand. Read the field's `options`. + +## Triggers — Event-Driven Automation + +There is **no standalone trigger +object and no top-level `trigger` / `event` key**. + +### Prerequisite — declare the capabilities your nodes need + +Metadata registers without its `defineStack({ requires })` token. Two pairs are +instead **refused** at `os validate` / `build` / `dev` / `serve` (422); neither +token implies the other: + +| `requires` token | Turns on | Absent ⇒ | +|:--|:--|:--| +| `automation` | the flow engine + node executors | flows never execute | +| `triggers` + `automation` | `record-*` / schedule / `api` start bindings | auto-launched flow refused: `STACK_TRIGGER_CAPABILITY_REQUIRED` | +| `job`° | cron cadence + the `timeRelative` sweep | scheduled flows never launch | +| `queue`° | the inbound-webhook consumer | inbound POST answers **503** | +| `approvals` | `approval` / `approval_revise` (`plugin-approvals`) | no executor for the node type | +| `messaging`° | `notify` delivery to inbox (`sys_inbox_message`) | **silent:** success with `skipped: true` | +| `webhooks` + `realtime` | `defineStack({ webhooks })` outbound dispatch | declared webhook refused: `STACK_WEBHOOK_CAPABILITY_REQUIRED` | + +° Always-on, so list it only under `--preset minimal` (**objectstack-platform** § `requires:`). + +### Trigger Types (start-node `config.triggerType`) + +`record-before-create` (can modify/reject) / `record-after-create` run on the +ObjectQL `beforeInsert` / `afterInsert` hooks, `record-before-update` / +`record-after-update` on `beforeUpdate` / `afterUpdate`, `record-before-delete` +/ `record-after-delete` on `beforeDelete` / `afterDelete`; +`record-before-write` / `record-after-write` are one flow on both the insert +and the update hooks. + +### Trigger Configuration — on the `start` node + +The `config` itself: `SKILL.md` § Flows. + +> **Prefer `record-after-*`.** A `record-before-*` flow that throws silently +> blocks the write — give it a user-facing message. + +An inbound webhook: [integration-recipes.md](./integration-recipes.md#inbound-webhook-api-triggers-adr-0041-tier-1). + +## Assignment rules + +`assignmentRules` on the stack routes each inserted +row of an `ownership: 'user'` object whose `owner_id` and `queue` are both still +empty — once, after every `beforeInsert` hook, never on update, never refusing the +insert. Entries are ordered; the first whose `criteria` (CEL over +`record.*`) match decides: + + +```typescript +import { defineAssignmentRule } from '@objectstack/spec/automation'; + +export const caseIntake = defineAssignmentRule({ + name: 'crm_case_intake', + object: 'crm_case', + entries: [ + { name: 'urgent', criteria: 'record.priority == "urgent"', + assignTo: { type: 'queue', value: 'crm_escalations' } }, // no strategy: parked for a claim + { name: 'rest', assignTo: { type: 'queue', value: 'crm_support_intake' }, + strategy: 'least_loaded', load: 'record.status != "closed"' }, // or 'round_robin'; `load` only with least_loaded + ], +}); +``` + +`strategy` is for a queue target only; `assignTo: { type: 'user', value: '' }` +names one owner, who holds the row only while an active member of its organization +(else ownerless). Queues are declared in `queues` (objectstack-data); an approval +for the same people is a `queue` approver ([Approver Types](./state-machines-and-approvals.md#approver-types)). +⛔ Never a `beforeInsert` hook that picks an owner, nor a round-robin counter field. + +**A packaged rule's queue** is its package's own, else the one holder +in its `dependencies` closure plus `sys`: `acme.helpdesk` naming `acme.crm`'s queue +declares `dependencies: { 'acme.crm': '^1.0.0' }`. Else refused — `outside-closure` +(an undeclared package's or environment-only queue), `ambiguous-in-closure` (two +in it) — the row is written ownerless, in no queue, and the server log warns once +(`… does not resolve … from the rule's package`). An organization's +`sys_assignment_rule` row and a rule no package ships read environment-wide (two +package holders: `ambiguous-in-environment`). A name no `queues` entry declares +reads the organization's `sys_queue` row. + +## Long examples ### Flow Example — Auto-Escalate Overdue Cases @@ -141,5 +428,5 @@ query placeholder such as `{today}` is refused there (`expression-invalid`). For "days remaining" in a message, use `daysBetween(today(), record.end_date)`. `timeRelative` ships in `@objectstack/trigger-schedule` (its `requires` tokens: -SKILL.md § Prerequisite). Full descriptor schema: +§ Prerequisite above). Full descriptor schema: `node_modules/@objectstack/spec/src/automation/time-relative-trigger.zod.ts`. diff --git a/skills/objectstack-automation/references/integration-recipes.md b/skills/objectstack-automation/references/integration-recipes.md index 03afc0ed6a4..b93ce19e395 100644 --- a/skills/objectstack-automation/references/integration-recipes.md +++ b/skills/objectstack-automation/references/integration-recipes.md @@ -129,7 +129,7 @@ export const CarrierCallback = defineFlow({ ``` `requires: ['automation', 'triggers']`. The sender signs each post -under `CARRIER_HOOK_SECRET` (SKILL.md *Signature* bullet). A vendor signing +under `CARRIER_HOOK_SECRET` (*Signature* bullet below). A vendor signing its own header adds, keyed by that ref, `signature: { signs: 'body', header: 'X-DocuSign-Signature-1', algorithm: 'hmac-sha256', encoding: 'base64' }`. @@ -184,3 +184,29 @@ against the `redirectUri` that `GET …/:name/connection` answers, then connects (no secret for a public client; a reconnect naming no client keeps it). The connection keeps it encrypted; a read shows `client: { source: 'installer', clientId, hasSecret }`. Still never park a short-lived token behind a `bearer` ref. + +## Inbound webhook (`api`) triggers (ADR-0041 Tier 1) + +`POST /api/v1/automation/hooks/:flowName/:hookId`, configured on the +**start node `config`**: + +| `config` key | Purpose | +|:--|:--| +| `hookId` | URL path token (default `'default'`). **Rotate it to revoke** a leaked endpoint | +| `secretRef` / `secret` | HMAC-SHA256 secret, **one required** (else refused at registration and `os validate`). Ship `secretRef: 'NAME'`: an env var the deployment fills, not `OS_*`; unfilled ⇒ `503`. Never a literal | + +- **Signature:** `x-objectstack-signature: t=,v1=` — HMAC of `.`; `t` within 300 s. Vendor-signed: `config.signature` replaces it (recipe 4). +- **Idempotency:** `x-idempotency-key` dedupes retries — delivery is at-least-once: author the flow idempotent. +- **Queue-backed:** it ACKs `202` and enqueues; the flow runs on the consumer. +- The JSON body is the flow's trigger record (`record.*` / bare fields) plus `params`. +- **A flow name two packages hold:** the bare hook answers `401 INVALID_SIGNATURE` whatever the signature (cause: server log only). Each package's flow answers only at `…/hooks/:namespace/:flowName/:hookId`, by its `manifest.namespace` (`_env`: a flow no package ships). +- **A disabled package's flow:** that `401` at both addresses, nothing enqueued; once enabled, a sender's retry gets `202`. + +## When the answer is platform code + +Platform code only when one holds — and then it is the platform's, filed as a +card, the app still writing none: the protocol is not HTTP; the work writes +identity objects (users, units, positions); it processes files locally; one fixed +action contract spans several vendors; the callback is signed in no form +`config.signature` declares. A document the loader cannot take yet (YAML, Swagger 2.0, +`$ref`) is a gap named against its platform card. diff --git a/skills/objectstack-automation/references/state-machines-and-approvals.md b/skills/objectstack-automation/references/state-machines-and-approvals.md index b04c008886d..a9d0ee5c085 100644 --- a/skills/objectstack-automation/references/state-machines-and-approvals.md +++ b/skills/objectstack-automation/references/state-machines-and-approvals.md @@ -222,11 +222,11 @@ an id that does not exist gets. | `department` | A department + all descendant departments | | `manager` | The submitter's manager (`sys_user.manager_id`) | | `field` | User id read from a record field (`value` = field name). Resolved against the record's **live** state at node entry, so a field written mid-flow routes correctly; a multi-select user field fans out into one approver per user | -| `queue` | Members of ownership queue `value` at node entry; an empty queue adds nobody. In a packaged flow, see below | +| `queue` | Members of ownership queue `value` at node entry; an empty queue adds nobody. A packaged flow: below | | `expression` | A **CEL expression** resolved at node entry (`value` = the expression string) — see **Dynamic approvers** below. The optional `resolveAs: 'user'(default) \| 'department' \| 'position' \| 'team'` re-expands each resolved id through the graph | **A packaged flow's `queue` approver** (ADR-0150 D3) resolves `value` as a -packaged assignment rule does (SKILL.md § Assignment rules), from the package +packaged assignment rule does (examples-flows.md § Assignment rules), from the package whose flow body runs; a disabled package holds none. `acme.deals` naming `acme.crm`'s `crm_finance` declares `dependencies: { 'acme.crm': '^1.0.0' }`. Refused (`outside-closure`, `ambiguous-in-closure`), the node opens no request: diff --git a/skills/objectstack-data/SKILL.md b/skills/objectstack-data/SKILL.md index f2e7fd1f56c..e1e6f822b25 100644 --- a/skills/objectstack-data/SKILL.md +++ b/skills/objectstack-data/SKILL.md @@ -18,41 +18,84 @@ metadata: # Data Modeling — ObjectStack Data Protocol -## Skill Boundaries - -| Need | Use instead | -|:-----|:------------| -| Query, filter, or aggregate records | **objectstack-query** | -| Define REST API endpoints or auth | **objectstack-api** | -| Build views, dashboards, or apps | **objectstack-ui** | -| Create a plugin or register services | **objectstack-platform** | +## First checks + +1. **Version.** Read the installed `@objectstack/spec` + (`node_modules/@objectstack/spec/package.json`); where it differs from this + skill's `compatibility` line, the installed contract is right. +2. **Read what exists.** Read the object being changed, those it references, + and the hooks, seeds and permission sets naming it. Extend what is there: + no second status field, owner field or look-alike object. +3. **Read the type's contract.** [references/_index.md](./references/_index.md) + points at each type's Zod source in `node_modules/@objectstack/spec/src/`. + `Read` it for exact keys, defaults and enum members, never from memory. A running environment serves the parsed shape as JSON Schema + (`GET /api/v1/meta/types`, `entries[].schema`): a defaulted key reads as + required and a bare-string predicate as `{}`. +4. **Verify before reporting done.** `os validate` (`npm run validate` in a + scaffolded project), then `os lint` + ([its rules](./references/lint-rules.md)). Most traps below pass both. + +**Nothing to read yet?** Say so in a line, then still give the whole +definition as code. + +## Traps — each parses, then fails at run time + +1. **A changed field does not reach a database that already has rows.** The + sync only adds: a column is never altered or dropped, and the column wins + at write time. Rename with `renamedFrom: ['old_key']`; `required` is the + write contract, never `NOT NULL` + ([Field Types](./rules/field-types.md#changing-a-field-that-has-data)). +2. **Search reads only this object's own stored columns.** To search by a + related record's title, mirror it into a stored text field in + `searchableFields`, kept fresh by hooks on both objects; a dotted path or a + `formula` there is refused + ([Search Fields](./references/examples-objects.md#search-fields-searchablefields)). +3. **An object you do not own is extended, never redeclared**: + `defineObjectExtension`, relabelling the owner's fields through + `fieldPatches` (redeclared in `fields`, a field is taken over and cut off + from the owner's upgrades). An installed package's object is extended from + its paired `.custom` package, each added field ending in `__c` + ([Object Extension Model](./references/examples-objects.md#object-extension-model)). + +## Where to go + +Open the file for your task first. + +| Authoring | Open first | +|:--|:--| +| An object's other keys, a starter object, field groups, `protection`, an extension | [examples-objects.md](./references/examples-objects.md) | +| A field's type and config, a default, changing a field that has data | [Field Types](./rules/field-types.md) | +| Names; labels in the request's language | [Naming](./rules/naming.md) | +| `lookup` or `master_detail`, junctions, delete behaviour, roll-ups, line items | [Relationships](./rules/relationships.md) | +| Validation rules, state machines, uniqueness, conditional field rules | [Validation](./rules/validation.md) | +| `indexes`, unique scope | [Indexing](./rules/indexing.md) | +| Record hooks: the sandboxed `body`, `ctx.api`, refusals, transactions | [data-hooks.md](./references/data-hooks.md) | +| Permission sets, RLS, field permissions, `secret`, tenancy, ownership queues | [Security](./rules/security.md) | +| Retention, append-only and audit objects, the save notice | [Lifecycle](./rules/lifecycle.md) | +| Seed and demo data: `defineSeed()`, import modes, `externalId`, relationship references, CEL values | [seeds.md](./references/seeds.md) | +| External databases, federated objects | [Datasources](./rules/datasources.md) | ---- +## Conditional Field Rules -## Quick Reference — Detailed Rules +`visibleWhen`, `requiredWhen` and `readonlyWhen` go on the **field**, as CEL +over `record.*` (`P\`record.status == 'paid'\``), so every form and +API write honours them. -- **[Naming Conventions](./rules/naming.md)** -- **[Field Types](./rules/field-types.md)** -- **[Relationships](./rules/relationships.md)** — lookup vs master_detail, junction patterns, delete behaviors -- **[Validation Rules](./rules/validation.md)** — All validation types, script inversion, severity levels -- **[Index Strategy](./rules/indexing.md)** — btree/gin/gist/fulltext, composite indexes -- **[Data Lifecycle & Retention](./rules/lifecycle.md)** — `lifecycle` classes, retention/TTL/rotation/archive policies (not *hooks*); plus the **save notice** a hook hands the saver (`ctx.notice`) -- **[Lifecycle Hooks](./references/data-hooks.md)** — the lifecycle events, the sandboxed `body` (ctx + capability contract; the inline `handler` is deprecated), registration, canonical patterns -- **[Datasources & Federation](./rules/datasources.md)** — `defineDatasource`, external/federated objects (`remoteName`/`columnMap`), auto-connect gating, credentials; ❌ no `field.columnName` on external objects -- **[Security & Access Control](./rules/security.md)** — permission sets, assignment rows, RLS policies, `secret` / `requiredPermissions`, `tenancy`, platform-global posture -- **[Quick-Start Template](./references/examples-objects.md#quick-start-template)** — one complete object: fields, `sharingModel`, `enable`, validations -- **[Metadata Protection](./references/examples-objects.md#metadata-protection-protection)** — the `protection` block that locks shipped metadata against edits and deletes -- **[Seed Data & Fixtures](./references/seeds.md)** — `defineSeed()`, import modes, `externalId`, relationship references, CEL values -- **[Linting & Generation Quality](./references/lint-rules.md)** — the `os lint` data-model rules and severities +- **`readonlyWhen` and `readonly: true` drop the value; they do not refuse the + write.** `readonly: true` binds non-system writes only; a `runAs:'system'` + flow, system hook or seed does write it + ([objectstack-automation → Failure routing & `runAs`](../objectstack-automation/SKILL.md#failure-routing--runas)). +- **`requiredWhen` is a transition gate, not an invariant**: it judges the + write, not the stored row. A fact true of every stored record is a + `validations[]` `script` rule. ---- +Example and syntax: [Validation](./rules/validation.md#conditional-field-rules). ## Core Concepts ### Object Definition -An **Object** maps to a database table and exposes automatic CRUD APIs. As JSON (in TypeScript the -same literal goes inside `ObjectSchema.create({...})`): +As JSON (in TypeScript the same literal goes inside `ObjectSchema.create({...})`): ```json { "name": "crm_account", "label": "Account", "pluralLabel": "Accounts", "icon": "building", @@ -60,413 +103,65 @@ same literal goes inside `ObjectSchema.create({...})`): "fields": { "name": { "type": "text", "label": "Name", "required": true } } } ``` -**Required properties:** - -| Property | Type | Convention | Description | -|:---------|:-------|:-----------|:------------| -| `name` | string | `snake_case` | Immutable machine identifier (`/^[a-z_][a-z0-9_]*$/`) | -| `fields` | map | keys in `snake_case` | Field definitions | -| `sharingModel` | enum | one of the four below | Org-wide default record visibility (OWD). Zod marks it optional, but **a publish with no authored `sharingModel` is refused** with the 422 lint envelope `security-owd-unset`. Author it on every object | - -**`sharingModel` — the four canonical values:** - -| Value | Who can read / write | -|:--|:--| -| `private` | owner only (widen with sharing rules, RLS, or `readScope`/`writeScope`) | -| `public_read` | everyone reads; the owner writes | -| `public_read_write` | everyone reads and writes | -| `controlled_by_parent` | inherited from the master record (`master_detail` children); a row with no (optional) master is its owner's | - -Choose the posture from the request: a business object a team -shares is `public_read_write` (`private` would hide every colleague's records -from everyone else); `private` fits personal or sensitive data only its owner -should see (HR reviews, pay, personal notes); `public_read` fits reference data -everyone reads and the owner maintains (price lists, policies, notices). -`ownership` is a separate axis: whether `owner_id` exists at -all (Relationship Patterns below). - -**Important optional properties:** - -| Property | Default | Description | -|:---------|:--------|:------------| -| `label` | Auto from `name` | Singular label | -| `pluralLabel` | — | Plural form; author it alongside `label` | -| `icon` | — | Icon for nav, list headers and lookup pickers; give every object one | -| `color` | `gray` | Tile colour behind the white `icon`: `gray` `blue` `teal` `green` `amber` `orange` `red` `pink` `purple` (no hex). Group the app's objects into a few business families, one name each, as the platform's own objects do: people `blue`, security `purple`, approvals and work `orange`, messaging `pink`, integrations `teal`, reference data and finance `green`, audit and settings `amber`. `red` only for an alert object; one nobody opens gets none | -| `highlightFields` | derived | Ordered field keys used as a record's compact face: the columns a **related list** renders on the parent's detail page, and what a lookup picker shows. Declare it on the CHILD object (see [Relationships](./rules/relationships.md)) | -| `namespace` | — | **Not a schema key**: refused as unknown. Embed the prefix in `name` | -| `datasource` | `'default'` | Target datasource ID | -| `nameField` | derived (e.g. `'name'`/`'title'`) | Record-title field: the stored field used as the record's display name. Use a single text/email field; a composite title to import, sort or search by is a stored computed field (a non-`formula` field with an `expression`); a text formula is display-only | -| `displayNameField` | — | **Deprecated** alias for `nameField`, still read | -| `titleFormat` | — | **Refused** by a save and `os validate` (`title-format-retired`): use `nameField` | -| `enable` | — | Capability flags (next section) | -| `fieldGroups` | — | Ordered field groups for forms/detail pages (see [Field Groups](./references/examples-objects.md#field-groups-mvp)) | -| `lifecycle` | `record` (permanent) | Data retention/rotation/archival contract. **Required for append-only, high-write-rate objects** (see [Data Lifecycle & Retention](./rules/lifecycle.md)) | - -### Object Capabilities (`enable`) - -| Flag | Default | Purpose | -|:-----|:--------|:--------| -| `fieldHistory` | on | A changed field's old → new values on the activity timeline, served per the reader's field read rule. `false`: off for the object. A field opts out with its own `fieldHistory: false`; a media or structured field (`json`, `address`, `code`…) shows values only with `true`, a credential never. `sys_audit_log` keeps its own grant | -| `trackHistory` | `false` | Ledger view on the record page and the `history` API verb; not the values switch | -| `searchable` | `true` | Index records for global search | -| `apiEnabled` | `true` | Expose via automatic REST + MCP APIs | -| `apiMethods` | all | Whitelist over the six primitives (`get`, `list`, `create`, `update`, `delete`, `bulk`); derived verbs (search/export/upsert/…) follow automatically | -| `files` | `false` | Attachments | -| `feeds` | `true` | Feed, comments, mentions; `false` hides the feed UI and rejects new comments | -| `activities` | `true` | Activity timeline (`sys_activity` mirror of CRUD); `false` stops mirroring and hides the timeline | -| `clone` | `true` | Record deep cloning | -| `aiReadable` | — | Platform `sys_*` objects only; on an app object, `false` included, refused at parse | - ---- - -## Search Fields (`searchableFields`) - -`searchableFields` on the object is the canonical set `$search` scans. -Leave it unset and search auto-defaults to the `nameField` plus the object's -short-text and enum columns (`text` / `email` / `phone` / `url` / `autonumber` / -`textarea` / `markdown` / `select`) plus every field marked `searchable: true`, -of any type except `secret` / `password` / `vector` or a virtual `formula`. `searchable: false`, the -default, never removes a field the type default scans; declare -`searchableFields` to choose the set. Views may narrow it, never widen it. - -### ⛔ Searching by a related record's title — mirror the value, always - -`$search` scans **the queried object's own columns**. A dotted path is never a -search target: unlike `fields` / `sort` / `filters`, the search axis does not -resolve traversal, and `project_id.name` in `searchableFields` (or in a -`$searchFields` override) is **refused** (`os validate` -`searchable-field-unknown`; a request, `400 INVALID_FIELD`). - -**This is the one prescription — emit it every time.** To search by a related -record's title, copy that title into a **stored field on this object** and -declare *that* field searchable. A task list searched by project name: - -```typescript -{ - name: 'task', - enable: { searchable: true }, - fields: { - name: { type: 'text', required: true }, - project_id: { type: 'lookup', reference: 'project' }, - project_name: { type: 'text', label: 'Project Name' }, - }, - searchableFields: ['name', 'project_name'], -} -``` - -`?search=apollo` expands to `name $contains 'apollo' OR project_name $contains -'apollo'` — one single-table scan, every driver. - -❌ **Never mirror onto a `formula` field.** It is *virtual* (no column to scan) -and CEL reads only this record's own fields, so it cannot hold the related title; -a `formula` entry in any `searchableFields` is refused — `os validate` -`searchable-field-unsearchable`, a request `400 INVALID_FIELD`. - -**Mirror maintenance is the trade-off.** Cover both paths: a `beforeInsert` / `beforeUpdate` hook on `task` -stamps `project_name` from the incoming `project_id`'s parent; an `afterUpdate` -hook on `project` re-stamps its tasks when it is renamed. Rows written past the hooks (bulk import, direct SQL) need a -one-off backfill. See [Lifecycle Hooks](./references/data-hooks.md). - ---- - -## Conditional Field Rules - -Put conditional UI/data-entry rules on the **field definition** when the rule -belongs to the data model and should apply everywhere the field is edited: -New and Edit, named and public forms, inline master-detail grids, API writes. - - -```typescript -import { P } from '@objectstack/spec'; -import { ObjectSchema, Field } from '@objectstack/spec/data'; - -export const Invoice = ObjectSchema.create({ - name: 'invoice', - sharingModel: 'public_read_write', - fields: { - status: Field.select({ - options: [ - { label: 'Draft', value: 'draft' }, - { label: 'Sent', value: 'sent' }, - { label: 'Paid', value: 'paid' }, - { label: 'Void', value: 'void' }, - ], - }), - paid_at: Field.datetime({ - visibleWhen: P`record.status == 'paid'`, - requiredWhen: P`record.status == 'paid'`, - }), - locked_total: Field.currency({ - readonlyWhen: P`record.status == 'paid'`, - }), - }, -}); -``` - -- Use `visibleWhen` to hide irrelevant fields in ObjectUI forms. -- `showOnCreate: false` keeps a field off every create surface; edit, the - record page and lists keep it. Refused beside `required: true`. -- Use `readonlyWhen` for state-locked fields; the ObjectQL write path ignores - incoming changes when the predicate is `TRUE` (for everyone; per permission - set → field permission `when`, rules/security.md). -- **`readonly: true` governs the end-user surface, not trusted system writers.** - A non-system write (REST/UI, and any `runAs:'user'` flow) has - the field **stripped**; the write reports - success but the value never lands. System-context writes — - `runAs:'system'` flows, system hooks, seeds, imports, migrations — are exempt - and DO write it. Keep the field `readonly` when automation maintains it; the - flow side: [objectstack-automation → Failure routing & `runAs`](../objectstack-automation/SKILL.md#failure-routing--runas). -- Use `requiredWhen` for conditional requiredness; the ObjectQL validator - enforces it on submit. The removed `conditionalRequired` alias is a parse - error. -- **Choose by intent — invariant or transition gate.** A fact true of *every - stored record* is an invariant: a `validations[]` `script` rule. A row that - violates it is refused on any edit until repaired. A *transition* condition - ("required once the record reaches `paid`") is `requiredWhen` / field bounds, - which judge the write, not the stored row. "Required when X" reads like an - invariant and is not one; an invariant written as a gate never enforces - itself. -- For inline `master_detail` grids, predicates are evaluated row-by-row against - the child row's `record`, so line-item rules should live on child fields. -- For complex predicates, load **objectstack-formula** and emit CEL via - `P\`...\``; do not use Salesforce-style `AND`, `IN (...)`, or `{field}` - syntax. - ---- - -## Schema evolution on an existing database - -The metadata→DB sync is **additive-only**: new tables/columns are created on -boot, but existing columns are **never** altered or dropped. A non-additive -change to an object that already has data silently diverges from the physical -schema, and the **database column wins at write time**: - -| Change | Existing DB on restart | -|--------|------------------------| -| add object / field / index | ✅ applied automatically | -| `storage: { notNull: true }` removed (relax `NOT NULL`) | ⚠️ **never auto-applied** — the drift is `category: 'needs_confirm'` (`relax_not_null`), so `os migrate apply` confirms it | -| `unique` re-scoped global → per-tenant | dev auto-heals; otherwise `os migrate apply` (`replace_unique_index`) | -| type / length change, drop field | `os migrate apply` (`--allow-destructive` for drops / tightenings) | -| rename a field | `renamedFrom: ['old_key']` on the new key: the sync carries the column's values | -| declared index removed, or its columns changed | `os migrate apply` (`--allow-destructive` when it drops, or rebuilds as `UNIQUE`) | - -**`required` is not the `NOT NULL` dial.** `required` is the -**write contract** — the engine refuses an insert that omits the value — and it -implies nothing about the column. The physical constraint is a separate explicit -opt-in, `storage: { notNull: true }`, and it is what drift detection compares -against. So tightening `required` on a deployed object is safe (existing null -rows stay readable), while declaring `storage.notNull` over null rows is a -destructive migration. The two cannot be combined with `requiredWhen`. - -Tell-tale: `/meta` reports a field optional (no `required`, no `storage.notNull`) -but writes that omit it fail with a **raw driver error** rather than a clean -validation 400 — that is a stale `NOT NULL` column, not a validator bug. Run -`os migrate plan` to preview and `os migrate apply` to reconcile, or ratify the -column by declaring `storage: { notNull: true }`. CLI details: see -**objectstack-platform**. - ---- - -## Common Patterns - -### Naming Rules Summary - -`snake_case` object names and field keys, `camelCase` schema properties, -lowercase option values — examples: [rules/naming.md](./rules/naming.md). +- `name` and field keys are immutable `snake_case`; a module prefix goes in + `name` (`namespace` is not a key). +- **Author `sharingModel` on every object**: Zod marks it optional, but a + publish without it is refused (`security-owd-unset`). Choose it from the + request. `public_read_write`: a business object a team shares + (`private` would hide every colleague's records). `private`: personal or + sensitive data only its owner should see (HR reviews, pay), widened by + sharing rules, RLS or `readScope`/`writeScope`. `public_read`: reference + data everyone reads and the owner maintains (price lists, policies). + `controlled_by_parent`: a `master_detail` child, inherited from its master. +- Author `pluralLabel` and `icon` beside `label`. The record title is + `nameField`: one stored text or email field, never a text formula. + +Every other key: [examples-objects.md](./references/examples-objects.md#object-keys). ### Field Type Selection -Two to get right here (the rest: [rules/field-types.md](./rules/field-types.md)): credentials are `secret` (**encrypted-at-rest**, ADR-0100) — -never `password`, which on a generic object is **plaintext at rest**; `formula` takes CEL in `expression` (a `{ dialect: 'cel', source }` envelope — -`F\`...\`` in TypeScript; see **objectstack-formula**). +Credentials are `secret` (encrypted at rest), never `password`, which on a +generic object is plaintext at rest. A person is `type: 'user'` with no +`reference`, optional unless the request says otherwise. `formula` takes CEL +in `expression`, a `{ dialect: 'cel', source }` envelope (`F\`...\`` in +TypeScript; **objectstack-formula**). + +- A yes/no flag is `{ type: 'boolean', defaultValue: false }`. `required` on + it refuses only `null`, so it never means "must be checked": that is a + `validations[]` rule. +- A dynamic default (`defaultValue: 'current_user'`) resolves when + the record is SAVED with the field empty. Describe it as save-time, not as + a pre-filled form. -- A yes/no flag (`is_*`, `has_*`, "done?", "active?") is `{ type: 'boolean', defaultValue: false }`. - `required` on it refuses only `null`: an unchecked box is a value, so it - never means "must be checked". A box that must be checked (terms, consent) - is a `validations[]` rule: `{ name: 'terms', type: 'script', - condition: { dialect: 'cel', source: 'record.accepted != true' }, message: 'Accept the terms.' }`. - The default also lands seeded or imported rows that omit the column on - `false`, not a null that only looks unchecked. -- A person on the record (approver, reviewer) is `type: 'user'` with - no `reference`, and optional unless the request says otherwise — the platform - already stamps the owner and `created_by`. -- A dynamic default (`defaultValue: 'current_user'`, `'NOW()'`, a CEL envelope) - resolves when the record is SAVED with the field empty. Describe it as - save-time; whether a create form pre-displays it is a client capability you - cannot promise. +More: [Field Types](./rules/field-types.md#choosing-a-type). ### Relationship Patterns -| Pattern | Implementation | -|:--------|:---------------| -| One-to-Many (independent) | `lookup` field on child | -| One-to-Many (owned) | `master_detail` field on child | -| Many-to-Many (simple) | multi-value `lookup` (`multiple: true`) — an **array column** of ids | -| Many-to-Many (with attributes) | Junction object with two `lookup` fields | -| Hierarchical | `tree` field (self-reference) | -| Record status / lifecycle | a `select` on the business object (plus a `state_machine` validation) — never a separate status / stage / step table | -| Approval, review, routing, audit trail | not objects: an approval is a flow node (**objectstack-automation**) and its trail is platform history; model only the people it references (approver, reviewer), as `user` fields beside the owner | -| Record owner | the platform's `owner_id` (`ownership: 'user'`, the default), also when the request says assignee, 负责人 or 处理人 — never a hand-added owner field, a second owner that owner-scoped visibility and "My records" views never read. A handler the request names apart from the owner is a `user` field that grants no access, with a label no other visible field carries, injected ones included: `owner_id` (Owner, 负责人), `created_by` (创建人), `updated_by` (更新人), `created_at` (创建时间), `updated_at` (更新时间). `ownership: 'none'` only for a shared catalog or a pure junction table | +| Need | Model it as | +|:--|:--| +| Many-to-many | multi-value `lookup` (`multiple: true`), an **array of ids**; with attributes, a junction object with two `lookup` fields | +| Record status / lifecycle | a `select` on the business object (plus a `state_machine` validation), never a separate status / stage / step table | +| Approval, review, routing, audit trail | not objects: an approval is a flow node (**objectstack-automation**) and its trail is platform history; model only the people, as `user` fields | +| Record owner | the platform's `owner_id` (`ownership: 'user'`, the default), also when the request says assignee, 负责人 or 处理人; never a hand-added owner field, which owner-scoped visibility and "My records" views never read | -> A `multiple: true` lookup's ids are referenced positionally (`{record.tags.0}` in flow values). +The rest, and a handler named apart from the owner: +[Relationships](./rules/relationships.md). ### Validation Patterns -**⚠️ Script validation is inverted:** Validation **fails** when expression is `true`. - -The **complete** set of types (`ValidationRuleSchema` discriminators): `script`, -`state_machine`, `format`, `cross_field`, `json_schema`, `conditional`. - -A `state_machine` rule that runs on insert declares `initialStates`, or publish -refuses it (`state-machine-no-initial-states`): a record could be created -already `approved`. An update-only machine (`events: ['update']`) needs none. -List only entry states (usually one: `draft` / `new`), never a terminal one; -keys and values are option `value`s, never labels. - -> **There is NO `unique` validation type** — uniqueness is a unique **index** -> with its scope ([rules/validation.md § Uniqueness](./rules/validation.md#uniqueness--use-unique-indexes)). - -### Index Patterns - -**The whole declaration surface is `fields` / `unique` / `name`.** - -```typescript -indexes: [ - { fields: ['status', 'created_at'] }, // composite - { fields: ['email'], unique: 'organization' }, // unique per organization - { fields: ['hostname'], unique: 'global' }, // unique platform-wide - { name: 'idx_acct_status', fields: ['status'] }, // custom name -] -``` - -See [rules/indexing.md](./rules/indexing.md) for unique scope -(on a declared index bare `unique: true` is refused), the retired `type` / `partial`, and partial / gin / gist indexes at the -database layer. - ---- - -## Object Extension Model - -To add fields/validations/indexes to an object you do not own, author -`defineObjectExtension({ extend, fields, fieldPatches, place, priority })` and register it on -`defineStack({ objectExtensions: [...] })`. `priority` sets merge order (default -`200`, `0–999`); an extension adds, never removes, except that a new -`label` without `pluralLabel` clears the base plural unless a tenant authored it (set both). ⛔ `extend` -is not object-level `ownership` (`'user' | 'business_unit' | 'org' | 'none'`). - -`place: [{ field: 'tax_id', group: 'basic', after: 'industry' }, { list: 'acme_contract', after: 'crm_opportunity' }]` -puts the extension's own fields, groups (`{ group: { key, label }, after }`) and child lists -after (or `before`) a named item, where the target declares `fieldGroups` / `relatedLists`. - -**Relabel a field the owner declares with `fieldPatches` — never by redeclaring -it in `fields`**, which takes the field over whole and cuts it off from the -owner's upgrades. A patch carries display keys only: -`label`, `description`, `inlineHelpText`, -`placeholder`, and an option's `label` keyed by its stored `value`; the type, -values and rules stay the owner's. A key the tenant edited keeps the tenant's -text; between two extensions the higher `priority` wins. A patch naming a field -or option value the target lacks is refused at install and by `os validate`, and -a `picklist`-bound field's options are never patchable. Example: -`defineObjectExtension({ extend: 'crm_account', fieldPatches: { industry: { label: 'Sector' }, type: { options: { customer: { label: 'Client' } } } } })`. -Translate patched text in the patching package's `translations`, under the -owner's keys (`objects.crm_account.fields.industry.label`, `.help`, -`.options.`): the owner's translation of the replaced text never applies, a -pair `.custom` translation comes first on `/meta`, and an untranslated locale -serves the patch text. +**⚠️ Script validation is inverted:** it **fails** when the expression is +`true`. -**An object an installed package ships** is extended from the -base's paired `.custom` package (`hotcrm.custom`; **objectstack-platform** -§ Customizing an installed package), never replaced: it takes no `overrides` -declaration. Every field the pair adds ends in `__c` (`region__c`). The suffix is -reserved to the pair, so a `__c` field in any other package, or an unsuffixed -field in a `.custom` extension, is refused at save, publish and install and by -`os validate` / `os build`. -Only the pair's extension also writes `fieldGroups`, `relatedLists` and `actionLayout` -(**objectstack-ui**), shaped as on an object. A written key replaces that arrangement -whole (the owner's and every `place`; `actionLayout`, each arm it writes): an unlisted -field shows after the last group, an unnamed tab after the listed ones, and -`{ list: 'crm_note', hidden: true }` hides a tab. Outside a `.custom` package they are -refused at those doors: use `place`, or for an action its own `locations` and `order`. -Studio's **Add field** on a base object writes the same extension, as an -`object_extension` item of the pair. - ---- - -## Security & Access Control - -Per-object access control is authored in **permission sets**, not on the object -schema. There is no object-level `permissions` key (and no `hooks` key either) — -`ObjectSchema.create()` **rejects** both as unknown keys. +A `state_machine` rule that runs on insert declares `initialStates` (entry +states only), or publish refuses it: a record could be created already +`approved`. **There is NO `unique` validation type**: +uniqueness is a unique index with its scope +([Validation](./rules/validation.md#uniqueness--use-unique-indexes)). ### Access depth (scope-depth) — the ERP "see my unit / my unit and below" axis -On an owner-scoped (`private`) object, a per-object grant in a permission set may -carry `readScope` / `writeScope` to widen the owner match declaratively instead of -hand-writing an RLS policy (ADR-0057 D1): `own` (default) · `own_and_reports` · -`unit` · `unit_and_below` · `org`. It resolves at request time into an -`owner_id IN (…)` set and AND-injects like RLS. ⚠️ Open-core boundary (ADR-0016): -only `own` and `org` work in open source — the hierarchy-relative three need the -paid `@objectstack/security-enterprise` plugin in `plugins[]`, **fail closed to -`own`** without it, and `defineStack` errors unless the stack declares -`requires: ['hierarchy-security']`. The CLI only advises on a missing or unwired -plugin: `os validate` warns, `os verify --json` lists it in `capabilities`. - -### Ownership queues — park a record for a team to claim - -Every `ownership: 'user'` object carries a platform-injected `queue` column -beside `owner_id` (an object declaring its own `queue` field is refused). A -record **sits in** a queue when `owner_id` is empty and `queue` names it: the -queue's members read and edit it (rows widen, verbs never — no delete). Declare -the queue on the stack; a declared queue's members are positions only, an -organization adds users and teams through `sys_queue_member` rows: - - -```typescript -import { defineQueue } from '@objectstack/spec/security'; - -export const supportIntake = defineQueue({ - name: 'crm_support_intake', // the one name the `queue` column, a rule, an approver and a sharing recipient use - label: 'Support Intake', - members: [{ type: 'position', value: 'crm_service_agent' }], -}); -// defineStack({ queues: [supportIntake], assignmentRules: [...] }) — routing rows in: objectstack-automation -``` - -**Claim** is an ordinary by-id update, `{ owner_id: }`, admitted to a -member while the record is unowned; one writer wins, the other gets `409 -CONCURRENT_UPDATE`. **Release**: the owner writes `owner_id: null` and the record -sits in its home queue again. **Move**: writing another `queue` is a transfer -(`allowTransfer` or `modifyAllRecords`). ⛔ Never a per-record `assigned_to` -picklist, a round-robin counter field, or a hook that picks an owner. - ---- - -## Verify your work - -After authoring or editing any `*.object.ts` / `*.seed.ts`, run the author-time -gate before reporting done: - -```bash -os validate # Zod schema + CEL predicates (record. existence) + bindings -# or: os build # the same gates, plus emits dist/ -``` - -It catches what otherwise surfaces only at runtime, where a bare field ref -(`done` for `record.done`) faults: an `error` validation rule or `requiredWhen` -refuses the write naming it, an option `visibleWhen` only a write picking the -option (forms still offer it); a `readonlyWhen` field stays editable and the -save succeeds without its change (logged); a formula reads `null` (logged). -`os lint` is a *separate* -pass that additionally checks the data model against the conventions in this -skill (relationships, master-detail, roll-ups) — run it too. -In a scaffolded project the gate is `npm run validate`. - ---- - -## 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. +On a `private` object a permission-set grant may carry `readScope` / +`writeScope`: `own` (default) · `own_and_reports` · `unit` · `unit_and_below` · +`org`. Only `own` and `org` work in open source: the other three need the paid +`@objectstack/security-enterprise` plugin, **fail closed to `own`** without +it, and need `requires: ['hierarchy-security']` on the stack. diff --git a/skills/objectstack-data/evals/hooks-security-seeds-datasources.json b/skills/objectstack-data/evals/hooks-security-seeds-datasources.json index eb7ca5a92d8..7df9d5f327f 100644 --- a/skills/objectstack-data/evals/hooks-security-seeds-datasources.json +++ b/skills/objectstack-data/evals/hooks-security-seeds-datasources.json @@ -104,10 +104,11 @@ { "id": 7, "prompt": "We serve English and Chinese users. An `order` whose `amount` exceeds its account's `credit_limit` must not save; API clients branch on `CREDIT_LIMIT`, a zh-CN rep reads `超出账户信用额度`.", - "expected_output": "A `beforeInsert` / `beforeUpdate` hook on `order` declares `refusals: { CREDIT_LIMIT: { message: 'Over the account credit limit.' } }`; its sandboxed `body: { language: 'js', source }` reads the account via `ctx.api` and refuses by code only (`throw Object.assign(new Error(), { code: 'CREDIT_LIMIT' })`); the zh-CN bundle's `hooks: { : { refusals: { CREDIT_LIMIT: { message: '超出账户信用额度' } } } }` is served in the caller's locale; a catalogue on a hook without a `js` body is refused at save.", + "expected_output": "A `beforeInsert` / `beforeUpdate` hook on `order` declares `refusals: { CREDIT_LIMIT: { message: 'Over the account credit limit.' } }`; its sandboxed `body: { language: 'js', source }` reads the account via `ctx.api` and refuses by code only (`throw Object.assign(new Error(), { code: 'CREDIT_LIMIT' })`); the zh-CN bundle's `hooks: { : { refusals: { CREDIT_LIMIT: { message: '超出账户信用额度' } } } }` (or the same entry as the dotted key `hooks..refusals.CREDIT_LIMIT.message`) is served in the caller's locale; a catalogue on a hook without a `js` body is refused at save.", "files": [], "assertions": { - "must_contain": ["refusals:", "CREDIT_LIMIT: {", "code: 'CREDIT_LIMIT'", "language: 'js'", "hooks: {", "超出账户信用额度"], + "must_contain": ["refusals:", "CREDIT_LIMIT: {", "code: 'CREDIT_LIMIT'", "language: 'js'", "超出账户信用额度"], + "must_contain_any": [["hooks: {", "\"hooks\": {", ".refusals.CREDIT_LIMIT"]], "must_not_contain": ["new Error('", "handler:"] } }, diff --git a/skills/objectstack-data/evals/objects-fields-relationships.json b/skills/objectstack-data/evals/objects-fields-relationships.json index 81c2a084142..4e27cd38d68 100644 --- a/skills/objectstack-data/evals/objects-fields-relationships.json +++ b/skills/objectstack-data/evals/objects-fields-relationships.json @@ -172,14 +172,14 @@ { "id": 10, "prompt": "给 `task` 加一个「是否完成」字段,设成必填,免得有人忘了填。", - "expected_output": "Adds `is_done: { type: 'boolean', label: '是否完成', defaultValue: false }`; `required: true` may stay or go, and either way the answer says what it does: on a boolean `required` refuses only `null`, and an unchecked box is a value, so it never means \"must be ticked\" and nobody can forget to fill it — the default lands every row, imported or seeded ones included, on a real `false`. Tells the user that \"must be ticked\" (terms, a consent) is a `validations[]` `script` rule whose `condition` is true while the box is not `true`, not `required`. The label is Chinese, as the request is.", + "expected_output": "Adds `is_done: { type: 'boolean', label: '是否完成', defaultValue: false }` (or the factory form, `Field.boolean({ label: '是否完成', defaultValue: false })`); `required: true` may stay or go, and either way the answer says what it does: on a boolean `required` refuses only `null`, and an unchecked box is a value, so it never means \"must be ticked\" and nobody can forget to fill it — the default lands every row, imported or seeded ones included, on a real `false`. Tells the user that \"must be ticked\" (terms, a consent) is a `validations[]` `script` rule whose `condition` is true while the box is not `true`, not `required`. The label is Chinese, as the request is.", "files": [], "assertions": { "must_contain": [ - "type: 'boolean'", "defaultValue: false", "label: '是否完成'" ], + "must_contain_any": [["type: 'boolean'", "Field.boolean("]], "must_not_contain": [ "label: 'Is Done'" ] diff --git a/skills/objectstack-data/references/examples-objects.md b/skills/objectstack-data/references/examples-objects.md index 292c81e3568..47eca461b75 100644 --- a/skills/objectstack-data/references/examples-objects.md +++ b/skills/objectstack-data/references/examples-objects.md @@ -1,4 +1,28 @@ -# Data — object authoring examples (moved verbatim from SKILL.md) +# Data — object keys, examples, search, extensions + +## Object keys + +Beyond `SKILL.md` § Object Definition. Every key, `enable` flag +(`ObjectCapabilities`) and default: `data/object.zod.ts` +([_index.md](./_index.md)). The ones to get right: + +| Property | Default | Description | +|:--|:--|:--| +| `color` | `gray` | Tile colour behind the white `icon`: `gray` `blue` `teal` `green` `amber` `orange` `red` `pink` `purple` (no hex). Group the app's objects into a few business families, one name each, as the platform's own objects do: people `blue`, security `purple`, approvals and work `orange`, messaging `pink`, integrations `teal`, reference data and finance `green`, audit and settings `amber`. `red` only for an alert object; one nobody opens gets none | +| `highlightFields` | derived | Ordered field keys used as a record's compact face: the columns a **related list** renders on the parent's detail page, and what a lookup picker shows. Declare it on the CHILD object (see [Relationships](../rules/relationships.md)) | +| `nameField` | derived (e.g. `'name'`/`'title'`) | Record-title field: the stored field used as the record's display name. Use a single text/email field; a composite title to import, sort or search by is a stored computed field (a non-`formula` field with an `expression`); a text formula is display-only | +| `ownership` | `'user'` | Whether `owner_id` exists at all, a different axis from `sharingModel` | + +### Object Capabilities (`enable`) + +| Flag | Default | Purpose | +|:--|:--|:--| +| `fieldHistory` | on | A changed field's old → new values on the activity timeline, served per the reader's field read rule. `false`: off for the object. A field opts out with its own `fieldHistory: false`; a media or structured field (`json`, `address`, `code`…) shows values only with `true`, a credential never. `sys_audit_log` keeps its own grant | +| `trackHistory` | `false` | Ledger view on the record page and the `history` API verb; not the values switch | +| `apiMethods` | all | Whitelist over the six primitives (`get`, `list`, `create`, `update`, `delete`, `bulk`); derived verbs (search/export/upsert/…) follow automatically | +| `feeds` | `true` | Feed, comments, mentions; `false` hides the feed UI and rejects new comments | +| `activities` | `true` | Activity timeline (`sys_activity` mirror of CRUD); `false` stops mirroring and hides the timeline | +| `aiReadable` | — | Platform `sys_*` objects only; on an app object, `false` included, refused at parse | ## Field Groups (MVP) @@ -190,3 +214,92 @@ agents, tools, skills, reports, email-templates). Enforcement: `PUT`/`DELETE` on `/api/v1/meta/:type/:name` return `403 item_locked`, and an artifact lock overrides a package lock. Default to **no** `protection` block for tenant-authored metadata. + +## Search Fields (`searchableFields`) + +`searchableFields` on the object is the canonical set `$search` scans. +Leave it unset and search auto-defaults to the `nameField` plus the object's +short-text and enum columns (`text` / `email` / `phone` / `url` / `autonumber` / +`textarea` / `markdown` / `select`) plus every field marked `searchable: true`, +of any type except `secret` / `password` / `vector` or a virtual `formula`. `searchable: false`, the +default, never removes a field the type default scans; declare +`searchableFields` to choose the set. Views may narrow it, never widen it. + +### ⛔ Searching by a related record's title — mirror the value, always + +`$search` scans **the queried object's own columns**. A dotted path is never a +search target: unlike `fields` / `sort` / `filters`, the search axis does not +resolve traversal, and `project_id.name` in `searchableFields` (or in a +`$searchFields` override) is **refused** (`os validate` +`searchable-field-unknown`; a request, `400 INVALID_FIELD`). + +**The one prescription** (`SKILL.md` trap 2), for a task list searched by project name: + +```typescript +{ + name: 'task', + enable: { searchable: true }, + fields: { + name: { type: 'text', required: true }, + project_id: { type: 'lookup', reference: 'project' }, + project_name: { type: 'text', label: 'Project Name' }, + }, + searchableFields: ['name', 'project_name'], +} +``` + +`?search=apollo` expands to `name $contains 'apollo' OR project_name $contains +'apollo'` — one single-table scan, every driver. + +❌ **Never mirror onto a `formula` field.** It is *virtual* (no column to scan) +and CEL reads only this record's own fields, so it cannot hold the related title; +a `formula` entry in any `searchableFields` is refused — `os validate` +`searchable-field-unsearchable`, a request `400 INVALID_FIELD`. + +**Mirror maintenance is the trade-off.** Cover both paths: a `beforeInsert` / `beforeUpdate` hook on `task` +stamps `project_name` from the incoming `project_id`'s parent; an `afterUpdate` +hook on `project` re-stamps its tasks when it is renamed. Rows written past the hooks (bulk import, direct SQL) need a +one-off backfill. See [Lifecycle Hooks](./data-hooks.md). + +## Object Extension Model + +To add fields/validations/indexes to an object you do not own, author +`defineObjectExtension({ extend, fields, fieldPatches, place, priority })` and register it on +`defineStack({ objectExtensions: [...] })`. `priority` sets merge order (default +`200`, `0–999`); an extension adds, never removes, except that a new +`label` without `pluralLabel` clears the base plural unless a tenant authored it (set both). ⛔ `extend` +is not object-level `ownership` (`'user' | 'business_unit' | 'org' | 'none'`). + +`place: [{ field: 'tax_id', group: 'basic', after: 'industry' }, { list: 'acme_contract', after: 'crm_opportunity' }]` +puts the extension's own fields, groups (`{ group: { key, label }, after }`) and child lists +after (or `before`) a named item, where the target declares `fieldGroups` / `relatedLists`. + +**A `fieldPatches` patch** (`SKILL.md` trap 3) carries display keys only: +`label`, `description`, `inlineHelpText`, +`placeholder`, and an option's `label` keyed by its stored `value`; the type, +values and rules stay the owner's. A key the tenant edited keeps the tenant's +text; between two extensions the higher `priority` wins. A patch naming a field +or option value the target lacks is refused at install and by `os validate`, and +a `picklist`-bound field's options are never patchable. Example: +`defineObjectExtension({ extend: 'crm_account', fieldPatches: { industry: { label: 'Sector' }, type: { options: { customer: { label: 'Client' } } } } })`. +Translate patched text in the patching package's `translations`, under the +owner's keys (`objects.crm_account.fields.industry.label`, `.help`, +`.options.`): the owner's translation of the replaced text never applies, a +pair `.custom` translation comes first on `/meta`, and an untranslated locale +serves the patch text. + +**An object an installed package ships** is extended from the +base's paired `.custom` package (`hotcrm.custom`; **objectstack-platform** +§ Customizing an installed package), never replaced: it takes no `overrides` +declaration. Every field the pair adds ends in `__c` (`region__c`). The suffix is +reserved to the pair, so a `__c` field in any other package, or an unsuffixed +field in a `.custom` extension, is refused at save, publish and install and by +`os validate` / `os build`. +Only the pair's extension also writes `fieldGroups`, `relatedLists` and `actionLayout` +(**objectstack-ui**), shaped as on an object. A written key replaces that arrangement +whole (the owner's and every `place`; `actionLayout`, each arm it writes): an unlisted +field shows after the last group, an unnamed tab after the listed ones, and +`{ list: 'crm_note', hidden: true }` hides a tab. Outside a `.custom` package they are +refused at those doors: use `place`, or for an action its own `locations` and `order`. +Studio's **Add field** on a base object writes the same extension, as an +`object_extension` item of the pair. diff --git a/skills/objectstack-data/rules/field-types.md b/skills/objectstack-data/rules/field-types.md index 8d9e4b54e6c..b2eed5cbf5b 100644 --- a/skills/objectstack-data/rules/field-types.md +++ b/skills/objectstack-data/rules/field-types.md @@ -271,3 +271,48 @@ The `format` is literal text interleaved with `{...}` tokens: 2. **Put a delimiter between adjacent variable tokens** — `{section}-{zone}{000}`, not `{section}{zone}{000}`. Without one, `('AB','C')` and `('A','BC')` both render prefix `ABC` and share a counter (to keep numbers unique). 3. **Pad width is a MINIMUM, not a cap.** `{000}` → `001`…`999`, then `1000`. 4. **Only known tokens are interpolated.** Date tokens are **case-sensitive** — `{yyyy}` parses as a `{field}` reference and renders **empty** (rule 1 applies). Only a spelling no field could have — `{ YYYY }`, `{YYYY-MM}` — is emitted **literally**. + +## Choosing a type + +Beyond `SKILL.md` § Field Type Selection (`secret` is encrypted at rest per +ADR-0100): + +- A yes/no flag, `{ type: 'boolean', defaultValue: false }`, is any `is_*`, + `has_*`, "done?" or "active?". An unchecked box is + a value. A box that must be checked (terms, consent) is the rule + `{ name: 'terms', type: 'script', + condition: { dialect: 'cel', source: 'record.accepted != true' }, message: 'Accept the terms.' }`. + The `false` default also lands seeded or imported rows that omit the column on + `false`, not a null that only looks unchecked. +- A person (approver, reviewer) stays optional because the platform already + stamps the owner and `created_by`. +- A dynamic default may also be `'NOW()'` or a CEL envelope. Whether a create + form pre-displays it is a client capability you cannot promise. + +## Changing a field that has data + +Beyond `SKILL.md` trap 1 (the sync only adds; the column wins at write time): + +| Change | Existing DB on restart | +|--|--| +| add object / field / index | ✅ applied automatically | +| `storage: { notNull: true }` removed (relax `NOT NULL`) | ⚠️ **never auto-applied** — the drift is `category: 'needs_confirm'` (`relax_not_null`), so `os migrate apply` confirms it | +| `unique` re-scoped global → per-tenant | dev auto-heals; otherwise `os migrate apply` (`replace_unique_index`) | +| type / length change, drop field | `os migrate apply` (`--allow-destructive` for drops / tightenings) | +| rename a field | `renamedFrom: ['old_key']` on the new key: the sync carries the column's values | +| declared index removed, or its columns changed | `os migrate apply` (`--allow-destructive` when it drops, or rebuilds as `UNIQUE`) | + +**`required` is not the `NOT NULL` dial.** `required` is the +**write contract** — the engine refuses an insert that omits the value — and it +implies nothing about the column. The physical constraint is a separate explicit +opt-in, `storage: { notNull: true }`, and it is what drift detection compares +against. So tightening `required` on a deployed object is safe (existing null +rows stay readable), while declaring `storage.notNull` over null rows is a +destructive migration. The two cannot be combined with `requiredWhen`. + +Tell-tale: `/meta` reports a field optional (no `required`, no `storage.notNull`) +but writes that omit it fail with a **raw driver error** rather than a clean +validation 400 — that is a stale `NOT NULL` column, not a validator bug. Run +`os migrate plan` to preview and `os migrate apply` to reconcile, or ratify the +column by declaring `storage: { notNull: true }`. CLI details: see +**objectstack-platform**. diff --git a/skills/objectstack-data/rules/relationships.md b/skills/objectstack-data/rules/relationships.md index 95b8a47bdc2..32848e714bd 100644 --- a/skills/objectstack-data/rules/relationships.md +++ b/skills/objectstack-data/rules/relationships.md @@ -382,3 +382,12 @@ A line item on a `lookup` can exist without its parent: use `master_detail`. No `many_to_many` field type exists: use a junction object. +## Record owner, and other people on a record + +Beyond `SKILL.md` § Relationship Patterns: a handler the request names apart +from the owner is a `user` field that grants no access, with a label +no other visible field carries, injected ones included: `owner_id` (Owner, 负责人), +`created_by` (创建人), `updated_by` (更新人), `created_at` (创建时间), `updated_at` +(更新时间). `ownership: 'none'` only for a shared catalog or a pure junction table. + +A `multiple: true` lookup's ids are referenced positionally (`record.tags[0]` in a flow's CEL). diff --git a/skills/objectstack-data/rules/security.md b/skills/objectstack-data/rules/security.md index 191cd5c322f..39cbcc683cd 100644 --- a/skills/objectstack-data/rules/security.md +++ b/skills/objectstack-data/rules/security.md @@ -173,7 +173,7 @@ rowLevelSecurity: [ a parent's owner, parent optional → an optional master (relationships.md); one record, once → a sharing rule or a manual share; a team's records → a sharing rule whose `sharedWith: { type: 'queue', value: '' }` - reaches an ownership queue's members (SKILL.md § Ownership queues). + reaches an ownership queue's members (§ Ownership queues below). - A package's rule reads `value` as its package's queue, else the one holder in its declared `dependencies` closure plus `sys`, else (none declares it) an org's `sys_queue` row. Else it grants no one new, warned @@ -192,7 +192,7 @@ rowLevelSecurity: [ in its declared `dependencies` closure plus `sys`; else it is refused. It still loads; the boot's catalog reference report logs each refusal with every candidate, and the position grants nothing through that name (its other sets - still do). `outside-closure` / `ambiguous-in-closure` as for a queue above + still do). The two closure refusals are as for a queue above (the environment: a set authored in Setup; a second package shipping a name is refused at install). Fix: declare the dependency. Stored grants, environment-authored positions, admin overlays of a package position and the @@ -347,3 +347,42 @@ references by table (sharing, queue and share recipients, pending approvers, invitations) for an admin. Not carried (warned): an old name still a position anywhere, claimed twice, recorded under another owner (a package or the environment), switched off, or a disabled claimant. + +## Access depth — `readScope` / `writeScope` + +Beyond `SKILL.md` § Access depth: a scope +widens the owner match declaratively instead of a hand-written RLS policy +(ADR-0057 D1): it resolves at request time into an `owner_id IN (…)` set and +AND-injects like RLS. Open-core boundary ADR-0016: the plugin goes in +`plugins[]`, and `defineStack` errors unless the stack declares +`requires: ['hierarchy-security']`. The CLI only advises on a +missing or unwired plugin: `os validate` warns, `os verify --json` lists it in +`capabilities`. + +## Ownership queues — park a record for a team to claim + +Every `ownership: 'user'` object carries a platform-injected `queue` column +beside `owner_id` (an object declaring its own `queue` field is refused). A +record **sits in** a queue when `owner_id` is empty and `queue` names it: the +queue's members read and edit it (rows widen, verbs never — no delete). Declare +the queue on the stack; a declared queue's members are positions only, an +organization adds users and teams through `sys_queue_member` rows: + + +```typescript +import { defineQueue } from '@objectstack/spec/security'; + +export const supportIntake = defineQueue({ + name: 'crm_support_intake', // the one name the `queue` column, a rule, an approver and a sharing recipient use + label: 'Support Intake', + members: [{ type: 'position', value: 'crm_service_agent' }], +}); +// defineStack({ queues: [supportIntake], assignmentRules: [...] }) — routing rows in: objectstack-automation +``` + +**Claim** is an ordinary by-id update, `{ owner_id: }`, admitted to a +member while the record is unowned; one writer wins, the other gets `409 +CONCURRENT_UPDATE`. **Release**: the owner writes `owner_id: null` and the record +sits in its home queue again. **Move**: writing another `queue` is a transfer +(`allowTransfer` or `modifyAllRecords`). ⛔ Never a per-record `assigned_to` +picklist, a round-robin counter field, or a hook that picks an owner. diff --git a/skills/objectstack-data/rules/validation.md b/skills/objectstack-data/rules/validation.md index 4eb1d435b23..b4b1fda4da0 100644 --- a/skills/objectstack-data/rules/validation.md +++ b/skills/objectstack-data/rules/validation.md @@ -48,8 +48,7 @@ exemption, so a row that already violates the rule is refused on any edit until a repairing write lands (frozen, not bricked). A condition that must hold only from a transition onward is not this tool: use `requiredWhen` or a field bound (`min` / `max` / `minLength` / `maxLength`), which judge the write, not the -stored row (see **Choose by intent — invariant or transition gate** in -`SKILL.md`). +stored row (`SKILL.md` § Conditional Field Rules). ```typescript @@ -103,7 +102,8 @@ driver layer. See [indexing.md](./indexing.md) for index options. A `validations[]` entry. `initialStates` holds the one state a record may be CREATED in; publish refuses a machine without it (`state-machine-no-initial-states`) unless it is update-only -(`events: ['update']`). `[]` marks a terminal state: +(`events: ['update']`). `[]` marks a terminal state; `transitions` keys and +values are option `value`s, never labels: ```json { @@ -327,3 +327,66 @@ priority: 1000 // User validations (run last) events: ['update'], // ✅ Only validate on update } ``` + +## Conditional Field Rules + +A rule that belongs to the data model goes on the **field definition** and +applies everywhere the field is edited: +New and Edit, named and public forms, inline master-detail grids, API writes. + + +```typescript +import { P } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +export const Invoice = ObjectSchema.create({ + name: 'invoice', + sharingModel: 'public_read_write', + fields: { + status: Field.select({ + options: [ + { label: 'Draft', value: 'draft' }, + { label: 'Sent', value: 'sent' }, + { label: 'Paid', value: 'paid' }, + { label: 'Void', value: 'void' }, + ], + }), + paid_at: Field.datetime({ + visibleWhen: P`record.status == 'paid'`, + requiredWhen: P`record.status == 'paid'`, + }), + locked_total: Field.currency({ + readonlyWhen: P`record.status == 'paid'`, + }), + }, +}); +``` + +- `showOnCreate: false` keeps a field off every create surface; edit, the + record page and lists keep it. Refused beside `required: true`. +- Use `readonlyWhen` for state-locked fields; the ObjectQL write path ignores + incoming changes when the predicate is `TRUE` (for everyone; per permission + set → field permission `when`, rules/security.md). +- **`readonly: true` governs the end-user surface, not trusted system writers.** + A stripped write (REST/UI, and any `runAs:'user'` flow) reports success. + Imports and migrations are system-context writes too. Keep the field `readonly` when automation maintains it; the flow + side: [objectstack-automation → Failure routing & `runAs`](../../objectstack-automation/SKILL.md#failure-routing--runas). +- Use `requiredWhen` for conditional requiredness; the ObjectQL validator + enforces it on submit. The removed `conditionalRequired` alias is a parse + error. +- **Choose by intent — invariant or transition gate** + ([Script Validation](#script-validation), Tool choice). "Required when X" + reads like an invariant and is not one; an invariant written as a gate never + enforces itself. +- For inline `master_detail` grids, predicates are evaluated row-by-row against + the child row's `record`, so line-item rules should live on child fields. +- For complex predicates, load **objectstack-formula** and emit CEL via + `P\`...\``; do not use Salesforce-style `AND`, `IN (...)`, or `{field}` + syntax. + +`os validate` catches a bare field ref (`done` for `record.done`) in any of +these predicates. Unchecked, it faults at run time: an `error` validation rule +or `requiredWhen` refuses the write naming it, an option `visibleWhen` only a +write picking the option (forms still offer it); a `readonlyWhen` field stays +editable and the save succeeds without its change (logged); a formula reads +`null` (logged). diff --git a/skills/objectstack-project/SKILL.md b/skills/objectstack-project/SKILL.md index 105ca67219f..2b66fe9f739 100644 --- a/skills/objectstack-project/SKILL.md +++ b/skills/objectstack-project/SKILL.md @@ -168,11 +168,11 @@ command fails on it, then replace the test with a one-line ## 5 · Bumping the platform, and customer data on upgrade Bump: -1. Move every `@objectstack/*` package to one version together, `@objectstack/skills` +1. Move every `@objectstack/*` package to one version, `@objectstack/skills` included, then re-sync the skills and commit them: `npx skills@1.7.2 experimental_sync --agent claude-code --copy -y` (name your own runtime after `--agent`). -2. Read each package's `CHANGELOG.md` between the two versions for breaking +2. Read each package's `CHANGELOG.md` between the versions for breaking entries. Crossing a protocol major: objectstack-upgrade. 3. Run the four checks. A new rule that reports existing metadata is fixed in the metadata, ⛔ never silenced. @@ -182,16 +182,16 @@ Bump: Data already installed: - Added objects, fields and indexes apply on boot. A rename carries - `renamedFrom`. A type change, a drop or a relaxed `NOT NULL` goes through + `renamedFrom`. A type change, a drop or a relaxed `NOT NULL` takes `os migrate plan` then `os migrate apply` (`--allow-destructive` for a drop). - Detail: objectstack-data, "Schema evolution". + Detail: objectstack-data `rules/field-types.md` § Changing a field that has data. - Removing a field or object, or changing what its value means, puts the old values out of reach once the new metadata is installed. Copy them first with a backfill script in `scripts/`: - - run it against each deployment while it is still on the old release; + - run it on each deployment while still on the old release; - REST API only, no import from `src/`, so it works on any installed metadata; - report by default, write only with `--apply`; - - touch only the rows that need it; a second run reports zero; + - touch only rows that need it; a second run reports zero; - sign in as an administrator named on the command line; the password or token comes from the environment or a prompt, never an argument. - ★ The release note names the script and when to run it.