From e569126128d4916d115bee3eb584644cb4cefdb9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 08:24:41 +0000 Subject: [PATCH 1/8] 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/8] 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/8] 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/8] 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; From 59ea4d2b24a4444418e4a216cb6c75d56406fa8c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 12:15:11 +0000 Subject: [PATCH 5/8] fix(metadata-protocol): a package install's flow calling a later sibling flow resolves at the publish gate The unmanaged install writes its items one at a time, so the publish gate's subflow-target judgement met a caller before its callee and rolled the whole install back. The door now states its plan's flow names on each flow write, as a publish batch does. The gate reads the stored flow names in one read projected to name, and none for a flow that calls no other flow. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSjBfkaFUVwRa3pdUK --- .../src/package-unmanaged-install.test.ts | 51 +++++++++++++ .../src/protocol-authoring-gate.ts | 70 +++++++++--------- .../src/protocol-door-requests.ts | 12 ++++ .../src/protocol-package-commits.ts | 10 +++ .../metadata-protocol/src/protocol-save.ts | 7 ++ .../protocol.runtime-authoring-gate.test.ts | 72 ++++++++++++++++++- packages/metadata-protocol/src/protocol.ts | 6 +- .../src/runtime-authoring-gate.ts | 16 +++++ ...-refuses-flows-that-save-and-do-not-run.ts | 26 ++++--- 9 files changed, 222 insertions(+), 48 deletions(-) diff --git a/packages/metadata-protocol/src/package-unmanaged-install.test.ts b/packages/metadata-protocol/src/package-unmanaged-install.test.ts index cd4c9305188..415e49cd071 100644 --- a/packages/metadata-protocol/src/package-unmanaged-install.test.ts +++ b/packages/metadata-protocol/src/package-unmanaged-install.test.ts @@ -1601,3 +1601,54 @@ describe('[#31530] the base row, as its own write answered it (`baseInstance`, d expect(await protocol.importUnmanagedPackage({ manifest: crmBody() })).not.toHaveProperty('baseInstance'); }); }); + +// [#35143] The publish gate judges a `subflow` / `map` call against every flow +// the deployment holds. This verb writes the package's items one at a time, +// so a flow calling a sibling the package declares AFTER it would meet a gate +// that holds no such flow yet; the verb states its plan's flow names, so the +// sibling resolves and the install goes in whole. +describe('importUnmanagedPackage — a flow calling a sibling flow of the same package', () => { + const flow = (name: string, calls?: string) => ({ + name, + label: name, + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + ...(calls !== undefined ? [{ id: 'call', type: 'subflow', label: 'Call', config: { flowName: calls } }] : []), + ], + edges: calls !== undefined ? [{ id: 'e1', source: 'start', target: 'call' }] : [], + }); + /** A protocol whose automation engine holds another flow, so the gate's universe is not empty. */ + const withAutomation = () => { + const harness = makeEngine(); + const services = new Map([['automation', { listFlows: async () => ['other_flow'] }]]); + const protocol = new ObjectStackProtocolImplementation(harness.engine, () => services as Map) as any; + return { ...harness, protocol }; + }; + + it('installs a package that declares the calling flow before the flow it calls', async () => { + const { protocol, table } = withAutomation(); + const result = await protocol.importUnmanagedPackage({ + manifest: crmBody({ flows: [flow('crm_parent', 'crm_child'), flow('crm_child')] }), + }); + expect(result.copied.filter((c: { type: string }) => c.type === 'flow')).toEqual([ + { type: 'flow', name: 'crm_parent' }, + { type: 'flow', name: 'crm_child' }, + ]); + const flows = table('sys_metadata').filter((r) => r.type === 'flow' && r.state === 'active').map((r) => r.name); + expect(flows.sort()).toEqual(['crm_child', 'crm_parent']); + }); + + it('still refuses a call to a flow neither the package nor the deployment holds, and leaves nothing behind', async () => { + const { protocol, table, packages } = withAutomation(); + const err = await refusalOf(() => protocol.importUnmanagedPackage({ + manifest: crmBody({ flows: [flow('crm_parent', 'crm_nowhere'), flow('crm_child')] }), + })); + const envelope = resolveThrownHttpError(err); + expect(envelope.status).toBe(422); + expect(JSON.stringify(err.issues ?? err.details ?? err.cause ?? null)).toContain('flow-subflow-unknown'); + expect(table('sys_metadata').filter((r) => r.state === 'active')).toEqual([]); + expect(packages.has('com.example.crm-copy')).toBe(false); + }); +}); diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 05dec1d3417..0e9182689ab 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -54,7 +54,7 @@ import { storedFlowVerdictBody } from './protocol-flow-save-replay.js'; import { withoutPlatformOrigin } from '@objectstack/metadata'; import { noPendingDraftError } from './protocol-authoring-refusals.js'; import { memberOption } from './protocol-bundle-members.js'; -import { evaluateRuntimeAuthoringGate } from './runtime-authoring-gate.js'; +import { evaluateRuntimeAuthoringGate, flowCallsAnotherFlow } from './runtime-authoring-gate.js'; 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'; @@ -385,9 +385,9 @@ export async function judgeRuntimeAuthoringRules( packageId?: string | null; /** * [#10377] The declarations this write's own BATCH is publishing - * alongside it, when the caller HAS a batch. Only - * `publishPackageDrafts` does; every other door writes one item, so its - * closure is the live universe and it states nothing here. + * alongside it, when the caller HAS a batch: `publishPackageDrafts`, and a + * package copy's flow write, its copy's flow names only (#35143). Every other + * door writes one item, so its closure is the live universe: it states none. * * Threaded rather than gathered: the batch's pending drafts are * `sys_metadata` rows the caller has already listed and is about to @@ -643,11 +643,12 @@ 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' + // [#35143] Every flow the deployment holds, by name, on a flow write whose + // body calls another flow only: the universe a `subflow` / `map` call is + // judged against, since the gate's own snapshot holds just the written + // flow. A flow with no such call pays no read for it. `undefined` when one + // source could not be read, and then no call is judged. + const deploymentFlowNames = singular === 'flow' && flowCallsAnotherFlow(evt.body, evt.name) ? await deploymentFlowNamesOf.call(this, listRegisteredCollection('flow', 'flows')) : undefined; @@ -683,7 +684,8 @@ export async function judgeRuntimeAuthoringRules( datasets, ...(flows !== undefined ? { flows } : {}), // [#10377] The batch's own pending drafts join the - // collections above. Absent on every non-batch door. + // collections above. Absent on every non-batch door (a package copy's + // flow write states its copy's flow names here, #35143). ...(evt.pending !== undefined ? { pending: evt.pending } : {}), ...(packageScope !== undefined ? { packageScope } : {}), orgWallEnforced: this.orgWallEnforced(), @@ -743,17 +745,19 @@ async function deploymentFlowNamesOf( if (typeof name === 'string' && name !== '') names.add(name); } try { - for (const type of ['flow', 'flows']) { - // 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); - } + // One read, both type spellings, projected to `name`: only the names + // are asked, so no stored body is carried through the process for + // them (the `STORE_MARK_FIELDS` rule, `meta-compile-cache.ts`). 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: { $in: ['flow', 'flows'] } }, + fields: ['name'], + 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); } } catch (error) { if (!isMissingTableError(error, 'sys_metadata')) { @@ -1043,18 +1047,6 @@ function draftConnectorAdvisories( })); } -/** - * [#34776] The node types the registered automation engine runs, read through - * its `getSealedNodeTypeVocabulary()`: the input the runtime publish gate - * refuses a flow node no executor runs with (`flow-node-type-no-executor`). - * - * Read per write, as the posture probes read their services, and recorded - * nowhere. `undefined` (the CLI's reading, under which no node type is judged) - * when the host has no registry, no automation service, or an engine that has - * not sealed its vocabulary yet: before the seal a plugin may still contribute - * 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. @@ -1086,6 +1078,18 @@ async function automationFlowNames( return Array.isArray(names) ? names.filter((n): n is string => typeof n === 'string') : undefined; } +/** + * [#34776] The node types the registered automation engine runs, read through + * its `getSealedNodeTypeVocabulary()`: the input the runtime publish gate + * refuses a flow node no executor runs with (`flow-node-type-no-executor`). + * + * Read per write, as the posture probes read their services, and recorded + * nowhere. `undefined` (the CLI's reading, under which no node type is judged) + * when the host has no registry, no automation service, or an engine that has + * not sealed its vocabulary yet: before the seal a plugin may still contribute + * a type, so "no executor" is not a verdict anyone may act on (AGENTS.md + * "Startup registry reads"). + */ export function sealedFlowNodeTypeVocabulary( this: { readonly getServicesRegistry?: () => Map }, ): readonly string[] | undefined { diff --git a/packages/metadata-protocol/src/protocol-door-requests.ts b/packages/metadata-protocol/src/protocol-door-requests.ts index 54faca54e40..e26a7196da6 100644 --- a/packages/metadata-protocol/src/protocol-door-requests.ts +++ b/packages/metadata-protocol/src/protocol-door-requests.ts @@ -28,6 +28,18 @@ type SaveMetaItemRequest = { * already holds. Set by server code only; no HTTP door forwards it. */ inheritedGrantObjects?: readonly string[], + /** + * [#35143] The names of the flows the same package copy writes, the copy + * door's plan (`importUnmanagedPackage`, whose items are the request's + * body; `duplicatePackage` copies stored rows, which the gate's own read + * of the stored flows already holds). A `flow` + * write's `subflow` / `map` call naming one of them is a call to a flow the + * copy holds once its loop ends, so the publish gate resolves it, as it + * resolves a flow of a `publishPackageDrafts` batch (`pending.flows`). + * Additive only: a name can let a call through, never refuse one. Set by + * server code only; no HTTP door forwards it. + */ + copyPlanFlowNames?: readonly string[], /** * [#32656] The locales the findings' user sentences are composed in, in * ladder order: the request's locale, then the workspace default diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index f484b6b3733..6208dd0b9a3 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -846,6 +846,15 @@ export class ProtocolPackageCommitsFacet { await host.installPackage({ manifest: plan.baseManifest, onStoredRow } as InstallPackageRequest & InstallPackageStoredRowHook); const copied: Array<{ type: string; name: string }> = []; + // [#35143] Every flow this install writes: the items go in one at a + // time, in the package's order, so a flow whose `subflow` / `map` step + // calls a sibling declared after it would meet a publish gate that + // holds no such flow yet. Stated on each flow write + // (`copyPlanFlowNames`), the sibling resolves, as a flow of a + // `publishPackageDrafts` batch does. + const copyPlanFlowNames = prepared + .filter((p) => (PLURAL_TO_SINGULAR[p.type] ?? p.type) === 'flow') + .map((p) => p.name); for (const item of prepared) { try { await host.saveMetaItem({ @@ -859,6 +868,7 @@ export class ProtocolPackageCommitsFacet { // [#30319] No `inheritedGrantObjects`, deliberately: the // package is the request's body, not a stored row, so its // permission sets are new writes and every grant is judged. + ...((PLURAL_TO_SINGULAR[item.type] ?? item.type) === 'flow' ? { copyPlanFlowNames } : {}), ...(actor ? { actor } : {}), }); copied.push({ type: item.type, name: item.name }); diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 104a3ca909a..c61f3bf9df9 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -1952,6 +1952,13 @@ export class ProtocolSaveFacet { // [#32656] The locales the door stated for the findings' user // sentences (`advisories[].userMessage`, the 422's `issues[]`). ...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}), + // [#35143] A package copy's flows, stated by its door: a flow the + // same copy loop writes later resolves as a `subflow` / `map` + // target, as a batch's own flow drafts do. Names only, on a flow + // write only, so no other rule reads them. + ...(singularType === 'flow' && request.copyPlanFlowNames !== undefined && request.copyPlanFlowNames.length > 0 + ? { pending: { flows: request.copyPlanFlowNames.map((name) => ({ name })) } } + : {}), // [#20611] The redaction context. The read path withholds a // credential from every served definition (a flow's start-node // `config.secret`), so a body saved back after a read arrives 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 d3e30ef4099..84b51e0970f 100644 --- a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts @@ -5781,15 +5781,33 @@ describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', }); /** A protocol whose automation engine holds `engineFlows`, and whose registry lists `registryFlows`. */ - const protocolWith = (engineFlows: readonly string[] | undefined, registryFlows: readonly string[] = []) => { + const protocolWith = ( + engineFlows: readonly string[] | undefined, + registryFlows: readonly string[] = [], + options: { listFlows?: () => Promise; namesRead?: () => Promise } = {}, + ) => { const { engine, rows } = makeStubEngine(); const objectsOf = engine.registry.listItems; engine.registry.listItems = (type: string) => type === 'flow' ? registryFlows.map((name) => ({ name })) : objectsOf(type); + // The gate's read of the stored flow names, told apart by its + // projection: every read of it is recorded, and `namesRead` replaces + // its answer. + const namesReads: Array<{ where: unknown; fields: unknown }> = []; + const find = engine.find; + engine.find = async (table: string, opts: { where: Record; fields?: unknown }) => { + if (table === 'sys_metadata' && Array.isArray(opts.fields) && opts.fields.join() === 'name') { + namesReads.push({ where: opts.where, fields: opts.fields }); + if (options.namesRead) return options.namesRead(); + } + return find(table, opts); + }; const services = new Map(); - if (engineFlows !== undefined) services.set('automation', { listFlows: async () => [...engineFlows] }); + if (engineFlows !== undefined) { + services.set('automation', { listFlows: options.listFlows ?? (async () => [...engineFlows]) }); + } const protocol = new ObjectStackProtocolImplementation(engine, () => services as Map, 'env_test'); - return { protocol: protocol as any, rows }; + return { protocol: protocol as any, rows, namesReads }; }; const publish = (protocol: any, item: { name: string }) => protocol.saveMetaItem({ type: 'flow', name: item.name, item }); @@ -5822,6 +5840,54 @@ describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', expect((await publish(protocol, calling('parent', 'missing_child'))).success).toBe(true); }); + it('reads the stored names once, projected to name, and not at all for a flow that calls no other flow', async () => { + const { protocol, namesReads } = protocolWith(['child']); + await publish(protocol, calling('parent', 'child')); + expect(namesReads).toEqual([{ where: { type: { $in: ['flow', 'flows'] } }, fields: ['name'] }]); + // A step calling the flow itself is no call to another flow. + await publish(protocol, calling('selfie', 'selfie')); + await publish(protocol, { + name: 'plain', + label: 'plain', + type: 'autolaunched', + status: 'active', + nodes: [{ id: 'start', type: 'start', label: 'Start' }], + edges: [], + }); + expect(namesReads).toHaveLength(1); + }); + + it('judges nothing when the stored read fails, and says so once at warn', async () => { + const { protocol } = protocolWith(['child'], [], { + namesRead: async () => { throw new Error('connection reset'); }, + }); + expect((await publish(protocol, calling('parent', 'missing_child'))).success).toBe(true); + const said = warn.mock.calls.filter((c) => String(c[0]).includes('could not read the stored flows')); + expect(said).toHaveLength(1); + expect(String(said[0]![0])).toContain('connection reset'); + }); + + it("judges nothing when the automation engine's flow list fails, and says so once at warn", async () => { + const { protocol } = protocolWith(['child'], [], { + listFlows: async () => { throw new Error('engine not ready'); }, + }); + expect((await publish(protocol, calling('parent', 'missing_child'))).success).toBe(true); + const said = warn.mock.calls.filter((c) => String(c[0]).includes("could not list the automation engine's flows")); + expect(said).toHaveLength(1); + expect(String(said[0]![0])).toContain('engine not ready'); + }); + + it('a missing metadata table is no stored flow: the other sources still decide', async () => { + const missing = async () => { throw new Error('SQLITE_ERROR: no such table: sys_metadata'); }; + const { protocol } = protocolWith(['engine_child'], ['packaged_child'], { namesRead: missing }); + expect((await publish(protocol, calling('a', 'engine_child'))).success).toBe(true); + expect((await publish(protocol, calling('b', 'packaged_child'))).success).toBe(true); + const err = await publish(protocol, calling('c', 'missing_child')).catch((e: any) => e); + expect(err.status).toBe(422); + expect(err.issues.map((i: { rule: string }) => i.rule)).toContain('flow-subflow-unknown'); + expect(warn.mock.calls.filter((c) => String(c[0]).includes('could not read the stored flows'))).toEqual([]); + }); + 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({ diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 9dabc486757..23e455d866e 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1826,9 +1826,9 @@ export class ObjectStackProtocolImplementation implements packageId?: string | null; /** * [#10377] The declarations this write's own BATCH is publishing - * alongside it, when the caller HAS a batch. Only - * `publishPackageDrafts` does; every other door writes one item, so its - * closure is the live universe and it states nothing here. + * alongside it, when the caller HAS a batch: `publishPackageDrafts`, and a + * package copy's flow write, its copy's flow names only (#35143). Every other + * door writes one item, so its closure is the live universe: it states none. * * Threaded rather than gathered: the batch's pending drafts are * `sys_metadata` rows the caller has already listed and is about to diff --git a/packages/metadata-protocol/src/runtime-authoring-gate.ts b/packages/metadata-protocol/src/runtime-authoring-gate.ts index 9931be0e6e9..2e5bed198a4 100644 --- a/packages/metadata-protocol/src/runtime-authoring-gate.ts +++ b/packages/metadata-protocol/src/runtime-authoring-gate.ts @@ -241,6 +241,22 @@ function walkNodes( return out; } +/** + * [#35143] Does this flow body call another flow by name: a `subflow` or + * `map` node, at any depth, whose `config.flowName` is a non-empty string + * other than the flow's own name? The question the publish gate asks before + * it reads the deployment's flow names, so a flow with no such call pays no + * read for them (`validateFlowSubflowTargets` judges nothing else). + */ +export function flowCallsAnotherFlow(body: unknown, ownName: string): boolean { + if (!isRec(body)) return false; + return walkNodes(body, 'flows[0]').some(({ node }) => { + if (node.type !== 'subflow' && node.type !== 'map') return false; + const called = isRec(node.config) ? node.config.flowName : undefined; + return typeof called === 'string' && called.trim() !== '' && called.trim() !== ownName; + }); +} + /** * Does this flow bind to the SCHEDULE trigger? * 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 7d090e3b0af..269b5ca53d1 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 @@ -11,7 +11,8 @@ import type { SemanticMigration } from '../../types.js'; export const entry: SemanticMigration = { id: 'publish-refuses-flows-that-save-and-do-not-run', surface: - 'Seven author-time flow errors, run by the runtime publish gate and by `os validate` / `lint` / `compile` / `build`: ' + 'Eight author-time flow errors at the runtime publish gate, seven of them also run by `os validate` / `lint` / ' + + '`compile` / `build`: ' + 'a record-triggered flow with no `objectName` (`flow-trigger-object-missing`); a start condition, an edge ' + 'condition or a `decision` branch that compares a select field with one of its option labels, or a ' + '`get_record` / `update_record` / `delete_record` or `timeRelative` `filter` operand that is one, where the row ' @@ -20,7 +21,9 @@ export const entry: SemanticMigration = { + '`maxRecords` beside `timeRelative` instead of inside it (`flow-time-relative-key-misplaced`); a `timeRelative.dateField` ' + 'that is not a `date` / `datetime` field of the object (`flow-time-relative-date-field-invalid`); a create / update ' + 'node that writes a select field a literal no option carries (`flow-node-write-unknown-option`); a create / update ' - + 'node that writes a date field the text of a date helper call such as `today()` (`flow-node-write-date-helper-text`)', + + 'node that writes a date field the text of a date helper call such as `today()` (`flow-node-write-date-helper-text`); ' + + 'and, at the publish gate only, a `subflow` / `map` step whose `config.flowName` names no flow the deployment ' + + 'holds (`flow-subflow-unknown`, a warning on the CLI)', replacement: '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 ' @@ -33,12 +36,17 @@ export const entry: SemanticMigration = { + 'time-relative schedule, so the sweep never runs; a misplaced `filter` / `maxRecords` is ignored, so the sweep reads ' + 'every row; a sweep over a field that is not a date matches no record; a write of an unknown option is refused ' + '`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 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.', + + 'flows are not rewritten or refused at boot. The next publish of a flow that carries one of the eight errors is ' + + 'refused with the fix named. 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 package install, or one ' + + 'the automation engine holds) fails on every run: the publish gate refuses it, and `os validate` warns, since ' + + 'another installed package may ship the called flow. A package install writes its flows one at a time, so a flow ' + + 'calling a sibling the package declares after it installs; a copy installed under another namespace renames its ' + + 'flows but not the `config.flowName` that calls them, so its install is refused unless the deployment holds the ' + + 'old name. Two warnings refuse nothing at either door: `flow-schedule-timezone-missing` (reported by `os validate` ' + + 'and on the publish answer) and `flow-create-update-pair` (reported by `os validate` only, where the stack holds ' + + 'both flows). They, and `flow-subflow-unknown` on the CLI, make `os validate --strict` exit 1 as any warning does.', acceptanceCriteria: - 'os validate reports none of the seven errors; a publish of every flow the package carries succeeds.', + 'os validate reports none of the seven errors it runs and no `flow-subflow-unknown` warning for a flow the ' + + 'deployment lacks; a publish or package install of every flow the package carries succeeds.', }; From 531aa7b28fb3d329ff2c9864c7f36158cca13edd Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 12:16:34 +0000 Subject: [PATCH 6/8] docs(lint): the subflow target refusal's package-install reading in the changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSjBfkaFUVwRa3pdUK --- .changeset/35143-subflow-target-publish-gate.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.changeset/35143-subflow-target-publish-gate.md b/.changeset/35143-subflow-target-publish-gate.md index 146ab626b46..70dec90c6bf 100644 --- a/.changeset/35143-subflow-target-publish-gate.md +++ b/.changeset/35143-subflow-target-publish-gate.md @@ -15,7 +15,8 @@ Metadata-protocol: narrowed 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. +- **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 or package install 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. The names are read only for a flow that calls another flow, and the stored ones in one read of the `name` column. +- **A package install.** An unmanaged install writes its flows one at a time and states the package's flow names on each, so a flow calling a sibling the package declares after it installs. A copy installed under another namespace renames its flows but not the `config.flowName` that calls them, so its install is refused, and rolled back whole, unless the deployment holds the old name. - **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. From a7c00fdd85944662fb7546646cb640b97e45cf6e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 12:24:23 +0000 Subject: [PATCH 7/8] test(metadata-protocol): type the subflow-target pins' publish helper and warn filters Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSjBfkaFUVwRa3pdUK --- .../src/protocol.runtime-authoring-gate.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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 84b51e0970f..821fcf68cdc 100644 --- a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts @@ -5809,7 +5809,7 @@ describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', const protocol = new ObjectStackProtocolImplementation(engine, () => services as Map, 'env_test'); return { protocol: protocol as any, rows, namesReads }; }; - const publish = (protocol: any, item: { name: string }) => + const publish = (protocol: any, item: { name: string; [key: string]: unknown }) => protocol.saveMetaItem({ type: 'flow', name: item.name, item }); it('refuses an active save calling a flow nothing in the deployment holds', async () => { @@ -5862,7 +5862,7 @@ describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', namesRead: async () => { throw new Error('connection reset'); }, }); expect((await publish(protocol, calling('parent', 'missing_child'))).success).toBe(true); - const said = warn.mock.calls.filter((c) => String(c[0]).includes('could not read the stored flows')); + const said = warn.mock.calls.filter((c: unknown[]) => String(c[0]).includes('could not read the stored flows')); expect(said).toHaveLength(1); expect(String(said[0]![0])).toContain('connection reset'); }); @@ -5872,7 +5872,7 @@ describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', listFlows: async () => { throw new Error('engine not ready'); }, }); expect((await publish(protocol, calling('parent', 'missing_child'))).success).toBe(true); - const said = warn.mock.calls.filter((c) => String(c[0]).includes("could not list the automation engine's flows")); + const said = warn.mock.calls.filter((c: unknown[]) => String(c[0]).includes("could not list the automation engine's flows")); expect(said).toHaveLength(1); expect(String(said[0]![0])).toContain('engine not ready'); }); @@ -5885,7 +5885,7 @@ describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', const err = await publish(protocol, calling('c', 'missing_child')).catch((e: any) => e); expect(err.status).toBe(422); expect(err.issues.map((i: { rule: string }) => i.rule)).toContain('flow-subflow-unknown'); - expect(warn.mock.calls.filter((c) => String(c[0]).includes('could not read the stored flows'))).toEqual([]); + expect(warn.mock.calls.filter((c: unknown[]) => String(c[0]).includes('could not read the stored flows'))).toEqual([]); }); it('a flow the same batch publishes resolves; without it the call is refused', () => { From 93f3643eafd6aa5d25ec772a661ad83e6e18fdb9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 14:12:12 +0000 Subject: [PATCH 8/8] fix(metadata-protocol): a disabled package's flows count as subflow targets at the publish gate The gate's names read the served registry listing, which drops a disabled package's items, so after a restart a call to such a flow was refused with a sentence saying no installed package holds it. The names now read the registry with its disabled packages, as the docblock and the changeset said. Docblocks, the explanation, the upgrade entry and the changeset's exports list now name a package install's flows and saveMetaItem's copyPlanFlowNames. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSjBfkaFUVwRa3pdUK --- .../35143-subflow-target-publish-gate.md | 4 +-- packages/lint/src/authoring-rules.ts | 5 +-- packages/lint/src/rule-explanations.ts | 6 ++-- packages/lint/src/runtime-gate.ts | 5 +-- .../src/validate-flow-trigger-readiness.ts | 7 ++-- .../src/protocol-authoring-gate.ts | 35 +++++++++++++++---- .../protocol.runtime-authoring-gate.test.ts | 24 +++++++++++-- .../src/runtime-authoring-gate.ts | 20 ++++++----- ...-refuses-flows-that-save-and-do-not-run.ts | 8 ++--- 9 files changed, 81 insertions(+), 33 deletions(-) diff --git a/.changeset/35143-subflow-target-publish-gate.md b/.changeset/35143-subflow-target-publish-gate.md index 70dec90c6bf..1d515f4187e 100644 --- a/.changeset/35143-subflow-target-publish-gate.md +++ b/.changeset/35143-subflow-target-publish-gate.md @@ -16,11 +16,11 @@ Metadata-protocol: narrowed 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 or package install 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. The names are read only for a flow that calls another flow, and the stored ones in one read of the `name` column. -- **A package install.** An unmanaged install writes its flows one at a time and states the package's flow names on each, so a flow calling a sibling the package declares after it installs. A copy installed under another namespace renames its flows but not the `config.flowName` that calls them, so its install is refused, and rolled back whole, unless the deployment holds the old name. +- **A package install.** An unmanaged install writes its flows one at a time and states the package's flow names on each, so a flow calling a sibling the package declares after it installs. A copy installed under another namespace renames its flows whose names carry the source prefix, but not the `config.flowName` that calls them, so its install is refused, and rolled back whole, unless the deployment holds the old name. - **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. +- **Exports.** `@objectstack/lint`: `validateFlowSubflowTargets` takes an optional second argument (`FlowSubflowTargetOptions`, `deploymentFlowNames`); `AuthoringRuleContext` gains `deploymentFlowNames`; `runRuntimeAuthoringRules` takes an optional `deploymentFlowNames`. `@objectstack/metadata-protocol`: `saveMetaItem`'s request gains an optional, server-only `copyPlanFlowNames` (the flows the same package install writes; set by the unmanaged install, forwarded by no HTTP door). All optional; an omitted value keeps the earlier behaviour. FROM → TO: diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index deca132f79a..3ef71244ffa 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -524,8 +524,9 @@ export interface AuthoringRuleContext { 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 + * flows (a disabled package's included), the stored flow rows in every + * state (drafts included), the flows the written item's publish batch or + * package install 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, diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 552a5e18823..d74df3ace5c 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -7182,9 +7182,9 @@ const FLOW_SUBFLOW_UNKNOWN_EXPLANATION: RuleExplanation = { 'name, the step fails on every run, and every run of the calling flow fails with it.', '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.', + 'installed package\'s flows (a disabled package\'s too), the stored flows in every state (a draft ' + + 'counts), the flows published in the same batch or installed in the same package, 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 2db5b72dff0..182c0e72de2 100644 --- a/packages/lint/src/runtime-gate.ts +++ b/packages/lint/src/runtime-gate.ts @@ -1469,8 +1469,9 @@ export function runRuntimeAuthoringRules(args: { 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). + * host read them (every installed package's flows, a disabled package's + * included, the stored flow rows in every state, the flows of the batch or + * package install, 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. diff --git a/packages/lint/src/validate-flow-trigger-readiness.ts b/packages/lint/src/validate-flow-trigger-readiness.ts index decece52698..16a6b933405 100644 --- a/packages/lint/src/validate-flow-trigger-readiness.ts +++ b/packages/lint/src/validate-flow-trigger-readiness.ts @@ -1929,9 +1929,10 @@ function signatureUnusableFinding( * - 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 + * (`deploymentFlowNames`: every installed package's flows, a disabled + * package's included, the stored rows in every state, drafts included, + * this publish batch's or package install's own flows, 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 diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 0e9182689ab..1c15da3a32c 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -649,7 +649,7 @@ export async function judgeRuntimeAuthoringRules( // flow. A flow with no such call pays no read for it. `undefined` when one // source could not be read, and then no call is judged. const deploymentFlowNames = singular === 'flow' && flowCallsAnotherFlow(evt.body, evt.name) - ? await deploymentFlowNamesOf.call(this, listRegisteredCollection('flow', 'flows')) + ? await deploymentFlowNamesOf.call(this, registeredFlowsWithDisabled(this.engine?.registry)) : undefined; // [#26188] Is a hierarchy resolver mounted — a host fact of the same kind, @@ -716,15 +716,38 @@ export async function judgeRuntimeAuthoringRules( return verdict; } +/** + * [#35143] Every flow the registry holds, a DISABLED package's included + * (`includeDisabledPackages`): the served listing drops a disabled package's + * items, and after a restart neither the stored rows nor the engine hold a + * disabled code package's flow, so a call to it would read as a call to + * nothing. Such a flow is held and not runnable, as a draft is, and it runs + * again once its package is enabled. Same singular-then-plural read as the + * gate's other registry collections; a registry that cannot list answers none. + */ +function registeredFlowsWithDisabled(registry: unknown): unknown[] { + const listItems = (registry as { listItems?: (type: string, packageId?: string, options?: { includeDisabledPackages?: boolean }) => unknown[] } | undefined)?.listItems; + if (typeof listItems !== 'function') return []; + try { + const list = (type: string): unknown[] => [...listItems.call(registry, type, undefined, { includeDisabledPackages: true })]; + const items = list('flow'); + return items.length > 0 ? items : list('flows'); + } catch { + return []; + } +} + /** * [#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}). + * installed package's, a disabled package's included: + * {@link registeredFlowsWithDisabled}), 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 flows of the write's + * publish batch or package install (`pending.flows`) 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 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 821fcf68cdc..18b484fa356 100644 --- a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts @@ -5784,12 +5784,20 @@ describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', const protocolWith = ( engineFlows: readonly string[] | undefined, registryFlows: readonly string[] = [], - options: { listFlows?: () => Promise; namesRead?: () => Promise } = {}, + options: { + listFlows?: () => Promise; + namesRead?: () => Promise; + /** Flows of a DISABLED package: listed only when the read asks for `includeDisabledPackages`, as the registry does. */ + disabledPackageFlows?: readonly string[]; + } = {}, ) => { const { engine, rows } = makeStubEngine(); const objectsOf = engine.registry.listItems; - engine.registry.listItems = (type: string) => - type === 'flow' ? registryFlows.map((name) => ({ name })) : objectsOf(type); + engine.registry.listItems = (type: string, _packageId?: string, opts?: { includeDisabledPackages?: boolean }) => + type === 'flow' + ? [...registryFlows, ...(opts?.includeDisabledPackages === true ? options.disabledPackageFlows ?? [] : [])] + .map((name) => ({ name })) + : objectsOf(type); // The gate's read of the stored flow names, told apart by its // projection: every read of it is recorded, and `namesRead` replaces // its answer. @@ -5835,6 +5843,16 @@ describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', expect((await publish(protocol, calling('d', 'a'))).success).toBe(true); }); + it("lets a call through to a disabled package's flow, which the served listing leaves out", async () => { + // After a restart neither the stored rows nor the engine hold a disabled + // code package's flow; only the registry, read with its disabled packages. + const { protocol } = protocolWith(['other'], [], { disabledPackageFlows: ['parked_child'] }); + expect((await publish(protocol, calling('parent', 'parked_child'))).success).toBe(true); + const err = await publish(protocol, calling('other_parent', 'missing_child')).catch((e: any) => e); + expect(err.status).toBe(422); + expect(err.issues.map((i: { rule: string }) => i.rule)).toContain('flow-subflow-unknown'); + }); + 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); diff --git a/packages/metadata-protocol/src/runtime-authoring-gate.ts b/packages/metadata-protocol/src/runtime-authoring-gate.ts index 2e5bed198a4..7a52fd69e64 100644 --- a/packages/metadata-protocol/src/runtime-authoring-gate.ts +++ b/packages/metadata-protocol/src/runtime-authoring-gate.ts @@ -797,7 +797,8 @@ export const CLOSURE_CONTEXT_KEY_BY_TYPE = { // 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. A FLOW write reads only their names, so a flow - // the batch publishes resolves as a subflow target ({@link withPendingFlowNames}). + // the batch publishes, or the same package install writes, 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 @@ -1009,9 +1010,10 @@ export function objectWriteFlowSubjects( } /** - * 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. + * The deployment's flow names with this batch's own flow drafts added (or a + * package install's flows, which its door states the same way): a flow + * published in the same batch or install 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); @@ -1354,7 +1356,9 @@ export function evaluateRuntimeAuthoringGate(args: { * * Stated by the batch door (`publishPackageDrafts`), which is the only * caller that HAS a batch; the single-item door publishes one item, so its - * batch is itself and it passes nothing. Absent ⇒ the closure is the live + * batch is itself and it passes nothing, except [#35143] a package + * install's flow write, which states its install's flow names as + * `flows` (`copyPlanFlowNames`; names only). Absent ⇒ the closure is the live * universe alone, exactly as before, which is the correct answer for every * write that is not part of a package publish rather than a fallback. * @@ -1503,9 +1507,9 @@ export function evaluateRuntimeAuthoringGate(args: { * 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 + * the host holds, of the #6285 kind. The batch's own flow drafts, or a + * package install's flows (`pending.flows`), are added here, so a flow + * published in the same batch or install 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. 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 269b5ca53d1..b7a29a56dfd 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 @@ -40,10 +40,10 @@ export const entry: SemanticMigration = { + 'refused with the fix named. 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 package install, or one ' + 'the automation engine holds) fails on every run: the publish gate refuses it, and `os validate` warns, since ' - + 'another installed package may ship the called flow. A package install writes its flows one at a time, so a flow ' - + 'calling a sibling the package declares after it installs; a copy installed under another namespace renames its ' - + 'flows but not the `config.flowName` that calls them, so its install is refused unless the deployment holds the ' - + 'old name. Two warnings refuse nothing at either door: `flow-schedule-timezone-missing` (reported by `os validate` ' + + 'another installed package may ship the called flow. A package install writes its flows one at a time and states ' + + 'the names of every flow it carries on each write, so a flow calling a sibling the package declares after it ' + + 'installs; a copy installed under another namespace renames its flows whose names carry the source prefix but not ' + + 'the `config.flowName` that calls them, so its install is refused unless the deployment holds the old name. Two warnings refuse nothing at either door: `flow-schedule-timezone-missing` (reported by `os validate` ' + 'and on the publish answer) and `flow-create-update-pair` (reported by `os validate` only, where the stack holds ' + 'both flows). They, and `flow-subflow-unknown` on the CLI, make `os validate --strict` exit 1 as any warning does.', acceptanceCriteria: