diff --git a/.changeset/33147-validate-expression-flow-condition-parity.md b/.changeset/33147-validate-expression-flow-condition-parity.md new file mode 100644 index 00000000000..a3227920f23 --- /dev/null +++ b/.changeset/33147-validate-expression-flow-condition-parity.md @@ -0,0 +1,32 @@ +--- +'@objectstack/mcp': patch +'@objectstack/lint': patch +'@object-ui/console': patch +--- + +fix(mcp): `validate_expression` gives the runtime publish gate's verdict at a `flow_condition`, and judges a formula-site expression as the field it is authored on + +Clause-②: yes (narrowing) — the MCP `validate_expression` tool now answers `ok: false` (or a warning) at a `flow_condition`, and for a named stored or formula field at a `formula` site, where the publish gate already refuses (or warns); and it accepts two new optional inputs, `startCondition` and `field`. The gate's acceptance set does not change. +Metadata-protocol: none + + + +**BREAKING** verdict narrowing of the MCP `validate_expression` tool (`@objectstack/mcp`), at `site: 'flow_condition'` and, given the new `field`, at `site: 'formula'`. + +At a flow condition the tool ran the shared expression validator and nothing else, so it answered `ok: true` for conditions the publish gate then refused when the flow was saved. It now also runs the gate's own passes there, through `judgeAuthoredSiteExpression` (`@objectstack/lint`), as the runtime publish gate judges a flow write, the door a flow saved through MCP or Studio meets: + +- an error on a record-triggered flow: a nullable field read as `record.FIELD` or `previous.FIELD` without a null guard (`record.days > 3` with `days` neither required nor defaulted), the run failing at the condition; +- a warning on any flow bound to an object: a read of an injected system column an external object has no storage behind (`record.owner_id` on an ADR-0015 `external` object). + +At a flow condition the verdict is that door's, not `os validate`'s: `os validate` also judges a bare name's null guard (`days > 3`) and a root the run does not bind, over the whole flow's variables, node ids and entrances, which the tool is not handed. The door itself also warns when a field is read bare under a name a flow variable shares; the tool is never handed the flow's variables, so it cannot give that warning. Write `record.FIELD` to be judged here. + +Two new optional inputs: + +- `startCondition` (`site: 'flow_condition'` only): the flow's start condition, for an edge or `decision` branch condition after it. What it proves non-null holds downstream, as at the gate, so `record.days > 3` after a start condition `record.days != null` is accepted. Omitted, the condition is judged as the start condition itself. +- `field` (`site: 'formula'` only, a snake_case field name): the field the expression is authored on. A field the caller is served keeps its definition with the expression in place: a stored field (any type but `formula`) gets the gate's stored-expression warnings (a read of another record, the clock, the acting user or a permission), and a formula field is refused when it would close a formula cycle. Any other name, a field masked from the caller included, is judged as a new formula field, so the answer never says whether a hidden field exists. A stored field that is not declared yet gets its stored-expression warnings once it is declared. + +Each finding is the gate's sentence, at the gate's severity. An expression the gate accepts answers exactly as before. A sentence that names the condition names it `flow 'this flow' · edge 'this condition' (start→end) condition`, since the tool is handed the condition and not the flow it will sit in. + +- `@objectstack/mcp`: the two inputs, the flow-condition judgment (it reads the subject's served definition alone there; nothing hydrates a hop at a flow condition), the tool description and the served `SKILL.md` line. +- `@objectstack/lint`: `judgeAuthoredSiteExpression` takes `site: 'flow_condition'` with `triggerKind`, `sweepObject` and `startCondition`, and `field` at `site: 'formula'`; exports `AUTHORED_FLOW_NAME`, `AUTHORED_CONDITION_ID` and the `AuthoredFlowTrigger` type. The gate's verdicts are unchanged. +- `@object-ui/console`: the downloadable `SKILL.md` mirror carries the same line. diff --git a/packages/lint/src/authored-site-expression.test.ts b/packages/lint/src/authored-site-expression.test.ts index 2bc8c3bc6dc..05de1a56095 100644 --- a/packages/lint/src/authored-site-expression.test.ts +++ b/packages/lint/src/authored-site-expression.test.ts @@ -11,14 +11,23 @@ import { describe, expect, it } from 'vitest'; // verdict reads that file too. import { maskComments, maskCommentsAndLiterals } from '../../../scripts/js-comment-mask.mjs'; +import { resolveFlowTriggerKind } from '@objectstack/spec/automation'; + import { + AUTHORED_CONDITION_ID, + AUTHORED_FLOW_NAME, AUTHORED_FORMULA_FIELD_NAME, AUTHORED_RULE_NAME, authoredExpressionHopTargets, + authoredFlowProbe, judgeAuthoredSiteExpression, type AuthoredExpressionSite, + type AuthoredFlowTrigger, } from './authored-site-expression.js'; -import { validateStackExpressions } from './validate-expressions.js'; +import { runStackExpressionPasses, validateStackExpressions } from './validate-expressions.js'; + +/** The two object-body sites; a flow condition has its own block below (#33147). */ +type ObjectSite = Exclude; /** * [#32872] `judgeAuthoredSiteExpression` is the publish gate's verdict on one @@ -91,7 +100,7 @@ function walkPushes(code: string): string[] { } /** The method names called on a receiver at each site, each plumbing: none of them judges an expression. */ -const SITE_MEMBER_CALLS: Record> = { +const SITE_MEMBER_CALLS: Record> = { validation: { get: 'a Map read (the object index, the field definitions)', indexOf: 'a string offset, reading the slot key', @@ -116,7 +125,7 @@ const WALK_PUSHES: Record = { }; /** The passes the walk pushes whole from INSIDE a site's regions: classified with that site's calls, in `SITE_CALLS`. */ -const WALK_PUSHES_IN_REGION: Record = { +const WALK_PUSHES_IN_REGION: Record = { formulaCycleIssues: 'formula', }; @@ -131,7 +140,7 @@ const CYCLE = { }; /** Where each site's calls are read: the rule loop and the `check` helper it calls; the field-formula pass and what follows the fields loop. */ -const SITE_REGIONS: Record> = { +const SITE_REGIONS: Record> = { validation: [ [' const check = (', ' const fieldRuleRootVerdict = ('], [' for (const rule of recordsOf(validations)) {', ' // Field-level formulas'], @@ -184,7 +193,7 @@ const BODY_HOP: Fixture = { objects: [REQ, BAL], expression: "record.meta.name = const ANCHOR: Fixture = { objects: [EXT], expression: "record.owner_id == 'u1'", severity: 'warning', names: 'owner_id' }; const asValue = (f: Fixture): Fixture => ({ ...f, expression: `${f.expression} ? 1 : 0` }); -const SITE_CALLS: Record> = { +const SITE_CALLS: Record> = { validation: { validateExpression: VALIDATOR, withAttachedBlocks: { kind: 'plumbing', why: 'the field list handed to the shared validator' }, @@ -216,24 +225,24 @@ const SITE_CALLS: Record> = { // finding on a cycle member's own `expression`; the probe is named // `__validate_expression__`, which no authored formula can read, so the // probe is never on a cycle and nothing is located on it, at the gate or - // through the entry. The cycle verdict on the formula being authored - // needs that field's own name, which `validate_expression` is not handed: - // the tool cannot give it (a follow-up, not this pin's to hide). + // through the entry. [#33147] The cycle verdict on the formula being + // authored needs that field's own name: given as `field`, the entry + // judges it under that name (the `field` block below pins it). formulaCycleIssues: { kind: 'pass-silent-here', - why: "locates each finding on a cycle member's own `expression`; the probe is on no cycle", + why: "locates each finding on a cycle member's own `expression`; the default probe is on no cycle (with `field`, see below)", fixture: { objects: [CYCLE], expression: 'record.f_x + record.days' }, }, storedExpressionInputIssues: { kind: 'pass-silent-here', - why: 'judges a STORED field\'s `expression` (any type but `formula`); the tool\'s formula site is a `formula` field', + why: 'judges a STORED field\'s `expression` (any type but `formula`); the default probe is a `formula` field (with `field` naming a stored one, see below)', fixture: { objects: [REQ, BAL], expression: 'record.balance.remaining > 1 ? now() : now()' }, }, }, }; /** The full gate's findings on the same rule or field, named as the entry names it. */ -function gateOn(site: AuthoredExpressionSite, objects: Array>, expression: string) { +function gateOn(site: ObjectSite, objects: Array>, expression: string) { const [subject, ...others] = objects as [Record, ...Array>]; const judged = site === 'validation' ? { ...subject, validations: [{ name: AUTHORED_RULE_NAME, type: 'script', condition: expression, message: 'm' }] } @@ -249,7 +258,7 @@ function gateOn(site: AuthoredExpressionSite, objects: Array [i.severity ?? 'error', i.message]); } -function entryOn(site: AuthoredExpressionSite, objects: Array>, expression: string) { +function entryOn(site: ObjectSite, objects: Array>, expression: string) { return judgeAuthoredSiteExpression({ site, objectName: 'obj', expression, objects }) .map((i) => [i.severity ?? 'error', i.message]); } @@ -409,3 +418,372 @@ describe('authoredExpressionHopTargets (#32872)', () => { expect(authoredExpressionHopTargets(REQ, 'record.title.size() > 1')).toEqual([]); }); }); + +// ── [#33147] A flow condition ──────────────────────────────────────────── +// +// The entry judges a flow condition as the runtime publish gate judges a flow +// write (`runtimeWriteType: 'flow'`): a one-flow probe whose start node +// carries the caller's trigger, with the condition on its one edge. The same +// two halves as above: every call the gate makes at a flow condition (the +// start node's trigger gate, a `decision` branch, an edge, and the helpers +// they hand the source to) is classified, and each pass refuses through the +// entry as the gate does on a hand-written flow. + +/** Where a flow condition's calls are read: the three slots, and the two helpers they hand the source to. */ +const FLOW_REGIONS: Array<[string, string]> = [ + [' const check = (', ' const fieldRuleRootVerdict = ('], + [' const checkDeclaredPredicate = (', ' const checkDeclaredValue = ('], + [' const nodeCondWhere = ', ' // Descriptor-declared expression slots'], + [" if (found.entry.role !== 'predicate') continue;", ' // [#19939] The `{…}` template dialect'], + [' for (const edge of recordsOf(graph.edges)) {', " // [#26858] A top-level edge's findings"], +]; + +const FLOW_MEMBER_CALLS: Record = { + get: 'a Map read (the object index, the field definitions)', + push: "appends a finding to the walk's list", + set: "records the judged slot's key for the node's key-path stamp", +}; + +/** A flow probe's slot, as the hand-written flows below place the condition. */ +type FlowSlot = 'start' | 'decision' | 'edge'; + +type FlowFixture = { + objects: Array>; + expression: string; + severity: 'error' | 'warning'; + names: string; +}; + +type FlowClassified = + | { kind: 'pass'; fixture: FlowFixture } + /** + * A pass the gate runs at a flow condition that the runtime publish gate's + * probe has nothing for. `buildDoor` is a fixture `os validate` does refuse + * or warn on, so the silence is the door's (or the missing input's), not a + * dead pass. + */ + | { kind: 'pass-silent-here'; why: string; fixture: Omit; buildDoor?: HandFlowOverrides } + | { kind: 'validator'; why: string } + | { kind: 'plumbing'; why: string }; + +type HandFlowOverrides = { variables?: Array> }; + +const FLOW_OBJ = { ...REQ, name: 'obj' }; +const FLOW_EXT = { ...EXT }; + +const FLOW_CALLS: Record = { + // The shared validator and the two envelope checks the tool runs itself + // (it parses the slot with `EvaluatedExpressionInputSchema` before it asks + // the gate, and a string is the only shape it is handed). + validateExpression: VALIDATOR, + checkStructuralCondition: { + kind: 'validator', + why: "the slot's envelope: the tool parses the same schema first and never asks the gate about a refused one", + }, + predicateSlotRefusal: { + kind: 'validator', + why: "a declared predicate slot's shape: the tool is handed a string, which that check admits", + }, + check: { kind: 'plumbing', why: 'the helper whose calls are the first region' }, + checkDeclaredPredicate: { kind: 'plumbing', why: "a `decision` branch's helper, the second region" }, + withAttachedBlocks: { kind: 'plumbing', why: 'the field list handed to the shared validator' }, + isBareReferenceToAny: { kind: 'plumbing', why: "filters the shared validator's findings on a field-rule slot" }, + checkFlowNullGuards: { + kind: 'pass', + fixture: { objects: [FLOW_OBJ], expression: 'record.days > 3', severity: 'error', names: 'record.days' }, + }, + warnUnprovisionedAnchors: { + kind: 'pass', + fixture: { objects: [FLOW_EXT], expression: "record.owner_id == 'u1'", severity: 'warning', names: 'owner_id' }, + }, + refuseUnboundRoots: { + kind: 'pass-silent-here', + why: "the runtime publish gate's root scope is never provable (its snapshot shows no entrance), so it judges no root; `os validate` does, over the flow's variables, node ids and entrances, which the tool is not handed", + fixture: { objects: [FLOW_OBJ], expression: 'foo.bar == 1' }, + buildDoor: {}, + }, + warnShadowedFieldReads: { + kind: 'pass-silent-here', + why: "needs the flow's declared variables, which the tool is not handed; the probe declares none", + fixture: { objects: [FLOW_OBJ], expression: "title == 'x'" }, + buildDoor: { variables: [{ name: 'title', type: 'text' }] }, + }, + refuseStoredMetadataBodyHop: { + kind: 'pass-silent-here', + why: 'runs only where a relationship hop is hydrated (a rule condition, a formula); nothing hydrates one at a flow condition', + fixture: { objects: [FLOW_OBJ, BAL], expression: "record.meta.name == 'x'" }, + }, + refuseUndeclaredHopField: { + kind: 'pass-silent-here', + why: 'runs only where a relationship hop is hydrated (a rule condition, a formula); nothing hydrates one at a flow condition', + fixture: { objects: [FLOW_OBJ, BAL], expression: 'record.balance.nope > 1' }, + }, +}; + +/** The start node of a hand-written flow on `obj`, with the trigger `kind` names. */ +function handStart(kind: AuthoredFlowTrigger, config: Record = {}): Record { + const trigger: Record> = { + record_change: { triggerType: 'record-after-create' }, + time_relative: { timeRelative: { object: 'obj', dateField: 'due', withinDays: 7 } }, + schedule: { schedule: '*/5 * * * *' }, + api: { triggerType: 'api' }, + none: {}, + }; + return { id: 'begin', type: 'start', config: { objectName: 'obj', ...trigger[kind], ...config } }; +} + +/** The `where` the hand-written flow's judged slot carries, as each gate sentence spells it. */ +const HAND_WHERE: Record = { + start: "flow 'escalate' · node 'begin' (start) condition", + decision: "flow 'escalate' · node 'triage' (decision) decision branch expression at config.conditions[0].expression", + edge: "flow 'escalate' · edge 'e2' (triage→alert) condition", +}; +const PROBE_WHERE = `flow '${AUTHORED_FLOW_NAME}' · edge '${AUTHORED_CONDITION_ID}' (start→end) condition`; + +/** + * A realistic flow the condition sits in at `slot`: a start node, a + * `decision`, two ends, three edges, and `startCondition` on the start node + * when the slot is downstream of it. + */ +function handFlow( + slot: FlowSlot, + expression: string, + { kind = 'record_change', startCondition, variables }: { kind?: AuthoredFlowTrigger; startCondition?: string } & HandFlowOverrides = {}, +): Record { + const startCond = slot === 'start' ? expression : startCondition; + return { + name: 'escalate', + label: 'Escalate', + type: kind === 'api' ? 'api' : 'autolaunched', + ...(variables ? { variables } : {}), + nodes: [ + handStart(kind, startCond !== undefined ? { condition: startCond } : {}), + { + id: 'triage', + type: 'decision', + config: { conditions: [{ label: 'Hot', expression: slot === 'decision' ? expression : 'true' }] }, + }, + { id: 'alert', type: 'end' }, + { id: 'calm', type: 'end' }, + ], + edges: [ + { id: 'e1', source: 'begin', target: 'triage' }, + { id: 'e2', source: 'triage', target: 'alert', ...(slot === 'edge' ? { condition: expression } : {}) }, + { id: 'e3', source: 'triage', target: 'calm', isDefault: true }, + ], + }; +} + +/** + * The gate's findings on the judged slot of the hand-written flow, the shared + * validator's left out (the tool answers those itself), with the slot's + * locator spelled as the probe's so the two read alike. + */ +function flowGateOn( + objects: Array>, + expression: string, + { slot = 'edge', door = 'runtime', ...rest }: { slot?: FlowSlot; door?: 'runtime' | 'build'; kind?: AuthoredFlowTrigger; startCondition?: string } & HandFlowOverrides = {}, +) { + const where = HAND_WHERE[slot]; + const issues = runStackExpressionPasses( + { objects, flows: [handFlow(slot, expression, rest)] }, + door === 'runtime' ? { runtimeWriteType: 'flow', sharedValidatorRunByCaller: true } : { sharedValidatorRunByCaller: true }, + ); + return issues + .filter((i) => i.where === where) + .map((i) => [i.severity ?? 'error', i.message.split(where).join(PROBE_WHERE)]); +} + +function flowEntryOn( + objects: Array>, + expression: string, + opts: { triggerKind?: AuthoredFlowTrigger; startCondition?: string } = {}, +) { + return judgeAuthoredSiteExpression({ site: 'flow_condition', objectName: 'obj', expression, objects, ...opts }) + .map((i) => [i.severity ?? 'error', i.message]); +} + +describe('judgeAuthoredSiteExpression at a flow condition — every gate pass is listed (#33147)', () => { + it('every call the gate makes at a flow condition is classified', () => { + const calls = bareCalls(FLOW_REGIONS.map(([start, end]) => region(start, end)).join('\n')); + expect(calls.length, 'the scan read nothing — the regions are vacuous').toBeGreaterThan(5); + expect(calls).toEqual(Object.keys(FLOW_CALLS).sort()); + }); + + it('every member call the gate makes at a flow condition is classified', () => { + const calls = memberCalls(FLOW_REGIONS.map(([start, end]) => region(start, end)).join('\n')); + expect(calls).toEqual(Object.keys(FLOW_MEMBER_CALLS).sort()); + }); + + for (const [name, classified] of Object.entries(FLOW_CALLS)) { + if (classified.kind === 'pass') { + const { objects, expression, severity, names } = classified.fixture; + for (const slot of ['start', 'decision', 'edge'] as const) { + it(`${name} refuses through the entry as the gate does at a flow's ${slot} condition`, () => { + const gate = flowGateOn(objects, expression, { slot }); + expect(gate.length, 'the fixture trips the gate').toBeGreaterThan(0); + const entry = flowEntryOn(objects, expression); + expect(entry).toEqual(gate); + expect(entry.map(([level]) => level)).toEqual(gate.map(() => severity)); + expect(entry.some(([, message]) => message!.includes(names))).toBe(true); + }); + } + } + if (classified.kind === 'pass-silent-here') { + const { objects, expression } = classified.fixture; + it(`${name} has nothing to say through the entry, as at the runtime publish gate`, () => { + expect(flowGateOn(objects, expression)).toEqual([]); + expect(flowEntryOn(objects, expression)).toEqual([]); + if (classified.buildDoor) { + // Non-vacuous: `os validate` speaks on the same condition, given what it reads. + expect(flowGateOn(objects, expression, { door: 'build', ...classified.buildDoor }).length).toBeGreaterThan(0); + } + }); + } + } + + it("a bare name's null guard is `os validate`'s, not the runtime publish gate's, and not the entry's", () => { + expect(flowGateOn([FLOW_OBJ], 'days > 3', { door: 'build' }).length).toBeGreaterThan(0); + expect(flowGateOn([FLOW_OBJ], 'days > 3')).toEqual([]); + expect(flowEntryOn([FLOW_OBJ], 'days > 3')).toEqual([]); + }); + + it('CONTROL — a clean condition answers nothing', () => { + for (const expression of ["record.title == 'x'", 'record.days != null && record.days > 3']) { + expect(flowGateOn([FLOW_OBJ], expression)).toEqual([]); + expect(flowEntryOn([FLOW_OBJ], expression)).toEqual([]); + } + }); + + it('a start probe and an edge probe answer alike when no start condition is given', () => { + for (const expression of ['record.days > 3', "record.title == 'x'", 'days > 3']) { + expect(flowGateOn([FLOW_OBJ], expression, { slot: 'start' })).toEqual(flowGateOn([FLOW_OBJ], expression, { slot: 'edge' })); + } + }); + + it('presumes what the start condition proves, as the gate does downstream of it', () => { + // Guarded at the start, the edge condition passes; unguarded, it is refused. + const guarded = { startCondition: 'record.days != null' }; + expect(flowGateOn([FLOW_OBJ], 'record.days > 3', guarded)).toEqual([]); + expect(flowEntryOn([FLOW_OBJ], 'record.days > 3', guarded)).toEqual([]); + expect(flowGateOn([FLOW_OBJ], 'record.days > 3', { slot: 'decision', ...guarded })).toEqual([]); + // A BARE start guard proves nothing at the runtime publish gate (its bound + // set is not provable), so the edge is still refused there and here. + const bare = { startCondition: 'days != null' }; + const refused = flowGateOn([FLOW_OBJ], 'record.days > 3', bare); + expect(refused.length).toBeGreaterThan(0); + expect(flowEntryOn([FLOW_OBJ], 'record.days > 3', bare)).toEqual(refused); + // The start condition's own findings are not the judged condition's. + expect(flowEntryOn([FLOW_OBJ], "record.title == 'x'", { startCondition: 'record.days > 3' })).toEqual([]); + }); + + it("the probe's trigger reads back as each kind, and each kind answers as the gate does", () => { + for (const kind of ['record_change', 'time_relative', 'schedule', 'api', 'none'] as const) { + const probe = authoredFlowProbe({ objectName: 'obj', expression: 'true', triggerKind: kind }); + expect(resolveFlowTriggerKind(probe) ?? 'none', kind).toBe(kind); + expect(resolveFlowTriggerKind(handFlow('edge', 'true', { kind })) ?? 'none', kind).toBe(kind); + for (const expression of ['record.days > 3', "record.owner_id == 'u1'"]) { + const objects = expression.includes('owner_id') ? [{ ...FLOW_EXT }] : [FLOW_OBJ]; + expect(flowEntryOn(objects, expression, { triggerKind: kind }), `${kind}: ${expression}`) + .toEqual(flowGateOn(objects, expression, { kind })); + } + } + // The null guard is a record-triggered flow's alone: another kind is not refused. + expect(flowEntryOn([FLOW_OBJ], 'record.days > 3', { triggerKind: 'schedule' })).toEqual([]); + }); + + it('judges a served definition (injected columns declared) as the authored body', () => { + const served = applyInjectedSystemColumns(FLOW_OBJ); + expect(flowEntryOn([served], "record.created_at > timestamp('2020-01-01T00:00:00Z')")).toEqual([]); + expect(flowEntryOn([served], 'record.days > 3')).toEqual(flowEntryOn([FLOW_OBJ], 'record.days > 3')); + expect(flowEntryOn([applyInjectedSystemColumns(FLOW_EXT)], "record.owner_id == 'u1'")) + .toEqual(flowEntryOn([FLOW_EXT], "record.owner_id == 'u1'")); + }); + + it("judges the caller's condition only, never the object's own rules or fields", () => { + const withOwn = { + ...FLOW_OBJ, + validations: [{ name: 'own', type: 'script', condition: 'record.days > 3', message: 'm' }], + fields: { ...FLOW_OBJ.fields, own_formula: { type: 'formula', label: 'Own', expression: 'record.balance.nope' } }, + }; + expect(flowEntryOn([withOwn, BAL], "record.title == 'x'")).toEqual([]); + }); + + it('answers nothing when the object is not among the definitions', () => { + expect(judgeAuthoredSiteExpression({ site: 'flow_condition', objectName: 'nope', expression: 'record.days > 3', objects: [FLOW_OBJ] })) + .toEqual([]); + }); +}); + +// ── [#33147] The field being authored, at the formula site ─────────────── +// +// Named as `field`, a field the definition declares keeps its definition with +// the expression in place: a stored field (any type but `formula`) is judged +// as stored, and a formula is judged on the object's formula graph under its +// own name. Any other name is a new `formula` field of that name. + +/** An object with a stored computed field (`stamp`) and a formula pair; `days` required. */ +const STORED = { + name: 'obj', + fields: { + ...REQ.fields, + stamp: { type: 'number', label: 'Stamp', expression: 'record.days' }, + f_x: { type: 'formula', label: 'X', expression: 'record.f_y + 1' }, + f_y: { type: 'formula', label: 'Y', expression: 'record.title.size()' }, + }, +}; + +/** The gate's findings on field `name` of `obj`, its expression replaced (the shared validator's left out). */ +function fieldGateOn(objects: Array>, name: string, expression: string) { + const [subject, ...others] = objects as [Record, ...Array>]; + const fields = Array.isArray(subject.fields) + ? subject.fields.map((f: Record) => (f.name === name ? { ...f, expression } : f)) + : { ...subject.fields, [name]: { ...subject.fields[name], expression } }; + const where = `object 'obj' · field '${name}' expression`; + return runStackExpressionPasses({ objects: [{ ...subject, fields }, ...others] }, { runtimeWriteType: 'object', sharedValidatorRunByCaller: true }) + .filter((i) => i.where === where) + .map((i) => [i.severity ?? 'error', i.message]); +} + +function fieldEntryOn(objects: Array>, expression: string, field?: string) { + return judgeAuthoredSiteExpression({ site: 'formula', objectName: 'obj', expression, objects, ...(field ? { field } : {}) }) + .map((i) => [i.severity ?? 'error', i.message]); +} + +describe('judgeAuthoredSiteExpression with the field being authored (#33147)', () => { + it("a declared stored field gets the gate's stored-expression warnings", () => { + for (const expression of ['record.balance.remaining + 1', 'record.days + (now() > now() ? 1 : 0)']) { + const gate = fieldGateOn([STORED, BAL], 'stamp', expression); + expect(gate.length, expression).toBeGreaterThan(0); + expect(gate.every(([level]) => level === 'warning')).toBe(true); + expect(fieldEntryOn([STORED, BAL], expression, 'stamp')).toEqual(gate); + // Without the field, the probe is a formula: nothing stored to warn on. + expect(fieldEntryOn([STORED, BAL], expression)).toEqual([]); + } + }); + + it('a declared formula is judged on the formula graph under its own name: the cycle it would close is refused', () => { + const gate = fieldGateOn([STORED], 'f_y', 'record.f_x + 1'); + expect(gate.length).toBeGreaterThan(0); + expect(gate.every(([level]) => level === 'error')).toBe(true); + expect(fieldEntryOn([STORED], 'record.f_x + 1', 'f_y')).toEqual(gate); + // The same expression on a field no formula reads closes no cycle. + expect(fieldEntryOn([STORED], 'record.f_x + 1', 'f_new')).toEqual([]); + expect(fieldEntryOn([STORED], 'record.f_x + 1')).toEqual([]); + }); + + it('reads an array-form field list the same way', () => { + const asArray = { ...STORED, fields: Object.entries(STORED.fields).map(([name, def]) => ({ name, ...def })) }; + expect(fieldEntryOn([asArray, BAL], 'record.balance.remaining + 1', 'stamp')) + .toEqual(fieldEntryOn([STORED, BAL], 'record.balance.remaining + 1', 'stamp')); + expect(fieldEntryOn([asArray], 'record.f_x + 1', 'f_y')).toEqual(fieldEntryOn([STORED], 'record.f_x + 1', 'f_y')); + }); + + it('a name the definition does not declare is judged as a new formula field, like no name at all', () => { + // So a field the caller is not served (masked, or absent) reads as one the + // object does not declare: the answer says nothing about whether it exists. + for (const expression of ['record.balance.remaining + 1', 'record.f_x + 1', "record.owner_id == 'u1' ? 1 : 0"]) { + expect(fieldEntryOn([STORED, BAL], expression, 'not_declared')).toEqual(fieldEntryOn([STORED, BAL], expression)); + } + }); +}); diff --git a/packages/lint/src/authored-site-expression.ts b/packages/lint/src/authored-site-expression.ts index 6221993d1dd..c4a664943c3 100644 --- a/packages/lint/src/authored-site-expression.ts +++ b/packages/lint/src/authored-site-expression.ts @@ -1,9 +1,10 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * [#32872] The publish gate's verdict on ONE authored expression, at the two + * [#32872] The publish gate's verdict on ONE authored expression, at the * sites the gate judges with passes of its own beyond the shared validator: a - * validation rule's `condition` and a formula field's `expression`. + * validation rule's `condition`, a formula field's `expression` and (#33147) a + * flow's condition. * * The MCP `validate_expression` tool promises "the verdict is the one the * publish gate gives that rule". It runs the shared validator @@ -24,10 +25,25 @@ * pass added to the gate at either site is carried by construction, and * `authored-site-expression.test.ts` lists each one so its refusal through * this entry is pinned. + * + * [#33147] A flow condition is judged the way the runtime publish gate judges + * a flow write (`runtimeWriteType: 'flow'`), the door an MCP or Studio write + * of the flow meets: the probe is a one-flow stack whose start node carries + * the trigger the caller names, and the condition sits on its one edge. That + * door gives the null guard on a `record.` / `previous.` read and the + * unprovisioned-anchor warning. It never judges a bare name's null guard or a + * root the run does not bind: those are `os validate`'s whole-flow judgments, + * over the flow's variables, node ids and entrances. The door does warn on a + * bare read of a name a flow variable shares with a field + * (`warnShadowedFieldReads`), but that needs the flow's declared variables, + * and the caller does not hand this entry any, so the probe declares none and + * that warning never fires here. So `[]` at a flow condition is that door's + * verdict, short of the shadowed-read warning, and not `os validate`'s. */ import { analyzeRelationshipTraversals } from '@objectstack/formula'; import { stripInjectedSystemColumns } from '@objectstack/metadata-core'; +import type { FlowTriggerKind } from '@objectstack/spec/automation'; import { referenceTargetOf } from '@objectstack/spec/data'; import { recordsOf } from './object-graph.js'; @@ -35,8 +51,16 @@ import { runStackExpressionPasses, type ExprIssue } from './validate-expressions type AnyRec = Record; -/** The two sites the gate judges with passes of its own, as `validate_expression` names them. */ -export type AuthoredExpressionSite = 'validation' | 'formula'; +/** The sites the gate judges with passes of its own, as `validate_expression` names them. */ +export type AuthoredExpressionSite = 'validation' | 'formula' | 'flow_condition'; + +/** + * [#33147] How the flow a condition sits on is started, as + * `resolveFlowTriggerKind` reads it off the flow, or `none` for a flow with + * no auto-launch trigger (a screen flow, a flow started by hand, an action or + * a parent flow). + */ +export type AuthoredFlowTrigger = FlowTriggerKind | 'none'; /** What {@link judgeAuthoredSiteExpression} judges. */ export interface AuthoredSiteExpression { @@ -47,6 +71,31 @@ export interface AuthoredSiteExpression { expression: string; /** site `validation` only: the rule's `severity` (the spec default is `error`). */ severity?: 'error' | 'warning' | 'info'; + /** + * [#33147] site `formula` only: the name of the field the expression is + * authored on. A field the subject's definition declares keeps its + * definition (its type above all) with this expression in place, so a + * stored field (any type but `formula`) is judged as stored and a formula + * is judged on the object's formula graph under its own name. A name the + * definition does not declare is judged as a new `formula` field of that + * name. Absent: a new formula field no authored formula can read. + */ + field?: string; + /** [#33147] site `flow_condition` only: how the flow is started. Default: `record_change`. */ + triggerKind?: AuthoredFlowTrigger; + /** + * [#33147] site `flow_condition` with `triggerKind` `time_relative` only: + * the flow's `timeRelative.object`. Default: `objectName`. + */ + sweepObject?: string; + /** + * [#33147] site `flow_condition` only: the flow's start condition, when the + * judged condition is an edge or a `decision` branch after it. The gate + * presumes what the start condition proves at every condition downstream, + * so a guard written there holds here. Absent: the judged condition is the + * start condition itself, or follows none (the gate answers both alike). + */ + startCondition?: string; /** * The object definitions as the registry serves them: the subject's, and * those of the objects its references name that the expression reads @@ -72,11 +121,81 @@ export interface AuthoredSiteExpression { export const AUTHORED_RULE_NAME = 'this rule'; /** - * The name the judged formula field carries. No sentence of the formula - * site names it; it is spelled so that no authored field can be it. + * The name the judged formula field carries when the caller names no field. + * No sentence of the formula site names it; it is spelled so that no authored + * field can be it. */ export const AUTHORED_FORMULA_FIELD_NAME = '__validate_expression__'; +/** + * [#33147] The names the probe flow carries. The gate's flow sentences name + * the slot they judge (`flow 'NAME' · edge 'ID' (start→end) condition`), so + * they read as the condition being authored. + */ +export const AUTHORED_FLOW_NAME = 'this flow'; +export const AUTHORED_CONDITION_ID = 'this condition'; + +/** [#33147] Where the probe flow's one edge sits, as the gate's findings spell its key path. */ +const AUTHORED_CONDITION_PATH = 'flows[0].edges[0].condition'; + +/** + * [#33147] The start node's trigger for each kind, spelled as + * `resolveFlowTriggerKind` reads it (`authored-site-expression.test.ts` reads + * each one back), with the flow `type` it needs. + */ +function probeTrigger( + triggerKind: AuthoredFlowTrigger, + objectName: string, + sweepObject: string | undefined, +): { type: string; config: AnyRec } { + switch (triggerKind) { + case 'record_change': + return { type: 'autolaunched', config: { triggerType: 'record-after-update' } }; + case 'time_relative': + return { type: 'autolaunched', config: { timeRelative: { object: sweepObject ?? objectName } } }; + case 'schedule': + return { type: 'schedule', config: { schedule: '0 * * * *' } }; + case 'api': + return { type: 'api', config: {} }; + case 'none': + return { type: 'autolaunched', config: {} }; + } +} + +/** + * [#33147] The flow the gate judges for one flow condition: a start node + * bound to `objectName` with the trigger the caller names (and its start + * condition, when given), and one edge to an end node carrying the + * condition. Exported for the read-back pin; the entry is its one caller. + */ +export function authoredFlowProbe({ + objectName, + expression, + triggerKind = 'record_change', + sweepObject, + startCondition, +}: Pick): AnyRec { + const trigger = probeTrigger(triggerKind, objectName, sweepObject); + return { + name: AUTHORED_FLOW_NAME, + label: AUTHORED_FLOW_NAME, + type: trigger.type, + nodes: [ + { + id: 'start', + type: 'start', + config: { + objectName, + ...trigger.config, + ...(startCondition !== undefined ? { condition: startCondition } : {}), + }, + }, + { id: 'end', type: 'end' }, + ], + edges: [{ id: AUTHORED_CONDITION_ID, source: 'start', target: 'end', condition: expression }], + }; +} + /** * The objects whose definitions {@link judgeAuthoredSiteExpression} needs * beyond the subject: the target of each reference field of `subject` that @@ -97,16 +216,20 @@ export function authoredExpressionHopTargets(subject: AnyRec, expression: string } /** - * The gate's findings on the one rule or formula field described, beyond the - * shared validator's: each the gate's own pass, in the gate's words, at the - * gate's severity. Empty when `objects` carries no definition of - * `objectName`. + * The gate's findings on the one rule, formula field or flow condition + * described, beyond the shared validator's: each the gate's own pass, in the + * gate's words, at the gate's severity. Empty when `objects` carries no + * definition of `objectName`. */ export function judgeAuthoredSiteExpression({ site, objectName, expression, severity, + field, + triggerKind, + sweepObject, + startCondition, objects, }: AuthoredSiteExpression): ExprIssue[] { const authored = objects.map((o) => stripInjectedSystemColumns(o)); @@ -114,34 +237,67 @@ export function judgeAuthoredSiteExpression({ if (!served) return []; const others = authored.filter((o) => o !== served && o?.name !== objectName); const { validations: _servedRules, ...body } = served; - const subject = site === 'validation' - ? { - ...body, - validations: [{ - name: AUTHORED_RULE_NAME, - type: 'script', - condition: expression, - message: AUTHORED_RULE_NAME, - ...(severity ? { severity } : {}), - }], - } - : { ...body, fields: withAuthoredFormulaField(body.fields, expression) }; - const issues = runStackExpressionPasses( - { objects: [subject, ...others] }, - { runtimeWriteType: 'object', sharedValidatorRunByCaller: true }, - ); - // Every finding of the validation-rule pass carries the judged slot's key - // path; the field-formula pass locates its findings on the field's key. - const rulePath = 'objects[0].validations[0].'; - const formulaWhere = `object '${objectName}' · field '${AUTHORED_FORMULA_FIELD_NAME}' expression`; - return issues.filter((issue) => - site === 'validation' ? issue.path?.startsWith(rulePath) === true : issue.where === formulaWhere, - ); + const fieldName = field ?? AUTHORED_FORMULA_FIELD_NAME; + // The stack the gate would judge, the write type of the door that judges + // it, and which of its findings are on the judged slot. + let stack: AnyRec; + let runtimeWriteType: 'object' | 'flow'; + let onSlot: (issue: ExprIssue) => boolean; + if (site === 'flow_condition') { + // [#33147] A flow write at the runtime publish gate: the walk judges the + // flow against the objects beside it, the subject among them, whose own + // rules are not what is judged here (left out, as at a validation site). + stack = { + objects: [body, ...others], + flows: [authoredFlowProbe({ objectName, expression, triggerKind, sweepObject, startCondition })], + }; + runtimeWriteType = 'flow'; + // Every finding on the probe's one edge carries that edge's key path. + onSlot = (issue) => issue.path === AUTHORED_CONDITION_PATH; + } else if (site === 'validation') { + const subject = { + ...body, + validations: [{ + name: AUTHORED_RULE_NAME, + type: 'script', + condition: expression, + message: AUTHORED_RULE_NAME, + ...(severity ? { severity } : {}), + }], + }; + stack = { objects: [subject, ...others] }; + runtimeWriteType = 'object'; + // Every finding of the validation-rule pass carries the judged slot's key path. + onSlot = (issue) => issue.path?.startsWith('objects[0].validations[0].') === true; + } else { + const subject = { ...body, fields: withAuthoredFormulaField(body.fields, fieldName, expression) }; + stack = { objects: [subject, ...others] }; + runtimeWriteType = 'object'; + // The field-formula pass (and the formula-cycle pass after it) locate + // their findings on the field's key. + const formulaWhere = `object '${objectName}' · field '${fieldName}' expression`; + onSlot = (issue) => issue.where === formulaWhere; + } + return runStackExpressionPasses(stack, { runtimeWriteType, sharedValidatorRunByCaller: true }).filter(onSlot); +} + +/** + * The served `fields`, in the shape they came in, with the judged field in + * place: [#33147] a field the body declares under `name` keeps its definition + * with `expression` written over it; any other name is added as a `formula`. + */ +function withAuthoredFormulaField(fields: unknown, name: string, expression: string): unknown { + const added = { type: 'formula', label: name, expression }; + if (Array.isArray(fields)) { + const at = fields.findIndex((f) => isRecord(f) && f.name === name); + if (at < 0) return [...fields, { name, ...added }]; + return fields.map((f, i) => (i === at ? { ...(f as AnyRec), expression } : f)); + } + const map = isRecord(fields) ? fields : {}; + const declared = Object.prototype.hasOwnProperty.call(map, name) && isRecord(map[name]) ? map[name] : undefined; + return { ...map, [name]: declared ? { ...declared, expression } : added }; } -/** The served `fields`, in the shape they came in, with the judged formula field added. */ -function withAuthoredFormulaField(fields: unknown, expression: string): unknown { - const field = { type: 'formula', label: AUTHORED_FORMULA_FIELD_NAME, expression }; - if (Array.isArray(fields)) return [...fields, { name: AUTHORED_FORMULA_FIELD_NAME, ...field }]; - return { ...(fields && typeof fields === 'object' ? fields : {}), [AUTHORED_FORMULA_FIELD_NAME]: field }; +function isRecord(v: unknown): v is AnyRec { + return !!v && typeof v === 'object' && !Array.isArray(v); } diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 036c2e3269d..dd377d8669c 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -75,15 +75,18 @@ export type { DatasetMeasureAggregateFinding, GroupKeyClass } from './validate-d export { validateStackExpressions, fieldRuleRootIssue, FIELD_RULE_BOUND_ROOTS } from './validate-expressions.js'; export type { ExprIssue } from './validate-expressions.js'; -// [#32872] The gate's verdict on one validation rule or formula field, the -// MCP `validate_expression` tool's second half (the shared validator is its first). +// [#32872] The gate's verdict on one validation rule, formula field or +// (#33147) flow condition, the MCP `validate_expression` tool's second half +// (the shared validator is its first). export { judgeAuthoredSiteExpression, authoredExpressionHopTargets, AUTHORED_RULE_NAME, AUTHORED_FORMULA_FIELD_NAME, + AUTHORED_FLOW_NAME, + AUTHORED_CONDITION_ID, } from './authored-site-expression.js'; -export type { AuthoredSiteExpression, AuthoredExpressionSite } from './authored-site-expression.js'; +export type { AuthoredSiteExpression, AuthoredExpressionSite, AuthoredFlowTrigger } from './authored-site-expression.js'; export { STORED_EXPRESSION_CROSS_RECORD_INPUT, STORED_EXPRESSION_VOLATILE_INPUT } from './stored-expression-inputs.js'; // #4763 — `has(x)` reads as a null guard and is not one. The decision procedure diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 14afb65c8bd..97e00242f58 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -92,8 +92,9 @@ import { type ExprFaultOutcome, type FieldRole, } from '@objectstack/formula'; -// [#32872] The publish gate's own passes at a validation rule and a formula -// field, run over the served definitions (see `VALIDATE_SITE_MAP.gatePasses`). +// [#32872] The publish gate's own passes at a validation rule, a formula +// field and (#33147) a flow condition, run over the served definitions (see +// `VALIDATE_SITE_MAP.gatePasses`). // [#32872] Types only: the entry itself is loaded lazily, in `gatePassFindings`. import type { AuthoredExpressionSite } from '@objectstack/lint'; // [#16913] The unknown-key error map every `strictToolInput` shape below is @@ -1749,10 +1750,17 @@ function jsonText(value: unknown): string { * `@objectstack/lint`'s walk. There the tool asks the gate itself * (`judgeAuthoredSiteExpression`) over the served definitions * (`McpDataBridge.servedObjectDefinitionOf`) and adds its findings to the - * validator's. A flow condition and a template are not judged by this: the - * gate's own passes there (the unprovisioned-anchor warning on an - * object-bound flow predicate, the null-guard gate on a record-triggered - * flow's conditions) are not run by the tool. + * validator's. A template is not judged by this. + * + * [#33147] A flow condition is judged too, as the runtime publish gate judges + * a flow write (the door an MCP or Studio write of the flow meets): the + * null-guard gate on a record-triggered flow's `record.` / `previous.` reads + * and the unprovisioned-anchor warning. A bare name's null guard and a root + * the run does not bind are `os validate`'s whole-flow judgments, over the + * flow's variables, node ids and entrances; that door does not give them, and + * neither does the tool. The door does warn on a bare read of a name a flow + * variable shares with a field, but the tool is never handed the flow's + * variables, so it cannot give that warning. */ const VALIDATE_SITE_MAP: Record< string, @@ -1803,6 +1811,7 @@ const VALIDATE_SITE_MAP: Record< // gate's `type-mismatch-run-may-fail` warning. flow_condition: { role: 'predicate', scope: 'flattened', slot: EvaluatedExpressionInputSchema, + gatePasses: 'flow_condition', faultOutcome: ({ triggerKind, sweepsTypedObject }) => (triggerKind === 'record_change' || (triggerKind === 'time_relative' && sweepsTypedObject) ? 'run-fails' : undefined), }, @@ -1818,12 +1827,33 @@ interface GatePassFinding { const NO_GATE_PASS_FINDINGS: { errors: GatePassFinding[]; warnings: GatePassFinding[] } = { errors: [], warnings: [] }; /** - * [#32872] The publish gate's findings at a `validation` / `formula` site - * beyond the shared validator's, judged by `@objectstack/lint`'s - * `judgeAuthoredSiteExpression` over the definitions the caller is served: - * the subject's, and each object the expression reads through. A bridge - * without `servedObjectDefinitionOf`, or an object it does not serve, adds - * none; a target it does not serve is not judged, as at the gate. + * [#33147] What the caller says about where the expression sits, beyond the + * site: the field being authored (formula), and how the flow is started and + * what its start condition proves (flow condition). Each is handed to the + * gate as given; the handler refuses one on a site it does not describe. + */ +interface GatePassContext { + severity?: ValidationSeverity; + field?: string; + triggerKind?: FlowTriggerOrNone; + sweepObject?: string; + startCondition?: string; +} + +/** + * [#32872] The publish gate's findings at a `validation` / `formula` / + * (#33147) `flow_condition` site beyond the shared validator's, judged by + * `@objectstack/lint`'s `judgeAuthoredSiteExpression` over the definitions + * the caller is served: the subject's, and at a rule or formula each object + * the expression reads through (nothing hydrates a hop at a flow condition, + * so no target is read there). A bridge without `servedObjectDefinitionOf`, + * or an object it does not serve, adds none; a target it does not serve is + * not judged, as at the gate. + * + * [#33147] The field being authored resolves through the same served + * definition, and nothing else: a field the caller is not served reads as + * one the object does not declare, so the answer never says whether it + * exists. * * A hop target follows the same system-object fence as `describe_object`: * `exposed` is the tool's object-name guard, and a target it refuses is @@ -1840,23 +1870,29 @@ async function gatePassFindings( site: AuthoredExpressionSite, objectName: string, expression: string, - severity: ValidationSeverity | undefined, + context: GatePassContext, ): Promise<{ errors: GatePassFinding[]; warnings: GatePassFinding[] }> { if (!bridge.servedObjectDefinitionOf) return NO_GATE_PASS_FINDINGS; const subject = await bridge.servedObjectDefinitionOf(objectName); if (!subject) return NO_GATE_PASS_FINDINGS; const { authoredExpressionHopTargets, judgeAuthoredSiteExpression } = await import('@objectstack/lint'); const targets: Array> = []; - for (const target of authoredExpressionHopTargets(subject, expression)) { + const hops = site === 'flow_condition' ? [] : authoredExpressionHopTargets(subject, expression); + for (const target of hops) { if (target === objectName || !exposed(target)) continue; const def = await bridge.servedObjectDefinitionOf(target); if (def) targets.push(def); } + const { severity, field, triggerKind, sweepObject, startCondition } = context; const findings = judgeAuthoredSiteExpression({ site, objectName, expression, ...(severity ? { severity } : {}), + ...(field !== undefined ? { field } : {}), + ...(triggerKind ? { triggerKind } : {}), + ...(sweepObject !== undefined ? { sweepObject } : {}), + ...(startCondition !== undefined ? { startCondition } : {}), objects: [subject, ...targets], }); const errors: GatePassFinding[] = []; @@ -2437,18 +2473,25 @@ export function registerObjectTools( 'build-time errors (bare field refs, unknown fields, unknown functions; at a `formula` or `validation` site, every ' + 'other refusal the publish gate gives there: a reference field read both through the relationship and as a plain ' + 'value, more than one hop, a hop to a field the target does not declare or into a stored-metadata table, and at a ' + - '`validation` site an unguarded nullable field or a read of `parent`) and advisory warnings ' + + '`validation` site an unguarded nullable field or a read of `parent`; at a `flow_condition` of a record-triggered ' + + 'flow, an unguarded nullable `record.`/`previous.` read) and advisory warnings ' + '(text/boolean fields misused in arithmetic, an error at a `validation` site, worded for the rule\'s ' + '`severity`, and at a `flow_condition` of a record-triggered or time-relative flow, where it fails the run; ' + - 'a warning on any other flow; date-equality pitfalls; at a `formula` or `validation` site, a read of an ' + - 'external object\'s unprovisioned system column), plus the fields and stdlib ' + + 'a warning on any other flow; date-equality pitfalls; at a `formula`, `validation` or `flow_condition` site, a read ' + + 'of an external object\'s unprovisioned system column; at a `formula` site naming a stored (non-formula) `field`, ' + + 'a read of another record, the clock, the user or a permission), plus the fields and stdlib ' + 'functions in scope so you can self-correct. A hop target follows the same system-object fence as ' + '`describe_object`. `site` says where the expression will live: a `formula` ' + - 'field, a `validation`/predicate, or a `flow_condition` (fields are bound bare in flow conditions). ' + + 'field, a `validation`/predicate, or a `flow_condition` (read fields as `record.` there too). ' + 'Pass the rule\'s `severity` (validation) or the flow\'s `triggerKind` (flow_condition), so the verdict is ' + 'the one the publish gate gives that rule or flow. A time-relative flow\'s conditions read a row of the object ' + 'its sweep scans (`timeRelative.object`): pass that object as objectName. A start whose objectName names ' + - 'another object is refused at publish (`flow-time-relative-object-mismatch`).', + 'another object is refused at publish (`flow-time-relative-object-mismatch`). At a `flow_condition` the verdict ' + + 'is the runtime publish gate\'s, which a flow saved through MCP or Studio meets: `os validate` also judges a ' + + 'bare name\'s null guard and unbound roots over the whole flow, which this tool is not handed, so write ' + + '`record.` to be judged here. Pass `field` (formula) to be judged as that field: its type, and the ' + + 'formula cycle it would close; a field not yet declared is judged as a new formula, so a new stored field gets ' + + 'its stored-expression warnings only once it is declared.', inputSchema: strictToolInput( { surface: 'this validate_expression call', @@ -2467,7 +2510,7 @@ export function registerObjectTools( .enum(['formula', 'validation', 'flow_condition', 'template']) .optional() .describe( - 'Where the expression will live. formula/validation bind `record.`; flow_condition binds fields bare. Default: formula.', + 'Where the expression will live. Every site reads fields as `record.`; a bare field name also resolves in a flow_condition, but this tool cannot judge its null guard there. Default: formula.', ), severity: z .enum(VALIDATION_SEVERITIES) @@ -2495,11 +2538,30 @@ export function registerObjectTools( '(`flow-time-relative-object-mismatch`); passed with another objectName, the verdict is the gate\'s ' + 'advisory one for such a flow, a type mismatch warning. Default: objectName.', ), + // [#33147] The two facts the gate reads off the item the expression + // sits on that `site` does not carry. + startCondition: z + .string() + .optional() + .describe( + 'site flow_condition only: the flow\'s start condition, when the expression is an edge or `decision` ' + + 'branch condition after it. What it proves non-null holds downstream, as at publish. Omit it when ' + + 'the expression is the start condition itself.', + ), + field: z + .string() + .regex(/^[a-z_][a-z0-9_]*$/, 'a field name is snake_case, e.g. "due_in_days"') + .optional() + .describe( + 'site formula only: the name of the field the expression is authored on. A declared field is judged ' + + 'as it is declared: a stored (non-formula) field gets the stored-expression warnings, and a formula ' + + 'the cycle it would close. Any other name is judged as a new formula field.', + ), }, ), annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, }, - async ({ objectName, expression, site, severity, triggerKind, sweepObject }) => { + async ({ objectName, expression, site, severity, triggerKind, sweepObject, startCondition, field }) => { const bad = guard(objectName); if (bad) return errorResult(bad); // [#29959] Each input describes one site; on another it would be @@ -2517,6 +2579,13 @@ export function registerObjectTools( `"time_relative", not site "${site ?? 'formula'}" with triggerKind "${triggerKind ?? 'record_change'}".`, ); } + // [#33147] The flow's start condition describes a flow; the field, a formula's. + if (startCondition !== undefined && site !== 'flow_condition') { + return errorResult(`\`startCondition\` describes a flow; it applies only with site "flow_condition", not "${site ?? 'formula'}".`); + } + if (field !== undefined && (site ?? 'formula') !== 'formula') { + return errorResult(`\`field\` names the field a formula is authored on; it applies only with site "formula", not "${site}".`); + } try { const def = (await bridge.describeObject(objectName)) as { fields?: unknown } | null; if (!def) return errorResult(`Object "${objectName}" not found`); @@ -2570,10 +2639,17 @@ export function registerObjectTools( })), warnings: [], }; - // [#32872] …and, at a validation rule or a formula field, every other - // pass the gate runs there, in the gate's own words. + // [#32872] …and, at a validation rule, a formula field or (#33147) a + // flow condition, every other pass the gate runs there, in the + // gate's own words. const gate = slotParse.success && gatePasses - ? await gatePassFindings(bridge, (name) => guard(name) === undefined, gatePasses, objectName, expression, severity) + ? await gatePassFindings(bridge, (name) => guard(name) === undefined, gatePasses, objectName, expression, { + severity, + field, + triggerKind, + sweepObject, + startCondition, + }) : NO_GATE_PASS_FINDINGS; const inScope = introspectScope(role, hint); const inferredType = diff --git a/packages/mcp/src/mcp-validate-expression.test.ts b/packages/mcp/src/mcp-validate-expression.test.ts index ab0d3d141d1..1c826bbcc94 100644 --- a/packages/mcp/src/mcp-validate-expression.test.ts +++ b/packages/mcp/src/mcp-validate-expression.test.ts @@ -7,7 +7,13 @@ import { TYPED_EXPRESSION_SOURCE_REQUIRED, } from '@objectstack/spec/shared'; -import { AUTHORED_FORMULA_FIELD_NAME, AUTHORED_RULE_NAME, validateStackExpressions } from '@objectstack/lint'; +import { + AUTHORED_CONDITION_ID, + AUTHORED_FLOW_NAME, + AUTHORED_FORMULA_FIELD_NAME, + AUTHORED_RULE_NAME, + validateStackExpressions, +} from '@objectstack/lint'; import { applyInjectedSystemColumns } from '@objectstack/metadata-core'; @@ -226,6 +232,12 @@ describe('validate_expression MCP tool (#1928)', () => { { site: 'flow_condition', triggerKind: 'record_change', sweepObject: 'crm_task' }, { site: 'validation', sweepObject: 'crm_task' }, { sweepObject: 'crm_task' }, + // [#33147] The start condition describes a flow; the field, a formula's. + { site: 'validation', startCondition: 'true' }, + { startCondition: 'true' }, + { site: 'validation', field: 'title' }, + { site: 'flow_condition', field: 'title' }, + { site: 'template', field: 'title' }, ]) { const { json } = await call(runtime, toolsCall(1, 'validate_expression', { objectName: 'crm_opportunity', expression: 'record.title > 5', ...args }), bridge); const { result } = json as { result: { isError?: boolean; content: { text: string }[] } }; @@ -620,9 +632,219 @@ describe("validate_expression answers the gate's own passes at validation and fo expect(recordCalls).toEqual([]); }); - it('does not judge a flow condition or a template: no definition is read there', async () => { - await validate(runtime, gateBridge(), { objectName: 'gp_req', expression: 'days > 3', site: 'flow_condition' }); + it('does not judge a template: no definition is read there', async () => { await validate(runtime, gateBridge(), { objectName: 'gp_req', expression: '{{record.title}}', site: 'template' }); expect(reads).toEqual([]); }); + + // [#33147] Nothing hydrates a hop at a flow condition, so no target is read. + it('reads the subject alone at a flow condition, whatever it reads through', async () => { + await validate(runtime, gateBridge(), { objectName: 'gp_req', expression: 'record.balance.nope > 1', site: 'flow_condition' }); + expect(reads).toEqual(['gp_req']); + expect(recordCalls).toEqual([]); + }); + + // ── [#33147] A flow condition, as the runtime publish gate judges a flow write ── + + /** + * The gate's verdicts on the same condition in a record-triggered flow on + * `objectName` (or the trigger `kind` names), on its one edge after the + * start node (carrying `startCondition`), its locator spelled as the + * tool's probe spells it. + */ + const flowGateOn = ( + objectName: string, + expression: string, + { kind = 'record', startCondition }: { kind?: 'record' | 'schedule'; startCondition?: string } = {}, + ) => { + const { validations: _own, ...subject } = OBJECTS[objectName]!; + const others = Object.keys(OBJECTS).filter((n) => n !== objectName).map((n) => OBJECTS[n]!); + const trigger = kind === 'record' ? { triggerType: 'record-after-update' } : { schedule: '0 * * * *' }; + const where = "flow 'g' · edge 'e1' (start→end) condition"; + const probe = `flow '${AUTHORED_FLOW_NAME}' · edge '${AUTHORED_CONDITION_ID}' (start→end) condition`; + return validateStackExpressions({ + objects: [subject, ...others], + flows: [{ + name: 'g', + type: 'autolaunched', + nodes: [ + { + id: 'start', + type: 'start', + config: { objectName, ...trigger, ...(startCondition !== undefined ? { condition: startCondition } : {}) }, + }, + { id: 'end', type: 'end' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end', condition: expression }], + }], + }) + .filter((i) => i.where === where) + .map((i) => [i.severity ?? 'error', i.message.split(where).join(probe)]); + }; + + // [member, object, condition, severity, the subject the finding names] + const FLOW_MEMBERS: Array<[string, string, string, 'error' | 'warning', string]> = [ + ['null-guard gate on a record-triggered flow', 'gp_req', 'record.days > 3', 'error', 'record.days'], + ['null-guard gate on `previous`', 'gp_req', 'previous.days > 3', 'error', 'previous.days'], + ['unprovisioned anchor (warning)', 'gp_ext', "record.owner_id == 'u1'", 'warning', 'owner_id'], + ]; + + for (const [member, objectName, expression, severity, names] of FLOW_MEMBERS) { + it(`site flow_condition: ${member} — the tool gives the gate's verdict`, async () => { + const gate = flowGateOn(objectName, expression); + expect(gate.map(([level]) => level)).toEqual([severity]); + const r = await validate(runtime, gateBridge(), { objectName, expression, site: 'flow_condition' }); + expect(r.ok).toBe(severity !== 'error'); + expect(sorted(verdicts(r))).toEqual(sorted(gate)); + expect(verdicts(r).some(([, message]) => message!.includes(names))).toBe(true); + // Before: the definition-less bridge, the shared validator alone, answered ok. + const before = await validate(runtime, gateBridge(false), { objectName, expression, site: 'flow_condition' }); + expect([before.ok, before.errors, before.warnings]).toEqual([true, [], []]); + }); + } + + it("site flow_condition: a bare name's null guard is os validate's, so the tool answers as before", async () => { + // `os validate` refuses it on a flow whose bindings it can see; the + // runtime publish gate cannot see them and does not, nor does the tool. + expect(flowGateOn('gp_req', 'days > 3').map(([level]) => level)).toEqual(['error']); + const args = { objectName: 'gp_req', expression: 'days > 3', site: 'flow_condition' }; + expect(await validate(runtime, gateBridge(), args)).toEqual(await validate(runtime, gateBridge(false), args)); + }); + + it('site flow_condition: a start condition that guards the read is honoured, as downstream of it at the gate', async () => { + const args = { objectName: 'gp_req', expression: 'record.days > 3', site: 'flow_condition' }; + const startCondition = 'record.days != null'; + expect(flowGateOn('gp_req', args.expression, { startCondition })).toEqual([]); + const guarded = await validate(runtime, gateBridge(), { ...args, startCondition }); + expect([guarded.ok, guarded.errors, guarded.warnings]).toEqual([true, [], []]); + // The start condition's own findings are not this condition's. + const clean = await validate(runtime, gateBridge(), { ...args, expression: "record.title == 'x'", startCondition: 'record.days > 3' }); + expect([clean.ok, clean.errors, clean.warnings]).toEqual([true, [], []]); + }); + + it('site flow_condition: the null guard is a record-triggered flow\'s alone', async () => { + // (`os validate` refuses this flow's `record` root, unbound on a schedule + // run; that is a whole-flow judgment the runtime publish gate leaves, so + // only the null-guard sentence is read here.) + const nullGuard = ([, message]: unknown[]) => String(message).includes('declares as nullable'); + expect(flowGateOn('gp_req', 'record.days > 3').filter(nullGuard)).toHaveLength(1); + expect(flowGateOn('gp_req', 'record.days > 3', { kind: 'schedule' }).filter(nullGuard)).toEqual([]); + const r = await validate(runtime, gateBridge(), { objectName: 'gp_req', expression: 'record.days > 3', site: 'flow_condition', triggerKind: 'schedule' }); + expect([r.ok, r.errors, r.warnings]).toEqual([true, [], []]); + }); + + it('site flow_condition: CONTROL — a clean condition answers as the definition-less bridge does', async () => { + for (const expression of ["record.title == 'x'", 'record.days != null && record.days > 3', "title == 'x'"]) { + expect(flowGateOn('gp_req', expression)).toEqual([]); + const args = { objectName: 'gp_req', expression, site: 'flow_condition' }; + const withGate = await validate(runtime, gateBridge(), args); + expect([withGate.errors, withGate.warnings], expression).toEqual([[], []]); + expect(withGate).toEqual(await validate(runtime, gateBridge(false), args)); + } + }); +}); + +// [#33147] The field a formula-site expression is authored on (`field`). A +// field the caller is served keeps its definition with the expression in +// place: a stored field gets the gate's stored-expression warnings, and a +// formula the cycle it would close. It resolves only through the definition +// the caller is served, so a field masked from the caller answers exactly as +// one the object does not declare. +describe('validate_expression judges the field being authored at the formula site (#33147)', () => { + const STORED: Record = { + name: 'gp_stored', + fields: { + days: { type: 'number', label: 'Days', required: true }, + balance: { type: 'lookup', label: 'Balance', reference: 'gp_target' }, + stamp: { type: 'number', label: 'Stamp', expression: 'record.days' }, + f_x: { type: 'formula', label: 'X', expression: 'record.f_y + 1' }, + f_y: { type: 'formula', label: 'Y', expression: 'record.days * 2' }, + secret: { type: 'number', label: 'Secret', expression: 'record.days' }, + }, + }; + const TARGET = { name: 'gp_target', fields: { remaining: { type: 'number', label: 'Remaining', required: true } } }; + const OBJECTS: Record> = { gp_stored: STORED, gp_target: TARGET }; + /** As the caller is served it: `secret` is masked from this caller (ADR-0106 D1), at both reads. */ + const served = (name: string) => { + const def = OBJECTS[name]; + if (!def) return null; + const { secret: _masked, ...fields } = def.fields; + return applyInjectedSystemColumns({ ...def, fields }); + }; + const bridge = (): McpDataBridge => ({ + ...makeBridge(), + async listObjects() { + return Object.keys(OBJECTS).map((name) => ({ name })); + }, + async describeObject(name: string) { + const def = served(name); + if (!def) return null; + return { name, fields: Object.entries(def.fields).map(([n, f]) => ({ name: n, ...(f as object) })) }; + }, + async servedObjectDefinitionOf(name: string) { + return served(name); + }, + }); + const verdicts = (r: { errors: { message: string }[]; warnings: { message: string }[] }) => [ + ...r.errors.map((e) => ['error', e.message]), + ...r.warnings.map((w) => ['warning', w.message]), + ]; + /** The gate's verdicts on field `name` of `gp_stored` with `expression` in place. */ + const gateOn = (name: string, expression: string) => { + const where = `object 'gp_stored' · field '${name}' expression`; + return validateStackExpressions({ + objects: [{ ...STORED, fields: { ...STORED.fields, [name]: { ...STORED.fields[name], expression } } }, TARGET], + }) + .filter((i) => i.where === where) + .map((i) => [i.severity ?? 'error', i.message]); + }; + + let runtime: MCPServerRuntime; + beforeEach(() => { + runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' }); + }); + + it("a stored field gets the gate's stored-expression warnings, where the formula probe gets none", async () => { + for (const expression of ['record.balance.remaining + 1', 'record.days + (now() > now() ? 1 : 0)']) { + const gate = gateOn('stamp', expression); + expect(gate.length, expression).toBeGreaterThan(0); + expect(gate.every(([level]) => level === 'warning'), expression).toBe(true); + const r = await validate(runtime, bridge(), { objectName: 'gp_stored', expression, site: 'formula', field: 'stamp' }); + expect(r.ok).toBe(true); + expect(r.warnings.map((w: { message: string }) => ['warning', w.message])).toEqual(gate); + const unnamed = await validate(runtime, bridge(), { objectName: 'gp_stored', expression, site: 'formula' }); + expect([unnamed.errors, unnamed.warnings], expression).toEqual([[], []]); + } + }); + + it('a formula is judged under its own name: the cycle it would close is refused', async () => { + const expression = 'record.f_x + 1'; + const gate = gateOn('f_y', expression); + expect(gate.map(([level]) => level)).toEqual(['error']); + const r = await validate(runtime, bridge(), { objectName: 'gp_stored', expression, site: 'formula', field: 'f_y' }); + expect(r.ok).toBe(false); + expect(verdicts(r)).toEqual(gate); + const unnamed = await validate(runtime, bridge(), { objectName: 'gp_stored', expression, site: 'formula' }); + expect([unnamed.ok, unnamed.errors, unnamed.warnings]).toEqual([true, [], []]); + }); + + it('a field masked from the caller answers exactly as a field the object does not declare', async () => { + for (const expression of ['record.balance.remaining + 1', 'record.days + (now() > now() ? 1 : 0)', 'record.f_x + 1']) { + const args = { objectName: 'gp_stored', expression, site: 'formula' }; + const hidden = await validate(runtime, bridge(), { ...args, field: 'secret' }); + const absent = await validate(runtime, bridge(), { ...args, field: 'not_declared' }); + expect(hidden, expression).toEqual(absent); + // …and both read as a new formula field: what no field name answers. + expect(hidden, expression).toEqual(await validate(runtime, bridge(), args)); + } + }); + + it('refuses a field name that is not a field name', async () => { + const { json } = await call( + runtime, + toolsCall(1, 'validate_expression', { objectName: 'gp_stored', expression: 'record.days', site: 'formula', field: 'Bad Name' }), + bridge(), + ); + expect((json as { result: { isError?: boolean } }).result.isError).toBe(true); + }); }); diff --git a/packages/mcp/src/skill-md.ts b/packages/mcp/src/skill-md.ts index 040382577c8..96172b74c5a 100644 --- a/packages/mcp/src/skill-md.ts +++ b/packages/mcp/src/skill-md.ts @@ -402,19 +402,23 @@ create/update payload. - **list_objects()** — list available objects (system \`sys_*\` objects are hidden). - **describe_object({ objectName })** — an object's fields and features. -- **validate_expression({ objectName, expression, site?, severity?, triggerKind?, sweepObject? })** — check a CEL +- **validate_expression({ objectName, expression, site?, severity?, triggerKind?, sweepObject?, startCondition?, field? })** — check a CEL expression against an object's schema *before* you author it into a formula, validation, or flow condition. Returns build-time errors (bare field refs, unknown fields/functions; at a \`formula\` or \`validation\` site, every other refusal the publish gate gives there: a reference read both through the relationship and as a value, more than one hop, a hop to a field the target does not declare or into a stored-metadata table, and at a \`validation\` site - an unguarded nullable field or a read of \`parent\`) and advisory warnings + an unguarded nullable field or a read of \`parent\`; at a \`flow_condition\` + of a record-triggered flow, an unguarded nullable \`record.\`/\`previous.\` + read) and advisory warnings (text/boolean fields misused in arithmetic; an error at a \`validation\` site, worded for the rule's \`severity\`, and at a \`flow_condition\` of a record-triggered or time-relative flow, where it fails the run; a warning on - any other flow; at a \`formula\` or \`validation\` site, a read of an - external object's unprovisioned system column), plus the fields and stdlib + any other flow; at a \`formula\`, \`validation\` or \`flow_condition\` site, + a read of an external object's unprovisioned system column; for a stored + (non-formula) \`field\`, a read of another record, the clock, the user or a + permission), plus the fields and stdlib functions in scope. A hop target follows the same system-object fence as \`describe_object\`. \`site\` is \`formula\` | \`validation\` | \`flow_condition\` | \`template\` (default \`formula\`). Pass the rule's @@ -424,6 +428,12 @@ create/update payload. as \`objectName\`: its conditions read rows of that object, and a start whose \`objectName\` names another object is refused at publish (\`flow-time-relative-object-mismatch\`). \`sweepObject\` names that same object. + At a \`flow_condition\` the verdict is the runtime publish gate's, the one a + flow saved through MCP meets: \`os validate\` also judges bare names and + unbound roots over the whole flow, so write \`record.\`, and pass the + flow's \`startCondition\` for an edge or \`decision\` condition after it. Pass + \`field\` (formula) to be judged as that field: its type, and the formula + cycle it would close; a field not yet declared is judged as a new formula. - **query_records({ objectName, where?, fields?, limit?, offset?, orderBy? })** — read records. \`where\` is a field→value match, e.g. \`{ "status": "open" }\`. Results are page-capped; use \`limit\`/\`offset\` to page. diff --git a/ui/apps/console/src/pages/developer/objectstack-skill.ts b/ui/apps/console/src/pages/developer/objectstack-skill.ts index 9425e4316b8..76d88015723 100644 --- a/ui/apps/console/src/pages/developer/objectstack-skill.ts +++ b/ui/apps/console/src/pages/developer/objectstack-skill.ts @@ -130,19 +130,23 @@ create/update payload. - **list_objects()** — list available objects (system \`sys_*\` objects are hidden). - **describe_object({ objectName })** — an object's fields and features. -- **validate_expression({ objectName, expression, site?, severity?, triggerKind?, sweepObject? })** — check a CEL +- **validate_expression({ objectName, expression, site?, severity?, triggerKind?, sweepObject?, startCondition?, field? })** — check a CEL expression against an object's schema *before* you author it into a formula, validation, or flow condition. Returns build-time errors (bare field refs, unknown fields/functions; at a \`formula\` or \`validation\` site, every other refusal the publish gate gives there: a reference read both through the relationship and as a value, more than one hop, a hop to a field the target does not declare or into a stored-metadata table, and at a \`validation\` site - an unguarded nullable field or a read of \`parent\`) and advisory warnings + an unguarded nullable field or a read of \`parent\`; at a \`flow_condition\` + of a record-triggered flow, an unguarded nullable \`record.\`/\`previous.\` + read) and advisory warnings (text/boolean fields misused in arithmetic; an error at a \`validation\` site, worded for the rule's \`severity\`, and at a \`flow_condition\` of a record-triggered or time-relative flow, where it fails the run; a warning on - any other flow; at a \`formula\` or \`validation\` site, a read of an - external object's unprovisioned system column), plus the fields and stdlib + any other flow; at a \`formula\`, \`validation\` or \`flow_condition\` site, + a read of an external object's unprovisioned system column; for a stored + (non-formula) \`field\`, a read of another record, the clock, the user or a + permission), plus the fields and stdlib functions in scope. A hop target follows the same system-object fence as \`describe_object\`. \`site\` is \`formula\` | \`validation\` | \`flow_condition\` | \`template\` (default \`formula\`). Pass the rule's @@ -152,6 +156,12 @@ create/update payload. as \`objectName\`: its conditions read rows of that object, and a start whose \`objectName\` names another object is refused at publish (\`flow-time-relative-object-mismatch\`). \`sweepObject\` names that same object. + At a \`flow_condition\` the verdict is the runtime publish gate's, the one a + flow saved through MCP meets: \`os validate\` also judges bare names and + unbound roots over the whole flow, so write \`record.\`, and pass the + flow's \`startCondition\` for an edge or \`decision\` condition after it. Pass + \`field\` (formula) to be judged as that field: its type, and the formula + cycle it would close; a field not yet declared is judged as a new formula. - **query_records({ objectName, where?, fields?, limit?, offset?, orderBy? })** — read records. \`where\` is a field→value match, e.g. \`{ "status": "open" }\`. Results are page-capped; use \`limit\`/\`offset\` to page.