diff --git a/.changeset/34946-flow-record-date-arithmetic.md b/.changeset/34946-flow-record-date-arithmetic.md new file mode 100644 index 00000000000..c6ba789098f --- /dev/null +++ b/.changeset/34946-flow-record-date-arithmetic.md @@ -0,0 +1,26 @@ +--- +'@objectstack/formula': minor +'@objectstack/spec': minor +--- + +fix(formula)!: a flow condition that does date arithmetic on `record.FIELD` or `previous.FIELD` is now refused, as the bare field name already was + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** accept-set narrowing. 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-arithmetic check judged only the bare name: `due_date + 1 > 5` over a `date` field was refused, but `record.due_date + 1 > 5` 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 and the evaluator cannot add a number to it. + +- **The verdict.** A `record.FIELD` / `previous.FIELD` read of a `date` or `datetime` field in arithmetic against a number now gets the verdict its bare name gets, with the same code and outcome arm (`date-arithmetic-run-fails` on a record-triggered flow or a sweep of the typed object, `date-arithmetic-run-may-fail` elsewhere). A root read keeps the row's arm where bare names are unproven or a flow variable shadows the bare name. The message names the read as written and prescribes `daysBetween(a, b)` or `addDays(d, n)`. +- **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 its run-time behaviour until it is next published. +- **Not refused.** An ordering of the field (`record.due_date < today()`), `daysBetween` / `addDays` over it, and the date-text shapes, which keep their own verdicts. Formula fields and validation rules read `record.FIELD` already and were refused before. The run-time evaluator is unchanged. + +## FROM → TO + +| FROM | TO | +|:---|:---| +| `record.due_date + 1 > 5` | `daysBetween(record.due_date, today()) > 5` (days past due) or `addDays(record.due_date, 1) < today()` (a shifted date) | +| `previous.due_date - 7 < today()` | `addDays(previous.due_date, -7) < today()` | + +One-line fix: in a flow condition, never add or subtract a number on a date field read through `record` or `previous`; use `daysBetween(a, b)` for a span and `addDays(d, n)` to shift a date. diff --git a/packages/formula/src/cel-engine.ts b/packages/formula/src/cel-engine.ts index da32d0f394e..8eb099d83f3 100644 --- a/packages/formula/src/cel-engine.ts +++ b/packages/formula/src/cel-engine.ts @@ -1339,7 +1339,10 @@ export function firstTypeMismatch( operands: string; celType: FieldCelType; field: string | null; - /** [#29959] Set when a flattened condition's mismatch is a `record.` / `previous.` read. */ + /** + * [#29959, #34946] Set when a flattened condition's mismatch (`type-mismatch` + * or `date-arith`) is a `record.` / `previous.` read. + */ root?: 'record' | 'previous'; category: 'date-arith' | 'type-mismatch'; } | null { @@ -1419,12 +1422,24 @@ 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-arith` verdict stays the - // bare name's alone, as before; the date-text family reaches the roots - // through `validate.ts`'s record-root pass (#34662). + // second pass types those roots too, for the verdicts the bare name gets + // here: the text/boolean mismatch, and (#34946) date/duration arithmetic + // against a number — `record.due_date + 1` faults on the field's text on + // every run exactly as `due_date + 1` does. Either names the read as + // written (`root`). The date-text family reaches the roots through + // `validate.ts`'s record-root pass (#34662), which stands down on the + // date-arith shape answered here ({@link recordRootReadsFaultDateArith}). if (scope !== 'flattened' || !RECORD_ROOT_READ_RE.test(source)) return null; const rootTyped = unsoundOverload(buildTypedEnv(bareTypes, 'flattened', 'timestamp', fieldCelTypes)); + if (rootTyped && isDateArith(rootTyped)) { + const read = offendingRecordRead(source, fieldCelTypes, 'timestamp'); + return { + operator: rootTyped[2], operands: `${rootTyped[1]} ${rootTyped[2]} ${rootTyped[3]}`, + celType: 'timestamp', category: 'date-arith', + field: read?.field ?? null, + ...(read ? { root: read.root } : {}), + }; + } const r = rootTyped && textOrBool(rootTyped) ? confirmAgainstDateText(rootTyped, fieldCelTypes) : null; const celType = r ? textOrBool(r) : null; if (!r || !celType) return null; @@ -1595,7 +1610,8 @@ export function firstDateTextVerdict( * 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 + * answers `date-arith` there (for the root read too, #34946) 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 diff --git a/packages/formula/src/validate.test.ts b/packages/formula/src/validate.test.ts index 114780cbefe..cf9b8881765 100644 --- a/packages/formula/src/validate.test.ts +++ b/packages/formula/src/validate.test.ts @@ -1,13 +1,14 @@ import { describe, it, expect } from 'vitest'; import { validateExpression, + type ExprSchemaHint, introspectScope, expectedDialect, inferExpressionType, nearestName, CEL_STDLIB_FUNCTIONS, } from './validate'; -import { buildEnv, firstUndeclaredReference, SCOPE_ROOTS } from './cel-engine'; +import { buildEnv, celEngine, firstUndeclaredReference, SCOPE_ROOTS } from './cel-engine'; describe('validateExpression (ADR-0032)', () => { describe('predicates (CEL)', () => { @@ -1328,3 +1329,85 @@ describe('inferExpressionType — coarse value-type of a formula', () => { expect(inferExpressionType('record')).toBe('unknown'); }); }); + +// [#34946] A flow condition reads the run's row bare AND through `record.` / +// `previous.` (#29959), and the date-arithmetic verdict (#3306) judged only the +// bare name: `due_date + 1 > 5` was refused while `record.due_date + 1 > 5` +// passed with no finding, and both fault on the `YYYY-MM-DD` text on every run. +// The root read now takes the bare name's verdict, code and arm, naming the +// read as written. +describe('a flow condition\'s record. / previous. read takes the date-arithmetic verdict as its bare name does (#34946)', () => { + /** 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 = { scope: 'flattened', 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); + const verdicts = (source: string, hint: ExprSchemaHint = CONDITION) => + errorsOf(source, hint).map((e) => ({ code: e.code, params: e.params })); + /** 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 date arithmetic on a date field through record. and previous. under the bare name\'s code, naming the read', () => { + expect(verdicts('due_date + 1 > 5')).toEqual([{ + code: 'date-arithmetic-run-fails', + params: { operands: 'google.protobuf.Timestamp + int', reference: 'due_date' }, + }]); + expect(run('due_date + 1 > 5')).toMatchObject({ ok: false }); + for (const root of ['record', 'previous'] as const) { + const source = `${root}.due_date + 1 > 5`; + const errors = errorsOf(source); + expect(errors.map((e) => ({ code: e.code, params: e.params })), source).toEqual([{ + code: 'date-arithmetic-run-fails', + params: { operands: 'google.protobuf.Timestamp + int', reference: `${root}.due_date` }, + }]); + expect(errors[0].message, source).toContain(`date arithmetic \`google.protobuf.Timestamp + int\` — \`${root}.due_date\` is a date`); + expect(errors[0].message, source).toContain('a flow condition that cannot be evaluated fails the run'); + // The run faults on the date-only text, exactly as the bare spelling does. + expect(run(source), source).toMatchObject({ ok: false }); + } + }); + + it('CONTROL: a datetime field\'s root reads take exactly the bare name\'s verdict', () => { + const [bare] = verdicts('picked_up_at + 1 > 5'); + expect(bare).toEqual({ + code: 'date-arithmetic-run-fails', + params: { operands: 'google.protobuf.Timestamp + int', reference: 'picked_up_at' }, + }); + for (const root of ['record', 'previous'] as const) { + const source = `${root}.picked_up_at + 1 > 5`; + expect(verdicts(source), source).toEqual([{ ...bare, params: { ...bare.params, reference: `${root}.picked_up_at` } }]); + } + }); + + it('takes the row\'s outcome arm: run-may-fail where none is declared, run-fails kept when bare names are unproven or shadowed', () => { + const undeclared: ExprSchemaHint = { ...CONDITION, faultOutcome: undefined }; + expect(codes('due_date + 1 > 5', undeclared)).toEqual(['date-arithmetic-run-may-fail']); + expect(codes('record.due_date + 1 > 5', undeclared)).toEqual(['date-arithmetic-run-may-fail']); + expect(errorsOf('record.due_date + 1 > 5', undeclared)[0].message) + .toContain('this faults wherever `record.due_date` holds the date when the condition runs'); + // 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('due_date + 1 > 5', unproven)).toEqual(['date-arithmetic-run-may-fail']); + expect(codes('record.due_date + 1 > 5', unproven)).toEqual(['date-arithmetic-run-fails']); + // A flow variable holding the bare name is not the field; the root read still is. + const shadowed: ExprSchemaHint = { ...CONDITION, flowVariables: ['due_date'] }; + expect(codes('due_date + 1 > 5', shadowed)).toEqual([]); + expect(codes('previous.due_date + 1 > 5', shadowed)).toEqual(['date-arithmetic-run-fails']); + }); + + it('CONTROL: an ordering against today() and the date-text shapes keep their verdicts, with no second finding', () => { + for (const source of [ + 'record.due_date < today()', 'previous.due_date < today()', 'date(record.due_date) < now()', + // The rewrites the verdict prescribes (the changeset's FROM → TO). + 'daysBetween(record.due_date, today()) > 5', 'addDays(record.due_date, 1) < today()', 'addDays(previous.due_date, -7) < today()', + ]) { + expect(validateExpression('predicate', source, CONDITION), source).toEqual({ ok: true, errors: [], warnings: [] }); + } + expect(codes('timestamp(record.borrow_date) < now()')).toEqual(['date-text-call-run-fails']); + expect(codes('record.due_date - record.borrow_date > 3')).toEqual(['date-text-arithmetic-run-fails']); + expect(codes("record.due_date - record.borrow_date > duration('24h')")).toEqual(['date-text-arithmetic-run-fails']); + // The text/boolean mismatch the record-root pass already reported is unchanged. + expect(codes('record.title > 5')).toEqual(['type-mismatch-run-fails']); + }); +}); diff --git a/packages/formula/src/validate.ts b/packages/formula/src/validate.ts index b0692e1423e..aeedf005910 100644 --- a/packages/formula/src/validate.ts +++ b/packages/formula/src/validate.ts @@ -519,7 +519,8 @@ const DATE_FAIL_CLOSED_CLAUSE = * (`date − date + 1`, `today() + 30`) — always faults at runtime and never * recovers, so it blocks the build. A formula reads that fault as null; a * flattened (flow) condition's fault fails the run, under the - * `date-arithmetic-run-fails` / `-run-may-fail` codes (#30016), a + * `date-arithmetic-run-fails` / `-run-may-fail` codes (#30016) — its + * `record.` / `previous.` read as its bare name (#34946) — a * fail-closed site's refuses the write, under `date-arithmetic-fail-closed` * (#30250), and an advisory rule's skips the rule, under * `date-arithmetic-fail-open` (#30494, {@link dateArm}). @@ -596,7 +597,10 @@ function typeSoundnessIssue( const use = `Use \`daysBetween(a, b)\` for the span in whole days, and \`daysFromNow(n)\` / ` + `\`addDays(d, n)\` / \`addMonths(d, n)\` to shift a date.`; - const arm = dateArm(scope, faultOutcome, bareNamesUnproven); + // [#34946] A `record.` / `previous.` read keeps the row's + // outcome whatever binds the bare names (#30025), as its type mismatch and + // its date-text verdicts do ({@link recordRootDateTextIssue}). + const arm = dateArm(scope, faultOutcome, mismatch.root !== undefined ? false : bareNamesUnproven); return { severity: 'error', issue: arm diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 7909672869b..e8370a926dd 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -6966,6 +6966,90 @@ describe('validateStackExpressions — a flow condition\'s record. / previous. r }); }); +// [#34946] A flow CONDITION reads the run's row through `record.` / +// `previous.` as well as through the flattened bare name, and the +// date-arithmetic verdict judged only the bare name: `record.due_date + 1 > 5` +// got zero findings and fails every run on the `YYYY-MM-DD` text, while +// `due_date + 1 > 5` was refused. The root read now takes the same finding, +// at the same path and severity, under the same rule. +describe('validateStackExpressions — a flow condition\'s record. / previous. read takes the date-arithmetic verdict (#34946)', () => { + const LOAN = { + name: 'library_loan', + fields: { due_date: { type: 'date', required: true }, picked_up_at: { type: 'datetime', required: true } }, + }; + type Site = 'start' | 'edge' | 'decision'; + const stackWith = (site: Site, condition: string) => ({ + objects: [LOAN], + flows: [{ + name: 'loan_due', + 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: 'Due', 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 at = (issues: ExprIssue[]) => issues.map((i) => [i.severity, i.path ?? i.where]); + + it.each(['start', 'edge', 'decision'] as const)( + 'refuses date arithmetic on a date field through record. and previous. in a %s condition, as its bare name is', + (site) => { + const bare = validateStackExpressions(stackWith(site, 'due_date + 1 > 5')); + expect(at(bare)).toHaveLength(1); + expect(bare[0].severity).toBe('error'); + expect(bare[0].message.startsWith('date arithmetic `google.protobuf.Timestamp + int` — `due_date` is a date')).toBe(true); + for (const root of ['record', 'previous']) { + const source = `${root}.due_date + 1 > 5`; + const issues = validateStackExpressions(stackWith(site, source)); + expect(at(issues), source).toEqual(at(bare)); + expect(issues[0].message, source).toBe(bare[0].message.replace('`due_date`', `\`${root}.due_date\``)); + } + }, + ); + + it('reports it under the expression rule id, as the bare name is', () => { + for (const source of ['due_date + 1 > 5', 'record.due_date + 1 > 5', 'previous.due_date + 1 > 5']) { + const stack = stackWith('start', source); + // The minimal fixture draws other rules' findings (region shape, sharing); this one's is the date arithmetic's. + const findings = runAuthoringRules('build', { normalized: stack, parsed: stack } as never) + .filter((f) => /^date arithmetic/.test(f.message)); + expect(findings.map((f) => [f.rule, f.severity]), source).toEqual([[EXPRESSION_INVALID, 'error']]); + } + }); + + it('CONTROL: a datetime field\'s root reads take exactly the bare name\'s finding', () => { + for (const site of ['start', 'edge', 'decision'] as const) { + const bare = validateStackExpressions(stackWith(site, 'picked_up_at + 1 > 5')); + for (const root of ['record', 'previous']) { + const source = `${root}.picked_up_at + 1 > 5`; + const issues = validateStackExpressions(stackWith(site, source)); + expect(at(issues), `${site}: ${source}`).toEqual(at(bare)); + expect(issues.map((i) => i.message), `${site}: ${source}`) + .toEqual(bare.map((i) => i.message.replace('`picked_up_at`', `\`${root}.picked_up_at\``))); + } + } + }); + + it('CONTROL: an ordering against today() stays clean, and timestamp() over the date keeps its one date-text finding', () => { + for (const site of ['start', 'edge', 'decision'] as const) { + for (const root of ['record', 'previous']) { + expect(validateStackExpressions(stackWith(site, `${root}.due_date < today()`)), `${site}: ${root}`).toEqual([]); + const dateText = validateStackExpressions(stackWith(site, `timestamp(${root}.due_date) < now()`)); + expect(dateText.map((i) => i.severity), `${site}: ${root}`).toEqual(['error']); + expect(dateText[0].message).toContain(`\`timestamp(${root}.due_date)\` — \`${root}.due_date\` is a date field`); + } + } + }); +}); + /** * [ADR-0113 D1, as amended] A `required` field's own `visibleWhen` decides its * requirement on the write, and a predicate the server cannot evaluate counts 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 index 1e4fafb429b..488d58d3937 100644 --- 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 @@ -62,6 +62,8 @@ const loan = { fields: { title: { name: 'title', label: 'Title', type: 'text' }, borrow_date: { name: 'borrow_date', label: 'Borrowed', type: 'date' }, + // [#34946] Required, so the null-guard gate draws no second finding on a comparison of it. + due_date: { name: 'due_date', label: 'Due', type: 'date', required: true }, picked_up_at: { name: 'picked_up_at', label: 'Picked up', type: 'datetime' }, }, }; @@ -150,3 +152,56 @@ describe('[#34662] the flow publish door refuses timestamp() over a date field r } }, 60_000); }); + +/** [#34946] The door's date-arithmetic findings on a refused publish. */ +const dateArithmeticIssues = (err: any) => + (err?.issues ?? []).filter((i: any) => i.rule === 'expression-invalid' && /^date arithmetic/.test(i.message)); + +/** + * [#34946] The flow publish door refuses date arithmetic on a date field read + * through `record.` / `previous.` in a flow condition, as it refuses the bare + * name. The business case: an administrator publishes a record-triggered flow + * on a loan that runs once the loan is a day past due (`record.due_date + 1 > 5` + * written as if the date were a number). The run holds the field as its + * `YYYY-MM-DD` text, the evaluator cannot add a number to it, and the flow + * failed on every run while the door published it; the bare spelling was + * refused. A `datetime` field takes exactly the bare name's verdict too, and an + * ordering against `today()` still publishes. + */ +describe('[#34946] the flow publish door refuses date arithmetic on 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_due_bare', 'due_date'], + ['loan_due_record', 'record.due_date'], + ['loan_due_previous', 'previous.due_date'], + ] as const) { + const err: any = await rig.publish(flowOn(name, `${read} + 1 > 5`)); + 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 = dateArithmeticIssues(err); + expect(issues, `${read}: ${JSON.stringify(err.issues)}`).toHaveLength(1); + expect(issues[0].message).toContain(`date arithmetic \`google.protobuf.Timestamp + int\` — \`${read}\` is a date`); + expect(await rig.state(name), read).toEqual(['draft']); + } + }, 60_000); + + it('⭐ CONTROL — a datetime field\'s root reads take the bare name\'s refusal, and an ordering against today() publishes', async () => { + const rig = await boot(); + for (const [name, read] of [ + ['loan_picked_bare', 'picked_up_at'], + ['loan_picked_record', 'record.picked_up_at'], + ['loan_picked_previous', 'previous.picked_up_at'], + ] as const) { + const err: any = await rig.publish(flowOn(name, `${read} + 1 > 5`)); + expect({ code: err?.code, status: err?.status }, read).toEqual({ code: 'INVALID_METADATA', status: 422 }); + const issues = dateArithmeticIssues(err); + expect(issues, `${read}: ${JSON.stringify(err?.issues)}`).toHaveLength(1); + expect(issues[0].message).toContain(`date arithmetic \`google.protobuf.Timestamp + int\` — \`${read}\` is a date`); + expect(await rig.state(name), read).toEqual(['draft']); + } + const err = await rig.publish(flowOn('loan_due_ordering', 'record.due_date < today()')); + expect(err?.issues ?? err, 'record.due_date < today(): the door refused').toBeUndefined(); + expect(await rig.state('loan_due_ordering')).toEqual(['active']); + }, 60_000); +}); 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 dceb87308b5..ccbcb34ac44 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 @@ -180,3 +180,72 @@ describe('registerFlow — a flow condition\'s record. / previous. date-text rea } }); }); + +// [#34946] The record-root date-arithmetic verdict reaches `registerFlow`'s +// schema advisory exactly as the bare name's does (the same shared validator): +// logged, never thrown — the publish door is what refuses. +describe('registerFlow — a flow condition\'s record. / previous. date arithmetic is advised as its bare name is (#34946)', () => { + let kernel: LiteKernel; + let engine: AutomationEngine; + let stdout: string[]; + let stdoutSpy: ReturnType; + const loanFlow = (name: string, condition: string) => ({ + name, + label: 'Loan due', + 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: { due_date: { type: 'date', required: true }, picked_up_at: { type: 'datetime', required: true } } } + : 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-arithmetic advisory for record. and previous. as for the bare name, and registers', () => { + for (const read of ['due_date', 'record.due_date', 'previous.due_date']) { + stdout.length = 0; + const name = `loan_${read.replace('.', '_')}`; + expect(() => engine.registerFlow(name, loanFlow(name, `${read} + 1 > 5`)), read).not.toThrow(); + expect(stdout.join(''), read).toContain(`date arithmetic \`google.protobuf.Timestamp + int\` — \`${read}\` is a date`); + } + }); + + it('CONTROL: an ordering of the date against today() is not advised', () => { + for (const read of ['record.due_date', 'previous.due_date']) { + stdout.length = 0; + const name = `loan_${read.replace('.', '_')}`; + expect(() => engine.registerFlow(name, loanFlow(name, `${read} < today()`)), read).not.toThrow(); + expect(stdout.join(''), read).not.toMatch(/date arithmetic/); + } + }); +}); diff --git a/packages/spec/src/migrations/entries/semantic/18.flow-condition-record-date-arithmetic-refused.ts b/packages/spec/src/migrations/entries/semantic/18.flow-condition-record-date-arithmetic-refused.ts new file mode 100644 index 00000000000..9289645a23b --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.flow-condition-record-date-arithmetic-refused.ts @@ -0,0 +1,40 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// A flow condition's record.FIELD / previous.FIELD read of a date or datetime +// field now takes the date-arithmetic verdict its bare name already took +// (#34946). A structured TODO, not a D2 conversion: which span or shift the +// author meant (days between, a shifted date, inclusive or not) is not +// recorded, and the platform does not guess. +export const entry: SemanticMigration = { + id: 'flow-condition-record-date-arithmetic-refused', + surface: + 'automation.Flow conditions (a start node config.condition, edges[].condition, a decision node\'s ' + + 'config.conditions[].expression): arithmetic against a number on a date or datetime field of the object the ' + + 'flow is typed against, read through record.FIELD or previous.FIELD (record.due_date + 1 > 5, ' + + 'previous.due_date - 7 < 0). The bare field name (due_date + 1 > 5) was refused already. Not the shape: ' + + 'an ordering or equality of the field (record.due_date < today()), daysBetween / addDays / addMonths over ' + + 'it, or a field record-scoped sites (formula fields, validation rules) read, which were refused already', + replacement: + 'daysBetween(a, b) for the span in whole days (daysBetween(record.due_date, today()) > 5 for more than five ' + + 'days past due), and addDays(d, n) / addMonths(d, n) / daysFromNow(n) to shift a date ' + + '(addDays(record.due_date, 1) < today())', + reason: + 'A flow run binds the trigger record twice: its fields flattened to bare names, and the row itself as record, ' + + 'with the row before the write as previous. A date field reaches the run as its YYYY-MM-DD text and a ' + + 'datetime field as its ISO-8601 instant text, so record.due_date + 1 faults the evaluator on every run, and a ' + + 'flow condition that faults fails the run (ADR-0032 section 1c): the flow stops there and the work it exists ' + + 'to do is not done. The authoring type check refused the arithmetic on the bare name (date-arithmetic, with ' + + 'the run-fails / run-may-fail outcome arms) and passed the record. / previous. read with no finding. It now ' + + 'refuses the read with the same code, the same outcome arm (the row\'s: a root read keeps run-fails where ' + + 'bare names are unproven) and the same words, naming the read as written. There is no mechanical rewrite: ' + + 'whether the author meant a span in days or a shifted date is a judgement about the condition. ' + + 'ADR-0032 / ADR-0087.', + acceptanceCriteria: + 'os validate and os build report no date-arithmetic-run-fails or date-arithmetic-run-may-fail finding on a ' + + 'flow condition that reads a date field through record or previous; POST /api/v1/packages/PKG/publish-drafts ' + + 'publishes the flow; a write that should start it runs past the condition instead of failing there. A stored ' + + 'flow carrying the shape still registers (registerFlow logs it as an advisory) and keeps failing at that ' + + 'condition on every run until it is rewritten and published.', +};