Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .changeset/34451-flow-value-envelope-date-text.md
Original file line number Diff line number Diff line change
@@ -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.<date field>)` 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

<!-- adr-0087: not-required (already-registered formula-timestamp-date-only-refused, formula-date-text-call-refused, formula-date-subtraction-refused) The three semantic entries already carry these verdicts, their codes and their rewrites to the upgrade guide; this change lets the same verdicts reach one more site, a flow value envelope, with the same rewrite, and rewrites each entry's surface in this PR to name that site, its scope (a record-triggered flow or a time-relative sweep of the typed object that rebinds neither record nor previous itself) and its consequence (a stored flow carrying one fails to register at boot on an engine with the object-schema resolver wired until rewritten), and adds to each entry's acceptance criteria how an upgrading operator confirms a stored flow is clear (no failed to register flow warning at boot, and no registerFlow TODO from POST /api/v1/meta/_migrate-stored on the running server; the CLI's os migrate meta --stored boots automation inert, with no object-schema resolver, so it types no value envelope and cannot show it). No id is added, no key is added, removed or re-shaped, and nothing an author wrote is rewritten. -->

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.<field>` / `previous.<field>` reads. `timestamp(record.<date field>)`, alone or inside `+ duration(…)`, is refused with the shift `isoDate(addDays(record.<date field>, 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.<date field>, N))`, never `timestamp(record.<date field>) + duration(…)`.
59 changes: 59 additions & 0 deletions packages/formula/src/validate-date-text-arithmetic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.<field> read, and date-text arithmetic over record.<field>', () => {
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([]);
});
});
86 changes: 85 additions & 1 deletion packages/formula/src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.<field>` / `previous.<field>` 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;
}

/**
Expand Down Expand Up @@ -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.<field>` / `previous.<field>` 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<Record<string, string>>,
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`. */
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading