Skip to content

Commit 1538596

Browse files
fix(lint,service-automation)!: a flow value envelope is typed for the date-text verdicts, so timestamp() over a date field is refused at os validate and registerFlow (#34654)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9USTJYAvMcxS7CFGZygeZG6)_ Fixes #34451 Completes #34661 (not closed by this PR: the seat closes it after merge). Clause-②: yes (narrowing) — narrowed: a flow value envelope (`assignment` values, `create_record` / `update_record` `fields.*`) that registered and published now refuses at `os validate` and at `registerFlow` when it hands `timestamp()` a date field (the date-text verdict family). Widened: the published `ExprSchemaHint` type gains one optional key, `flowValueEnvelope`. Metadata-protocol: narrowed Skills-docs: none — no published skill teaches a flow value envelope over a date field; `skills/objectstack-formula/SKILL.md` already states the `timestamp()` / `date-text-call` rule without naming a site, so it now holds for value envelopes as written ## 维护者速读 - 改了什么:flow 的值信封(`update_record` / `create_record` 的 `fields.*`、`assignment` 的值)在记录触发或对被定型对象的 sweep、且 flow 不自己重绑 `record`/`previous`(previous 只算节点绑定,声明的会被运行时覆盖)时,按触发对象的字段类型校验,只放行 date-text 这一族判词;`isoDate(timestamp(record.DATE_FIELD) + duration('168h'))` 这类写法在 `os validate` 和引擎 `registerFlow` 同时被拒,并提示改写为 `isoDate(addDays(record.DATE_FIELD, N))`;inbound hook、schedule、无触发或被父流程调用的 flow 不判。spec 的三条 ADR-0087 条目 surface 同步点名这个新位置(#34661)。 - 为什么改:日期字段运行时是 `YYYY-MM-DD` 文本,`timestamp()` 只认完整时间戳,这种写法过去校验通过、发布成功、每次运行都失败(cloud#4717 的现场);#34447 的拒绝够不到值信封。 - 风险与回滚:收窄(BREAKING,按 minor 发布):已存的、值信封里带这种写法的 flow 在挂了对象解析器的引擎上会注册失败,直到改写;只判 `record.FIELD` / `previous.FIELD` 读,其它类型判词不进值信封,运行时求值路径不变。回滚即 revert 本 PR。 - 先看:`packages/formula/src/validate.ts`(`flowValueEnvelopeDateTextIssue` 与新 hint 键)、`packages/services/service-automation/src/flow-registration-checks.ts`(注册门传字段类型、存量预览也算)、`packages/lint/src/validate-expressions.ts`(`checkDeclaredValue`)。 - 两分钟验证:`pnpm --filter @objectstack/service-automation exec vitest run --maxWorkers=2 src/builtin/assignment-value-envelope.test.ts -t 34451`,预期全部通过。 - 需要你做的:受管面未触及;本 PR 是收窄,落地前需一次契约复审记录,由席位路由。 ## What changes A flow value envelope was validated with no field types, by `@objectstack/lint`'s `checkDeclaredValue` and by the engine's `valueEnvelopeRefusals` alike, so the date-text verdicts (#28944, #32595, #34447) never reached it. Measured on `origin/main` ffa6db1 before building: a record-triggered flow whose `update_record` writes `due_date` from `isoDate(timestamp(record.borrow_date) + duration('168h'))` got zero findings from `validateStackExpressions` and registered clean, in `update_record`, `create_record` and `assignment` alike. Route A, as the seat named it: the date-text family only. - `packages/formula/src/validate.ts`: `ExprSchemaHint` gains the optional `flowValueEnvelope` key. With it (and `fieldTypes`), the `value` role runs ONE schema-aware pass, `flowValueEnvelopeDateTextIssue`: the date-text check typed at `record` scope, so it judges `record.FIELD` / `previous.FIELD` reads only; the Timestamp-typing mismatch is asked first and stands it down (so `record.due_date + 1` and `record.title * 2` stay another family's and say nothing here); the result is kept only when its code is `date-text-call*` / `date-text-arithmetic*`, under the `run-may-fail` arm. A bare name and a source that reads `input` take no verdict. Field existence, the near-miss, the bare-reference refusal, `type-mismatch*`, `date-arithmetic*`, `date-duration-value` and the traversal arm all stand down. Without the key the call is unchanged. - `packages/lint/src/validate-expressions.ts`: `checkDeclaredValue` takes the field types of the object the flow's conditions are typed against (start `objectName`, else a time-relative flow's swept object) and passes the hint only where the run's `record` is that object's row: the same `faultOutcomeOf` set a flow condition's proven outcome uses (record-triggered, or a sweep of the typed object), and only while the flow rebinds neither `record` (any row of `collectFlowVariableNames`) nor `previous` (a node row only: the collector asked without `flow.variables`, since `seedRunVariables` sets `previous` over a declared variable). Every other flow's envelopes are judged untyped, as before. - `packages/services/service-automation`: `valueEnvelopeRefusals(value, fieldTypes?)` passes the same hint when handed types. `validateFlowExpressions` hands it the resolver's field types for the bound object in BOTH modes, so `registerFlow` throws the refusal and the stored pass (`canonicalizeStoredFlow`) lists it at the slot; the binding is now derived in the stored mode too, so a time-relative flow is typed with its swept object there as well. The run-time evaluator still calls `valueEnvelopeRefusals(envelope)` untyped, unchanged. Three `engine.ts` docblocks that said "a resolver can never break a flow that used to register cleanly" now name this one exception. The typing is handed on only where `deriveTriggerBinding` gives record_change (string `triggerType`) or a time-relative sweep of the typed object, and `flowRebindsRunRowRoots` finds neither `record` (declared variable, node id, output / iterator / index / error variable, assignment target) nor `previous` (the same rows less the declared variable) via `flowNodeBoundNames`, so both doors judge one set. `plugin.ts`'s resolver wiring comment and debug line now say the same (L2 N2). - `.changeset/34451-flow-value-envelope-date-text.md`: `minor` for `@objectstack/spec`, `@objectstack/formula`, `@objectstack/lint` and `@objectstack/service-automation`, the declaration lines, **BREAKING** banner, FROM to TO table, ADR-0087 disposition `already-registered` naming the three semantic entries (`formula-timestamp-date-only-refused`, `formula-date-text-call-refused`, `formula-date-subtraction-refused`), whose `surface` this PR rewrites to name the value-envelope site, its scope (record-triggered or a sweep of the typed object, rebinding neither `record` nor `previous`), its boot-registration consequence, and an acceptance-criteria line telling an operator how to confirm a stored flow is clear (no "failed to register flow" warning at boot; no `registerFlow` TODO from `POST /api/v1/meta/_migrate-stored` on the running server — the CLI's `os migrate meta --stored` boots automation inert, `armRuntime: false`, with no object-schema resolver, so it types no value envelope and cannot show this); it states #34661 is completed by this PR. - `packages/spec/src/migrations/entries/semantic/18.formula-timestamp-date-only-refused.ts`, `18.formula-date-text-call-refused.ts`, `18.formula-date-subtraction-refused.ts`: `surface` text only (seat ruling on L2 S1, option i). No generated file moves (`check:generated` 14/14 up to date). ## Tests - `packages/formula/src/validate-date-text-arithmetic.test.ts`, new top-level describe: the measured expression refused under `date-text-call-run-may-fail` with its params (call, reference, rewrite, shift); the bare call, a `previous.FIELD` read and `record.borrow_date - duration('24h')`; CONTROL: a `datetime` field under `timestamp()` and the taught `addDays` shift stay clean; CONTROL: `record.title * 2`, `record.due_date + 1`, `today() - record.borrow_date` and an unknown field say nothing in an envelope while a formula site still reports `type-mismatch`; a bare name and an `input` read take no verdict; a malformed envelope is still refused, and no hint means no change. - `packages/lint/src/validate-expressions.test.ts`, new top-level describe: `validateStackExpressions` refuses the measured expression and the bare call in `update_record`, `create_record` and `assignment`, at the slot's key path, naming the `addDays` shift; a time-relative flow is typed with its swept object; CONTROL: a `datetime` field and the taught shift are clean, and a text field in arithmetic stays silent in the envelope. CONTROLs for the stand-down, each carrying `timestamp(record.borrow_date)`: an inbound-hook (`api`) start, a start with no trigger, a schedule, a child flow a parent starts through `subflow`, a record-triggered flow declaring a `record` variable, and one whose assignment assigns `record`. For the no-trigger and schedule starts the lint CONTROL asserts the findings equal those of a bare `record.borrow_date` read (the existing unbound-root refusal, #22565) and carry no date-text verdict. Round 3: `record` bound through a get_record outputVariable, a loop iterator / index variable, a try_catch errorVariable, a node id, and assignment shapes 2 and 3, and a sweep whose start names another object, each a CONTROL; `timestamp(previous.borrow_date)` refused, and two `previous` CONTROLs (get_record `outputVariable: 'previous'`, an assignment building it); a declared `previous` still refused; field minus field refused. - `packages/services/service-automation/src/builtin/assignment-value-envelope.test.ts`, new top-level describe: `registerFlow` throws for all three slots, located and led by the published value-envelope sentence, naming the shift; the stored pass lists exactly the slot `registerFlow` refuses; a time-relative flow is typed with its swept object; CONTROL: `datetime`, a text field in arithmetic and `record.due_date + 1` still register; with no resolver nothing changes, and the evaluator's own call stays untyped. CONTROLs for the stand-down, each carrying `timestamp(record.borrow_date)`: an inbound-hook (`api`) start, a start with no trigger, a schedule, a child flow a parent starts through `subflow`, a record-triggered flow declaring a `record` variable, and one whose assignment assigns `record`. Each registers, with no stored todos. Round 3: `record` bound through a get_record outputVariable, a loop iterator / index variable, a try_catch errorVariable, a node id, and assignment shapes 2 and 3, and a sweep whose start names another object, each a CONTROL; `timestamp(previous.borrow_date)` refused, and two `previous` CONTROLs (get_record `outputVariable: 'previous'`, an assignment building it); a declared `previous` still refused; field minus field refused. - No existing test changed: no test pinned the untyped value-envelope behaviour this narrows. ## Acceptance notes - **The outcome clause says "condition".** The verdict rides the existing `-run-may-fail` codes, whose shared clause reads "when the condition runs ... a flow condition that cannot be evaluated fails the run". On a value envelope the run does fail at that node (the evaluator throws), but the sentence names a condition. A value-worded arm would be a new code in the refusal ledger, which this card does not decide; the location and the leading value-envelope sentence name the slot. Reported to the seat. Disposition: filed #34660. - **Bare names stand down.** In a value envelope a bare name holds whatever the run's variable map holds; `@objectstack/lint` knows a flow's declared variables and open binders, the engine does not, and the two doors must refuse one set. So only `record.FIELD` / `previous.FIELD` reads are judged, at both doors. - **`date-duration-value` stays out.** It is a date verdict outside the date-text family the ruling names. - **ADR-0087.** The three registered entries carry the same verdicts, codes and rewrites; this PR rewrites their `surface` to name the flow value envelope (assignment values, create_record / update_record `fields.*`) within the stand-down scope (record-triggered flow or a time-relative sweep of the typed object, rebinding neither `record` nor `previous`), and the consequence: a stored flow carrying one fails to register at boot on an engine with the object-schema resolver wired until rewritten. For the subtraction entry only its first two shapes reach the envelope. Completes #34661 (not closed by this PR: the seat closes it after merge). - **Found on the way (reported to the seat, not fixed here):** in a flow CONDITION (flattened scope) a `record.FIELD` read is not typed by the date-text check: a record-triggered start condition comparing `timestamp(record.borrow_date)` with `now()` gets zero findings from `validateStackExpressions`, while the same comparison over the bare `timestamp(borrow_date)` is refused. Disposition: filed #34662. - **Stand-down residues (seat ruling).** (1) A screen field named `record` is not counted as the flow binding `record`, at either door, as lint's `declaredVariables` does not count screen fields: kept. (3) An open binder node (`script` and the like) could in principle rebind `record`; it is not counted, as lint's existing reading of `record.FIELD` in flow conditions keeps the row outcome (#30025): kept. (2) A record-triggered flow that a parent also starts through `subflow` / `map` is judged as if `record` were its trigger row, while on that entrance it is the parent's record. Disposition: filed #34694. - **A declared `record` variable stands the envelope down.** Kept from the S2 ruling: on a record-triggered or sweep entrance `seedRunVariables` writes `record` over a declared variable, so counting a declared `record` only refuses less, never wrongly. A conservative under-refusal, accepted by the seat. - **A `previous.F` read in a branch that never runs is refused too (L2 N8).** That is the scope of the published date-text rule itself, the same as on flow conditions on `main`; follows the published rule's scope, accepted by the seat, no card. - Governed surfaces: none in the diff. ## Verification Final head: `8598c1dcb77d7865c91fac5e967d1df84ed44d7d` (round 5, text only: 2a1630d, then a merge of `origin/main`). Round 5: the three entries' printed guidance no longer cites a tracker number (CI red at f11fa42: `packages/cli/test/migrate-meta-engine-guidance.test.ts:420`); `packages/cli/test/migrate-meta-engine-guidance.test.ts` 3/3, spec `src/migrations` + upgrade-guide-surface-span 213/213, `check:generated` up to date, the three changeset gates exit 0, `check:nul-bytes` exit 0. Round 4 head `f11fa429a9928903a4c41f400f34eb5ccc70be0e` ( text only: L2 S4 and N7 in 50adcc3, then a merge of `origin/main`). Round 4 (text only): spec build, `check:generated` (14 up to date), spec `src/migrations` + upgrade-guide-surface-span + build-migration-registry-entry 216/216, spec and formula typecheck, the three changeset gates on the current body (exit 0), `check:nul-bytes` exit 0; the derived-gate set, the lint / service-automation suites and the dogfood battery were not re-run (last at 97856f7, readings below). Round 3 head `97856f7327f7470fedfc65045b9a03eb4e4a6da8` ( L2 S3 / N5 / N6 in b49e849, then a merge of `origin/main` a34eb07; round 2 was 9a6882b and 8401e76). At that head: `@objectstack/formula` 68 files / 1872 tests, `@objectstack/lint` 214 / 9132, `@objectstack/service-automation` 287 / 4132, `@objectstack/spec` 848 / 27168 (1 todo), all passed, the four typechecks exit 0; spec `check:generated` exit 0 (14/14 up to date); `dispatch-gates --commands` 98 families, all exit 0, `--ran` 98 run / 0 NOT-MEASURED (`/mnt/project-files/objectstack-seat2/34451-gates-ran.txt`); dogfood battery `VERDICT command-exit 0`, 478 files passed / 3 skipped, 4055 tests passed / 68 skipped; the three changeset gates exit 0 (`not-required (already-registered)`). Stand-down ablations (`scripts/ablation-replace.mjs`, each restored, `git diff HEAD` empty): lint, the `previous` stand-down removed → 2 failed / 23 passed (the two `previous` CONTROLs); engine, `|| nodeBound.has('previous')` removed → 2 failed / 74 passed; lint, the trigger half removed → 5 failed (api, no trigger, schedule, subflow child, mismatched sweep); lint, the `record` half removed → 9 failed (declared `record`, the seven other binders, an assignment to `record`); engine, the whole predicate replaced by `true` → 16 failed (every CONTROL). The details below are the first round's, at `81d78bb0f0` (merge of `origin/main` 31096af into the branch). <details><summary>Premise on origin/main ffa6db1</summary> `validateStackExpressions` over a record-triggered flow, three slots, the measured expression, the bare call, the `datetime` control and `record.note * 2`: zero findings in all twelve. `registerFlow` with a resolver wired: all six (three slots, measured and `datetime`) registered, no warning logged. </details> <details><summary>Packages</summary> - `pnpm --filter @objectstack/formula test`: `Test Files 68 passed (68)`, `Tests 1872 passed (1872)`; `typecheck` exit 0 (at 17673d2; formula is untouched by the later merge). - `pnpm --filter @objectstack/lint test` at 81d78bb: `Test Files 214 passed (214)`, `Tests 9097 passed (9097)`; `typecheck` exit 0. - `pnpm --filter @objectstack/service-automation test` at 81d78bb: `Test Files 287 passed (287)`, `Tests 4113 passed (4113)`; `typecheck` exit 0. </details> <details><summary>Ablation: the field types withheld at each door</summary> Through `scripts/ablation-replace.mjs` (both suites import the edited file from source): - lint: anchor `fieldTypes ? { fieldTypes, flowValueEnvelope: true } : undefined,` x1 to x0, blob a47831c to 71212190e115: `Tests 4 failed | 2 passed` (the three slot cases and the time-relative case red; the two CONTROLs green). Restored: blob == HEAD a47831c, `git diff HEAD` empty. - service-automation: anchor `this.valueEnvelopeRefusals(found.value, schemaHint?.fieldTypes)` x1 to x0, blob 104d6e1 to b7c46e5799bc: `Tests 5 failed | 52 passed` (three slots, the stored pass, time-relative). Restored: blob == HEAD 104d6e1, `git diff HEAD` empty. </details> <details><summary>Gates and dogfood battery</summary> - `node scripts/pm/dispatch-gates.mjs --commands` at 81d78bb: 74 families, each run with its exit captured before any pipe; `--ran`: `74 derived famil(ies) accounted for — 74 run, 0 NOT-MEASURED`. `check:dual-build-cjs-loads` and `check:type-check-debt` first answered exit 3 (unbuilt packages; the lock held by the battery) and were re-run after building: exit 0 both. - `check-adr-0087-registration`: `[BREAKING+clause-②-narrowing+metadata-protocol-narrowed] not-required (already-registered)`, exit 0. - Dogfood battery at 81d78bb (closure `@objectstack/dogfood^...` built, then `pnpm --filter @objectstack/dogfood test` under the verify lock): `VERDICT command-exit 0`, `Test Files 478 passed | 3 skipped (481)`, `Tests 4055 passed | 68 skipped (4123)`. </details> <details><summary>git merge-tree against the in-flight lint PRs</summary> `git merge-tree --write-tree --name-only` of 81d78bb with each head, exit code and tree: - #34600 head 2da6508: exit 0, tree c652042ab2e9, no conflicted path. - #34513 head e5d2d0c (merged into main as b1efa37, and in this branch through the merge): exit 0, tree 49596be, no conflicted path. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmQAXHSQEgnYyx9tstb)_ <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmQAXHSQEgnYyx9tstb --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent dfbc316 commit 1538596

13 files changed

Lines changed: 871 additions & 33 deletions
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/formula': minor
4+
'@objectstack/lint': minor
5+
'@objectstack/service-automation': minor
6+
---
7+
8+
fix(lint,service-automation): a flow value envelope is typed for the date-text verdicts, so `timestamp(record.<date field>)` in an `update_record` / `create_record` field or an `assignment` value is refused at `os validate` and at `registerFlow`
9+
10+
Clause-②: yes (narrowing) — narrowed: a flow value envelope that registered and published now refuses at `os validate` and at `registerFlow`; owes the contract-review-tier review before the queue, and Tier H via the seat. Widened: the published `ExprSchemaHint` type gains one optional key, `flowValueEnvelope`.
11+
Metadata-protocol: narrowed
12+
Skills-docs: none — no published skill teaches a flow value envelope over a date field; `skills/objectstack-formula/SKILL.md` already states the `timestamp()` / `date-text-call` rule without naming a site, so it now holds for value envelopes as written
13+
14+
<!-- adr-0087: not-required (already-registered formula-timestamp-date-only-refused, formula-date-text-call-refused, formula-date-subtraction-refused) The three semantic entries already carry these verdicts, their codes and their rewrites to the upgrade guide; this change lets the same verdicts reach one more site, a flow value envelope, with the same rewrite, and rewrites each entry's surface in this PR to name that site, its scope (a record-triggered flow or a time-relative sweep of the typed object that rebinds neither record nor previous itself) and its consequence (a stored flow carrying one fails to register at boot on an engine with the object-schema resolver wired until rewritten), and adds to each entry's acceptance criteria how an upgrading operator confirms a stored flow is clear (no failed to register flow warning at boot, and no registerFlow TODO from POST /api/v1/meta/_migrate-stored on the running server; the CLI's os migrate meta --stored boots automation inert, with no object-schema resolver, so it types no value envelope and cannot show it). No id is added, no key is added, removed or re-shaped, and nothing an author wrote is rewritten. -->
15+
16+
The upgrade-guide half of the narrowing (#34661) is completed by this PR: the three ADR-0087 entries above now name the flow value envelope in their `surface`.
17+
18+
**BREAKING** accept-set narrowing, shipped as `minor`. A flow's value envelope (`assignment` `assignments.*`, `create_record` / `update_record` `fields.*`) was validated without field types, so the date-text verdicts never reached it. `isoDate(timestamp(record.borrow_date) + duration('168h'))` written into an `update_record` field passed `os validate`, registered, and failed every run: the runtime holds a `date` field as its `YYYY-MM-DD` text, and `timestamp()` parses only a full ISO-8601 instant.
19+
20+
- **The verdicts.** The envelope is now typed with the object the flow's run binds as `record` (the start node's `objectName`; a time-relative flow's swept object) — on a record-triggered flow, or a time-relative sweep of the typed object, that rebinds neither root the typing reads (no declared variable, node id, output / iterator / index / error variable or `assignment` target named `record`; no node id, output / iterator / index / error variable or `assignment` target named `previous` — the run's seed sets `previous` over a declared variable of that name) — for the date-text family alone: `date-text-call-run-may-fail` and `date-text-arithmetic-run-may-fail`, over `record.<field>` / `previous.<field>` reads. `timestamp(record.<date field>)`, alone or inside `+ duration(…)`, is refused with the shift `isoDate(addDays(record.<date field>, N))`; so are a `date` / `datetime` field handed straight to a timestamp-only call (`isoDate(record.picked_up_at)`) and arithmetic on its text (`record.borrow_date - duration('24h')`).
21+
- **Where.** `@objectstack/lint` `validateStackExpressions` (`os validate`, `os build`, the flow publish door) reports an `error` at the slot. `@objectstack/service-automation` `registerFlow` throws it when an object-schema resolver is wired, and the stored pass (`canonicalizeStoredFlow`) lists it at the slot. The two doors judge the same set of flows. A flow stored with such an envelope stops registering at boot until it is rewritten.
22+
- **Not refused.** Any envelope of a flow whose `record` is not proven to be the typed object's row: an inbound hook (`api`), a schedule, a flow with no trigger (started by hand or by a parent's `subflow` / `map`), a sweep of another object, and a record-triggered flow that declares or assigns its own `record` variable, or assigns or outputs its own `previous` — judged untyped, as before. `timestamp()` over a `datetime` field. A bare field name in an envelope, and an expression reading `input`: neither door can prove what the run binds there. Every other type verdict (`type-mismatch*`, `date-arithmetic*`, `date-duration-value`) and field existence stay out of value envelopes, as before. The run-time evaluator is unchanged.
23+
- **`@objectstack/formula`.** `ExprSchemaHint` gains the optional `flowValueEnvelope` key that both doors pass.
24+
- **`@objectstack/spec`.** The ADR-0087 entries `formula-timestamp-date-only-refused`, `formula-date-text-call-refused` and `formula-date-subtraction-refused` name the flow value envelope in their `surface` (for the subtraction entry, its first two shapes; the formula-only duration value stays out of envelopes). Text only: no id, key or shape changes.
25+
26+
## FROM → TO
27+
28+
| FROM | TO |
29+
|:---|:---|
30+
| `isoDate(timestamp(record.borrow_date) + duration('168h'))` | `isoDate(addDays(record.borrow_date, 7))` |
31+
| `timestamp(record.borrow_date)` | `date(record.borrow_date)` |
32+
| `isoDate(record.picked_up_at)` | `isoDate(date(record.picked_up_at))` |
33+
34+
One-line fix: in a flow value envelope, shift a date field by whole days with `isoDate(addDays(record.<date field>, N))`, never `timestamp(record.<date field>) + duration(…)`.

‎packages/formula/src/validate-date-text-arithmetic.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,3 +432,62 @@ describe('timestamp() handed a date-only field\'s text (#34363)', () => {
432432
expect(validateExpression('value', MEASURED, { scope: 'record' }).errors).toEqual([]);
433433
});
434434
});
435+
436+
describe('a flow value envelope typed for the date-text family alone (#34451)', () => {
437+
/** The object a record-triggered flow binds as `record`: a loan's borrow day, pick-up instant and title. */
438+
const fieldTypes = { title: 'text', borrow_date: 'date', due_date: 'date', picked_up_at: 'datetime' };
439+
const ENVELOPE: ExprSchemaHint = { fieldTypes, flowValueEnvelope: true };
440+
const codes = (source: string, hint: ExprSchemaHint | undefined = ENVELOPE) =>
441+
validateExpression('value', { dialect: 'cel', source }, hint).errors.map((e) => e.code);
442+
/** The expression cloud measured in an `update_record` node's `fields.due_date`. */
443+
const MEASURED = "isoDate(timestamp(record.borrow_date) + duration('168h'))";
444+
445+
it('refuses the measured expression under the run-may-fail arm, with the addDays shift', () => {
446+
const r = validateExpression('value', { dialect: 'cel', source: MEASURED }, ENVELOPE);
447+
expect(r.warnings).toEqual([]);
448+
expect(r.errors.map((e) => ({ code: e.code, params: e.params }))).toEqual([{
449+
code: 'date-text-call-run-may-fail',
450+
params: {
451+
call: 'timestamp(record.borrow_date)',
452+
reference: 'record.borrow_date',
453+
rewrite: 'date(record.borrow_date)',
454+
shift: 'isoDate(addDays(record.borrow_date, N))',
455+
},
456+
}]);
457+
expect(r.errors[0].message).toContain('`isoDate(addDays(record.borrow_date, N))`');
458+
});
459+
460+
it('refuses the bare call, a previous.<field> read, and date-text arithmetic over record.<field>', () => {
461+
expect(codes('timestamp(record.borrow_date)')).toEqual(['date-text-call-run-may-fail']);
462+
expect(codes('timestamp(previous.borrow_date)')).toEqual(['date-text-call-run-may-fail']);
463+
expect(codes("record.borrow_date - duration('24h')")).toEqual(['date-text-arithmetic-run-may-fail']);
464+
});
465+
466+
it('CONTROL: a datetime field under timestamp(), and the taught shift, stay clean', () => {
467+
expect(codes("isoDate(timestamp(record.picked_up_at) + duration('168h'))")).toEqual([]);
468+
expect(codes('isoDate(addDays(record.borrow_date, 7))')).toEqual([]);
469+
});
470+
471+
it('CONTROL: no verdict outside the date-text family reaches the envelope', () => {
472+
// type-mismatch, date-arithmetic, date-duration-value, field existence: all stand down.
473+
expect(codes('record.title * 2')).toEqual([]);
474+
expect(codes('record.due_date + 1')).toEqual([]);
475+
expect(codes('today() - record.borrow_date')).toEqual([]);
476+
expect(codes('record.no_such_field')).toEqual([]);
477+
// The same sources are refused or warned where a formula site types them.
478+
const formula: ExprSchemaHint = { scope: 'record', fields: Object.keys(fieldTypes), fieldTypes };
479+
const r = validateExpression('value', 'record.title * 2', formula);
480+
expect([...r.errors, ...r.warnings].map((e) => e.code)).toEqual(['type-mismatch']);
481+
});
482+
483+
it('a bare name, and a source reading `input`, take no verdict: the envelope cannot prove either is the field', () => {
484+
expect(codes("isoDate(timestamp(borrow_date) + duration('168h'))")).toEqual([]);
485+
expect(codes('timestamp(input.borrow_date)')).toEqual([]);
486+
});
487+
488+
it('a malformed envelope is refused as before, and without field types nothing new runs', () => {
489+
expect(codes('{record.borrow_date}')).toEqual(['cel-template-brace']);
490+
expect(validateExpression('value', { dialect: 'cel', source: MEASURED }).errors).toEqual([]);
491+
expect(codes(MEASURED, { flowValueEnvelope: true })).toEqual([]);
492+
});
493+
});

‎packages/formula/src/validate.ts‎

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,50 @@ export interface ExprSchemaHint {
297297
* Absent ⇒ every verdict is exactly as before this key.
298298
*/
299299
timeRelativeSweep?: boolean;
300+
/**
301+
* [#34451] `value` role only: the expression is a flow VALUE envelope — an
302+
* `assignment` node's `assignments.*`, a `create_record` / `update_record`
303+
* node's `fields.*` — and {@link fieldTypes} are the field types of the
304+
* object whose row the flow's run binds as `record`.
305+
*
306+
* The PREMISE is the caller's to establish, and both callers pass the key
307+
* only where it holds: the flow is record-triggered on that object, or a
308+
* time-relative sweep of it (the entrance hands the run that object's row
309+
* as `record`), AND the flow rebinds neither root the typing reads — no
310+
* declared variable, node id, output / iterator / index / error variable
311+
* or `assignment` target named `record`, and no node id, output / iterator
312+
* / index / error variable or `assignment` target named `previous` (the
313+
* run's seed sets `previous` over a declared variable of that name, so a
314+
* declaration does not rebind it) — since the run's variables are spread
315+
* over the scope an envelope reads. On any other flow (an inbound hook, a schedule,
316+
* a flow started by a parent's `subflow` / `map` or by hand) `record` is
317+
* whatever the entrance handed the run, and the key is not set.
318+
*
319+
* Of the schema-aware passes, ONLY the date-text verdict family runs —
320+
* `date-text-call*` and `date-text-arithmetic*` — and only over the
321+
* `record.<field>` / `previous.<field>` reads, which under that premise hold
322+
* what the entrance bound: the row under `record`, and under `previous` the
323+
* row before the write (on a record-change trigger's update leg) or null
324+
* (its create leg, and a sweep, have none; a read of it faults whatever the
325+
* field's type). Every other pass stands down: field existence, the
326+
* near-miss, the role catalog, the bare-reference refusal, `type-mismatch*`,
327+
* `date-arithmetic*` and `date-duration-value` say nothing here. A bare name
328+
* stands down too: in a value envelope it holds whatever the run's variable
329+
* map holds under that name, which no door judging this envelope alone can
330+
* prove is the field. So does an expression that reads the `input` root,
331+
* which a flow does not bind to the row the types describe.
332+
*
333+
* The verdict is an error under the `-run-may-fail` arm: the envelope faults
334+
* wherever the field holds the text the runtime keeps for it, and the
335+
* engine's value evaluator throws on that fault, so the run fails there.
336+
*
337+
* Both doors set it with the same inputs — `@objectstack/lint`'s
338+
* `validateStackExpressions` and `@objectstack/service-automation`'s
339+
* `registerFlow` — so they refuse one set. The run-time evaluator does not
340+
* set it: an envelope that registered is evaluated exactly as before.
341+
* Absent ⇒ every verdict is exactly as before this key.
342+
*/
343+
flowValueEnvelope?: boolean;
300344
}
301345

302346
/**
@@ -778,6 +822,37 @@ function dateTextCallIssue(
778822
};
779823
}
780824

825+
/** [#34451] The date-text verdict family: `date-text-call` / `date-text-arithmetic` and their outcome arms. */
826+
const DATE_TEXT_FAMILY_RE = /^date-text-(?:call|arithmetic)(?:-|$)/;
827+
828+
/**
829+
* [#34451] The verdict a flow value envelope gets ({@link ExprSchemaHint.flowValueEnvelope}):
830+
* the date-text family over the `record.<field>` / `previous.<field>` reads,
831+
* or `null`.
832+
*
833+
* Typed at `record` scope, which types exactly those roots (and `input`, which
834+
* is why a source reading `input` stands down): a bare name is then not a
835+
* field at all, so it never takes a verdict. The order is
836+
* {@link typeSoundnessIssue}'s: a shape the Timestamp typing already faults on
837+
* (`record.due_date + 1`, `record.note * 2`) is another family's, so the
838+
* date-text check is not asked about it. The outcome is `run-may-fail`, the
839+
* arm that names the field as the condition of the fault.
840+
*/
841+
function flowValueEnvelopeDateTextIssue(
842+
source: string,
843+
fieldTypes: Readonly<Record<string, string>>,
844+
ast: () => CelAstNode | null,
845+
): ExprValidationError | null {
846+
const celFieldTypes = toCelFieldTypes(fieldTypes);
847+
if (!Object.values(celFieldTypes).includes('timestamp')) return null;
848+
const tree = ast();
849+
if (!tree || readRootMembers(tree, ['input']).length > 0) return null;
850+
if (firstTypeMismatch(source, celFieldTypes, 'record')) return null;
851+
const dateOnly = new Set(Object.keys(fieldTypes).filter((name) => fieldTypes[name] === 'date'));
852+
const found = dateTextIssue(source, celFieldTypes, 'record', 'value', 'run-may-fail', dateOnly);
853+
return found && DATE_TEXT_FAMILY_RE.test(found.issue.code) ? found.issue : null;
854+
}
855+
781856
/** A bare `{x}` that is NOT part of a `{{x}}` mustache hole. */
782857
const SINGLE_BRACE_RE = /(?:^|[^{])\{\s*([A-Za-z_$][\w.$]*)\s*\}(?!\})/;
783858
/** The roots whose members the field-existence pass judges against `schema.fields`. */
@@ -1536,6 +1611,12 @@ export function validateExpression(
15361611
`${lead} — ${role}s are bare CEL (e.g. \`record.rating >= 4\`).`,
15371612
));
15381613
}
1614+
} else if (schema?.flowValueEnvelope === true) {
1615+
// [#34451] A flow value envelope: the date-text family alone (see the key's docblock).
1616+
const issue = role === 'value' && schema.fieldTypes
1617+
? flowValueEnvelopeDateTextIssue(source, schema.fieldTypes, ast)
1618+
: null;
1619+
if (issue) errors.push(issue);
15391620
} else {
15401621
checkFieldExistence(ast, source, schema, errors);
15411622
checkOptionLabelTargets(ast, source, schema, errors);
@@ -1632,7 +1713,10 @@ export function validateExpression(
16321713
// engine's formula read path preloads it before computing the field. Its
16331714
// caller opts in exactly as a validation condition's does, and the conflicts
16341715
// are worded for a field that reads null rather than a write that is refused.
1635-
if (schema?.fieldTypes && schema.traversalHydration === true && (role === 'predicate' || role === 'value')) {
1716+
if (
1717+
schema?.fieldTypes && schema.traversalHydration === true && schema.flowValueEnvelope !== true
1718+
&& (role === 'predicate' || role === 'value')
1719+
) {
16361720
const tree = ast();
16371721
const analysis = tree ? traversalsOf(readRootMembers(tree, [DEFAULT_TRAVERSAL_ROOT])) : null;
16381722
if (analysis) {

0 commit comments

Comments
 (0)