Skip to content

Commit c809deb

Browse files
fix(formula)!: a flow condition's record. / previous. read of a date field takes the date-text verdicts, so timestamp(record.DATE_FIELD) is refused as its bare name is (#34935)
Fixes #34662 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: none — `skills/objectstack-formula/SKILL.md` already states the `date-text-call` rule (a `date` / `datetime` field handed to a timestamp-only call, and `timestamp()` over a `date` field) with `record.FIELD` spellings and names no site it is limited to, so it now holds for a flow condition's root reads as written ## 维护者速读 - 改了什么:flow 条件(start / edge / `decision` 分支)里通过 `record.FIELD` / `previous.FIELD` 读日期字段时,现在与裸字段名一样接受 date-text 这一族校验;`timestamp(record.borrow_date) < now()`(`borrow_date` 为 date 字段)在 `os validate` 和 flow 发布门被拒,错误码、措辞、结果分支(`date-text-call-run-fails` 等)与裸名写法相同,提示改写为 `date(record.borrow_date)` 或 `isoDate(addDays(record.borrow_date, N))`。 - 为什么改:运行时 date 字段是 `YYYY-MM-DD` 文本,`timestamp()` 解析不了,这条 flow 每次运行都失败;裸名写法早已被拒,`record.` 写法却零告警通过。 - 风险与回滚:收窄(BREAKING,按 minor 发布):以前能通过 `os validate` 和发布的 flow 条件,若经 `record.` / `previous.` 把 date 字段交给 `timestamp()`(或交给 `isoDate()`、做文本日期运算),现在被拒,直到改写为 `date(record.FIELD)`;`registerFlow` 仍只记 advisory 日志、照常注册,已存的 flow 在下次发布前继续运行。datetime 字段、`date(...)` 改写、Timestamp 类型已判的形状(`record.due_date + 1`)不受影响。回滚即 revert 本 PR。 - 先看:`packages/formula/src/validate.ts`(`recordRootDateTextIssue` 与 `typeSoundnessIssue` 的接入点)、`packages/formula/src/cel-engine.ts`(`firstDateTextCall` / `firstDateTextVerdict` 新增的 `recordRootTypes` 参数与 `recordRootReadsFaultTimestampTyping`)、`.changeset/34662-flow-record-date-text.md`。 - 两分钟验证:`pnpm --filter @objectstack/formula exec vitest run --maxWorkers=2 src/validate-date-text-arithmetic.test.ts -t 34662`,预期 6 个用例全部通过。 - 需要你做的:无,席位落地(受管面未触及);本 PR 是收窄,落地前需一次契约复审记录,由席位路由。 ## What changes A flow condition is evaluated over a scope where the run's row is bound twice: its fields flattened to bare names, and the row itself as `record` (with the row before the write as `previous`). The date-text family (`date-text-call*`, `date-text-arithmetic*`) typed the bare names only. Measured on `origin/main` fc5913e through `validateStackExpressions`, with the card's fixture (`library_loan`, `borrow_date: date`, `picked_up_at: datetime`, start `record-after-update`): | start condition | findings before | findings after | |:---|:---|:---| | `timestamp(record.borrow_date) < now()` | 0 | 1 error, `record.borrow_date` named | | `timestamp(borrow_date) < now()` | 1 error | 1 error (unchanged) | | `timestamp(previous.borrow_date) < now()` | 0 | 1 error, `previous.borrow_date` named | | `timestamp(record.picked_up_at) < now()` (CONTROL) | 0 | 0 | The same holds on an edge condition and on a `decision` branch. The other members of the family missed root reads the same way and are covered by the same change: `isoDate(record.picked_up_at) == '...'` (0 findings before; the bare `isoDate(picked_up_at)` was refused) and `record.due_date - record.borrow_date > duration('24h')` (no date-text finding before). - `packages/formula/src/validate.ts`: `typeSoundnessIssue` runs a record-root pass after the bare-name date-text pass, at flattened scope only: `recordRootDateTextIssue`. It types `record.FIELD` / `previous.FIELD` with every field's type (a flow variable shadows a bare name, never a root member), leaves every bare name `dyn`, and keeps only `date-text-call*` / `date-text-arithmetic*`. This is the record-root pass `firstTypeMismatch` already runs for the text/boolean mismatch, applied to the date-text family. The outcome arm is the row's (`dateArm` with `bareNamesUnproven` false), as a root read keeps its outcome for `type-mismatch`. A shape the Timestamp typing of the roots already faults on (`record.due_date + 1`) belongs to the `date-arithmetic` family and stands down, the same order the flow value envelope uses. `dateTextIssue` / `dateTextCallIssue` take the optional root typing, and the message names the read as written (`verdict.root`). - `packages/formula/src/cel-engine.ts`: `firstDateTextVerdict` and `firstDateTextCall` take an optional `recordRootTypes` (flattened scope only) and pass it to `buildTypedEnv`. On that pass a root read qualifies by the root typing alone, so an `input.FIELD` read does not qualify. Without the argument every call is unchanged. `DateTextVerdict` gains the optional `root`. `recordRootReadsFaultTimestampTyping` is the stand-down probe. None of these is on the package's public entry. - `.changeset/34662-flow-record-date-text.md`: `minor` for `@objectstack/formula` (the kind `narrowed` takes at least `minor`), with the declaration lines, the **BREAKING** banner, a FROM to TO table and the ADR-0087 disposition `already-registered` naming the three semantic entries (`formula-timestamp-date-only-refused`, `formula-date-text-call-refused`, `formula-date-subtraction-refused`). Their `surface` text already names flow conditions among the predicates judged with field types, spelled with `record.FIELD`, so it is left as is: this change makes that text true for a root read. No entry, generated file or registry changes. No producer change was needed outside `packages/formula`. `@objectstack/lint` (`os validate`, and the runtime publish gate that runs the same `runStackExpressionPasses` body) and `@objectstack/service-automation` (`registerFlow`) already hand flow conditions the flattened hint with field types and the declared outcome. The fix reaches all three through the shared validator. ## Tests - `packages/formula/src/validate-date-text-arithmetic.test.ts`: new top-level describe in the date-text harness. `record.` and `previous.` over a date field are refused under `date-text-call-run-fails` with full params (call, reference, rewrite, shift), and the evaluator faults on them over the run's scope. CONTROL: `datetime` and the prescribed `date(...)` parse are clean and evaluate to `true`. Arm pins: `run-may-fail` with no declared outcome; `run-fails` kept on a root read when bare names are unproven. A flow variable shadowing the bare name leaves the root read judged. `isoDate(record.picked_up_at)` and root-read date-text arithmetic are refused. The stand-downs (`record.due_date + 1`, an `input.` read) take no date-text code. - `packages/lint/src/validate-expressions.test.ts`: new top-level describe. Start, edge and `decision` conditions refuse `record.` / `previous.` at the bare name's path and severity, with the shift text. Rule id `expression-invalid` through `runAuthoringRules('build', ...)`. CONTROL: `datetime` stays clean through either root at all three sites. - `packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts` (new; the flow publish door, `saveMetaItem` then `publishMetaItem` over the real engine): the bare name, `record.` and `previous.` are each refused with `{ code: 'INVALID_METADATA', status: 422 }`, one `expression-invalid` date-text issue each, and the item left `draft`. CONTROL: `datetime` through either root publishes (`active`). - `packages/services/service-automation/src/flow-registration-schema-e2e.test.ts`: new describe. `registerFlow` logs the date-text advisory for `record.` / `previous.` as for the bare name and registers the flow. CONTROL: `datetime` is not advised. Ablation, after the fix was committed (`scripts/ablation-replace.mjs --hold`, trap restore): the record-root pass was disabled in `validate.ts` (call guarded by a literal that never equals the source), `@objectstack/formula` rebuilt, and `ablation-dist-preflight.mjs` confirmed the marker in `dist/index.js` and `dist/index.mjs`. Result: formula 4 failed / 83 passed, lint 4 failed / 1 passed, service-automation 1 failed / 4 passed, runtime 1 failed / 1 passed. Every refusal pin went red and every CONTROL stayed green. Restore: blob equal to HEAD, `git diff HEAD` empty, rebuilt, `--absent` preflight clean, `git status --porcelain` empty. ## Acceptance notes - **Declaration (seat ruling, L1 REWORK round 1).** `Clause-②: no (narrowing)`, `Metadata-protocol: narrowed`: a pure narrowing, since the new `recordRootTypes` parameter is on non-exported functions and nothing published widens. A contract-review-tier L2 review is owed before the queue; the seat routes it. - **The publish door for a flow condition is `publishMetaItem` (seat: accepted as landed).** `registerFlow` logs a condition's schema-aware findings as an advisory and never throws, by contract (#1928, `flow-registration-checks.ts`); it does not refuse the bare spelling either. The refusal with `code` / `status` is the metadata publish gate (`INVALID_METADATA` / 422), pinned in `packages/runtime`; `registerFlow` is pinned for advisory parity. - **Test placement.** The dispatch asked for a new test file named after the card. AGENTS.md (ruling record 6583487846) puts a new pin for a component that already has a shared harness into that file as a top-level `describe`. So the formula, lint and `registerFlow` pins went into their existing harnesses. The publish-door pin is a new file, because no harness pins a flow condition's date verdict at that door. - The `record` root is typed even when a flow declares a variable named `record`. The `type-mismatch` record-root pass has always done the same, and this change does not alter it. - Same-shape gap outside this family, not fixed here: the `date-arithmetic` verdict (Timestamp typing, `due_date + 1 > 5`) refuses the bare name in a flow condition but not `record.due_date + 1 > 5` / `previous.due_date + 1 > 5`. Measured on this branch with a `required` date field: 1 error and 0 / 0 findings. The seat files it; this family stands down on that shape so as not to change its code. ## Verification Final head 60d4e1c. Dogfood battery on it (the `(narrowing)` arm): `pnpm --filter '@objectstack/dogfood^...' build` then `pnpm --filter @objectstack/dogfood test` under the lock, VERDICT command-exit 0, Test Files 479 passed / 3 skipped (482), Tests 4072 passed / 68 skipped (4140). Merged-head (653f1fb) package tests and typechecks: formula 68 files / 1878 tests, lint `validate-expressions.test.ts` 505/505, service-automation e2e 5/5, runtime publish-door 2/2, all four typechecks green. Gate readings and CI: the os-dev-report comments on the card. <details><summary>Premise table on origin/main fc5913e (built lint dist)</summary> ``` [start] timestamp(record.borrow_date) LT now() -> 0 [start] timestamp(borrow_date) LT now() -> 1 (error, `borrow_date` is a date field ...) [start] timestamp(record.picked_up_at) LT now() -> 0 [start] timestamp(previous.borrow_date) LT now() -> 0 [edge] same three rows: 0 / 1 / 0 ``` (LT spells the less-than operator.) </details> <details><summary>After the fix (same probe)</summary> ``` [start] timestamp(record.borrow_date) LT now() -> 1 error, `record.borrow_date` is a date field [start] timestamp(borrow_date) LT now() -> 1 error [start] timestamp(record.picked_up_at) LT now() -> 0 [start] timestamp(previous.borrow_date) LT now() -> 1 error, `previous.borrow_date` is a date field [start] timestamp(previous.picked_up_at) LT now() -> 0 [edge] identical ``` </details> --- _Generated by [Claude Code](https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C)_ <!-- signed: repo:objectstack#4 · os-lizheng · session_012MmDsS4GoHCgYwA2uv3n3C --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent dc53d4a commit c809deb

7 files changed

Lines changed: 583 additions & 27 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
'@objectstack/formula': minor
3+
---
4+
5+
fix(formula)!: a flow condition that hands `timestamp()` a date field through `record.FIELD` or `previous.FIELD` is now refused, as the bare field name already was
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: narrowed
9+
Skills-docs: none — `skills/objectstack-formula/SKILL.md` already states the `date-text-call` rule (a `date` / `datetime` field handed to a timestamp-only call, and `timestamp()` over a `date` field) with `record.FIELD` spellings and names no site it is limited to, so it now holds for a flow condition's root reads as written
10+
11+
<!-- 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, and each entry's surface already names flow conditions among the CEL predicates judged with the object's field types, with record.FIELD spellings as its examples. This change makes that text true for a flow condition that reads the field through record or previous, where only the bare field name was judged before; the verdicts, codes, rewrites and acceptance criteria are the entries' own. No id is added, no key is added, removed or re-shaped, and nothing an author wrote is rewritten. -->
12+
13+
**BREAKING** accept-set narrowing, shipped as `minor`. In a flow condition (a start, edge or `decision` branch condition) the run binds the record's fields under their bare names and also as `record`, with the row before the write as `previous`. The date-text checks judged only the bare name. `timestamp(borrow_date) < now()` over a `date` field was refused, but `timestamp(record.borrow_date) < now()` passed `os validate` and the publish door. The flow then failed on every run, because a date field reaches the run as its `YYYY-MM-DD` text, which `timestamp()` does not parse.
14+
15+
- **The verdicts.** A `record.FIELD` / `previous.FIELD` read in a flow condition now gets the date-text checks its bare name gets, with the same code and outcome arm (`date-text-call-run-fails` / `date-text-arithmetic-run-fails` on a record-triggered flow or a sweep of the typed object, `-run-may-fail` elsewhere). The message names the read as written and prescribes `date(record.FIELD)`, or `isoDate(addDays(record.FIELD, N))` to shift by whole days. This covers the calls the text cannot take (`timestamp(record.FIELD)` over a `date` field, `isoDate(record.FIELD)` over a `date` or `datetime` field) and arithmetic on the text (`record.end_date - record.start_date`).
16+
- **Where.** `os validate` / `os build` (`validateStackExpressions`) report an `error`, and the flow publish door refuses the publish with `INVALID_METADATA` (422). `registerFlow` logs it as an advisory, as it does for the bare name, and still registers the flow, so a stored flow keeps running until it is next published.
17+
- **Not refused.** `timestamp()` over a `datetime` field. A shape the Timestamp typing already faults on (`record.due_date + 1`), which is another verdict's. An `input.FIELD` read. The run-time evaluator is unchanged.
18+
19+
## FROM → TO
20+
21+
| FROM | TO |
22+
|:---|:---|
23+
| `timestamp(record.borrow_date) < now()` | `date(record.borrow_date) < now()` |
24+
| `timestamp(previous.borrow_date) < now()` | `date(previous.borrow_date) < now()` |
25+
| `isoDate(record.picked_up_at) == '2026-11-16'` | `isoDate(date(record.picked_up_at)) == '2026-11-16'` |
26+
27+
One-line fix: in a flow condition, parse a date field with `date(record.FIELD)` before comparing it with a timestamp, never `timestamp(record.FIELD)`.

‎packages/formula/src/cel-engine.ts‎

Lines changed: 89 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1255,6 +1255,14 @@ function withoutNames(
12551255
return out;
12561256
}
12571257

1258+
/**
1259+
* [#29959, #34662] A `record.` / `previous.` read spelled member-wise — the gate
1260+
* of every flattened record-root pass ({@link firstTypeMismatch}'s and
1261+
* `validate.ts`'s date-text one), so the two can never disagree on whether a
1262+
* source reads a root.
1263+
*/
1264+
export const RECORD_ROOT_READ_RE = /(?<![\w$.])(?:record|previous)\s*\./;
1265+
12581266
/**
12591267
* [#29959] The `record.<field>` / `previous.<field>` read of a field of
12601268
* `celType` in a flattened condition, as written — what
@@ -1408,9 +1416,10 @@ export function firstTypeMismatch(
14081416
// [#29959] A flattened condition reads the same field as `record.<field>`
14091417
// (and `previous.<field>`), which the bare typing above leaves `dyn`. A
14101418
// second pass types those roots too, for the text/boolean mismatch only:
1411-
// the same verdict the bare name gets. The date verdicts stay the bare
1412-
// name's alone, as before.
1413-
if (scope !== 'flattened' || !/(?<![\w$.])(?:record|previous)\s*\./.test(source)) return null;
1419+
// the same verdict the bare name gets. The `date-arith` verdict stays the
1420+
// bare name's alone, as before; the date-text family reaches the roots
1421+
// through `validate.ts`'s record-root pass (#34662).
1422+
if (scope !== 'flattened' || !RECORD_ROOT_READ_RE.test(source)) return null;
14141423
const rootTyped = unsoundOverload(buildTypedEnv(bareTypes, 'flattened', 'timestamp', fieldCelTypes));
14151424
const r = rootTyped && textOrBool(rootTyped) ? confirmAgainstDateText(rootTyped, fieldCelTypes) : null;
14161425
const celType = r ? textOrBool(r) : null;
@@ -1510,10 +1519,15 @@ function registerDateTextAnswersOnString(env: Environment): void {
15101519
* answer, so the expression faults and the field reads null;
15111520
* - `type` — the expression checks clean, and `type` is the CEL type it
15121521
* computes (`google.protobuf.Duration` for `today() - record.start_date`).
1522+
* `root` is set on the flattened record-root pass (`recordRootTypes`, #34662)
1523+
* when `field` is named by its `record.<field>` / `previous.<field>` read.
15131524
*/
15141525
export type DateTextVerdict =
1515-
| { readonly kind: 'fault'; readonly operator: string; readonly operands: string; readonly field: string | null }
1516-
| { readonly kind: 'type'; readonly type: string; readonly field: string | null };
1526+
| {
1527+
readonly kind: 'fault'; readonly operator: string; readonly operands: string; readonly field: string | null;
1528+
readonly root?: 'record' | 'previous';
1529+
}
1530+
| { readonly kind: 'type'; readonly type: string; readonly field: string | null; readonly root?: 'record' | 'previous' };
15171531

15181532
/**
15191533
* #28944 — type-check `source` with every `date`/`datetime` field declared as
@@ -1535,32 +1549,73 @@ export type DateTextVerdict =
15351549
* Returns `null` when the source does not parse, or the check faults on
15361550
* anything other than arithmetic with a date field's text — that is another
15371551
* check's to report, and this one never guesses.
1552+
*
1553+
* [#34662] `recordRootTypes` (flattened scope only) types a flow condition's
1554+
* `record.<field>` / `previous.<field>` reads as well, the record-root pass
1555+
* {@link firstTypeMismatch} runs for the text/boolean mismatch: the field is
1556+
* then named by its root read (`root`) wherever one is spelled member-wise.
15381557
*/
15391558
export function firstDateTextVerdict(
15401559
source: string,
15411560
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
15421561
scope: 'record' | 'flattened' = 'record',
1562+
recordRootTypes?: Readonly<Record<string, FieldCelType>>,
15431563
): DateTextVerdict | null {
15441564
if (typeof source !== 'string' || !source.trim()) return null;
1565+
const rootTypes = scope === 'flattened' ? recordRootTypes : undefined;
15451566
try {
1546-
const env = buildTypedEnv(fieldCelTypes, scope, 'date-text');
1567+
const env = buildTypedEnv(fieldCelTypes, scope, 'date-text', rootTypes);
15471568
const result = env.parse(rewriteNullableTernary(rewriteIndexedHas(source))).check?.() as
15481569
| { valid?: boolean; type?: unknown; error?: { message?: string } }
15491570
| undefined;
15501571
if (!result) return null;
1551-
const field = offendingField(source, fieldCelTypes, 'timestamp', scope);
1572+
const read = rootTypes ? offendingRecordRead(source, rootTypes, 'timestamp') : null;
1573+
const named = read
1574+
? { field: read.field, root: read.root }
1575+
: { field: offendingField(source, fieldCelTypes, 'timestamp', scope) };
15521576
if (result.valid !== false) {
1553-
return typeof result.type === 'string' ? { kind: 'type', type: result.type, field } : null;
1577+
return typeof result.type === 'string' ? { kind: 'type', type: result.type, ...named } : null;
15541578
}
15551579
const m = UNSOUND_OVERLOAD_RE.exec(result.error?.message ?? '');
15561580
if (!m || !ARITH_OPS.has(m[2]) || (m[1] !== DATE_TEXT_CEL_TYPE && m[3] !== DATE_TEXT_CEL_TYPE)) return null;
1557-
return { kind: 'fault', operator: m[2], operands: `${m[1]} ${m[2]} ${m[3]}`, field };
1581+
return { kind: 'fault', operator: m[2], operands: `${m[1]} ${m[2]} ${m[3]}`, ...named };
15581582
} catch {
15591583
// A parse/other fault is the syntax checker's job (celEngine.compile).
15601584
return null;
15611585
}
15621586
}
15631587

1588+
/**
1589+
* [#34662] Whether the FIRST operator fault the Timestamp typing of a flattened
1590+
* condition's `record.<field>` / `previous.<field>` reads meets (every bare
1591+
* name `dyn`) is date/duration arithmetic against a number ({@link isDateArith})
1592+
* — `record.due_date + 1`. That shape is the `date-arithmetic` family's, and it
1593+
* is exactly where the bare name's own order stops: {@link firstTypeMismatch}
1594+
* answers `date-arith` there and the date-text check is never asked. Any other
1595+
* Timestamp-typing fault — `record.end_date - record.start_date > 3` (a Duration
1596+
* ordered against a number), `record.d >= "2026-01-01"` (the text ordering the
1597+
* runtime answers) — leaves the bare name's mismatch check at null and the
1598+
* date-text check asked, so it does not stand the record-root pass down
1599+
* either. `false` when the source does not parse.
1600+
*/
1601+
export function recordRootReadsFaultDateArith(
1602+
source: string,
1603+
recordRootTypes: Readonly<Record<string, FieldCelType>>,
1604+
): boolean {
1605+
if (typeof source !== 'string' || !source.trim()) return false;
1606+
try {
1607+
const result = buildTypedEnv({}, 'flattened', 'timestamp', recordRootTypes)
1608+
.parse(rewriteNullableTernary(rewriteIndexedHas(source))).check?.() as
1609+
| { valid?: boolean; error?: { message?: string } }
1610+
| undefined;
1611+
if (result?.valid !== false) return false;
1612+
const m = UNSOUND_OVERLOAD_RE.exec(result.error?.message ?? '');
1613+
return m !== null && isDateArith(m);
1614+
} catch {
1615+
return false;
1616+
}
1617+
}
1618+
15641619
/**
15651620
* cel-js's code for a CALL no overload accepts — `isoDate(string)`,
15661621
* `string.getFullYear()` — raised by the checker and the evaluator alike
@@ -1622,24 +1677,39 @@ export interface DateTextCall {
16221677
* wrap the field for, so the rewrite is `date(<field>)` in place of the call,
16231678
* and `shift` carries the whole-day shift the stdlib teaches,
16241679
* `isoDate(addDays(<field>, N))`, which reads the date text as it is.
1680+
*
1681+
* [#34662] `recordRootTypes` (flattened scope only): a flow condition's
1682+
* `record.<field>` / `previous.<field>` reads are typed with these, as
1683+
* {@link firstDateTextVerdict}'s record-root pass types them, and a root read
1684+
* qualifies by them alone (an `input.<field>` read then does not qualify: a
1685+
* flow does not bind `input` to the row the types describe). Absent, every
1686+
* reference is judged by `fieldCelTypes`, exactly as before.
16251687
*/
16261688
export function firstDateTextCall(
16271689
source: string,
16281690
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
16291691
scope: 'record' | 'flattened' = 'record',
16301692
dateOnlyFields: ReadonlySet<string> = new Set(),
1693+
recordRootTypes?: Readonly<Record<string, FieldCelType>>,
16311694
): DateTextCall | null {
16321695
if (typeof source !== 'string' || !source.trim()) return null;
1633-
const dateFields: Record<string, FieldCelType> = {};
1634-
let any = false;
1635-
for (const [name, t] of Object.entries(fieldCelTypes)) {
1636-
dateFields[name] = t === 'timestamp' ? 'timestamp' : 'dyn';
1637-
any ||= t === 'timestamp';
1638-
}
1696+
const textTyping = (types: Readonly<Record<string, FieldCelType>>): Record<string, FieldCelType> =>
1697+
Object.fromEntries(Object.entries(types).map(([name, t]) => [name, t === 'timestamp' ? 'timestamp' : 'dyn']));
1698+
const dateFields = textTyping(fieldCelTypes);
1699+
const rootDateFields = scope === 'flattened' && recordRootTypes ? textTyping(recordRootTypes) : undefined;
1700+
/** The date-text typing a reference is judged by: its root's, on the record-root pass. */
1701+
const typingOf = (written: string): Record<string, FieldCelType> | undefined => {
1702+
if (!rootDateFields) return dateFields;
1703+
const root = written.includes('.') ? written.slice(0, written.indexOf('.')) : undefined;
1704+
return root === undefined ? dateFields : root === 'record' || root === 'previous' ? rootDateFields : undefined;
1705+
};
1706+
const isDate = (name: string, types: Record<string, FieldCelType> | undefined): boolean =>
1707+
types?.[name] === 'timestamp';
1708+
const any = [dateFields, rootDateFields].some((types) => types && Object.values(types).includes('timestamp'));
16391709
if (!any) return null;
1640-
const anyDateOnly = [...dateOnlyFields].some((name) => dateFields[name] === 'timestamp');
1710+
const anyDateOnly = [...dateOnlyFields].some((name) => isDate(name, dateFields) || isDate(name, rootDateFields));
16411711
try {
1642-
const env = buildTypedEnv(dateFields, scope, 'text');
1712+
const env = buildTypedEnv(dateFields, scope, 'text', rootDateFields);
16431713
const parsed = env.parse(rewriteNullableTernary(rewriteIndexedHas(source)));
16441714
// The whole expression checking clean is the common case: nothing to find,
16451715
// unless a date-only field can reach `timestamp()`, which checks clean.
@@ -1655,7 +1725,7 @@ export function firstDateTextCall(
16551725
};
16561726
const dateRef = (node: unknown): string | null => {
16571727
const ref = typedFieldRef(node, scope);
1658-
return ref && dateFields[ref.name] === 'timestamp' ? ref.written : null;
1728+
return ref && isDate(ref.name, typingOf(ref.written)) ? ref.written : null;
16591729
};
16601730
let verdict: DateTextCall | null = null;
16611731
const visit = (v: unknown): void => {
@@ -1672,7 +1742,7 @@ export function firstDateTextCall(
16721742
// [#34363] `timestamp(<date-only field>)`: clean on the text, faults on it.
16731743
if (v.op === 'call' && Array.isArray(args) && args[0] === 'timestamp' && operands?.length === 1) {
16741744
const ref = typedFieldRef(operands[0], scope);
1675-
if (ref && dateFields[ref.name] === 'timestamp' && dateOnlyFields.has(ref.name)) {
1745+
if (ref && isDate(ref.name, typingOf(ref.written)) && dateOnlyFields.has(ref.name)) {
16761746
const rewrite = wrapInDate(operands[0] as CelNode);
16771747
if (checkOf(rewrite) === true) {
16781748
verdict = {

0 commit comments

Comments
 (0)