Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/34779-verify-flow-run.md
Original file line number Diff line number Diff line change
@@ -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 <name>` 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 (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. 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`.

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.
52 changes: 50 additions & 2 deletions content/docs/deployment/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -3092,6 +3093,50 @@ 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 <name>`, 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 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 (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
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.
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.
Expand Down Expand Up @@ -3128,8 +3173,11 @@ 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 `outboundStops`, the `writes`
and the `confinement`)
and `hardFailures`, the count the exit status is read from.
- **Could not run:** `{ "error": "<sentence>" }`, plus `code` and `httpStatus`
when the failure carries them.

Expand Down
64 changes: 61 additions & 3 deletions packages/cli/src/commands/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import {
formatDashboardWindowReport,
readSeedOutcome,
formatSeedReport,
runFlowProof,
formatFlowRunReport,
type VerifyReport,
type SeedReport,
type RlsReport,
Expand All @@ -36,6 +38,7 @@ import {
type UniqueScopeReport,
type ParentWriteReachReport,
type DashboardWindowReport,
type FlowRunReport,
type RlsProbeDescriptor,
type RlsPositionPersonaInput,
} from '@objectstack/verify';
Expand All @@ -59,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?
Expand Down Expand Up @@ -138,12 +142,20 @@ 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, 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.
*/
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',
Expand All @@ -154,6 +166,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 = {
Expand Down Expand Up @@ -185,6 +199,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 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:
'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 (and, for an API-triggered flow, as its record, the request body)',
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,
Expand Down Expand Up @@ -267,9 +294,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<void> {
// 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_*`
Expand Down Expand Up @@ -465,6 +500,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.
Expand Down Expand Up @@ -506,13 +558,18 @@ 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, 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) {
// `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));
Expand All @@ -522,6 +579,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
Expand Down
30 changes: 30 additions & 0 deletions packages/cli/src/utils/flow-json-flag.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// 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 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 '../utils/flow-json-flag.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/);
});
});
19 changes: 19 additions & 0 deletions packages/cli/src/utils/flow-json-flag.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> | 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<string, unknown>;
}
Loading
Loading