From e569126128d4916d115bee3eb584644cb4cefdb9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 08:24:41 +0000 Subject: [PATCH 1/4] feat(lint): judge a subflow or map call against the deployment's flows at the publish gate Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- packages/lint/src/authoring-rules.ts | 37 ++++-- packages/lint/src/rule-explanations.ts | 8 +- packages/lint/src/runtime-gate.ts | 14 +++ .../src/validate-flow-trigger-readiness.ts | 66 +++++++++-- .../src/protocol-authoring-gate.ts | 109 +++++++++++++++++- packages/metadata-protocol/src/protocol.ts | 12 ++ .../src/runtime-authoring-gate.ts | 31 ++++- 7 files changed, 254 insertions(+), 23 deletions(-) diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 7f72959de0a..deca132f79a 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -522,6 +522,18 @@ export interface AuthoringRuleContext { * contradict (AGENTS.md "Startup registry reads"). */ flowNodeTypeVocabulary?: ReadonlySet; + /** + * The names of every flow the deployment holds: every installed package's + * flows, the stored flow rows in every state (drafts included), the flows + * the written item's publish batch carries, and every flow the automation + * engine holds. Set only by the runtime publish gate, and only when its host + * could read all of them; ABSENT on the three CLI commands, whose stack is + * one app. Read by `validateFlowSubflowTargets` only: present and non-empty, + * a `subflow` / `map` call naming none of them is refused; absent or empty + * at the runtime gate, that rule judges nothing there (the written flow + * alone is no universe). + */ + deploymentFlowNames?: ReadonlySet; } export interface AuthoringRule { @@ -1728,20 +1740,27 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // GET → edit → PUT passes, and a secretless `api` flow is refused at `/meta` // with this id instead of being stored for the engine to refuse at // registration. - // #35143 — a `subflow` / `map` node calling a flow this stack does not - // define. CLI only: the runtime gate's flow snapshot holds just the written - // flow, so every call to another stored flow would read as unknown there. - // Advisory, with the sibling unknown-object hedge: another installed package - // may ship the called flow. + // #35143 — a `subflow` / `map` node calling a flow that does not exist. + // One verdict per door (the rule's docblock): on the CLI a `warning`, since + // another installed package may ship the called flow; at the runtime publish + // gate an `error`, judged against the deployment's flow names the host + // states (`deploymentFlowNames`), because the gate's own flow snapshot holds + // just the written flow. With no stated names, or none, the runtime gate's + // pass judges nothing: a call to another stored flow cannot be told from a + // call to a missing one there. { name: 'validateFlowSubflowTargets', - tier: 'advisory', + tier: 'gating', input: 'normalized', commands: ALL, source: 'packages/lint/src/validate-flow-trigger-readiness.ts', - surfaces: CLI_ONLY, - surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, - run: (stack) => validateFlowSubflowTargets(stack), + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['flow'], + run: (stack, ctx) => { + if (ctx.runtimeWriteType === undefined) return validateFlowSubflowTargets(stack); + if (ctx.deploymentFlowNames === undefined || ctx.deploymentFlowNames.size === 0) return []; + return validateFlowSubflowTargets(stack, { deploymentFlowNames: ctx.deploymentFlowNames }); + }, }, { name: 'validateFlowApiTriggerSecret', diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 41ad33b3d9a..b8354020d44 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -7175,9 +7175,11 @@ const FLOW_SUBFLOW_UNKNOWN_EXPLANATION: RuleExplanation = { paragraphs: [ 'A `subflow` or `map` step runs another flow by the name in `config.flowName`. When no flow has that ' + 'name, the step fails on every run, and every run of the calling flow fails with it.', - 'A warning, and on the CLI only. Another installed package may ship the called flow, which this stack ' + - 'cannot see. And the runtime publish gate judges one flow per write, so a call to another stored flow ' + - 'could not be told from a call to a missing one there.', + 'On the CLI it is a warning: another installed package may ship the called flow, which this stack ' + + 'cannot see. At publish it is an error, judged against every flow the deployment holds: every ' + + 'installed package\'s flows, the stored flows in every state (a draft counts), the flows published in ' + + 'the same batch, and the flows the automation engine holds. Save the called flow first, then publish ' + + 'the one that calls it.', ], }; diff --git a/packages/lint/src/runtime-gate.ts b/packages/lint/src/runtime-gate.ts index 5706700cc16..2db5b72dff0 100644 --- a/packages/lint/src/runtime-gate.ts +++ b/packages/lint/src/runtime-gate.ts @@ -1467,6 +1467,15 @@ export function runRuntimeAuthoringRules(args: { * same value in every pass. Omitted, a flow node's type is not judged. */ flowNodeTypeVocabulary?: readonly string[]; + /** + * On a `flow` write: the names of every flow the deployment holds, as the + * host read them (every installed package's flows, the stored flow rows in + * every state, the batch's own flow drafts, the automation engine's flows). + * Handed to the rules as `AuthoringRuleContext.deploymentFlowNames`, the + * same value in every pass, so it moves no baseline. Omitted, or empty, a + * `subflow` / `map` call to another flow is not judged at this door. + */ + deploymentFlowNames?: readonly string[]; }): RuntimeGateResult { const rules = runtimeAuthoringRulesFor(args.type); const empty: RuntimeGateResult = { errors: [], advisories: [], rulesRun: [] }; @@ -1539,6 +1548,11 @@ export function runRuntimeAuthoringRules(args: { ...(args.flowNodeTypeVocabulary !== undefined && args.flowNodeTypeVocabulary.length > 0 ? { flowNodeTypeVocabulary: new Set(args.flowNodeTypeVocabulary) } : {}), + // The deployment's flow names, stated by the host on a flow write; the + // same value in every pass, so it moves no baseline. + ...(args.deploymentFlowNames !== undefined && args.deploymentFlowNames.length > 0 + ? { deploymentFlowNames: new Set(args.deploymentFlowNames) } + : {}), }; const added = addedFindings(rules, snapshots, ctx, args.type, args.item); diff --git a/packages/lint/src/validate-flow-trigger-readiness.ts b/packages/lint/src/validate-flow-trigger-readiness.ts index 1fced8487bd..decece52698 100644 --- a/packages/lint/src/validate-flow-trigger-readiness.ts +++ b/packages/lint/src/validate-flow-trigger-readiness.ts @@ -1920,21 +1920,52 @@ function signatureUnusableFinding( * the engine to run that flow by name, and the engine finds none, so the step * fails every run (`subflow 'X' failed`). * - * Its OWN exported rule, run on the CLI only, for the reason - * `flow-trigger-unknown-object` carries a hedge plus one more: the runtime - * publish gate judges a flow write over a snapshot whose `flows` holds only - * the written item, so a call to any other stored flow would read as unknown - * there. On the CLI the stack is one app; a flow another installed package - * ships is a legitimate target, so the finding is advisory, as that sibling's - * is without a stated closure. + * Its OWN exported rule, with one verdict per door, decided by #5762's + * question (is what this rule reads enough to know?): + * + * - On the CLI the stack is one app. A flow another installed package ships + * is a legitimate target the stack cannot see, so the finding is a + * `warning`, as `flow-trigger-unknown-object`'s is without a stated closure. + * - At the runtime publish gate the snapshot's `flows` holds only the written + * item, so that snapshot alone cannot judge a call. The host states the + * names of every flow the deployment holds instead + * (`deploymentFlowNames`: every installed package's flows, the stored rows + * in every state, drafts included, this publish batch's own drafts, and + * every flow the automation engine holds). A name in none of those is a + * flow the engine cannot find, so every run of the step fails: `error`. + * The set is the whole deployment, never narrowed to the written package's + * closure, so a call this rule lets through may still be one the engine's + * package-scoped name resolution refuses (ADR-0150 D3); this rule does not + * judge that. A draft counts as held, so two new flows that call each + * other can be published one at a time. + * - At the runtime gate with no stated names, or an empty set, it judges + * nothing: no deployment state was handed over, and the written flow + * alone is no universe (the #24668 reading of an empty set with no + * closure). */ export const FLOW_SUBFLOW_UNKNOWN = 'flow-subflow-unknown'; -export function validateFlowSubflowTargets(stack: AnyRec): FlowTriggerReadinessFinding[] { +export interface FlowSubflowTargetOptions { + /** + * The names of every flow the deployment holds, as the runtime publish + * gate's host states them (`AuthoringRuleContext.deploymentFlowNames`). + * Present and non-empty, a call that names none of them, nor a flow of + * this stack, is an `error`. Absent, the CLI's `warning` verdict applies. + */ + readonly deploymentFlowNames?: ReadonlySet; +} + +export function validateFlowSubflowTargets( + stack: AnyRec, + options: FlowSubflowTargetOptions = {}, +): FlowTriggerReadinessFinding[] { const findings: FlowTriggerReadinessFinding[] = []; const flows = recordsOf(stack.flows); if (flows.length === 0) return findings; - const known = new Set(); + const deployment = options.deploymentFlowNames !== undefined && options.deploymentFlowNames.size > 0 + ? options.deploymentFlowNames + : undefined; + const known = new Set(deployment); for (const flow of flows) { const name = nonEmptyString(flow.name); if (name) known.add(name); @@ -1954,6 +1985,23 @@ export function validateFlowSubflowTargets(stack: AnyRec): FlowTriggerReadinessF if (!called || known.has(called)) continue; const nodeId = nonEmptyString(node.id) ?? String(node.type); const nodeWhere = regionTrail ? `${regionTrail} › node "${nodeId}"` : `node "${nodeId}"`; + if (deployment) { + findings.push({ + severity: 'error', + rule: FLOW_SUBFLOW_UNKNOWN, + where: `flow "${flowName}" › ${nodeWhere}`, + path: `${path}.config.flowName`, + message: + `${String(node.type)} node '${nodeId}' calls flow '${called}', but no flow of this deployment (an ` + + `installed package's, a stored flow or a draft) has that name, so the engine finds none and the ` + + `step fails on every run` + + suggestName(called, known), + hint: + `Set config.flowName to the exact name of a flow this deployment holds, or save the called flow ` + + `first (a draft is enough) and publish this one after it`, + }); + continue; + } findings.push({ severity: 'warning', rule: FLOW_SUBFLOW_UNKNOWN, diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 64eef5c1272..2f460ca6eb4 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -59,6 +59,7 @@ import { withDisabledExtensionsFolded } from './metadata-diagnostics.js'; import { unresolvedConnectorSteps, type ProbeAutomation } from './build-probes.js'; import type { PackagedRuleCopyRefusal, RuntimeAuthoringIssue, RuntimeAuthoringVerdict, RuntimePendingDeclarations } from './runtime-authoring-gate.js'; import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name'; +import { isMissingTableError } from '@objectstack/metadata/errors'; import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared'; import type { IObjectQLEngine } from '@objectstack/spec/contracts'; import type { StoredObjectExtension } from '@objectstack/lint/runtime'; @@ -110,6 +111,18 @@ export interface AuthoringGateHost { formRestoreRefusal: (type: string, item: unknown, name: string, binding: string | null) => Promise; /** [#34776] The automation engine's sealed node-type vocabulary ({@link sealedFlowNodeTypeVocabulary}). */ sealedFlowNodeTypeVocabulary: () => readonly string[] | undefined; + /** + * The names of every flow the automation engine holds + * ({@link automationFlowNames}). Optional: a host that does not state it + * gets no `subflow` / `map` target judgement at the publish gate. + */ + automationFlowNames?: () => Promise; + /** + * The environment's `sys_metadata` rows, read as the stored-collection + * fold reads them. Optional for the same reason; read by + * {@link deploymentFlowNamesOf} for the stored flows of every state. + */ + findEnvironmentRows?: ObjectStackProtocolImplementation['findEnvironmentRows']; } /** The body of `ObjectStackProtocolImplementation#restoredBodyDerivation`; the method's docblock there is its contract. */ @@ -341,7 +354,7 @@ export function withTargetFoldedWithout( * The members {@link judgeRuntimeAuthoringRules} reads: the host facts and * collections every judgement of the shared rules is made against. */ -type RuntimeRulesHost = Pick; +type RuntimeRulesHost = Pick; /** The body of `ObjectStackProtocolImplementation#assertRuntimeAuthoringRules`; the method's docblock there is its contract. */ export async function assertRuntimeAuthoringRules( @@ -634,6 +647,14 @@ export async function judgeRuntimeAuthoringRules( // flow write only, and passed in so the gate stays pure. const flowNodeTypeVocabulary = singular === 'flow' ? this.sealedFlowNodeTypeVocabulary() : undefined; + // [#35143] Every flow the deployment holds, by name, on a flow write only: + // the universe a `subflow` / `map` call is judged against, since the gate's + // own snapshot holds just the written flow. `undefined` when one source + // could not be read, and then no call is judged. + const deploymentFlowNames = singular === 'flow' + ? await deploymentFlowNamesOf.call(this, listRegisteredCollection('flow', 'flows')) + : undefined; + // [#26188] Is a hierarchy resolver mounted — a host fact of the same kind, // read here per publish and passed in so the gate stays pure. const hierarchyResolverMounted = this.hierarchyResolverMounted(); @@ -685,6 +706,8 @@ export async function judgeRuntimeAuthoringRules( ...(rlsMembershipResolverKeys !== undefined ? { rlsMembershipResolverKeys } : {}), // With it the gate refuses a flow node no executor of this deployment runs. ...(flowNodeTypeVocabulary !== undefined ? { flowNodeTypeVocabulary } : {}), + // [#35143] With it the gate refuses a subflow / map call to a flow the deployment does not hold. + ...(deploymentFlowNames !== undefined ? { deploymentFlowNames } : {}), // [#26188] With it the gate refuses a hierarchy scope no resolver enforces. ...(hierarchyResolverMounted !== undefined ? { hierarchyResolverMounted } : {}), // [#28448] With it the gate refuses a rule copy that changes what the package owns. @@ -695,6 +718,59 @@ export async function judgeRuntimeAuthoringRules( return verdict; } +/** + * [#35143] The names of every flow this deployment holds, the universe the + * publish gate judges a `subflow` / `map` node's `config.flowName` against + * (`validateFlowSubflowTargets`): the registry's flows (`registered`, every + * installed package's, a disabled package's included), the stored flow rows + * of EVERY state (a draft counts, so two new flows that call each other can be + * published one at a time), and every flow the automation engine holds (a flow + * registered straight into the engine has no metadata row). The batch's own + * flow drafts are added by the gate ({@link evaluateRuntimeAuthoringGate}). + * + * Union only: every source can only make more names resolvable, never fewer. + * `undefined`, and so no judgement, when the host cannot state one of the + * sources: no stored-row reader or engine reader, or a read that fails (said + * once, at `warn`). Judging against a partial universe would refuse a call to + * a flow the missing source holds. + */ +async function deploymentFlowNamesOf( + this: Pick, + registered: readonly unknown[], +): Promise { + if (typeof this.findEnvironmentRows !== 'function' || typeof this.automationFlowNames !== 'function') return undefined; + const engineNames = await this.automationFlowNames(); + if (engineNames === undefined) return undefined; + const names = new Set(engineNames); + for (const item of registered) { + const name = (item as { name?: unknown } | null)?.name; + if (typeof name === 'string' && name !== '') names.add(name); + } + try { + for (const type of ['flow', 'flows']) { + // [ADR-0131 D6] The environment's rows, every state, as the + // stored-collection fold reads them (that fold reads `active` only). + const rows = await this.findEnvironmentRows('sys_metadata', { + where: { type }, + context: { isSystem: true }, + }); + for (const row of (rows ?? []) as Array<{ name?: unknown }>) { + if (typeof row?.name === 'string' && row.name !== '') names.add(row.name); + } + } + } catch (error) { + if (!isMissingTableError(error, 'sys_metadata')) { + console.warn( + `[Protocol] the runtime authoring gate could not read the stored flows: ` + + `${(error as { message?: string } | null)?.message ?? String(error)}. ` + + `This write is NOT blocked; a subflow or map step's called flow is not judged for it.`, + ); + return undefined; + } + } + return [...names]; +} + /** * [#32666] The flows of the package an object write belongs to — the subjects * the object write is judged against (`RuntimeStackContext.flows`). @@ -982,6 +1058,37 @@ function draftConnectorAdvisories( * a type, so "no executor" is not a verdict anyone may act on (AGENTS.md * "Startup registry reads"). */ +/** + * [#35143] The names of every flow the automation engine holds + * (`IAutomationService.listFlows`), read per publish and recorded nowhere. + * `undefined` when no automation service is registered (no flow runs here at + * all) or its read fails; then no `subflow` / `map` call is judged. + */ +export async function automationFlowNames( + this: { readonly getServicesRegistry?: () => Map }, +): Promise { + let automation: unknown; + try { + automation = this.getServicesRegistry?.().get('automation'); + } catch { + return undefined; + } + const list = (automation as { listFlows?: () => unknown } | undefined)?.listFlows; + if (typeof list !== 'function') return undefined; + let names: unknown; + try { + names = await list.call(automation); + } catch (error) { + console.warn( + `[Protocol] the runtime authoring gate could not list the automation engine's flows: ` + + `${(error as { message?: string } | null)?.message ?? String(error)}. ` + + `This write is NOT blocked; a subflow or map step's called flow is not judged for it.`, + ); + return undefined; + } + return Array.isArray(names) ? names.filter((n): n is string => typeof n === 'string') : undefined; +} + export function sealedFlowNodeTypeVocabulary( this: { readonly getServicesRegistry?: () => Map }, ): readonly string[] | undefined { diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index cbd8f442c8d..57eb6abed6e 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -273,6 +273,7 @@ import { restoredBodyWriter, runAuthoringGate, sealedFlowNodeTypeVocabulary, + automationFlowNames, } from './protocol-authoring-gate.js'; // [#25467 cut 9] The credential carry-forward and the credential channel lookup. import { @@ -1933,6 +1934,8 @@ export class ObjectStackProtocolImplementation implements resolveWritePackageScope: (...a) => this.resolveWritePackageScope(...a), rlsMembershipResolverKeys: (...a) => this.rlsMembershipResolverKeys(...a), sealedFlowNodeTypeVocabulary: (...a) => this.sealedFlowNodeTypeVocabulary(...a), + automationFlowNames: (...a) => this.automationFlowNames(...a), + findEnvironmentRows: (...a) => this.findEnvironmentRows(...a), tenancyPostureInForce: (...a) => this.tenancyPostureInForce(...a), servicesRegistry: () => this.getServicesRegistry, }; @@ -2231,6 +2234,15 @@ export class ObjectStackProtocolImplementation implements return rlsMembershipResolverKeys.call(host); } + /** [#35143] The names of every flow the automation engine holds; the body's docblock is its contract. */ + private automationFlowNames(): Promise { + const readGetServicesRegistry = () => this.getServicesRegistry; + const host: ThisParameterType = { + get getServicesRegistry() { return readGetServicesRegistry(); }, + }; + return automationFlowNames.call(host); + } + /** [#34776] The automation engine's sealed node-type vocabulary; the body's docblock is its contract. */ private sealedFlowNodeTypeVocabulary(): readonly string[] | undefined { const readGetServicesRegistry = () => this.getServicesRegistry; diff --git a/packages/metadata-protocol/src/runtime-authoring-gate.ts b/packages/metadata-protocol/src/runtime-authoring-gate.ts index 2c3c4b2b246..9931be0e6e9 100644 --- a/packages/metadata-protocol/src/runtime-authoring-gate.ts +++ b/packages/metadata-protocol/src/runtime-authoring-gate.ts @@ -780,7 +780,8 @@ export const CLOSURE_CONTEXT_KEY_BY_TYPE = { // same batch is judged against the flows the batch leaves live: a live flow // the batch redrafts is the draft's own write to answer for, against this // batch's objects ({@link objectWriteFlowSubjects}). They are not folded in - // as subjects themselves, and no other write type reads them. + // as subjects themselves. A FLOW write reads only their names, so a flow + // the batch publishes resolves as a subflow target ({@link withPendingFlowNames}). flow: 'flows', // [#33152] A batch's extension drafts, folded onto their targets in // `objects` ({@link foldPendingObjectExtensions}), never a context @@ -991,6 +992,19 @@ export function objectWriteFlowSubjects( return liveFlows.filter((entry) => !(isRec(entry) && typeof entry.name === 'string' && redrafted.has(entry.name))); } +/** + * The deployment's flow names with this batch's own flow drafts added: a flow + * published in the same batch as the flow that calls it is held once the batch + * lands. Additive only, as {@link mergePendingDeclarations} is. + */ +function withPendingFlowNames(names: readonly string[], pending: readonly unknown[] | undefined): string[] { + const out = new Set(names); + for (const entry of pending ?? []) { + if (isRec(entry) && typeof entry.name === 'string' && entry.name !== '') out.add(entry.name); + } + return [...out]; +} + /** [#32666] `pending` without the entries named `name` — the written item's own draft. */ function withoutWrittenItem(pending: readonly unknown[] | undefined, name: string): readonly unknown[] | undefined { return pending?.filter((entry) => !(isRec(entry) && entry.name === name)); @@ -1469,6 +1483,18 @@ export function evaluateRuntimeAuthoringGate(args: { * judged. */ flowNodeTypeVocabulary?: readonly string[]; + /** + * On a `flow` write: the names of every flow the deployment holds, as the + * impure caller read them (every installed package's flows, the stored + * flow rows in every state, the automation engine's flows). A fact only + * the host holds, of the #6285 kind. The batch's own flow drafts + * (`pending.flows`) are added here, so a flow published in the same batch + * as its caller resolves. Handed to the shared rules, where + * `validateFlowSubflowTargets` refuses a `subflow` / `map` call naming none + * of them. Absent (the host could not read one of the sources), a call to + * another flow is not judged. + */ + deploymentFlowNames?: readonly string[]; }): RuntimeAuthoringVerdict { const toIssue = issueOf(args.userTextLocales ?? []); // [#26188] The one finding a draft hears: a hierarchy scope this runtime @@ -1548,6 +1574,9 @@ export function evaluateRuntimeAuthoringGate(args: { ...(args.flowNodeTypeVocabulary !== undefined ? { flowNodeTypeVocabulary: args.flowNodeTypeVocabulary } : {}), + ...(args.type === 'flow' && args.deploymentFlowNames !== undefined + ? { deploymentFlowNames: withPendingFlowNames(args.deploymentFlowNames, args.pending?.flows) } + : {}), }); // [#6285] The gate-local refusal, folded into the SAME verdict set as the From eca6aa5eb0901304d31c4b306c2b21870f25e7ae Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 08:27:39 +0000 Subject: [PATCH 2/4] test: pin the subflow target refusal at the publish door Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../flow-publish-checks-second-batch.test.ts | 56 ++++++++++++- .../protocol.runtime-authoring-gate.test.ts | 81 +++++++++++++++++++ 2 files changed, 133 insertions(+), 4 deletions(-) diff --git a/packages/lint/src/flow-publish-checks-second-batch.test.ts b/packages/lint/src/flow-publish-checks-second-batch.test.ts index eb201d9bf03..c09eb23b427 100644 --- a/packages/lint/src/flow-publish-checks-second-batch.test.ts +++ b/packages/lint/src/flow-publish-checks-second-batch.test.ts @@ -615,11 +615,59 @@ describe('flow-subflow-unknown', () => { ).toEqual([]); }); - it('runs on the CLI commands and not on the runtime publish gate', () => { + it('stays a warning on the CLI commands', () => { const cli = runAuthoringRules('validate', { normalized: stack(calling('missing_child')) } as never); - expect(rulesOf(cli)).toContain(FLOW_SUBFLOW_UNKNOWN); - const verdict = runRuntimeAuthoringRules({ type: 'flow', item: calling('missing_child'), context: { objects: [DEAL] } }); - expect(rulesOf([...verdict.errors, ...verdict.advisories])).not.toContain(FLOW_SUBFLOW_UNKNOWN); + expect(cli.filter((f) => f.rule === FLOW_SUBFLOW_UNKNOWN).map((f) => f.severity)).toEqual(['warning']); + }); + + const publish = (item: AnyRec, deploymentFlowNames?: readonly string[]) => + runRuntimeAuthoringRules({ + type: 'flow', + item, + context: { objects: [DEAL] }, + ...(deploymentFlowNames !== undefined ? { deploymentFlowNames } : {}), + }); + + it('the runtime publish gate refuses a call to a flow the deployment does not hold', () => { + const verdict = publish(calling('missing_child'), ['child', 'other']); + const refused = verdict.errors.filter((f) => f.rule === FLOW_SUBFLOW_UNKNOWN); + expect(refused).toHaveLength(1); + expect(refused[0]).toMatchObject({ severity: 'error', path: 'flows[0].nodes[1].config.flowName' }); + expect(refused[0].message).toContain("calls flow 'missing_child', but no flow of this deployment"); + expect(verdict.rulesRun).toContain('validateFlowSubflowTargets'); + }); + + it('refuses a map call nested in a loop body too', () => { + const nested = flow('parent', {}, [ + { + id: 'each', + type: 'loop', + label: 'Each', + config: { + collection: { dialect: 'cel', source: '[1]' }, + iteratorVariable: 'i', + body: { + nodes: [{ id: 'fan', type: 'map', label: 'Fan', config: { collection: '{{items}}', flowName: 'nope' } }], + edges: [], + }, + }, + }, + ]); + const direct = validateFlowSubflowTargets(stack(nested), { deploymentFlowNames: new Set(['child']) }); + expect(direct.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [FLOW_SUBFLOW_UNKNOWN, 'error', 'flows[0].nodes[1].config.body.nodes[0].config.flowName'], + ]); + }); + + it('the runtime publish gate lets a call through to a flow the deployment holds, or to the written flow itself', () => { + expect(rulesOf(publish(calling('child'), ['child']).errors)).not.toContain(FLOW_SUBFLOW_UNKNOWN); + expect(rulesOf(publish(calling('parent'), ['child']).errors)).not.toContain(FLOW_SUBFLOW_UNKNOWN); + }); + + it('the runtime publish gate judges nothing with no stated flow names, or an empty set', () => { + for (const verdict of [publish(calling('missing_child')), publish(calling('missing_child'), [])]) { + expect(rulesOf([...verdict.errors, ...verdict.advisories])).not.toContain(FLOW_SUBFLOW_UNKNOWN); + } }); }); diff --git a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts index 4ac24333c66..d3e30ef4099 100644 --- a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts @@ -55,6 +55,7 @@ import { HIERARCHY_SCOPE_CAPABILITY_REQUIRED, HIERARCHY_SCOPE_RESOLVER_SERVICE, PUBLIC_FORM_INTAKE_UNAVAILABLE, + evaluateRuntimeAuthoringGate, stampHtmlPageRequires, } from './runtime-authoring-gate.js'; @@ -5755,3 +5756,83 @@ describe('ai_context author defects at save (ADR-0160 D1)', () => { expect((active.advisories ?? []).map((a: any) => a.rule)).toEqual(['ai-context-field-unknown']); }); }); + +// [#35143] A `subflow` / `map` call to a flow the deployment does not hold is +// refused at the publish door, judged against every flow the deployment holds: +// the registry's, the stored rows in every state, the automation engine's, and +// the batch's own drafts. No source readable, no judgement. +describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', () => { + let warn: ReturnType; + beforeEach(() => { + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => warn.mockRestore()); + + const calling = (name: string, flowName: string) => ({ + name, + label: name, + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'call', type: 'subflow', label: 'Call', config: { flowName } }, + ], + edges: [{ id: 'e1', source: 'start', target: 'call' }], + }); + + /** A protocol whose automation engine holds `engineFlows`, and whose registry lists `registryFlows`. */ + const protocolWith = (engineFlows: readonly string[] | undefined, registryFlows: readonly string[] = []) => { + const { engine, rows } = makeStubEngine(); + const objectsOf = engine.registry.listItems; + engine.registry.listItems = (type: string) => + type === 'flow' ? registryFlows.map((name) => ({ name })) : objectsOf(type); + const services = new Map(); + if (engineFlows !== undefined) services.set('automation', { listFlows: async () => [...engineFlows] }); + const protocol = new ObjectStackProtocolImplementation(engine, () => services as Map, 'env_test'); + return { protocol: protocol as any, rows }; + }; + const publish = (protocol: any, item: { name: string }) => + protocol.saveMetaItem({ type: 'flow', name: item.name, item }); + + it('refuses an active save calling a flow nothing in the deployment holds', async () => { + const { protocol, rows } = protocolWith(['child'], ['packaged_child']); + const err = await publish(protocol, calling('parent', 'missing_child')).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + expect(err.status).toBe(422); + expect(err.code).toBe('INVALID_METADATA'); + const issue = err.issues.find((i: any) => i.rule === 'flow-subflow-unknown'); + expect(issue, `issues: ${JSON.stringify(err.issues)}`).toBeDefined(); + expect(issue.path).toBe('flows[0].nodes[1].config.flowName'); + expect(err.rulesRun).toContain('validateFlowSubflowTargets'); + expect(flowRows(rows)).toEqual([]); + }); + + it("lets a call through to the engine's flow, an installed package's flow, or a stored draft", async () => { + const { protocol } = protocolWith(['engine_child'], ['packaged_child']); + expect((await publish(protocol, calling('a', 'engine_child'))).success).toBe(true); + expect((await publish(protocol, calling('b', 'packaged_child'))).success).toBe(true); + await protocol.saveMetaItem({ type: 'flow', name: 'draft_child', item: calling('draft_child', 'a'), mode: 'draft' }); + expect((await publish(protocol, calling('c', 'draft_child'))).success).toBe(true); + // …and a flow published earlier is a stored active row. + expect((await publish(protocol, calling('d', 'a'))).success).toBe(true); + }); + + it('judges nothing when no automation service states its flows', async () => { + const { protocol } = protocolWith(undefined, ['packaged_child']); + expect((await publish(protocol, calling('parent', 'missing_child'))).success).toBe(true); + }); + + it('a flow the same batch publishes resolves; without it the call is refused', () => { + const body = calling('parent', 'batch_child'); + const judge = (pending?: { flows: unknown[] }) => evaluateRuntimeAuthoringGate({ + type: 'flow', + name: 'parent', + state: 'active', + body, + deploymentFlowNames: ['other'], + ...(pending !== undefined ? { pending: pending as never } : {}), + }); + expect(((judge().error as any)?.issues ?? []).map((i: { rule: string }) => i.rule)).toContain('flow-subflow-unknown'); + expect(judge({ flows: [{ name: 'batch_child' }] }).error).toBeNull(); + }); +}); From 4a9e48c3455c650ea4db13973bb7dea79422a25c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 08:28:50 +0000 Subject: [PATCH 3/4] docs(lint): the subflow target refusal in the upgrade-guide entry and changeset Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../35143-subflow-target-publish-gate.md | 28 +++++++++++++++++++ packages/lint/src/index.ts | 1 + ...-refuses-flows-that-save-and-do-not-run.ts | 8 ++++-- 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 .changeset/35143-subflow-target-publish-gate.md diff --git a/.changeset/35143-subflow-target-publish-gate.md b/.changeset/35143-subflow-target-publish-gate.md new file mode 100644 index 00000000000..146ab626b46 --- /dev/null +++ b/.changeset/35143-subflow-target-publish-gate.md @@ -0,0 +1,28 @@ +--- +'@objectstack/lint': minor +'@objectstack/metadata-protocol': minor +'@objectstack/spec': patch +--- + +fix(lint)!: the publish gate refuses a subflow or map step that calls a flow the deployment does not hold + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** accept-set narrowing, shipped as `minor`: an active publish of a flow whose `subflow` or `map` step names a flow that no part of the deployment holds was accepted before and is refused now (`422 INVALID_METADATA`, rule `flow-subflow-unknown`), with the fix named. The schema is unchanged, stored flows are not rewritten or refused at boot, and drafts are not gated. + +A `subflow` or `map` step runs the flow its `config.flowName` names. When the engine holds no flow of that name, the step fails on every run (`Flow 'X' not found`). `flow-subflow-unknown` reported this only as a CLI warning, because the publish gate judged one flow at a time and could not tell a call to another stored flow from a call to a missing one. + +- **The refusal.** On a flow publish the host now states the names of every flow the deployment holds: every installed package's flows (a disabled package's included), the stored flow rows in every state (a draft counts), the flows the same publish batch carries, and every flow the automation engine holds (a flow registered straight into the engine has no metadata row). A call naming none of them, and not the written flow itself, is an `error` at the publish gate. +- **No verdict.** When the host cannot read one of those sources (no automation service, a failed store read, said once at `warn`), or the set is empty, the gate does not judge the call. +- **Not judged.** Whether the engine's package-scoped name resolution (ADR-0150 D3) lets the calling flow reach the called one: the set is the whole deployment, never narrowed to the written package's dependency closure. +- **The CLI.** `os validate` / `lint` / `compile` / `build` still report `flow-subflow-unknown` as a warning: the stack is one app, and another installed package may ship the called flow. +- **Exports.** `validateFlowSubflowTargets` takes an optional second argument (`FlowSubflowTargetOptions`, `deploymentFlowNames`); `AuthoringRuleContext` gains `deploymentFlowNames`; `runRuntimeAuthoringRules` and `evaluateRuntimeAuthoringGate` take an optional `deploymentFlowNames`. All optional; an omitted value keeps the earlier behaviour. + +FROM → TO: + +- `{ type: 'subflow', config: { flowName: 'notfy_owner' } }` (no such flow) → `{ type: 'subflow', config: { flowName: 'notify_owner' } }` + +One-line fix: name a flow the deployment holds, or save the called flow first (a draft is enough) and publish the caller after it. diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 57f1d56abef..77aa5a13a74 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -188,6 +188,7 @@ export { } from './validate-flow-trigger-readiness.js'; export type { FlowTriggerReadinessFinding, + FlowSubflowTargetOptions, FlowTriggerReadinessSeverity, } from './validate-flow-trigger-readiness.js'; diff --git a/packages/spec/src/migrations/entries/semantic/18.publish-refuses-flows-that-save-and-do-not-run.ts b/packages/spec/src/migrations/entries/semantic/18.publish-refuses-flows-that-save-and-do-not-run.ts index 356e9b40829..7d090e3b0af 100644 --- a/packages/spec/src/migrations/entries/semantic/18.publish-refuses-flows-that-save-and-do-not-run.ts +++ b/packages/spec/src/migrations/entries/semantic/18.publish-refuses-flows-that-save-and-do-not-run.ts @@ -25,7 +25,8 @@ export const entry: SemanticMigration = { 'Set the trigger\'s `objectName`; compare the option value, not its label; drop the record `triggerType` or the ' + '`timeRelative` block, whichever the flow does not mean; move `filter` / `maxRecords` inside `timeRelative`; point ' + '`dateField` at a `date` or `datetime` field; write an option value the field lists; write a date as a CEL value ' - + 'envelope (`{ dialect: \'cel\', source: \'isoDate(today())\' }`) instead of the helper call as text', + + 'envelope (`{ dialect: \'cel\', source: \'isoDate(today())\' }`) instead of the helper call as text; ' + + 'point a `subflow` / `map` step\'s `config.flowName` at a flow the deployment holds, or save the called flow first', reason: 'Each flow parses and publishes, then misbehaves on every run: a record trigger with no object fires on writes to ' + 'every object; a label comparison is never true, because the row stores the value; a record trigger shadows the ' @@ -34,7 +35,10 @@ export const entry: SemanticMigration = { + '`invalid_option` and a write of helper text is refused `invalid_date`, so the node fails on every run. Stored ' + 'flows are not rewritten or refused at boot. The next publish of a flow that carries one of the seven errors is ' + 'refused with the fix named. Three warnings join them (`flow-schedule-timezone-missing`, `flow-subflow-unknown`, ' - + '`flow-create-update-pair`), which refuse nothing and make `os validate --strict` exit 1 as any warning does.', + + '`flow-create-update-pair`), which refuse nothing on the CLI and make `os validate --strict` exit 1 as any warning ' + + 'does. At the runtime publish gate `flow-subflow-unknown` is an error: a `subflow` / `map` step whose ' + + '`config.flowName` names no flow the deployment holds (an installed package\'s, a stored flow in any state, a flow ' + + 'of the same publish batch, or one the automation engine holds) fails on every run, so its publish is refused.', acceptanceCriteria: 'os validate reports none of the seven errors; a publish of every flow the package carries succeeds.', }; From 3842e1899c4d150b935c96d09f240d73719b986e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 08:57:36 +0000 Subject: [PATCH 4/4] refactor(metadata-protocol): read the deployment's flow names off the protocol facade Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../src/protocol-authoring-gate.ts | 41 +++++++++---------- packages/metadata-protocol/src/protocol.ts | 12 ------ 2 files changed, 19 insertions(+), 34 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 2f460ca6eb4..05dec1d3417 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -111,18 +111,6 @@ export interface AuthoringGateHost { formRestoreRefusal: (type: string, item: unknown, name: string, binding: string | null) => Promise; /** [#34776] The automation engine's sealed node-type vocabulary ({@link sealedFlowNodeTypeVocabulary}). */ sealedFlowNodeTypeVocabulary: () => readonly string[] | undefined; - /** - * The names of every flow the automation engine holds - * ({@link automationFlowNames}). Optional: a host that does not state it - * gets no `subflow` / `map` target judgement at the publish gate. - */ - automationFlowNames?: () => Promise; - /** - * The environment's `sys_metadata` rows, read as the stored-collection - * fold reads them. Optional for the same reason; read by - * {@link deploymentFlowNamesOf} for the stored flows of every state. - */ - findEnvironmentRows?: ObjectStackProtocolImplementation['findEnvironmentRows']; } /** The body of `ObjectStackProtocolImplementation#restoredBodyDerivation`; the method's docblock there is its contract. */ @@ -354,7 +342,15 @@ export function withTargetFoldedWithout( * The members {@link judgeRuntimeAuthoringRules} reads: the host facts and * collections every judgement of the shared rules is made against. */ -type RuntimeRulesHost = Pick; +type RuntimeRulesHost = Pick & { + /** + * [#35143] The protocol's services registry reader, read per call and + * recorded nowhere: {@link deploymentFlowNamesOf} asks its `automation` + * service for the flows the engine holds. Optional: a host that does not + * state it gets no `subflow` / `map` target judgement at the publish gate. + */ + servicesRegistry?: () => (() => Map) | undefined; +}; /** The body of `ObjectStackProtocolImplementation#assertRuntimeAuthoringRules`; the method's docblock there is its contract. */ export async function assertRuntimeAuthoringRules( @@ -730,16 +726,16 @@ export async function judgeRuntimeAuthoringRules( * * Union only: every source can only make more names resolvable, never fewer. * `undefined`, and so no judgement, when the host cannot state one of the - * sources: no stored-row reader or engine reader, or a read that fails (said + * sources: no store or no automation service, or a read that fails (said * once, at `warn`). Judging against a partial universe would refuse a call to * a flow the missing source holds. */ async function deploymentFlowNamesOf( - this: Pick, + this: Pick, registered: readonly unknown[], ): Promise { - if (typeof this.findEnvironmentRows !== 'function' || typeof this.automationFlowNames !== 'function') return undefined; - const engineNames = await this.automationFlowNames(); + if (typeof this.engine?.find !== 'function') return undefined; + const engineNames = await automationFlowNames.call({ getServicesRegistry: this.servicesRegistry?.() }); if (engineNames === undefined) return undefined; const names = new Set(engineNames); for (const item of registered) { @@ -748,12 +744,13 @@ async function deploymentFlowNamesOf( } try { for (const type of ['flow', 'flows']) { - // [ADR-0131 D6] The environment's rows, every state, as the - // stored-collection fold reads them (that fold reads `active` only). - const rows = await this.findEnvironmentRows('sys_metadata', { + // Every state (the stored-collection fold reads `active` only). + // Unfiltered for legacy organization rows: a name too many can + // only let a call through, never refuse one. + const rows = await this.engine.find('sys_metadata', { where: { type }, context: { isSystem: true }, - }); + } as never); for (const row of (rows ?? []) as Array<{ name?: unknown }>) { if (typeof row?.name === 'string' && row.name !== '') names.add(row.name); } @@ -1064,7 +1061,7 @@ function draftConnectorAdvisories( * `undefined` when no automation service is registered (no flow runs here at * all) or its read fails; then no `subflow` / `map` call is judged. */ -export async function automationFlowNames( +async function automationFlowNames( this: { readonly getServicesRegistry?: () => Map }, ): Promise { let automation: unknown; diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 57eb6abed6e..cbd8f442c8d 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -273,7 +273,6 @@ import { restoredBodyWriter, runAuthoringGate, sealedFlowNodeTypeVocabulary, - automationFlowNames, } from './protocol-authoring-gate.js'; // [#25467 cut 9] The credential carry-forward and the credential channel lookup. import { @@ -1934,8 +1933,6 @@ export class ObjectStackProtocolImplementation implements resolveWritePackageScope: (...a) => this.resolveWritePackageScope(...a), rlsMembershipResolverKeys: (...a) => this.rlsMembershipResolverKeys(...a), sealedFlowNodeTypeVocabulary: (...a) => this.sealedFlowNodeTypeVocabulary(...a), - automationFlowNames: (...a) => this.automationFlowNames(...a), - findEnvironmentRows: (...a) => this.findEnvironmentRows(...a), tenancyPostureInForce: (...a) => this.tenancyPostureInForce(...a), servicesRegistry: () => this.getServicesRegistry, }; @@ -2234,15 +2231,6 @@ export class ObjectStackProtocolImplementation implements return rlsMembershipResolverKeys.call(host); } - /** [#35143] The names of every flow the automation engine holds; the body's docblock is its contract. */ - private automationFlowNames(): Promise { - const readGetServicesRegistry = () => this.getServicesRegistry; - const host: ThisParameterType = { - get getServicesRegistry() { return readGetServicesRegistry(); }, - }; - return automationFlowNames.call(host); - } - /** [#34776] The automation engine's sealed node-type vocabulary; the body's docblock is its contract. */ private sealedFlowNodeTypeVocabulary(): readonly string[] | undefined { const readGetServicesRegistry = () => this.getServicesRegistry;