diff --git a/.changeset/34451-flow-value-envelope-date-text.md b/.changeset/34451-flow-value-envelope-date-text.md new file mode 100644 index 00000000000..b9088036635 --- /dev/null +++ b/.changeset/34451-flow-value-envelope-date-text.md @@ -0,0 +1,34 @@ +--- +'@objectstack/spec': minor +'@objectstack/formula': minor +'@objectstack/lint': minor +'@objectstack/service-automation': minor +--- + +fix(lint,service-automation): a flow value envelope is typed for the date-text verdicts, so `timestamp(record.)` in an `update_record` / `create_record` field or an `assignment` value is refused at `os validate` and at `registerFlow` + +Clause-②: yes (narrowing) — narrowed: a flow value envelope that registered and published now refuses at `os validate` and at `registerFlow`; owes the contract-review-tier review before the queue, and Tier H via the seat. Widened: the published `ExprSchemaHint` type gains one optional key, `flowValueEnvelope`. +Metadata-protocol: narrowed +Skills-docs: none — no published skill teaches a flow value envelope over a date field; `skills/objectstack-formula/SKILL.md` already states the `timestamp()` / `date-text-call` rule without naming a site, so it now holds for value envelopes as written + + + +The upgrade-guide half of the narrowing (#34661) is completed by this PR: the three ADR-0087 entries above now name the flow value envelope in their `surface`. + +**BREAKING** accept-set narrowing, shipped as `minor`. A flow's value envelope (`assignment` `assignments.*`, `create_record` / `update_record` `fields.*`) was validated without field types, so the date-text verdicts never reached it. `isoDate(timestamp(record.borrow_date) + duration('168h'))` written into an `update_record` field passed `os validate`, registered, and failed every run: the runtime holds a `date` field as its `YYYY-MM-DD` text, and `timestamp()` parses only a full ISO-8601 instant. + +- **The verdicts.** The envelope is now typed with the object the flow's run binds as `record` (the start node's `objectName`; a time-relative flow's swept object) — on a record-triggered flow, or a time-relative sweep of the typed object, that rebinds neither root the typing reads (no declared variable, node id, output / iterator / index / error variable or `assignment` target named `record`; no node id, output / iterator / index / error variable or `assignment` target named `previous` — the run's seed sets `previous` over a declared variable of that name) — for the date-text family alone: `date-text-call-run-may-fail` and `date-text-arithmetic-run-may-fail`, over `record.` / `previous.` reads. `timestamp(record.)`, alone or inside `+ duration(…)`, is refused with the shift `isoDate(addDays(record., N))`; so are a `date` / `datetime` field handed straight to a timestamp-only call (`isoDate(record.picked_up_at)`) and arithmetic on its text (`record.borrow_date - duration('24h')`). +- **Where.** `@objectstack/lint` `validateStackExpressions` (`os validate`, `os build`, the flow publish door) reports an `error` at the slot. `@objectstack/service-automation` `registerFlow` throws it when an object-schema resolver is wired, and the stored pass (`canonicalizeStoredFlow`) lists it at the slot. The two doors judge the same set of flows. A flow stored with such an envelope stops registering at boot until it is rewritten. +- **Not refused.** Any envelope of a flow whose `record` is not proven to be the typed object's row: an inbound hook (`api`), a schedule, a flow with no trigger (started by hand or by a parent's `subflow` / `map`), a sweep of another object, and a record-triggered flow that declares or assigns its own `record` variable, or assigns or outputs its own `previous` — judged untyped, as before. `timestamp()` over a `datetime` field. A bare field name in an envelope, and an expression reading `input`: neither door can prove what the run binds there. Every other type verdict (`type-mismatch*`, `date-arithmetic*`, `date-duration-value`) and field existence stay out of value envelopes, as before. The run-time evaluator is unchanged. +- **`@objectstack/formula`.** `ExprSchemaHint` gains the optional `flowValueEnvelope` key that both doors pass. +- **`@objectstack/spec`.** The ADR-0087 entries `formula-timestamp-date-only-refused`, `formula-date-text-call-refused` and `formula-date-subtraction-refused` name the flow value envelope in their `surface` (for the subtraction entry, its first two shapes; the formula-only duration value stays out of envelopes). Text only: no id, key or shape changes. + +## FROM → TO + +| FROM | TO | +|:---|:---| +| `isoDate(timestamp(record.borrow_date) + duration('168h'))` | `isoDate(addDays(record.borrow_date, 7))` | +| `timestamp(record.borrow_date)` | `date(record.borrow_date)` | +| `isoDate(record.picked_up_at)` | `isoDate(date(record.picked_up_at))` | + +One-line fix: in a flow value envelope, shift a date field by whole days with `isoDate(addDays(record., N))`, never `timestamp(record.) + duration(…)`. diff --git a/packages/formula/src/validate-date-text-arithmetic.test.ts b/packages/formula/src/validate-date-text-arithmetic.test.ts index 6e099b6fa60..fda6fb58498 100644 --- a/packages/formula/src/validate-date-text-arithmetic.test.ts +++ b/packages/formula/src/validate-date-text-arithmetic.test.ts @@ -432,3 +432,62 @@ describe('timestamp() handed a date-only field\'s text (#34363)', () => { expect(validateExpression('value', MEASURED, { scope: 'record' }).errors).toEqual([]); }); }); + +describe('a flow value envelope typed for the date-text family alone (#34451)', () => { + /** The object a record-triggered flow binds as `record`: a loan's borrow day, pick-up instant and title. */ + const fieldTypes = { title: 'text', borrow_date: 'date', due_date: 'date', picked_up_at: 'datetime' }; + const ENVELOPE: ExprSchemaHint = { fieldTypes, flowValueEnvelope: true }; + const codes = (source: string, hint: ExprSchemaHint | undefined = ENVELOPE) => + validateExpression('value', { dialect: 'cel', source }, hint).errors.map((e) => e.code); + /** The expression cloud measured in an `update_record` node's `fields.due_date`. */ + const MEASURED = "isoDate(timestamp(record.borrow_date) + duration('168h'))"; + + it('refuses the measured expression under the run-may-fail arm, with the addDays shift', () => { + const r = validateExpression('value', { dialect: 'cel', source: MEASURED }, ENVELOPE); + expect(r.warnings).toEqual([]); + expect(r.errors.map((e) => ({ code: e.code, params: e.params }))).toEqual([{ + code: 'date-text-call-run-may-fail', + params: { + call: 'timestamp(record.borrow_date)', + reference: 'record.borrow_date', + rewrite: 'date(record.borrow_date)', + shift: 'isoDate(addDays(record.borrow_date, N))', + }, + }]); + expect(r.errors[0].message).toContain('`isoDate(addDays(record.borrow_date, N))`'); + }); + + it('refuses the bare call, a previous. read, and date-text arithmetic over record.', () => { + expect(codes('timestamp(record.borrow_date)')).toEqual(['date-text-call-run-may-fail']); + expect(codes('timestamp(previous.borrow_date)')).toEqual(['date-text-call-run-may-fail']); + expect(codes("record.borrow_date - duration('24h')")).toEqual(['date-text-arithmetic-run-may-fail']); + }); + + it('CONTROL: a datetime field under timestamp(), and the taught shift, stay clean', () => { + expect(codes("isoDate(timestamp(record.picked_up_at) + duration('168h'))")).toEqual([]); + expect(codes('isoDate(addDays(record.borrow_date, 7))')).toEqual([]); + }); + + it('CONTROL: no verdict outside the date-text family reaches the envelope', () => { + // type-mismatch, date-arithmetic, date-duration-value, field existence: all stand down. + expect(codes('record.title * 2')).toEqual([]); + expect(codes('record.due_date + 1')).toEqual([]); + expect(codes('today() - record.borrow_date')).toEqual([]); + expect(codes('record.no_such_field')).toEqual([]); + // The same sources are refused or warned where a formula site types them. + const formula: ExprSchemaHint = { scope: 'record', fields: Object.keys(fieldTypes), fieldTypes }; + const r = validateExpression('value', 'record.title * 2', formula); + expect([...r.errors, ...r.warnings].map((e) => e.code)).toEqual(['type-mismatch']); + }); + + it('a bare name, and a source reading `input`, take no verdict: the envelope cannot prove either is the field', () => { + expect(codes("isoDate(timestamp(borrow_date) + duration('168h'))")).toEqual([]); + expect(codes('timestamp(input.borrow_date)')).toEqual([]); + }); + + it('a malformed envelope is refused as before, and without field types nothing new runs', () => { + expect(codes('{record.borrow_date}')).toEqual(['cel-template-brace']); + expect(validateExpression('value', { dialect: 'cel', source: MEASURED }).errors).toEqual([]); + expect(codes(MEASURED, { flowValueEnvelope: true })).toEqual([]); + }); +}); diff --git a/packages/formula/src/validate.ts b/packages/formula/src/validate.ts index 22399887cb1..ab8704550e3 100644 --- a/packages/formula/src/validate.ts +++ b/packages/formula/src/validate.ts @@ -297,6 +297,50 @@ export interface ExprSchemaHint { * Absent ⇒ every verdict is exactly as before this key. */ timeRelativeSweep?: boolean; + /** + * [#34451] `value` role only: the expression is a flow VALUE envelope — an + * `assignment` node's `assignments.*`, a `create_record` / `update_record` + * node's `fields.*` — and {@link fieldTypes} are the field types of the + * object whose row the flow's run binds as `record`. + * + * The PREMISE is the caller's to establish, and both callers pass the key + * only where it holds: the flow is record-triggered on that object, or a + * time-relative sweep of it (the entrance hands the run that object's row + * as `record`), AND the flow rebinds neither root the typing reads — no + * declared variable, node id, output / iterator / index / error variable + * or `assignment` target named `record`, and no node id, output / iterator + * / index / error variable or `assignment` target named `previous` (the + * run's seed sets `previous` over a declared variable of that name, so a + * declaration does not rebind it) — since the run's variables are spread + * over the scope an envelope reads. On any other flow (an inbound hook, a schedule, + * a flow started by a parent's `subflow` / `map` or by hand) `record` is + * whatever the entrance handed the run, and the key is not set. + * + * Of the schema-aware passes, ONLY the date-text verdict family runs — + * `date-text-call*` and `date-text-arithmetic*` — and only over the + * `record.` / `previous.` reads, which under that premise hold + * what the entrance bound: the row under `record`, and under `previous` the + * row before the write (on a record-change trigger's update leg) or null + * (its create leg, and a sweep, have none; a read of it faults whatever the + * field's type). Every other pass stands down: field existence, the + * near-miss, the role catalog, the bare-reference refusal, `type-mismatch*`, + * `date-arithmetic*` and `date-duration-value` say nothing here. A bare name + * stands down too: in a value envelope it holds whatever the run's variable + * map holds under that name, which no door judging this envelope alone can + * prove is the field. So does an expression that reads the `input` root, + * which a flow does not bind to the row the types describe. + * + * The verdict is an error under the `-run-may-fail` arm: the envelope faults + * wherever the field holds the text the runtime keeps for it, and the + * engine's value evaluator throws on that fault, so the run fails there. + * + * Both doors set it with the same inputs — `@objectstack/lint`'s + * `validateStackExpressions` and `@objectstack/service-automation`'s + * `registerFlow` — so they refuse one set. The run-time evaluator does not + * set it: an envelope that registered is evaluated exactly as before. + * Absent ⇒ every verdict is exactly as before this key. + */ + flowValueEnvelope?: boolean; } /** @@ -778,6 +822,37 @@ 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)(?:-|$)/; + +/** + * [#34451] The verdict a flow value envelope gets ({@link ExprSchemaHint.flowValueEnvelope}): + * the date-text family over the `record.` / `previous.` reads, + * or `null`. + * + * Typed at `record` scope, which types exactly those roots (and `input`, which + * is why a source reading `input` stands down): a bare name is then not a + * field at all, so it never takes a verdict. The order is + * {@link typeSoundnessIssue}'s: a shape the Timestamp typing already faults on + * (`record.due_date + 1`, `record.note * 2`) is another family's, so the + * date-text check is not asked about it. The outcome is `run-may-fail`, the + * arm that names the field as the condition of the fault. + */ +function flowValueEnvelopeDateTextIssue( + source: string, + fieldTypes: Readonly>, + ast: () => CelAstNode | null, +): ExprValidationError | null { + const celFieldTypes = toCelFieldTypes(fieldTypes); + if (!Object.values(celFieldTypes).includes('timestamp')) return null; + const tree = ast(); + if (!tree || readRootMembers(tree, ['input']).length > 0) return null; + if (firstTypeMismatch(source, celFieldTypes, 'record')) return null; + const dateOnly = new Set(Object.keys(fieldTypes).filter((name) => fieldTypes[name] === 'date')); + const found = dateTextIssue(source, celFieldTypes, 'record', 'value', 'run-may-fail', dateOnly); + return found && DATE_TEXT_FAMILY_RE.test(found.issue.code) ? found.issue : null; +} + /** A bare `{x}` that is NOT part of a `{{x}}` mustache hole. */ const SINGLE_BRACE_RE = /(?:^|[^{])\{\s*([A-Za-z_$][\w.$]*)\s*\}(?!\})/; /** The roots whose members the field-existence pass judges against `schema.fields`. */ @@ -1536,6 +1611,12 @@ export function validateExpression( `${lead} — ${role}s are bare CEL (e.g. \`record.rating >= 4\`).`, )); } + } else if (schema?.flowValueEnvelope === true) { + // [#34451] A flow value envelope: the date-text family alone (see the key's docblock). + const issue = role === 'value' && schema.fieldTypes + ? flowValueEnvelopeDateTextIssue(source, schema.fieldTypes, ast) + : null; + if (issue) errors.push(issue); } else { checkFieldExistence(ast, source, schema, errors); checkOptionLabelTargets(ast, source, schema, errors); @@ -1632,7 +1713,10 @@ export function validateExpression( // engine's formula read path preloads it before computing the field. Its // caller opts in exactly as a validation condition's does, and the conflicts // are worded for a field that reads null rather than a write that is refused. - if (schema?.fieldTypes && schema.traversalHydration === true && (role === 'predicate' || role === 'value')) { + if ( + schema?.fieldTypes && schema.traversalHydration === true && schema.flowValueEnvelope !== true + && (role === 'predicate' || role === 'value') + ) { const tree = ast(); const analysis = tree ? traversalsOf(readRootMembers(tree, [DEFAULT_TRAVERSAL_ROOT])) : null; if (analysis) { diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index c6f53476494..726254e0e4c 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -6603,3 +6603,219 @@ describe('[#22227] settledWhen — the deadline settle predicate in the field-ru expect(issues.filter((i) => /master_detail/.test(i.message))).toEqual([]); }); }); + +// [#34451] A flow VALUE envelope (`update_record` / `create_record` `fields.*`, +// `assignment` values) is typed with the object the run binds as `record`, for +// the date-text verdict family alone: `timestamp(record.)` checks +// clean as CEL and faults on the `YYYY-MM-DD` text on every run. The engine's +// `registerFlow` refuses the same set (service-automation's +// `assignment-value-envelope.test.ts`). +describe('validateStackExpressions — flow value envelopes take the date-text family (#34451)', () => { + const LOAN = { + name: 'library_loan', + fields: { + borrow_date: { type: 'date' }, + due_date: { type: 'date' }, + picked_up_at: { type: 'datetime' }, + title: { type: 'text' }, + }, + }; + const MEASURED = "isoDate(timestamp(record.borrow_date) + duration('168h'))"; + type Slot = 'update_record' | 'create_record' | 'assignment'; + const envelope = (source: string) => ({ dialect: 'cel', source }); + const nodeFor = (slot: Slot, source: string) => + slot === 'assignment' + ? { id: 'n1', type: 'assignment', config: { assignments: { due: envelope(source) } } } + : { + id: 'n1', type: slot, + config: { + objectName: 'library_loan', + ...(slot === 'update_record' ? { filter: { id: envelope('record.id') } } : {}), + fields: { due_date: envelope(source) }, + }, + }; + const stackWith = (slot: Slot, source: string, start: Record = { + objectName: 'library_loan', triggerType: 'record-after-update', + }) => ({ + objects: [LOAN], + flows: [{ + name: 'loan_due', + nodes: [{ id: 'start', type: 'start', config: start }, nodeFor(slot, source), { id: 'end', type: 'end' }], + edges: [{ id: 'e1', source: 'start', target: 'n1' }, { id: 'e2', source: 'n1', target: 'end' }], + }], + }); + const SLOT_KEY: Record = { + update_record: 'config.fields.due_date', + create_record: 'config.fields.due_date', + assignment: 'config.assignments.due', + }; + + it.each(['update_record', 'create_record', 'assignment'] as const)( + 'refuses timestamp() over a date field in %s, alone or inside + duration(), naming the addDays shift', + (slot) => { + for (const source of [MEASURED, 'timestamp(record.borrow_date)']) { + const issues = validateStackExpressions(stackWith(slot, source)); + expect(issues.map((i) => [i.severity, i.path]), source).toEqual([['error', `flows[0].nodes[1].${SLOT_KEY[slot]}`]]); + expect(issues[0].message).toContain('`timestamp(record.borrow_date)`'); + expect(issues[0].message).toContain('`isoDate(addDays(record.borrow_date, N))`'); + } + }, + ); + + it('types a time-relative flow\'s envelope with the swept object', () => { + const issues = validateStackExpressions(stackWith('update_record', MEASURED, { + schedule: '0 * * * *', timeRelative: { object: 'library_loan', dateField: 'due_date', offsetDays: 1 }, + })); + expect(issues.filter((i) => /isoDate\(addDays\(record\.borrow_date, N\)\)/.test(i.message))).toHaveLength(1); + }); + + it('CONTROL: a datetime field in the same envelope, and the taught shift, stay clean', () => { + for (const source of ["isoDate(timestamp(record.picked_up_at) + duration('168h'))", 'isoDate(addDays(record.borrow_date, 7))']) { + expect(validateStackExpressions(stackWith('update_record', source)), source).toEqual([]); + } + }); + + it('CONTROL: only the date-text family reaches the envelope — a text field in arithmetic stays silent here', () => { + // A flow condition over the same object gets the type-mismatch verdict; the envelope does not. + expect(validateStackExpressions(stackWith('update_record', 'record.title * 2'))).toEqual([]); + expect(validateStackExpressions(stackWith('update_record', 'record.due_date + 1'))).toEqual([]); + }); + + // The stand-downs: the typing holds only where the run's `record` IS a row + // of the typed object — a record-triggered flow or a sweep of it — and the + // flow binds no `record` of its own. Each CONTROL carries the refused source. + const REFUSED = 'timestamp(record.borrow_date)'; + + it('CONTROL: an inbound hook (api) start is not typed — zero findings', () => { + for (const slot of ['update_record', 'create_record', 'assignment'] as const) { + expect(validateStackExpressions(stackWith(slot, REFUSED, { objectName: 'library_loan', triggerType: 'api', secretRef: 'LOAN_HOOK_SECRET' })), slot).toEqual([]); + } + }); + + // No entrance of these hands the run a record, so the existing unbound-root + // refusal (#22565) already names every `record.` read in them — the bare + // `record.borrow_date` read included. The CONTROL is that `timestamp()` over + // it adds nothing: the findings are the bare read's, one for one. + it.each([ + ['a start with no trigger (started by hand)', { objectName: 'library_loan' }], + ['a schedule', { objectName: 'library_loan', schedule: '0 * * * *' }], + ])('CONTROL: %s is not typed — no finding beyond the bare read\'s', (_label, start) => { + for (const slot of ['update_record', 'create_record', 'assignment'] as const) { + const shape = (source: string) => validateStackExpressions(stackWith(slot, source, start)) + .map((i) => [i.severity, i.path, i.message.replace(/record\.borrow_date|borrow_date/g, 'X')]); + const refused = shape(REFUSED); + expect(refused, slot).toEqual(shape('record.borrow_date')); + expect(refused.some(([, , m]) => /addDays/.test(String(m))), slot).toBe(false); + } + }); + + it('CONTROL: a child flow a parent starts through `subflow` is not typed — zero findings', () => { + const stack = stackWith('update_record', REFUSED, { objectName: 'library_loan' }); + stack.flows[0] = { ...stack.flows[0], name: 'loan_due_child' }; + stack.flows.push({ + name: 'loan_due_parent', + nodes: [ + { id: 'start', type: 'start', config: { objectName: 'library_loan', triggerType: 'record-after-update' } }, + { id: 'call', type: 'subflow', config: { flowName: 'loan_due_child' } } as never, + { id: 'end', type: 'end' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'call' }, { id: 'e2', source: 'call', target: 'end' }], + }); + expect(validateStackExpressions(stack)).toEqual([]); + }); + + it('CONTROL: a record-triggered flow that declares a `record` variable is not typed — zero findings', () => { + for (const slot of ['update_record', 'create_record', 'assignment'] as const) { + const stack = stackWith(slot, REFUSED); + stack.flows[0] = { ...stack.flows[0], variables: [{ name: 'record', type: 'object' }] } as never; + expect(validateStackExpressions(stack), slot).toEqual([]); + } + }); + + // A binder node placed between the start and the slot node. + const withBinder = (stack: ReturnType, binder: Record) => { + const flow = stack.flows[0]; + stack.flows[0] = { + ...flow, + nodes: [flow.nodes[0], binder as never, ...flow.nodes.slice(1)], + edges: [ + { id: 'e0', source: 'start', target: String(binder.id) }, + { id: 'e1', source: String(binder.id), target: 'n1' }, + flow.edges[1], + ], + }; + return stack; + }; + const region = () => ({ nodes: [{ id: 'inner', type: 'assignment', config: { assignments: { note: envelope('1') } } }], edges: [] }); + // Every row of the binder check other than shape 1 of `assignment`, each binding `record`. + // The legacy assignment shapes evaluate nothing, so they bind a literal. + const RECORD_BINDERS: ReadonlyArray<[string, Record]> = [ + ['a get_record outputVariable', { id: 'fetch', type: 'get_record', config: { objectName: 'library_loan', limit: 1, outputVariable: 'record' } }], + ['a loop iteratorVariable', { id: 'each', type: 'loop', config: { collection: envelope('[1]'), iteratorVariable: 'record', body: region() } }], + ['a loop indexVariable', { id: 'each', type: 'loop', config: { collection: envelope('[1]'), iteratorVariable: 'row', indexVariable: 'record', body: region() } }], + ['a try_catch errorVariable', { id: 'guard', type: 'try_catch', config: { errorVariable: 'record', try: region(), catch: { nodes: [{ id: 'inner2', type: 'assignment', config: { assignments: { note: envelope('2') } } }], edges: [] } } }], + ['a node id', { id: 'record', type: 'assignment', config: { assignments: { note: envelope('1') } } }], + ['an assignment, shape 2 (array entries)', { id: 'rebind', type: 'assignment', config: { assignments: [{ variable: 'record', value: 'rebound' }] } }], + ['an assignment, shape 3 (no wrapper)', { id: 'rebind', type: 'assignment', config: { record: 'rebound' } }], + ]; + + it.each(RECORD_BINDERS)('CONTROL: a record-triggered flow binding `record` through %s is not typed — zero findings', (_label, binder) => { + expect(validateStackExpressions(withBinder(stackWith('update_record', REFUSED), binder))).toEqual([]); + }); + + // `previous`: the envelope reads it too, and a node rebinds it the same way. + // A DECLARED `previous` does not: `seedRunVariables` sets it over the + // declaration, so the declared row stays typed. + const PREVIOUS_REFUSED = 'timestamp(previous.borrow_date)'; + it('reads through `previous` are refused on a record-triggered flow', () => { + const issues = validateStackExpressions(stackWith('update_record', PREVIOUS_REFUSED)); + expect(issues.map((i) => [i.severity, i.path])).toEqual([['error', 'flows[0].nodes[1].config.fields.due_date']]); + }); + + it.each([ + ['a get_record outputVariable', { id: 'fetch', type: 'get_record', config: { objectName: 'library_loan', limit: 1, outputVariable: 'previous' } }], + ['an assignment that builds it', { id: 'rebind', type: 'assignment', config: { assignments: { previous: envelope('{"borrow_date": "2026-01-01T00:00:00Z"}') } } }], + ])('CONTROL: a record-triggered flow binding `previous` through %s is not typed — zero findings', (_label, binder) => { + expect(validateStackExpressions(withBinder(stackWith('update_record', PREVIOUS_REFUSED), binder))).toEqual([]); + }); + + it('a DECLARED `previous` variable does not stand the typing down — the seed sets `previous` over it', () => { + const stack = stackWith('update_record', PREVIOUS_REFUSED); + stack.flows[0] = { ...stack.flows[0], variables: [{ name: 'previous', type: 'object' }] } as never; + expect(validateStackExpressions(stack).map((i) => i.path)).toEqual(['flows[0].nodes[1].config.fields.due_date']); + }); + + it('refuses a date field subtracted from another in an envelope (date-text-arithmetic)', () => { + const issues = validateStackExpressions(stackWith('update_record', 'record.due_date - record.borrow_date')); + expect(issues.map((i) => [i.severity, i.path])).toEqual([['error', 'flows[0].nodes[1].config.fields.due_date']]); + }); + + it('CONTROL: a sweep whose start names another object than the swept one is not typed — zero findings', () => { + const stack = stackWith('update_record', REFUSED, { + objectName: 'archive_loan', schedule: '0 * * * *', timeRelative: { object: 'library_loan', dateField: 'due_date', offsetDays: 1 }, + }); + stack.objects.push({ ...LOAN, name: 'archive_loan' }); + expect(validateStackExpressions(stack)).toEqual([]); + }); + + it('CONTROL: a record-triggered flow whose assignment assigns `record` is not typed — zero findings', () => { + for (const slot of ['update_record', 'create_record', 'assignment'] as const) { + const stack = stackWith(slot, REFUSED); + const flow = stack.flows[0]; + stack.flows[0] = { + ...flow, + nodes: [ + flow.nodes[0], + { id: 'rebind', type: 'assignment', config: { assignments: { record: envelope('{"borrow_date": "2026-01-01"}') } } } as never, + ...flow.nodes.slice(1), + ], + edges: [ + { id: 'e0', source: 'start', target: 'rebind' }, + { id: 'e1', source: 'rebind', target: 'n1' }, + flow.edges[1], + ], + }; + expect(validateStackExpressions(stack), slot).toEqual([]); + } + }); +}); diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index add3f7ac219..630a4a1f1ed 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -3103,11 +3103,28 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression * registers, and a malformed envelope used to be stored verbatim and rendered * by `notify` as JSON with nothing said at any layer. * + * [#34451] `fieldTypes`: the field types of the object the flow's run binds + * as `record` — the object its conditions are typed against (the start + * node's `objectName`, else a time-relative flow's swept object) — passed + * only where that binding holds: a record-triggered flow or a sweep of the + * typed object, rebinding neither `record` nor `previous` (the caller's + * `valueEnvelopeFieldTypes`). Handed on + * as `ExprSchemaHint.flowValueEnvelope`, which lets the date-text verdict + * family alone reach the envelope, over its `record.` / + * `previous.` reads: `timestamp(record.)` faults on the + * `YYYY-MM-DD` text on every run. The engine's `registerFlow` passes the + * same hint (`valueEnvelopeRefusals`), so the two doors refuse one set. + * Absent (no typed object), the call is byte for byte what it was. + * * @returns whether the slot was refused on SHAPE, so the caller can skip the * root judgment (#22565) — a value that is not an envelope has no source to * read roots from. */ - const checkDeclaredValue = (where: string, raw: unknown): { refused: boolean } => { + const checkDeclaredValue = ( + where: string, + raw: unknown, + fieldTypes?: Readonly>, + ): { refused: boolean } => { if (raw == null) return { refused: false }; // `celSourceOf` — not a second read of `.source`: the same helper every // other slot in this file locates its finding with. @@ -3118,7 +3135,11 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression for (const issue of shape.error.issues) issues.push({ where, message: issue.message, source, severity: 'error' }); return { refused: true }; } - const res = validateExpression('value', raw as { dialect?: string; source?: string }); + const res = validateExpression( + 'value', + raw as { dialect?: string; source?: string }, + fieldTypes ? { fieldTypes, flowValueEnvelope: true } : undefined, + ); for (const e of res.errors) { issues.push({ where, message: `${VALUE_ENVELOPE_REFUSAL} ${e.message}`, source: e.source, severity: 'error' }); } @@ -3294,6 +3315,24 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression triggerKind, sweepsTypedObject: sweepObject !== undefined && sweepObject === objectName, }); + // [#34451] The value envelopes' typing holds on the same flows: where the + // run's `record` IS a row of the typed object — the flows a condition has + // a proven outcome on — and only while the flow rebinds neither root the + // typing reads (`celScope` spreads the run's variables over the context, + // so an assigned or output `record` / `previous` is what an envelope + // reads): `record` by any row of `collectFlowVariableNames` (a declared + // one too), `previous` by a NODE row only — the collector asked without + // `flow.variables` — since `seedRunVariables` sets `previous` over a + // declared variable of that name. Elsewhere (an inbound hook, a schedule, + // a flow a parent's `subflow` / `map` starts) `record` holds whatever the + // entrance handed the run, and the envelope is judged untyped. The + // engine's `registerFlow` stands down on the same set + // (`flow-registration-checks.ts` `flowRebindsRunRowRoots`). + const valueEnvelopeFieldTypes = flowFaultOutcome !== undefined && objectName + && !declaredVariables.has('record') + && !collectFlowVariableNames({}, graphs).has('previous') + ? fieldTypeIndex.get(objectName) + : undefined; // [#29959] The names the run binds over the flattening — its declared // variables and node ids, and the engine's own — which a bare read holds // instead of the field: the type check never types them as the field. @@ -3521,7 +3560,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // design — there is no field reading to displace. if (found.entry.role === 'value') { const from = issues.length; - if (!checkDeclaredValue(slotWhere, found.value).refused) { + if (!checkDeclaredValue(slotWhere, found.value, valueEnvelopeFieldTypes).refused) { refuseUnboundRoots(slotWhere, found.value, from, 'value'); } continue; diff --git a/packages/services/service-automation/src/builtin/assignment-value-envelope.test.ts b/packages/services/service-automation/src/builtin/assignment-value-envelope.test.ts index 36c9495f3c7..a0bd9e5d5c9 100644 --- a/packages/services/service-automation/src/builtin/assignment-value-envelope.test.ts +++ b/packages/services/service-automation/src/builtin/assignment-value-envelope.test.ts @@ -569,3 +569,217 @@ describe('[#19939] where an envelope is literal data, the refusal names a spelli expect(copyLiteral('{x}')).toBe('{x}'); }); }); + +// [#34451] With an object-schema resolver wired, a value envelope is typed with +// the object the run binds as `record`, for the date-text verdict family alone — +// the same hint `objectstack validate` passes (`@objectstack/lint`'s +// `validate-expressions.test.ts` pins that door) — and the refusal is THROWN: +// `timestamp(record.)` checks clean as CEL and faults on the +// `YYYY-MM-DD` text on every run. The evaluator's own call stays untyped. +describe('value envelope — the date-text family at registerFlow (#34451)', () => { + const LOAN_SCHEMA = { + fields: ['borrow_date', 'due_date', 'picked_up_at', 'title'], + fieldTypes: { borrow_date: 'date', due_date: 'date', picked_up_at: 'datetime', title: 'text' } as Record, + }; + const MEASURED = "isoDate(timestamp(record.borrow_date) + duration('168h'))"; + type Slot = 'update_record' | 'create_record' | 'assignment'; + const SLOT_PATH: Record = { + update_record: 'config.fields.due_date', + create_record: 'config.fields.due_date', + assignment: 'config.assignments.due', + }; + function loanFlow(slot: Slot, source: string, start: Record = { + objectName: 'library_loan', triggerType: 'record-after-update', + }) { + const envelope = { dialect: 'cel', source }; + const n1 = slot === 'assignment' + ? { id: 'n1', type: 'assignment', label: 'Set', config: { assignments: { due: envelope } } } + : { + id: 'n1', type: slot, label: 'Write', + config: { + objectName: 'library_loan', + ...(slot === 'update_record' ? { filter: { id: { dialect: 'cel', source: 'record.id' } } } : {}), + fields: { due_date: envelope }, + }, + }; + return { + name: 'loan_due', label: 'Loan due', type: 'record_change', + nodes: [{ id: 'start', type: 'start', label: 'Start', config: start }, n1, { id: 'end', type: 'end', label: 'End' }], + edges: [{ id: 'e1', source: 'start', target: 'n1' }, { id: 'e2', source: 'n1', target: 'end' }], + }; + } + function engineWith(resolver: boolean): AutomationEngine { + const engine = new AutomationEngine(createTestLogger()); + registerLogicNodes(engine, createCtx()); + if (resolver) engine.setObjectSchemaResolver((name) => (name === 'library_loan' ? LOAN_SCHEMA : undefined)); + return engine; + } + + it.each(['update_record', 'create_record', 'assignment'] as const)( + 'refuses timestamp() over a date field in %s, alone or inside + duration(), with the addDays shift', + (slot) => { + for (const source of [MEASURED, 'timestamp(record.borrow_date)']) { + const error = catchError(() => engineWith(true).registerFlow('loan_due', loanFlow(slot, source))); + expect(error.message).toContain(`node 'n1' (${slot})`); + expect(error.message).toContain(SLOT_PATH[slot]); + expect(error.message).toContain(ASSIGNMENT_VALUE_ENVELOPE_REFUSAL); + expect(error.message).toContain('`isoDate(addDays(record.borrow_date, N))`'); + } + }, + ); + + it('the stored pass lists exactly what registerFlow refuses, at the slot', () => { + const refused = engineWith(true).canonicalizeStoredFlow('loan_due', loanFlow('update_record', MEASURED)).todos; + expect(refused.map((t) => t.path)).toEqual(['flows[0].nodes[1].config.fields.due_date']); + const clean = loanFlow('update_record', 'isoDate(addDays(record.borrow_date, 7))'); + expect(engineWith(true).canonicalizeStoredFlow('loan_due', clean).todos).toEqual([]); + expect(() => engineWith(true).registerFlow('loan_due', clean)).not.toThrow(); + }); + + it('types a time-relative flow\'s envelope with the swept object', () => { + const start = { schedule: '0 * * * *', timeRelative: { object: 'library_loan', dateField: 'due_date', offsetDays: 1 } }; + expect(() => engineWith(true).registerFlow('loan_due', loanFlow('update_record', MEASURED, start))) + .toThrow(/isoDate\(addDays\(record\.borrow_date, N\)\)/); + }); + + it('CONTROL: a datetime field, and a text field in arithmetic, still register', () => { + for (const source of ["isoDate(timestamp(record.picked_up_at) + duration('168h'))", 'record.title * 2', 'record.due_date + 1']) { + expect(() => engineWith(true).registerFlow('loan_due', loanFlow('update_record', source)), source).not.toThrow(); + } + }); + + // The stand-downs: the typing holds only where the run's `record` IS a row + // of the typed object — a record-triggered flow or a sweep of it — and the + // flow binds no `record` of its own. Each CONTROL carries the refused source + // and registers, with no todo in the stored pass. + const REFUSED = 'timestamp(record.borrow_date)'; + const registersClean = (engine: AutomationEngine, name: string, flow: unknown, label: string): void => { + expect(() => engine.registerFlow(name, flow as never), label).not.toThrow(); + expect(engineWith(true).canonicalizeStoredFlow(name, flow as never).todos, label).toEqual([]); + }; + + it.each([ + ['an inbound hook (api) start', 'api', { objectName: 'library_loan', triggerType: 'api', secretRef: 'LOAN_HOOK_SECRET' }], + ['a start with no trigger (started by hand or by a parent)', 'autolaunched', { objectName: 'library_loan' }], + ['a schedule', 'schedule', { objectName: 'library_loan', schedule: '0 * * * *' }], + ])('CONTROL: %s is not typed — registers', (_label, type, start) => { + for (const slot of ['update_record', 'create_record', 'assignment'] as const) { + registersClean(engineWith(true), 'loan_due', { ...loanFlow(slot, REFUSED, start), type }, slot); + } + }); + + it('CONTROL: a child flow a parent starts through `subflow` is not typed — both register', () => { + const engine = engineWith(true); + const child = { ...loanFlow('update_record', REFUSED, { objectName: 'library_loan' }), name: 'loan_due_child', type: 'autolaunched' }; + registersClean(engine, 'loan_due_child', child, 'child'); + const parent = { + name: 'loan_due_parent', label: 'Loan due parent', type: 'record_change', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'library_loan', triggerType: 'record-after-update' } }, + { id: 'call', type: 'subflow', label: 'Call', config: { flowName: 'loan_due_child' } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'call' }, { id: 'e2', source: 'call', target: 'end' }], + }; + expect(() => engine.registerFlow('loan_due_parent', parent as never)).not.toThrow(); + }); + + it('CONTROL: a record-triggered flow that declares a `record` variable is not typed — registers', () => { + for (const slot of ['update_record', 'create_record', 'assignment'] as const) { + const flow = { ...loanFlow(slot, REFUSED), variables: [{ name: 'record', type: 'object' }] }; + registersClean(engineWith(true), 'loan_due', flow, slot); + } + }); + + // A binder node placed between the start and the slot node. + const withBinder = (flow: ReturnType, binder: Record) => ({ + ...flow, + nodes: [flow.nodes[0], binder, ...flow.nodes.slice(1)], + edges: [ + { id: 'e0', source: 'start', target: String(binder.id) }, + { id: 'e1', source: String(binder.id), target: 'n1' }, + flow.edges[1], + ], + }); + const cel = (source: string) => ({ dialect: 'cel', source }); + const region = (id: string) => ({ nodes: [{ id, type: 'assignment', label: 'Inner', config: { assignments: { note: cel('1') } } }], edges: [] }); + // Every row of the binder check other than shape 1 of `assignment`, each binding `record`. + // The legacy assignment shapes evaluate nothing, so they bind a literal. + const RECORD_BINDERS: ReadonlyArray<[string, Record]> = [ + ['a get_record outputVariable', { id: 'fetch', type: 'get_record', label: 'Fetch', config: { objectName: 'library_loan', limit: 1, outputVariable: 'record' } }], + ['a loop iteratorVariable', { id: 'each', type: 'loop', label: 'Each', config: { collection: cel('[1]'), iteratorVariable: 'record', body: region('inner') } }], + ['a loop indexVariable', { id: 'each', type: 'loop', label: 'Each', config: { collection: cel('[1]'), iteratorVariable: 'row', indexVariable: 'record', body: region('inner') } }], + ['a try_catch errorVariable', { id: 'guard', type: 'try_catch', label: 'Guard', config: { errorVariable: 'record', try: region('inner'), catch: region('inner2') } }], + ['a node id', { id: 'record', type: 'assignment', label: 'Note', config: { assignments: { note: cel('1') } } }], + ['an assignment, shape 2 (array entries)', { id: 'rebind', type: 'assignment', label: 'Rebind', config: { assignments: [{ variable: 'record', value: 'rebound' }] } }], + ['an assignment, shape 3 (no wrapper)', { id: 'rebind', type: 'assignment', label: 'Rebind', config: { record: 'rebound' } }], + ]; + + it.each(RECORD_BINDERS)('CONTROL: a record-triggered flow binding `record` through %s is not typed — registers', (_label, binder) => { + registersClean(engineWith(true), 'loan_due', withBinder(loanFlow('update_record', REFUSED), binder), _label); + }); + + // `previous`: the envelope reads it too, and a node rebinds it the same way. + // A DECLARED `previous` does not: `seedRunVariables` sets it over the + // declaration, so the declared row stays typed. + const PREVIOUS_REFUSED = 'timestamp(previous.borrow_date)'; + it('reads through `previous` are refused on a record-triggered flow', () => { + expect(() => engineWith(true).registerFlow('loan_due', loanFlow('update_record', PREVIOUS_REFUSED))) + .toThrow(/isoDate\(addDays\(previous\.borrow_date, N\)\)/); + }); + + it.each([ + ['a get_record outputVariable', { id: 'fetch', type: 'get_record', label: 'Fetch', config: { objectName: 'library_loan', limit: 1, outputVariable: 'previous' } }], + ['an assignment that builds it', { id: 'rebind', type: 'assignment', label: 'Rebind', config: { assignments: { previous: cel('{"borrow_date": "2026-01-01T00:00:00Z"}') } } }], + ])('CONTROL: a record-triggered flow binding `previous` through %s is not typed — registers', (_label, binder) => { + registersClean(engineWith(true), 'loan_due', withBinder(loanFlow('update_record', PREVIOUS_REFUSED), binder), _label); + }); + + it('a DECLARED `previous` variable does not stand the typing down — the seed sets `previous` over it', () => { + const flow = { ...loanFlow('update_record', PREVIOUS_REFUSED), variables: [{ name: 'previous', type: 'object' }] }; + expect(() => engineWith(true).registerFlow('loan_due', flow as never)).toThrow(/previous\.borrow_date/); + }); + + it('refuses a date field subtracted from another in an envelope (date-text-arithmetic)', () => { + const error = catchError(() => engineWith(true).registerFlow('loan_due', loanFlow('update_record', 'record.due_date - record.borrow_date'))); + expect(error.message).toContain(SLOT_PATH.update_record); + expect(error.message).toContain(ASSIGNMENT_VALUE_ENVELOPE_REFUSAL); + }); + + it('CONTROL: a sweep whose start names another object than the swept one is not typed — registers', () => { + const engine = new AutomationEngine(createTestLogger()); + registerLogicNodes(engine, createCtx()); + engine.setObjectSchemaResolver((name) => (name === 'library_loan' || name === 'archive_loan' ? LOAN_SCHEMA : undefined)); + const start = { objectName: 'archive_loan', schedule: '0 * * * *', timeRelative: { object: 'library_loan', dateField: 'due_date', offsetDays: 1 } }; + expect(() => engine.registerFlow('loan_due', loanFlow('update_record', REFUSED, start) as never)).not.toThrow(); + expect(engine.canonicalizeStoredFlow('loan_due', loanFlow('update_record', REFUSED, start) as never).todos).toEqual([]); + }); + + it('CONTROL: a record-triggered flow whose assignment assigns `record` is not typed — registers', () => { + for (const slot of ['update_record', 'create_record', 'assignment'] as const) { + const flow = loanFlow(slot, REFUSED); + const rebound = { + ...flow, + nodes: [ + flow.nodes[0], + { id: 'rebind', type: 'assignment', label: 'Rebind', config: { assignments: { record: { dialect: 'cel', source: '{"borrow_date": "2026-01-01"}' } } } }, + ...flow.nodes.slice(1), + ], + edges: [ + { id: 'e0', source: 'start', target: 'rebind' }, + { id: 'e1', source: 'rebind', target: 'n1' }, + flow.edges[1], + ], + }; + registersClean(engineWith(true), 'loan_due', rebound, slot); + } + }); + + it('without a resolver, and at evaluation, the envelope is judged untyped as before', () => { + expect(() => engineWith(false).registerFlow('loan_due', loanFlow('update_record', MEASURED))).not.toThrow(); + // The evaluator's call: no field types, so no new refusal — it faults on the live value instead. + const engine = engineWith(true); + expect((engine as unknown as { valueEnvelopeRefusals(v: unknown): unknown[] }) + .valueEnvelopeRefusals({ dialect: 'cel', source: MEASURED })).toEqual([]); + }); +}); diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index 136e5e1ada9..4bc28229b27 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -1036,8 +1036,11 @@ export function celScope( return { extra: { ...vars, vars, current_user: runUserOf(context) } }; } -/** The body of {@link AutomationEngine.valueEnvelopeRefusals}, moved unedited; that method's docblock is its contract. */ -export function valueEnvelopeRefusals(value: unknown): { message: string; source: string }[] { +/** The body of {@link AutomationEngine.valueEnvelopeRefusals}; that method's docblock is its contract. */ +export function valueEnvelopeRefusals( + value: unknown, + fieldTypes?: Readonly>, +): { message: string; source: string }[] { // [#16439] Presence, asked before either primitive, because neither can // answer it (see rule 0 above). It is stated HERE and not as a guard in // {@link evaluateValueEnvelope} deliberately: a reject reason living @@ -1080,7 +1083,13 @@ export function valueEnvelopeRefusals(value: unknown): { message: string; source // `superRefine` — re-prefixing would say it twice. return shape.error.issues.map((issue) => ({ message: issue.message, source: sourceText })); } - const parsed = validateExpression('value', value as { dialect?: string; source?: string }); + // [#34451] Typed only where the caller hands the bound object's field + // types — `registerFlow`'s pass, never the evaluator below. + const parsed = validateExpression( + 'value', + value as { dialect?: string; source?: string }, + fieldTypes ? { fieldTypes, flowValueEnvelope: true } : undefined, + ); return parsed.errors.map((e) => ({ message: `${VALUE_ENVELOPE_REFUSAL} ${e.message}`, source: e.source, diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 505c49d9c29..501c1897aa4 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -820,9 +820,14 @@ export type FlowFunctionResolver = ( * misused in arithmetic (#1928). Injected by the host (bridged to the object * registry), so the engine stays decoupled from any metadata store. Returns * `undefined` for an unknown object. When unwired, registration validation is - * unchanged (syntax + bare-ref only). Everything it surfaces is advisory (logged - * as a warning, never thrown) — a resolver can never break a flow that used to - * register cleanly. + * unchanged (syntax + bare-ref only). What it surfaces on a CONDITION is + * advisory (logged as a warning, never thrown). One verdict is not: on a flow + * VALUE envelope it adds the date-text family's refusal (#34451, + * {@link AutomationEngine.valueEnvelopeRefusals}), an expression that faults on + * every run, so a flow carrying one stops registering once a resolver is wired — + * on a record-triggered flow or a time-relative sweep of the typed object that + * rebinds neither `record` nor `previous` itself, the flows whose `record` is + * that row. */ export type FlowObjectSchemaResolver = ( objectName: string, @@ -4752,9 +4757,13 @@ export class AutomationEngine implements IAutomationService { * Wire the engine to the host's object registry (#1928) so `registerFlow` * runs the same schema-aware condition checks as `objectstack build` — * unknown-field refs, likely bare-field typos, and text/boolean fields - * misused in arithmetic. Everything it adds is advisory (logged, never - * thrown); passing `null` detaches the bridge (registration reverts to - * syntax + bare-ref validation only). + * misused in arithmetic. Everything it adds on a condition is advisory + * (logged, never thrown); on a flow value envelope it adds one refusal, + * the date-text family (#34451, {@link valueEnvelopeRefusals}), where the + * run's `record` is the typed object's row (a record-triggered flow or a + * sweep of that object, rebinding neither `record` nor `previous`). Passing + * `null` detaches the bridge (registration reverts to syntax + bare-ref + * validation only). */ setObjectSchemaResolver(resolver: FlowObjectSchemaResolver | null): void { this.objectSchemaResolver = resolver; @@ -10856,8 +10865,13 @@ export class AutomationEngine implements IAutomationService { * The object they are typed against is the one the run binds: a * time-relative flow's swept object, read off {@link deriveTriggerBinding} * (#30396). - * The fatal set is unchanged — a resolver can never break a flow that used to - * register cleanly. `advisory: false` skips that pass: the stored pass + * The fatal set is unchanged by it but for one verdict: a flow VALUE + * envelope is typed with the same object where the run's `record` is that + * object's row — a record-triggered flow, or a time-relative sweep of the + * typed object, that rebinds neither `record` nor `previous` — and the date-text + * family it fails (#34451, {@link valueEnvelopeRefusals}) is thrown — in + * both modes, so the stored pass previews it. Any other flow's envelopes + * are judged untyped, as before. `advisory: false` skips the advisory pass: the stored pass * previews refusals ({@link registrationCheckRefusals}), and an advisory * finding is none. * @@ -11400,10 +11414,28 @@ export class AutomationEngine implements IAutomationService { * once. Two independently-derived notions of "malformed" is how a flow comes * to register cleanly and then fault, or to be refused for a shape the * executor would have run. - */ - private valueEnvelopeRefusals(value: unknown): { message: string; source: string }[] { + * + * [#34451] `fieldTypes` — handed ONLY by `registerFlow`'s pass (and the + * stored pass that previews it), as the field types of the object the + * run binds as `record`, read through {@link setObjectSchemaResolver} and + * handed only where that binding holds (a record-triggered flow or a sweep + * of the typed object, rebinding neither `record` nor `previous`) — + * adds one more refusal: the date-text verdict family over the + * envelope's `record.` / `previous.` reads + * (`ExprSchemaHint.flowValueEnvelope`, `@objectstack/formula`), the + * same call `objectstack validate` makes. `timestamp(record.)` checks clean as CEL and faults on the `YYYY-MM-DD` text on + * every run, so a flow carrying it is refused at registration rather + * than at each run. The evaluator never passes it, so registration's + * set is evaluation's plus that one family, never less: an envelope + * that registered is evaluated exactly as before. + */ + private valueEnvelopeRefusals( + value: unknown, + fieldTypes?: Readonly>, + ): { message: string; source: string }[] { // The body lives in ./dag-traversal.ts (#25222). - return valueEnvelopeRefusals(value); + return valueEnvelopeRefusals(value, fieldTypes); } /** diff --git a/packages/services/service-automation/src/flow-registration-checks.ts b/packages/services/service-automation/src/flow-registration-checks.ts index fcecd3ddbda..e4511803374 100644 --- a/packages/services/service-automation/src/flow-registration-checks.ts +++ b/packages/services/service-automation/src/flow-registration-checks.ts @@ -633,6 +633,72 @@ export function collectUndeclaredConfigKeys( } } +/** The config keys whose value names a variable the node binds (`@objectstack/lint`'s `VARIABLE_NAME_CONFIG_KEYS`). */ +const VARIABLE_NAME_CONFIG_KEYS = ['iteratorVariable', 'indexVariable', 'errorVariable', 'outputVariable'] as const; +/** The keys an `assignments` array entry names its target with, in `logic-nodes.ts`'s precedence. */ +const ASSIGNMENT_ENTRY_NAME_KEYS = ['variable', 'name', 'key'] as const; + +/** + * [#34451] The names the flow's NODES bind into the run's variable map, in any + * graph: a node id, a node's `outputVariable` / iterator / index / error + * variable, and an `assignment` target in any of its three shapes. These are + * rows 2-8 of `@objectstack/lint`'s `collectFlowVariableNames` (that package + * is not a dependency of this one, and the two doors must stand down on the + * same flows); row 1, `flow.variables`, is read by the caller, because + * `seedRunVariables` sets `previous` over a declared variable of that name and + * so only a node can rebind it. + */ +function flowNodeBoundNames(flow: FlowParsed): ReadonlySet { + const names = new Set(); + for (const graph of collectFlowGraphs(flow)) { + for (const node of graph.nodes) { + if (!node || typeof node !== 'object') continue; + if (typeof node.id === 'string' && node.id) names.add(node.id); + const config = node.config; + if (!config || typeof config !== 'object' || Array.isArray(config)) continue; + const cfg = config as Record; + for (const key of VARIABLE_NAME_CONFIG_KEYS) { + if (typeof cfg[key] === 'string' && cfg[key]) names.add(cfg[key] as string); + } + if (node.type !== 'assignment') continue; + const raw = cfg.assignments; + if (Array.isArray(raw)) { + // Shape 2: [{ variable | name | key, value }, …], the first name key present wins. + for (const item of raw) { + if (!item || typeof item !== 'object') continue; + const entry = item as Record; + const nameKey = ASSIGNMENT_ENTRY_NAME_KEYS.find((k) => typeof entry[k] === 'string' && entry[k]); + if (nameKey) names.add(entry[nameKey] as string); + } + } else if (raw && typeof raw === 'object') { + // Shape 1: { : , … }. + for (const key of Object.keys(raw)) names.add(key); + } else { + // Shape 3: no wrapper — the config's own keys are the variable names. + for (const key of Object.keys(cfg)) names.add(key); + } + } + } + return names; +} + +/** + * [#34451] Whether the flow itself rebinds a root the value-envelope typing + * reads — `record` by any row (a declared variable too, as ruled, though the + * seed sets `record` over it on a record-change or sweep entrance), `previous` + * by a node row only (the seed sets it over a declared one unconditionally). + * `celScope` spreads the run's variables over the scope an envelope reads, so + * a rebound root is what the envelope reads, not the bound row. + */ +function flowRebindsRunRowRoots(flow: FlowParsed): boolean { + const declared = (flow as { variables?: unknown }).variables; + if (Array.isArray(declared) && declared.some((v) => !!v && typeof v === 'object' && (v as { name?: unknown }).name === 'record')) { + return true; + } + const nodeBound = flowNodeBoundNames(flow); + return nodeBound.has('record') || nodeBound.has('previous'); +} + /** The body of {@link AutomationEngine.validateFlowExpressions}, moved unedited; that method's docblock is its contract. */ export function validateFlowExpressions( this: Pick, @@ -658,10 +724,12 @@ export function validateFlowExpressions( // start naming another object at publish, but a flow stored before it // still registers, and its advisory must speak of the scanned object. // Absent resolver / no object → the hint is undefined and only the fatal - // syntax/bare-ref pass runs (unchanged); the stored pass (`advisory: - // false`) never reads the hint, so it derives no binding. + // syntax/bare-ref pass runs (unchanged). The stored pass (`advisory: + // false`) never reads the advisory hint, but it does type the value + // envelopes below (#34451) — a refusal it must preview — so it derives the + // same binding. const startNode = flow.nodes.find((n) => n.type === 'start'); - const bound = advisory && this.objectSchemaResolver ? this.deriveTriggerBinding(flowName, flow) : undefined; + const bound = this.objectSchemaResolver ? this.deriveTriggerBinding(flowName, flow) : undefined; const objectName = bound?.triggerType === 'time_relative' ? bound.binding.object : ((startNode?.config ?? {}) as Record).objectName; @@ -672,6 +740,29 @@ export function validateFlowExpressions( })() : undefined; + // [#34451] The value-envelope typing below holds only where the run's + // `record` IS a row of the typed object: a record-change trigger on it, + // or a time-relative sweep of it — the two kinds `@objectstack/lint` + // declares a proven outcome for on a flow condition — and only while the + // flow rebinds neither root the typing reads, `record` or `previous` + // ({@link flowRebindsRunRowRoots}: `celScope` resolves both through the + // variable spread, so an assigned or output one is what the envelope + // reads). Anywhere else (an inbound hook, a + // schedule, a flow started by a parent's `subflow` / `map` or by hand) the + // name holds what the entrance handed the run, and no verdict is given. + // `objectstack validate` stands down on the same set. + const startCfg = (startNode?.config ?? {}) as Record; + const sweep = (startCfg.timeRelative ?? {}) as Record; + const runBindsTypedRow = bound?.triggerType === 'record_change' + // The array form routes here only to be refused at bind: it never fires. + ? typeof startCfg.triggerType === 'string' + : bound?.triggerType === 'time_relative' + && typeof sweep.object === 'string' + && (typeof startCfg.objectName !== 'string' || startCfg.objectName === sweep.object); + const valueEnvelopeFieldTypes = runBindsTypedRow && !flowRebindsRunRowRoots(flow) + ? schemaHint?.fieldTypes + : undefined; + const check = (path: string, where: string, raw: unknown, useSchemaHint = true): void => { if (raw == null) return; // Fatal pass — syntax, brace-in-CEL, unknown-function (ADR-0032 §5). @@ -890,8 +981,14 @@ export function validateFlowExpressions( // envelope stored verbatim (a variable `notify` rendered as // JSON, a record column holding the envelope object), with // nothing said at any layer. + // + // [#34451] Typed with the bound object's field types where the + // run's `record` is that object's row (`valueEnvelopeFieldTypes` + // above), so the date-text family reaches the envelope — the + // same set `objectstack validate` refuses. Thrown, in both + // modes: the envelope faults on every run. if (found.entry.role === 'value') { - for (const refusal of this.valueEnvelopeRefusals(found.value)) { + for (const refusal of this.valueEnvelopeRefusals(found.value, valueEnvelopeFieldTypes)) { refuse(slotPath, slotWhere, refusal.message, refusal.source); } continue; diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 3e3d93da996..172ba8ca75a 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -2561,10 +2561,17 @@ export class AutomationServicePlugin implements Plugin { // #1928 — bridge the object registry so `registerFlow` runs the same // schema-aware condition checks as `objectstack build`: unknown-field // refs, likely bare-field typos, and text/boolean fields misused in - // arithmetic. Everything it surfaces is advisory (logged, never thrown), - // so a dynamically-registered flow (which bypasses the build lint) still - // gets the guardrail. Wired BEFORE the flow pull below so pulled flows - // are covered too. Best-effort: without ObjectQL, registration falls back + // arithmetic. What it surfaces on a flow CONDITION is advisory (logged, + // never thrown), so a dynamically-registered flow (which bypasses the + // build lint) still gets the guardrail. One verdict is thrown (#34451): + // on a flow VALUE envelope (`assignment` values, `create_record` / + // `update_record` `fields.*`) of a record-triggered flow or a + // time-relative sweep of the typed object that rebinds neither + // `record` nor `previous` itself, the date-text family refuses + // registration — so with this resolver wired a stored flow carrying + // `timestamp(record.)` there stops registering until + // rewritten. Wired BEFORE the flow pull below so pulled flows are + // covered too. Best-effort: without ObjectQL, registration falls back // to syntax + bare-ref validation only. try { const ql = ctx.getService<{ @@ -2575,7 +2582,8 @@ export class AutomationServicePlugin implements Plugin { parseObjectFieldSchema((ql.registry!.getObject!(objectName) as { fields?: unknown } | undefined)?.fields)); ctx.logger.debug( '[Automation] object-schema resolver bridged to objectql.registry ' + - '(flow conditions are checked against object fields at registration)', + '(flow conditions are checked against object fields at registration, advisory; ' + + 'flow value envelopes are refused on the date-text family)', ); } } catch { diff --git a/packages/spec/src/migrations/entries/semantic/18.formula-date-subtraction-refused.ts b/packages/spec/src/migrations/entries/semantic/18.formula-date-subtraction-refused.ts index a83d32113e4..bc2d195b7ff 100644 --- a/packages/spec/src/migrations/entries/semantic/18.formula-date-subtraction-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/18.formula-date-subtraction-refused.ts @@ -9,7 +9,17 @@ export const entry: SemanticMigration = { + 'validation conditions, flow conditions) — a date or datetime field subtracted from another ' + '(record.end_date - record.start_date), or arithmetic on one with a duration ' + '(record.start_date - duration("24h")); and, as a formula value, an expression that computes a ' - + 'duration (today() - record.start_date, now() - record.start_at)', + + 'duration (today() - record.start_date, now() - record.start_at)' + + '. The first two shapes (a field subtracted from another, a field in arithmetic with a duration; ' + + 'not the formula-only duration value) are refused in a flow VALUE envelope too: an assignment node\'s ' + + 'assignments value, a create_record / update_record node\'s fields.* value, reading the field ' + + 'through record (or previous), in a record-triggered flow or a time-relative sweep of the typed ' + + 'object that rebinds neither record nor previous itself (no assignment target, output, iterator, ' + + 'index or error variable or node id of either name, and no declared variable named record); ' + + 'os validate and the engine\'s registerFlow ' + + 'refuse the same set. A stored flow carrying one fails to register at boot on an engine with the ' + + 'object-schema resolver wired (the automation service bridged to ObjectQL) until it is rewritten ' + + 'with the same rewrite', replacement: 'daysBetween(a, b) for the span in whole days: daysBetween(record.start_date, record.end_date) for end ' + 'minus start, daysBetween(record.start_date, today()) for the days since a date. addDays(d, n) / ' @@ -31,5 +41,11 @@ export const entry: SemanticMigration = { acceptanceCriteria: 'os validate and os build report no date-text-arithmetic or date-duration-value finding; each ' + 'rewritten formula field reads a number on GET /api/v1/data/OBJECT/ID where it read null or {} ' - + 'before; no stored sys_metadata object row reports either finding in its _diagnostics.', + + 'before; no stored sys_metadata object row reports either finding in its _diagnostics.' + + ' For a stored flow: the boot log carries no "[Automation] failed to register flow" (or ' + + '"cold-boot flow bind: failed to register flow") warning naming it, and POST ' + + '/api/v1/meta/_migrate-stored on the running server lists no registerFlow TODO at its assignments ' + + 'or fields slots. The CLI\'s os migrate meta --stored cannot show this: it boots the automation ' + + 'plugin inert (armRuntime: false), which returns before the object-schema resolver is wired, so ' + + 'its stored pass types no value envelope and lists no such TODO whether or not the flow carries one.', }; diff --git a/packages/spec/src/migrations/entries/semantic/18.formula-date-text-call-refused.ts b/packages/spec/src/migrations/entries/semantic/18.formula-date-text-call-refused.ts index 03ce10bf7c4..fb2189a98bf 100644 --- a/packages/spec/src/migrations/entries/semantic/18.formula-date-text-call-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/18.formula-date-text-call-refused.ts @@ -8,7 +8,16 @@ export const entry: SemanticMigration = { 'data.Field.expression of a formula field (and any CEL predicate judged with the object\'s field types: ' + 'validation conditions, flow conditions) — a date or datetime field handed straight to a call that ' + 'takes a timestamp: isoDate(record.start_at), isoDatetime(record.start_at), ' - + 'startsWith(isoDate(record.start_at), "2026"), record.start_date.getFullYear()', + + 'startsWith(isoDate(record.start_at), "2026"), record.start_date.getFullYear()' + + '. The same shapes in a flow VALUE envelope are refused too: an assignment node\'s ' + + 'assignments value, a create_record / update_record node\'s fields.* value, reading the field ' + + 'through record (or previous), in a record-triggered flow or a time-relative sweep of the typed ' + + 'object that rebinds neither record nor previous itself (no assignment target, output, iterator, ' + + 'index or error variable or node id of either name, and no declared variable named record); ' + + 'os validate and the engine\'s registerFlow ' + + 'refuse the same set. A stored flow carrying one fails to register at boot on an engine with the ' + + 'object-schema resolver wired (the automation service bridged to ObjectQL) until it is rewritten ' + + 'with the same rewrite', replacement: 'Parse the field\'s text into a timestamp first with date(…): isoDate(date(record.start_at)), ' + 'isoDatetime(date(record.start_at)), date(record.start_date).getFullYear(). date(…) keeps a ' @@ -36,5 +45,11 @@ export const entry: SemanticMigration = { 'os validate and os build report no date-text-call finding; each rewritten formula field reads a ' + 'value on GET /api/v1/data/OBJECT/ID where it read null before (and the same value where it read ' + 'one), and each rewritten validation rule admits a write it refused as unevaluable before; no ' - + 'stored sys_metadata object row reports the finding in its _diagnostics.', + + 'stored sys_metadata object row reports the finding in its _diagnostics.' + + ' For a stored flow: the boot log carries no "[Automation] failed to register flow" (or ' + + '"cold-boot flow bind: failed to register flow") warning naming it, and POST ' + + '/api/v1/meta/_migrate-stored on the running server lists no registerFlow TODO at its assignments ' + + 'or fields slots. The CLI\'s os migrate meta --stored cannot show this: it boots the automation ' + + 'plugin inert (armRuntime: false), which returns before the object-schema resolver is wired, so ' + + 'its stored pass types no value envelope and lists no such TODO whether or not the flow carries one.', }; diff --git a/packages/spec/src/migrations/entries/semantic/18.formula-timestamp-date-only-refused.ts b/packages/spec/src/migrations/entries/semantic/18.formula-timestamp-date-only-refused.ts index 543e9fecbb6..6869c9180a7 100644 --- a/packages/spec/src/migrations/entries/semantic/18.formula-timestamp-date-only-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/18.formula-timestamp-date-only-refused.ts @@ -8,7 +8,16 @@ export const entry: SemanticMigration = { 'data.Field.expression of a formula field (and any CEL predicate judged with the object\'s field types: ' + 'validation conditions, field rule predicates, flow conditions) — a date-only (date) field handed to ' + 'timestamp(), alone or inside duration arithmetic: timestamp(record.borrow_date), ' - + 'isoDate(timestamp(record.borrow_date) + duration(\'168h\'))', + + 'isoDate(timestamp(record.borrow_date) + duration(\'168h\'))' + + '. The same shapes in a flow VALUE envelope are refused too: an assignment node\'s ' + + 'assignments value, a create_record / update_record node\'s fields.* value, reading the field ' + + 'through record (or previous), in a record-triggered flow or a time-relative sweep of the typed ' + + 'object that rebinds neither record nor previous itself (no assignment target, output, iterator, ' + + 'index or error variable or node id of either name, and no declared variable named record); ' + + 'os validate and the engine\'s registerFlow ' + + 'refuse the same set. A stored flow carrying one fails to register at boot on an engine with the ' + + 'object-schema resolver wired (the automation service bridged to ObjectQL) until it is rewritten ' + + 'with the same rewrite', replacement: 'Shift a date by whole days with addDays and keep it a date with isoDate: ' + 'isoDate(addDays(record.borrow_date, 7)). Where a timestamp is wanted, parse the field with date(…) in place ' @@ -28,5 +37,11 @@ export const entry: SemanticMigration = { acceptanceCriteria: 'os validate and os build report no date-text-call finding naming timestamp(…); each rewritten formula ' + 'field reads the date plus N days on GET /api/v1/data/OBJECT/ID where it read null before; no stored ' - + 'sys_metadata object row reports the finding in its _diagnostics.', + + 'sys_metadata object row reports the finding in its _diagnostics.' + + ' For a stored flow: the boot log carries no "[Automation] failed to register flow" (or ' + + '"cold-boot flow bind: failed to register flow") warning naming it, and POST ' + + '/api/v1/meta/_migrate-stored on the running server lists no registerFlow TODO at its assignments ' + + 'or fields slots. The CLI\'s os migrate meta --stored cannot show this: it boots the automation ' + + 'plugin inert (armRuntime: false), which returns before the object-schema resolver is wired, so ' + + 'its stored pass types no value envelope and lists no such TODO whether or not the flow carries one.', };