Skip to content

Commit 1bbeb94

Browse files
fix(formula): date-subtraction refusals name the sub-day datetime() form (#33291)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9D4Jsmd91BqTVB7dSii9uJMV)_ Fixes #32980 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:公式校验对「两个日期/日期时间字段相减」的拒绝提示(`date-text-arithmetic` 及其各 arm、`date-duration-value`),在 `daysBetween` 旁边补上按小时/分钟算跨度的写法:两侧各包一层 `datetime(…)`,再读 Duration 的 `.getMinutes()` / `.getHours()`;公式文档与 formula 技能表格同步一行。 - **为什么改**:「加班小时 = 结束 − 开始」是 HR 应用第一天就要写的公式,原提示只指向按整天计的 `daysBetween`,能用的写法只能去翻 stdlib 源码才找得到。 - **风险与回滚**:只改提示文案,拒绝码与 params 不变,该写法在 main 上本就校验通过、求值正确(新测试实测 98 小时与 3.5 小时);回滚即 revert 本 PR。 - **先看**:`packages/formula/src/validate.ts`(`shift` 常量,两个拒绝共用这一句);`packages/formula/src/validate-date-text-arithmetic.test.ts`(新增的子日跨度用例)。 - **两分钟验证**:`pnpm --filter @objectstack/formula exec vitest run src/validate-date-text-arithmetic.test.ts`,预期全绿,其中含 `the sub-day form reads the hours between two date-time fields`。 - **需要你做的**:无。`skills/**` 那一行已按席位指示移到单独的 PR #33294(Refs #32980,等授权审批人),本 PR 不再受管,复审通过后由本区落地。 ## What changes - `packages/formula/src/validate.ts`: the shared `shift` sentence that both the `date-text-arithmetic` family (bare, `-fail-closed`, `-fail-open`, `-run-fails`, `-run-may-fail`) and `date-duration-value` append now adds: "For a span in hours or minutes, wrap each side in `datetime(…)` and read the Duration: `(datetime(b) - datetime(a)).getMinutes()` / `.getHours()`." Codes and params are unchanged. The `date-arithmetic` refusal (a date plus a number) is untouched: it is not a span. - `content/docs/data-modeling/formulas.mdx`: the Date subtraction row names the same form and gives the hours example. The `skills/objectstack-formula/SKILL.md` row moved to PR #33294 at `bb078699`, so this PR is no longer governed. - One `patch` changeset for `@objectstack/formula`. ## Tests - `validate-date-text-arithmetic.test.ts`: two control rows in the gate-versus-evaluator table (`double((datetime(record.end_at) - datetime(record.start_at)).getMinutes()) / 60.0` and `(now() - datetime(record.start_at)).getHours()`: both validate clean and evaluate to a value), and one test that the hours form validates `ok` and evaluates to `98` and `3.5` on two served rows. These pin the card's premise: the form works at `origin/main` `d4fbb4db`, before and after this diff, because only wording changed. - `expression-refusal-codes.test.ts`: the existing exact-message pins for the seven affected codes take the new sentence. Those pins are the file's declared control (the message is what API callers, the CLI and the agent tool read beside the code), so no new message pin was added. ## Acceptance notes - Ruled out here, per the dispatch: a new stdlib helper such as `hoursBetween(a, b)`. It would be a new authorable function (a contract change), so it needs its own ruling; the card's Expected names it as an alternative only. - Not changed: `packages/spec/src/migrations/entries/semantic/18.formula-date-subtraction-refused.ts`. Its `replacement` is released 18.x text written by hand, not generated from the `validate.ts` sentence, so changing it would rewrite a published migration entry; it still prescribes `daysBetween`, which remains correct for whole days. - Skills: no `skills/**` change at head `bb078699` (the row measured at `4350de67`, 493 → 494 lines, ships in PR #33294). ## Verification Head `4350de67` (the merge of `origin/main` was a no-op: `origin/main` had not moved from `d4fbb4db`). <details><summary>formula test + typecheck (under the verify lock)</summary> ``` pnpm --filter @objectstack/formula test && pnpm --filter @objectstack/formula typecheck Test Files 67 passed (67) Tests 1760 passed (1760) check:test-typecheck: OK os-verify-lock: VERDICT command-exit 0 ``` </details> <details><summary>Derived gate families (dispatch-gates --commands, 103 families)</summary> 102 of 103 exit 0 locally, each exit code captured before any pipe. Six first answered exit 3 (prerequisite not met: unbuilt `formula`, `lint`, `client-react`, `objectql` dist) and were re-run green after a build of those packages: `check:doc-formula-expressions`, `check:doc-security-posture`, `check:skill-examples`, `check:docs-transcript-drift`, `check:dual-build-cjs-loads`, `check:lean-entry-closure`. `check:skill-docs` exit 0. NOT MEASURED: `node scripts/check-plugin-teardown-shape.mjs --self-test`, reason: shallow clone cannot reach its pinned positive-control commit; CI runs it on a full checkout. `dispatch-gates --ran`: 103 derived families accounted for. `check:nul-bytes`: OK. </details> `test:repo` was not run locally (the diff does not touch that project); `Test Core` carries it in CI. domain:server#5 · os-elon-musk · session_016WV4cw787kMeaX7oyz7DDC 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4cw787kMeaX7oyz7DDC <!-- signed: domain:server#5 · os-elon-musk · session_016WV4cw787kMeaX7oyz7DDC --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3ae387d commit 1bbeb94

5 files changed

Lines changed: 51 additions & 9 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/formula': patch
3+
---
4+
5+
fix(formula): the date-subtraction refusals name the sub-day form next to `daysBetween`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The `date-text-arithmetic` refusal (and its flow and fail-closed / fail-open arms) and the `date-duration-value` refusal sent an author who wanted an hour span, such as overtime hours from two date-time fields, to `daysBetween(a, b)`, which counts whole days only. Both refusals now add: for a span in hours or minutes, wrap each side in `datetime(…)` and read the Duration, `(datetime(b) - datetime(a)).getMinutes()` / `.getHours()`. That form already validated and evaluated; only the refusal wording changes, and the refusal codes and params are unchanged.
11+
12+
FROM `record.end_at - record.start_at` (refused, `date-text-arithmetic`) TO `double((datetime(record.end_at) - datetime(record.start_at)).getMinutes()) / 60.0` for the hours between them.

‎content/docs/data-modeling/formulas.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ come at two severities: **errors** fail the build; **warnings** are advisory
244244
| **Unknown function** — a misspelled or nonexistent stdlib call. | `isBlnk(record.x)` | error |
245245
| **Type soundness** — a text or boolean field used with an arithmetic (`+ - * / %`) or ordering (`< > <= >=`) operator against a number faults at runtime unless the text is numeric. In a formula it evaluates to `null`. Where a fault does something else it is an error, worded for what happens: a validation rule, a field `requiredWhen` / `readonlyWhen`, an option `visibleWhen` or a hook `condition` refuses the write; a record-triggered flow's start, edge or `decision` branch condition fails the run (the write that fired it still lands), whether it reads the field bare or as `record.<field>`, and so does a time-relative flow's that sweeps the same object, where no write fires the run and only the run for that row fails; a bare name that a declared flow variable or a `screen` field holds reads that value, so it is not judged as the field, and a bare name after a node that can bind any name (`script`, `connector_action`, `wait`, `subflow`, `map`, a screen with no fields) gets the warning instead, while its `record.<field>` read is still refused; an advisory (`severity: 'warning'` / `'info'`) validation rule is skipped, so it never gives its advisory. Store it as a number field, compare text with text, or convert explicitly (`size(record.name)` for the length; `double(record.name)`, which itself faults on text that is not a number). | `record.title * 2`; `record.name > 5` in a validation rule → `size(record.name) > 5` | warning in a formula or a display predicate, and in a condition of any other flow, where the warning says the run fails if the condition faults (what such a flow binds under the name depends on how it is started); error at the sites named |
246246
| **Date arithmetic** — a `date` / `datetime` field used with `+` / `-` against a number (a `YYYY-MM-DD` value is a string at runtime, so this always faulted to `null`). Use the date helpers instead. | `record.end_date - record.start_date + 1` → `daysBetween(record.start_date, record.end_date) + 1`; `today() + 30` → `daysFromNow(30)`; `record.date + n` → `addDays(record.date, n)` | error (#3306) |
247-
| **Date subtraction** — the runtime holds a `date` / `datetime` field as its text (`YYYY-MM-DD`, or an ISO-8601 instant), so subtracting two of them faults and the formula reads `null`; a timestamp minus one computes a duration, which a field reads as `{}`. Use `daysBetween`. A condition may still compare a duration (`today() - record.start_date > duration("72h")`). | `record.end_date - record.start_date` → `daysBetween(record.start_date, record.end_date)`; `today() - record.start_date` → `daysBetween(record.start_date, today())` | error |
247+
| **Date subtraction** — the runtime holds a `date` / `datetime` field as its text (`YYYY-MM-DD`, or an ISO-8601 instant), so subtracting two of them faults and the formula reads `null`; a timestamp minus one computes a duration, which a field reads as `{}`. Use `daysBetween`; for hours or minutes, wrap each side in `datetime(…)` and read the Duration. A condition may still compare a duration (`today() - record.start_date > duration("72h")`). | `record.end_date - record.start_date` → `daysBetween(record.start_date, record.end_date)`; `today() - record.start_date` → `daysBetween(record.start_date, today())`; `record.end_at - record.start_at` in hours → `double((datetime(record.end_at) - datetime(record.start_at)).getMinutes()) / 60.0` | error |
248248

249249
> **Integer literals in arithmetic are fine.** `record.amount / 100`,
250250
> `record.price * 2`, `record.total - fee` all work — the engine handles mixed

‎packages/formula/src/expression-refusal-codes.test.ts‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -381,7 +381,9 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
381381
'date arithmetic `DateText - DateText` — `record.start_date` is a date field, and the runtime holds a date field ' +
382382
'as its text (`YYYY-MM-DD`, or an ISO-8601 instant for a date-time), which CEL can\'t do arithmetic on: this ' +
383383
'faults at runtime, so the field silently evaluates to null. Use `daysBetween(a, b)` for the span in whole days, ' +
384-
'and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
384+
'and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date. ' +
385+
'For a span in hours or minutes, wrap each side in `datetime(…)` and read the Duration: ' +
386+
'`(datetime(b) - datetime(a)).getMinutes()` / `.getHours()`.',
385387
},
386388
],
387389
'date-text-arithmetic-fail-closed': [
@@ -398,7 +400,9 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
398400
'as its text (`YYYY-MM-DD`, or an ISO-8601 instant for a date-time), which CEL can\'t do arithmetic on: ' +
399401
'this faults at runtime, and here an expression that cannot be evaluated fails closed: the write (or the operation ' +
400402
'a hook guards) is refused, not skipped (it does not read null). ' +
401-
'Use `daysBetween(a, b)` for the span in whole days, and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
403+
'Use `daysBetween(a, b)` for the span in whole days, and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date. ' +
404+
'For a span in hours or minutes, wrap each side in `datetime(…)` and read the Duration: ' +
405+
'`(datetime(b) - datetime(a)).getMinutes()` / `.getHours()`.',
402406
},
403407
],
404408
'date-text-arithmetic-fail-open': [
@@ -416,7 +420,9 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
416420
'this faults at runtime, and here the rule is advisory, so a rule that cannot be evaluated is skipped, not refused: ' +
417421
'the write proceeds, the rule is never applied (its advisory never fires), and the only trace is a log line saying ' +
418422
'it could not be evaluated. ' +
419-
'Use `daysBetween(a, b)` for the span in whole days, and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
423+
'Use `daysBetween(a, b)` for the span in whole days, and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date. ' +
424+
'For a span in hours or minutes, wrap each side in `datetime(…)` and read the Duration: ' +
425+
'`(datetime(b) - datetime(a)).getMinutes()` / `.getHours()`.',
420426
},
421427
],
422428
'date-text-arithmetic-run-fails': [
@@ -434,7 +440,9 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
434440
'this faults at runtime, and ' +
435441
'a flow condition that cannot be evaluated fails the run: the flow stops at this condition and the work the flow ' +
436442
'exists to do is not done (it does not read null). ' +
437-
'Use `daysBetween(a, b)` for the span in whole days, and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
443+
'Use `daysBetween(a, b)` for the span in whole days, and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date. ' +
444+
'For a span in hours or minutes, wrap each side in `datetime(…)` and read the Duration: ' +
445+
'`(datetime(b) - datetime(a)).getMinutes()` / `.getHours()`.',
438446
},
439447
],
440448
'date-text-arithmetic-run-may-fail': [
@@ -451,7 +459,9 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
451459
'this faults wherever `start_at` holds that text when the condition runs, and ' +
452460
'a flow condition that cannot be evaluated fails the run: the flow stops at this condition and the work the flow ' +
453461
'exists to do is not done (it does not read null). ' +
454-
'Use `daysBetween(a, b)` for the span in whole days, and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
462+
'Use `daysBetween(a, b)` for the span in whole days, and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date. ' +
463+
'For a span in hours or minutes, wrap each side in `datetime(…)` and read the Duration: ' +
464+
'`(datetime(b) - datetime(a)).getMinutes()` / `.getHours()`.',
455465
},
456466
],
457467
// [#32595] A call handed a date field's text that no overload accepts.
@@ -563,15 +573,19 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
563573
message:
564574
'date arithmetic — this computes a `google.protobuf.Duration` from `record.start_date`, and a field can\'t hold ' +
565575
'a duration: it reads `{}` at runtime. Use `daysBetween(a, b)` for the span in whole days, and ' +
566-
'`daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
576+
'`daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date. ' +
577+
'For a span in hours or minutes, wrap each side in `datetime(…)` and read the Duration: ' +
578+
'`(datetime(b) - datetime(a)).getMinutes()` / `.getHours()`.',
567579
},
568580
{
569581
produce: () => onlyError('value', 'today() - daysAgo(3)', { scope: 'record', fieldTypes: { name: 'text' } }),
570582
params: {},
571583
message:
572584
'date arithmetic — this computes a `google.protobuf.Duration`, and a field can\'t hold ' +
573585
'a duration: it reads `{}` at runtime. Use `daysBetween(a, b)` for the span in whole days, and ' +
574-
'`daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
586+
'`daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date. ' +
587+
'For a span in hours or minutes, wrap each side in `datetime(…)` and read the Duration: ' +
588+
'`(datetime(b) - datetime(a)).getMinutes()` / `.getHours()`.',
575589
},
576590
],
577591
'type-mismatch': [

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,9 @@ describe('date subtraction the runtime cannot answer (#28944)', () => {
8383
['value', 'daysBetween(record.start_date, today())', null, 'value'],
8484
['predicate', 'today() - record.start_date > duration("72h")', null, 'value'],
8585
['value', '(today() - record.start_date).getHours()', null, 'value'],
86+
// The sub-day form the refusals prescribe: each side parsed, the Duration read.
87+
['value', 'double((datetime(record.end_at) - datetime(record.start_at)).getMinutes()) / 60.0', null, 'value'],
88+
['value', '(now() - datetime(record.start_at)).getHours()', null, 'value'],
8689
['predicate', 'record.end_date < record.start_date', null, 'value'],
8790
['predicate', 'record.start_date < today()', null, 'value'],
8891
['predicate', 'record.start_at > now()', null, 'value'],
@@ -119,6 +122,15 @@ describe('date subtraction the runtime cannot answer (#28944)', () => {
119122
expect(since.message).toMatch(/daysBetween\(a, b\)/);
120123
});
121124

125+
it('the sub-day form reads the hours between two date-time fields', () => {
126+
const source = 'double((datetime(record.end_at) - datetime(record.start_at)).getMinutes()) / 60.0';
127+
expect(validateExpression('value', source, RECORD_SCOPE).ok).toBe(true);
128+
const r = celEngine.evaluate({ dialect: 'cel', source }, { record: SERVED_ROW });
129+
expect(r).toMatchObject({ ok: true, value: 98 });
130+
const half = { ...SERVED_ROW, start_at: '2026-11-05T08:30:00.000Z' };
131+
expect(celEngine.evaluate({ dialect: 'cel', source }, { record: half })).toMatchObject({ ok: true, value: 3.5 });
132+
});
133+
122134
it('judges a flattened (flow) condition the same way, under the flow codes (#30016)', () => {
123135
const flattened: ExprSchemaHint = {
124136
fields: ['start_date', 'end_date'],

‎packages/formula/src/validate.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -684,7 +684,11 @@ function dateTextIssue(
684684
? (scope === 'record' ? `record.${verdict.field}` : verdict.field)
685685
: undefined;
686686
const ref = reference !== undefined ? `\`${reference}\`` : null;
687-
const shift = `\`daysFromNow(n)\` / \`addDays(d, n)\` / \`addMonths(d, n)\` to shift a date.`;
687+
// A span under a day has no stdlib helper; the Duration of two parsed sides does it.
688+
const shift =
689+
`\`daysFromNow(n)\` / \`addDays(d, n)\` / \`addMonths(d, n)\` to shift a date. For a span in ` +
690+
`hours or minutes, wrap each side in \`datetime(…)\` and read the Duration: ` +
691+
`\`(datetime(b) - datetime(a)).getMinutes()\` / \`.getHours()\`.`;
688692
if (verdict.kind === 'fault') {
689693
const subject = ref ? `${ref} is a date field` : 'a date field is an operand';
690694
const params = { operands: verdict.operands, ...(reference !== undefined ? { reference } : {}) };

0 commit comments

Comments
 (0)