From 89c181ca5f3632af28f39d00e0604638f110f18c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:29:35 +0000 Subject: [PATCH 1/7] wip(formula): type record./previous. reads for the date-text family in a flow condition Claude-Session: https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C Co-authored-by: Claude --- packages/formula/src/cel-engine.ts | 86 ++++++++++++++++++++++++------ packages/formula/src/validate.ts | 66 ++++++++++++++++++++--- 2 files changed, 128 insertions(+), 24 deletions(-) diff --git a/packages/formula/src/cel-engine.ts b/packages/formula/src/cel-engine.ts index e4d83827d46..85b191d2669 100644 --- a/packages/formula/src/cel-engine.ts +++ b/packages/formula/src/cel-engine.ts @@ -1460,10 +1460,15 @@ function registerDateTextAnswersOnString(env: Environment): void { * answer, so the expression faults and the field reads null; * - `type` — the expression checks clean, and `type` is the CEL type it * computes (`google.protobuf.Duration` for `today() - record.start_date`). + * `root` is set on the flattened record-root pass (`recordRootTypes`, #34662) + * when `field` is named by its `record.` / `previous.` read. */ export type DateTextVerdict = - | { readonly kind: 'fault'; readonly operator: string; readonly operands: string; readonly field: string | null } - | { readonly kind: 'type'; readonly type: string; readonly field: string | null }; + | { + readonly kind: 'fault'; readonly operator: string; readonly operands: string; readonly field: string | null; + readonly root?: 'record' | 'previous'; + } + | { readonly kind: 'type'; readonly type: string; readonly field: string | null; readonly root?: 'record' | 'previous' }; /** * #28944 — type-check `source` with every `date`/`datetime` field declared as @@ -1485,32 +1490,66 @@ export type DateTextVerdict = * Returns `null` when the source does not parse, or the check faults on * anything other than arithmetic with a date field's text — that is another * check's to report, and this one never guesses. + * + * [#34662] `recordRootTypes` (flattened scope only) types a flow condition's + * `record.` / `previous.` reads as well, the record-root pass + * {@link firstTypeMismatch} runs for the text/boolean mismatch: the field is + * then named by its root read (`root`) wherever one is spelled member-wise. */ export function firstDateTextVerdict( source: string, fieldCelTypes: Readonly>, scope: 'record' | 'flattened' = 'record', + recordRootTypes?: Readonly>, ): DateTextVerdict | null { if (typeof source !== 'string' || !source.trim()) return null; + const rootTypes = scope === 'flattened' ? recordRootTypes : undefined; try { - const env = buildTypedEnv(fieldCelTypes, scope, 'date-text'); + const env = buildTypedEnv(fieldCelTypes, scope, 'date-text', rootTypes); const result = env.parse(rewriteNullableTernary(rewriteIndexedHas(source))).check?.() as | { valid?: boolean; type?: unknown; error?: { message?: string } } | undefined; if (!result) return null; - const field = offendingField(source, fieldCelTypes, 'timestamp', scope); + const read = rootTypes ? offendingRecordRead(source, rootTypes, 'timestamp') : null; + const named = read + ? { field: read.field, root: read.root } + : { field: offendingField(source, fieldCelTypes, 'timestamp', scope) }; if (result.valid !== false) { - return typeof result.type === 'string' ? { kind: 'type', type: result.type, field } : null; + return typeof result.type === 'string' ? { kind: 'type', type: result.type, ...named } : null; } const m = UNSOUND_OVERLOAD_RE.exec(result.error?.message ?? ''); if (!m || !ARITH_OPS.has(m[2]) || (m[1] !== DATE_TEXT_CEL_TYPE && m[3] !== DATE_TEXT_CEL_TYPE)) return null; - return { kind: 'fault', operator: m[2], operands: `${m[1]} ${m[2]} ${m[3]}`, field }; + return { kind: 'fault', operator: m[2], operands: `${m[1]} ${m[2]} ${m[3]}`, ...named }; } catch { // A parse/other fault is the syntax checker's job (celEngine.compile). return null; } } +/** + * [#34662] Whether the Timestamp typing of a flattened condition's + * `record.` / `previous.` reads (every bare name `dyn`) faults an + * operator overload — `record.due_date + 1`. Such a shape is the Timestamp + * typing's family (`date-arithmetic`), never the date-text check's, so the + * record-root date-text pass stands down on it, as a flow value envelope's + * does. `false` when the source does not parse. + */ +export function recordRootReadsFaultTimestampTyping( + source: string, + recordRootTypes: Readonly>, +): boolean { + if (typeof source !== 'string' || !source.trim()) return false; + try { + const result = buildTypedEnv({}, 'flattened', 'timestamp', recordRootTypes) + .parse(rewriteNullableTernary(rewriteIndexedHas(source))).check?.() as + | { valid?: boolean; error?: { message?: string } } + | undefined; + return result?.valid === false && UNSOUND_OVERLOAD_RE.test(result.error?.message ?? ''); + } catch { + return false; + } +} + /** * cel-js's code for a CALL no overload accepts — `isoDate(string)`, * `string.getFullYear()` — raised by the checker and the evaluator alike @@ -1572,24 +1611,39 @@ export interface DateTextCall { * wrap the field for, so the rewrite is `date()` in place of the call, * and `shift` carries the whole-day shift the stdlib teaches, * `isoDate(addDays(, N))`, which reads the date text as it is. + * + * [#34662] `recordRootTypes` (flattened scope only): a flow condition's + * `record.` / `previous.` reads are typed with these, as + * {@link firstDateTextVerdict}'s record-root pass types them, and a root read + * qualifies by them alone (an `input.` read then does not qualify: a + * flow does not bind `input` to the row the types describe). Absent, every + * reference is judged by `fieldCelTypes`, exactly as before. */ export function firstDateTextCall( source: string, fieldCelTypes: Readonly>, scope: 'record' | 'flattened' = 'record', dateOnlyFields: ReadonlySet = new Set(), + recordRootTypes?: Readonly>, ): DateTextCall | null { if (typeof source !== 'string' || !source.trim()) return null; - const dateFields: Record = {}; - let any = false; - for (const [name, t] of Object.entries(fieldCelTypes)) { - dateFields[name] = t === 'timestamp' ? 'timestamp' : 'dyn'; - any ||= t === 'timestamp'; - } + const textTyping = (types: Readonly>): Record => + Object.fromEntries(Object.entries(types).map(([name, t]) => [name, t === 'timestamp' ? 'timestamp' : 'dyn'])); + const dateFields = textTyping(fieldCelTypes); + const rootDateFields = scope === 'flattened' && recordRootTypes ? textTyping(recordRootTypes) : undefined; + /** The date-text typing a reference is judged by: its root's, on the record-root pass. */ + const typingOf = (written: string): Record | undefined => { + if (!rootDateFields) return dateFields; + const root = written.includes('.') ? written.slice(0, written.indexOf('.')) : undefined; + return root === undefined ? dateFields : root === 'record' || root === 'previous' ? rootDateFields : undefined; + }; + const isDate = (name: string, types: Record | undefined): boolean => + types?.[name] === 'timestamp'; + const any = [dateFields, rootDateFields].some((types) => types && Object.values(types).includes('timestamp')); if (!any) return null; - const anyDateOnly = [...dateOnlyFields].some((name) => dateFields[name] === 'timestamp'); + const anyDateOnly = [...dateOnlyFields].some((name) => isDate(name, dateFields) || isDate(name, rootDateFields)); try { - const env = buildTypedEnv(dateFields, scope, 'text'); + const env = buildTypedEnv(dateFields, scope, 'text', rootDateFields); const parsed = env.parse(rewriteNullableTernary(rewriteIndexedHas(source))); // The whole expression checking clean is the common case: nothing to find, // unless a date-only field can reach `timestamp()`, which checks clean. @@ -1605,7 +1659,7 @@ export function firstDateTextCall( }; const dateRef = (node: unknown): string | null => { const ref = typedFieldRef(node, scope); - return ref && dateFields[ref.name] === 'timestamp' ? ref.written : null; + return ref && isDate(ref.name, typingOf(ref.written)) ? ref.written : null; }; let verdict: DateTextCall | null = null; const visit = (v: unknown): void => { @@ -1622,7 +1676,7 @@ export function firstDateTextCall( // [#34363] `timestamp()`: clean on the text, faults on it. if (v.op === 'call' && Array.isArray(args) && args[0] === 'timestamp' && operands?.length === 1) { const ref = typedFieldRef(operands[0], scope); - if (ref && dateFields[ref.name] === 'timestamp' && dateOnlyFields.has(ref.name)) { + if (ref && isDate(ref.name, typingOf(ref.written)) && dateOnlyFields.has(ref.name)) { const rewrite = wrapInDate(operands[0] as CelNode); if (checkOf(rewrite) === true) { verdict = { diff --git a/packages/formula/src/validate.ts b/packages/formula/src/validate.ts index ab8704550e3..b6b759921b8 100644 --- a/packages/formula/src/validate.ts +++ b/packages/formula/src/validate.ts @@ -24,6 +24,7 @@ import { firstDateTextVerdict, firstTypeMismatch, inferCelType, + recordRootReadsFaultTimestampTyping, parseCelToAst, parseCelToAstWithReason, type CelAstNode, @@ -508,7 +509,9 @@ const DATE_FAIL_CLOSED_CLAUSE = * the Timestamp typing passes, re-checked with a date field declared as the * text the runtime holds — see {@link dateTextIssue}; in a flow condition * and on a fail-closed site the fault takes the same outcome codes as - * `date-arith`. + * `date-arith`. A flattened condition's `record.` / `previous.` + * read takes the date-text family as its bare name does + * ({@link recordRootDateTextIssue}, #34662). * `scope` selects `record.` vs bare field binding, shaping the message. */ function typeSoundnessIssue( @@ -548,7 +551,8 @@ function typeSoundnessIssue( : celFieldTypes; // [#34363] The `date` fields (never `datetime`) by name: `timestamp()` faults on their text. const dateOnly = new Set(Object.keys(bareCelTypes).filter((name) => fieldTypes[name] === 'date')); - return dateTextIssue(source, bareCelTypes, scope, role, dateArm(scope, faultOutcome, bareNamesUnproven), dateOnly); + const bare = dateTextIssue(source, bareCelTypes, scope, role, dateArm(scope, faultOutcome, bareNamesUnproven), dateOnly); + return bare ?? (scope === 'flattened' ? recordRootDateTextIssue(source, fieldTypes, celFieldTypes, role, faultOutcome) : null); } const reference = mismatch.field ? (mismatch.root !== undefined @@ -657,7 +661,9 @@ function typeSoundnessIssue( * fault (ADR-0032 §1c) on every flow: a date verdict there never reads null. * `run-fails` where the caller declares the run proven to hold the field * (`faultOutcome: 'run-fails'`) and no node can rebind a bare name - * (`bareNamesUnproven`) — the date verdicts read bare names only. Anywhere + * (`bareNamesUnproven`) — for a bare-name verdict; a `record.` / + * `previous.` read keeps the row's outcome whatever binds the bare + * names (#30025, {@link recordRootDateTextIssue} passes `false`). Anywhere * else in a flow the name holds what the entrance handed the run (an API body * whose value is a number answers `close_date + 1`), so the run fails only * where it holds the date: `run-may-fail`. A `record`-scoped site that fails @@ -713,6 +719,9 @@ function dateArmFault(arm: DateArm, ref: string | null, held: 'date' | 'text'): * (`today() - record.d > duration('72h')`) evaluates, and is not touched. * Runs only when there is something to find: a date field to retype, or a * `value` whose computed type is the question. + * + * [#34662] `recordRoots` (flattened scope only) is the record-root pass's + * typing of `record.` / `previous.` ({@link recordRootDateTextIssue}). */ function dateTextIssue( source: string, @@ -721,14 +730,18 @@ function dateTextIssue( role: 'predicate' | 'value', flowArm: DateArm | null, dateOnlyFields: ReadonlySet, + recordRoots?: Readonly>, ): { issue: ExprValidationError; severity: 'error' | 'warning' } | null { - if (role !== 'value' && !Object.values(celFieldTypes).includes('timestamp')) return null; - const verdict = firstDateTextVerdict(source, celFieldTypes, scope); + const anyDate = [celFieldTypes, recordRoots].some((types) => types && Object.values(types).includes('timestamp')); + if (role !== 'value' && !anyDate) return null; + const verdict = firstDateTextVerdict(source, celFieldTypes, scope, recordRoots); // [#32595] A call the date text cannot take faults that typing too, so it is // asked only where the date-text check faulted on something but arithmetic. - if (!verdict) return dateTextCallIssue(source, celFieldTypes, scope, flowArm, dateOnlyFields); + if (!verdict) return dateTextCallIssue(source, celFieldTypes, scope, flowArm, dateOnlyFields, recordRoots); const reference = verdict.field - ? (scope === 'record' ? `record.${verdict.field}` : verdict.field) + ? (verdict.root !== undefined + ? `${verdict.root}.${verdict.field}` + : scope === 'record' ? `record.${verdict.field}` : verdict.field) : undefined; const ref = reference !== undefined ? `\`${reference}\`` : null; // A span under a day has no stdlib helper; the Duration of two parsed sides does it. @@ -791,8 +804,9 @@ function dateTextCallIssue( scope: 'record' | 'flattened', flowArm: DateArm | null, dateOnlyFields: ReadonlySet, + recordRoots?: Readonly>, ): { issue: ExprValidationError; severity: 'error' | 'warning' } | null { - const found = firstDateTextCall(source, celFieldTypes, scope, dateOnlyFields); + const found = firstDateTextCall(source, celFieldTypes, scope, dateOnlyFields, recordRoots); if (!found) return null; const params = { call: found.call, @@ -825,6 +839,42 @@ function dateTextCallIssue( /** [#34451] The date-text verdict family: `date-text-call` / `date-text-arithmetic` and their outcome arms. */ const DATE_TEXT_FAMILY_RE = /^date-text-(?:call|arithmetic)(?:-|$)/; +/** A `record.` / `previous.` read spelled member-wise — what the record-root pass can type. */ +const RECORD_ROOT_READ_RE = /(?` / `previous.` reads. + * + * A flow run binds the record it was handed as `record` beside the flattened + * bare names, and the row before the write as `previous` (#29959), so + * `timestamp(record.borrow_date)` faults on the `YYYY-MM-DD` text exactly as + * `timestamp(borrow_date)` does — the bare spelling was refused while the + * root read, left `dyn`, checked clean. Typed here with every field's type + * (a flow variable shadows a bare name, never a root member), every bare name + * `dyn`, the same verdict, code and words come back, naming the read as + * written. The order is {@link flowValueEnvelopeDateTextIssue}'s: a shape the + * Timestamp typing of the roots already faults on (`record.due_date + 1`) is + * the Timestamp typing's family, not this one, so the pass stands down on it; + * only `date-text-call*` / `date-text-arithmetic*` are kept. The outcome arm is + * the row's: a root read keeps the declared outcome whatever binds the bare + * names (#30025), so `bareNamesUnproven` is not asked. + */ +function recordRootDateTextIssue( + source: string, + fieldTypes: Readonly>, + celFieldTypes: Readonly>, + role: 'predicate' | 'value', + faultOutcome: ExprSchemaHint['faultOutcome'], +): { issue: ExprValidationError; severity: 'error' | 'warning' } | null { + if (!RECORD_ROOT_READ_RE.test(source) || !Object.values(celFieldTypes).includes('timestamp')) return null; + if (recordRootReadsFaultTimestampTyping(source, celFieldTypes)) return null; + const dateOnly = new Set(Object.keys(celFieldTypes).filter((name) => fieldTypes[name] === 'date')); + const found = dateTextIssue(source, {}, 'flattened', role, dateArm('flattened', faultOutcome, false), dateOnly, celFieldTypes); + return found && DATE_TEXT_FAMILY_RE.test(found.issue.code) ? found : null; +} + /** * [#34451] The verdict a flow value envelope gets ({@link ExprSchemaHint.flowValueEnvelope}): * the date-text family over the `record.` / `previous.` reads, From 190e741b7ebc48d6545168df50135962748550e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:37:52 +0000 Subject: [PATCH 2/7] wip: pins for the flow condition record-root date-text verdict Claude-Session: https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C Co-authored-by: Claude --- .../src/validate-date-text-arithmetic.test.ts | 77 +++++++++++++++++++ .../lint/src/validate-expressions.test.ts | 70 +++++++++++++++++ 2 files changed, 147 insertions(+) diff --git a/packages/formula/src/validate-date-text-arithmetic.test.ts b/packages/formula/src/validate-date-text-arithmetic.test.ts index fda6fb58498..10fa42787a4 100644 --- a/packages/formula/src/validate-date-text-arithmetic.test.ts +++ b/packages/formula/src/validate-date-text-arithmetic.test.ts @@ -491,3 +491,80 @@ describe('a flow value envelope typed for the date-text family alone (#34451)', expect(codes(MEASURED, { flowValueEnvelope: true })).toEqual([]); }); }); + +describe('a flow condition\'s record. / previous. read takes the date-text family as its bare name does (#34662)', () => { + /** A record-triggered flow's condition over a loan: the hint `@objectstack/lint` hands a start, edge or decision condition. */ + const fieldTypes = { title: 'text', borrow_date: 'date', due_date: 'date', picked_up_at: 'datetime' }; + const CONDITION: ExprSchemaHint = { fields: Object.keys(fieldTypes), fieldTypes, faultOutcome: 'run-fails' }; + const errorsOf = (source: string, hint: ExprSchemaHint = CONDITION) => + validateExpression('predicate', source, hint).errors; + const codes = (source: string, hint: ExprSchemaHint = CONDITION) => errorsOf(source, hint).map((e) => e.code); + /** What the run binds: the row under `record` (and `previous`), and its fields flattened bare. */ + const ROW = { title: 'Dune', borrow_date: '2026-11-16', due_date: '2026-11-30', picked_up_at: '2026-11-16T09:30:00.000Z' }; + const run = (source: string) => celEngine.evaluate({ dialect: 'cel', source }, { ...ROW, record: ROW, previous: ROW }); + + it('refuses timestamp() over a date field through record. and previous. under the same code as the bare name, naming the read', () => { + expect(codes('timestamp(borrow_date) < now()')).toEqual(['date-text-call-run-fails']); + for (const root of ['record', 'previous'] as const) { + const source = `timestamp(${root}.borrow_date) < now()`; + const errors = errorsOf(source); + expect(errors.map((e) => ({ code: e.code, params: e.params })), source).toEqual([{ + code: 'date-text-call-run-fails', + params: { + call: `timestamp(${root}.borrow_date)`, + reference: `${root}.borrow_date`, + rewrite: `date(${root}.borrow_date)`, + shift: `isoDate(addDays(${root}.borrow_date, N))`, + }, + }]); + expect(errors[0].message).toContain(`\`isoDate(addDays(${root}.borrow_date, N))\``); + // The run faults on the date-only text, exactly as the bare spelling does. + expect(run(source), source).toMatchObject({ ok: false }); + } + expect(run('timestamp(borrow_date) < now()')).toMatchObject({ ok: false }); + }); + + it('CONTROL: a datetime field under timestamp(), and the prescribed parse, stay clean and evaluate', () => { + for (const source of [ + 'timestamp(record.picked_up_at) < now()', + 'timestamp(previous.picked_up_at) < now()', + 'date(record.borrow_date) < now()', + ]) { + expect(validateExpression('predicate', source, CONDITION), source).toEqual({ ok: true, errors: [], warnings: [] }); + expect(run(source), source).toEqual({ ok: true, value: true }); + } + }); + + it('takes the row\'s outcome arm: run-may-fail where none is declared, and run-fails kept when bare names are unproven', () => { + const undeclared: ExprSchemaHint = { ...CONDITION, faultOutcome: undefined }; + expect(codes('timestamp(record.borrow_date) < now()', undeclared)).toEqual(['date-text-call-run-may-fail']); + expect(codes('timestamp(borrow_date) < now()', undeclared)).toEqual(['date-text-call-run-may-fail']); + // A node that can bind a name no reader sees moves a bare name's arm, never a root read's. + const unproven: ExprSchemaHint = { ...CONDITION, bareNamesUnproven: true }; + expect(codes('timestamp(borrow_date) < now()', unproven)).toEqual(['date-text-call-run-may-fail']); + expect(codes('timestamp(record.borrow_date) < now()', unproven)).toEqual(['date-text-call-run-fails']); + }); + + it('a flow variable shadowing the bare name leaves the root read the field\'s', () => { + const shadowed: ExprSchemaHint = { ...CONDITION, flowVariables: ['borrow_date'] }; + expect(codes('timestamp(borrow_date) < now()', shadowed)).toEqual([]); + expect(codes('timestamp(record.borrow_date) < now()', shadowed)).toEqual(['date-text-call-run-fails']); + }); + + it('refuses the other date-text verdicts over a root read too: a call and arithmetic on the text', () => { + expect(codes("isoDate(record.picked_up_at) == '2026-11-16'")).toEqual(['date-text-call-run-fails']); + const arithmetic = errorsOf("record.due_date - record.borrow_date > duration('24h')"); + expect(arithmetic.map((e) => ({ code: e.code, params: e.params }))).toEqual([{ + code: 'date-text-arithmetic-run-fails', + params: { operands: 'DateText - DateText', reference: 'record.borrow_date' }, + }]); + expect(run("record.due_date - record.borrow_date > duration('24h')")).toMatchObject({ ok: false }); + }); + + it('CONTROL: what the Timestamp typing of the roots faults on, and an input read, are not this family\'s', () => { + // `record.due_date + 1` is the date-arithmetic family's shape, not the date-text check's. + expect(codes('record.due_date + 1 > 5').filter((c) => c.startsWith('date-text-'))).toEqual([]); + // A flow does not bind `input` to the row the types describe. + expect(codes('timestamp(input.borrow_date) < now()').filter((c) => c.startsWith('date-text-'))).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 726254e0e4c..9a7f20aad2b 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -32,6 +32,8 @@ import { FIELD_RULE_JUDGED_ROOTS, } from './validate-expressions.js'; import type { ExprIssue } from './validate-expressions.js'; +// [#34662] The rule id a flow condition's finding is reported under (bottom of this file). +import { EXPRESSION_INVALID, runAuthoringRules } from './authoring-rules.js'; // [#8405] Cross-site pin only — see the describe block at the bottom of this // file. Not otherwise used here; validate-semantic-roles.test.ts owns the // rest of this rule's coverage. @@ -6819,3 +6821,71 @@ describe('validateStackExpressions — flow value envelopes take the date-text f } }); }); + +// [#34662] A flow CONDITION (start, edge, `decision` branch) reads the run's +// row through `record.` / `previous.` as well as through the +// flattened bare name, and the date-text family judged only the bare name: +// `timestamp(record.borrow_date) < now()` got zero findings and fails every +// run on the `YYYY-MM-DD` text, while `timestamp(borrow_date) < now()` was +// refused. The root read now takes the same finding, under the same rule. +describe('validateStackExpressions — a flow condition\'s record. / previous. read takes the date-text family (#34662)', () => { + const LOAN = { + name: 'library_loan', + fields: { borrow_date: { type: 'date' }, picked_up_at: { type: 'datetime' } }, + }; + type Site = 'start' | 'edge' | 'decision'; + const stackWith = (site: Site, condition: string) => ({ + objects: [LOAN], + flows: [{ + name: 'loan_overdue', + nodes: [ + { + id: 'start', type: 'start', + config: { objectName: 'library_loan', triggerType: 'record-after-update', ...(site === 'start' ? { condition } : {}) }, + }, + ...(site === 'decision' + ? [{ id: 'gate', type: 'decision', config: { conditions: [{ label: 'Overdue', expression: condition }] } }] + : []), + { id: 'end', type: 'end' }, + ], + edges: site === 'decision' + ? [{ id: 'e1', source: 'start', target: 'gate' }, { id: 'e2', source: 'gate', target: 'end' }] + : [{ id: 'e1', source: 'start', target: 'end', ...(site === 'edge' ? { condition } : {}) }], + }], + }); + const dateTextOf = (issues: ExprIssue[]) => issues.filter((i) => /is a date field, and the runtime holds/.test(i.message)); + + it.each(['start', 'edge', 'decision'] as const)( + 'refuses timestamp() over a date field through record. and previous. in a %s condition, as its bare name is', + (site) => { + const bare = dateTextOf(validateStackExpressions(stackWith(site, 'timestamp(borrow_date) < now()'))); + expect(bare.map((i) => i.severity)).toEqual(['error']); + for (const root of ['record', 'previous']) { + const source = `timestamp(${root}.borrow_date) < now()`; + const issues = validateStackExpressions(stackWith(site, source)); + expect(issues.map((i) => [i.severity, i.path ?? i.where]), source).toEqual([['error', bare[0].path ?? bare[0].where]]); + expect(issues[0].message).toContain(`\`timestamp(${root}.borrow_date)\` — \`${root}.borrow_date\` is a date field`); + expect(issues[0].message).toContain(`\`isoDate(addDays(${root}.borrow_date, N))\``); + } + }, + ); + + it('reports it under the expression rule id, as the bare name is', () => { + for (const source of ['timestamp(borrow_date) < now()', 'timestamp(record.borrow_date) < now()', 'timestamp(previous.borrow_date) < now()']) { + const stack = stackWith('start', source); + // The minimal fixture draws other rules' findings (region shape, sharing); this one's is the date text's. + const findings = runAuthoringRules('build', { normalized: stack, parsed: stack } as never) + .filter((f) => /is a date field, and the runtime holds/.test(f.message)); + expect(findings.map((f) => [f.rule, f.severity]), source).toEqual([[EXPRESSION_INVALID, 'error']]); + } + }); + + it('CONTROL: a datetime field under timestamp() stays clean through either root', () => { + for (const site of ['start', 'edge', 'decision'] as const) { + for (const root of ['record', 'previous']) { + const source = `timestamp(${root}.picked_up_at) < now()`; + expect(validateStackExpressions(stackWith(site, source)), `${site}: ${source}`).toEqual([]); + } + } + }); +}); From d16b3b53106635facbae6439e44065c169c60f36 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:38:26 +0000 Subject: [PATCH 3/7] wip: publish-door pin for the flow condition record-root date-text verdict Claude-Session: https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C Co-authored-by: Claude --- ...ta-flow-condition-record-date-text.test.ts | 152 ++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts diff --git a/packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts b/packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts new file mode 100644 index 00000000000..1e4fafb429b --- /dev/null +++ b/packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts @@ -0,0 +1,152 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34662] The flow publish door refuses `timestamp()` over a date field read + * through `record.` / `previous.` in a flow condition, as it refuses the bare + * name. + * + * The business case: an administrator publishes, in Studio or through an MCP + * agent, a record-triggered flow on a library loan that runs only once the + * loan's borrow day is past (`timestamp(record.borrow_date) < now()`). A + * `date` field reaches the run as its `YYYY-MM-DD` text, which `timestamp()` + * does not parse, so the condition faults and the flow fails on every run. + * The door refused the bare spelling (`timestamp(borrow_date) < now()`) and + * published the `record.` one; both are refused now, in the same finding. + * A `datetime` field holds an ISO-8601 instant, which `timestamp()` parses: it + * still publishes. + * + * ## The rig + * + * The rig of `meta-flow-hook-injected-column-null-guard.test.ts`: + * better-sqlite3 `:memory:` behind the real `ObjectQL` engine, the real + * `sys_metadata*` objects and a real `ObjectStackProtocolImplementation`. The + * loan object comes from a code package registered through `registerApp`; + * each flow is saved as a draft in a writable package and published through + * `publishMetaItem`, the door Studio, REST and MCP authors use. + */ + +import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; +// The protocol's package door reaches `import('@objectstack/metadata')`; pay +// that load during collection, never inside a clocked case +// (check:test-source-alias). +import '@objectstack/metadata'; + +let home: string; +let priorHome: string | undefined; +beforeAll(() => { + priorHome = process.env.OS_HOME; + home = mkdtempSync(join(tmpdir(), 'os-flow-record-date-text-')); + process.env.OS_HOME = home; +}); +afterAll(() => { + if (priorHome === undefined) delete process.env.OS_HOME; + else process.env.OS_HOME = priorHome; + rmSync(home, { recursive: true, force: true }); +}); + +const BASE = 'com.acme.library'; +const PAIR = 'com.acme.library.custom'; +const TARGET = 'library_loan'; + +const loan = { + name: TARGET, + label: 'Loan', + sharingModel: 'private', + fields: { + title: { name: 'title', label: 'Title', type: 'text' }, + borrow_date: { name: 'borrow_date', label: 'Borrowed', type: 'date' }, + picked_up_at: { name: 'picked_up_at', label: 'Picked up', type: 'datetime' }, + }, +}; + +const liveEngines: ObjectQL[] = []; +afterEach(async () => { + while (liveEngines.length) { + try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +async function boot() { + const engine = new ObjectQL(); + liveEngines.push(engine); + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }), true); + await engine.init(); + engine.registry.registerObject(SysMetadata as any, 'objectstack-test'); + engine.registry.registerObject(SysMetadataHistoryObject as any, 'objectstack-test'); + engine.registry.registerObject(SysMetadataAuditObject as any, 'objectstack-test'); + (engine.registry as unknown as { logLevel: string }).logLevel = 'silent'; + engine.registerApp({ id: BASE, name: 'library', version: '1.0.0', type: 'app', namespace: 'library', objects: [loan] }); + await engine.syncSchemas(); + const protocol = new ObjectStackProtocolImplementation(engine as any, () => new Map()) as any; + await protocol.installPackage({ + manifest: { id: PAIR, name: 'library-custom', version: '0.1.0', type: 'app', namespace: 'library_custom', dependencies: { [BASE]: '^1' } }, + }); + /** Save as a draft in the writable package, then publish; the refusal, or `undefined` when it published. */ + const publish = async (item: Record) => { + await protocol.saveMetaItem({ type: 'flow', name: item.name, item, mode: 'draft', packageId: PAIR }); + return protocol.publishMetaItem({ type: 'flow', name: item.name, packageId: PAIR }).then(() => undefined, (e: any) => e); + }; + const state = async (name: unknown) => + ((await engine.find('sys_metadata', { where: { type: 'flow', name }, context: { isSystem: true } })) ?? []) + .map((r: any) => r.state); + return { publish, state }; +} + +/** A record-triggered flow on the loan whose start node carries the condition. */ +const flowOn = (name: string, condition: string) => ({ + name, + label: 'Overdue loan', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: TARGET, triggerType: 'record-after-update', condition } }, + { id: 'done', type: 'end', label: 'Done' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'done' }], +}); + +/** The door's date-text findings on a refused publish. */ +const dateTextIssues = (err: any) => + (err?.issues ?? []).filter((i: any) => i.rule === 'expression-invalid' && /is a date field, and the runtime holds/.test(i.message)); + +describe('[#34662] the flow publish door refuses timestamp() over a date field read through record. / previous.', () => { + it('⭐ LIT — refuses the bare name, `record.` and `previous.` alike, with INVALID_METADATA / 422, leaving the draft', async () => { + const rig = await boot(); + for (const [name, read] of [ + ['loan_overdue_bare', 'borrow_date'], + ['loan_overdue_record', 'record.borrow_date'], + ['loan_overdue_previous', 'previous.borrow_date'], + ] as const) { + const err: any = await rig.publish(flowOn(name, `timestamp(${read}) < now()`)); + expect(err, `${read}: the publish was admitted`).toBeInstanceOf(Error); + expect({ code: err.code, status: err.status }, read).toEqual({ code: 'INVALID_METADATA', status: 422 }); + const issues = dateTextIssues(err); + expect(issues, `${read}: ${JSON.stringify(err.issues)}`).toHaveLength(1); + expect(issues[0].message).toContain(`\`timestamp(${read})\` — \`${read}\` is a date field`); + expect(issues[0].message).toContain(`\`isoDate(addDays(${read}, N))\``); + expect(await rig.state(name), read).toEqual(['draft']); + } + }, 60_000); + + it('⭐ CONTROL — a datetime field under timestamp(), through either root, publishes', async () => { + const rig = await boot(); + for (const [name, read] of [ + ['loan_picked_up_record', 'record.picked_up_at'], + ['loan_picked_up_previous', 'previous.picked_up_at'], + ] as const) { + const err = await rig.publish(flowOn(name, `timestamp(${read}) < now()`)); + expect(err?.issues ?? err, `${read}: the door refused`).toBeUndefined(); + expect(await rig.state(name), read).toEqual(['active']); + } + }, 60_000); +}); From b55562c2dcc566b767075944dc0fdf745ec3f48b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:43:57 +0000 Subject: [PATCH 4/7] wip: registerFlow advisory parity pin Claude-Session: https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C Co-authored-by: Claude --- .../src/flow-registration-schema-e2e.test.ts | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/packages/services/service-automation/src/flow-registration-schema-e2e.test.ts b/packages/services/service-automation/src/flow-registration-schema-e2e.test.ts index 374490961ee..dceb87308b5 100644 --- a/packages/services/service-automation/src/flow-registration-schema-e2e.test.ts +++ b/packages/services/service-automation/src/flow-registration-schema-e2e.test.ts @@ -109,3 +109,74 @@ describe('AutomationServicePlugin — object-schema resolver wired end-to-end (# expect(logged).not.toMatch(/type mismatch|did you mean|unknown field/i); }); }); + +// [#34662] `registerFlow` judges a flow CONDITION's schema-aware findings as an +// advisory it logs and never throws (#1928: registration stays strictly +// additive; the publish door is what refuses). The record-root date-text +// verdict reaches that advisory exactly as the bare name's does, because it is +// the same shared validator. +describe('registerFlow — a flow condition\'s record. / previous. date-text read is advised as its bare name is (#34662)', () => { + let kernel: LiteKernel; + let engine: AutomationEngine; + let stdout: string[]; + let stdoutSpy: ReturnType; + const loanFlow = (name: string, condition: string) => ({ + name, + label: 'Overdue loan', + type: 'record_change', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'library_loan', triggerType: 'record-after-update', condition } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], + }); + + beforeEach(async () => { + stdout = []; + stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown) => { + stdout.push(String(chunk)); + return true; + }) as never); + kernel = new LiteKernel(); + kernel.use({ + name: 'fake-objectql', + version: '1.0.0', + async init(ctx: PluginContext) { + (ctx as unknown as { registerService(name: string, svc: unknown): void }).registerService('objectql', { + registry: { + getObject: (name: string) => + name === 'library_loan' + ? { name, fields: { borrow_date: { type: 'date' }, picked_up_at: { type: 'datetime' } } } + : undefined, + }, + }); + }, + }); + kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + engine = kernel.getService('automation') as AutomationEngine; + }); + + afterEach(async () => { + stdoutSpy.mockRestore(); + await kernel.shutdown(); + }); + + it('logs the date-text advisory for record. and previous. as for the bare name, and registers', () => { + for (const read of ['borrow_date', 'record.borrow_date', 'previous.borrow_date']) { + stdout.length = 0; + const name = `loan_${read.replace('.', '_')}`; + expect(() => engine.registerFlow(name, loanFlow(name, `timestamp(${read}) < now()`)), read).not.toThrow(); + expect(stdout.join(''), read).toContain(`\`timestamp(${read})\` — \`${read}\` is a date field`); + } + }); + + it('CONTROL: a datetime field under timestamp() is not advised', () => { + for (const read of ['record.picked_up_at', 'previous.picked_up_at']) { + stdout.length = 0; + const name = `loan_${read.replace('.', '_')}`; + expect(() => engine.registerFlow(name, loanFlow(name, `timestamp(${read}) < now()`)), read).not.toThrow(); + expect(stdout.join(''), read).not.toMatch(/is a date field/); + } + }); +}); From 94a67af8098b3969d5d8b6da58f2146e75e249c1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:45:33 +0000 Subject: [PATCH 5/7] chore: changeset for the flow condition record-root date-text verdict Claude-Session: https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C Co-authored-by: Claude --- .changeset/34662-flow-record-date-text.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/34662-flow-record-date-text.md diff --git a/.changeset/34662-flow-record-date-text.md b/.changeset/34662-flow-record-date-text.md new file mode 100644 index 00000000000..68ebb2fc098 --- /dev/null +++ b/.changeset/34662-flow-record-date-text.md @@ -0,0 +1,14 @@ +--- +'@objectstack/formula': patch +--- + +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 + +Clause-②: no +Metadata-protocol: none + +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` (and 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. + +A `record.FIELD` / `previous.FIELD` read in a flow condition now gets the same date-text checks as its bare name, with the same code and outcome arm (`date-text-call-run-fails` on a record-triggered flow, `-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`). The shapes stay what they were: `timestamp()` over a `datetime` field still passes, and a shape the Timestamp typing already faults on (`record.due_date + 1`) is not this check's. + +`registerFlow` logs the finding as an advisory, as it does for the bare name, and still registers the flow. A stored flow that carries such a condition is refused at its next publish. To fix it, write `date(record.FIELD) < now()`, or compare whole days with `daysBetween` / `addDays`. From 60d4e1c6c7fa1ef7813c0cf1ff12b3bca90d3a20 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:39:11 +0000 Subject: [PATCH 6/7] chore(changeset): declare the flow condition record-root date-text verdict a narrowing Claude-Session: https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C Co-authored-by: Claude --- .changeset/34662-flow-record-date-text.md | 27 +++++++++++++++++------ 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/.changeset/34662-flow-record-date-text.md b/.changeset/34662-flow-record-date-text.md index 68ebb2fc098..4b5f38fcb49 100644 --- a/.changeset/34662-flow-record-date-text.md +++ b/.changeset/34662-flow-record-date-text.md @@ -1,14 +1,27 @@ --- -'@objectstack/formula': patch +'@objectstack/formula': minor --- -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 +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 -Clause-②: no -Metadata-protocol: none +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 -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` (and 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. + -A `record.FIELD` / `previous.FIELD` read in a flow condition now gets the same date-text checks as its bare name, with the same code and outcome arm (`date-text-call-run-fails` on a record-triggered flow, `-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`). The shapes stay what they were: `timestamp()` over a `datetime` field still passes, and a shape the Timestamp typing already faults on (`record.due_date + 1`) is not this check's. +**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. -`registerFlow` logs the finding as an advisory, as it does for the bare name, and still registers the flow. A stored flow that carries such a condition is refused at its next publish. To fix it, write `date(record.FIELD) < now()`, or compare whole days with `daysBetween` / `addDays`. +- **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`). +- **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. +- **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. + +## FROM → TO + +| FROM | TO | +|:---|:---| +| `timestamp(record.borrow_date) < now()` | `date(record.borrow_date) < now()` | +| `timestamp(previous.borrow_date) < now()` | `date(previous.borrow_date) < now()` | +| `isoDate(record.picked_up_at) == '2026-11-16'` | `isoDate(date(record.picked_up_at)) == '2026-11-16'` | + +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)`. From 1ce9b683e91b5d1a6c58c4f012f0a9f94107bf99 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:51:16 +0000 Subject: [PATCH 7/7] fix(formula): the record-root date-text pass stands down only on date arithmetic against a number Claude-Session: https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C Co-authored-by: Claude --- packages/formula/src/cel-engine.ts | 38 +++++++++++++------ .../src/validate-date-text-arithmetic.test.ts | 20 ++++++++++ packages/formula/src/validate.ts | 22 ++++++----- .../lint/src/validate-expressions.test.ts | 15 ++++++++ 4 files changed, 75 insertions(+), 20 deletions(-) diff --git a/packages/formula/src/cel-engine.ts b/packages/formula/src/cel-engine.ts index 85b191d2669..d0a7e27af46 100644 --- a/packages/formula/src/cel-engine.ts +++ b/packages/formula/src/cel-engine.ts @@ -1205,6 +1205,14 @@ function withoutNames( return out; } +/** + * [#29959, #34662] A `record.` / `previous.` read spelled member-wise — the gate + * of every flattened record-root pass ({@link firstTypeMismatch}'s and + * `validate.ts`'s date-text one), so the two can never disagree on whether a + * source reads a root. + */ +export const RECORD_ROOT_READ_RE = /(?` / `previous.` read of a field of * `celType` in a flattened condition, as written — what @@ -1358,9 +1366,10 @@ export function firstTypeMismatch( // [#29959] A flattened condition reads the same field as `record.` // (and `previous.`), which the bare typing above leaves `dyn`. A // second pass types those roots too, for the text/boolean mismatch only: - // the same verdict the bare name gets. The date verdicts stay the bare - // name's alone, as before. - if (scope !== 'flattened' || !/(?` / `previous.` reads (every bare name `dyn`) faults an - * operator overload — `record.due_date + 1`. Such a shape is the Timestamp - * typing's family (`date-arithmetic`), never the date-text check's, so the - * record-root date-text pass stands down on it, as a flow value envelope's - * does. `false` when the source does not parse. + * [#34662] Whether the FIRST operator fault the Timestamp typing of a flattened + * condition's `record.` / `previous.` reads meets (every bare + * name `dyn`) is date/duration arithmetic against a number ({@link isDateArith}) + * — `record.due_date + 1`. That shape is the `date-arithmetic` family's, and it + * is exactly where the bare name's own order stops: {@link firstTypeMismatch} + * answers `date-arith` there and the date-text check is never asked. Any other + * Timestamp-typing fault — `record.end_date - record.start_date > 3` (a Duration + * ordered against a number), `record.d >= "2026-01-01"` (the text ordering the + * runtime answers) — leaves the bare name's mismatch check at null and the + * date-text check asked, so it does not stand the record-root pass down + * either. `false` when the source does not parse. */ -export function recordRootReadsFaultTimestampTyping( +export function recordRootReadsFaultDateArith( source: string, recordRootTypes: Readonly>, ): boolean { @@ -1544,7 +1558,9 @@ export function recordRootReadsFaultTimestampTyping( .parse(rewriteNullableTernary(rewriteIndexedHas(source))).check?.() as | { valid?: boolean; error?: { message?: string } } | undefined; - return result?.valid === false && UNSOUND_OVERLOAD_RE.test(result.error?.message ?? ''); + if (result?.valid !== false) return false; + const m = UNSOUND_OVERLOAD_RE.exec(result.error?.message ?? ''); + return m !== null && isDateArith(m); } catch { return false; } diff --git a/packages/formula/src/validate-date-text-arithmetic.test.ts b/packages/formula/src/validate-date-text-arithmetic.test.ts index 10fa42787a4..5267538156d 100644 --- a/packages/formula/src/validate-date-text-arithmetic.test.ts +++ b/packages/formula/src/validate-date-text-arithmetic.test.ts @@ -561,6 +561,26 @@ describe('a flow condition\'s record. / previous. read takes the d expect(run("record.due_date - record.borrow_date > duration('24h')")).toMatchObject({ ok: false }); }); + it('stands down only on date arithmetic against a number: another Timestamp-typing fault leaves the root read judged, as the bare name is', () => { + // A Duration ordered against a number faults the Timestamp typing, but it is no date-arith shape. + expect(codes('due_date - borrow_date > 3')).toEqual(['date-text-arithmetic-run-fails']); + const span = errorsOf('record.due_date - record.borrow_date > 3'); + expect(span.map((e) => ({ code: e.code, params: e.params }))).toEqual([{ + code: 'date-text-arithmetic-run-fails', + params: { operands: 'DateText - DateText', reference: 'record.borrow_date' }, + }]); + // An ordering of the date text against a text literal (which the runtime answers) does not mask a later call, in either order. + for (const [bare, root] of [ + ['due_date >= "2026-01-01" && timestamp(borrow_date) < now()', 'record.due_date >= "2026-01-01" && timestamp(record.borrow_date) < now()'], + ['timestamp(borrow_date) < now() && due_date >= "2026-01-01"', 'timestamp(record.borrow_date) < now() && record.due_date >= "2026-01-01"'], + ]) { + expect(codes(bare), bare).toEqual(['date-text-call-run-fails']); + const errors = errorsOf(root); + expect(errors.map((e) => e.code), root).toEqual(['date-text-call-run-fails']); + expect(errors[0].params, root).toMatchObject({ call: 'timestamp(record.borrow_date)', reference: 'record.borrow_date' }); + } + }); + it('CONTROL: what the Timestamp typing of the roots faults on, and an input read, are not this family\'s', () => { // `record.due_date + 1` is the date-arithmetic family's shape, not the date-text check's. expect(codes('record.due_date + 1 > 5').filter((c) => c.startsWith('date-text-'))).toEqual([]); diff --git a/packages/formula/src/validate.ts b/packages/formula/src/validate.ts index b6b759921b8..88a0f8a21af 100644 --- a/packages/formula/src/validate.ts +++ b/packages/formula/src/validate.ts @@ -24,7 +24,8 @@ import { firstDateTextVerdict, firstTypeMismatch, inferCelType, - recordRootReadsFaultTimestampTyping, + recordRootReadsFaultDateArith, + RECORD_ROOT_READ_RE, parseCelToAst, parseCelToAstWithReason, type CelAstNode, @@ -839,9 +840,6 @@ function dateTextCallIssue( /** [#34451] The date-text verdict family: `date-text-call` / `date-text-arithmetic` and their outcome arms. */ const DATE_TEXT_FAMILY_RE = /^date-text-(?:call|arithmetic)(?:-|$)/; -/** A `record.` / `previous.` read spelled member-wise — what the record-root pass can type. */ -const RECORD_ROOT_READ_RE = /(? 3` (a Duration ordered + * against a number) and an expression that orders a date field against a text + * literal before it calls `timestamp()` are judged, as their bare spellings + * are. Only `date-text-call*` / `date-text-arithmetic*` are kept. The outcome arm is * the row's: a root read keeps the declared outcome whatever binds the bare * names (#30025), so `bareNamesUnproven` is not asked. */ @@ -869,7 +873,7 @@ function recordRootDateTextIssue( faultOutcome: ExprSchemaHint['faultOutcome'], ): { issue: ExprValidationError; severity: 'error' | 'warning' } | null { if (!RECORD_ROOT_READ_RE.test(source) || !Object.values(celFieldTypes).includes('timestamp')) return null; - if (recordRootReadsFaultTimestampTyping(source, celFieldTypes)) return null; + if (recordRootReadsFaultDateArith(source, celFieldTypes)) return null; const dateOnly = new Set(Object.keys(celFieldTypes).filter((name) => fieldTypes[name] === 'date')); const found = dateTextIssue(source, {}, 'flattened', role, dateArm('flattened', faultOutcome, false), dateOnly, celFieldTypes); return found && DATE_TEXT_FAMILY_RE.test(found.issue.code) ? found : null; diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 9a7f20aad2b..e17240e9c36 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -6880,6 +6880,21 @@ describe('validateStackExpressions — a flow condition\'s record. / previous. r } }); + it('takes the run-may-fail sentence where the run is not proven to hold the row, as the bare name does', () => { + // No trigger: the start names the object but no entrance binds its row, so no outcome is declared. + const untriggered = (condition: string) => { + const stack = stackWith('start', condition); + const start = stack.flows[0].nodes[0] as { config: Record }; + delete start.config.triggerType; + return stack; + }; + for (const read of ['borrow_date', 'record.borrow_date', 'previous.borrow_date']) { + const issues = dateTextOf(validateStackExpressions(untriggered(`timestamp(${read}) < now()`))); + expect(issues.map((i) => i.severity), read).toEqual(['error']); + expect(issues[0].message, read).toContain(`this faults wherever \`${read}\` holds that text when the condition runs`); + } + }); + it('CONTROL: a datetime field under timestamp() stays clean through either root', () => { for (const site of ['start', 'edge', 'decision'] as const) { for (const root of ['record', 'previous']) {