From b9bf8d6b6cc3fbfa147459f006cd83c780f8b357 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:12:12 +0000 Subject: [PATCH 01/11] wip(verify): local flow run family Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/verify/src/flow-run.ts | 636 ++++++++++++++++++++++++++++++++ packages/verify/src/index.ts | 20 +- 2 files changed, 655 insertions(+), 1 deletion(-) create mode 100644 packages/verify/src/flow-run.ts diff --git a/packages/verify/src/flow-run.ts b/packages/verify/src/flow-run.ts new file mode 100644 index 00000000000..cbbc9d6f23e --- /dev/null +++ b/packages/verify/src/flow-run.ts @@ -0,0 +1,636 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// @objectstack/verify — the local flow run (`os verify --flow`). +// +// A flow is the item most often saved clean and dead at run time, and the one +// a static rule sees least of: a node type no executor runs, a trigger that +// never binds, a write the data layer refuses. This family runs ONE flow once +// against the booted ephemeral stack and reports what the engine did: each +// node's status, the first failure with its code and the node named, and what +// the run wrote. +// +// ## How the run starts: the way production starts it +// +// - A record-change flow is started by its own trigger: the run writes the +// triggering record through the engine's write door as the signed-in dev +// admin (`hooks.run`), so the record-change trigger the boot bound fires the +// flow exactly as a save does. A create or write leg inserts the record; an +// update leg seeds it first (the seed door fires no trigger) and then saves +// it unchanged, so a condition comparing old and new values sees no change; +// a delete leg seeds it and deletes it. +// - A flow its own trigger starts with no caller (a schedule, an API trigger, +// or a flow declared `runAs: 'system'`) is started as that trigger starts it: +// the `automation` service's own `execute`, with no caller (`flows.run(…, +// { system: true })`). +// - Every other flow is started by a person: through the runtime's trigger +// route as the dev admin (`flows.run(…, { as })`). +// +// Nothing here re-derives an engine decision. Whether the trigger is bound, +// and why not, is the engine's own runtime state (`getFlowRuntimeStates`, the +// sentence `/automation/_status` serves); which node types no executor runs is +// the engine's own audit (`getUnknownNodeTypeAudit`); the node trace is the +// run's own log (`listRuns`); what the run wrote is the engine's middleware +// chain (`observeWrites`). All of them are read-only seams the engine already +// exposes. +// +// ## Confinement: the run writes to the ephemeral stack only +// +// `bootStack` boots the app on an in-memory database, but an app that declares +// datasources gets them connected too (a federated object writes through its +// own driver). Before the run starts, this family registers one middleware on +// the engine's chain that refuses every write (insert, update, delete, purge, +// restore) whose object resolves to any driver other than the stack's own +// default one, the in-memory database the boot created. The refusal happens +// before the driver is called, so the other datasource is never touched; the +// node that wrote fails with the refusal, and the report names the object and +// its datasource. `flow-run.test.ts` pins it against a recording driver. + +import { isServiceNotRegisteredError } from '@objectstack/core'; +import { collectFlowGraphs } from '@objectstack/spec/automation'; +import type { ObjectQL, OperationContext } from '@objectstack/objectql'; +import type { AutomationEngine } from '@objectstack/service-automation'; +import type { VerifyStack } from './harness.js'; +import type { EngineRow, FlowRun, ObservedWrite } from './handle.js'; + +/** What the caller asks to run. */ +export interface FlowRunRequest { + /** The flow's machine name. */ + flow: string; + /** + * For a record-change flow: the field values of the record whose write + * starts it. Ignored (and said so) for any other flow. + */ + record?: EngineRow; + /** For a flow started directly: its input, handed as the start's `params`. */ + input?: EngineRow; +} + +/** What the run came to. */ +export type FlowRunVerdict = 'completed' | 'failed' | 'paused' | 'refused' | 'skipped' | 'not_run'; + +/** How the run was started (see the file header). */ +export type FlowRunStart = 'record_write' | 'trigger_route' | 'system' | 'none'; + +/** One node the run executed, as the run's own log records it. */ +export interface FlowRunStep { + nodeId: string; + nodeType: string; + label?: string; + status: 'success' | 'failure' | 'skipped'; + /** The container the step ran in (a loop body, a parallel branch, a try or catch region). */ + region?: string; + error?: { code: string; message: string }; +} + +/** One write the engine received while the run was open. */ +export interface FlowRunWrite { + object: string; + operation: ObservedWrite['operation']; + /** The ids written, as the engine answered them (an insert) or as the write addressed them. */ + ids: string[]; + outcome: 'written' | 'refused'; + /** The refusal's own code, when the engine refused it and the error carries one. */ + code?: string; + /** The datasource the object routes to: the stack's own default driver's name, or the bound datasource. */ + datasource: string; + /** `true` when this family's confinement refused it: the object routes outside the ephemeral stack. */ + confined?: boolean; +} + +/** Why the run did not prove the flow. */ +export type FlowRunFailureKind = + /** The app's composition holds no automation service. */ + | 'no_automation' + /** No flow of that name is registered. */ + | 'flow_not_registered' + /** The flow is switched off. */ + | 'flow_disabled' + /** The flow's trigger never binds, or binds to an object nobody can write. */ + | 'trigger_unbound' + /** A node type no executor runs. */ + | 'no_executor' + /** A record-change flow was asked to run with no record to write. */ + | 'record_required' + /** The start itself was refused before any node ran. */ + | 'start_refused' + /** The triggering write landed and no run of the flow followed it. */ + | 'not_started' + /** A node failed. */ + | 'node_failed' + /** The run failed with no failing step in its log. */ + | 'run_failed' + /** A write outside the ephemeral stack was refused. */ + | 'confined_write' + /** The ephemeral driver could not be identified, so the run was not started. */ + | 'confinement_unavailable'; + +export interface FlowRunFailure { + kind: FlowRunFailureKind; + message: string; + /** The engine's own code, when it gave one. */ + code?: string; + nodeId?: string; + nodeType?: string; + /** The trigger, named: its type and the object it watches. */ + trigger?: string; +} + +/** The flow's trigger, as the engine's runtime state reports it. */ +export interface FlowRunTrigger { + type: string; + object?: string; + /** The start node's `triggerType` token (`record-after-create`, …), when it declares one. */ + event?: string; + bound: boolean; + reason?: string; + cause?: string; +} + +export interface FlowRunReport { + app: string; + flow: string; + verdict: FlowRunVerdict; + start: FlowRunStart; + trigger?: FlowRunTrigger; + /** The triggering record a record-change run wrote. */ + record?: { object: string; operation: 'insert' | 'update' | 'delete'; id?: string }; + runId?: string; + /** Every node the run executed, in the order the log records them. */ + steps: FlowRunStep[]; + /** Every node whose type no executor runs, reached or not. */ + missingExecutors: Array<{ nodeId: string; nodeType: string; region?: string }>; + firstFailure?: FlowRunFailure; + /** What the run wrote: every write the engine received while it was open, the triggering write excluded. */ + writes: FlowRunWrite[]; + /** The confinement: the one datasource the run may write, and how many writes it refused. */ + confinement: { datasource: string; refused: number }; + /** Notes the reader needs (a skipped start, an ignored record, a paused node). */ + notes: string[]; + summary: { steps: number; failedSteps: number; writes: number; hardFailures: number }; +} + +/** The writes the confinement judges: every verb that changes a row. */ +const CONFINED_OPERATIONS: ReadonlySet = new Set([ + 'insert', + 'update', + 'delete', + 'purge', + 'restore', +]); + +/** + * The run history the engine keeps for itself. Its rows are the engine's + * bookkeeping of the run, not something the flow wrote. + */ +const RUN_HISTORY_OBJECTS: ReadonlySet = new Set(['sys_automation_run']); + +/** The automation members this family reads, each typed as the engine's own member. */ +type FlowRunAutomation = Pick< + AutomationEngine, + 'getFlow' | 'listRuns' | 'getFlowRuntimeStates' | 'getUnknownNodeTypeAudit' +>; +type RunLogEntry = Awaited>[number]; +type RuntimeState = ReturnType[number]; + +/** + * The engines whose chain already carries the confinement middleware, each + * with the list the current run's refusals go to (the engine has no way to + * take a middleware back, so a second run on the same stack swaps the list). + */ +const confinedEngines = new WeakMap }>(); + +/** The refusal the confinement throws: the ADR-0112 pair, and the object and datasource named. */ +function confinementRefusal(object: string, datasource: string, operation: string): Error { + const error = new Error( + `verify --flow: a flow run writes to the ephemeral stack only, and '${object}' routes to datasource ` + + `'${datasource}', which is not the in-memory database this run booted — the ${operation} was refused before ` + + 'that datasource was called.', + ) as Error & { code: string; status: number; statusCode: number; confinedObject: string }; + error.code = 'PERMISSION_DENIED'; + error.status = 403; + error.statusCode = 403; + error.confinedObject = object; + return error; +} + +/** The name of the datasource `object` routes to, as the engine resolves it. */ +function datasourceOf(ql: ObjectQL, object: string): string { + return ql.resolveEffectiveDatasource(object) ?? ql.getDefaultDriverName() ?? 'default'; +} + +/** + * Register the confinement middleware on the stack's engine, once. Answers the + * ephemeral datasource's name, or `undefined` when the engine names no default + * driver (then nothing can be judged, and the run is not started). + */ +function confineToEphemeral(ql: ObjectQL, refused: Array<{ object: string; datasource: string }>): string | undefined { + const defaultName = ql.getDefaultDriverName(); + const ephemeral = defaultName ? ql.getDriverByName(defaultName) : undefined; + if (!defaultName || !ephemeral) return undefined; + const held = confinedEngines.get(ql); + if (held) { + held.refused = refused; + return defaultName; + } + const sink = { refused }; + confinedEngines.set(ql, sink); + ql.registerMiddleware(async (op: OperationContext, next: () => Promise) => { + if (!CONFINED_OPERATIONS.has(op.operation)) return next(); + if (ql.getDriverForObject(op.object) === ephemeral) return next(); + const datasource = datasourceOf(ql, op.object); + sink.refused.push({ object: op.object, datasource }); + throw confinementRefusal(op.object, datasource, op.operation); + }); + return defaultName; +} + +function strings(values: unknown[]): string[] { + return values.filter((v) => typeof v === 'string' || typeof v === 'number').map(String); +} + +/** The ids one observed write wrote or addressed. */ +function idsOf(write: ObservedWrite): string[] { + if (write.outcome.status === 'resolved' && write.operation === 'insert') { + const result = write.outcome.result as unknown; + const rows = Array.isArray(result) ? result : [result]; + return strings(rows.map((r) => (r as EngineRow | null)?.id)); + } + const id = write.where?.id ?? (Array.isArray(write.data) ? undefined : write.data?.id); + return id === undefined ? [] : strings([id]); +} + +/** The start node's `triggerType` token, when it declares a single one. */ +function startEventOf(definition: { nodes?: unknown } | null): string | undefined { + const nodes = Array.isArray(definition?.nodes) ? (definition!.nodes as Array<{ type?: unknown; config?: unknown }>) : []; + const start = nodes.find((n) => n?.type === 'start'); + const token = (start?.config as { triggerType?: unknown } | undefined)?.triggerType; + return typeof token === 'string' ? token : undefined; +} + +/** Whether the start node declares a start condition. */ +function hasStartCondition(definition: { nodes?: unknown } | null): boolean { + const nodes = Array.isArray(definition?.nodes) ? (definition!.nodes as Array<{ type?: unknown; config?: unknown }>) : []; + const start = nodes.find((n) => n?.type === 'start'); + return (start?.config as { condition?: unknown } | undefined)?.condition != null; +} + +/** The write a record-change leg makes: create and write legs insert, the others act on a seeded row. */ +function legOperation(event: string | undefined): 'insert' | 'update' | 'delete' { + if (event && /-update$/.test(event)) return 'update'; + if (event && /-delete$/.test(event)) return 'delete'; + return 'insert'; +} + +/** Every node whose type the engine's audit names as having no executor, with where it sits. */ +function missingExecutorNodes( + definition: { nodes?: unknown; edges?: unknown } | null, + unknownTypes: readonly string[], +): FlowRunReport['missingExecutors'] { + if (!definition || unknownTypes.length === 0 || !Array.isArray(definition.nodes)) return []; + const unknown = new Set(unknownTypes); + const found: FlowRunReport['missingExecutors'] = []; + const graphs = collectFlowGraphs({ + nodes: definition.nodes as never, + edges: (Array.isArray(definition.edges) ? definition.edges : []) as never, + }); + for (const graph of graphs) { + for (const node of graph.nodes as ReadonlyArray<{ id?: unknown; type?: unknown }>) { + if (typeof node.type !== 'string' || !unknown.has(node.type)) continue; + found.push({ + nodeId: typeof node.id === 'string' ? node.id : node.type, + nodeType: node.type, + ...(graph.scope ? { region: graph.scope } : {}), + }); + } + } + return found; +} + +function stepOf(entry: RunLogEntry['steps'][number]): FlowRunStep { + return { + nodeId: entry.nodeId, + nodeType: entry.nodeType, + ...(entry.nodeLabel ? { label: entry.nodeLabel } : {}), + status: entry.status, + ...(entry.regionKind && entry.parentNodeId ? { region: `${entry.regionKind} of '${entry.parentNodeId}'` } : {}), + ...(entry.error ? { error: { code: entry.error.code, message: entry.error.message } } : {}), + }; +} + +const VERDICT_OF_STATUS: Readonly> = { + completed: 'completed', + failed: 'failed', + paused: 'paused', + refused: 'refused', + cancelled: 'failed', + timed_out: 'failed', +}; + +/** + * Run one flow once against the booted stack and report what the engine did. + * Never throws for anything the flow does: every failure is on the report. + * The stack should be one booted for this run alone: the confinement + * middleware stays on its engine for the stack's life. + */ +export async function runFlowProof(stack: VerifyStack, config: any, request: FlowRunRequest): Promise { + const flow = request.flow; + const report: FlowRunReport = { + app: config?.manifest?.id ?? config?.manifest?.namespace ?? 'app', + flow, + verdict: 'not_run', + start: 'none', + steps: [], + missingExecutors: [], + writes: [], + confinement: { datasource: 'default', refused: 0 }, + notes: [], + summary: { steps: 0, failedSteps: 0, writes: 0, hardFailures: 0 }, + }; + const finish = (): FlowRunReport => summarize(report); + + // 1. The automation service the app's composition holds. + let automation: FlowRunAutomation; + try { + automation = stack.kernel.getService('automation'); + } catch (e) { + if (!isServiceNotRegisteredError(e)) throw e; + report.firstFailure = { + kind: 'no_automation', + message: + "this app's composition holds no automation service, so no flow runs here or under `os serve` — declare " + + "requires: ['automation'] (and 'triggers' for a flow its own trigger starts)", + }; + return finish(); + } + + // 2. The flow as the engine registered it: what a run executes. + const definition = (await automation.getFlow(flow)) as ({ nodes?: unknown; edges?: unknown; runAs?: unknown } & EngineRow) | null; + if (!definition) { + report.firstFailure = { + kind: 'flow_not_registered', + message: `no flow named '${flow}' is registered on the booted stack`, + }; + return finish(); + } + + // 3. The node types no executor runs: the engine's own audit, read after the + // boot sealed the vocabulary, mapped onto the nodes that carry them. + const audit = automation.getUnknownNodeTypeAudit().find((entry) => entry.flowName === flow); + report.missingExecutors = missingExecutorNodes(definition, audit?.unknownTypes ?? []); + + // 4. The trigger, as the engine's runtime state reports it. + const state: RuntimeState | undefined = automation.getFlowRuntimeStates().find((row) => row.name === flow); + const event = startEventOf(definition); + if (state?.triggerType) { + report.trigger = { + type: state.triggerType, + ...(state.object ? { object: state.object } : {}), + ...(event ? { event } : {}), + bound: state.bound, + ...(state.reason ? { reason: state.reason } : {}), + ...(state.unboundCause ? { cause: state.unboundCause } : {}), + }; + } + if (state && !state.enabled) { + report.firstFailure = { kind: 'flow_disabled', message: `flow '${flow}' is switched off, so nothing starts it` }; + return finish(); + } + const triggerName = report.trigger + ? `'${report.trigger.type}'${report.trigger.object ? ` on '${report.trigger.object}'` : ''}` + : undefined; + if (report.trigger && !report.trigger.bound) { + report.firstFailure = { + kind: 'trigger_unbound', + trigger: triggerName, + message: + `the flow's trigger ${triggerName} never binds, so nothing ever starts it: ` + + (report.trigger.reason ?? 'the engine reports it unbound'), + }; + return finish(); + } + const recordChange = report.trigger?.type === 'record_change'; + if (recordChange && report.trigger?.object && !stack.metadata.object(report.trigger.object)) { + report.firstFailure = { + kind: 'trigger_unbound', + trigger: triggerName, + message: `the flow's trigger ${triggerName} watches an object this stack does not register, so no write ever fires it`, + }; + return finish(); + } + + // 5. The confinement, before anything writes. + const ql = stack.kernel.getService('objectql'); + const refused: Array<{ object: string; datasource: string }> = []; + const ephemeral = confineToEphemeral(ql, refused); + if (!ephemeral) { + report.firstFailure = { + kind: 'confinement_unavailable', + message: 'the booted engine names no default driver, so the run cannot be confined to the ephemeral stack and was not started', + }; + return finish(); + } + report.confinement.datasource = ephemeral; + + // 6. Start it, the way production starts it, observing every write. + const runsBefore = new Set((await automation.listRuns(flow, { limit: 100 })).map((r) => r.id)); + let result: FlowRun | undefined; + let startRefusal: { code?: string; message: string } | undefined; + let triggerWrite: ObservedWrite | undefined; + let observed: ObservedWrite[] = []; + + if (recordChange) { + const object = report.trigger!.object!; + if (!request.record) { + report.firstFailure = { + kind: 'record_required', + trigger: triggerName, + message: + `a record-change flow starts from a write of a '${object}' record; name the record's fields ` + + `(--flow-record '{"field":"value"}') and the run writes it to fire the trigger`, + }; + return finish(); + } + if (request.input) report.notes.push('the input was ignored: a record-change flow starts from the record it is handed'); + const operation = legOperation(event); + report.start = 'record_write'; + report.record = { object, operation }; + if (operation !== 'insert') { + report.notes.push( + operation === 'update' + ? 'the record was seeded and then saved unchanged: a condition comparing old and new values sees no change' + : 'the record was seeded and then deleted', + ); + } + const admin = await stack.signIn(); + try { + let id: string | undefined; + if (operation !== 'insert') { + const [seeded] = await stack.seed(object, [{ ...request.record }]); + id = seeded?.id === undefined ? undefined : String(seeded.id); + } + observed = await stack.observeWrites(async () => { + if (operation === 'insert') { + const row = await stack.hooks.run(object, 'insert', { ...request.record }, { as: admin }); + id = row?.id === undefined ? undefined : String(row.id); + } else if (operation === 'update') { + await stack.hooks.run(object, 'update', { ...request.record, id }, { as: admin }); + } else { + await stack.hooks.run(object, 'delete', { id }, { as: admin }); + } + }); + if (id !== undefined) report.record.id = id; + } catch (e) { + startRefusal = { code: (e as { code?: string })?.code, message: (e as Error)?.message ?? String(e) }; + } + triggerWrite = observed.find((w) => w.object === object && w.operation === operation); + } else { + if (request.record) report.notes.push('the record was ignored: only a record-change flow starts from a record'); + const selfStarted = report.trigger !== undefined || definition.runAs === 'system'; + report.start = selfStarted ? 'system' : 'trigger_route'; + const opts = selfStarted ? ({ system: true } as const) : { as: await stack.signIn() }; + try { + observed = await stack.observeWrites(async () => { + result = await stack.flows.run(flow, request.input, opts as never); + }); + } catch (e) { + startRefusal = { code: (e as { code?: string })?.code, message: (e as Error)?.message ?? String(e) }; + } + } + + // 7. The run the start caused: the run log's entries that were not there before. + const fresh = (await automation.listRuns(flow, { limit: 100 })).filter((r) => !runsBefore.has(r.id)); + fresh.sort((a, b) => String(a.startedAt).localeCompare(String(b.startedAt))); + const run = fresh[0]; + if (fresh.length > 1) report.notes.push(`${fresh.length} runs of the flow started; the first is reported`); + + report.writes = observed + .filter((w) => w !== triggerWrite && !RUN_HISTORY_OBJECTS.has(w.object)) + .map((w) => { + const datasource = datasourceOf(ql, w.object); + const confined = refused.some((r) => r.object === w.object); + return { + object: w.object, + operation: w.operation, + ids: idsOf(w), + outcome: w.outcome.status === 'refused' ? 'refused' : 'written', + ...(w.outcome.status === 'refused' && w.outcome.code ? { code: w.outcome.code } : {}), + datasource, + ...(w.outcome.status === 'refused' && confined ? { confined: true } : {}), + } satisfies FlowRunWrite; + }); + report.confinement.refused = refused.length; + + if (run) { + report.runId = run.id; + report.steps = (run.steps ?? []).map(stepOf); + report.verdict = VERDICT_OF_STATUS[run.status] ?? 'failed'; + const failing = report.steps.find((s) => s.status === 'failure'); + if (failing) { + const confinedWrite = refused.length > 0 && failing.error?.code === 'PERMISSION_DENIED' && /ephemeral stack only/.test(failing.error.message); + const missing = report.missingExecutors.some((m) => m.nodeId === failing.nodeId); + report.firstFailure = { + kind: confinedWrite ? 'confined_write' : missing ? 'no_executor' : 'node_failed', + nodeId: failing.nodeId, + nodeType: failing.nodeType, + ...(failing.error?.code ? { code: failing.error.code } : {}), + message: failing.error?.message ?? `node '${failing.nodeId}' failed`, + }; + } else if (report.verdict === 'failed') { + report.firstFailure = { kind: 'run_failed', message: run.error ?? `run ${run.id} failed with no failing step in its log` }; + } + if (report.verdict === 'paused') { + const last = report.steps[report.steps.length - 1]; + report.notes.push(`the run paused${last ? ` after node '${last.nodeId}' (${last.nodeType})` : ''}; that is normal for a screen, wait or approval`); + } + } else if (startRefusal) { + report.firstFailure = { + kind: refused.length > 0 ? 'confined_write' : 'start_refused', + ...(startRefusal.code ? { code: startRefusal.code } : {}), + message: startRefusal.message, + }; + } else if (result && result.success === false) { + report.verdict = 'failed'; + report.firstFailure = { + kind: 'start_refused', + ...(result.code ? { code: result.code } : {}), + message: result.error ?? 'the engine refused to start the flow', + }; + } else if (result && (result.output as { skipped?: unknown } | undefined)?.skipped === true) { + report.verdict = 'skipped'; + const reason = (result.output as { reason?: unknown }).reason; + report.notes.push(`the engine skipped the run (${typeof reason === 'string' ? reason : 'no reason given'}), so no node ran: this is not a proof that the flow works`); + } else if (recordChange && hasStartCondition(definition)) { + report.verdict = 'skipped'; + report.notes.push("the write started no run: the start node's condition decides whether it runs, and no run means it did not hold for this record — not a proof that the flow works"); + } else { + report.firstFailure = { + kind: 'not_started', + ...(triggerName ? { trigger: triggerName } : {}), + message: recordChange + ? `the ${report.record?.operation ?? 'write'} of the '${report.trigger?.object}' record landed and no run of the flow followed it: its trigger ${triggerName} did not fire` + : 'the start returned and no run of the flow is in its log', + }; + } + return finish(); +} + +/** Count what the report proves and what it failed. */ +function summarize(report: FlowRunReport): FlowRunReport { + const failedSteps = report.steps.filter((s) => s.status === 'failure').length; + let hardFailures = report.firstFailure ? 1 : 0; + // A node with no executor the run did not reach is still a node that cannot run. + hardFailures += report.missingExecutors.filter((m) => m.nodeId !== report.firstFailure?.nodeId).length; + // A confined write the flow swallowed (a fault edge, a try region) left the run green and the write unlanded. + if (report.firstFailure?.kind !== 'confined_write') hardFailures += report.confinement.refused > 0 ? 1 : 0; + report.summary = { steps: report.steps.length, failedSteps, writes: report.writes.length, hardFailures }; + return report; +} + +function clip(text: string, max: number): string { + return text.length > max ? `${text.slice(0, max - 1)}…` : text; +} + +/** The text face of a {@link FlowRunReport}, in the shape of the other families' reports. */ +export function formatFlowRunReport(report: FlowRunReport): string { + const lines: string[] = [`\n=== objectstack verify — flow run — ${report.app} ===`]; + const t = report.trigger; + lines.push( + ` flow: ${report.flow}; started by ${report.start === 'record_write' ? 'a record write' : report.start === 'system' ? 'its own trigger (no caller)' : report.start === 'trigger_route' ? 'the trigger route, as the dev admin' : 'nothing'}` + + (t ? `; trigger ${t.type}${t.object ? ` on ${t.object}` : ''}${t.event ? ` (${t.event})` : ''} ${t.bound ? 'bound' : 'NOT BOUND'}` : ''), + ); + if (report.record) { + lines.push(` record: ${report.record.operation} ${report.record.object}${report.record.id ? ` ${report.record.id}` : ''}`); + } + lines.push(` confined to datasource '${report.confinement.datasource}' (the in-memory database this run booted)`); + for (const s of report.steps) { + const mark = s.status === 'success' ? '✓' : s.status === 'failure' ? '✗' : '–'; + const where = s.region ? ` [${s.region}]` : ''; + const label = s.label && s.label !== s.nodeId ? ` "${s.label}"` : ''; + lines.push( + ` ${mark} ${s.nodeId} <${s.nodeType}>${label}${where} ${s.status}` + + (s.error ? ` — ${s.error.code}: ${clip(s.error.message, 200)}` : ''), + ); + } + for (const m of report.missingExecutors) { + lines.push(` ✗ ${m.nodeId} <${m.nodeType}>${m.region ? ` [${m.region}]` : ''} NO EXECUTOR: no installed plugin runs this node type`); + } + for (const w of report.writes) { + lines.push( + ` ${w.outcome === 'written' ? '+' : '✗'} wrote ${w.operation} ${w.object}${w.ids.length ? ` ${w.ids.join(', ')}` : ''}` + + ` (datasource ${w.datasource})` + + (w.outcome === 'refused' ? ` REFUSED${w.code ? ` ${w.code}` : ''}${w.confined ? ': outside the ephemeral stack' : ''}` : ''), + ); + } + const f = report.firstFailure; + if (f) { + const where = f.nodeId ? ` at node '${f.nodeId}'${f.nodeType ? ` <${f.nodeType}>` : ''}` : f.trigger ? ` at trigger ${f.trigger}` : ''; + lines.push(` first failure${where}: ${f.kind}${f.code ? ` ${f.code}` : ''} — ${clip(f.message, 300)}`); + } + for (const note of report.notes) lines.push(` note: ${note}`); + const s = report.summary; + lines.push( + ` ── run ${report.verdict.toUpperCase()}${report.runId ? ` (${report.runId})` : ''}: ${s.steps} step(s), ${s.failedSteps} failed, ` + + `${s.writes} write(s), ${report.confinement.refused} refused outside the ephemeral stack; ${s.hardFailures} hard failure(s)`, + ); + return lines.join('\n'); +} diff --git a/packages/verify/src/index.ts b/packages/verify/src/index.ts index 5f27b0dce27..b968fb4d350 100644 --- a/packages/verify/src/index.ts +++ b/packages/verify/src/index.ts @@ -3,7 +3,8 @@ // @objectstack/verify — public API. // // Boot any ObjectStack app in-process and verify it through the real HTTP -// stack. Seven proof families, all app-agnostic (derived from your metadata): +// stack. Seven proof families, all app-agnostic (derived from your metadata), +// and one run of a flow the caller names: // - data fidelity : runCrudVerification — author → write → read → assert // - authorization : runRlsProofs — "you can't write what you can't read" // - value shape : runReferenceShapeProofs — "a reference refuses a value that is not a record id" @@ -11,6 +12,7 @@ // - unique scope : runUniqueScopeProofs — "a declared unique collides where its scope says" // - parent write : runParentWriteReachProofs — "a detail write needs edit on its master, and its own verb" // - dashboard window: runDashboardWindowProofs — "a dashboard's date picker counts the rows its window selects" +// - flow run : runFlowProof — "this flow, run once, did what each node says" export { bootStack, bootStackOnce } from './harness.js'; export type { VerifyStack, BootOptions } from './harness.js'; @@ -185,6 +187,22 @@ export type { DashboardWindowReport, } from './dashboard-window.js'; +// The local flow run: one flow, run once against the booted ephemeral stack +// the way production starts it, reported node by node with the first failure +// and what it wrote; every write outside the ephemeral stack is refused. +export { runFlowProof, formatFlowRunReport } from './flow-run.js'; +export type { + FlowRunRequest, + FlowRunVerdict, + FlowRunStart, + FlowRunStep, + FlowRunWrite, + FlowRunFailureKind, + FlowRunFailure, + FlowRunTrigger, + FlowRunReport, +} from './flow-run.js'; + // ADR-0060 — reusable conformance-ledger helper (static complement to the // runtime harness): classify every declarable property, fail closed on drift. export { checkLedger } from './conformance.js'; From 7f37d3191bb0c3b1af9eb65895211348bb2c7a8d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:17:16 +0000 Subject: [PATCH 02/11] wip(cli): os verify --flow Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/cli/src/commands/verify.ts | 77 ++++++- packages/verify/src/flow-run.test.ts | 318 +++++++++++++++++++++++++++ packages/verify/src/flow-run.ts | 54 +++-- 3 files changed, 429 insertions(+), 20 deletions(-) create mode 100644 packages/verify/src/flow-run.test.ts diff --git a/packages/cli/src/commands/verify.ts b/packages/cli/src/commands/verify.ts index 0250b1f3d80..7b57c5e6ebe 100644 --- a/packages/cli/src/commands/verify.ts +++ b/packages/cli/src/commands/verify.ts @@ -28,6 +28,8 @@ import { formatDashboardWindowReport, readSeedOutcome, formatSeedReport, + runFlowProof, + formatFlowRunReport, type VerifyReport, type SeedReport, type RlsReport, @@ -36,6 +38,7 @@ import { type UniqueScopeReport, type ParentWriteReachReport, type DashboardWindowReport, + type FlowRunReport, type RlsProbeDescriptor, type RlsPositionPersonaInput, } from '@objectstack/verify'; @@ -91,6 +94,24 @@ export function resolveVerifyMultiTenant(flags: { 'multi-tenant'?: boolean }): b return Boolean(flags['multi-tenant']) || postureEnforcesWall(resolveTenancyPosture()); } +/** + * Read one of `--flow-record` / `--flow-input`: a JSON object, or a refusal + * naming the flag. `undefined` when the flag was not given. + */ +export function parseFlowJsonFlag(flag: string, raw: string | undefined): Record | undefined { + if (raw === undefined) return undefined; + let value: unknown; + try { + value = JSON.parse(raw); + } catch (e) { + throw new Error(`${flag} takes a JSON object; it did not parse (${(e as Error).message})`); + } + if (value === null || typeof value !== 'object' || Array.isArray(value)) { + throw new Error(`${flag} takes a JSON object, such as '{"name":"Acme"}'`); + } + return value as Record; +} + /** * One capability finding on `os verify --json`'s `capabilities`: the sentence * `os validate` prints for it, and that door's verdict on it. Advisory on this @@ -138,12 +159,17 @@ export interface VerifyCapabilityAdvisory { * dashboard's `dateRange` binds counts, under each preset of the * picker, the fixture rows that window selects, asked of the dataset * door as the signed-in principal + * - a flow run (--flow NAME): the named flow, run once the way + * production starts it (a record-change flow by a real write of the + * record --flow-record names), reported node by node with the first + * failure and what it wrote; every write outside the ephemeral + * stack is refused before its datasource is called * * Exits non-zero on either stage's failures so it drops straight into CI. */ export default class Verify extends Command { static override description = - 'Run the author-time rules os validate runs, then boot the app in-process and verify it through the real HTTP stack (CRUD round-trip fidelity, plus the cross-owner RLS invariant, the reference-value shape proofs, the declared delete-behaviour proofs, the declared unique-scope proofs, the parent-derived write reach proofs and the dashboard date-window proofs on request)'; + 'Run the author-time rules os validate runs, then boot the app in-process and verify it through the real HTTP stack (CRUD round-trip fidelity, plus the cross-owner RLS invariant, the reference-value shape proofs, the declared delete-behaviour proofs, the declared unique-scope proofs, the parent-derived write reach proofs, the dashboard date-window proofs and one flow run on request)'; static override examples = [ '<%= config.bin %> verify', @@ -154,6 +180,8 @@ export default class Verify extends Command { '<%= config.bin %> verify --unique-scopes --multi-tenant', '<%= config.bin %> verify --parent-write-reach', '<%= config.bin %> verify --dashboard-windows', + `<%= config.bin %> verify --flow notify_on_new_case --flow-record '{"subject":"Printer jam"}'`, + '<%= config.bin %> verify --flow nightly_cleanup --json', ]; static override flags = { @@ -185,6 +213,19 @@ export default class Verify extends Command { description: "Also prove, for every controlled_by_parent object, that a persona's edit, delete or create of a detail is admitted exactly when it holds that verb on the detail's object and can edit the master, written through the engine as verifier personas and one persona per declared position (ADR-0055 master-detail write reach)", default: false, }), + flow: Flags.string({ + description: + "Also run this flow once on a fresh boot and report each node's status, the first failure with its code and the node named, and what the run wrote. It starts the way production starts it: a record-change flow by a real write of the record --flow-record names, a flow its own trigger starts (a schedule, an API trigger, runAs: 'system') with no caller, any other flow through the trigger route as the dev admin. Every write outside the in-memory database this run boots is refused before its datasource is called", + }), + 'flow-record': Flags.string({ + description: + 'With --flow on a record-change flow: the triggering record\'s fields as a JSON object. A create or write leg inserts it; an update leg seeds it and saves it unchanged; a delete leg seeds it and deletes it', + dependsOn: ['flow'], + }), + 'flow-input': Flags.string({ + description: 'With --flow on a flow started directly: its input as a JSON object, handed to the start as its params', + dependsOn: ['flow'], + }), 'multi-tenant': Flags.boolean({ description: 'Boot org-scoped (register the @objectstack/organizations plugin) so tenant-isolation RLS policies apply (also honors a walled $OS_TENANCY_POSTURE, and the legacy $OS_MULTI_ORG_ENABLED it falls back to)', default: false, @@ -267,9 +308,17 @@ export default class Verify extends Command { 'unique-scopes': boolean; 'parent-write-reach': boolean; 'dashboard-windows': boolean; + flow?: string; + 'flow-record'?: string; + 'flow-input'?: string; 'multi-tenant': boolean; json: boolean; }): Promise { + // The flow run's JSON arguments, judged before anything loads or boots: + // a malformed one is the caller's to fix, and no stage should run first. + const flowRecord = parseFlowJsonFlag('--flow-record', flags['flow-record']); + const flowInput = parseFlowJsonFlag('--flow-input', flags['flow-input']); + // [#32141] The project's `.env*` files, loaded before anything reads the // environment — the config module, the tenancy posture below, and every // service the boot composes (the settings service reads its `OS_*` @@ -465,6 +514,23 @@ export default class Verify extends Command { } } + // The flow run boots a fresh stack of its own as well: the run writes its + // triggering record and whatever its nodes write, and the confinement + // middleware it registers stays on that engine for the stack's life. + let flowRun: FlowRunReport | undefined; + if (flags.flow) { + const flowStack = await bootStack(config, { multiTenant, hostRoot }); + try { + flowRun = await runFlowProof(flowStack, config, { + flow: flags.flow, + ...(flowRecord ? { record: flowRecord } : {}), + ...(flowInput ? { input: flowInput } : {}), + }); + } finally { + await flowStack.stop(); + } + } + // Failure contract: a "real" runtime break the app's author must see. // A degraded RLS probe counts: the run reported verdicts it could not have // established, which is worse than no verifier at all. @@ -506,13 +572,17 @@ export default class Verify extends Command { // A bound widget that went blank or counted other rows than its window // selects, or a windowed query the door refused or faulted. Inconclusive, // unbound and excluded widgets are reported, not counted. - (dashboardWindows?.summary.hardFailures ?? 0); + (dashboardWindows?.summary.hardFailures ?? 0) + + // The flow did not run, failed at a node, has a node no executor runs, + // or had a write outside the ephemeral stack refused. A skipped or + // paused run is reported, not counted. + (flowRun?.summary.hardFailures ?? 0); if (flags.json) { // `emitJson`, not `this.log`: stdout is reserved (see `run()`), so the // report has to leave through the real stream — and awaiting the write // drains a report larger than one pipe buffer before `this.exit` below. - await emitJson({ app: crud.app, config: absolutePath, multiTenant, capabilities, seed, crud, rls, referenceShapes, deleteBehaviors, uniqueScopes, parentWriteReach, dashboardWindows, hardFailures }); + await emitJson({ app: crud.app, config: absolutePath, multiTenant, capabilities, seed, crud, rls, referenceShapes, deleteBehaviors, uniqueScopes, parentWriteReach, dashboardWindows, flowRun, hardFailures }); } else { this.log(formatReport(crud)); this.log(formatSeedReport(seed)); @@ -522,6 +592,7 @@ export default class Verify extends Command { if (uniqueScopes) this.log(formatUniqueScopeReport(uniqueScopes)); if (parentWriteReach) this.log(formatParentWriteReachReport(parentWriteReach)); if (dashboardWindows) this.log(formatDashboardWindowReport(dashboardWindows)); + if (flowRun) this.log(formatFlowRunReport(flowRun)); this.log(''); this.log( hardFailures > 0 diff --git a/packages/verify/src/flow-run.test.ts b/packages/verify/src/flow-run.test.ts new file mode 100644 index 00000000000..9767818bca9 --- /dev/null +++ b/packages/verify/src/flow-run.test.ts @@ -0,0 +1,318 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The local flow run (`runFlowProof`, `os verify --flow`): one flow, run once + * against the booted ephemeral stack the way production starts it, reported + * node by node. + * + * Four pins, each read off what only the real engine produces: + * + * - CONTROL: a healthy record-change flow, started by a real write of its + * triggering record, reports each node's status and the row it wrote, and + * the row is there. + * - a node whose type no executor runs is reported with that node named; + * - a trigger that never binds is reported with the trigger named, and + * nothing runs; + * - a write to an object bound to another datasource is refused before that + * datasource's driver is called: the recording driver below sees no write. + * + * ⚠️ This suite resolves `@objectstack/runtime` and + * `@objectstack/service-automation` through their BUILT `dist/`. Rebuild both + * before trusting a run of this file. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; + +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import type { Flow } from '@objectstack/spec/automation'; +import type { Plugin, PluginContext } from '@objectstack/core'; +import type { IDataDriver } from '@objectstack/spec/contracts'; + +import { bootStack, type VerifyStack } from './harness.js'; +import { runFlowProof, formatFlowRunReport } from './flow-run.js'; +import { warmUpBoot } from './boot-warm-up.testkit.js'; + +await warmUpBoot({ automation: true }, { requires: ['automation', 'triggers'] }); + +// Booting the full in-process stack runs well past vitest's 5s default. +const BOOT_TIMEOUT = 120_000; + +const WATCH = 'fr_watch'; +const LEDGER = 'fr_ledger'; +const REMOTE = 'fr_remote'; +const REMOTE_DS = 'fr_remote_ds'; + +const Watch = ObjectSchema.create({ + name: WATCH, + sharingModel: 'public_read_write', + label: 'Watch', + pluralLabel: 'Watches', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +const Ledger = ObjectSchema.create({ + name: LEDGER, + sharingModel: 'public_read_write', + label: 'Ledger', + pluralLabel: 'Ledgers', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +// ── A datasource that is not the ephemeral stack: a driver that records every call ── + +type Call = { method: string; object?: string }; +const remoteCalls: Call[] = []; +const refuse = (what: string) => async (): Promise => { + throw new Error(`flow-run remote: ${what} is not part of this fixture`); +}; + +/** A remote store this suite owns. Reads are refused; a write that reached it would be recorded. */ +const remoteDriver = { + name: REMOTE_DS, + version: '0.0.1', + supports: { transactionsUnsupported: true }, + async connect() {}, + async disconnect() {}, + async checkHealth() { + return true; + }, + execute: refuse('execute'), + find: refuse('find'), + findOne: refuse('findOne'), + count: refuse('count'), + async create(object: string) { + remoteCalls.push({ method: 'create', object }); + return { id: `remote_${remoteCalls.length}` }; + }, + async update(object: string) { + remoteCalls.push({ method: 'update', object }); + return null; + }, + async delete(object: string) { + remoteCalls.push({ method: 'delete', object }); + return false; + }, + upsert: refuse('upsert'), + bulkCreate: refuse('bulkCreate'), + bulkUpdate: refuse('bulkUpdate'), + bulkDelete: refuse('bulkDelete'), + beginTransaction: refuse('beginTransaction'), + commit: refuse('commit'), + rollback: refuse('rollback'), + async syncSchema() {}, + dropTable: refuse('dropTable'), +} as unknown as IDataDriver; + +const remoteDriverPlugin: Plugin = { + name: 'com.objectstack.verify.flow-run-remote-driver', + version: '1.0.0', + init: async (ctx: PluginContext) => { + ctx.registerService(`driver.${REMOTE_DS}`, remoteDriver); + }, +}; + +// ── The flows ── + +const HEALTHY = 'fr_healthy'; +const NO_EXECUTOR = 'fr_no_executor'; +const CONFINED = 'fr_confined'; +const UNBOUND = 'fr_unbound'; +const MISSING_TYPE = 'fr_missing_node'; + +/** On a new Watch record: create a Ledger row named after it. */ +const healthy: Flow = { + name: HEALTHY, + label: HEALTHY, + type: 'record_change', + status: 'active', + runAs: 'system', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: WATCH, triggerType: 'record-after-create' } }, + { + id: 'write_ledger', + type: 'create_record', + label: 'Write ledger', + config: { objectName: LEDGER, fields: { name: { dialect: 'cel', source: "'ledger of ' + record.name" } } }, + }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'write_ledger' }, + { id: 'e2', source: 'write_ledger', target: 'end' }, + ], +} as Flow; + +/** start → a node of a type no installed plugin runs → end. */ +const noExecutor: Flow = { + name: NO_EXECUTOR, + label: NO_EXECUTOR, + type: 'autolaunched', + status: 'active', + runAs: 'system', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'mystery', type: MISSING_TYPE, label: 'Mystery' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'mystery' }, + { id: 'e2', source: 'mystery', target: 'end' }, + ], +} as Flow; + +/** start → create a row of the object bound to the other datasource → end. */ +const confined: Flow = { + name: CONFINED, + label: CONFINED, + type: 'autolaunched', + status: 'active', + runAs: 'system', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'write_remote', type: 'create_record', label: 'Write remote', config: { objectName: REMOTE, fields: { name: 'outside' } } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'write_remote' }, + { id: 'e2', source: 'write_remote', target: 'end' }, + ], +} as Flow; + +const fixtureStack = defineStack({ + manifest: { + id: 'com.objectstack.verify.flow-run', + namespace: 'fr', + version: '0.0.0', + type: 'app', + name: 'Flow Run Fixture', + description: 'Flows the local flow run reports on: healthy, a missing executor, a write outside the ephemeral stack.', + }, + requires: ['automation', 'triggers'], + datasources: [ + { + name: REMOTE_DS, + label: 'Flow run remote (plugin driver)', + driver: REMOTE_DS, + schemaMode: 'external', + config: {}, + external: { allowWrites: true, validation: { onMismatch: 'fail', checkOnBoot: false } }, + }, + ], + objects: [ + Watch, + Ledger, + { + name: REMOTE, + label: 'Remote', + pluralLabel: 'Remotes', + datasource: REMOTE_DS, + external: { remoteName: REMOTE, writable: true }, + sharingModel: 'public_read_write', + fields: { name: { type: 'text', label: 'Name' } }, + }, + ], + flows: [healthy, noExecutor, confined], + plugins: [remoteDriverPlugin], +} as never); + +/** + * The same record-change flow on a composition that mounts the automation + * service but no trigger. `defineStack` refuses this shape at authoring (the + * flow would never auto-launch), so it is handed to the boot unparsed: the + * runtime verdict is what is under test, the one a stack loaded past the + * authoring gate (an artifact, a stored flow) meets. + */ +const unboundStack = { + manifest: { + id: 'com.objectstack.verify.flow-run-unbound', + namespace: 'fru', + version: '0.0.0', + type: 'app', + name: 'Flow Run Unbound Fixture', + }, + requires: ['automation'], + objects: [Watch, Ledger], + flows: [{ ...healthy, name: UNBOUND, label: UNBOUND }], +}; + +describe('runFlowProof — the local flow run', () => { + let stack: VerifyStack; + + beforeAll(async () => { + stack = await bootStack(fixtureStack as never, { automation: true }); + }, BOOT_TIMEOUT); + + afterAll(async () => { + await stack?.stop().catch(() => undefined); + }); + + it('CONTROL: a healthy record-change flow, fired by a real write, reports each node and the row it wrote', async () => { + const report = await runFlowProof(stack, fixtureStack, { flow: HEALTHY, record: { name: 'alpha' } }); + expect(report.verdict, formatFlowRunReport(report)).toBe('completed'); + expect(report.start).toBe('record_write'); + expect(report.trigger).toMatchObject({ type: 'record_change', object: WATCH, bound: true }); + expect(report.record).toMatchObject({ object: WATCH, operation: 'insert' }); + expect(report.firstFailure).toBeUndefined(); + const write = report.steps.find((s) => s.nodeId === 'write_ledger'); + expect(write).toMatchObject({ nodeType: 'create_record', status: 'success' }); + expect(report.steps.every((s) => s.status === 'success')).toBe(true); + + const ledgerWrites = report.writes.filter((w) => w.object === LEDGER); + expect(ledgerWrites).toHaveLength(1); + expect(ledgerWrites[0]).toMatchObject({ operation: 'insert', outcome: 'written', datasource: report.confinement.datasource }); + // The triggering write is the record's, not the flow's: it is not reported as the flow's write. + expect(report.writes.filter((w) => w.object === WATCH)).toEqual([]); + const rows = await stack.rows(LEDGER, { name: 'ledger of alpha' }); + expect(rows.map((r) => String(r.id))).toEqual(ledgerWrites[0].ids); + expect(report.summary.hardFailures).toBe(0); + }); + + it('a node whose type no executor runs is reported with that node named', async () => { + const report = await runFlowProof(stack, fixtureStack, { flow: NO_EXECUTOR }); + expect(report.missingExecutors).toEqual([{ nodeId: 'mystery', nodeType: MISSING_TYPE }]); + expect(report.verdict, formatFlowRunReport(report)).toBe('failed'); + expect(report.firstFailure).toMatchObject({ kind: 'no_executor', nodeId: 'mystery', nodeType: MISSING_TYPE }); + expect(report.steps.find((s) => s.nodeId === 'mystery')?.status).toBe('failure'); + expect(report.summary.hardFailures).toBe(1); + expect(formatFlowRunReport(report)).toContain(`mystery <${MISSING_TYPE}>`); + }); + + it('a write to an object on another datasource is refused before that datasource is called', async () => { + const mark = remoteCalls.length; + const report = await runFlowProof(stack, fixtureStack, { flow: CONFINED }); + expect(report.verdict, formatFlowRunReport(report)).toBe('failed'); + expect(report.firstFailure).toMatchObject({ kind: 'confined_write', nodeId: 'write_remote', nodeType: 'create_record' }); + expect(report.firstFailure?.message).toContain(`'${REMOTE}' routes to datasource '${REMOTE_DS}'`); + expect(report.confinement.refused).toBe(1); + expect(report.writes.filter((w) => w.object === REMOTE)).toEqual([ + { object: REMOTE, operation: 'insert', ids: [], outcome: 'refused', code: 'PERMISSION_DENIED', datasource: REMOTE_DS, confined: true }, + ]); + // The recording driver saw nothing: the refusal came before the driver call. + expect(remoteCalls.slice(mark)).toEqual([]); + expect(report.summary.hardFailures).toBe(1); + }); +}); + +describe('runFlowProof — a trigger that never binds', () => { + let stack: VerifyStack; + + beforeAll(async () => { + stack = await bootStack(unboundStack as never, { automation: true }); + }, BOOT_TIMEOUT); + + afterAll(async () => { + await stack?.stop().catch(() => undefined); + }); + + it('is reported with the trigger named, and nothing runs or is written', async () => { + const report = await runFlowProof(stack, unboundStack, { flow: UNBOUND, record: { name: 'beta' } }); + expect(report.verdict, formatFlowRunReport(report)).toBe('not_run'); + expect(report.trigger).toMatchObject({ type: 'record_change', object: WATCH, bound: false, cause: 'missing_trigger' }); + expect(report.firstFailure).toMatchObject({ kind: 'trigger_unbound', trigger: `'record_change' on '${WATCH}'` }); + expect(report.steps).toEqual([]); + expect(report.writes).toEqual([]); + expect(await stack.rows(LEDGER, {})).toEqual([]); + expect(report.summary.hardFailures).toBe(1); + }); +}); diff --git a/packages/verify/src/flow-run.ts b/packages/verify/src/flow-run.ts index cbbc9d6f23e..37624804c18 100644 --- a/packages/verify/src/flow-run.ts +++ b/packages/verify/src/flow-run.ts @@ -197,7 +197,17 @@ type RuntimeState = ReturnType[number] * with the list the current run's refusals go to (the engine has no way to * take a middleware back, so a second run on the same stack swaps the list). */ -const confinedEngines = new WeakMap }>(); +const confinedEngines = new WeakMap(); + +/** One write the confinement refused. */ +interface ConfinedRefusal { + object: string; + datasource: string; + operation: ObservedWrite['operation']; +} + +/** How a failing step's message is recognised as the confinement's refusal (the engine wraps the node's code). */ +const CONFINEMENT_SENTENCE = /a flow run writes to the ephemeral stack only/; /** The refusal the confinement throws: the ADR-0112 pair, and the object and datasource named. */ function confinementRefusal(object: string, datasource: string, operation: string): Error { @@ -223,7 +233,7 @@ function datasourceOf(ql: ObjectQL, object: string): string { * ephemeral datasource's name, or `undefined` when the engine names no default * driver (then nothing can be judged, and the run is not started). */ -function confineToEphemeral(ql: ObjectQL, refused: Array<{ object: string; datasource: string }>): string | undefined { +function confineToEphemeral(ql: ObjectQL, refused: ConfinedRefusal[]): string | undefined { const defaultName = ql.getDefaultDriverName(); const ephemeral = defaultName ? ql.getDriverByName(defaultName) : undefined; if (!defaultName || !ephemeral) return undefined; @@ -238,7 +248,7 @@ function confineToEphemeral(ql: ObjectQL, refused: Array<{ object: string; datas if (!CONFINED_OPERATIONS.has(op.operation)) return next(); if (ql.getDriverForObject(op.object) === ephemeral) return next(); const datasource = datasourceOf(ql, op.object); - sink.refused.push({ object: op.object, datasource }); + sink.refused.push({ object: op.object, datasource, operation: op.operation as ConfinedRefusal['operation'] }); throw confinementRefusal(op.object, datasource, op.operation); }); return defaultName; @@ -420,7 +430,7 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo // 5. The confinement, before anything writes. const ql = stack.kernel.getService('objectql'); - const refused: Array<{ object: string; datasource: string }> = []; + const refused: ConfinedRefusal[] = []; const ephemeral = confineToEphemeral(ql, refused); if (!ephemeral) { report.firstFailure = { @@ -503,21 +513,30 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo const run = fresh[0]; if (fresh.length > 1) report.notes.push(`${fresh.length} runs of the flow started; the first is reported`); - report.writes = observed - .filter((w) => w !== triggerWrite && !RUN_HISTORY_OBJECTS.has(w.object)) - .map((w) => { - const datasource = datasourceOf(ql, w.object); - const confined = refused.some((r) => r.object === w.object); - return { + // The engine's observer sits on the same chain; a write the confinement + // refused never reaches the driver, and is reported from the confinement's + // own record of it, after the writes the observer saw. + report.writes = [ + ...observed + .filter((w) => w !== triggerWrite && !RUN_HISTORY_OBJECTS.has(w.object)) + .map((w): FlowRunWrite => ({ object: w.object, operation: w.operation, ids: idsOf(w), outcome: w.outcome.status === 'refused' ? 'refused' : 'written', ...(w.outcome.status === 'refused' && w.outcome.code ? { code: w.outcome.code } : {}), - datasource, - ...(w.outcome.status === 'refused' && confined ? { confined: true } : {}), - } satisfies FlowRunWrite; - }); + datasource: datasourceOf(ql, w.object), + })), + ...refused.map((r): FlowRunWrite => ({ + object: r.object, + operation: r.operation, + ids: [], + outcome: 'refused', + code: 'PERMISSION_DENIED', + datasource: r.datasource, + confined: true, + })), + ]; report.confinement.refused = refused.length; if (run) { @@ -526,7 +545,7 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo report.verdict = VERDICT_OF_STATUS[run.status] ?? 'failed'; const failing = report.steps.find((s) => s.status === 'failure'); if (failing) { - const confinedWrite = refused.length > 0 && failing.error?.code === 'PERMISSION_DENIED' && /ephemeral stack only/.test(failing.error.message); + const confinedWrite = refused.length > 0 && CONFINEMENT_SENTENCE.test(failing.error?.message ?? ''); const missing = report.missingExecutors.some((m) => m.nodeId === failing.nodeId); report.firstFailure = { kind: confinedWrite ? 'confined_write' : missing ? 'no_executor' : 'node_failed', @@ -611,8 +630,9 @@ export function formatFlowRunReport(report: FlowRunReport): string { (s.error ? ` — ${s.error.code}: ${clip(s.error.message, 200)}` : ''), ); } - for (const m of report.missingExecutors) { - lines.push(` ✗ ${m.nodeId} <${m.nodeType}>${m.region ? ` [${m.region}]` : ''} NO EXECUTOR: no installed plugin runs this node type`); + // A node the run reached is already on its step line above; one it did not reach is named here. + for (const m of report.missingExecutors.filter((x) => !report.steps.some((s) => s.nodeId === x.nodeId))) { + lines.push(` ✗ ${m.nodeId} <${m.nodeType}>${m.region ? ` [${m.region}]` : ''} NO EXECUTOR: not reached by this run, and no installed plugin runs this node type`); } for (const w of report.writes) { lines.push( From e93ccc4b56af023e4755f5e97256e628b023b357 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:26:59 +0000 Subject: [PATCH 03/11] docs(verify): document os verify --flow; changeset; flag parser pin Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .changeset/34779-verify-flow-run.md | 19 +++++++++++ content/docs/deployment/cli.mdx | 32 +++++++++++++++++-- .../commands/verify-flow-json-flag.test.ts | 31 ++++++++++++++++++ 3 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 .changeset/34779-verify-flow-run.md create mode 100644 packages/cli/src/commands/verify-flow-json-flag.test.ts diff --git a/.changeset/34779-verify-flow-run.md b/.changeset/34779-verify-flow-run.md new file mode 100644 index 00000000000..634c4716a63 --- /dev/null +++ b/.changeset/34779-verify-flow-run.md @@ -0,0 +1,19 @@ +--- +'@objectstack/verify': patch +'@objectstack/cli': patch +--- + +feat(verify): run a flow locally and report its node trace before it is submitted + +Clause-②: yes (widening: a new `os verify --flow` option, and new `@objectstack/verify` exports) +Metadata-protocol: none + +`os verify --flow ` runs one flow once on a fresh in-memory boot of the app and reports what the engine did: each node's status as the run's log records it, the first failure with its code and the node named, and every write the run made. + +- The run starts the way production starts it. A record-change flow is fired by its own trigger: the run writes the record `--flow-record '{"field":"value"}'` names as the dev admin (inserted for a create or write leg; seeded and saved unchanged for an update leg; seeded and deleted for a delete leg). A schedule, an API-triggered flow or a flow declared `runAs: 'system'` is started with no caller, as its trigger starts it. Any other flow goes through the trigger route as the dev admin, with `--flow-input '{...}'` as its params. +- A node whose type no installed plugin runs is named, whether the run reached it or not. A flow whose trigger never binds is reported with the trigger and the engine's reason, and is not run. +- The run writes to the in-memory database the boot creates and nowhere else: a write to an object bound to any other datasource is refused before that datasource's driver is called, and the node that made it fails naming the object and the datasource. Nodes that call out (`http`, `connector_action`, `notify`, `script`) are not confined and run for real. +- A failed run, a missing executor, an unbound trigger, a record-change flow given no record, and a write refused outside the ephemeral stack each fail `os verify`. A run its start condition skipped, or one that paused at a screen, wait or approval, is reported and does not. +- `--json` carries the report as `flowRun`. + +New exports from `@objectstack/verify`: `runFlowProof`, `formatFlowRunReport`, and the `FlowRunRequest`, `FlowRunVerdict`, `FlowRunStart`, `FlowRunStep`, `FlowRunWrite`, `FlowRunFailureKind`, `FlowRunFailure`, `FlowRunTrigger` and `FlowRunReport` types. Nothing that ran before changes. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index cd2b81bc5a7..1ef212f1a01 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -2943,6 +2943,7 @@ os verify --delete-behaviors # Also prove each declared delete os verify --unique-scopes --multi-tenant # Also prove each declared unique collides where its scope says os verify --parent-write-reach # Also prove each controlled_by_parent detail write follows its master os verify --dashboard-windows # Also prove each dashboard date picker counts the rows its window selects +os verify --flow notify_on_new_case --flow-record '{"subject":"Printer jam"}' # Also run one flow and report its node trace ``` 1. **Author-time rules.** The rule registry `os validate` runs, over the stack @@ -3092,6 +3093,31 @@ os verify --dashboard-windows # Also prove each dashboard date ground truth cannot model (`$or`, a range, a relationship path, a condition on the window's own field), are reported `excluded`. + With `--flow `, another fresh boot runs that one flow once and reports + what the engine did: each node's status as the run's log records it, the + first failure with its code and the node named, and every write the run + made. The run starts the way production starts it. A record-change flow is + started by its own trigger: the run writes the record `--flow-record` + names (its fields as a JSON object) as the dev admin, inserting it for a + create or write leg, seeding it and saving it unchanged for an update leg + (so a condition comparing old and new values sees no change), and seeding + it and deleting it for a delete leg. A flow its own trigger starts with no + caller (a schedule, an API trigger, or a flow declared `runAs: 'system'`) + is started the way that trigger starts it, with no caller; any other flow + goes through the trigger route as the dev admin. `--flow-input` (a JSON + object) is handed to a directly started flow as its params. Before the run + starts, every node whose type no installed plugin runs is named, reached or + not, and a flow whose trigger never binds is reported with the trigger and + the engine's reason, and is not run. A run that fails, a node with no + executor, a trigger that never binds, a record-change flow given no record, + and a write refused because its object lives outside the ephemeral stack + each fail `os verify`; a run the start condition skipped, or one that paused at a + screen, wait or approval, is reported and does not. The run writes to the + in-memory database this boot creates and nowhere else: a write to an object + bound to any other datasource is refused before that datasource's driver is + called, and the node that made it fails naming the object and the + datasource. Only data writes are confined: a node that calls out (`http`, + `connector_action`, `notify`, `script`) runs for real. `--multi-tenant` boots org-scoped so tenant-isolation RLS policies apply; a walled tenancy posture (`OS_TENANCY_POSTURE` set to `isolated` or `group`) asks for the same boot. @@ -3128,8 +3154,10 @@ document carries depends on where the run ended: `parentWriteReach` (with `--parent-write-reach`; its `personas` name who wrote and who could not be provisioned), `dashboardWindows` (with `--dashboard-windows`; its `presets` name what each preset handed the door - and how it resolved) and `hardFailures`, the count the exit status is read - from. + and how it resolved), `flowRun` (with `--flow`: the `verdict`, how the run + started, the `trigger` and whether it is bound, the `steps`, the + `missingExecutors`, the `firstFailure`, the `writes` and the `confinement`) + and `hardFailures`, the count the exit status is read from. - **Could not run:** `{ "error": "" }`, plus `code` and `httpStatus` when the failure carries them. diff --git a/packages/cli/src/commands/verify-flow-json-flag.test.ts b/packages/cli/src/commands/verify-flow-json-flag.test.ts new file mode 100644 index 00000000000..e3398619dc1 --- /dev/null +++ b/packages/cli/src/commands/verify-flow-json-flag.test.ts @@ -0,0 +1,31 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// `os verify --flow` takes the triggering record (`--flow-record`) and the +// start's input (`--flow-input`) as JSON objects, judged before anything loads +// or boots. This pins the exported decision, `parseFlowJsonFlag`, the way this +// package pins `resolveVerifyMultiTenant`: the command body hands each flag to +// it once, before the author-time stage. + +import { describe, it, expect } from 'vitest'; +import { parseFlowJsonFlag } from './verify.js'; + +describe('parseFlowJsonFlag', () => { + it('an absent flag is no value', () => { + expect(parseFlowJsonFlag('--flow-record', undefined)).toBeUndefined(); + }); + + it('a JSON object is handed on as given', () => { + expect(parseFlowJsonFlag('--flow-record', '{"subject":"Printer jam","priority":2}')).toEqual({ + subject: 'Printer jam', + priority: 2, + }); + }); + + it('text that does not parse is refused, naming the flag', () => { + expect(() => parseFlowJsonFlag('--flow-input', '{subject: x}')).toThrow(/--flow-input/); + }); + + it.each([['[1,2]'], ['"text"'], ['null'], ['3']])('JSON that is not an object (%s) is refused, naming the flag', (raw) => { + expect(() => parseFlowJsonFlag('--flow-record', raw)).toThrow(/--flow-record/); + }); +}); From 2356565d4e48d51848c771fd4474c5b11b162f13 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:32:21 +0000 Subject: [PATCH 04/11] fix(verify): flag parser in its own module; classify the flow-run exports; collection imports Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/cli/src/commands/verify.ts | 19 +------------------ .../flow-json-flag.test.ts} | 7 +++---- packages/cli/src/utils/flow-json-flag.ts | 19 +++++++++++++++++++ packages/verify/src/flow-run.test.ts | 4 ++++ scripts/check-verify-stand-in-erasure.mjs | 3 +++ 5 files changed, 30 insertions(+), 22 deletions(-) rename packages/cli/src/{commands/verify-flow-json-flag.test.ts => utils/flow-json-flag.test.ts} (80%) create mode 100644 packages/cli/src/utils/flow-json-flag.ts diff --git a/packages/cli/src/commands/verify.ts b/packages/cli/src/commands/verify.ts index 7b57c5e6ebe..ffb94adac15 100644 --- a/packages/cli/src/commands/verify.ts +++ b/packages/cli/src/commands/verify.ts @@ -62,6 +62,7 @@ import { isReportedError, } from '../utils/format.js'; import { reserveStdoutForJson } from '../utils/json-stdout.js'; +import { parseFlowJsonFlag } from '../utils/flow-json-flag.js'; /** * Should this `os verify` run boot an org-scoped (multi-tenant) stack? @@ -94,24 +95,6 @@ export function resolveVerifyMultiTenant(flags: { 'multi-tenant'?: boolean }): b return Boolean(flags['multi-tenant']) || postureEnforcesWall(resolveTenancyPosture()); } -/** - * Read one of `--flow-record` / `--flow-input`: a JSON object, or a refusal - * naming the flag. `undefined` when the flag was not given. - */ -export function parseFlowJsonFlag(flag: string, raw: string | undefined): Record | undefined { - if (raw === undefined) return undefined; - let value: unknown; - try { - value = JSON.parse(raw); - } catch (e) { - throw new Error(`${flag} takes a JSON object; it did not parse (${(e as Error).message})`); - } - if (value === null || typeof value !== 'object' || Array.isArray(value)) { - throw new Error(`${flag} takes a JSON object, such as '{"name":"Acme"}'`); - } - return value as Record; -} - /** * One capability finding on `os verify --json`'s `capabilities`: the sentence * `os validate` prints for it, and that door's verdict on it. Advisory on this diff --git a/packages/cli/src/commands/verify-flow-json-flag.test.ts b/packages/cli/src/utils/flow-json-flag.test.ts similarity index 80% rename from packages/cli/src/commands/verify-flow-json-flag.test.ts rename to packages/cli/src/utils/flow-json-flag.test.ts index e3398619dc1..328d651f626 100644 --- a/packages/cli/src/commands/verify-flow-json-flag.test.ts +++ b/packages/cli/src/utils/flow-json-flag.test.ts @@ -2,12 +2,11 @@ // // `os verify --flow` takes the triggering record (`--flow-record`) and the // start's input (`--flow-input`) as JSON objects, judged before anything loads -// or boots. This pins the exported decision, `parseFlowJsonFlag`, the way this -// package pins `resolveVerifyMultiTenant`: the command body hands each flag to -// it once, before the author-time stage. +// or boots. This pins the decision, `parseFlowJsonFlag`, on its own: the +// command body hands each flag to it once, before the author-time stage. import { describe, it, expect } from 'vitest'; -import { parseFlowJsonFlag } from './verify.js'; +import { parseFlowJsonFlag } from '../utils/flow-json-flag.js'; describe('parseFlowJsonFlag', () => { it('an absent flag is no value', () => { diff --git a/packages/cli/src/utils/flow-json-flag.ts b/packages/cli/src/utils/flow-json-flag.ts new file mode 100644 index 00000000000..21807ec9a9d --- /dev/null +++ b/packages/cli/src/utils/flow-json-flag.ts @@ -0,0 +1,19 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Read one of `--flow-record` / `--flow-input`: a JSON object, or a refusal + * naming the flag. `undefined` when the flag was not given. + */ +export function parseFlowJsonFlag(flag: string, raw: string | undefined): Record | undefined { + if (raw === undefined) return undefined; + let value: unknown; + try { + value = JSON.parse(raw); + } catch (e) { + throw new Error(`${flag} takes a JSON object; it did not parse (${(e as Error).message})`); + } + if (value === null || typeof value !== 'object' || Array.isArray(value)) { + throw new Error(`${flag} takes a JSON object, such as '{"name":"Acme"}'`); + } + return value as Record; +} diff --git a/packages/verify/src/flow-run.test.ts b/packages/verify/src/flow-run.test.ts index 9767818bca9..a04308e4a2b 100644 --- a/packages/verify/src/flow-run.test.ts +++ b/packages/verify/src/flow-run.test.ts @@ -33,6 +33,10 @@ import { bootStack, type VerifyStack } from './harness.js'; import { runFlowProof, formatFlowRunReport } from './flow-run.js'; import { warmUpBoot } from './boot-warm-up.testkit.js'; +// Paid at collection: the harness's boot loads these lazily (check:test-source-alias). +import '@objectstack/service-datasource'; +import '@objectstack/service-automation'; + await warmUpBoot({ automation: true }, { requires: ['automation', 'triggers'] }); // Booting the full in-process stack runs well past vitest's 5s default. diff --git a/scripts/check-verify-stand-in-erasure.mjs b/scripts/check-verify-stand-in-erasure.mjs index a53f3bc3546..2d4d13c9f41 100644 --- a/scripts/check-verify-stand-in-erasure.mjs +++ b/scripts/check-verify-stand-in-erasure.mjs @@ -236,6 +236,9 @@ const NOT_A_STAND_IN = { runDashboardWindowProofs: 'same `VerifyStack` handle as runCrudVerification.', formatDashboardWindowReport: 'formats a `DashboardWindowReport` this package produced; presentation, not conformance.', + runFlowProof: 'same `VerifyStack` handle as runCrudVerification.', + formatFlowRunReport: + 'formats a `FlowRunReport` this package produced; presentation, not conformance.', formatSeedReport: 'formats a `SeedReport` this package produced (`judgeSeedOutcome` / `readSeedOutcome`, #32141); ' + 'presentation, not conformance.', From 348cc18de61c582bcb961b0f23aca34cc01bf160 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:38:53 +0000 Subject: [PATCH 05/11] fix(verify): print the confinement line only once the confinement is set Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/verify/src/flow-run.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/verify/src/flow-run.ts b/packages/verify/src/flow-run.ts index 37624804c18..fd506b369cd 100644 --- a/packages/verify/src/flow-run.ts +++ b/packages/verify/src/flow-run.ts @@ -162,7 +162,11 @@ export interface FlowRunReport { firstFailure?: FlowRunFailure; /** What the run wrote: every write the engine received while it was open, the triggering write excluded. */ writes: FlowRunWrite[]; - /** The confinement: the one datasource the run may write, and how many writes it refused. */ + /** + * The confinement: the one datasource the run may write, and how many writes + * it refused. `datasource` is empty when the report ends before the + * confinement is set (nothing was started, so nothing could write). + */ confinement: { datasource: string; refused: number }; /** Notes the reader needs (a skipped start, an ignored record, a paused node). */ notes: string[]; @@ -352,7 +356,7 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo steps: [], missingExecutors: [], writes: [], - confinement: { datasource: 'default', refused: 0 }, + confinement: { datasource: '', refused: 0 }, notes: [], summary: { steps: 0, failedSteps: 0, writes: 0, hardFailures: 0 }, }; @@ -620,7 +624,9 @@ export function formatFlowRunReport(report: FlowRunReport): string { if (report.record) { lines.push(` record: ${report.record.operation} ${report.record.object}${report.record.id ? ` ${report.record.id}` : ''}`); } - lines.push(` confined to datasource '${report.confinement.datasource}' (the in-memory database this run booted)`); + if (report.confinement.datasource) { + lines.push(` confined to datasource '${report.confinement.datasource}' (the in-memory database this run booted)`); + } for (const s of report.steps) { const mark = s.status === 'success' ? '✓' : s.status === 'failure' ? '✗' : '–'; const where = s.region ? ` [${s.region}]` : ''; From ffa765fe85f582050fd162d0aeb315e5753cd3b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:35:25 +0000 Subject: [PATCH 06/11] fix(verify): outbound nodes are not executed; a policy-unarmed schedule still runs; api and time-relative starts get their record Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .changeset/34779-verify-flow-run.md | 8 +- content/docs/deployment/cli.mdx | 46 ++++-- packages/cli/src/commands/verify.ts | 13 +- packages/verify/src/flow-run.test.ts | 231 ++++++++++++++++++++++++++- packages/verify/src/flow-run.ts | 197 +++++++++++++++++++++-- 5 files changed, 449 insertions(+), 46 deletions(-) diff --git a/.changeset/34779-verify-flow-run.md b/.changeset/34779-verify-flow-run.md index 634c4716a63..6674013e9b8 100644 --- a/.changeset/34779-verify-flow-run.md +++ b/.changeset/34779-verify-flow-run.md @@ -10,10 +10,10 @@ Metadata-protocol: none `os verify --flow ` runs one flow once on a fresh in-memory boot of the app and reports what the engine did: each node's status as the run's log records it, the first failure with its code and the node named, and every write the run made. -- The run starts the way production starts it. A record-change flow is fired by its own trigger: the run writes the record `--flow-record '{"field":"value"}'` names as the dev admin (inserted for a create or write leg; seeded and saved unchanged for an update leg; seeded and deleted for a delete leg). A schedule, an API-triggered flow or a flow declared `runAs: 'system'` is started with no caller, as its trigger starts it. Any other flow goes through the trigger route as the dev admin, with `--flow-input '{...}'` as its params. -- A node whose type no installed plugin runs is named, whether the run reached it or not. A flow whose trigger never binds is reported with the trigger and the engine's reason, and is not run. -- The run writes to the in-memory database the boot creates and nowhere else: a write to an object bound to any other datasource is refused before that datasource's driver is called, and the node that made it fails naming the object and the datasource. Nodes that call out (`http`, `connector_action`, `notify`, `script`) are not confined and run for real. -- A failed run, a missing executor, an unbound trigger, a record-change flow given no record, and a write refused outside the ephemeral stack each fail `os verify`. A run its start condition skipped, or one that paused at a screen, wait or approval, is reported and does not. +- The run starts the way production starts it. A record-change flow is fired by its own trigger: the run writes the record `--flow-record '{"field":"value"}'` names as the dev admin (inserted for a create or write leg; seeded and saved unchanged for an update leg; seeded and deleted for a delete leg). A flow its own trigger starts is started with no caller, with the context that trigger builds: an API-triggered flow gets `--flow-input '{...}'` as its record and its params (the request body); a time-relative flow gets the `--flow-record` row, seeded first, as its record; a schedule or another `runAs: 'system'` flow gets `--flow-input` as its params. Any other flow goes through the trigger route as the dev admin, with `--flow-input` as its params. +- A node whose type no installed plugin runs is named, whether the run reached it or not. A flow whose trigger never binds is reported with the trigger and the engine's reason, and is not run. A schedule or time-relative trigger left unarmed by the deployment's scheduled-work switch (the default) is not a defect: it is reported as not armed and the flow is still run. +- The run writes to the in-memory database the boot creates and nowhere else: a write to an object bound to any other datasource is refused before that datasource's driver is called, and the node that made it fails naming the object and the datasource. Nothing calls out of the machine: an outbound node (`http`, `connector_action`, `notify`, `script`) is not executed. The run stops at the first one and the report names it (`outbound_not_run`); every node before it ran for real. +- A failed run, a missing executor, an unbound trigger, a record-change or time-relative flow given no record, and a write refused outside the ephemeral stack each fail `os verify`. A run its start condition skipped, one that paused at a screen, wait or approval, and one stopped at an outbound node are reported and do not. - `--json` carries the report as `flowRun`. New exports from `@objectstack/verify`: `runFlowProof`, `formatFlowRunReport`, and the `FlowRunRequest`, `FlowRunVerdict`, `FlowRunStart`, `FlowRunStep`, `FlowRunWrite`, `FlowRunFailureKind`, `FlowRunFailure`, `FlowRunTrigger` and `FlowRunReport` types. Nothing that ran before changes. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 1ef212f1a01..4c4790178e0 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -3101,23 +3101,35 @@ os verify --flow notify_on_new_case --flow-record '{"subject":"Printer jam"}' names (its fields as a JSON object) as the dev admin, inserting it for a create or write leg, seeding it and saving it unchanged for an update leg (so a condition comparing old and new values sees no change), and seeding - it and deleting it for a delete leg. A flow its own trigger starts with no - caller (a schedule, an API trigger, or a flow declared `runAs: 'system'`) - is started the way that trigger starts it, with no caller; any other flow - goes through the trigger route as the dev admin. `--flow-input` (a JSON - object) is handed to a directly started flow as its params. Before the run - starts, every node whose type no installed plugin runs is named, reached or - not, and a flow whose trigger never binds is reported with the trigger and - the engine's reason, and is not run. A run that fails, a node with no - executor, a trigger that never binds, a record-change flow given no record, - and a write refused because its object lives outside the ephemeral stack - each fail `os verify`; a run the start condition skipped, or one that paused at a - screen, wait or approval, is reported and does not. The run writes to the - in-memory database this boot creates and nowhere else: a write to an object - bound to any other datasource is refused before that datasource's driver is - called, and the node that made it fails naming the object and the - datasource. Only data writes are confined: a node that calls out (`http`, - `connector_action`, `notify`, `script`) runs for real. + it and deleting it for a delete leg. A flow its own trigger starts is + started with no caller, with the context that trigger builds: an + API-triggered flow is handed `--flow-input` (a JSON object) as its record + and its params, as the inbound hook hands it the request body; a + time-relative flow is handed the `--flow-record` row as its record, seeded + first so it is in the table, as a swept row is; a schedule, or another + flow declared `runAs: 'system'`, is handed `--flow-input` as its params + (a real tick's own `jobId`, `flowName` and `schedule` params and a + binding's acting organization are not reproduced). Any other flow goes + through the trigger route as the dev admin, with `--flow-input` as its + params. Before the run starts, every node whose type no installed plugin + runs is named, reached or not, and a flow whose trigger never binds is + reported with the trigger and the engine's reason, and is not run. A + schedule or time-relative trigger the deployment's scheduled-work switch + keeps unarmed (the default) is not a defect: it is reported as not armed + and the flow is still run. A run that fails, a node with no executor, a + trigger that never binds, a record-change or time-relative flow given no + record, and a write refused because its object lives outside the + ephemeral stack each fail `os verify`; a run the start condition skipped, + one that paused at a screen, wait or approval, and one stopped at an + outbound node are reported and do not. The run writes to the in-memory + database this boot creates and nowhere else: a write to an object bound to + any other datasource is refused before that datasource's driver is called, + and the node that made it fails naming the object and the datasource. + Nothing calls out of the machine either: an outbound node (`http`, + `connector_action`, `notify`, `script`) is not executed. The run stops at + the first one it reaches, and the report names it (`outbound_not_run`); + every node before it ran for real. Inside a `try_catch` region the catch + region handles the stop as it would a failed call. `--multi-tenant` boots org-scoped so tenant-isolation RLS policies apply; a walled tenancy posture (`OS_TENANCY_POSTURE` set to `isolated` or `group`) asks for the same boot. diff --git a/packages/cli/src/commands/verify.ts b/packages/cli/src/commands/verify.ts index ffb94adac15..06581504896 100644 --- a/packages/cli/src/commands/verify.ts +++ b/packages/cli/src/commands/verify.ts @@ -146,7 +146,9 @@ export interface VerifyCapabilityAdvisory { * production starts it (a record-change flow by a real write of the * record --flow-record names), reported node by node with the first * failure and what it wrote; every write outside the ephemeral - * stack is refused before its datasource is called + * stack is refused before its datasource is called, and an + * outbound node (http, connector_action, notify, script) is not + * executed: the run stops there * * Exits non-zero on either stage's failures so it drops straight into CI. */ @@ -198,15 +200,15 @@ export default class Verify extends Command { }), flow: Flags.string({ description: - "Also run this flow once on a fresh boot and report each node's status, the first failure with its code and the node named, and what the run wrote. It starts the way production starts it: a record-change flow by a real write of the record --flow-record names, a flow its own trigger starts (a schedule, an API trigger, runAs: 'system') with no caller, any other flow through the trigger route as the dev admin. Every write outside the in-memory database this run boots is refused before its datasource is called", + "Also run this flow once on a fresh boot and report each node's status, the first failure with its code and the node named, and what the run wrote. It starts the way production starts it: a record-change flow by a real write of the record --flow-record names, a flow its own trigger starts with no caller (an API-triggered flow with --flow-input as its record and params, a time-relative flow with --flow-record seeded and handed in as its record, a schedule or runAs: 'system' flow with --flow-input as its params), any other flow through the trigger route as the dev admin. A schedule the deployment's scheduled-work switch keeps unarmed is reported as not armed and still run. Every write outside the in-memory database this run boots is refused before its datasource is called. Outbound nodes (http, connector_action, notify, script) are not executed: the run stops at the first one and names it, so nothing calls out of this machine }), 'flow-record': Flags.string({ description: - 'With --flow on a record-change flow: the triggering record\'s fields as a JSON object. A create or write leg inserts it; an update leg seeds it and saves it unchanged; a delete leg seeds it and deletes it', + 'With --flow on a record-change or time-relative flow: the record\'s fields as a JSON object. A create or write leg inserts it; an update leg seeds it and saves it unchanged; a delete leg seeds it and deletes it; a time-relative flow is handed the seeded row as the swept record', dependsOn: ['flow'], }), 'flow-input': Flags.string({ - description: 'With --flow on a flow started directly: its input as a JSON object, handed to the start as its params', + description: 'With --flow on a flow started directly: its input as a JSON object, handed to the start as its params (and, for an API-triggered flow, as its record, the request body)', dependsOn: ['flow'], }), 'multi-tenant': Flags.boolean({ @@ -558,7 +560,8 @@ export default class Verify extends Command { (dashboardWindows?.summary.hardFailures ?? 0) + // The flow did not run, failed at a node, has a node no executor runs, // or had a write outside the ephemeral stack refused. A skipped or - // paused run is reported, not counted. + // paused run, a run stopped at an outbound node, and a schedule left + // unarmed by the deployment's switch are reported, not counted. (flowRun?.summary.hardFailures ?? 0); if (flags.json) { diff --git a/packages/verify/src/flow-run.test.ts b/packages/verify/src/flow-run.test.ts index a04308e4a2b..e3e5de0d915 100644 --- a/packages/verify/src/flow-run.test.ts +++ b/packages/verify/src/flow-run.test.ts @@ -5,7 +5,7 @@ * against the booted ephemeral stack the way production starts it, reported * node by node. * - * Four pins, each read off what only the real engine produces: + * The pins, each read off what only the real engine produces: * * - CONTROL: a healthy record-change flow, started by a real write of its * triggering record, reports each node's status and the row it wrote, and @@ -14,14 +14,24 @@ * - a trigger that never binds is reported with the trigger named, and * nothing runs; * - a write to an object bound to another datasource is refused before that - * datasource's driver is called: the recording driver below sees no write. + * datasource's driver is called: the recording driver below sees no write; + * - an outbound node is not executed: the run stops there with the node + * named, and the local server below receives no request; + * - a schedule the deployment's scheduled-work switch keeps unarmed is not a + * defect: it is reported as not armed and still run with no caller; + * - an API-triggered flow gets its body as `record` as well as `params`, and + * a time-relative flow gets the given row as `record`, as their triggers + * hand them in; + * - the update and delete legs of a record-change flow fire it. * * ⚠️ This suite resolves `@objectstack/runtime` and * `@objectstack/service-automation` through their BUILT `dist/`. Rebuild both * before trusting a run of this file. */ -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; import { defineStack } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; @@ -37,6 +47,26 @@ import { warmUpBoot } from './boot-warm-up.testkit.js'; import '@objectstack/service-datasource'; import '@objectstack/service-automation'; +// The local server an `http` node below would reach. The egress guard opens +// loopback only when the allowlist names it, so a request that left the run +// would land here and be counted. +const outboundHits: string[] = []; +const outboundServer = createServer((req, res) => { + outboundHits.push(req.url ?? ''); + res.setHeader('content-type', 'application/json'); + res.end('{}'); +}); +await new Promise((resolve) => outboundServer.listen(0, '127.0.0.1', resolve)); +const OUTBOUND_URL = `http://127.0.0.1:${(outboundServer.address() as AddressInfo).port}/ping`; +vi.stubEnv('OS_EGRESS_ALLOWED_TARGETS', '127.0.0.1'); +// The default deployment: package-authored scheduled work switched off. +vi.stubEnv('OS_AUTOMATION_SCHEDULED_WORK_ENABLED', 'false'); +vi.stubEnv('FR_HOOK_SECRET', 'flow-run-fixture-hook-secret'); +afterAll(async () => { + vi.unstubAllEnvs(); + await new Promise((resolve) => outboundServer.close(() => resolve())); +}); + await warmUpBoot({ automation: true }, { requires: ['automation', 'triggers'] }); // Booting the full in-process stack runs well past vitest's 5s default. @@ -63,6 +93,16 @@ const Ledger = ObjectSchema.create({ fields: { name: Field.text({ label: 'Name', required: true }) }, }); +const CONTRACT = 'fr_contract'; + +const Contract = ObjectSchema.create({ + name: CONTRACT, + sharingModel: 'public_read_write', + label: 'Contract', + pluralLabel: 'Contracts', + fields: { name: Field.text({ label: 'Name', required: true }), end_date: Field.date({ label: 'End date' }) }, +}); + // ── A datasource that is not the ephemeral stack: a driver that records every call ── type Call = { method: string; object?: string }; @@ -183,6 +223,114 @@ const confined: Flow = { ], } as Flow; +/** One node that writes a Ledger row named by a CEL expression. */ +const ledgerNode = (id: string, source: string) => ({ + id, + type: 'create_record', + label: id, + config: { objectName: LEDGER, fields: { name: { dialect: 'cel', source } } }, +}); + +/** start → an `http` call → a Ledger write that must not run → end. */ +const OUTBOUND = 'fr_outbound'; +const outbound: Flow = { + name: OUTBOUND, + label: OUTBOUND, + type: 'autolaunched', + status: 'active', + runAs: 'system', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'call', type: 'http', label: 'Call out', config: { url: OUTBOUND_URL, method: 'GET' } }, + ledgerNode('after_call', "'after the call'"), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'call' }, + { id: 'e2', source: 'call', target: 'after_call' }, + { id: 'e3', source: 'after_call', target: 'end' }, + ], +} as Flow; + +/** A nightly schedule that writes one Ledger row. */ +const NIGHTLY = 'fr_nightly'; +const nightly: Flow = { + name: NIGHTLY, + label: NIGHTLY, + type: 'schedule', + status: 'active', + runAs: 'system', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { schedule: '0 3 * * *' } }, + ledgerNode('write_nightly', "'nightly'"), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'write_nightly' }, + { id: 'e2', source: 'write_nightly', target: 'end' }, + ], +} as Flow; + +/** An inbound hook whose Ledger row is named from `record`, the request body. */ +const HOOK = 'fr_hook'; +const hook: Flow = { + name: HOOK, + label: HOOK, + type: 'api', + status: 'active', + runAs: 'system', + nodes: [ + // The hook secret is named, not carried: the deployment fills it (stubbed above). + { id: 'start', type: 'start', label: 'Start', config: { triggerType: 'api', secretRef: 'FR_HOOK_SECRET' } }, + ledgerNode('write_hook', "'hook for ' + record.name"), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'write_hook' }, + { id: 'e2', source: 'write_hook', target: 'end' }, + ], +} as Flow; + +/** A renewal sweep over contracts whose Ledger row is named from `record`, the swept row. */ +const RENEWAL = 'fr_renewal'; +const renewal: Flow = { + name: RENEWAL, + label: RENEWAL, + type: 'autolaunched', + status: 'active', + runAs: 'system', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { timeRelative: { object: CONTRACT, dateField: 'end_date', withinDays: 30 } } }, + ledgerNode('write_renewal', "'renewal of ' + record.name + ' ' + record.id"), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'write_renewal' }, + { id: 'e2', source: 'write_renewal', target: 'end' }, + ], +} as Flow; + +/** A record-change flow on a Watch save or delete. */ +const legFlow = (name: string, triggerType: string, label: string): Flow => + ({ + name, + label: name, + type: 'record_change', + status: 'active', + runAs: 'system', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: WATCH, triggerType } }, + ledgerNode('write_leg', `'${label}'`), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'write_leg' }, + { id: 'e2', source: 'write_leg', target: 'end' }, + ], + }) as Flow; +const ON_UPDATE = 'fr_on_update'; +const ON_DELETE = 'fr_on_delete'; + const fixtureStack = defineStack({ manifest: { id: 'com.objectstack.verify.flow-run', @@ -206,6 +354,7 @@ const fixtureStack = defineStack({ objects: [ Watch, Ledger, + Contract, { name: REMOTE, label: 'Remote', @@ -216,7 +365,17 @@ const fixtureStack = defineStack({ fields: { name: { type: 'text', label: 'Name' } }, }, ], - flows: [healthy, noExecutor, confined], + flows: [ + healthy, + noExecutor, + confined, + outbound, + nightly, + hook, + renewal, + legFlow(ON_UPDATE, 'record-after-update', 'a watch was saved'), + legFlow(ON_DELETE, 'record-after-delete', 'a watch was deleted'), + ], plugins: [remoteDriverPlugin], } as never); @@ -296,6 +455,70 @@ describe('runFlowProof — the local flow run', () => { expect(remoteCalls.slice(mark)).toEqual([]); expect(report.summary.hardFailures).toBe(1); }); + + it('an outbound node is not executed: the run stops there, the node is named, and no request leaves', async () => { + const mark = outboundHits.length; + const report = await runFlowProof(stack, fixtureStack, { flow: OUTBOUND }); + expect(report.confinement.outbound).toContain('http'); + expect(report.verdict, formatFlowRunReport(report)).toBe('stopped'); + expect(report.firstFailure).toMatchObject({ kind: 'outbound_not_run', nodeId: 'call', nodeType: 'http' }); + // The run log is the engine's own: the start ran, the call is the failing step, nothing after it ran. + expect(report.steps.map((s) => [s.nodeId, s.status])).toEqual([ + ['start', 'success'], + ['call', 'failure'], + ]); + expect(outboundHits.slice(mark)).toEqual([]); + expect(await stack.rows(LEDGER, { name: 'after the call' })).toEqual([]); + // Not a defect of the flow: it does not fail `os verify`. + expect(report.summary.hardFailures).toBe(0); + }); + + it('a schedule the scheduled-work switch keeps unarmed is reported as not armed, and still run with no caller', async () => { + const report = await runFlowProof(stack, fixtureStack, { flow: NIGHTLY }); + expect(report.trigger).toMatchObject({ type: 'schedule', bound: false, cause: 'deployment_policy' }); + expect(report.firstFailure, formatFlowRunReport(report)).toBeUndefined(); + expect(report.start).toBe('system'); + expect(report.verdict).toBe('completed'); + expect(report.notes.some((n) => n.includes("'schedule'") && n.includes('not a defect'))).toBe(true); + expect(report.writes.filter((w) => w.object === LEDGER)).toHaveLength(1); + expect(await stack.rows(LEDGER, { name: 'nightly' })).toHaveLength(1); + expect(report.summary.hardFailures).toBe(0); + }); + + it('an API-triggered flow is handed its body as the record, as the inbound hook hands it', async () => { + const report = await runFlowProof(stack, fixtureStack, { flow: HOOK, input: { name: 'zeta' } }); + expect(report.trigger?.type).toBe('api'); + expect(report.start).toBe('system'); + expect(report.verdict, formatFlowRunReport(report)).toBe('completed'); + expect(await stack.rows(LEDGER, { name: 'hook for zeta' })).toHaveLength(1); + }); + + it('a time-relative flow is handed the given row, seeded, as the record the sweep hands it', async () => { + const report = await runFlowProof(stack, fixtureStack, { flow: RENEWAL, record: { name: 'acme', end_date: '2030-01-01' } }); + expect(report.trigger).toMatchObject({ type: 'time_relative', object: CONTRACT }); + expect(report.verdict, formatFlowRunReport(report)).toBe('completed'); + expect(report.record).toMatchObject({ object: CONTRACT, operation: 'insert' }); + const id = report.record?.id; + expect(id).toBeTruthy(); + expect(await stack.rows(LEDGER, { name: `renewal of acme ${id}` })).toHaveLength(1); + // The seed is the fixture, not the flow's write. + expect(report.writes.filter((w) => w.object === CONTRACT)).toEqual([]); + }); + + it('the update leg seeds the record and saves it, and the save fires the flow', async () => { + const report = await runFlowProof(stack, fixtureStack, { flow: ON_UPDATE, record: { name: 'gamma' } }); + expect(report.record).toMatchObject({ object: WATCH, operation: 'update' }); + expect(report.verdict, formatFlowRunReport(report)).toBe('completed'); + expect(await stack.rows(LEDGER, { name: 'a watch was saved' })).toHaveLength(1); + }); + + it('the delete leg seeds the record and deletes it, and the delete fires the flow', async () => { + const report = await runFlowProof(stack, fixtureStack, { flow: ON_DELETE, record: { name: 'delta' } }); + expect(report.record).toMatchObject({ object: WATCH, operation: 'delete' }); + expect(report.verdict, formatFlowRunReport(report)).toBe('completed'); + expect(await stack.rows(LEDGER, { name: 'a watch was deleted' })).toHaveLength(1); + expect(await stack.rows(WATCH, { name: 'delta' })).toEqual([]); + }); }); describe('runFlowProof — a trigger that never binds', () => { diff --git a/packages/verify/src/flow-run.ts b/packages/verify/src/flow-run.ts index fd506b369cd..2157605f984 100644 --- a/packages/verify/src/flow-run.ts +++ b/packages/verify/src/flow-run.ts @@ -18,13 +18,33 @@ // update leg seeds it first (the seed door fires no trigger) and then saves // it unchanged, so a condition comparing old and new values sees no change; // a delete leg seeds it and deletes it. -// - A flow its own trigger starts with no caller (a schedule, an API trigger, -// or a flow declared `runAs: 'system'`) is started as that trigger starts it: -// the `automation` service's own `execute`, with no caller (`flows.run(…, -// { system: true })`). +// - A flow its own trigger starts with no caller is started with no caller, +// through the `automation` service's own `execute`, with the context that +// trigger builds: +// - an API trigger hands the request body in as both `record` and +// `params`, with `event: 'api'` (`trigger-api/src/api-trigger.ts`, the +// queue consumer in `arm`). The body is `--flow-input`. +// - a time-relative sweep hands each swept row in as `record` and as +// `params`, with the watched `object` and `event: 'time_relative'` +// (`trigger-schedule/src/time-relative-trigger.ts`, the per-row context +// in the sweep). The row is `--flow-record`, seeded first (the seed door +// fires no trigger), so the run gets a row that is in the table, as a +// swept one is. +// - a schedule, or any other flow declared `runAs: 'system'`, gets +// `--flow-input` as its `params` and no caller-supplied keys +// (`flows.run(…, { system: true })`). A real tick seeds its own +// `jobId` / `flowName` / `schedule` params instead, and an acting +// organization a binding declares; neither is reproduced here. // - Every other flow is started by a person: through the runtime's trigger // route as the dev admin (`flows.run(…, { as })`). // +// A trigger the deployment's scheduled-work switch keeps unarmed +// (`unboundCause: 'deployment_policy'`, which the spec's +// `FLOW_UNBOUND_CAUSES` calls an operator setting and not a defect) is +// reported as not armed, with the engine's sentence, and the flow still runs +// through the no-caller start above: the graph is what is under test. Every +// other unbound cause is a defect, and the flow is not run. +// // Nothing here re-derives an engine decision. Whether the trigger is bound, // and why not, is the engine's own runtime state (`getFlowRuntimeStates`, the // sentence `/automation/_status` serves); which node types no executor runs is @@ -44,6 +64,20 @@ // before the driver is called, so the other datasource is never touched; the // node that wrote fails with the refusal, and the report names the object and // its datasource. `flow-run.test.ts` pins it against a recording driver. +// +// ## Outbound nodes are not executed +// +// A node that calls out of the process (`http`, `connector_action`, +// `notify`, `script`) would reach real systems with the project's own +// credentials. Before the run starts, this family replaces each of those +// executors the boot registered, on this stack's engine only, with a +// stand-in that executes nothing and fails the node with a guard-class +// result: the run stops at the first one (a guard result never follows a +// `fault` edge), and the report names it with kind `outbound_not_run`. The +// run log stays the engine's own: every node before it ran for real. A +// `try_catch` region catches a guard result like any other failure, so an +// outbound node inside one hands the run to the catch region, and the report +// says so. Running outbound nodes locally is not offered. import { isServiceNotRegisteredError } from '@objectstack/core'; import { collectFlowGraphs } from '@objectstack/spec/automation'; @@ -66,7 +100,7 @@ export interface FlowRunRequest { } /** What the run came to. */ -export type FlowRunVerdict = 'completed' | 'failed' | 'paused' | 'refused' | 'skipped' | 'not_run'; +export type FlowRunVerdict = 'completed' | 'failed' | 'paused' | 'refused' | 'skipped' | 'stopped' | 'not_run'; /** How the run was started (see the file header). */ export type FlowRunStart = 'record_write' | 'trigger_route' | 'system' | 'none'; @@ -121,6 +155,8 @@ export type FlowRunFailureKind = | 'run_failed' /** A write outside the ephemeral stack was refused. */ | 'confined_write' + /** The run reached an outbound node, which this run does not execute: it stopped there. Not a defect. */ + | 'outbound_not_run' /** The ephemeral driver could not be identified, so the run was not started. */ | 'confinement_unavailable'; @@ -163,11 +199,12 @@ export interface FlowRunReport { /** What the run wrote: every write the engine received while it was open, the triggering write excluded. */ writes: FlowRunWrite[]; /** - * The confinement: the one datasource the run may write, and how many writes - * it refused. `datasource` is empty when the report ends before the - * confinement is set (nothing was started, so nothing could write). + * The confinement: the one datasource the run may write, how many writes it + * refused, and the outbound node types this run does not execute. + * `datasource` is empty when the report ends before the confinement is set + * (nothing was started, so nothing could write). */ - confinement: { datasource: string; refused: number }; + confinement: { datasource: string; refused: number; outbound: string[] }; /** Notes the reader needs (a skipped start, an ignored record, a paused node). */ notes: string[]; summary: { steps: number; failedSteps: number; writes: number; hardFailures: number }; @@ -191,7 +228,14 @@ const RUN_HISTORY_OBJECTS: ReadonlySet = new Set(['sys_automation_run']) /** The automation members this family reads, each typed as the engine's own member. */ type FlowRunAutomation = Pick< AutomationEngine, - 'getFlow' | 'listRuns' | 'getFlowRuntimeStates' | 'getUnknownNodeTypeAudit' + | 'getFlow' + | 'listRuns' + | 'getFlowRuntimeStates' + | 'getUnknownNodeTypeAudit' + | 'execute' + | 'getRegisteredNodeTypes' + | 'getActionDescriptor' + | 'registerNodeExecutor' >; type RunLogEntry = Awaited>[number]; type RuntimeState = ReturnType[number]; @@ -258,6 +302,57 @@ function confineToEphemeral(ql: ObjectQL, refused: ConfinedRefusal[]): string | return defaultName; } +/** The node types that call out of the process: this run does not execute them. */ +const OUTBOUND_NODE_TYPES: readonly string[] = ['http', 'connector_action', 'notify', 'script']; + +/** One outbound node the run reached, and that the stand-in did not execute. */ +interface OutboundStop { + nodeId: string; + nodeType: string; +} + +/** + * The engines whose outbound executors are already stood in, each with the + * list the current run's stops go to (the same swap as the confinement). + */ +const standInEngines = new WeakMap(); + +/** + * Replace each outbound executor the engine registered with a stand-in that + * executes nothing. Once per engine; answers the types it stands in for. + */ +function standInOutbound(automation: FlowRunAutomation, stopped: OutboundStop[]): string[] { + const held = standInEngines.get(automation); + if (held) { + held.stopped = stopped; + return held.types; + } + const registered = new Set(automation.getRegisteredNodeTypes()); + const types = OUTBOUND_NODE_TYPES.filter((type) => registered.has(type)); + const sink = { types, stopped }; + standInEngines.set(automation, sink); + for (const type of types) { + const descriptor = automation.getActionDescriptor(type); + automation.registerNodeExecutor({ + type, + ...(descriptor ? { descriptor } : {}), + async execute(node) { + sink.stopped.push({ nodeId: node.id, nodeType: type }); + return { + success: false, + // Guard class: the stop must not follow a `fault` edge into the + // author's handler for a call that was never made. + errorClass: 'guard', + error: + `verify --flow does not execute outbound nodes: '${node.id}' (${type}) would call out of the process, ` + + 'so the run stopped here and nothing after it is proven', + }; + }, + }); + } + return types; +} + function strings(values: unknown[]): string[] { return values.filter((v) => typeof v === 'string' || typeof v === 'number').map(String); } @@ -356,7 +451,7 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo steps: [], missingExecutors: [], writes: [], - confinement: { datasource: '', refused: 0 }, + confinement: { datasource: '', refused: 0, outbound: [] }, notes: [], summary: { steps: 0, failedSteps: 0, writes: 0, hardFailures: 0 }, }; @@ -412,7 +507,13 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo const triggerName = report.trigger ? `'${report.trigger.type}'${report.trigger.object ? ` on '${report.trigger.object}'` : ''}` : undefined; - if (report.trigger && !report.trigger.bound) { + const policyUnarmed = report.trigger?.bound === false && report.trigger.cause === 'deployment_policy'; + if (policyUnarmed) { + report.notes.push( + `the trigger ${triggerName} is not armed on this deployment: ${report.trigger!.reason ?? 'its scheduled-work switch is off'}. ` + + 'That is an operator setting, not a defect; the flow was run anyway with no caller, as the trigger would start it', + ); + } else if (report.trigger && !report.trigger.bound) { report.firstFailure = { kind: 'trigger_unbound', trigger: triggerName, @@ -444,6 +545,8 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo return finish(); } report.confinement.datasource = ephemeral; + const stopped: OutboundStop[] = []; + report.confinement.outbound = [...standInOutbound(automation, stopped)]; // 6. Start it, the way production starts it, observing every write. const runsBefore = new Set((await automation.listRuns(flow, { limit: 100 })).map((r) => r.id)); @@ -497,8 +600,53 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo startRefusal = { code: (e as { code?: string })?.code, message: (e as Error)?.message ?? String(e) }; } triggerWrite = observed.find((w) => w.object === object && w.operation === operation); + } else if (report.trigger?.type === 'api' || report.trigger?.type === 'time_relative') { + // The context the trigger itself builds (file header): the API trigger's + // queue consumer, or the time-relative sweep's per-row context. + const api = report.trigger.type === 'api'; + report.start = 'system'; + let context: Record | undefined; + if (api) { + if (request.record) report.notes.push("the record was ignored: an API-triggered flow's record is the request body, given as --flow-input"); + const body = { ...(request.input ?? {}) }; + context = { record: body, params: { ...body }, event: 'api' }; + } else { + const object = report.trigger.object; + if (!request.record) { + report.firstFailure = { + kind: 'record_required', + trigger: triggerName, + message: + `a time-relative flow runs once per swept '${object ?? 'record'}' row; name the row's fields ` + + `(--flow-record '{"field":"value"}') and the run seeds it and hands it in as the sweep does`, + }; + return finish(); + } + if (request.input) report.notes.push("the input was ignored: a time-relative sweep's params are the swept row"); + try { + let row: EngineRow = { ...request.record }; + if (object && stack.metadata.object(object)) { + const [seeded] = await stack.seed(object, [{ ...request.record }]); + if (seeded) row = seeded; + report.record = { object, operation: 'insert', ...(row.id !== undefined ? { id: String(row.id) } : {}) }; + report.notes.push('the record was seeded first, so the run is handed a row that is in the table, as a swept row is'); + } + context = { record: row, ...(object ? { object } : {}), event: 'time_relative', params: row }; + } catch (e) { + startRefusal = { code: (e as { code?: string })?.code, message: (e as Error)?.message ?? String(e) }; + } + } + if (context) { + try { + observed = await stack.observeWrites(async () => { + result = { ...(await automation.execute(flow, context as never)), flowName: flow }; + }); + } catch (e) { + startRefusal = { code: (e as { code?: string })?.code, message: (e as Error)?.message ?? String(e) }; + } + } } else { - if (request.record) report.notes.push('the record was ignored: only a record-change flow starts from a record'); + if (request.record) report.notes.push('the record was ignored: only a record-change or time-relative flow starts from a record'); const selfStarted = report.trigger !== undefined || definition.runAs === 'system'; report.start = selfStarted ? 'system' : 'trigger_route'; const opts = selfStarted ? ({ system: true } as const) : { as: await stack.signIn() }; @@ -551,8 +699,18 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo if (failing) { const confinedWrite = refused.length > 0 && CONFINEMENT_SENTENCE.test(failing.error?.message ?? ''); const missing = report.missingExecutors.some((m) => m.nodeId === failing.nodeId); + const outbound = stopped.some((o) => o.nodeId === failing.nodeId && o.nodeType === failing.nodeType); + if (outbound) { + if (report.verdict === 'failed') report.verdict = 'stopped'; + report.notes.push( + `the run reached outbound node '${failing.nodeId}' (${failing.nodeType}), which verify --flow does not execute` + + (report.verdict === 'stopped' + ? ': it stopped there, and no node after it is proven' + : `; a try region caught the stop, so the run went on as it would after a failed call`), + ); + } report.firstFailure = { - kind: confinedWrite ? 'confined_write' : missing ? 'no_executor' : 'node_failed', + kind: outbound ? 'outbound_not_run' : confinedWrite ? 'confined_write' : missing ? 'no_executor' : 'node_failed', nodeId: failing.nodeId, nodeType: failing.nodeType, ...(failing.error?.code ? { code: failing.error.code } : {}), @@ -600,7 +758,8 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo /** Count what the report proves and what it failed. */ function summarize(report: FlowRunReport): FlowRunReport { const failedSteps = report.steps.filter((s) => s.status === 'failure').length; - let hardFailures = report.firstFailure ? 1 : 0; + // An outbound node this run did not execute is not a defect of the flow. + let hardFailures = report.firstFailure && report.firstFailure.kind !== 'outbound_not_run' ? 1 : 0; // A node with no executor the run did not reach is still a node that cannot run. hardFailures += report.missingExecutors.filter((m) => m.nodeId !== report.firstFailure?.nodeId).length; // A confined write the flow swallowed (a fault edge, a try region) left the run green and the write unlanded. @@ -619,7 +778,10 @@ export function formatFlowRunReport(report: FlowRunReport): string { const t = report.trigger; lines.push( ` flow: ${report.flow}; started by ${report.start === 'record_write' ? 'a record write' : report.start === 'system' ? 'its own trigger (no caller)' : report.start === 'trigger_route' ? 'the trigger route, as the dev admin' : 'nothing'}` + - (t ? `; trigger ${t.type}${t.object ? ` on ${t.object}` : ''}${t.event ? ` (${t.event})` : ''} ${t.bound ? 'bound' : 'NOT BOUND'}` : ''), + (t + ? `; trigger ${t.type}${t.object ? ` on ${t.object}` : ''}${t.event ? ` (${t.event})` : ''} ` + + (t.bound ? 'bound' : t.cause === 'deployment_policy' ? 'not armed on this deployment (scheduled work is switched off)' : 'NOT BOUND') + : ''), ); if (report.record) { lines.push(` record: ${report.record.operation} ${report.record.object}${report.record.id ? ` ${report.record.id}` : ''}`); @@ -627,6 +789,9 @@ export function formatFlowRunReport(report: FlowRunReport): string { if (report.confinement.datasource) { lines.push(` confined to datasource '${report.confinement.datasource}' (the in-memory database this run booted)`); } + if (report.confinement.outbound.length > 0) { + lines.push(` not executed: outbound node types ${report.confinement.outbound.join(', ')} (the run stops at the first one it reaches)`); + } for (const s of report.steps) { const mark = s.status === 'success' ? '✓' : s.status === 'failure' ? '✗' : '–'; const where = s.region ? ` [${s.region}]` : ''; From 97bd03bdec5e77c08dd11b5b01f8b14efbda42f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:37:58 +0000 Subject: [PATCH 07/11] test(verify): the outbound pin reads the server's request log first Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/verify/src/flow-run.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/verify/src/flow-run.test.ts b/packages/verify/src/flow-run.test.ts index e3e5de0d915..2588bd03f0d 100644 --- a/packages/verify/src/flow-run.test.ts +++ b/packages/verify/src/flow-run.test.ts @@ -459,6 +459,8 @@ describe('runFlowProof — the local flow run', () => { it('an outbound node is not executed: the run stops there, the node is named, and no request leaves', async () => { const mark = outboundHits.length; const report = await runFlowProof(stack, fixtureStack, { flow: OUTBOUND }); + // First: nothing left the process. + expect(outboundHits.slice(mark), formatFlowRunReport(report)).toEqual([]); expect(report.confinement.outbound).toContain('http'); expect(report.verdict, formatFlowRunReport(report)).toBe('stopped'); expect(report.firstFailure).toMatchObject({ kind: 'outbound_not_run', nodeId: 'call', nodeType: 'http' }); @@ -467,7 +469,6 @@ describe('runFlowProof — the local flow run', () => { ['start', 'success'], ['call', 'failure'], ]); - expect(outboundHits.slice(mark)).toEqual([]); expect(await stack.rows(LEDGER, { name: 'after the call' })).toEqual([]); // Not a defect of the flow: it does not fail `os verify`. expect(report.summary.hardFailures).toBe(0); From 07a5495f1132fbadab8181a56a9dc2722af91d25 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:45:46 +0000 Subject: [PATCH 08/11] fix(cli): close the --flow description string Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/cli/src/commands/verify.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli/src/commands/verify.ts b/packages/cli/src/commands/verify.ts index 06581504896..2e76228959c 100644 --- a/packages/cli/src/commands/verify.ts +++ b/packages/cli/src/commands/verify.ts @@ -200,7 +200,7 @@ export default class Verify extends Command { }), flow: Flags.string({ description: - "Also run this flow once on a fresh boot and report each node's status, the first failure with its code and the node named, and what the run wrote. It starts the way production starts it: a record-change flow by a real write of the record --flow-record names, a flow its own trigger starts with no caller (an API-triggered flow with --flow-input as its record and params, a time-relative flow with --flow-record seeded and handed in as its record, a schedule or runAs: 'system' flow with --flow-input as its params), any other flow through the trigger route as the dev admin. A schedule the deployment's scheduled-work switch keeps unarmed is reported as not armed and still run. Every write outside the in-memory database this run boots is refused before its datasource is called. Outbound nodes (http, connector_action, notify, script) are not executed: the run stops at the first one and names it, so nothing calls out of this machine + "Also run this flow once on a fresh boot and report each node's status, the first failure with its code and the node named, and what the run wrote. It starts the way production starts it: a record-change flow by a real write of the record --flow-record names, a flow its own trigger starts with no caller (an API-triggered flow with --flow-input as its record and params, a time-relative flow with --flow-record seeded and handed in as its record, a schedule or runAs: 'system' flow with --flow-input as its params), any other flow through the trigger route as the dev admin. A schedule the deployment's scheduled-work switch keeps unarmed is reported as not armed and still run. Every write outside the in-memory database this run boots is refused before its datasource is called. Outbound nodes (http, connector_action, notify, script) are not executed: the run stops at the first one and names it, so nothing calls out of this machine", }), 'flow-record': Flags.string({ description: From f1b566279d8b071c0363ed2b4cb2a6a90c624fd5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:47:37 +0000 Subject: [PATCH 09/11] fix(verify): the stand-in's sentence does not claim the run stopped Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/verify/src/flow-run.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/verify/src/flow-run.ts b/packages/verify/src/flow-run.ts index 2157605f984..47edf478c4d 100644 --- a/packages/verify/src/flow-run.ts +++ b/packages/verify/src/flow-run.ts @@ -345,7 +345,7 @@ function standInOutbound(automation: FlowRunAutomation, stopped: OutboundStop[]) errorClass: 'guard', error: `verify --flow does not execute outbound nodes: '${node.id}' (${type}) would call out of the process, ` + - 'so the run stopped here and nothing after it is proven', + 'so it was not run, and nothing that depends on it is proven', }; }, }); From 17561e0f981be1d0e70026531f633ee78ed9eb62 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:35:03 +0000 Subject: [PATCH 10/11] fix(verify): a caught outbound stop does not hide a later failure; a child flow's stop is named Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/verify/src/flow-run.test.ts | 133 +++++++++++++++++++++++++++ packages/verify/src/flow-run.ts | 97 ++++++++++++++----- 2 files changed, 207 insertions(+), 23 deletions(-) diff --git a/packages/verify/src/flow-run.test.ts b/packages/verify/src/flow-run.test.ts index 2588bd03f0d..f24af7e189c 100644 --- a/packages/verify/src/flow-run.test.ts +++ b/packages/verify/src/flow-run.test.ts @@ -17,6 +17,10 @@ * datasource's driver is called: the recording driver below sees no write; * - an outbound node is not executed: the run stops there with the node * named, and the local server below receives no request; + * - a stop the run goes on past (a try region's catch, a parallel branch) + * does not hide a later real failure: that node is the first failure; + * - a stop inside a child flow is named at the child's node, not reported + * as the calling `subflow` node's failure; * - a schedule the deployment's scheduled-work switch keeps unarmed is not a * defect: it is reported as not armed and still run with no caller; * - an API-triggered flow gets its body as `record` as well as `params`, and @@ -252,6 +256,97 @@ const outbound: Flow = { ], } as Flow; +/** A Ledger write with no name: the required field refuses it at run time. */ +const failingWrite = (id: string) => ({ id, type: 'create_record', label: id, config: { objectName: LEDGER, fields: {} } }); +const httpCall = (id: string) => ({ id, type: 'http', label: id, config: { url: OUTBOUND_URL, method: 'GET' } }); + +/** start → a try region around an `http` call, caught → a write that really fails → end. */ +const CAUGHT = 'fr_caught'; +const caught: Flow = { + name: CAUGHT, + label: CAUGHT, + type: 'autolaunched', + status: 'active', + runAs: 'system', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { + id: 'guard', + type: 'try_catch', + label: 'Guard', + config: { + try: { nodes: [httpCall('caught_call')] }, + catch: { nodes: [{ id: 'call_failed', type: 'assignment', label: 'Call failed' }] }, + }, + }, + failingWrite('boom'), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'guard' }, + { id: 'e2', source: 'guard', target: 'boom' }, + { id: 'e3', source: 'boom', target: 'end' }, + ], +} as Flow; + +/** start → one branch calls out, the other branch's write really fails → end. */ +const FORKED = 'fr_forked'; +const forked: Flow = { + name: FORKED, + label: FORKED, + type: 'autolaunched', + status: 'active', + runAs: 'system', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { + id: 'fan', + type: 'parallel', + label: 'Fan out', + config: { branches: [{ name: 'call', nodes: [httpCall('fork_call')] }, { name: 'write', nodes: [failingWrite('fork_boom')] }] }, + }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'fan' }, + { id: 'e2', source: 'fan', target: 'end' }, + ], +} as Flow; + +/** A child flow that calls out, and a parent that calls it and then writes. */ +const CHILD = 'fr_child'; +const child: Flow = { + name: CHILD, + label: CHILD, + type: 'autolaunched', + status: 'active', + runAs: 'system', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, httpCall('child_call'), { id: 'end', type: 'end', label: 'End' }], + edges: [ + { id: 'e1', source: 'start', target: 'child_call' }, + { id: 'e2', source: 'child_call', target: 'end' }, + ], +} as Flow; +const PARENT = 'fr_parent'; +const parent: Flow = { + name: PARENT, + label: PARENT, + type: 'autolaunched', + status: 'active', + runAs: 'system', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'call_child', type: 'subflow', label: 'Call child', config: { flowName: CHILD } }, + ledgerNode('after_child', "'after the child'"), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'call_child' }, + { id: 'e2', source: 'call_child', target: 'after_child' }, + { id: 'e3', source: 'after_child', target: 'end' }, + ], +} as Flow; + /** A nightly schedule that writes one Ledger row. */ const NIGHTLY = 'fr_nightly'; const nightly: Flow = { @@ -370,6 +465,10 @@ const fixtureStack = defineStack({ noExecutor, confined, outbound, + caught, + forked, + child, + parent, nightly, hook, renewal, @@ -464,6 +563,7 @@ describe('runFlowProof — the local flow run', () => { expect(report.confinement.outbound).toContain('http'); expect(report.verdict, formatFlowRunReport(report)).toBe('stopped'); expect(report.firstFailure).toMatchObject({ kind: 'outbound_not_run', nodeId: 'call', nodeType: 'http' }); + expect(report.outboundStops).toEqual([{ nodeId: 'call', nodeType: 'http' }]); // The run log is the engine's own: the start ran, the call is the failing step, nothing after it ran. expect(report.steps.map((s) => [s.nodeId, s.status])).toEqual([ ['start', 'success'], @@ -474,6 +574,39 @@ describe('runFlowProof — the local flow run', () => { expect(report.summary.hardFailures).toBe(0); }); + it('a stop a try region catches does not hide the later node that really fails', async () => { + const mark = outboundHits.length; + const report = await runFlowProof(stack, fixtureStack, { flow: CAUGHT }); + expect(outboundHits.slice(mark)).toEqual([]); + expect(report.verdict, formatFlowRunReport(report)).toBe('failed'); + expect(report.firstFailure).toMatchObject({ kind: 'node_failed', nodeId: 'boom', nodeType: 'create_record' }); + expect(report.outboundStops).toEqual([{ nodeId: 'caught_call', nodeType: 'http' }]); + expect(report.notes.some((n) => n.includes("'caught_call' (http)") && n.includes('went on past'))).toBe(true); + expect(report.summary.hardFailures).toBe(1); + }); + + it('a stopped parallel branch does not hide the other branch that really fails', async () => { + const mark = outboundHits.length; + const report = await runFlowProof(stack, fixtureStack, { flow: FORKED }); + expect(outboundHits.slice(mark)).toEqual([]); + expect(report.verdict, formatFlowRunReport(report)).toBe('failed'); + expect(report.firstFailure).toMatchObject({ kind: 'node_failed', nodeId: 'fork_boom' }); + expect(report.outboundStops).toEqual([{ nodeId: 'fork_call', nodeType: 'http' }]); + expect(report.summary.hardFailures).toBe(1); + }); + + it("a stop inside a child flow is named at the child's node, not as the subflow node's failure", async () => { + const mark = outboundHits.length; + const report = await runFlowProof(stack, fixtureStack, { flow: PARENT }); + expect(outboundHits.slice(mark)).toEqual([]); + expect(report.verdict, formatFlowRunReport(report)).toBe('stopped'); + expect(report.firstFailure).toMatchObject({ kind: 'outbound_not_run', nodeId: 'child_call', nodeType: 'http' }); + expect(report.steps.find((s) => s.nodeId === 'call_child')?.status).toBe('failure'); + expect(report.outboundStops).toEqual([{ nodeId: 'child_call', nodeType: 'http' }]); + expect(await stack.rows(LEDGER, { name: 'after the child' })).toEqual([]); + expect(report.summary.hardFailures).toBe(0); + }); + it('a schedule the scheduled-work switch keeps unarmed is reported as not armed, and still run with no caller', async () => { const report = await runFlowProof(stack, fixtureStack, { flow: NIGHTLY }); expect(report.trigger).toMatchObject({ type: 'schedule', bound: false, cause: 'deployment_policy' }); diff --git a/packages/verify/src/flow-run.ts b/packages/verify/src/flow-run.ts index 47edf478c4d..835d69e8cab 100644 --- a/packages/verify/src/flow-run.ts +++ b/packages/verify/src/flow-run.ts @@ -67,17 +67,31 @@ // // ## Outbound nodes are not executed // -// A node that calls out of the process (`http`, `connector_action`, -// `notify`, `script`) would reach real systems with the project's own -// credentials. Before the run starts, this family replaces each of those -// executors the boot registered, on this stack's engine only, with a -// stand-in that executes nothing and fails the node with a guard-class -// result: the run stops at the first one (a guard result never follows a -// `fault` edge), and the report names it with kind `outbound_not_run`. The -// run log stays the engine's own: every node before it ran for real. A -// `try_catch` region catches a guard result like any other failure, so an -// outbound node inside one hands the run to the catch region, and the report -// says so. Running outbound nodes locally is not offered. +// Four node types call out of the process: `http`, `connector_action` (and +// every connector a plugin contributes, which runs behind it), `notify` and +// `script`. Run for real they would reach real systems with the project's own +// credentials. Before the run starts, this family replaces each of those four +// executors the boot registered, on this stack's engine only, with a stand-in +// that executes nothing and fails the node with a guard-class result: a guard +// result never follows a `fault` edge. A plugin's own node type that calls out +// under another name is not stood in, and runs for real. +// +// How a stop is reported: +// - Each step is classified. A stop is the stopped node's own step, or a +// step whose failure carries the stand-in's sentence: a container around +// it, or a `subflow` / `map` node whose child run was stopped (the child's +// error text reaches the parent's step, but not its guard class, so a +// `fault` edge on the calling node is still followed). +// - The first failure is the first failing step that is not a stop. Only +// when no other step failed and the run failed is the stop why it ended: +// then the verdict is `stopped` and the first failure is `outbound_not_run` +// naming the outbound node (the child's node, for a child flow). +// - A stop the run went on past (a `try_catch` region's catch, or a fault +// edge on a calling node) is a note: what came after reads a call that +// never happened. +// - Every stood-in node the run reached is listed in `outboundStops`. +// The run log stays the engine's own. Running outbound nodes locally is not +// offered. import { isServiceNotRegisteredError } from '@objectstack/core'; import { collectFlowGraphs } from '@objectstack/spec/automation'; @@ -195,6 +209,8 @@ export interface FlowRunReport { steps: FlowRunStep[]; /** Every node whose type no executor runs, reached or not. */ missingExecutors: Array<{ nodeId: string; nodeType: string; region?: string }>; + /** Every outbound node the run reached and did not execute, in a child flow too, in the order reached. */ + outboundStops: Array<{ nodeId: string; nodeType: string }>; firstFailure?: FlowRunFailure; /** What the run wrote: every write the engine received while it was open, the triggering write excluded. */ writes: FlowRunWrite[]; @@ -254,6 +270,13 @@ interface ConfinedRefusal { operation: ObservedWrite['operation']; } +/** + * How a failing step's message is recognised as the outbound stand-in's stop: + * the node's own step, a container's, or a `subflow` / `map` node's, whose + * error text carries the child's. Captures the stopped node's id and type. + */ +const OUTBOUND_SENTENCE = /verify --flow does not execute outbound nodes: '([^']+)' \(([^)]+)\)/; + /** How a failing step's message is recognised as the confinement's refusal (the engine wraps the node's code). */ const CONFINEMENT_SENTENCE = /a flow run writes to the ephemeral stack only/; @@ -450,6 +473,7 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo start: 'none', steps: [], missingExecutors: [], + outboundStops: [], writes: [], confinement: { datasource: '', refused: 0, outbound: [] }, notes: [], @@ -691,34 +715,61 @@ export async function runFlowProof(stack: VerifyStack, config: any, request: Flo ]; report.confinement.refused = refused.length; + report.outboundStops = stopped.map((o) => ({ ...o })); + if (run) { report.runId = run.id; report.steps = (run.steps ?? []).map(stepOf); report.verdict = VERDICT_OF_STATUS[run.status] ?? 'failed'; - const failing = report.steps.find((s) => s.status === 'failure'); + // A stand-in stop is classified per step: the stopped node's own step, or a + // step whose failure carries the stand-in's sentence (a container, or a + // `subflow` / `map` node whose child run was stopped). The first failure is + // the first failing step that is NOT a stop; a stop is why the run ended + // only when no other step failed. + const isStop = (step: FlowRunStep): boolean => + stopped.some((o) => o.nodeId === step.nodeId && o.nodeType === step.nodeType) || + OUTBOUND_SENTENCE.test(step.error?.message ?? ''); + const failingSteps = report.steps.filter((s) => s.status === 'failure'); + const failing = failingSteps.find((s) => !isStop(s)); + const stopStep = failingSteps.find(isStop); if (failing) { const confinedWrite = refused.length > 0 && CONFINEMENT_SENTENCE.test(failing.error?.message ?? ''); const missing = report.missingExecutors.some((m) => m.nodeId === failing.nodeId); - const outbound = stopped.some((o) => o.nodeId === failing.nodeId && o.nodeType === failing.nodeType); - if (outbound) { - if (report.verdict === 'failed') report.verdict = 'stopped'; - report.notes.push( - `the run reached outbound node '${failing.nodeId}' (${failing.nodeType}), which verify --flow does not execute` + - (report.verdict === 'stopped' - ? ': it stopped there, and no node after it is proven' - : `; a try region caught the stop, so the run went on as it would after a failed call`), - ); - } report.firstFailure = { - kind: outbound ? 'outbound_not_run' : confinedWrite ? 'confined_write' : missing ? 'no_executor' : 'node_failed', + kind: confinedWrite ? 'confined_write' : missing ? 'no_executor' : 'node_failed', nodeId: failing.nodeId, nodeType: failing.nodeType, ...(failing.error?.code ? { code: failing.error.code } : {}), message: failing.error?.message ?? `node '${failing.nodeId}' failed`, }; + } else if (stopStep && report.verdict === 'failed') { + // The stop itself ended the run: name the outbound node, which for a + // child flow's node is the one its sentence names, not the calling node. + const named = OUTBOUND_SENTENCE.exec(stopStep.error?.message ?? ''); + const nodeId = named?.[1] ?? stopStep.nodeId; + const nodeType = named?.[2] ?? stopStep.nodeType; + report.verdict = 'stopped'; + report.firstFailure = { + kind: 'outbound_not_run', + nodeId, + nodeType, + ...(stopStep.error?.code ? { code: stopStep.error.code } : {}), + message: stopStep.error?.message ?? `outbound node '${nodeId}' was not executed`, + }; + report.notes.push( + `the run ended at outbound node '${nodeId}' (${nodeType}), which verify --flow does not execute` + + (nodeId !== stopStep.nodeId ? `, reached through '${stopStep.nodeId}' (${stopStep.nodeType})` : '') + + ': no node after it is proven', + ); } else if (report.verdict === 'failed') { report.firstFailure = { kind: 'run_failed', message: run.error ?? `run ${run.id} failed with no failing step in its log` }; } + if (report.outboundStops.length > 0 && report.verdict !== 'stopped') { + const names = report.outboundStops.map((o) => `'${o.nodeId}' (${o.nodeType})`).join(', '); + report.notes.push( + `outbound node(s) ${names} were not executed; the run went on past the stop (a try region's catch, or a fault edge on a calling subflow or map node, handled it as a failed call), so what came after reads a call that never happened`, + ); + } if (report.verdict === 'paused') { const last = report.steps[report.steps.length - 1]; report.notes.push(`the run paused${last ? ` after node '${last.nodeId}' (${last.nodeType})` : ''}; that is normal for a screen, wait or approval`); From 3d4db25136b66d721c89967d9658172c76dfb8a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:36:32 +0000 Subject: [PATCH 11/11] docs(verify): name the four stood-in outbound types and the plugin-type boundary; the time-relative start sets no acting organization Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .changeset/34779-verify-flow-run.md | 4 ++-- content/docs/deployment/cli.mdx | 22 +++++++++++++++------- packages/cli/src/commands/verify.ts | 9 +++++---- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/.changeset/34779-verify-flow-run.md b/.changeset/34779-verify-flow-run.md index 6674013e9b8..cc972d7d1cd 100644 --- a/.changeset/34779-verify-flow-run.md +++ b/.changeset/34779-verify-flow-run.md @@ -10,9 +10,9 @@ Metadata-protocol: none `os verify --flow ` runs one flow once on a fresh in-memory boot of the app and reports what the engine did: each node's status as the run's log records it, the first failure with its code and the node named, and every write the run made. -- The run starts the way production starts it. A record-change flow is fired by its own trigger: the run writes the record `--flow-record '{"field":"value"}'` names as the dev admin (inserted for a create or write leg; seeded and saved unchanged for an update leg; seeded and deleted for a delete leg). A flow its own trigger starts is started with no caller, with the context that trigger builds: an API-triggered flow gets `--flow-input '{...}'` as its record and its params (the request body); a time-relative flow gets the `--flow-record` row, seeded first, as its record; a schedule or another `runAs: 'system'` flow gets `--flow-input` as its params. Any other flow goes through the trigger route as the dev admin, with `--flow-input` as its params. +- The run starts the way production starts it. A record-change flow is fired by its own trigger: the run writes the record `--flow-record '{"field":"value"}'` names as the dev admin (inserted for a create or write leg; seeded and saved unchanged for an update leg; seeded and deleted for a delete leg). A flow its own trigger starts is started with no caller, with the context that trigger builds: an API-triggered flow gets `--flow-input '{...}'` as its record and its params (the request body); a time-relative flow gets the `--flow-record` row, seeded first, as its record (the acting organization a sweep can set is not reproduced); a schedule or another `runAs: 'system'` flow gets `--flow-input` as its params. Any other flow goes through the trigger route as the dev admin, with `--flow-input` as its params. - A node whose type no installed plugin runs is named, whether the run reached it or not. A flow whose trigger never binds is reported with the trigger and the engine's reason, and is not run. A schedule or time-relative trigger left unarmed by the deployment's scheduled-work switch (the default) is not a defect: it is reported as not armed and the flow is still run. -- The run writes to the in-memory database the boot creates and nowhere else: a write to an object bound to any other datasource is refused before that datasource's driver is called, and the node that made it fails naming the object and the datasource. Nothing calls out of the machine: an outbound node (`http`, `connector_action`, `notify`, `script`) is not executed. The run stops at the first one and the report names it (`outbound_not_run`); every node before it ran for real. +- The run writes to the in-memory database the boot creates and nowhere else: a write to an object bound to any other datasource is refused before that datasource's driver is called, and the node that made it fails naming the object and the datasource. Four outbound node types are not executed: `http`, `connector_action` (with every connector a plugin contributes behind it), `notify` and `script`; a plugin's own node type that calls out under another name is not stood in and runs for real. A run that ends at one of them stops there and the report names it (`outbound_not_run`), in a child flow too; every node before it ran for real. A stop a `try_catch` catches is listed in `outboundStops`, and a later node that fails is still the first failure. - A failed run, a missing executor, an unbound trigger, a record-change or time-relative flow given no record, and a write refused outside the ephemeral stack each fail `os verify`. A run its start condition skipped, one that paused at a screen, wait or approval, and one stopped at an outbound node are reported and do not. - `--json` carries the report as `flowRun`. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 4c4790178e0..e21f6117ccf 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -3106,7 +3106,8 @@ os verify --flow notify_on_new_case --flow-record '{"subject":"Printer jam"}' API-triggered flow is handed `--flow-input` (a JSON object) as its record and its params, as the inbound hook hands it the request body; a time-relative flow is handed the `--flow-record` row as its record, seeded - first so it is in the table, as a swept row is; a schedule, or another + first so it is in the table, as a swept row is (the acting organization a + sweep can set, `tenantId`, is not reproduced); a schedule, or another flow declared `runAs: 'system'`, is handed `--flow-input` as its params (a real tick's own `jobId`, `flowName` and `schedule` params and a binding's acting organization are not reproduced). Any other flow goes @@ -3125,11 +3126,17 @@ os verify --flow notify_on_new_case --flow-record '{"subject":"Printer jam"}' database this boot creates and nowhere else: a write to an object bound to any other datasource is refused before that datasource's driver is called, and the node that made it fails naming the object and the datasource. - Nothing calls out of the machine either: an outbound node (`http`, - `connector_action`, `notify`, `script`) is not executed. The run stops at - the first one it reaches, and the report names it (`outbound_not_run`); - every node before it ran for real. Inside a `try_catch` region the catch - region handles the stop as it would a failed call. + Four outbound node types are not executed: `http`, `connector_action` + (which also runs every connector a plugin contributes), `notify` and + `script`. A plugin's own node type that calls out under another name is + not stood in, and runs for real. A run that ends at one of the four stops + there, and the report names it (`outbound_not_run`); every node before it + ran for real. A stop inside a child flow is named at the child's node, and + a `fault` edge on the calling `subflow` or `map` node is still followed. + Inside a `try_catch` region the catch region handles the stop as it would + a failed call, and the run goes on: the stop is listed + (`outboundStops`), and a later node that fails is still the first failure + and still fails `os verify`. `--multi-tenant` boots org-scoped so tenant-isolation RLS policies apply; a walled tenancy posture (`OS_TENANCY_POSTURE` set to `isolated` or `group`) asks for the same boot. @@ -3168,7 +3175,8 @@ document carries depends on where the run ended: `--dashboard-windows`; its `presets` name what each preset handed the door and how it resolved), `flowRun` (with `--flow`: the `verdict`, how the run started, the `trigger` and whether it is bound, the `steps`, the - `missingExecutors`, the `firstFailure`, the `writes` and the `confinement`) + `missingExecutors`, the `firstFailure`, the `outboundStops`, the `writes` + and the `confinement`) and `hardFailures`, the count the exit status is read from. - **Could not run:** `{ "error": "" }`, plus `code` and `httpStatus` when the failure carries them. diff --git a/packages/cli/src/commands/verify.ts b/packages/cli/src/commands/verify.ts index 2e76228959c..ab2da629f03 100644 --- a/packages/cli/src/commands/verify.ts +++ b/packages/cli/src/commands/verify.ts @@ -146,9 +146,10 @@ export interface VerifyCapabilityAdvisory { * production starts it (a record-change flow by a real write of the * record --flow-record names), reported node by node with the first * failure and what it wrote; every write outside the ephemeral - * stack is refused before its datasource is called, and an - * outbound node (http, connector_action, notify, script) is not - * executed: the run stops there + * stack is refused before its datasource is called, and the four + * outbound node types (http, connector_action, notify, script) + * are not executed: the run stops there (a plugin's own outbound + * node type is not stood in) * * Exits non-zero on either stage's failures so it drops straight into CI. */ @@ -200,7 +201,7 @@ export default class Verify extends Command { }), flow: Flags.string({ description: - "Also run this flow once on a fresh boot and report each node's status, the first failure with its code and the node named, and what the run wrote. It starts the way production starts it: a record-change flow by a real write of the record --flow-record names, a flow its own trigger starts with no caller (an API-triggered flow with --flow-input as its record and params, a time-relative flow with --flow-record seeded and handed in as its record, a schedule or runAs: 'system' flow with --flow-input as its params), any other flow through the trigger route as the dev admin. A schedule the deployment's scheduled-work switch keeps unarmed is reported as not armed and still run. Every write outside the in-memory database this run boots is refused before its datasource is called. Outbound nodes (http, connector_action, notify, script) are not executed: the run stops at the first one and names it, so nothing calls out of this machine", + "Also run this flow once on a fresh boot and report each node's status, the first failure with its code and the node named, and what the run wrote. It starts the way production starts it: a record-change flow by a real write of the record --flow-record names, a flow its own trigger starts with no caller (an API-triggered flow with --flow-input as its record and params, a time-relative flow with --flow-record seeded and handed in as its record (no acting organization), a schedule or runAs: 'system' flow with --flow-input as its params), any other flow through the trigger route as the dev admin. A schedule the deployment's scheduled-work switch keeps unarmed is reported as not armed and still run. Every write outside the in-memory database this run boots is refused before its datasource is called. Four outbound node types (http, connector_action, notify, script) are not executed: a run that reaches one stops there and names it. A plugin's own node type that calls out under another name is not stood in, and runs for real", }), 'flow-record': Flags.string({ description: