Skip to content

Commit be2df75

Browse files
fix(formula)!: a flow condition's mixed bare / record. date arithmetic and record['FIELD'] index reads take the date-text verdicts (#38949)
Fixes #35295 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: none — `skills/objectstack-formula/SKILL.md` already states "The build refuses date arithmetic (`end - start`, `date + n`)" and that a date field is refused in a timestamp-only call, naming no spelling either rule is limited to, so both now hold for the mixed and index spellings as written; no skill teaches the index spelling ## 维护者速读 - 用户能看到什么变化:作者在校验或发布流程时,若流程条件把一个直接写的日期字段与「当前记录.字段」或「改动前记录.字段」相减,或用「记录['字段']」这种下标写法读日期字段,现在会和写法一致时一样被拒,并给出相同的改法;以前这两种写法能通过校验,流程每次运行都失败。 - 为什么做:属于「表达式校验与作者护栏」,是上一张同类修复留下的两个漏网写法,替编写流程的管理员和代写流程的 AI 助手解决「校验通过、上线后每次运行都出错」。 - 出错会怎样:若误判,作者在校验或发布流程时会看到一条拒绝;流程变量、节点输出这类真正认不出类型的写法照旧放行,已保存的流程照常加载注册,只在下次发布时要求改写;本改动可整体撤回。 - 要你做什么:这是收紧已接受写法的破坏性变更,待座位契约审核通过、试跑全套通过后,需要你本人审阅、批准并合并。 ## What changes Ruled C on the card (ruling record 7311348060, on the decision analysis 7306749599): one PR for both items. - **Item (2), mixed operands** — `packages/formula/src/validate.ts`, `recordRootDateTextIssue`. The flattened date-text check typed bare names in one pass (roots left `dyn`) and `record.` / `previous.` reads in another (bare names left `dyn`), so `due_date - record.borrow_date > duration('24h')` faulted neither while both consistent spellings were refused. The root pass now, after the roots-alone typing answers nothing, types the bare names (less the ones a flow variable shadows) and the roots against the field table in ONE pass. Every verdict the roots prove alone keeps its arm byte for byte; a verdict that rests on a bare name takes the bare name's arm, so where a node can rebind it (`bareNamesUnproven`) it is `date-text-arithmetic-run-may-fail`, as the ruling orders. A genuinely unproven operand (flow variable, node output, shadowed name) stays `dyn` and passes (ADR-0032 1c). - **Item (1), index reads** — `packages/formula/src/cel-engine.ts`. A new gate, `RECORD_ROOT_DATE_TEXT_READ_RE`, admits `record[` / `previous[` (single or double quotes) for the record-root DATE-TEXT pass only, so `timestamp(record['borrow_date'])`, `record['due_date'] - record['borrow_date']`, `isoDate(record['picked_up_at'])` and `record['due_date'] + 1 > 5` take the date-text verdicts. `RECORD_ROOT_READ_RE`, the gate of `firstTypeMismatch`'s root pass, stays member-only, so the text/boolean mismatch and date-arithmetic passes see index reads exactly as on the merge base: no verdict an expression had before changes, and no refusal is stood down to a warning (L2 7315274427, M1 / S1). `offendingRecordRead` names an index read by its member spelling (`record.borrow_date`) only for the date-text pass (`indexReads`), as `typedFieldRef` already did for calls; without it `due_date - record['borrow_date']` named a bare `borrow_date` that is not in the source. - `packages/spec/src/migrations/entries/semantic/19.flow-condition-mixed-or-index-spelling-date-text-refused.ts`: the ADR-0087 semantic entry (a structured TODO, no mechanical rewrite), modelled on PR #37840's entry. - `.changeset/35295-date-text-mixed-spelling.md`: `minor` for `@objectstack/formula` and `@objectstack/spec`, both declaration lines, the Skills-docs line, **BREAKING** banner, FROM → TO table, the `adr-0087: registered` marker. Reach: the flattened scope is used only by flow conditions (lint's start / edge / `decision` conditions, `registerFlow`'s advisory, the MCP `validate_expression` flow-condition site). Record-scoped sites are unchanged. ## Tests `packages/formula/src/validate-date-text-arithmetic.test.ts`, new top-level describe (30 tests): - The 9 mixed forms of the analysis (`record.`, `previous.`, datetime, a span against a number, behind a select guard, no declared outcome, bare names unproven): one error, `ok: false`, the same code, operands, words (read named as written aside) and prescription as each consistent spelling; the run faults with no such overload on a dyn string minus a dyn string, over the engine's real scope. - The arm: run-fails proven, run-may-fail under `bareNamesUnproven`, the all-root spelling keeps run-fails there. - Six index rows (the analysis's 5 faulting index forms plus `previous["borrow_date"]`; 5 of the 6 passed on the merge base, `record['due_date'] - record.borrow_date` was refused there already because its member read opened the gate): the member spelling's code and reference; arithmetic equal byte for byte; for a call the prescribed `date(...)` parse substituted in place checks clean and evaluates `true`. - The narrower reach: `record['due_date'] + 1 > 5` takes `date-text-arithmetic-run-fails` (named `record.due_date`, the run faults); `previous['title'] > 5` takes no type-mismatch finding, as on the merge base. - M1 (L2): `due_date - borrow_date > duration('1h') && record['title'] > 5` and `record['active'] > 5 && isoDate(picked_up_at) == 'x'` stay refused with their date-text code on both arms (no declared outcome: `-run-may-fail`; record-triggered: `-run-fails`), no warning, as on the merge base. - S1 (L2) CONTROL: `record['due_date'] > record['title']`, `due_date > record['title']`, `record['due_date'] > title` and the same ordering written title-first by index check clean on both arms and evaluate, as on the merge base. The analysis's battery did not cover this shape; the first head refused it. - CONTROLS: five index reads the runtime answers (datetime under `timestamp()`, equality, `date(...)`, `daysBetween`, an ordering) stay clean and evaluate `true`; the TEN expressions that run today and B refused (a flow variable or node output holding an instant, `vars.cutoff`, a shadowing variable, four text concatenations) pass with no finding and evaluate `true`. Run harnesses: the analysis found `run` at `validate-date-text-arithmetic.test.ts:568` and `validate.test.ts:1349`, `:1432` binding bare names outside `ctx.extra`, so bare-spelling run pins faulted on `Unknown variable`. All three now bind the engine's scope (`celScope`: bare names, `record`, `previous` under `extra`); every existing run pin stays green on the real fault, and the two older bare-spelling run pins now assert the fault text (`ISO 8601`, `no such overload`), as the index run pin does. <details><summary>Local runs (head 5b8b6af)</summary> Tests under `scripts/pm/os-verify-lock.sh`, exit codes captured before any pipe. - `pnpm --filter @objectstack/formula exec vitest run --maxWorkers=2`: Test Files 72 passed (72), Tests 2211 passed (2211); `pnpm --filter @objectstack/formula run typecheck`: VERDICT command-exit 0 (`tsc --noEmit` and `check:test-typecheck`). - `pnpm --filter @objectstack/lint exec vitest run --maxWorkers=2 src/validate-expressions.test.ts`: Tests 546 passed (546), against a formula `dist/` built from this branch. - `pnpm --filter @objectstack/spec exec vitest run --maxWorkers=2 src/migrations`: Tests 212 passed (212); `pnpm --filter @objectstack/spec check:generated`: all 14 generated artifacts up to date after `pnpm --filter @objectstack/spec build`. - Re-run at 5b8b6af after the patch: `check-adr-0087-registration`, spec `check:spec-changes` / `check:upgrade-guide`, `check:doc-authoring`, `check:nul-bytes`, `check:issue-citations`, `check-empty-changeset`, `check-changeset-no-major`: exit 0 each. - At 03e1b9d (first head; the patch touches the same six files): `node scripts/pm/dispatch-gates.mjs --commands`: 95 families derived for this diff; `--ran`: "95 derived, 93 run, 2 NOT-MEASURED, 0 UNRUN". NOT-MEASURED: `check:dual-build-cjs-loads` (exit 3, PREREQUISITE NOT MET: needs a full `pnpm build`), `check:type-check-debt` (stopped at the foreground bound while its closure build waited on the shared lock). Both are CI's. `check:slot-lookup` was cut by the same bound on its first pass and re-run alone to exit 0 (scan 203 s, self-test passed in the first pass). `pnpm --filter @objectstack/cli exec vitest run test/migrate-meta-engine-guidance.test.ts` and `check:doc-formula-expressions` first answered PREREQUISITE (no `dist/`) and passed after building their closures. - `test:repo` not run locally: the diff touches none of its tests; it is CI's (`Test Core`). </details> <details><summary>Ablation (committed first, mutated through scripts/ablation-replace.mjs, restored to the HEAD blob)</summary> The formula suite imports `./validate` from source, so no dist leg. At 5b8b6af, `src/validate-date-text-arithmetic.test.ts src/validate.test.ts` (273 tests): - Shared gate re-widened (`RECORD_ROOT_READ_RE` admits `[` again, marker `ABLATION-35295-REWIDEN`): 3 failed / 270 passed — the date-text-only reach test, the M1 test and the S1 control. Restored, blob equals HEAD, `git diff HEAD` empty. - Date-text gate back to the member spelling (marker `ABLATION-35295-INDEX`): 6 failed / 267 passed. Restored. - One-pass leg (`?? judged(bareCelTypes, …)` replaced by `?? null`, marker `ABLATION-35295-ONEPASS`): 11 failed / 262 passed — all 9 mixed rows, the arm test, `due_date - record['borrow_date']`. Restored. - Index naming off for the date-text pass (marker `ABLATION-35295-NAMING`): 3 failed / 270 passed. Restored. </details> <details><summary>Corpus</summary> - Behavioural, at 5b8b6af: every `validateExpression` call recorded by the analysis over the shipped examples (app-crm, app-showcase, app-multi-package) and the formula and lint suites, re-judged by the base formula source (05da5bd, equal to `origin/main`'s) and this head: 9,157 unique calls, 2,586 at flattened scope with field types, 0 verdict changes. Controls (4 rows): the mixed form and an index call change; an index text mismatch (`record['title'] > 5`) and the `due_date` ordering do not. - Text scan over 29,402 tracked files: index reads of `record` / `previous` with a quoted key, 109 hits outside this PR's test file, none a flow condition doing date arithmetic or a date call (record-scope formulas, equality-only field-existence pins, UI code); mixed bare / root arithmetic, 0 CEL hits outside this PR (positive control: 14 and 6 hits in the new test file). No authored instance in examples, docs or skills. </details> ## Acceptance notes - The ruling's "one pass" is the second leg of `recordRootDateTextIssue`, asked only after the roots-alone typing answers nothing (the analysis's prototype C, measured 0 false refusals). Keeping the roots-alone leg first is what keeps every currently refused verdict, and its arm, byte for byte. - Index reach (seat decision on L2 7315274427): the index spelling takes the date-text verdicts only. The first head widened the shared gate, which also opened the text/boolean mismatch pass to index reads; that stood a date-text refusal down to a warning (M1) and refused an ordering against a text field that evaluates (S1). Both are back to the merge base and pinned; re-widening the shared gate reds those pins. - Under `bareNamesUnproven` the mixed verdict's `run-may-fail` sentence names the read the reference names (`record.borrow_date`), while the unproven operand is the bare name. The sentence is the existing one, as ruled; not reworded here. - Standing behaviour on main, outside this diff and left as it is: a text mismatch warning hiding a date-family error for the member and bare spellings; the member spelling's verdict on an ordering of a date against a text field; `[due_date, record.borrow_date].exists(d, d > '2026-01-01')` refused while it evaluates; `(status == 'open' ? now() : null) - record.picked_up_at > duration('1h')` passing while it faults. The seat files or dedupes them. - Clause-② line: the claim comment carries `Clause-②: no`; the ruling record and the dispatch carry `no (narrowing)`, which this PR and its changeset use. - L2: a narrowing, so a contract-tier review is owed, and the dogfood battery runs on the final head (the seat arms it). ## Verification Read first: (1) `packages/formula/src/validate.ts` `recordRootDateTextIssue` — the arm of the second leg is the risk; (2) `packages/formula/src/cel-engine.ts` `RECORD_ROOT_READ_RE` / `RECORD_ROOT_DATE_TEXT_READ_RE` — which gate opens to the index spelling is the risk; (3) the `RUNS_TODAY` controls in the new describe. Two-minute check: `pnpm --filter @objectstack/formula exec vitest run src/validate-date-text-arithmetic.test.ts` — expect 30 tests under "(#35295)" passing, among them ten "CONTROL: … runs today and still passes". --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2)_ <!-- signed: repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 776dddf commit be2df75

6 files changed

Lines changed: 353 additions & 17 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
'@objectstack/formula': minor
3+
'@objectstack/spec': minor
4+
---
5+
6+
fix(formula)!: a flow condition's date arithmetic that mixes a bare date field with `record.FIELD` / `previous.FIELD`, and a field read by index (`record['FIELD']`), now take the verdicts their consistent spellings already took
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: narrowed
10+
Skills-docs: none — `skills/objectstack-formula/SKILL.md` already states "The build refuses date arithmetic (`end - start`, `date + n`)" and that a `date` / `datetime` field is refused in a timestamp-only call, naming no spelling those rules are limited to, so they now hold for the mixed and index spellings as written; no skill teaches the index spelling
11+
12+
<!-- adr-0087: registered flow-condition-mixed-or-index-spelling-date-text-refused -->
13+
14+
**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`. A `date` or `datetime` field reaches the run as its text, so subtracting one from another faults on every run and fails the flow. Two spellings of that mistake passed `os validate` and the publish door with no finding:
15+
16+
- **Mixed operands.** `due_date - record.borrow_date > duration('24h')`, `previous.due_date - due_date > duration('24h')`. The all-bare (`due_date - borrow_date …`) and all-root (`record.due_date - record.borrow_date …`) spellings were refused already. The check typed the bare names and the root reads in two separate passes, each leaving the other spelling untyped; they are now typed against the object's field table in one pass.
17+
- **Index reads.** `timestamp(record['borrow_date']) < now()`, `record['due_date'] - record['borrow_date'] > duration('24h')`, `isoDate(record['picked_up_at']) == '2026-11-16'`, `record['due_date'] + 1 > 5`. The record-root date-text pass only looked at the member spelling; it now has a gate of its own that admits an index read of `record` or `previous`, so the index read takes the date-text verdicts the member read takes, named by its member spelling, and those only (`record['due_date'] + 1 > 5` takes `date-text-arithmetic`, where its member spelling takes `date-arithmetic`; both prescribe `daysBetween` / `addDays`). The text and boolean mismatch keeps its member-only gate: through an index read, `record['title'] > 5` and an ordering against a text field (`record['due_date'] > record['title']`) are judged exactly as before, and no refusal an expression had before is stood down to a warning.
18+
19+
- **The verdict.** The code, outcome arm and words of the consistent spelling: `date-text-arithmetic-run-fails` on a record-triggered flow or a sweep of the typed object, `-run-may-fail` elsewhere. A mixed verdict that rests on a bare name takes the bare name's `-run-may-fail` arm where a node can rebind it.
20+
- **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 and still registers the flow, so a stored flow keeps its run-time behaviour until it is next published.
21+
- **Not refused.** An operand the field table does not type keeps passing: a flow variable or node output holding an instant (`cutoff - record.due_date > duration('24h')`, `get_policy.effective_at - record.due_date > duration('24h')`), a bare name a flow variable shadows, a concatenation of the date text (`prefix + record.due_date`); through an index read, the text or boolean mismatch, an ordering against a text field and equality. The run-time evaluator is unchanged.
22+
23+
## FROM → TO
24+
25+
| FROM | TO |
26+
|:---|:---|
27+
| `due_date - record.borrow_date > duration('24h')` | `daysBetween(record.borrow_date, due_date) > 1` |
28+
| `timestamp(record['borrow_date']) < now()` | `date(record['borrow_date']) < now()` |
29+
| `record['due_date'] - record['borrow_date'] > duration('24h')` | `daysBetween(record['borrow_date'], record['due_date']) > 1` |
30+
31+
One-line fix: in a flow condition, never subtract one date field from another or hand one to a timestamp-only call, whichever way it is spelled; use `daysBetween(a, b)` for a span, `addDays(d, n)` to shift a date and `date(…)` to parse it.

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

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1261,26 +1261,45 @@ function withoutNames(
12611261

12621262
/**
12631263
* [#29959, #34662] A `record.` / `previous.` read spelled member-wise — the gate
1264-
* of every flattened record-root pass ({@link firstTypeMismatch}'s and
1265-
* `validate.ts`'s date-text one), so the two can never disagree on whether a
1266-
* source reads a root.
1264+
* of {@link firstTypeMismatch}'s flattened record-root pass. [#35295] It stays
1265+
* member-only: that pass answers before the date-text family is asked, so
1266+
* opening it to the index spelling would hand an index read the text/boolean
1267+
* mismatch verdict, which can stand a date-text refusal down to a warning and
1268+
* refuses an ordering against a text field the runtime answers. The date-text
1269+
* family has its own gate, {@link RECORD_ROOT_DATE_TEXT_READ_RE}.
12671270
*/
12681271
export const RECORD_ROOT_READ_RE = /(?<![\w$.])(?:record|previous)\s*\./;
12691272

1273+
/**
1274+
* [#35295] The gate of `validate.ts`'s flattened record-root date-text pass: a
1275+
* `record.` / `previous.` read spelled member-wise or by index
1276+
* (`record['borrow_date']`, `previous["due_date"]`). The typed env types the
1277+
* index read as the member read and the run hands both the same text, so the
1278+
* date-text verdicts — and only those — reach both spellings.
1279+
*/
1280+
export const RECORD_ROOT_DATE_TEXT_READ_RE = /(?<![\w$.])(?:record|previous)\s*[.[]/;
1281+
12701282
/**
12711283
* [#29959] The `record.<field>` / `previous.<field>` read of a field of
12721284
* `celType` in a flattened condition, as written — what
12731285
* {@link firstTypeMismatch}'s record-root pass names. `null` when no such read
12741286
* is spelled member-wise (an index read, say), so the message names no field.
1287+
* [#35295] With `indexReads` (the date-text pass, which
1288+
* {@link RECORD_ROOT_DATE_TEXT_READ_RE} opens to the index spelling) an index
1289+
* read (`record['due_date']`) is named too, by its member spelling
1290+
* (`record.due_date`) — as {@link typedFieldRef} names it for a call — never as
1291+
* the bare name its quoted key would otherwise match.
12751292
*/
12761293
function offendingRecordRead(
12771294
source: string,
12781295
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
12791296
celType: FieldCelType,
1297+
indexReads = false,
12801298
): { field: string; root: 'record' | 'previous' } | null {
12811299
for (const [name, t] of Object.entries(fieldCelTypes)) {
12821300
if (t !== celType) continue;
1283-
const m = new RegExp(`(?<![\\w$.])(record|previous)\\.${name}(?![\\w$])`).exec(source);
1301+
const index = indexReads ? `|\\s*\\[\\s*(['"])${name}\\2\\s*\\]` : '';
1302+
const m = new RegExp(`(?<![\\w$.])(record|previous)(?:\\.${name}(?![\\w$])${index})`).exec(source);
12841303
if (m) return { field: name, root: m[1] as 'record' | 'previous' };
12851304
}
12861305
return null;
@@ -1588,7 +1607,7 @@ export function firstDateTextVerdict(
15881607
| { valid?: boolean; type?: unknown; error?: { message?: string } }
15891608
| undefined;
15901609
if (!result) return null;
1591-
const read = rootTypes ? offendingRecordRead(source, rootTypes, 'timestamp') : null;
1610+
const read = rootTypes ? offendingRecordRead(source, rootTypes, 'timestamp', true) : null;
15921611
const named = read
15931612
? { field: read.field, root: read.root }
15941613
: { field: offendingField(source, fieldCelTypes, 'timestamp', scope) };

0 commit comments

Comments
 (0)