diff --git a/.changeset/35256-draft-connector-advisory.md b/.changeset/35256-draft-connector-advisory.md new file mode 100644 index 00000000000..1e340b05288 --- /dev/null +++ b/.changeset/35256-draft-connector-advisory.md @@ -0,0 +1,12 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +Clause-②: yes — widening: the draft verdict gains an advisory for a draft flow whose `connector_action` names a connector or action the runtime cannot dispatch; advisory only, never a refusal (the probe "never fails the publish"), so no save or publish accepted today is refused. Seat runs a contract read before ready. +Metadata-protocol: none + +fix(metadata-protocol): a flow draft's verdict says when a connector step cannot dispatch + +The publish's build probe `flow_connector_action_unresolved` warns, after a flow is published, that a `connector_action` step names a connector or action this environment cannot dispatch, so every run that reaches the step fails. The draft verdict (`draftPublishJudgement`, read by Studio's draft review and by the MCP draft tools' `verdict.advisories`) now says the same thing before Publish is pressed: one advisory per such step, rule `flow_connector_action_unresolved`, `severity: 'warning'`, located at the step (`flows[0].nodes[N].connectorConfig`, which the draft read serves as `nodes.N.connectorConfig`), with the probe's own `message`, its `fix` as the `hint`, and its user sentence in the read's language. + +It is never a refusal: a draft with such a step still saves, reads valid, and publishes, as before. The publish gate's own answer is unchanged, and the build probe reports exactly what it reported before; both doors now ask one shared lookup (`unresolvedConnectorSteps`). A host without an automation service, or one without the connector lookups, judges nothing, as the probe does. diff --git a/packages/metadata-protocol/src/build-probes.ts b/packages/metadata-protocol/src/build-probes.ts index 3ea90398dc3..e342534ca4c 100644 --- a/packages/metadata-protocol/src/build-probes.ts +++ b/packages/metadata-protocol/src/build-probes.ts @@ -1259,76 +1259,23 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise x.type === 'flow')) { const body = asRec(await readItem('flow', p.name)); if (!body) continue; - let graphs: ReturnType; - try { - graphs = collectFlowGraphs(body as Parameters[0]); - } catch { - continue; - } - for (const node of graphs.flatMap((g) => g.nodes as readonly unknown[]).map(asRec)) { - if (!node || node.type !== 'connector_action') continue; - const cfg = asRec(node.connectorConfig); - const connectorId = typeof cfg?.connectorId === 'string' ? cfg.connectorId : undefined; - const actionId = typeof cfg?.actionId === 'string' ? cfg.actionId : undefined; - if (!connectorId || !actionId) continue; // the schema's refusal, not a probe's - const nodeId = typeof node.id === 'string' ? node.id : 'connector_action'; - let cause: 'refused' | 'no-action' | 'degraded' | undefined; - let why = ''; - try { - const instance = typeof automation.resolveConnectorInstanceFor === 'function' - ? automation.resolveConnectorInstanceFor(connectorId, callerPackageId) - : ({ status: 'instance', packageId: callerPackageId } as const); - if (instance.status === 'refused') { - cause = 'refused'; - why = instance.refusal.message; - } else { - const packageId = instance.status === 'instance' ? instance.packageId : undefined; - const handler = packageId === undefined ? undefined : automation.resolveConnectorAction(connectorId, actionId, packageId); - if (!handler) { - const degraded = packageId === undefined ? undefined : automation.getConnectorDegradedReason?.(connectorId, packageId); - cause = degraded ? 'degraded' : 'no-action'; - why = degraded - ? `connector "${connectorId}" is degraded — ${degraded.replace(/\.\s*$/, '')}` - : `no connector on this environment serves "${connectorId}.${actionId}"`; - } - } - } catch { - continue; // a lookup that threw judges nothing - } - if (!cause) continue; + for (const step of unresolvedConnectorSteps(p.name, body, automation, opts.packageId ?? null, userTextLocales)) { issues.push({ layer: 'runtime', severity: 'warning', artifact: { type: 'flow', name: p.name }, - ref: { type: 'connector', name: connectorId, member: actionId }, + ref: { type: 'connector', name: step.connectorId, member: step.actionId }, code: 'flow_connector_action_unresolved', - message: - `Flow "${p.name}" step "${nodeId}" (connector_action) dispatches "${connectorId}.${actionId}", but ${why} — ` + - 'every run that reaches the step fails.', - fix: cause === 'degraded' - ? `Resolve what keeps connector "${connectorId}" degraded (its upstream or its credential), then re-run the flow.` - : cause === 'refused' - ? `Make "${connectorId}" name one connector from this flow's package (declare the dependency, or hold the connector in the package), then republish.` - : `Point the step's connectorConfig at a connector and action this environment has, or install the package or plugin that provides "${connectorId}".`, - userMessage: say('flow_connector_action_unresolved', { - flow: labelIn(body, p.name), - step: labelIn(node, nodeId), - connector: connectorId, - cause, - }), + message: step.message, + fix: step.fix, + userMessage: step.userMessage, }); } } @@ -1337,6 +1284,118 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise; + try { + graphs = collectFlowGraphs(flow as Parameters[0]); + } catch { + return steps; + } + const userTextLocale = buildProbeUserTextLocale(userTextLocales); + const labelIn = (rec: Rec | undefined, name: string): string => { + const label = resolveI18nLabel(rec?.label as I18nLabel | undefined, userTextLocale); + return typeof label === 'string' && label.trim() ? label : name; + }; + for (const graph of graphs) { + // The graph's own list, as written: an index is where the author put the step. + const written: unknown = graph.path.reduce((at, key) => asRec(at)?.[key] ?? asArr(at)[key as number], flow); + const listed = asArr(asRec(written)?.nodes); + const base = graph.path.map((key) => (typeof key === 'number' ? `[${key}]` : `.${key}`)).join('').replace(/^\./, ''); + for (const node of (graph.nodes as readonly unknown[]).map(asRec)) { + if (!node || node.type !== 'connector_action') continue; + const cfg = asRec(node.connectorConfig); + const connectorId = typeof cfg?.connectorId === 'string' ? cfg.connectorId : undefined; + const actionId = typeof cfg?.actionId === 'string' ? cfg.actionId : undefined; + if (!connectorId || !actionId) continue; // the schema's refusal, not a probe's + const nodeId = typeof node.id === 'string' ? node.id : 'connector_action'; + let cause: UnresolvedConnectorStep['cause'] | undefined; + let why = ''; + try { + const instance = typeof automation.resolveConnectorInstanceFor === 'function' + ? automation.resolveConnectorInstanceFor(connectorId, callerPackageId) + : ({ status: 'instance', packageId: callerPackageId } as const); + if (instance.status === 'refused') { + cause = 'refused'; + why = instance.refusal.message; + } else { + const packageId = instance.status === 'instance' ? instance.packageId : undefined; + const handler = packageId === undefined ? undefined : automation.resolveConnectorAction(connectorId, actionId, packageId); + if (!handler) { + const degraded = packageId === undefined ? undefined : automation.getConnectorDegradedReason?.(connectorId, packageId); + cause = degraded ? 'degraded' : 'no-action'; + why = degraded + ? `connector "${connectorId}" is degraded — ${degraded.replace(/\.\s*$/, '')}` + : `no connector on this environment serves "${connectorId}.${actionId}"`; + } + } + } catch { + continue; // a lookup that threw judges nothing + } + if (!cause) continue; + steps.push({ + path: `${base ? `${base}.` : ''}nodes[${listed.indexOf(node)}]`, + nodeId, + connectorId, + actionId, + cause, + message: + `Flow "${flowName}" step "${nodeId}" (connector_action) dispatches "${connectorId}.${actionId}", but ${why} — ` + + 'every run that reaches the step fails.', + fix: cause === 'degraded' + ? `Resolve what keeps connector "${connectorId}" degraded (its upstream or its credential), then re-run the flow.` + : cause === 'refused' + ? `Make "${connectorId}" name one connector from this flow's package (declare the dependency, or hold the connector in the package), then republish.` + : `Point the step's connectorConfig at a connector and action this environment has, or install the package or plugin that provides "${connectorId}".`, + userMessage: buildProbeUserMessage('flow_connector_action_unresolved', { + flow: labelIn(flow, flowName), + step: labelIn(node, nodeId), + connector: connectorId, + cause, + }, userTextLocales), + }); + } + } + return steps; +} + /** * The one field on a child object that points back at `parent`, the * foreign key a roll-up resolves when it names no `relationshipField`: diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index b39496855a8..6f8bb43a759 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -55,6 +55,7 @@ import { noPendingDraftError } from './protocol-authoring-refusals.js'; import { memberOption } from './protocol-bundle-members.js'; import { evaluateRuntimeAuthoringGate } 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'; import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name'; import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared'; @@ -726,7 +727,14 @@ function packagedRuleCopyRefusalOf( } /** The members {@link draftPublishJudgement} and {@link draftPublishVerdict} read. */ -type DraftVerdictHost = RuntimeRulesHost & Pick; +type DraftVerdictHost = RuntimeRulesHost & Pick & { + /** + * [#35256] The protocol's services registry reader, read per call and + * recorded nowhere: {@link draftConnectorAdvisories} asks its `automation` + * service, as {@link sealedFlowNodeTypeVocabulary} does. + */ + servicesRegistry: () => (() => Map) | undefined; +}; /** * [#34818] What publishing a stored draft would answer: the refusal's issues @@ -734,6 +742,12 @@ type DraftVerdictHost = RuntimeRulesHost & Pick 0 ? [...told, ...issues] : issues, advisories: verdict.advisories }; + const connectorAdvisories = singular === 'flow' + ? draftConnectorAdvisories(this, draft.name, judged, draft.packageId, draft.userTextLocales) + : []; + return { + refusals: told.length > 0 ? [...told, ...issues] : issues, + advisories: connectorAdvisories.length > 0 ? [...verdict.advisories, ...connectorAdvisories] : verdict.advisories, + }; +} + +/** + * [#35256] What the publish's build probe `flow_connector_action_unresolved` + * will report for this flow draft, said on the draft verdict first: one + * ADVISORY per `connector_action` step no connector this environment serves + * can dispatch, in the gate-issue shape Studio's draft read and the MCP draft + * tools read (`verdict.advisories`). Never a refusal: the probe never fails a + * publish, so the draft verdict does not either. + * + * One judgement, {@link unresolvedConnectorSteps}, the probe's own: the same + * lookups for the draft's package, the same `message`, the probe's `fix` as + * the `hint` and its user sentence in the read's locales; the rule id is the + * probe's code. Only the draft door asks it: the publish's gate + * (`assertRuntimeAuthoringRules`) does not, since its probe reports it. The + * lookups are in-memory registry reads with no storage read, so a draft list + * judging many drafts pays no per-pass cache. No automation service, or one + * without the lookups, judges nothing, as the probe does. + */ +function draftConnectorAdvisories( + host: Pick, + name: string, + body: unknown, + packageId: string | null, + userTextLocales: readonly (string | undefined)[] | undefined, +): RuntimeAuthoringIssue[] { + let automation: unknown; + try { + automation = host.servicesRegistry()?.().get('automation'); + } catch { + return []; + } + if (!automation || typeof (automation as ProbeAutomation).resolveConnectorAction !== 'function') return []; + return unresolvedConnectorSteps(name, body, automation as ProbeAutomation, packageId, userTextLocales ?? []) + .map((step) => ({ + rule: 'flow_connector_action_unresolved', + // A flow write is the sole member of its snapshot collection, so `flows[0]` IS this draft. + path: `flows[0].${step.path}.connectorConfig`, + where: `flow "${name}" · node "${step.nodeId}"`, + message: step.message, + hint: step.fix, + severity: 'warning' as const, + userMessage: step.userMessage, + })); } /** diff --git a/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts b/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts index be522f9254e..99623be33dd 100644 --- a/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts +++ b/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts @@ -1495,3 +1495,185 @@ describe('[#34766] the public draft publish verdict judges the stored draft', () expect((await protocol.draftPublishJudgement({ type: 'flow', name: 'deal_followup', packageId: PKG })).refusals).toEqual([]); }); }); + +/** + * [#35256] The publish's build probe `flow_connector_action_unresolved` reads no + * landed data, only the flow body and the automation engine's connector + * lookups, so the draft verdict asks it too: one ADVISORY per connector step no + * connector can dispatch, in the gate-issue shape the draft read and the MCP + * draft tools read. Pinned: the advisory's rule, path, words and locale; a + * resolving step is silent; the publish is not refused by it; the publish + * gate's own answer (`assertRuntimeAuthoringRules`) does not carry it; and the + * landed probe reports the same words for the same body (one judgement). + */ +describe('[#35256] a flow draft whose connector step cannot dispatch reads the probe\'s advisory', () => { + let warn: ReturnType; + beforeEach(() => { + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + delete process.env.OS_ALLOW_UNLINTED_METADATA_WRITES; + }); + afterEach(() => { + warn.mockRestore(); + }); + + const RULE = 'flow_connector_action_unresolved'; + const syncFlow = { + name: 'order_sync', + label: '订单同步', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'push', type: 'connector_action', label: '推送订单', connectorConfig: { connectorId: 'erp', actionId: 'push_order', input: {} } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'push' }, + { id: 'e2', source: 'push', target: 'end' }, + ], + }; + + /** An engine that knows `known` (connector.action) and asks for the flow's package. */ + function automationKnowing(known: readonly string[], over: Record = {}) { + const asked: Array<[string, string | null]> = []; + const automation = { + resolveConnectorInstanceFor: (id: string, pkg: string | null) => { + asked.push([id, pkg]); + return { status: 'instance' as const, packageId: pkg }; + }, + resolveConnectorAction: (id: string, action: string) => (known.includes(`${id}.${action}`) ? async () => ({}) : undefined), + getConnectorDegradedReason: () => undefined, + ...over, + }; + return { automation, asked }; + } + + function protocolWith(automation: unknown) { + const { engine } = makeStubEngine(); + const services = new Map(automation === undefined ? [] : [['automation', automation]]); + return new ObjectStackProtocolImplementation(engine, () => services as Map); + } + + it('an unknown connector action: one warning advisory with the rule and the step\'s path, and no refusal', async () => { + const { automation, asked } = automationKnowing([]); + const protocol = protocolWith(automation); + await stageDraft(protocol, 'flow', syncFlow); + + const judgement = await protocol.draftPublishJudgement({ type: 'flow', name: 'order_sync', packageId: PKG }); + expect(judgement.refusals).toEqual([]); + const found = judgement.advisories.filter((a) => a.rule === RULE); + expect(found).toHaveLength(1); + expect(found[0]).toMatchObject({ path: 'flows[0].nodes[1].connectorConfig', severity: 'warning', where: 'flow "order_sync" · node "push"' }); + expect(found[0]!.message).toContain('no connector on this environment serves "erp.push_order"'); + expect(found[0]!.hint).toContain('install the package or plugin that provides "erp"'); + // Asked for the draft's own package, as the executor will ask. + expect(asked).toEqual([['erp', PKG]]); + + // Studio's draft read: a warning on the step's node, the draft still valid, in the read's language. + const diagnostics = await draftRead(protocol, 'flow', 'order_sync', ['zh-CN']); + expect(diagnostics.valid).toBe(true); + const warning = (diagnostics.warnings ?? []).find((w) => w.path === 'nodes.1.connectorConfig'); + expect(warning, JSON.stringify(diagnostics)).toBeDefined(); + expect(warning!.message).toContain('自动化“订单同步”中的步骤“推送订单”调用了连接器“erp”'); + }); + + it('a step inside a loop body: the advisory\'s path is the step\'s place in its region', async () => { + const { automation } = automationKnowing([]); + const protocol = protocolWith(automation); + const loopFlow = regionFlow('order_sweep', { + id: 'each', type: 'loop', label: 'Each', + config: { + collection: [1, 2], iteratorVariable: 'row', + body: { + nodes: [ + { id: 'prep', type: 'assignment', label: 'prep' }, + { id: 'push', type: 'connector_action', label: 'push', connectorConfig: { connectorId: 'erp', actionId: 'push_order', input: {} } }, + ], + edges: [{ id: 'b1', source: 'prep', target: 'push' }], + }, + }, + }); + await stageDraft(protocol, 'flow', loopFlow); + + const judgement = await protocol.draftPublishJudgement({ type: 'flow', name: 'order_sweep', packageId: PKG }); + expect(judgement.refusals).toEqual([]); + const found = judgement.advisories.filter((a) => a.rule === RULE); + expect(found.map((a) => [a.path, a.where])).toEqual([ + ['flows[0].nodes[1].config.body.nodes[1].connectorConfig', 'flow "order_sweep" · node "push"'], + ]); + }); + + it('a known connector and action: no advisory, and the lookups were asked', async () => { + const { automation, asked } = automationKnowing(['erp.push_order']); + const protocol = protocolWith(automation); + await stageDraft(protocol, 'flow', syncFlow); + + const judgement = await protocol.draftPublishJudgement({ type: 'flow', name: 'order_sync', packageId: PKG }); + expect(judgement.advisories.filter((a) => a.rule === RULE)).toEqual([]); + expect(asked).toEqual([['erp', PKG]]); + }); + + it('the cause stays readable: a degraded connector and a refused name each say why', async () => { + const degraded = protocolWith(automationKnowing([], { getConnectorDegradedReason: () => 'its upstream answered 503.' }).automation); + await stageDraft(degraded, 'flow', syncFlow); + const [down] = (await degraded.draftPublishJudgement({ type: 'flow', name: 'order_sync', packageId: PKG })).advisories + .filter((a) => a.rule === RULE); + expect(down!.message).toContain('connector "erp" is degraded — its upstream answered 503'); + expect(down!.hint).toContain('Resolve what keeps connector "erp" degraded'); + + const refused = protocolWith(automationKnowing([], { + resolveConnectorInstanceFor: () => ({ status: 'refused', refusal: { message: 'two connectors named "erp" are in reach' } }), + }).automation); + await stageDraft(refused, 'flow', syncFlow); + const [two] = (await refused.draftPublishJudgement({ type: 'flow', name: 'order_sync', packageId: PKG })).advisories + .filter((a) => a.rule === RULE); + expect(two!.message).toContain('two connectors named "erp" are in reach'); + expect(two!.hint).toContain('name one connector from this flow\'s package'); + }); + + it('no automation service, or one without the lookup, judges nothing', async () => { + for (const automation of [undefined, {}]) { + const protocol = protocolWith(automation); + await stageDraft(protocol, 'flow', syncFlow); + const judgement = await protocol.draftPublishJudgement({ type: 'flow', name: 'order_sync', packageId: PKG }); + expect(judgement.advisories.filter((a) => a.rule === RULE)).toEqual([]); + } + }); + + it('the publish is not refused by it, and the publish gate\'s own answer does not carry it', async () => { + const { automation } = automationKnowing([]); + const protocol = protocolWith(automation); + await stageDraft(protocol, 'flow', syncFlow); + + const gate = await (protocol as any).assertRuntimeAuthoringRules({ + type: 'flow', name: 'order_sync', state: 'active', body: syncFlow, packageId: PKG, + }); + expect(gate.filter((a: { rule: string }) => a.rule === RULE)).toEqual([]); + + const published: any = await protocol.publishMetaItem({ type: 'flow', name: 'order_sync', packageId: PKG } as any); + expect(published.success).toBe(true); + expect((published.advisories ?? []).filter((a: { rule: string }) => a.rule === RULE)).toEqual([]); + }); + + it('one judgement: the advisory says what the landed probe reports for the same body', async () => { + const { automation } = automationKnowing([]); + const protocol = protocolWith(automation); + await stageDraft(protocol, 'flow', syncFlow); + const [advisory] = (await protocol.draftPublishJudgement({ + type: 'flow', name: 'order_sync', packageId: PKG, userTextLocales: ['zh-CN'], + })).advisories.filter((a) => a.rule === RULE); + + const { runBuildProbes } = await import('./build-probes.js'); + const report = await runBuildProbes({ + engine: { find: async () => [] }, + getItem: async () => syncFlow, + published: [{ type: 'flow', name: 'order_sync' }], + organizationId: null, + automation, + packageId: PKG, + userTextLocales: ['zh-CN'], + }); + const probe = report.issues.find((i) => i.code === RULE); // adr0112-ok: D6c build-probe diagnostics code + expect(probe, JSON.stringify(report.issues)).toBeDefined(); + expect([advisory!.message, advisory!.hint, advisory!.userMessage]).toEqual([probe!.message, probe!.fix, probe!.userMessage]); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 8d2778005f0..6f6142e5f7c 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1901,7 +1901,7 @@ export class ObjectStackProtocolImplementation implements return draftPublishVerdict.call(this.draftVerdictHost(), draft); } - /** [#34818, #34766] PUBLIC: this judgement with the gate's advisories; no `body` ⇒ the stored draft (see `draftPublishJudgement`). */ + /** [#34818, #34766] PUBLIC: this judgement with its advisories (the gate's, plus a flow's #35256 connector-probe finding); no `body` ⇒ the stored draft (see `draftPublishJudgement`). */ draftPublishJudgement(draft: { type: string; name: string; body?: unknown; packageId: string | null; member?: string; userTextLocales?: readonly (string | undefined)[]; @@ -1912,8 +1912,7 @@ export class ObjectStackProtocolImplementation implements /** The host both draft verdict bodies read: the promotion's own collaborators. */ private draftVerdictHost(): ThisParameterType { - const readAuthoringChannel = () => this.authoringChannel; - const readEngine = () => this.engine; + const readAuthoringChannel = () => this.authoringChannel, readEngine = () => this.engine; const host: ThisParameterType = { get authoringChannel() { return readAuthoringChannel(); }, get engine() { return readEngine(); }, @@ -1930,6 +1929,7 @@ export class ObjectStackProtocolImplementation implements rlsMembershipResolverKeys: (...a) => this.rlsMembershipResolverKeys(...a), sealedFlowNodeTypeVocabulary: (...a) => this.sealedFlowNodeTypeVocabulary(...a), tenancyPostureInForce: (...a) => this.tenancyPostureInForce(...a), + servicesRegistry: () => this.getServicesRegistry, }; return host; }