diff --git a/.changeset/34776-publish-checks-build-probes.md b/.changeset/34776-publish-checks-build-probes.md new file mode 100644 index 00000000000..2d2191334b1 --- /dev/null +++ b/.changeset/34776-publish-checks-build-probes.md @@ -0,0 +1,28 @@ +--- +'@objectstack/lint': minor +'@objectstack/metadata-protocol': minor +'@objectstack/service-automation': minor +'@objectstack/spec': minor +--- + +feat(lint): five publish-time checks for metadata that passes the schema and does nothing at run time, and four build probes over what landed + +Clause-②: no (narrowing: four publish-time refusals of metadata the schema accepts today) +Metadata-protocol: narrowed +Skills-docs: follow-up #35245 + + + +Five authoring rules join the registry the runtime publish gate and `objectstack validate` / `lint` / `compile` run. Each finding names its fix. + +- `flow-node-type-no-executor` (error): a flow node whose `type` no executor in this deployment runs fails every run with `NO_EXECUTOR`. Judged only against the automation engine's SEALED node-type vocabulary, which the publish gate reads from the new `AutomationEngine.getSealedNodeTypeVocabulary()` (it answers `undefined` until `sealNodeTypeVocabulary()` ran at `kernel:bootstrapped`). The CLI does not know which plugins a deployment loads, so it judges nothing here. +- `flow-approval-decision-unrouted` (error): an `approval` node whose decision out-edges are not labelled exactly `approve` and `reject` runs every out-edge for a decision no label claims, so the approving and the rejecting branch both run. +- `flow-http-timeout-missing` (warning): an `http` node with no positive `config.timeoutMs` and no positive node-level `timeoutMs` waits on a slow upstream for as long as the connection stays open; the engine arms no default timer. A `durable: true` node, which does not wait on the endpoint, is not reported. Like every warning, it makes `os validate --strict` exit 1. +- `state-machine-no-initial-states` (error): an active `state_machine` validation without `initialStates` (or with an empty list) lets a record be created already in any state. Add `initialStates`. +- `action-no-object-binding` (error): a standalone action that declares `locations` but no `objectName` binds to no object, so its button never renders. Set `objectName`, or write `locations: []` for a headless action. + +What was accepted before and is refused at publish now: a flow with an unrouted approval decision or a node type the deployment cannot run, a state machine without `initialStates`, a placed action with no object. The fix for each is in the finding. + +Four post-publish build probes report, as warnings on the publish receipt, what the person will see: `widget_empty_result` (a dashboard card whose real query reads only zeros), `rollup_never_computed` (a roll-up blank on every parent that has children), `seed_reference_unresolved` (a sample record the seed loader landed whose reference names no row in the organization that record belongs to, so the reference leads nowhere) and `flow_connector_action_unresolved` (a `connector_action` step naming a connector or action this environment does not serve). Each carries its sentence for the person in every platform locale. `RunBuildProbesOptions` gains `automation`, `packageId` and `seedLanded`; the publish passes the automation engine's connector lookups, the publishing package and its `seedApplied.landed` ids. `ProbeEngine` gains an optional `getSchema`, which names the column a row's organization is stamped in; the roll-up and seed probes judge each row inside that organization. + +New exports: `@objectstack/lint` adds `validateFlowNodeExecutors`, `validateInertObjectDeclarations`, `validateActionObjectBinding`, their finding types, and the rule ids `FLOW_NODE_TYPE_NO_EXECUTOR`, `FLOW_APPROVAL_DECISION_UNROUTED`, `FLOW_HTTP_TIMEOUT_MISSING`, `STATE_MACHINE_NO_INITIAL_STATES`, `ACTION_NO_OBJECT_BINDING`; `@objectstack/metadata-protocol` adds the `ProbeAutomation` and `SeedLandedRows` types; `@objectstack/service-automation` adds `AutomationEngine.getSealedNodeTypeVocabulary()`. `@objectstack/spec` changes only descriptions: those of `RuntimeBuildIssueSchema`, and that of a state machine validation's `initialStates`. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index e21f6117ccf..24cc22d5abe 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -887,7 +887,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (70)... + → Running author-time rules (73)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 21163750710..1a9178bc5b7 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -866,7 +866,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (70)... + → Running author-time rules (73)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index b3cdd1858d9..e4543a7bfda 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -311,7 +311,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (70)... + → Running author-time rules (73)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index d918b8a95f6..f24938a4721 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -489,10 +489,10 @@ Canonical cross-paradigm action/node descriptor (ADR-0018) | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **layer** | `'runtime'` | ✅ | The ADR-0038 verification plane that found it. Always `runtime` on this report: these are the post-publish probes. | -| **severity** | `Enum<'error' \| 'warning'>` | ✅ | `error`: the published artifact is broken at runtime, or the check that judges it could not run (`object_field_ref_rule_failed`). `warning`: a dashboard widget was not probed, so nothing is known about it. Neither fails the publish. | +| **severity** | `Enum<'error' \| 'warning'>` | ✅ | `error`: the published artifact is broken at runtime, or the check that judges it could not run (`object_field_ref_rule_failed`). `warning`: a dashboard widget was not probed, so nothing is known about it (`widget_not_probed`, `probes_unavailable`); what landed reads in a way the person will notice although it may be the truth (`widget_empty_result`, `rollup_never_computed`); or what landed is wrong in a way that depends on data or on what the environment serves rather than on the artifact alone: a stored reference that names no row (`seed_reference_unresolved`), a flow step that fails on every run that reaches it until the connector it names is served (`flow_connector_action_unresolved`). Neither fails the publish. | | **artifact** | `{ type: string; name: string }` | ✅ | The published artifact whose runtime behaviour the finding is about. | -| **ref** | `{ type: string; name: string; member?: string }` | optional | What the probe exercised, when that is not the artifact itself: the object a seed loads into or a view reads, the dataset a widget is bound to. Absent when the finding is about the artifact as a whole. | -| **code** | `string` | ✅ | Stable machine id of the finding class, lowercase snake: a diagnostics code carried in a 200, not an ADR-0112 error code. The probes emit `seed_not_applied`, `view_read_failed`, `object_field_ref_unknown`, `object_field_ref_rule_failed`, `empty_query`, `widget_query_failed`, `widget_not_probed` and `probes_unavailable`. The list is the producer's and may grow: a consumer treats an id it does not know as any other finding. | +| **ref** | `{ type: string; name: string; member?: string }` | optional | What the probe exercised: the object a seed loads into or a view reads, the dataset a widget is bound to, the connector a flow step dispatches, or the published object itself when `member` names the field the finding is about (a roll-up). Absent when the finding is about the artifact as a whole. | +| **code** | `string` | ✅ | Stable machine id of the finding class, lowercase snake: a diagnostics code carried in a 200, not an ADR-0112 error code. The probes emit `seed_not_applied`, `view_read_failed`, `object_field_ref_unknown`, `object_field_ref_rule_failed`, `empty_query`, `widget_query_failed`, `widget_not_probed`, `probes_unavailable`, `widget_empty_result`, `rollup_never_computed`, `seed_reference_unresolved` and `flow_connector_action_unresolved`. The list is the producer's and may grow: a consumer treats an id it does not know as any other finding. | | **message** | `string` | ✅ | What is wrong, written for the AGENT that built the app (ADR-0038): English, naming the exact artifact and member by machine name. Not the sentence for the person who published; that is `userMessage`. | | **fix** | `string` | optional | How to repair it, written for the same agent. Absent when the probe has no remedy to name. | | **userMessage** | `string` | optional | The finding's sentence for the PERSON who published, composed by its producer in the request's locale (else the workspace default locale, else `en`) — the same field name and producer-marked meaning as `RuntimeAuthoringIssueSchema.userMessage` and `ApiErrorSchema.userMessage`. It names an artifact by its label where the probe can read one, else by its machine name; an object the publishing caller was refused, or whose read access could not be decided, by the machine name the refusal carries, its label unread. Present when the producer authors a user sentence for this `code`, which the probes do for every code they emit; absent, a consumer shows its own generic sentence. Consumers render it as received and keep no per-code translation table; `code` stays the stable id and `message` / `fix` stay the agent-facing text. | @@ -3024,10 +3024,10 @@ Answer to a device registration: the device id the client keeps | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **layer** | `'runtime'` | ✅ | The ADR-0038 verification plane that found it. Always `runtime` on this report: these are the post-publish probes. | -| **severity** | `Enum<'error' \| 'warning'>` | ✅ | `error`: the published artifact is broken at runtime, or the check that judges it could not run (`object_field_ref_rule_failed`). `warning`: a dashboard widget was not probed, so nothing is known about it. Neither fails the publish. | +| **severity** | `Enum<'error' \| 'warning'>` | ✅ | `error`: the published artifact is broken at runtime, or the check that judges it could not run (`object_field_ref_rule_failed`). `warning`: a dashboard widget was not probed, so nothing is known about it (`widget_not_probed`, `probes_unavailable`); what landed reads in a way the person will notice although it may be the truth (`widget_empty_result`, `rollup_never_computed`); or what landed is wrong in a way that depends on data or on what the environment serves rather than on the artifact alone: a stored reference that names no row (`seed_reference_unresolved`), a flow step that fails on every run that reaches it until the connector it names is served (`flow_connector_action_unresolved`). Neither fails the publish. | | **artifact** | `{ type: string; name: string }` | ✅ | The published artifact whose runtime behaviour the finding is about. | -| **ref** | `{ type: string; name: string; member?: string }` | optional | What the probe exercised, when that is not the artifact itself: the object a seed loads into or a view reads, the dataset a widget is bound to. Absent when the finding is about the artifact as a whole. | -| **code** | `string` | ✅ | Stable machine id of the finding class, lowercase snake: a diagnostics code carried in a 200, not an ADR-0112 error code. The probes emit `seed_not_applied`, `view_read_failed`, `object_field_ref_unknown`, `object_field_ref_rule_failed`, `empty_query`, `widget_query_failed`, `widget_not_probed` and `probes_unavailable`. The list is the producer's and may grow: a consumer treats an id it does not know as any other finding. | +| **ref** | `{ type: string; name: string; member?: string }` | optional | What the probe exercised: the object a seed loads into or a view reads, the dataset a widget is bound to, the connector a flow step dispatches, or the published object itself when `member` names the field the finding is about (a roll-up). Absent when the finding is about the artifact as a whole. | +| **code** | `string` | ✅ | Stable machine id of the finding class, lowercase snake: a diagnostics code carried in a 200, not an ADR-0112 error code. The probes emit `seed_not_applied`, `view_read_failed`, `object_field_ref_unknown`, `object_field_ref_rule_failed`, `empty_query`, `widget_query_failed`, `widget_not_probed`, `probes_unavailable`, `widget_empty_result`, `rollup_never_computed`, `seed_reference_unresolved` and `flow_connector_action_unresolved`. The list is the producer's and may grow: a consumer treats an id it does not know as any other finding. | | **message** | `string` | ✅ | What is wrong, written for the AGENT that built the app (ADR-0038): English, naming the exact artifact and member by machine name. Not the sentence for the person who published; that is `userMessage`. | | **fix** | `string` | optional | How to repair it, written for the same agent. Absent when the probe has no remedy to name. | | **userMessage** | `string` | optional | The finding's sentence for the PERSON who published, composed by its producer in the request's locale (else the workspace default locale, else `en`) — the same field name and producer-marked meaning as `RuntimeAuthoringIssueSchema.userMessage` and `ApiErrorSchema.userMessage`. It names an artifact by its label where the probe can read one, else by its machine name; an object the publishing caller was refused, or whose read access could not be decided, by the machine name the refusal carries, its label unread. Present when the producer authors a user sentence for this `code`, which the probes do for every code they emit; absent, a consumer shows its own generic sentence. Consumers render it as received and keep no per-code translation table; `code` stays the stable id and `message` / `fix` stay the agent-facing text. | @@ -3036,16 +3036,16 @@ Answer to a device registration: the device id the client keeps | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | Metadata type of the artifact (`seed`, `view`, `object`, `dashboard`). | +| **type** | `string` | ✅ | Metadata type of the artifact (`seed`, `view`, `object`, `dashboard`, `flow`). | | **name** | `string` | ✅ | Item name of the artifact. On `probes_unavailable` it is the name of every dashboard whose widgets went unprobed, joined by `, `. | ### Nested Shape: `RuntimeBuildIssue.ref` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | Metadata type of what was exercised (`object`, `dataset`). | +| **type** | `string` | ✅ | Metadata type of what was exercised (`object`, `dataset`, `connector`). | | **name** | `string` | ✅ | Its item name. | -| **member** | `string` | optional | The dashboard widget the finding is about, when the finding is about one widget: its `id`, else its `title` as a string, else `?`. | +| **member** | `string` | optional | The part of it the finding is about: the dashboard widget, when the finding is about one widget (its `id`, else its `title` as a string, else `?`); the field of an object (a roll-up, a reference column); the action of a connector. | --- diff --git a/content/docs/references/data/validation.mdx b/content/docs/references/data/validation.mdx index f4f6c0a0bfb..4fcf686bbd7 100644 --- a/content/docs/references/data/validation.mdx +++ b/content/docs/references/data/validation.mdx @@ -192,7 +192,7 @@ const result = ConditionalValidationSchema.parse(data); | **type** | `'state_machine'` | ✅ | | | **field** | `string` | ✅ | State field (e.g. status) | | **transitions** | `Record` | ✅ | Map of `{ OldState: [AllowedNewStates] }` | -| **initialStates** | `string[]` | optional | States a record may be CREATED in. When set, an INSERT whose state field carries a value outside this list is rejected (server-enforced) — the FSM entry point. `transitions` only governs UPDATE, and a `select` field permits ANY declared option as an initial value, so without this a record could be born mid-flow (e.g. created already `approved`). Omit to keep the legacy behavior (no initial-state check on insert). | +| **initialStates** | `string[]` | optional | States a record may be CREATED in. When set, an INSERT whose state field carries a value outside this list is rejected (server-enforced) — the FSM entry point. `transitions` only governs UPDATE, and a `select` field permits ANY declared option as an initial value, so without this a record could be born mid-flow (e.g. created already `approved`). Omitted or empty, insert is not checked; the author-time rule `state-machine-no-initial-states` refuses an active machine declared that way at publish and in `os validate`. | ### Nested Shape: `ConditionalValidation.then[type='format']` @@ -313,7 +313,7 @@ const result = ConditionalValidationSchema.parse(data); | **type** | `'state_machine'` | ✅ | | | **field** | `string` | ✅ | State field (e.g. status) | | **transitions** | `Record` | ✅ | Map of `{ OldState: [AllowedNewStates] }` | -| **initialStates** | `string[]` | optional | States a record may be CREATED in. When set, an INSERT whose state field carries a value outside this list is rejected (server-enforced) — the FSM entry point. `transitions` only governs UPDATE, and a `select` field permits ANY declared option as an initial value, so without this a record could be born mid-flow (e.g. created already `approved`). Omit to keep the legacy behavior (no initial-state check on insert). | +| **initialStates** | `string[]` | optional | States a record may be CREATED in. When set, an INSERT whose state field carries a value outside this list is rejected (server-enforced) — the FSM entry point. `transitions` only governs UPDATE, and a `select` field permits ANY declared option as an initial value, so without this a record could be born mid-flow (e.g. created already `approved`). Omitted or empty, insert is not checked; the author-time rule `state-machine-no-initial-states` refuses an active machine declared that way at publish and in `os validate`. | ### Nested Shape: `ConditionalValidation.otherwise[type='format']` @@ -532,7 +532,7 @@ const result = ConditionalValidationSchema.parse(data); | **type** | `'state_machine'` | ✅ | | | **field** | `string` | ✅ | State field (e.g. status) | | **transitions** | `Record` | ✅ | Map of `{ OldState: [AllowedNewStates] }` | -| **initialStates** | `string[]` | optional | States a record may be CREATED in. When set, an INSERT whose state field carries a value outside this list is rejected (server-enforced) — the FSM entry point. `transitions` only governs UPDATE, and a `select` field permits ANY declared option as an initial value, so without this a record could be born mid-flow (e.g. created already `approved`). Omit to keep the legacy behavior (no initial-state check on insert). | +| **initialStates** | `string[]` | optional | States a record may be CREATED in. When set, an INSERT whose state field carries a value outside this list is rejected (server-enforced) — the FSM entry point. `transitions` only governs UPDATE, and a `select` field permits ANY declared option as an initial value, so without this a record could be born mid-flow (e.g. created already `approved`). Omitted or empty, insert is not checked; the author-time rule `state-machine-no-initial-states` refuses an active machine declared that way at publish and in `os validate`. | --- @@ -599,7 +599,7 @@ This schema accepts one of the following structures: | **type** | `'state_machine'` | ✅ | | | **field** | `string` | ✅ | State field (e.g. status) | | **transitions** | `Record` | ✅ | Map of `{ OldState: [AllowedNewStates] }` | -| **initialStates** | `string[]` | optional | States a record may be CREATED in. When set, an INSERT whose state field carries a value outside this list is rejected (server-enforced) — the FSM entry point. `transitions` only governs UPDATE, and a `select` field permits ANY declared option as an initial value, so without this a record could be born mid-flow (e.g. created already `approved`). Omit to keep the legacy behavior (no initial-state check on insert). | +| **initialStates** | `string[]` | optional | States a record may be CREATED in. When set, an INSERT whose state field carries a value outside this list is rejected (server-enforced) — the FSM entry point. `transitions` only governs UPDATE, and a `select` field permits ANY declared option as an initial value, so without this a record could be born mid-flow (e.g. created already `approved`). Omitted or empty, insert is not checked; the author-time rule `state-machine-no-initial-states` refuses an active machine declared that way at publish and in `os validate`. | --- diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index b52c38b01c8..4da1da497c2 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (70)... + → Running author-time rules (73)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/examples/app-crm/src/objects/lead.object.ts b/examples/app-crm/src/objects/lead.object.ts index 4653478bbb7..560ac89d0a2 100644 --- a/examples/app-crm/src/objects/lead.object.ts +++ b/examples/app-crm/src/objects/lead.object.ts @@ -112,6 +112,9 @@ export const Lead = ObjectSchema.create({ description: 'Enforces valid status progression for leads.', field: 'status', message: 'Invalid lead status transition.', + // A lead is created `new` (the field's default and the machine's only + // root); every later status is reached through `transitions`. + initialStates: ['new'], transitions: { new: ['contacted', 'qualifying', 'disqualified'], contacted: ['qualifying', 'disqualified'], diff --git a/examples/app-crm/src/objects/opportunity.object.ts b/examples/app-crm/src/objects/opportunity.object.ts index 1973d5efd4e..398e39b81f4 100644 --- a/examples/app-crm/src/objects/opportunity.object.ts +++ b/examples/app-crm/src/objects/opportunity.object.ts @@ -138,6 +138,11 @@ export const Opportunity = ObjectSchema.create({ description: 'Opportunities should progress through stages in order.', field: 'stage', message: 'Invalid stage transition.', + // A deal may be recorded at any stage, an already-won or already-lost + // one included: `OpportunityStageHook` sets the probability on INSERT + // for exactly that case (test/opportunity-stage-hook.test.ts). The + // machine guards how a deal MOVES, not where it is first entered. + initialStates: ['prospecting', 'qualification', 'proposal', 'closed_won', 'closed_lost'], transitions: { prospecting: ['qualification', 'closed_lost'], qualification:['proposal', 'closed_lost'], diff --git a/examples/app-showcase/src/automation/flows/exchange-rate-sync.flow.ts b/examples/app-showcase/src/automation/flows/exchange-rate-sync.flow.ts index 56fd5b47a93..2995c7fcb6f 100644 --- a/examples/app-showcase/src/automation/flows/exchange-rate-sync.flow.ts +++ b/examples/app-showcase/src/automation/flows/exchange-rate-sync.flow.ts @@ -97,6 +97,7 @@ export const ExchangeRateSyncFlow = defineFlow({ config: { url: '{{ rate_feed_url }}', method: 'GET', + timeoutMs: 10000, }, }, { diff --git a/examples/app-showcase/src/automation/flows/index.ts b/examples/app-showcase/src/automation/flows/index.ts index 42bda3d105a..a2407f05323 100644 --- a/examples/app-showcase/src/automation/flows/index.ts +++ b/examples/app-showcase/src/automation/flows/index.ts @@ -1094,6 +1094,9 @@ export const FanOutNotifyFlow = defineFlow({ // `TaskCompletedSlackFlow` uses. url: 'https://hooks.slack.com/services/T000/B000/XXXX', method: 'POST', + // The node arms no timer without one: an endpoint that never + // answers would hold the run open. + timeoutMs: 10000, // The body is a value slot (#19939): one CEL envelope builds // the whole payload. `title` is a required field, so it is // read unguarded. @@ -1281,6 +1284,7 @@ export const ResilientSyncFlow = defineFlow({ config: { url: 'https://api.example.com/v1/tasks', method: 'POST', + timeoutMs: 10000, // CEL holds a map's values to one type: the literal beside the // field reads is wrapped in `dyn(…)`. body: { dialect: 'cel', source: "{'id': taskId, 'title': title, 'status': dyn('done')}" }, @@ -1523,7 +1527,7 @@ export const ProjectEscalationFlow = defineFlow({ // the request cannot be queued, and the catch region reports that. errorVariable: '$error', try: { - nodes: [{ id: 'push', type: 'http', label: 'POST incident', config: { url: 'https://api.example.com/v1/incidents', method: 'POST', durable: true, body: { dialect: 'cel', source: "{'project': record.id, 'severity': dyn('critical')}" } } }], + nodes: [{ id: 'push', type: 'http', label: 'POST incident', config: { url: 'https://api.example.com/v1/incidents', method: 'POST', durable: true, timeoutMs: 10000, body: { dialect: 'cel', source: "{'project': record.id, 'severity': dyn('critical')}" } } }], edges: [], }, catch: { diff --git a/examples/app-showcase/src/data/objects/account.object.ts b/examples/app-showcase/src/data/objects/account.object.ts index db6c9249cbd..f6fde33e0b9 100644 --- a/examples/app-showcase/src/data/objects/account.object.ts +++ b/examples/app-showcase/src/data/objects/account.object.ts @@ -141,6 +141,10 @@ export const Account = ObjectSchema.create({ field: 'status', // Transitions are validated on update; insert sets the initial state. events: ['update'] as const, + // The entry state: `prospect`, the field's default and the machine's + // root. This machine runs on updates only, so the server does not check + // it on create; it states the entry the lifecycle assumes. + initialStates: ['prospect'], message: 'Invalid account lifecycle transition.', transitions: { prospect: ['active', 'churned'], diff --git a/examples/app-showcase/src/data/objects/project.object.ts b/examples/app-showcase/src/data/objects/project.object.ts index 9964f9805f6..a6bf34eb424 100644 --- a/examples/app-showcase/src/data/objects/project.object.ts +++ b/examples/app-showcase/src/data/objects/project.object.ts @@ -191,6 +191,9 @@ export const Project = ObjectSchema.create({ description: 'Health should change one step at a time; skips are warned, not blocked.', field: 'health', events: ['update'] as const, + // A project starts `green` (the field's default). Updates only, so this + // states the entry rather than checking it on create. + initialStates: ['green'], severity: 'warning' as const, message: 'Health changed by more than one step — confirm this is intentional.', transitions: { diff --git a/examples/app-showcase/src/data/objects/task.object.ts b/examples/app-showcase/src/data/objects/task.object.ts index 760dfedcbe5..e45404bcbef 100644 --- a/examples/app-showcase/src/data/objects/task.object.ts +++ b/examples/app-showcase/src/data/objects/task.object.ts @@ -115,6 +115,10 @@ export const Task = ObjectSchema.create({ // — an authored message is emitted verbatim unless the bundle carries // that key, and the bundle wins once it does (#14518). message: 'Invalid task status transition.', + // A task is created on the board's first two columns: `backlog` (the + // default) or `todo`. Updates only, so this states the entry rather + // than checking it on create. + initialStates: ['backlog', 'todo'], transitions: { backlog: ['todo'], todo: ['in_progress', 'backlog'], diff --git a/packages/cli/test/stack-conversion-record-door.test.ts b/packages/cli/test/stack-conversion-record-door.test.ts index 65e0fb9bbd8..9f494a1f7d3 100644 --- a/packages/cli/test/stack-conversion-record-door.test.ts +++ b/packages/cli/test/stack-conversion-record-door.test.ts @@ -160,7 +160,7 @@ const flow = (ns: string, nodeType: NodeType) => `{ type: 'autolaunched', nodes: [ { id: 'start', type: 'start', label: 'Start' }, - { id: 'call', type: '${nodeType}', label: 'Call', config: { url: 'https://example.com/hook' } }, + { id: 'call', type: '${nodeType}', label: 'Call', timeoutMs: 10000, config: { url: 'https://example.com/hook' } }, { id: 'end', type: 'end', label: 'End' }, ], edges: [{ id: 'e1', source: 'start', target: 'call' }, { id: 'e2', source: 'call', target: 'end' }], diff --git a/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index b9b2a7f381e..d8ecae0ef8b 100644 --- a/packages/core/src/security/second-object-read-exposure.pin.test.ts +++ b/packages/core/src/security/second-object-read-exposure.pin.test.ts @@ -282,6 +282,18 @@ const CALLERS: Record = { kind: 'not-a-served-read', reason: 'authoring-time static analysis of metadata; reads no record', }, + // [#35146] The post-publish build probes' two landed-data checks. + 'packages/metadata-protocol/src/build-probes.ts': { + kind: 'not-a-served-read', + reason: + "the post-publish build probes (`runBuildProbes`) name the object a reference column or a roll-up's foreign key " + + "points at, under the system identity kept inside an organization the way `inspectDanglingReferences` keeps its " + + "probe (#19837: the publishing organization, else the referencing row's own), only to report whether a landed " + + "reference resolves (`seed_reference_unresolved`, the target read projected to `id`) or a parent's roll-up was " + + "ever computed (`rollup_never_computed`, projected to `id` and the roll-up field); the finding carries counts " + + "and the referencing column's own values, never a field of the target, and is returned to the publisher on the " + + 'publish receipt, not served to a caller', + }, 'packages/metadata-protocol/src/seed-loader.ts': { kind: 'not-a-served-read', reason: "resolves a seed's references at install, under the system identity; serves nothing to a caller", diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index b5e747f4118..4e48111b30e 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -151,6 +151,9 @@ import { validateRuleCompilability } from './validate-rule-compilability.js'; import { validateActionBodyCompiles } from './validate-action-body-compiles.js'; import { validateRuleSchemaFormats } from './validate-rule-schema-formats.js'; import { validateActionLocations } from './validate-action-locations.js'; +import { validateActionObjectBinding } from './validate-action-object-binding.js'; +import { validateFlowNodeExecutors } from './validate-flow-node-executors.js'; +import { validateInertObjectDeclarations } from './validate-inert-object-declarations.js'; import { lintFlowPatterns } from './lint-flow-patterns.js'; import { lintFlowCredentialLiterals } from './lint-flow-credential-literals.js'; import { validateFlowRegionShape } from './validate-flow-region-shape.js'; @@ -490,6 +493,18 @@ export interface AuthoringRuleContext { * nobody owns). */ membershipKeyOwners?: MembershipKeyOwners; + /** + * The node types the deployment's automation engine runs, handed in only + * once the host has declared that vocabulary CLOSED + * (`AutomationEngine.getSealedNodeTypeVocabulary()`, answered after + * `sealNodeTypeVocabulary()` at `kernel:bootstrapped`). Set only by the + * runtime publish gate, and only on a sealed engine; ABSENT on the three CLI + * commands, whose stack does not say which plugins the deployment loads. + * Read by `validateFlowNodeExecutors` only, which judges nothing without it: + * a verdict drawn from a vocabulary still filling at boot is one the boot can + * contradict (AGENTS.md "Startup registry reads"). + */ + flowNodeTypeVocabulary?: ReadonlySet; } export interface AuthoringRule { @@ -1839,6 +1854,22 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, run: (stack) => validateActionLocations(stack), }, + // A standalone action that declares a location but no `objectName` binds to + // no object, so the button it declares never renders (every location is an + // object's surface). The handler still runs: an object-less action answers + // every object's action route (`resolveActionByPackage` falls through to the + // global scope). Gating: the placement the declaration names can never work. On the runtime door for an + // `action` write, whose snapshot carries the written action itself. + { + name: 'validateActionObjectBinding', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-action-object-binding.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['action'], + run: (stack) => validateActionObjectBinding(stack), + }, // [ADR-0142 D5] An assignment rule naming a user id carries one // organization's data in package metadata, and one targeting a declared queue // with no member parks every row it matches. Advisory: the engine never @@ -1872,6 +1903,20 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, run: (stack) => validateSeedStateMachine(stack), }, + // An active state machine with no (or an empty) `initialStates`: a record + // can be born in any state. Gating: the declaration works against its author + // on every create. Reads the object's own body alone, so it judges an `object` write + // at the runtime door exactly as on the CLI. + { + name: 'validateInertObjectDeclarations', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-inert-object-declarations.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['object'], + run: (stack) => validateInertObjectDeclarations(stack), + }, // ADR-0089 D3b — a mis-layered binding root, plus (#6128) the bare-identifier // gate and (#6253) the syntax gate. This entry used to read "pre-parse: the // schema folds `visibleOn`/`visibility` into `visibleWhen` during parse, so @@ -2060,7 +2105,9 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // `error` gates. Three do today: `flow-runas-unscoped` (#3760 — metadata the // runtime REFUSES to execute), plus `flow-branch-label-unmatched` and // `flow-default-edge-with-condition` (#4414 — a declaration that is inert, so - // the route silently differs from what the author wrote). The bar for + // the route silently differs from what the author wrote), and others since, + // `flow-approval-decision-unrouted` among them (an approval whose edges do not + // claim both decisions runs every branch on either). The bar for // promoting one is stated at the top of `lint-flow-patterns.ts`. { name: 'lintFlowPatterns', @@ -2090,6 +2137,21 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ ...(f.userTextParams !== undefined ? { userTextParams: f.userTextParams } : {}), })), }, + // A flow node whose `type` no executor runs fails every run with + // NO_EXECUTOR. Judged only against the SEALED vocabulary the runtime gate + // hands in (`AuthoringRuleContext.flowNodeTypeVocabulary`); the CLI commands + // have none, so there the entry runs and judges nothing — the vocabulary is + // the deployment's, not the stack's. + { + name: 'validateFlowNodeExecutors', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-flow-node-executors.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['flow'], + run: (stack, ctx) => validateFlowNodeExecutors(stack, ctx.flowNodeTypeVocabulary), + }, // A credential typed as a LITERAL into a flow position every flow reader is // served — an `http` node's `headers` or `url` query, a node's // `connectorConfig.input` — named at every authoring door, with the diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index e99997db292..186a386d1b8 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -675,6 +675,15 @@ export type { ActionNameRefFinding, ActionNameRefSeverity } from './validate-act export { validateActionLocations, ACTION_NO_PLACEMENT } from './validate-action-locations.js'; export type { ActionLocationsFinding, ActionLocationsSeverity } from './validate-action-locations.js'; +export { validateActionObjectBinding, ACTION_NO_OBJECT_BINDING } from './validate-action-object-binding.js'; +export type { ActionObjectBindingFinding } from './validate-action-object-binding.js'; +export { validateFlowNodeExecutors, FLOW_NODE_TYPE_NO_EXECUTOR } from './validate-flow-node-executors.js'; +export type { FlowNodeExecutorFinding } from './validate-flow-node-executors.js'; +export { + validateInertObjectDeclarations, + STATE_MACHINE_NO_INITIAL_STATES, +} from './validate-inert-object-declarations.js'; +export type { InertObjectDeclarationFinding } from './validate-inert-object-declarations.js'; export { validatePageFieldBindings, @@ -1106,6 +1115,8 @@ export { FLOW_TRY_CATCH_WITHOUT_CATCH, FLOW_DECISION_MODE_INVALID, FLOW_DECISION_INCLUSIVE_OVERLAP, + FLOW_APPROVAL_DECISION_UNROUTED, + FLOW_HTTP_TIMEOUT_MISSING, } from './lint-flow-patterns.js'; // A credential typed as a literal into a served flow position — the advisory, diff --git a/packages/lint/src/lint-flow-patterns.test.ts b/packages/lint/src/lint-flow-patterns.test.ts index 031cd2624dc..f90504fc0a2 100644 --- a/packages/lint/src/lint-flow-patterns.test.ts +++ b/packages/lint/src/lint-flow-patterns.test.ts @@ -42,6 +42,8 @@ import { FLOW_TRY_CATCH_WITHOUT_CATCH, FLOW_DECISION_MODE_INVALID, FLOW_DECISION_INCLUSIVE_OVERLAP, + FLOW_APPROVAL_DECISION_UNROUTED, + FLOW_HTTP_TIMEOUT_MISSING, } from './lint-flow-patterns.js'; // [#17495] Cross-site pin only — the re-judged `flow-inert-node-condition` // case below. This family's own coverage is unaffected by it; @@ -903,7 +905,8 @@ function edgeFlow(edge: Record, sourceType = 'http') { type: 'autolaunched', nodes: [ { id: 'start', type: 'start', config: {} }, - { id: 'op', type: sourceType, config: { url: 'https://x.test' } }, + // A timeout, so the http source is judged only on its edges here. + { id: 'op', type: sourceType, config: { url: 'https://x.test', timeoutMs: 10000 } }, { id: 'handler', type: 'notify', config: { topic: 'x' } }, { id: 'end', type: 'end' }, ], @@ -2404,7 +2407,7 @@ describe('per-iteration containment (#13681 / #14394)', () => { name: 'charge', label: 'Charge', type: 'autolaunched', nodes: [ { id: 'start', type: 'start', label: 'Start', config: { triggerType: 'api' } }, - { id: 'guard', type: 'try_catch', label: 'Guarded', config: { try: { nodes: [{ id: 'pay', type: 'http', label: 'Pay', config: { url: 'https://example.test' } }], edges: [] } } }, + { id: 'guard', type: 'try_catch', label: 'Guarded', config: { try: { nodes: [{ id: 'pay', type: 'http', label: 'Pay', config: { url: 'https://example.test', timeoutMs: 10000 } }], edges: [] } } }, ], edges: [{ id: 'e1', source: 'start', target: 'guard' }], }], @@ -4141,3 +4144,95 @@ describe('lintFlowPatterns — a retried inline outbound call in an after-save f expect(explainRule(FLOW_AFTER_SAVE_INLINE_RETRY)).toBeDefined(); }); }); + +describe('flow-approval-decision-unrouted — an approval decision continues only down an exact `approve` / `reject` edge', () => { + const approvalFlow = (edges: Array>) => ({ + flows: [{ + name: 'expense_signoff', + label: 'Expense sign-off', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'signoff', type: 'approval', label: 'Sign-off', config: { approvers: [{ type: 'user', value: 'u1' }] } }, + { id: 'paid', type: 'update_record', label: 'Mark paid', config: { objectName: 'expense', filter: { id: 'x' }, fields: { status: 'paid' } } }, + { id: 'refused', type: 'update_record', label: 'Mark refused', config: { objectName: 'expense', filter: { id: 'x' }, fields: { status: 'refused' } } }, + ], + edges: [{ id: 'e0', source: 'start', target: 'signoff' }, ...edges], + }], + }); + const unrouted = (stack: Record) => + lintFlowPatterns(stack).filter((f) => f.rule === FLOW_APPROVAL_DECISION_UNROUTED); + + it('refuses edges labelled in other words, naming both missing decisions and the labels written', () => { + const findings = unrouted(approvalFlow([ + { id: 'e1', source: 'signoff', target: 'paid', label: 'Approved' }, + { id: 'e2', source: 'signoff', target: 'refused', label: '驳回' }, + ])); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ severity: 'error', path: 'flows[0].nodes[1]' }); + expect(findings[0].message).toContain("'approve' or 'reject'"); + expect(findings[0].message).toContain("'Approved', '驳回'"); + }); + + it('refuses an approval that claims one decision and not the other', () => { + const findings = unrouted(approvalFlow([{ id: 'e1', source: 'signoff', target: 'paid', label: 'approve' }])); + expect(findings.map((f) => f.message.includes("'reject'"))).toEqual([true]); + }); + + it('is silent when both decisions are claimed, beside a fault edge, and on an approval with no out-edge', () => { + expect(unrouted(approvalFlow([ + { id: 'e1', source: 'signoff', target: 'paid', label: 'approve' }, + { id: 'e2', source: 'signoff', target: 'refused', label: 'reject' }, + { id: 'e3', source: 'signoff', target: 'refused', type: 'fault' }, + ]))).toEqual([]); + expect(unrouted(approvalFlow([]))).toEqual([]); + }); +}); + +describe('flow-http-timeout-missing — an http node without a timeout of its own', () => { + const httpFlow = (config: Record, node: Record = {}) => ({ + flows: [{ + name: 'push_order', + label: 'Push order', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'call', type: 'http', label: 'Call ERP', config: { url: 'https://erp.example.com/orders', ...config }, ...node }, + ], + edges: [{ id: 'e0', source: 'start', target: 'call' }], + }], + }); + const missing = (stack: Record) => + lintFlowPatterns(stack).filter((f) => f.rule === FLOW_HTTP_TIMEOUT_MISSING); + + it('warns on an http node with no `config.timeoutMs`, at its config', () => { + const findings = missing(httpFlow({})); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ severity: 'warning', path: 'flows[0].nodes[1].config' }); + expect(findings[0].hint).toContain('timeoutMs'); + }); + + it('is silent once the node sets one', () => { + expect(missing(httpFlow({ timeoutMs: 10000 }))).toEqual([]); + }); + + it('is silent on a node-level `timeoutMs`: the engine races the node against it', () => { + expect(missing(httpFlow({}, { timeoutMs: 10000 }))).toEqual([]); + }); + + it('reads `config.timeoutMs: 0` (and a node-level 0) as no timer: neither arms one', () => { + const findings = missing(httpFlow({ timeoutMs: 0 }, { timeoutMs: 0 })); + expect(findings).toHaveLength(1); + expect(findings[0].message).toContain('arms no timer'); + }); + + it('names a negative `config.timeoutMs` as the value it is, which arms no timer', () => { + const findings = missing(httpFlow({ timeoutMs: -5 })); + expect(findings).toHaveLength(1); + expect(findings[0].message).toContain('`config.timeoutMs: -5`, which arms no timer'); + }); + + it('is silent on a `durable: true` node: the run does not wait on the endpoint', () => { + expect(missing(httpFlow({ durable: true, method: 'POST' }))).toEqual([]); + }); +}); diff --git a/packages/lint/src/lint-flow-patterns.ts b/packages/lint/src/lint-flow-patterns.ts index a6f9efc50e0..6f3919da016 100644 --- a/packages/lint/src/lint-flow-patterns.ts +++ b/packages/lint/src/lint-flow-patterns.ts @@ -377,6 +377,19 @@ export const FLOW_LOOP_BODY_UNCONTAINED = 'flow-loop-body-uncontained'; * See {@link scanTryCatchWithoutCatch}. */ export const FLOW_TRY_CATCH_WITHOUT_CATCH = 'flow-try-catch-without-catch'; +/** + * An `approval` node whose out-edges do not claim both decisions. `error`: the + * engine routes the decision by out-edge `label`, matched exactly, and a + * decision no edge claims falls back to EVERY out-edge. See + * {@link scanApprovalDecisionEdges}. + */ +export const FLOW_APPROVAL_DECISION_UNROUTED = 'flow-approval-decision-unrouted'; +/** + * An `http` node with no timer: no positive `config.timeoutMs` and no positive + * node-level `timeoutMs`. `warning`: the run is held, not lost. See + * {@link scanHttpTimeouts}. + */ +export const FLOW_HTTP_TIMEOUT_MISSING = 'flow-http-timeout-missing'; /** * Node types that ship in the box. `config.condition` is only ever READ on the @@ -1822,6 +1835,88 @@ function scanBulkUpdatesMovingStoredInputs( } } +/** + * An approval decision continues ONLY down an out-edge whose `label` is exactly + * `approve` or `reject` (`APPROVAL_BRANCH_LABELS`, `@objectstack/spec/automation`): + * the engine narrows the out-edges to that label (`traverseNext`), and a label no + * edge carries falls back to every out-edge. So an approval whose edges are + * labelled `Approved` / `通过`, or that claims one decision and not the other, + * publishes clean and then runs the approving AND the rejecting branch on the + * same decision. An approval with no out-edge at all ends the flow on either + * decision and is not reported; a `fault` edge routes failures, not decisions, + * and is not counted. + */ +function scanApprovalDecisionEdges( + at: string, + nodes: AnyRec[], + edges: AnyRec[], + findings: FlowLintFinding[], + sites?: FlowNodeSites, +): void { + for (const node of nodes) { + if (node.type !== APPROVAL_NODE_TYPE || typeof node.id !== 'string') continue; + const outs = edges.filter((e) => e.source === node.id && e.type !== 'fault'); + if (outs.length === 0) continue; + const labels = new Set(outs.map((e) => (typeof e.label === 'string' ? e.label : ''))); + const missing = (['approve', 'reject'] as const).filter((d) => !labels.has(d)); + if (missing.length === 0) continue; + const written = [...labels].map((l) => (l ? `'${l}'` : '(none)')).join(', '); + findings.push({ + severity: 'error', + where: `${at} · approval '${node.id}'`, + ...(sites?.nodes.get(node) ? { path: sites.nodes.get(node)!.path } : {}), + message: + `approval '${node.id}' has no out-edge labelled ${missing.map((d) => `'${d}'`).join(' or ')} ` + + `(its out-edge labels: ${written}). The decision is routed by an exact edge label, and a decision no ` + + 'edge claims runs EVERY out-edge — approving and rejecting branches alike.', + hint: + "Label the out-edge the approved request takes `label: 'approve'` and the rejected one " + + "`label: 'reject'`, exactly as written.", + rule: FLOW_APPROVAL_DECISION_UNROUTED, + }); + } +} + +/** + * An `http` node with no timer at all: the executor arms one only when + * `config.timeoutMs` is a positive number (`timeoutMs ? setTimeout : undefined` + * in `service-automation` `builtin/http-nodes.ts`, so `0` arms none), and the + * engine races a node against its node-level `timeoutMs` only when that is + * positive (`dag-traversal.ts`). With neither, an endpoint that never answers + * holds the run — and a record-triggered run holds the save that started it — + * for as long as the transport waits. A warning, not an error: the run is + * held, not lost. + * + * A `durable: true` node is not reported: it enqueues onto the HTTP outbox and + * returns, and on the save path its no-outbox fallback is sent in the + * background, so the run does not wait on the endpoint. Its one waiting arm — + * no outbox wired, off the save path — is a deployment fact this lint cannot + * see. + */ +function scanHttpTimeouts(at: string, nodes: AnyRec[], findings: FlowLintFinding[], sites?: FlowNodeSites): void { + const armed = (v: unknown) => typeof v === 'number' && v > 0; + for (const node of nodes) { + if (node.type !== 'http') continue; + const cfg = (node.config ?? {}) as AnyRec; + if (armed(cfg.timeoutMs) || armed(node.timeoutMs) || cfg.durable === true) continue; + const nodeId = typeof node.id === 'string' ? node.id : 'http'; + // A number here is not positive (`armed` said so): it arms no timer. + const what = typeof cfg.timeoutMs === 'number' + ? `sets \`config.timeoutMs: ${cfg.timeoutMs}\`, which arms no timer` + : 'sets no `config.timeoutMs`'; + findings.push({ + severity: 'warning', + where: `${at} · node '${nodeId}' (http)`, + ...(sites?.nodes.get(node) ? { path: `${sites.nodes.get(node)!.path}.config` } : {}), + message: + `http node '${nodeId}' ${what} and no node-level \`timeoutMs\`, so the call has no timeout: an endpoint ` + + 'that never answers holds the run, and a record-triggered run holds the save that started it.', + hint: 'Set `config.timeoutMs` to a positive number of milliseconds, e.g. `timeoutMs: 10000`.', + rule: FLOW_HTTP_TIMEOUT_MISSING, + }); + } +} + function scanApprovalReviseLoops( at: string, nodes: AnyRec[], @@ -2632,6 +2727,12 @@ export function lintFlowPatterns(stack: AnyRec): FlowLintFinding[] { // (c) ADR-0044 — approval send-back-for-revision loop footguns. scanApprovalReviseLoops(at, graphNodes, graphEdges, findings); + // (c') An approval whose out-edges do not claim both decisions runs every + // branch on either decision; an http node without a timeout can hold + // its run indefinitely. + scanApprovalDecisionEdges(at, graphNodes, graphEdges, findings, sites); + scanHttpTimeouts(at, graphNodes, findings, sites); + // (d) #3863 — an edge labelled like an error path but typed 'default' is an // unconditional out-edge: the handler runs on every SUCCESS, in parallel // with the real path, and never on a failure. diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 1103448ad3f..cba378f810d 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -6252,6 +6252,83 @@ const FIELD_LABEL_DUPLICATE_EXPLANATION: RuleExplanation = { ], }; +// ── Publish-time refusals of metadata that parses and does nothing ────────── +// (`validate-flow-node-executors.ts`, `lint-flow-patterns.ts`, +// `validate-inert-object-declarations.ts`, `validate-action-object-binding.ts`) + +const FLOW_NODE_TYPE_NO_EXECUTOR_EXPLANATION: RuleExplanation = { + rule: 'flow-node-type-no-executor', + covers: 'which node types a flow may use', + paragraphs: [ + 'A flow node\'s `type` is an open name: plugins contribute node types, so the schema cannot list them and ' + + 'refuses only the retired callout names. A node typed after anything the deployment does not run — most ' + + 'often an AI author\'s own tool name, such as `query_records` for a read — parses and publishes, and then ' + + 'every run that reaches it fails with NO_EXECUTOR.', + 'The rule judges against the node types the deployment\'s automation engine runs, and only once the engine ' + + 'has declared that vocabulary closed, at the end of boot. Before that a plugin can still add a type, so ' + + '"no executor" would be a verdict the boot can contradict. The CLI commands therefore judge nothing here: ' + + 'which plugins a deployment loads is not part of the stack. The publish door of a running server judges ' + + 'every node, region bodies included, and its message lists the types that deployment runs.', + ], +}; + +const FLOW_APPROVAL_DECISION_UNROUTED_EXPLANATION: RuleExplanation = { + rule: 'flow-approval-decision-unrouted', + covers: 'how an approval decision picks its branch', + paragraphs: [ + 'An approval node continues down the out-edge whose `label` is exactly `approve` or `reject`, matching the ' + + 'decision. A decision that no edge claims is not an error at run time: the engine falls back to every ' + + 'out-edge, so the approving and the rejecting branch both run on the same decision.', + 'So both labels must be on an out-edge, spelled exactly: `Approve`, `approved` or a translated label is ' + + 'another label. An approval with no out-edge at all simply ends the flow and is not reported, and a ' + + '`fault` edge routes failures rather than decisions, so it is not counted. A `revise` edge (send back ' + + 'for revision) is checked by the `flow-approval-revise-*` rules.', + ], +}; + +const FLOW_HTTP_TIMEOUT_MISSING_EXPLANATION: RuleExplanation = { + rule: 'flow-http-timeout-missing', + covers: 'why an http node needs a timeout', + paragraphs: [ + 'The `http` node arms a timer only when `config.timeoutMs` is a positive number (`0` arms none), and the ' + + 'engine races a node against its node-level `timeoutMs` only when that is positive. With neither, the call ' + + 'waits for as long as the transport does: an endpoint that never answers holds the run, and a flow ' + + 'triggered by a record save holds that save with it. A `durable: true` node is not reported: it hands the ' + + 'request to the HTTP outbox and does not wait on the endpoint.', + 'A warning, not an error: the run is held, not lost, and a slow endpoint may be expected. Set `timeoutMs` to ' + + 'the longest answer the flow should wait for, in milliseconds.', + ], +}; + +const STATE_MACHINE_NO_INITIAL_STATES_EXPLANATION: RuleExplanation = { + rule: 'state-machine-no-initial-states', + covers: 'why a state machine needs an entry guard', + paragraphs: [ + 'A `state_machine` validation\'s `transitions` judge UPDATES: from this state, a record may move to those. ' + + 'Nothing in them judges an insert, and a select field accepts any of its options on create, so without ' + + '`initialStates` a record can be created already `approved` or `done` and skip the whole process. An ' + + 'empty `initialStates` list is the same as none: the engine reads it as no entry contract.', + '`initialStates` lists the states a record may be created in, and the server refuses an insert in any ' + + 'other. Seed rows are exempt from the machine on purpose, so curated sample data can start mid-process. ' + + 'A machine with `active: false` is not run, so it is not reported.', + ], +}; + +const ACTION_NO_OBJECT_BINDING_EXPLANATION: RuleExplanation = { + rule: 'action-no-object-binding', + covers: 'which actions need an objectName', + paragraphs: [ + 'Every action location is a surface of an object: its list toolbar, a list row, a record\'s header, menu, ' + + 'related list or section. A standalone action reaches them only through `objectName`, which folds it into ' + + 'that object\'s actions and keys its dispatch. Without it the action registers under the global scope and ' + + 'the button it declares renders nowhere. The handler itself still runs when called: an object-less action ' + + 'answers every object\'s action route, so only the placement is lost.', + 'An action written inside an object\'s own `actions` is bound by that object and is never reported. An ' + + 'action with no UI surface at all declares `locations: []`; one that omits `locations` is ' + + '`action-no-placement`\'s question.', + ], +}; + export const RULE_EXPLANATIONS: Readonly> = Object.freeze({ [FIELD_NO_CONSUMERS_EXPLANATION.rule]: FIELD_NO_CONSUMERS_EXPLANATION, [SECURITY_OWD_UNSET_EXPLANATION.rule]: SECURITY_OWD_UNSET_EXPLANATION, @@ -6487,6 +6564,11 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [STORED_EXPRESSION_CROSS_RECORD_INPUT_EXPLANATION.rule]: STORED_EXPRESSION_CROSS_RECORD_INPUT_EXPLANATION, [STORED_EXPRESSION_VOLATILE_INPUT_EXPLANATION.rule]: STORED_EXPRESSION_VOLATILE_INPUT_EXPLANATION, [FIELD_LABEL_DUPLICATE_EXPLANATION.rule]: FIELD_LABEL_DUPLICATE_EXPLANATION, + [FLOW_NODE_TYPE_NO_EXECUTOR_EXPLANATION.rule]: FLOW_NODE_TYPE_NO_EXECUTOR_EXPLANATION, + [FLOW_APPROVAL_DECISION_UNROUTED_EXPLANATION.rule]: FLOW_APPROVAL_DECISION_UNROUTED_EXPLANATION, + [FLOW_HTTP_TIMEOUT_MISSING_EXPLANATION.rule]: FLOW_HTTP_TIMEOUT_MISSING_EXPLANATION, + [STATE_MACHINE_NO_INITIAL_STATES_EXPLANATION.rule]: STATE_MACHINE_NO_INITIAL_STATES_EXPLANATION, + [ACTION_NO_OBJECT_BINDING_EXPLANATION.rule]: ACTION_NO_OBJECT_BINDING_EXPLANATION, }); /** The explanation for `rule`, or `undefined` when the rule has none. Exact id match. */ diff --git a/packages/lint/src/runtime-gate.object-writes.test.ts b/packages/lint/src/runtime-gate.object-writes.test.ts index 3ae2b38889e..7844c61232e 100644 --- a/packages/lint/src/runtime-gate.object-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-writes.test.ts @@ -162,6 +162,9 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () // at the metadata save gate and by `os validate`. Its refusal and the // re-save of a stored row that carries it are in the cases below. 'validateTitleFormatRetired', + // A state machine with no entry guard, judged on the object's own body + // (`validate-inert-object-declarations.ts`). + 'validateInertObjectDeclarations', 'lintAutonumberFormats', // A ruled join: the card's acceptance names this door. R13 judges a // roll-up's aggregand against the child objects the snapshot carries @@ -564,6 +567,7 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () 'validatePresetComparands', 'validateReferenceIntegrity', // [#15254] 'validateTitleFormatRetired', // [#29007] — see the roster pin above + 'validateInertObjectDeclarations', // see the roster pin above 'lintAutonumberFormats', 'lintSummaryRollups', // see the roster pin above 'lintDuplicateFieldLabels', // see the roster pin above diff --git a/packages/lint/src/runtime-gate.ts b/packages/lint/src/runtime-gate.ts index 186490e62e9..de37ecbeb90 100644 --- a/packages/lint/src/runtime-gate.ts +++ b/packages/lint/src/runtime-gate.ts @@ -1438,6 +1438,13 @@ export function runRuntimeAuthoringRules(args: { * folds the written entry over the target as served, as before. */ storedObjectExtensions?: readonly StoredObjectExtension[]; + /** + * The node types the host's automation engine runs, stated only once the host + * has SEALED that vocabulary (`AutomationEngine.getSealedNodeTypeVocabulary()`). + * Handed to the rules as `AuthoringRuleContext.flowNodeTypeVocabulary`, the + * same value in every pass. Omitted, a flow node's type is not judged. + */ + flowNodeTypeVocabulary?: readonly string[]; }): RuntimeGateResult { const rules = runtimeAuthoringRulesFor(args.type); const empty: RuntimeGateResult = { errors: [], advisories: [], rulesRun: [] }; @@ -1505,6 +1512,11 @@ export function runRuntimeAuthoringRules(args: { ...(args.type === 'object_extension' && args.storedObjectExtensions !== undefined ? { storedObjectExtensions: args.storedObjectExtensions } : {}), + // The sealed vocabulary, stated by the host; the same value in every pass, + // so it moves no baseline. + ...(args.flowNodeTypeVocabulary !== undefined && args.flowNodeTypeVocabulary.length > 0 + ? { flowNodeTypeVocabulary: new Set(args.flowNodeTypeVocabulary) } + : {}), }; const added = addedFindings(rules, snapshots, ctx, args.type, args.item); diff --git a/packages/lint/src/validate-action-object-binding.test.ts b/packages/lint/src/validate-action-object-binding.test.ts new file mode 100644 index 00000000000..bbba2fbc6ec --- /dev/null +++ b/packages/lint/src/validate-action-object-binding.test.ts @@ -0,0 +1,32 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; +import { ACTION_NO_OBJECT_BINDING, validateActionObjectBinding } from './validate-action-object-binding.js'; + +const action = (extra: Record) => ({ name: 'mark_done', label: 'Mark done', type: 'script', ...extra }); + +describe('action-no-object-binding', () => { + it('refuses a standalone action that declares a location and no objectName', () => { + const findings = validateActionObjectBinding({ actions: [action({ locations: ['record_header'] })] }); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ rule: ACTION_NO_OBJECT_BINDING, severity: 'error', path: 'actions[0].objectName' }); + expect(findings[0].hint).toContain('locations: []'); + }); + + it('is silent on a bound action, a headless one, one with no `locations`, and one embedded on its object', () => { + expect(validateActionObjectBinding({ + actions: [ + action({ objectName: 'qa_task', locations: ['record_header'] }), + action({ name: 'sync_all', locations: [] }), + action({ name: 'unplaced' }), + ], + objects: [{ name: 'qa_task', actions: [action({ locations: ['record_header'] })] }], + })).toEqual([]); + }); + + it('the runtime publish gate refuses the `action` write', () => { + const verdict = runRuntimeAuthoringRules({ type: 'action', item: action({ locations: ['list_toolbar'] }) }); + expect(verdict.errors.map((f) => f.rule)).toContain(ACTION_NO_OBJECT_BINDING); + }); +}); diff --git a/packages/lint/src/validate-action-object-binding.ts b/packages/lint/src/validate-action-object-binding.ts new file mode 100644 index 00000000000..84c08d2fecd --- /dev/null +++ b/packages/lint/src/validate-action-object-binding.ts @@ -0,0 +1,63 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A standalone action that declares where it renders but names no object. + * + * Every location in `ACTION_LOCATIONS` (`@objectstack/spec/ui`) is a surface + * of an object: its list toolbar, a list row, a record's header, menu, + * related list or section. A standalone action (`stack.actions[]`) reaches + * those surfaces only through its `objectName`, which `defineStack` folds into + * that object's `actions` and the runtime keys its dispatch by. Without one the + * action registers under the global scope: no object's list or record page + * carries it, so the button it declares never renders. (The handler still + * runs: an object-less action answers every object's action route, since + * `resolveActionByPackage` falls through to the global scope — only the + * placement is lost.) The spec's own note on the + * location vocabulary names the honest shape for an object-less action: + * `locations: []`, headless. + * + * An action embedded in an object's own `actions` is bound by the object it is + * written on and is never visited. An action that omits `locations` is + * `action-no-placement`'s question, not this rule's. + */ + +import { recordsOf } from './object-graph.js'; + +export const ACTION_NO_OBJECT_BINDING = 'action-no-object-binding'; + +export interface ActionObjectBindingFinding { + severity: 'error'; + rule: string; + where: string; + path: string; + message: string; + hint: string; +} + +/** Flag every standalone action that declares a location and names no object. */ +export function validateActionObjectBinding(stack: Record): ActionObjectBindingFinding[] { + const findings: ActionObjectBindingFinding[] = []; + if (!stack || typeof stack !== 'object') return findings; + const list: readonly unknown[] = Array.isArray(stack.actions) ? stack.actions : []; + for (const action of recordsOf(stack.actions)) { + if (typeof action.objectName === 'string' && action.objectName.length > 0) continue; + const locations = Array.isArray(action.locations) + ? action.locations.filter((l): l is string => typeof l === 'string') + : []; + if (locations.length === 0) continue; + const name = typeof action.name === 'string' ? action.name : '(unnamed action)'; + findings.push({ + severity: 'error', + rule: ACTION_NO_OBJECT_BINDING, + where: `action "${name}"`, + path: `actions[${list.indexOf(action)}].objectName`, + message: + `Action "${name}" declares ${locations.map((l) => `\`${l}\``).join(', ')} but no \`objectName\`, so it binds ` + + 'to no object: no list or record page carries it, so the button it declares never renders.', + hint: + `Set \`objectName\` to the object the action acts on, or write \`locations: []\` if it is headless ` + + '(REST / MCP / AI only).', + }); + } + return findings; +} diff --git a/packages/lint/src/validate-flow-node-executors.test.ts b/packages/lint/src/validate-flow-node-executors.test.ts new file mode 100644 index 00000000000..63c4d187d47 --- /dev/null +++ b/packages/lint/src/validate-flow-node-executors.test.ts @@ -0,0 +1,61 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; +import { FLOW_NODE_TYPE_NO_EXECUTOR, validateFlowNodeExecutors } from './validate-flow-node-executors.js'; + +const SEALED = ['start', 'end', 'get_record', 'update_record', 'loop', 'http']; + +const flow = (nodes: Array>) => ({ + name: 'nightly_digest', + label: 'Nightly digest', + type: 'schedule', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, ...nodes, { id: 'end', type: 'end', label: 'End' }], + edges: [], +}); + +/** A tool name used as a node type: the shape the rule exists for. */ +const TOOL_NAMED = flow([{ id: 'find_open', type: 'query_records', label: 'Find open' }]); + +describe('flow-node-type-no-executor', () => { + it('refuses a node type outside the sealed vocabulary, located on the node, naming the vocabulary', () => { + const findings = validateFlowNodeExecutors({ flows: [TOOL_NAMED] }, new Set(SEALED)); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ + severity: 'error', + rule: FLOW_NODE_TYPE_NO_EXECUTOR, + path: 'flows[0].nodes[1].type', + }); + expect(findings[0].message).toContain("'query_records'"); + expect(findings[0].hint).toContain('get_record'); + }); + + it('judges a node in a region body as one beside it', () => { + const looped = flow([ + { id: 'each', type: 'loop', label: 'Each', config: { collection: 'rows', body: { nodes: [{ id: 'inner', type: 'query_records', label: 'Inner' }] } } }, + ]); + const findings = validateFlowNodeExecutors({ flows: [looped] }, new Set(SEALED)); + expect(findings.map((f) => f.path)).toEqual(['flows[0].nodes[1].config.body.nodes[0].type']); + }); + + it('is silent on a flow whose every type the vocabulary runs', () => { + const clean = flow([{ id: 'find_open', type: 'get_record', label: 'Find open' }]); + expect(validateFlowNodeExecutors({ flows: [clean] }, new Set(SEALED))).toEqual([]); + }); + + it('judges nothing without a sealed vocabulary: the CLI commands hand none in', () => { + expect(validateFlowNodeExecutors({ flows: [TOOL_NAMED] }, undefined)).toEqual([]); + for (const command of ['validate', 'build', 'lint'] as const) { + const rules = runAuthoringRules(command, { normalized: { flows: [TOOL_NAMED] } } as never); + expect(rules.filter((f) => f.rule === FLOW_NODE_TYPE_NO_EXECUTOR)).toEqual([]); + } + }); + + it('the runtime publish gate refuses the flow when the host states a sealed vocabulary, and only then', () => { + const sealed = runRuntimeAuthoringRules({ type: 'flow', item: TOOL_NAMED, flowNodeTypeVocabulary: SEALED }); + expect(sealed.errors.map((f) => f.rule)).toContain(FLOW_NODE_TYPE_NO_EXECUTOR); + const unsealed = runRuntimeAuthoringRules({ type: 'flow', item: TOOL_NAMED }); + expect([...unsealed.errors, ...unsealed.advisories].map((f) => f.rule)).not.toContain(FLOW_NODE_TYPE_NO_EXECUTOR); + }); +}); diff --git a/packages/lint/src/validate-flow-node-executors.ts b/packages/lint/src/validate-flow-node-executors.ts new file mode 100644 index 00000000000..7006b386670 --- /dev/null +++ b/packages/lint/src/validate-flow-node-executors.ts @@ -0,0 +1,77 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A flow node whose `type` no executor runs. + * + * `FlowNodeSchema.type` is an open string (ADR-0018: the node vocabulary is + * plugin-extensible), so the schema refuses only the reserved callout names. + * A node typed after anything else — most often an AI author's own tool name, + * `query_records` for a read — parses, publishes, and then fails EVERY run + * with `NO_EXECUTOR`. The engine notices only in a warning once its + * vocabulary is sealed, after the flow already shipped. + * + * ## Judged against the SEALED vocabulary, never a registry still filling + * + * A plugin contributes its node types from its own `init()` / `start()`, so + * "no executor for `approval`" read during boot is "not registered YET" + * (AGENTS.md "Startup registry reads"). The rule therefore judges only with + * the vocabulary its caller hands in, and a caller hands one in only after the + * host declared it closed: the runtime publish gate reads + * `AutomationEngine.getSealedNodeTypeVocabulary()`, which answers nothing until + * `sealNodeTypeVocabulary()` ran at `kernel:bootstrapped`. With no vocabulary — + * every CLI command, whose stack does not say which plugins the deployment + * will load, and a gate on an unsealed engine — the rule judges nothing. + * + * Every node is visited, region bodies included: a node in a `loop` body runs + * as surely as one beside it. + */ + +import { recordsOf } from './object-graph.js'; +import { walkFlowNodes } from './flow-walk.js'; + +export const FLOW_NODE_TYPE_NO_EXECUTOR = 'flow-node-type-no-executor'; + +export interface FlowNodeExecutorFinding { + severity: 'error'; + rule: string; + where: string; + path: string; + message: string; + hint: string; +} + +/** + * Flag every flow node whose `type` is outside `vocabulary`, the node types the + * deployment's sealed automation engine runs. Returns nothing when no + * vocabulary is given. + */ +export function validateFlowNodeExecutors( + stack: Record, + vocabulary: ReadonlySet | undefined, +): FlowNodeExecutorFinding[] { + const findings: FlowNodeExecutorFinding[] = []; + if (!vocabulary || vocabulary.size === 0 || !stack || typeof stack !== 'object') return findings; + const flowList: readonly unknown[] = Array.isArray(stack.flows) ? stack.flows : []; + for (const flow of recordsOf(stack.flows)) { + const flowName = typeof flow.name === 'string' ? flow.name : '(unnamed flow)'; + const flowPath = `flows[${Math.max(flowList.indexOf(flow), 0)}]`; + for (const { node, path } of walkFlowNodes(flow, flowPath)) { + const type = typeof node.type === 'string' ? node.type : undefined; + if (!type || vocabulary.has(type)) continue; + const nodeId = typeof node.id === 'string' ? node.id : path; + findings.push({ + severity: 'error', + rule: FLOW_NODE_TYPE_NO_EXECUTOR, + where: `flow '${flowName}' · node '${nodeId}'`, + path: `${path}.type`, + message: + `Node '${nodeId}' has type '${type}', which no executor in this deployment runs — the flow publishes, ` + + 'and every run that reaches the node fails with NO_EXECUTOR.', + hint: + `Use a node type this deployment runs (${[...vocabulary].sort().join(', ')}), or install the plugin ` + + `that contributes '${type}'.`, + }); + } + } + return findings; +} diff --git a/packages/lint/src/validate-inert-object-declarations.test.ts b/packages/lint/src/validate-inert-object-declarations.test.ts new file mode 100644 index 00000000000..0bbf17b6661 --- /dev/null +++ b/packages/lint/src/validate-inert-object-declarations.test.ts @@ -0,0 +1,67 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; +import { + STATE_MACHINE_NO_INITIAL_STATES, + validateInertObjectDeclarations, +} from './validate-inert-object-declarations.js'; + +const task = (fields: Record, validations: unknown[] = []) => ({ + name: 'qa_task', + label: 'Task', + fields: { title: { type: 'text', label: 'Title' }, ...fields }, + validations, +}); + +const STATUS = { + type: 'select', + label: 'Status', + options: [{ label: 'Draft', value: 'draft' }, { label: 'Approved', value: 'approved' }], +}; +const machine = (extra: Record = {}) => ({ + name: 'status_flow', + type: 'state_machine', + message: 'Illegal status change', + field: 'status', + transitions: { draft: ['approved'], approved: [] }, + ...extra, +}); + +describe('state-machine-no-initial-states', () => { + it('refuses a state machine with no `initialStates`, naming a first state in the fix', () => { + const findings = validateInertObjectDeclarations({ objects: [task({ status: STATUS }, [machine()])] }); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ rule: STATE_MACHINE_NO_INITIAL_STATES, severity: 'error', path: 'objects[0].validations[0]' }); + expect(findings[0].hint).toContain("initialStates: ['draft']"); + }); + + it('refuses an empty `initialStates` list: the engine reads it as no entry contract', () => { + const findings = validateInertObjectDeclarations({ objects: [task({ status: STATUS }, [machine({ initialStates: [] })])] }); + expect(findings.map((f) => [f.rule, f.path])).toEqual([[STATE_MACHINE_NO_INITIAL_STATES, 'objects[0].validations[0]']]); + }); + + it('is silent on a machine with `active: false`: the engine skips it', () => { + expect(validateInertObjectDeclarations({ objects: [task({ status: STATUS }, [machine({ active: false })])] })).toEqual([]); + }); + + it('is silent when the machine declares its entry states, and on other validation types', () => { + expect(validateInertObjectDeclarations({ + objects: [task({ status: STATUS }, [machine({ initialStates: ['draft'] }), { name: 'r', type: 'script', message: 'm', condition: 'false' }])], + })).toEqual([]); + }); +}); + +describe('the runtime publish gate refuses an object write carrying the declaration', () => { + it('raises it as an error on an `object` write', () => { + const item = task({ status: STATUS }, [machine()]); + const verdict = runRuntimeAuthoringRules({ type: 'object', item }); + expect(verdict.errors.map((f) => f.rule)).toContain(STATE_MACHINE_NO_INITIAL_STATES); + }); + + it('a required boolean is not refused: the form treats false as present', () => { + const item = task({ is_done: { type: 'boolean', label: 'Done', required: true, defaultValue: true } }); + const verdict = runRuntimeAuthoringRules({ type: 'object', item }); + expect(verdict.errors.map((f) => f.rule)).not.toContain('field-boolean-required'); + }); +}); diff --git a/packages/lint/src/validate-inert-object-declarations.ts b/packages/lint/src/validate-inert-object-declarations.ts new file mode 100644 index 00000000000..3c722679f88 --- /dev/null +++ b/packages/lint/src/validate-inert-object-declarations.ts @@ -0,0 +1,65 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * An object declaration that passes the schema and then works against its + * author at run time — a refusal at publish, with the fix named. + * + * {@link STATE_MACHINE_NO_INITIAL_STATES} — an active `state_machine` + * validation with no `initialStates`, or an empty list. `transitions` governs + * UPDATE only, and the engine treats an absent or empty `initialStates` as + * "no entry contract" (`checkStateMachine`), so a record can be CREATED + * already in any state (born `approved`), walking straight past the process + * the machine declares. A rule with `active: false` is skipped, as the engine + * skips it. + * + * It reads the object's own body alone, so the runtime publish gate judges an + * `object` write exactly as the CLI judges the stack. + */ + +import { collectionEntries } from './collection-entries.js'; +import { recordsOf } from './object-graph.js'; + +export const STATE_MACHINE_NO_INITIAL_STATES = 'state-machine-no-initial-states'; + +export interface InertObjectDeclarationFinding { + severity: 'error'; + rule: string; + where: string; + path: string; + message: string; + hint: string; +} + +/** Flag an entry-unguarded state machine on every object. */ +export function validateInertObjectDeclarations(stack: Record): InertObjectDeclarationFinding[] { + const findings: InertObjectDeclarationFinding[] = []; + if (!stack || typeof stack !== 'object') return findings; + for (const { rec: obj, path: objPath } of collectionEntries(stack.objects, 'objects')) { + const objectName = typeof obj.name === 'string' ? obj.name : objPath; + + const validations = recordsOf(obj.validations); + const validationList: readonly unknown[] = Array.isArray(obj.validations) ? obj.validations : []; + for (const rule of validations) { + if (rule.type !== 'state_machine' || rule.active === false) continue; + // Absent and empty are the same to the engine: no entry contract. + if (Array.isArray(rule.initialStates) && rule.initialStates.length > 0) continue; + const ruleName = typeof rule.name === 'string' ? rule.name : 'state_machine'; + const stateField = typeof rule.field === 'string' ? rule.field : 'its state field'; + const transitions = rule.transitions && typeof rule.transitions === 'object' ? Object.keys(rule.transitions) : []; + const first = transitions[0]; + findings.push({ + severity: 'error', + rule: STATE_MACHINE_NO_INITIAL_STATES, + where: `object "${objectName}" validation "${ruleName}"`, + path: `${objPath}.validations[${validationList.indexOf(rule)}]`, + message: + `State machine "${ruleName}" declares no \`initialStates\` (an empty list counts as none). Its \`transitions\` govern updates only, so a ` + + `record can be created with "${stateField}" already at any state and skip the process.`, + hint: + `Add \`initialStates\` listing the states a record may be created in` + + `${first ? `, e.g. \`initialStates: ['${first}']\`` : ''}.`, + }); + } + } + return findings; +} diff --git a/packages/metadata-protocol/src/build-probes-landed-data.test.ts b/packages/metadata-protocol/src/build-probes-landed-data.test.ts new file mode 100644 index 00000000000..dabae6244d4 --- /dev/null +++ b/packages/metadata-protocol/src/build-probes-landed-data.test.ts @@ -0,0 +1,432 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35146] The four probes that read what LANDED: a dashboard card that reads + * only zeros, a roll-up never computed, a seed reference naming no row, and a + * flow step naming a connector action the runtime does not serve. Each is a + * warning: the publish stands, and the receipt says what the person will see. + * Each has its finding pinned beside the shape that must stay silent. + * The sentences themselves are pinned in `build-probes-user-message.test.ts`. + */ + +import { describe, expect, it } from 'vitest'; +import './lint-root-preload.testkit.js'; +import { runBuildProbes, type ProbeAutomation, type ProbeEngine, type RunBuildProbesOptions } from './build-probes.js'; + +type Row = Record; + +/** One `where` on one row: equality and `{ $in: [...] }`; any other operator or combinator is refused. */ +const matches = (row: Row, where: Record | undefined): boolean => + Object.entries(where ?? {}).every(([key, want]) => { + if (key.startsWith('$')) throw new Error(`double: combinator ${key} not implemented`); + if (!want || typeof want !== 'object') return row[key] === want; + const ops = Object.keys(want); + const $in = (want as { $in?: unknown }).$in; + if (ops.length !== 1 || !Array.isArray($in)) throw new Error(`double: operator ${ops.join(',')} not implemented`); + return $in.includes(row[key]); + }); + +/** + * Fixed tables; honours `where`, the context's organization, then `limit` + * (`check:objectql-double-limit`), and the `fields` projection. A table whose + * rows carry `organization_id` is tenant-scoped, as the engine reads it: a + * read with a `tenantId` sees that organization's rows only, and `getSchema` + * names the column. A table whose rows carry none (`sys_user`) is not scoped. + */ +const engineOver = (tables: Record): ProbeEngine => ({ + find: async (object, query) => { + const q = query as + | { where?: Record; limit?: unknown; fields?: unknown; context?: { tenantId?: unknown } } + | undefined; + const tenant = q?.context?.tenantId; + const rows = (tables[object] ?? []) + .filter((r) => matches(r, q?.where)) + .filter((r) => tenant === undefined || !('organization_id' in r) || r.organization_id === tenant); + const limited = typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows; + const fields = Array.isArray(q?.fields) ? (q.fields as string[]) : undefined; + return fields ? limited.map((r) => Object.fromEntries(fields.filter((f) => f in r).map((f) => [f, r[f]]))) : limited; + }, + getSchema: (object) => + (tables[object] ?? []).some((r) => 'organization_id' in r) + ? { name: object, fields: { organization_id: { type: 'lookup', reference: 'sys_organization' } } } + : { name: object, fields: {} }, +}); + +const ITEMS: Record = { + 'object acct': { + name: 'acct', + fields: { + deal_count: { type: 'summary', summaryOperations: { object: 'deal', function: 'count' } }, + deal_total: { type: 'summary', summaryOperations: { object: 'deal', function: 'sum', field: 'amount' } }, + won_total: { + type: 'summary', + summaryOperations: { object: 'deal', function: 'sum', field: 'amount', filter: { stage: 'won' } }, + }, + }, + }, + 'object deal': { + name: 'deal', + fields: { + acct_ref: { type: 'master_detail', reference: 'acct' }, + amount: { type: 'number' }, + owner: { type: 'user' }, + }, + }, + 'seed deal_seed': { object: 'deal', records: [{ name: 'D1' }, { name: 'D2' }] }, + 'seed deal_seed_upsert': { object: 'deal', mode: 'upsert', records: [{ name: 'D1' }, { name: 'D2' }] }, + 'dashboard board': { + name: 'board', + widgets: [{ id: 'w1', dataset: 'deal_totals', values: ['total'] }], + }, + 'dataset deal_totals': { name: 'deal_totals', object: 'deal', measures: [{ name: 'total', aggregate: 'count' }] }, + 'flow sync': { + name: 'sync', + nodes: [ + { id: 'start', type: 'start' }, + { id: 'push', type: 'connector_action', connectorConfig: { connectorId: 'erp', actionId: 'push_order' } }, + ], + edges: [{ id: 'e', source: 'start', target: 'push' }], + }, +}; + +const run = (opts: Partial & Pick) => + runBuildProbes({ engine: engineOver({}), getItem: async (t, n) => ITEMS[`${t} ${n}`], ...opts }); + +const codes = (report: Awaited>) => report.issues.map((i) => [i.code, i.severity, i.ref?.member]); + +/** `seedApplied.landed` for one object: the ids the loader created and the ids a seed key matched. */ +const landedOn = (object: string, inserted: string[], matched: string[] = []) => + [{ object, inserted: { ids: inserted }, matched: { ids: matched } }]; + +describe('widget_empty_result: a card whose real query reads only zeros', () => { + const analytics = (rows: Row[]) => ({ queryDataset: async () => ({ rows }) }); + const deals = engineOver({ deal: [{ id: 'd1' }] }); + + it('only zeros and nulls on every row: a warning naming the widget', async () => { + const report = await run({ + engine: deals, + analytics: analytics([{ total: 0 }, { total: null }]), + published: [{ type: 'dashboard', name: 'board' }], + }); + expect(codes(report)).toEqual([['widget_empty_result', 'warning', 'w1']]); + expect(report.issues[0]!.artifact).toEqual({ type: 'dashboard', name: 'board' }); + }); + + it('one non-zero value, or no asked measure in the result: silent', async () => { + for (const rows of [[{ total: 0 }, { total: 3 }], [{ other: 0 }]]) { + const report = await run({ engine: deals, analytics: analytics(rows), published: [{ type: 'dashboard', name: 'board' }] }); + expect(report.issues).toEqual([]); + } + }); + + it('no rows over an object with rows stays `empty_query`, not a second finding', async () => { + const report = await run({ engine: deals, analytics: analytics([]), published: [{ type: 'dashboard', name: 'board' }] }); + expect(codes(report)).toEqual([['empty_query', 'error', 'w1']]); + }); +}); + +describe('rollup_never_computed: a roll-up blank on every parent that has children', () => { + const published = [{ type: 'object', name: 'acct' }]; + + it('blank on every parent a child points at: one warning per roll-up, the filtered one unjudged', async () => { + const report = await run({ + engine: engineOver({ + deal: [{ id: 'd1', acct_ref: 'a1', amount: 5 }, { id: 'd2', acct_ref: 'a2', amount: 7 }], + acct: [{ id: 'a1', deal_count: null, deal_total: null }, { id: 'a2' }], + }), + published, + }); + expect(codes(report)).toEqual([ + ['rollup_never_computed', 'warning', 'deal_count'], + ['rollup_never_computed', 'warning', 'deal_total'], + ]); + }); + + it('computed on one parent (a zero counts), or no parent with children: silent', async () => { + for (const engine of [ + engineOver({ deal: [{ id: 'd1', acct_ref: 'a1', amount: 0 }], acct: [{ id: 'a1', deal_count: 1, deal_total: 0 }] }), + engineOver({ deal: [{ id: 'd1', acct_ref: null }], acct: [{ id: 'a1', deal_count: null, deal_total: null }] }), + ]) { + expect((await run({ engine, published })).issues).toEqual([]); + } + }); + + it('a sum whose children carry no value in its field is not judged', async () => { + const report = await run({ + engine: engineOver({ deal: [{ id: 'd1', acct_ref: 'a1' }], acct: [{ id: 'a1', deal_count: 1, deal_total: null }] }), + published, + }); + expect(report.issues).toEqual([]); + }); +}); + +describe('seed_reference_unresolved: a landed reference naming no row', () => { + const published = [{ type: 'seed', name: 'deal_seed' }]; + + it('a value no target row has: a warning on the seed, naming the column', async () => { + const report = await run({ + engine: engineOver({ + deal: [{ id: 'd1', name: 'D1', acct_ref: 'a1', owner: 'Jane Smith' }, { id: 'd2', name: 'D2', acct_ref: 'a_gone' }], + acct: [{ id: 'a1' }], + sys_user: [{ id: 'u1' }], + }), + seedLanded: landedOn('deal', ['d1', 'd2']), + published, + }); + expect(codes(report)).toEqual([ + ['seed_reference_unresolved', 'warning', 'acct_ref'], + ['seed_reference_unresolved', 'warning', 'owner'], + ]); + expect(report.issues[0]!.artifact).toEqual({ type: 'seed', name: 'deal_seed' }); + expect(report.issues[0]!.message).toContain('"a_gone"'); + expect(report.issues[1]!.message).toContain('"Jane Smith"'); + }); + + it('every value resolves, or the column is blank: silent', async () => { + const report = await run({ + engine: engineOver({ + deal: [{ id: 'd1', name: 'D1', acct_ref: 'a1', owner: 'u1' }, { id: 'd2', name: 'D2', acct_ref: null }], + acct: [{ id: 'a1' }], + sys_user: [{ id: 'u1' }], + }), + seedLanded: landedOn('deal', ['d1', 'd2']), + published, + }); + expect(report.issues).toEqual([]); + }); + + it('a row the loader did not land is not judged as the seed\'s, though it shares a seed key', async () => { + const report = await run({ + engine: engineOver({ + deal: [{ id: 'd1', name: 'D1', acct_ref: 'a1' }, { id: 'd9', name: 'D2', acct_ref: 'a_typed_by_a_person' }], + acct: [{ id: 'a1' }], + }), + seedLanded: landedOn('deal', ['d1']), + published, + }); + expect(report.issues).toEqual([]); + }); + + it('a row a seed key matched is the seed\'s only when the seed\'s mode wrote it', async () => { + const engine = engineOver({ deal: [{ id: 'd9', name: 'D1', acct_ref: 'a_gone' }], acct: [] }); + const seedLanded = landedOn('deal', [], ['d9']); + // `ignore` (the default) left the matched row as its writer left it. + expect((await run({ engine, seedLanded, published })).issues).toEqual([]); + // `upsert` wrote it. + const upsert = await run({ engine, seedLanded, published: [{ type: 'seed', name: 'deal_seed_upsert' }] }); + expect(codes(upsert)).toEqual([['seed_reference_unresolved', 'warning', 'acct_ref']]); + }); + + it('no `seedApplied.landed` for the object: not judged', async () => { + const report = await run({ + engine: engineOver({ deal: [{ id: 'd1', name: 'D1', acct_ref: 'a_gone' }], acct: [] }), + published, + }); + expect(report.issues).toEqual([]); + }); + + it('a target read that throws judges nothing', async () => { + const report = await run({ + engine: { + find: async (object) => { + if (object === 'deal') return [{ id: 'd1', name: 'D1', acct_ref: 'a_gone' }]; + throw new Error('no such table'); + }, + }, + seedLanded: landedOn('deal', ['d1']), + published, + }); + expect(report.issues).toEqual([]); + }); +}); + +describe('flow_connector_action_unresolved: a connector step the runtime cannot dispatch', () => { + const published = [{ type: 'flow', name: 'sync' }]; + const automation = (over: Partial): ProbeAutomation => ({ + resolveConnectorInstanceFor: () => ({ status: 'instance', packageId: 'com.acme.app' }), + resolveConnectorAction: () => undefined, + getConnectorDegradedReason: () => undefined, + ...over, + }); + + it('no handler for the action: a warning on the flow, naming connector and action', async () => { + const report = await run({ automation: automation({}), published, packageId: 'com.acme.app' }); + expect(codes(report)).toEqual([['flow_connector_action_unresolved', 'warning', 'push_order']]); + expect(report.issues[0]!.artifact).toEqual({ type: 'flow', name: 'sync' }); + expect(report.issues[0]!.ref).toEqual({ type: 'connector', name: 'erp', member: 'push_order' }); + }); + + it('the action resolves for the flow\'s package: silent, and the lookups were asked for that package', async () => { + const asked: Array<[string, string | null | undefined]> = []; + const report = await run({ + automation: automation({ + resolveConnectorInstanceFor: (id, pkg) => { + asked.push([id, pkg]); + return { status: 'instance', packageId: pkg }; + }, + resolveConnectorAction: () => async () => ({}), + }), + published, + packageId: 'com.acme.app', + }); + expect(report.issues).toEqual([]); + expect(asked).toEqual([['erp', 'com.acme.app']]); + }); + + it('an engine without the connector lookup is not probed', async () => { + const report = await run({ automation: {}, published }); + expect(report.issues).toEqual([]); + }); +}); + +describe('the landed-data reads are scoped like the engine\'s reference audit, and projected', () => { + type Read = { object: string; where?: Record; fields?: unknown; context?: Record }; + /** Records every read, over the same fixed tables. */ + const recording = (tables: Record) => { + const reads: Read[] = []; + const inner = engineOver(tables); + const engine: ProbeEngine = { + find: async (object, query) => { + const q = query as Omit; + reads.push({ object, where: q.where, fields: q.fields, context: q.context }); + return inner.find(object, query); + }, + getSchema: inner.getSchema, + }; + return { engine, reads }; + }; + const seedRowsRead = (r: Read) => r.object === 'deal' && r.where?.id !== undefined; + + it('seed_reference_unresolved: a target row of another organization does not resolve the reference', async () => { + const { engine, reads } = recording({ + deal: [{ id: 'd1', name: 'D1', organization_id: 'o1', acct_ref: 'a9' }], + acct: [{ id: 'a9', organization_id: 'o2' }], + }); + const report = await run({ + engine, organizationId: 'o1', seedLanded: landedOn('deal', ['d1']), published: [{ type: 'seed', name: 'deal_seed' }], + }); + expect(codes(report)).toEqual([['seed_reference_unresolved', 'warning', 'acct_ref']]); + expect(reads.filter((r) => r.object === 'acct')).toEqual([ + { object: 'acct', where: { id: { $in: ['a9'] } }, fields: ['id'], context: { isSystem: true, tenantId: 'o1' } }, + ]); + // The seed's own rows, by the loader's ids, projected to what is judged. + // (The first `deal` read is `seed_not_applied`'s row count.) + expect(reads.find(seedRowsRead)).toEqual({ + object: 'deal', + where: { id: { $in: ['d1'] } }, + fields: ['id', 'acct_ref', 'owner'], + context: { isSystem: true, tenantId: 'o1' }, + }); + }); + + it('seed_reference_unresolved: a row of another organization with the seed\'s key is not matched, counted or quoted', async () => { + const { engine, reads } = recording({ + deal: [ + { id: 'd1', name: 'D1', organization_id: 'o1', acct_ref: 'a1', owner: 'u1' }, + { id: 'd7', name: 'D1', organization_id: 'o2', acct_ref: 'a_other_org_value', owner: 'u1' }, + ], + acct: [{ id: 'a1', organization_id: 'o1' }], + sys_user: [{ id: 'u1' }], + }); + const report = await run({ engine, seedLanded: landedOn('deal', ['d1']), published: [{ type: 'seed', name: 'deal_seed' }] }); + expect(report.issues).toEqual([]); + expect(JSON.stringify(reads)).not.toContain('a_other_org_value'); + expect(reads.filter((r) => r.object === 'acct').map((r) => r.where)).toEqual([{ id: { $in: ['a1'] } }]); + }); + + it('seed_reference_unresolved with no publishing organization: each value is judged in its row\'s own organization', async () => { + const { engine, reads } = recording({ + deal: [ + { id: 'd1', name: 'D1', organization_id: 'o1', acct_ref: 'a1', owner: 'u1' }, + { id: 'd2', name: 'D2', organization_id: 'o2', acct_ref: 'a1', owner: 'u1' }, + ], + acct: [{ id: 'a1', organization_id: 'o1' }], + sys_user: [{ id: 'u1' }], + }); + const report = await run({ engine, seedLanded: landedOn('deal', ['d1', 'd2']), published: [{ type: 'seed', name: 'deal_seed' }] }); + // `a1` resolves for the o1 row and not for the o2 one; `sys_user` has no + // tenant column, so `u1` resolves in both. + expect(codes(report)).toEqual([['seed_reference_unresolved', 'warning', 'acct_ref']]); + expect(report.issues[0]!.message).toContain('1 value(s)'); + expect(reads.filter((r) => r.object === 'acct').map((r) => r.context)).toEqual([ + { isSystem: true, tenantId: 'o1' }, + { isSystem: true, tenantId: 'o2' }, + ]); + expect(reads.find(seedRowsRead)!.fields).toEqual(['id', 'acct_ref', 'owner', 'organization_id']); + }); + + it('rollup_never_computed: a parent row of another organization is not judged', async () => { + const { engine, reads } = recording({ + deal: [{ id: 'd1', organization_id: 'o1', acct_ref: 'a1', amount: 5 }], + acct: [{ id: 'a1', organization_id: 'o2', deal_count: null, deal_total: null }], + }); + const report = await run({ engine, organizationId: 'o1', published: [{ type: 'object', name: 'acct' }] }); + expect(report.issues).toEqual([]); + const parents = reads.filter((r) => r.object === 'acct'); + expect(parents.map((r) => [r.where, r.fields, r.context])).toEqual([ + [{ id: { $in: ['a1'] } }, ['id', 'deal_count'], { isSystem: true, tenantId: 'o1' }], + [{ id: { $in: ['a1'] } }, ['id', 'deal_total'], { isSystem: true, tenantId: 'o1' }], + ]); + expect(reads.filter((r) => r.object === 'deal').map((r) => [r.fields, r.context])).toEqual([ + [['id', 'acct_ref'], { isSystem: true, tenantId: 'o1' }], + [['id', 'acct_ref', 'amount'], { isSystem: true, tenantId: 'o1' }], + ]); + }); + + it('rollup_never_computed with no publishing organization: a child of another organization is not counted', async () => { + const { engine, reads } = recording({ + deal: [ + { id: 'd1', organization_id: 'o1', acct_ref: 'a1', amount: 5 }, + { id: 'd2', organization_id: 'o2', acct_ref: 'b1', amount: 5 }, + { id: 'd3', organization_id: 'o2', acct_ref: 'b2', amount: 5 }, + ], + acct: [ + { id: 'a1', organization_id: 'o1', deal_count: 1, deal_total: 5 }, + { id: 'b1', organization_id: 'o2', deal_count: null, deal_total: null }, + { id: 'b2', organization_id: 'o2', deal_count: null, deal_total: null }, + ], + }); + const report = await run({ engine, published: [{ type: 'object', name: 'acct' }] }); + // o1 computed its roll-ups; o2 never did. The verdict and the count are o2's alone. + expect(codes(report)).toEqual([ + ['rollup_never_computed', 'warning', 'deal_count'], + ['rollup_never_computed', 'warning', 'deal_total'], + ]); + expect(report.issues[0]!.message).toContain('all 2 parent row(s) of one organization'); + const samples = reads.filter((r) => r.object === 'deal' && r.context?.tenantId !== undefined); + expect(samples.map((r) => r.context!.tenantId)).toEqual(['o1', 'o2', 'o1', 'o2']); + // The organizations come from a read projected to the tenant column alone. + expect(reads.filter((r) => r.object === 'deal' && r.context?.tenantId === undefined).map((r) => r.fields)) + .toEqual([['organization_id'], ['organization_id']]); + for (const r of reads.filter((x) => x.object === 'acct')) expect(r.context!.tenantId).toBeDefined(); + }); +}); + +describe('rollup_never_computed names the repair that fills the function', () => { + const items: Record = { + ...ITEMS, + 'object acct': { + name: 'acct', + fields: { + deal_total: { type: 'summary', summaryOperations: { object: 'deal', function: 'sum', field: 'amount' } }, + deal_max: { type: 'summary', summaryOperations: { object: 'deal', function: 'max', field: 'amount' } }, + }, + }, + }; + it('`sum` names the plain run; `max` names `--recompute-undefined-on-empty object.field`', async () => { + const report = await run({ + engine: engineOver({ deal: [{ id: 'd1', acct_ref: 'a1', amount: 5 }], acct: [{ id: 'a1' }] }), + getItem: async (t, n) => items[`${t} ${n}`], + published: [{ type: 'object', name: 'acct' }], + }); + expect(codes(report)).toEqual([ + ['rollup_never_computed', 'warning', 'deal_total'], + ['rollup_never_computed', 'warning', 'deal_max'], + ]); + expect(report.issues[0]!.fix).toContain('`os migrate summary-nulls --apply` computes'); + expect(report.issues[0]!.fix).not.toContain('--recompute-undefined-on-empty'); + expect(report.issues[1]!.fix).toContain('`os migrate summary-nulls --apply --recompute-undefined-on-empty acct.deal_max`'); + expect(report.issues[1]!.userMessage).toContain('--recompute-undefined-on-empty'); + expect(report.issues[0]!.userMessage).not.toContain('--recompute-undefined-on-empty'); + }); +}); diff --git a/packages/metadata-protocol/src/build-probes-user-message.test.ts b/packages/metadata-protocol/src/build-probes-user-message.test.ts index face19bd449..e7a5b165b3c 100644 --- a/packages/metadata-protocol/src/build-probes-user-message.test.ts +++ b/packages/metadata-protocol/src/build-probes-user-message.test.ts @@ -66,6 +66,11 @@ const BOARD: I18nLabel = { en: 'Team board', 'zh-CN': '团队看板', de: 'Team const WIDGET: I18nLabel = { en: 'Open tasks', 'zh-CN': '未完成任务' }; const DATASET: I18nLabel = { en: 'Task totals', 'zh-CN': '任务汇总' }; const VIEW: I18nLabel = { en: 'All tasks', 'zh-CN': '全部任务' }; +const ACCOUNTS = 'Accounts'; +const DEALS = 'Deals'; +const OPEN_DEALS: I18nLabel = { en: 'Open deals', 'zh-CN': '未结交易' }; +const ACCT_REF: I18nLabel = { en: 'Customer', 'zh-CN': '客户' }; +const ERP_SYNC: I18nLabel = { en: 'ERP sync', 'zh-CN': 'ERP 同步' }; const ITEMS: Record = { 'object crm_task': { @@ -96,6 +101,31 @@ const ITEMS: Record = { widgets: [{ id: 'w_open_tasks', title: WIDGET, dataset: 'crm_bare_totals', values: ['total'] }], }, 'dataset crm_bare_totals': { name: 'crm_bare_totals', label: DATASET, measures: [{ name: 'total', aggregate: 'count' }] }, + // [#35146] A parent with a roll-up over its children, the children's + // reference back, the seed that loads them, and a flow with a connector step. + 'object crm_acct': { + name: 'crm_acct', + label: ACCOUNTS, + fields: { + title: { type: 'text', label: 'Title' }, + open_deal_count: { type: 'summary', label: OPEN_DEALS, summaryOperations: { object: 'crm_deal', function: 'count' } }, + }, + }, + 'object crm_deal': { + name: 'crm_deal', + label: DEALS, + fields: { acct_ref: { type: 'lookup', reference: 'crm_acct', label: ACCT_REF } }, + }, + 'seed crm_deal_seed': { object: 'crm_deal', records: [{ name: 'Big deal' }] }, + 'flow crm_erp_sync': { + name: 'crm_erp_sync', + label: ERP_SYNC, + nodes: [ + { id: 'start', type: 'start' }, + { id: 'push_step', type: 'connector_action', label: 'Push order', connectorConfig: { connectorId: 'erp_link', actionId: 'push' } }, + ], + edges: [{ id: 'e1', source: 'start', target: 'push_step' }], + }, }; type GetItem = RunBuildProbesOptions['getItem']; @@ -114,6 +144,45 @@ const engineThrowing: ProbeEngine = { }, }; +/** One `where` on one row: equality and `{ $in: [...] }`; any other operator or combinator is refused. */ +const matches = (row: Record, where: Record | undefined): boolean => + Object.entries(where ?? {}).every(([key, want]) => { + if (key.startsWith('$')) throw new Error(`double: combinator ${key} not implemented`); + if (!want || typeof want !== 'object') return row[key] === want; + const ops = Object.keys(want); + const $in = (want as { $in?: unknown }).$in; + if (ops.length !== 1 || !Array.isArray($in)) throw new Error(`double: operator ${ops.join(',')} not implemented`); + return $in.includes(row[key]); + }); +/** + * An engine over fixed tables: honours `where`, then `limit`, so the roll-up + * and reference probes read exactly the rows a real engine would give. + */ +const engineOver = (tables: Record>>): ProbeEngine => ({ + find: async (object, query) => { + const rows = (tables[object] ?? []).filter((r) => matches(r, (query as { where?: Record } | undefined)?.where)); + return limited(rows, query); + }, +}); +/** The automation engine's connector lookups, answering as a test says. */ +const automationAnswering = (answer: { + instance?: 'refused' | 'none'; + degraded?: string; +}): NonNullable => ({ + resolveConnectorInstanceFor: () => + answer.instance === 'refused' + ? { status: 'refused', refusal: { message: 'two packages hold the connector "erp_link".' } } + : answer.instance === 'none' ? { status: 'none' } : { status: 'instance', packageId: null }, + resolveConnectorAction: () => undefined, + getConnectorDegradedReason: () => answer.degraded, +}); +const FLOW = [{ type: 'flow', name: 'crm_erp_sync' }]; +const flowNames = (tag: PlatformLocaleTag): Names => ({ + flow: said(ERP_SYNC, tag, 'crm_erp_sync'), + step: 'Push order', + connector: 'erp_link', +}); + const analyticsReturning = (result: unknown) => ({ queryDataset: async () => result }); const analyticsThrowing = (message: string, fields: Record = {}) => ({ queryDataset: async () => { @@ -346,6 +415,58 @@ const CASES: readonly ProbeCase[] = [ // The remedy is the dataset's, so the sentence names it and not the object. silent: ['object'], }, + { + title: 'a widget whose query answers only zeros', + code: 'widget_empty_result', // adr0112-ok: D6c build-probe diagnostics code + run: probe({ analytics: analyticsReturning({ rows: [{ total: 0 }] }), published: DASHBOARD }), + params: (tag) => ({ ...widgetNames(tag), dataset: said(DATASET, tag, 'crm_task_totals') }), + hidden: ['crm_board', 'w_open_tasks', 'crm_task_totals'], + }, + { + title: 'a roll-up blank on every parent that has children', + code: 'rollup_never_computed', // adr0112-ok: D6c build-probe diagnostics code + run: probe({ + engine: engineOver({ + crm_deal: [{ id: 'd1', acct_ref: 'a1' }, { id: 'd2', acct_ref: 'a1' }], + crm_acct: [{ id: 'a1', open_deal_count: null }, { id: 'a2', open_deal_count: null }], + }), + published: [{ type: 'object', name: 'crm_acct' }], + }), + params: (tag) => ({ object: ACCOUNTS, field: said(OPEN_DEALS, tag, 'open_deal_count'), child: DEALS, cause: 'fills' }), + hidden: ['crm_acct', 'open_deal_count', 'crm_deal'], + }, + { + title: 'sample records whose reference names no record', + code: 'seed_reference_unresolved', // adr0112-ok: D6c build-probe diagnostics code + run: probe({ + engine: engineOver({ crm_deal: [{ id: 'd1', name: 'Big deal', acct_ref: 'Acme Corp' }], crm_acct: [{ id: 'a1' }] }), + seedLanded: [{ object: 'crm_deal', inserted: { ids: ['d1'] }, matched: { ids: [] } }], + published: [{ type: 'seed', name: 'crm_deal_seed' }], + }), + params: (tag) => ({ object: DEALS, field: said(ACCT_REF, tag, 'acct_ref'), target: ACCOUNTS, count: '1' }), + hidden: ['crm_deal', 'acct_ref', 'crm_acct', 'Acme Corp'], + }, + { + title: 'a flow step whose connector name two connectors share', + code: 'flow_connector_action_unresolved', // adr0112-ok: D6c build-probe diagnostics code + run: probe({ automation: automationAnswering({ instance: 'refused' }), published: FLOW }), + params: (tag) => ({ ...flowNames(tag), cause: 'refused' }), + hidden: ['crm_erp_sync', 'push_step', 'two packages hold'], + }, + { + title: 'a flow step whose connector this environment does not have', + code: 'flow_connector_action_unresolved', // adr0112-ok: D6c build-probe diagnostics code + run: probe({ automation: automationAnswering({ instance: 'none' }), published: FLOW }), + params: (tag) => ({ ...flowNames(tag), cause: 'no-action' }), + hidden: ['crm_erp_sync', 'push_step', 'push'], + }, + { + title: 'a flow step whose connector is degraded', + code: 'flow_connector_action_unresolved', // adr0112-ok: D6c build-probe diagnostics code + run: probe({ automation: automationAnswering({ degraded: 'the upstream is unreachable.' }), published: FLOW }), + params: (tag) => ({ ...flowNames(tag), cause: 'degraded' }), + hidden: ['crm_erp_sync', 'push_step', 'unreachable'], + }, { title: 'dataset widgets and no analytics service', code: 'probes_unavailable', // adr0112-ok: D6c build-probe diagnostics code diff --git a/packages/metadata-protocol/src/build-probes.ts b/packages/metadata-protocol/src/build-probes.ts index feb1269216a..266521d3718 100644 --- a/packages/metadata-protocol/src/build-probes.ts +++ b/packages/metadata-protocol/src/build-probes.ts @@ -25,7 +25,9 @@ import type { BuildProbeReport, RuntimeBuildIssue, StandardErrorCode } from '@objectstack/spec/api'; import { resolveI18nLabel, type I18nLabel } from '@objectstack/spec/ui'; -import { PackageScopedNameRefusedError, describePackageScopedHolder, type PackageScopedRefusal } from '@objectstack/core'; +import { referenceTargetOf } from '@objectstack/spec/data'; +import { collectFlowGraphs } from '@objectstack/spec/automation'; +import { PackageScopedNameRefusedError, describePackageScopedHolder, resolveTenantFieldName, type PackageScopedRefusal } from '@objectstack/core'; import { buildProbeUserMessage, buildProbeUserTextLocale } from './build-probes.user-text.js'; /** @@ -69,7 +71,11 @@ export type RuntimeBuildIssueCode = | 'widget_not_probed' | 'empty_query' | 'widget_query_failed' - | 'probes_unavailable'; + | 'probes_unavailable' + | 'widget_empty_result' + | 'rollup_never_computed' + | 'seed_reference_unresolved' + | 'flow_connector_action_unresolved'; /** * A finding as this module builds it: the wire shape, with the code closed @@ -82,6 +88,14 @@ type ProbeFinding = RuntimeBuildIssue & { code: RuntimeBuildIssueCode; userMessa /** The single read the probes need from the data engine. */ export interface ProbeEngine { find(objectName: string, query: unknown): Promise>>; + /** + * The REGISTERED object definition (the authored body plus the columns the + * engine injects), which names the column a row's organization is stamped + * in (`resolveTenantFieldName`). Optional: an engine without it is read as + * one whose rows carry no organization, so the landed-data probes ask their + * existence questions unscoped, as the reference audit does for such a row. + */ + getSchema?(objectName: string): unknown; } /** Optional analytics surface — when absent, widget probes degrade to a warning. */ @@ -127,6 +141,48 @@ export interface RunBuildProbesOptions { * sentence names; `message` and `fix` never read it. */ userTextLocales?: readonly (string | null | undefined)[]; + /** + * The kernel's automation engine, when one is mounted: the connector lookup + * a `connector_action` step dispatches through. Absent, or without the + * lookup, published flows' connector steps are not probed. + */ + automation?: ProbeAutomation; + /** + * The package the published artifacts belong to (`null`: authored in the + * environment, no package). A `connector_action` step names its connector + * from its flow's package, so the probe asks the engine for that package. + */ + packageId?: string | null; + /** + * The seed loader's own answer to "which rows did this publish's seeds + * land on" (`seedApplied.landed`, per object): the ids it created, and + * the pre-existing ids a seed key matched. The reference probe reads the + * seeds' rows by these ids. Absent, published seeds' references are not + * probed. + */ + seedLanded?: ReadonlyArray; +} + +/** One object's entry of `seedApplied.landed`, as far as the probes read it. */ +export interface SeedLandedRows { + object: string; + inserted: { ids: readonly string[] }; + matched: { ids: readonly string[] }; +} + +/** + * The slice of the automation engine (`AutomationEngine`, service-automation) + * the connector probe reads — the same two lookups the `connector_action` + * executor makes before it dispatches, and the reason it gives for a degraded + * connector. All optional: a host whose engine lacks one is not probed. + */ +export interface ProbeAutomation { + resolveConnectorInstanceFor?(connectorId: string, callerPackageId: string | null): + | { status: 'instance'; packageId: string | null } + | { status: 'refused'; refusal: { message: string } } + | { status: 'none' }; + resolveConnectorAction?(connectorId: string, actionId: string, packageId?: string | null): unknown; + getConnectorDegradedReason?(connectorId: string, packageId?: string | null): string | undefined; } type Rec = Record; @@ -220,6 +276,104 @@ async function hasRows( return Array.isArray(rows) && rows.length > 0; } +/** Rows sampled from an object by the data probes, and distinct values probed per column. */ +const PROBE_SAMPLE_ROWS = 50; + +/** The declared fields of an object body, by name, from either the map or the array shape. */ +function fieldsOf(body: Rec | undefined): Array<[string, Rec]> { + const raw = body?.fields; + if (Array.isArray(raw)) { + return raw.map(asRec).filter((f): f is Rec => !!f && typeof f.name === 'string').map((f) => [f.name as string, f]); + } + const map = asRec(raw); + return map ? Object.entries(map).flatMap(([n, f]) => (asRec(f) ? [[n, asRec(f)!] as [string, Rec]] : [])) : []; +} + +/** The id strings a reference column holds on one row: an expanded `{ id }` and a blank are not ids. */ +function idsIn(value: unknown): string[] { + return (Array.isArray(value) ? value : [value]).filter((v): v is string => typeof v === 'string' && v.length > 0); +} + +/** + * The identity a landed-data read runs under: the system (the probe judges + * data, not a caller's grants), kept inside one organization the way the + * engine's own reference audit keeps its existence probe (#19837, + * `inspectDanglingReferences`): the organization rides the context's + * `tenantId`, and the engine applies it to a tenant-scoped object and leaves an + * object with no tenant column (`sys_user`) unscoped. `null` reads unscoped, as + * the audit does for a row that carries no organization. + */ +function landedReadContext(organization: string | null): Rec { + return organization ? { isSystem: true, tenantId: organization } : { isSystem: true }; +} + +/** + * The organization column of an object as the engine registered it, or `null` + * when it has none or the engine does not say (`ProbeEngine.getSchema`). + */ +function organizationColumnOf(engine: ProbeEngine, objectName: string): string | null { + try { + return resolveTenantFieldName(engine.getSchema?.(objectName)); + } catch { + return null; + } +} + +/** + * The organization a sampled row's references are held to: the publishing + * organization when the publish names one (every read is already inside it), + * else the row's own stamped organization, else none (#19837: "a + * NULL-organization row, or an object with no tenant column, probes + * unscoped"). + */ +function rowOrganization(row: Rec, column: string | null, publishing: string | null): string | null { + if (publishing) return publishing; + const stamped = column ? row[column] : undefined; + return stamped === undefined || stamped === null || stamped === '' ? null : String(stamped); +} + +/** + * The organizations a roll-up's children are judged in, one at a time: the + * publishing organization when the publish names one; else every + * organization a bounded read of the object's rows, projected to its tenant + * column alone, finds stamped; else (no tenant column, or the engine does not + * say) one unscoped pass, `null`. On an object that has a tenant column, a + * row stamped with no organization is not judged: an unscoped pass there would + * read every organization's rows together. + */ +async function probeOrganizations(engine: ProbeEngine, objectName: string, publishing: string | null): Promise> { + if (publishing) return [publishing]; + const column = organizationColumnOf(engine, objectName); + if (!column) return [null]; + const stamped = asArr(await engine.find(objectName, { + fields: [column], + limit: PROBE_SAMPLE_ROWS, + context: landedReadContext(null), + })).map(asRec).map((r) => rowOrganization(r ?? {}, column, null)); + return [...new Set(stamped)].filter((o): o is string => o !== null); +} + +/** Push `value` under `key` in a map of lists. */ +function pushTo(map: Map, key: K, value: V): void { + const list = map.get(key); + if (list) list.push(value); + else map.set(key, [value]); +} + +/** A measure value that renders as an empty card: no value, or zero. */ +const isZeroish = (v: unknown): boolean => v === null || v === undefined || v === 0 || v === '0'; + +/** + * Every measure the result carries reads zero or nothing on every row. Judged + * only on the measure columns the rows actually hold: a result that names none + * of the asked measures cannot be judged, and answers `false`. + */ +function everyMeasureZero(rows: unknown[], measures: readonly string[]): boolean { + const recs = rows.map(asRec).filter((r): r is Rec => !!r); + const visible = measures.filter((m) => recs.some((r) => m in r)); + return visible.length > 0 && recs.every((r) => visible.every((m) => isZeroish(r[m]))); +} + /** * Run the L3 runtime probes over a just-published artifact set: * @@ -533,6 +687,224 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise !!r); + const ids = [...new Set(children.flatMap((c) => + childField && (c[childField] === null || c[childField] === undefined) ? [] : idsIn(c[fk])))]; + if (ids.length === 0) continue; + const parents = asArr(await engine.find(p.name, { + where: { id: { $in: ids } }, + fields: ['id', fieldName], + limit: ids.length, + context: landedReadContext(organization), + })).map(asRec).filter((r): r is Rec => !!r); + if (parents.length > 0 && parents.every((r) => r[fieldName] === null || r[fieldName] === undefined)) { + blank = parents; + break; + } + } + if (!blank) continue; + // [#15064] The plain run fills `count` and `sum` only; a `min`, + // `max` or `avg` roll-up is recomputed only when it is named. + const fillsByDefault = ops.function === 'count' || ops.function === 'sum'; + const command = fillsByDefault + ? '`os migrate summary-nulls --apply`' + : `\`os migrate summary-nulls --apply --recompute-undefined-on-empty ${p.name}.${fieldName}\``; + issues.push({ + layer: 'runtime', + severity: 'warning', + artifact: { type: 'object', name: p.name }, + ref: { type: 'object', name: p.name, member: fieldName }, + code: 'rollup_never_computed', + message: + `Roll-up "${p.name}.${fieldName}" is empty on all ${blank.length} parent row(s) of one organization that have ` + + `"${childObject}" children — the field is configured, but its stored value was never computed for them. A ` + + 'roll-up is written when a parent is inserted, when a child write names the parent, by `os migrate ' + + 'summary-nulls`, and by the install door that adds it; one declared after its children landed reaches none ' + + 'of these on its own.', + fix: + `Check that "${childObject}" rows carry "${fk}" back to "${p.name}", then fill the stored values: ` + + `${command} computes every parent that still reads blank` + + (fillsByDefault ? '' : ` (a ${String(ops.function)} roll-up is filled only when named this way)`) + + '. A package install or upgrade materialises a roll-up it adds at the install door, and a write to a ' + + 'child recomputes the parent that child names. Do not present the figure as working while it reads blank.', + userMessage: say('rollup_never_computed', { + object: labelIn(body, p.name), + field: labelIn(def, fieldName), + child: await labelOf('object', childObject), + cause: fillsByDefault ? 'fills' : 'named', + }), + }); + } catch { + // A read the engine refused is not a roll-up that never ran: + // nothing is judged. + } + } + } + + // ── Seed references: a reference column must name rows that exist ────── + // + // [#35146] The seed loader resolves what it can and reports the rest on + // `seedApplied`; this is the backstop over what LANDED. A seed load is a + // system write, which the engine does not check for references, so a value + // naming no row lands unchallenged and stays: an edit of the record later + // is not refused for it (#29062: the write check judges only the references + // a write ADDS). The finding is the column naming nothing, not a refusal + // the person will meet; the operator's reference audit + // (`inspectDanglingReferences`) reports the same rows later. + // + // The rows judged are the SEED's own: the ids the loader reports it landed + // (`seedApplied.landed`), read by `id`, so no row the loader did not land + // is matched, judged or quoted. Those it created always; those a seed key + // matched only when the seed's mode wrote them (`upsert`, `update`): under + // `ignore` a matched row was left as its writer left it, and may be a + // customer's. `landed` is per object, so two seeds of one object in one + // publish are judged over the object's landed rows together. + // + // Why this is not `ObjectQL.inspectDanglingReferences`: that audit reads + // the first rows of the whole object (no row filter, so it cannot read the + // seed's own), and asks one existence probe per value. Here each column's + // values are pushed into one `id $in` read per organization, projected to + // `id`, under the audit's scope (#19837): the publishing organization when + // the publish names one, else each value judged inside the organization + // its row is stamped with (unscoped for a row with none). One residual is + // stated, not hidden: under a `group` tenancy posture the audit leaves its + // probe unscoped, because the write rule's reach is the writer's + // membership set; this probe stays inside the row's own organization, so a + // seed row that names a row of a sibling organization would be reported. + // A seed loads into one organization and resolves its references there. + const landedByObject = new Map((opts.seedLanded ?? []).map((l) => [l.object, l] as const)); + for (const p of published.filter((x) => x.type === 'seed')) { + const seed = asRec(await readItem('seed', p.name)); + const objectName = typeof seed?.object === 'string' ? seed.object : undefined; + if (!objectName) continue; + const landed = landedByObject.get(objectName); + if (!landed) continue; + const mode = typeof seed?.mode === 'string' ? seed.mode : 'ignore'; + const ids = [...new Set([ + ...asArr(landed.inserted?.ids), + ...(mode === 'upsert' || mode === 'update' ? asArr(landed.matched?.ids) : []), + ].filter((id): id is string => typeof id === 'string' && id !== ''))].slice(0, PROBE_SAMPLE_ROWS); + if (ids.length === 0) continue; + const objectBody = asRec(await readItem('object', objectName)); + const refFields = fieldsOf(objectBody).flatMap(([name, def]) => { + let target: string | undefined; + try { + target = referenceTargetOf(def); + } catch { + target = undefined; + } + return target ? [{ name, def, target }] : []; + }); + if (refFields.length === 0) continue; + const orgColumn = organizationId ? null : organizationColumnOf(engine, objectName); + let rows: Rec[]; + try { + rows = asArr(await engine.find(objectName, { + where: { id: { $in: ids } }, + fields: [...new Set(['id', ...refFields.map((f) => f.name), ...(orgColumn ? [orgColumn] : [])])], + limit: ids.length, + context: landedReadContext(organizationId ?? null), + })).map(asRec).filter((r): r is Rec => !!r); + } catch { + continue; + } + for (const { name: field, def, target } of refFields) { + const byOrganization = new Map(); + for (const r of rows) { + for (const v of idsIn(r[field])) pushTo(byOrganization, rowOrganization(r, orgColumn, organizationId ?? null), v); + } + if (byOrganization.size === 0) continue; + const missing: string[] = []; + try { + for (const [organization, list] of byOrganization) { + const values = [...new Set(list)]; + const existing = asArr(await engine.find(target, { + where: { id: { $in: values } }, + fields: ['id'], + limit: values.length, + context: landedReadContext(organization), + })).map(asRec); + const found = new Set(existing.map((r) => String(r?.id ?? r?._id))); + missing.push(...values.filter((v) => !found.has(v))); + } + } catch { + continue; + } + const distinct = [...new Set(missing)]; + if (distinct.length === 0) continue; + // The values quoted are the landed rows' own column; nothing of + // the target is read beyond its `id`. + const shown = distinct.slice(0, 5).map((v) => `"${v}"`).join(', '); + issues.push({ + layer: 'runtime', + severity: 'warning', + artifact: { type: 'seed', name: p.name }, + ref: { type: 'object', name: objectName, member: field }, + code: 'seed_reference_unresolved', + message: + `Reference column "${objectName}.${field}" holds ${distinct.length} value(s) on the rows the seed landed that ` + + `name no "${target}" row in their organization: ${shown}${distinct.length > 5 ? ', …' : ''}. The rows landed ` + + 'as a system write, which is not checked for references, so they point at nothing.', + fix: + `Point "${objectName}.${field}" on those rows at real "${target}" records (in the seed, by a value the loader ` + + 'resolves), or clear it, then republish the seed.', + userMessage: say('seed_reference_unresolved', { + object: labelIn(objectBody, objectName), + field: labelIn(def, field), + target: await labelOf('object', target), + count: String(distinct.length), + }), + }); + } + } + // ── Dashboard widgets: the real dataset selection must return data ────── const dashboards = published.filter((x) => x.type === 'dashboard'); let widgetsToProbe = 0; @@ -619,6 +991,31 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise x.type === 'flow')) { + const body = asRec(await readItem('flow', p.name)); + if (!body) continue; + let graphs: ReturnType; + try { + graphs = collectFlowGraphs(body as Parameters[0]); + } catch { + continue; + } + for (const node of graphs.flatMap((g) => g.nodes as readonly unknown[]).map(asRec)) { + if (!node || node.type !== 'connector_action') continue; + const cfg = asRec(node.connectorConfig); + const connectorId = typeof cfg?.connectorId === 'string' ? cfg.connectorId : undefined; + const actionId = typeof cfg?.actionId === 'string' ? cfg.actionId : undefined; + if (!connectorId || !actionId) continue; // the schema's refusal, not a probe's + const nodeId = typeof node.id === 'string' ? node.id : 'connector_action'; + let cause: 'refused' | 'no-action' | 'degraded' | undefined; + let why = ''; + try { + const instance = typeof automation.resolveConnectorInstanceFor === 'function' + ? automation.resolveConnectorInstanceFor(connectorId, callerPackageId) + : ({ status: 'instance', packageId: callerPackageId } as const); + if (instance.status === 'refused') { + cause = 'refused'; + why = instance.refusal.message; + } else { + const packageId = instance.status === 'instance' ? instance.packageId : undefined; + const handler = packageId === undefined ? undefined : automation.resolveConnectorAction(connectorId, actionId, packageId); + if (!handler) { + const degraded = packageId === undefined ? undefined : automation.getConnectorDegradedReason?.(connectorId, packageId); + cause = degraded ? 'degraded' : 'no-action'; + why = degraded + ? `connector "${connectorId}" is degraded — ${degraded.replace(/\.\s*$/, '')}` + : `no connector on this environment serves "${connectorId}.${actionId}"`; + } + } + } catch { + continue; // a lookup that threw judges nothing + } + if (!cause) continue; + issues.push({ + layer: 'runtime', + severity: 'warning', + artifact: { type: 'flow', name: p.name }, + ref: { type: 'connector', name: connectorId, member: actionId }, + code: 'flow_connector_action_unresolved', + message: + `Flow "${p.name}" step "${nodeId}" (connector_action) dispatches "${connectorId}.${actionId}", but ${why} — ` + + 'every run that reaches the step fails.', + fix: cause === 'degraded' + ? `Resolve what keeps connector "${connectorId}" degraded (its upstream or its credential), then re-run the flow.` + : cause === 'refused' + ? `Make "${connectorId}" name one connector from this flow's package (declare the dependency, or hold the connector in the package), then republish.` + : `Point the step's connectorConfig at a connector and action this environment has, or install the package or plugin that provides "${connectorId}".`, + userMessage: say('flow_connector_action_unresolved', { + flow: labelIn(body, p.name), + step: labelIn(node, nodeId), + connector: connectorId, + cause, + }), + }); + } + } + } + return { issues, checked }; } + +/** + * The one field on a child object that points back at `parent`, the + * foreign key a roll-up resolves when it names no `relationshipField`: + * a `master_detail` or `lookup` whose target is the parent. Two such fields + * leave the engine to refuse, so the probe judges neither. + */ +function childForeignKey(child: Rec | undefined, parent: string): string | undefined { + const candidates = fieldsOf(child).filter(([, def]) => { + if (def.type !== 'master_detail' && def.type !== 'lookup') return false; + try { + return referenceTargetOf(def) === parent; + } catch { + return false; + } + }); + return candidates.length === 1 ? candidates[0][0] : undefined; +} diff --git a/packages/metadata-protocol/src/build-probes.user-text.ts b/packages/metadata-protocol/src/build-probes.user-text.ts index b0fa7dd7647..e095b09719e 100644 --- a/packages/metadata-protocol/src/build-probes.user-text.ts +++ b/packages/metadata-protocol/src/build-probes.user-text.ts @@ -47,6 +47,10 @@ * | `empty_query` | `dashboard`, `widget`, `dataset`, `object` | all four by label | * | `widget_query_failed` | `dashboard`, `widget`, `dataset`, `object`, `cause` (`access` · `field-access` · `unavailable` · `query`) | dashboard, widget and dataset by label; `object` by label for `query`, and by the API name the refusal names for `access` · `field-access` · `unavailable` (the caller was not admitted to it, so nothing of it is read); empty when there is none | * | `probes_unavailable` | `count` | no name: one finding covers every dashboard of the publish | + * | `widget_empty_result` | `dashboard`, `widget`, `dataset` | all three by label | + * | `rollup_never_computed` | `object`, `field`, `child`, `cause` (`fills` · `named`) | the parent object, the roll-up field and the child object by label | + * | `seed_reference_unresolved` | `object`, `field`, `target`, `count` | the seeded object, its reference field and the target object by label | + * | `flow_connector_action_unresolved` | `flow`, `step`, `connector`, `cause` (`refused` · `no-action` · `degraded`) | flow and step by label; the connector by its name (the step names it so) | * * A label is the published body's own (`label`, a widget's `title`), read * through the probe's item reader and resolved for the sentence's locale. An @@ -842,6 +846,249 @@ const PROBES_UNAVAILABLE: UserTextEntry = { `게시된 각 대시보드를 열어 위젯이 로드되는지 확인하세요.`, }; +/** `widget_empty_result`: the widget's real query answered only zeros, so the card shows an empty "0" tile. */ +const WIDGET_EMPTY_RESULT: UserTextEntry = { + en: (p) => + `${WIDGET_ON_DASHBOARD.en(p)} shows only zeros: its data source "${p.dataset}" has nothing to count right now. ` + + `If that is not expected, check the records it reads (their dates and values), then publish again.`, + 'zh-Hans': (p) => + `${WIDGET_ON_DASHBOARD['zh-Hans'](p)}只显示 0:它的数据源“${p.dataset}”目前没有可统计的内容。` + + `如果这不符合预期,请检查它读取的记录(日期和数值),然后重新发布。`, + 'zh-Hant': (p) => + `${WIDGET_ON_DASHBOARD['zh-Hant'](p)}只顯示 0:它的資料來源「${p.dataset}」目前沒有可統計的內容。` + + `如果這不符合預期,請檢查它讀取的記錄(日期和數值),然後重新發布。`, + es: (p) => + `${WIDGET_ON_DASHBOARD.es(p)} solo muestra ceros: su origen de datos "${p.dataset}" no tiene nada que contar ` + + `por ahora. Si no es lo esperado, revise los registros que lee (sus fechas y valores) y vuelva a publicar.`, + ar: (p) => + `${WIDGET_ON_DASHBOARD.ar(p)} لا يعرض سوى أصفار: مصدر بياناته "${p.dataset}" لا يحتوي حاليًا على ما يمكن ` + + `احتسابه. إذا لم يكن ذلك متوقعًا، فراجع السجلات التي يقرؤها (تواريخها وقيمها) ثم أعد النشر.`, + fr: (p) => + `${WIDGET_ON_DASHBOARD.fr(p)} n’affiche que des zéros : sa source de données « ${p.dataset} » n’a rien à ` + + `compter pour l’instant. Si ce n’est pas attendu, vérifiez les enregistrements qu’il lit (leurs dates et ` + + `valeurs), puis publiez à nouveau.`, + 'pt-BR': (p) => + `${WIDGET_ON_DASHBOARD['pt-BR'](p)} mostra apenas zeros: sua fonte de dados "${p.dataset}" não tem nada a ` + + `contar no momento. Se isso não for o esperado, verifique os registros que ele lê (datas e valores) e publique novamente.`, + ru: (p) => + `${WIDGET_ON_DASHBOARD.ru(p)} показывает только нули: в его источнике данных «${p.dataset}» сейчас нечего ` + + `считать. Если это неожиданно, проверьте записи, которые он читает (их даты и значения), и опубликуйте снова.`, + de: (p) => + `${WIDGET_ON_DASHBOARD.de(p)} zeigt nur Nullen: Seine Datenquelle „${p.dataset}“ hat derzeit nichts zu zählen. ` + + `Wenn das nicht erwartet ist, prüfen Sie die Datensätze, die es liest (Datumswerte und Werte), und ` + + `veröffentlichen Sie dann erneut.`, + ja: (p) => + `${WIDGET_ON_DASHBOARD.ja(p)}は 0 しか表示していません。データソース「${p.dataset}」には現在集計する内容がありません。` + + `想定外の場合は、読み取るレコード(日付と値)を確認してから、もう一度公開してください。`, + ko: (p) => + `${WIDGET_ON_DASHBOARD.ko(p)}에 0만 표시됩니다. 데이터 소스 "${p.dataset}"에 현재 집계할 내용이 없습니다. ` + + `예상과 다르다면 읽어 오는 레코드(날짜와 값)를 확인한 후 다시 게시하세요.`, +}; + +/** `rollup_never_computed`: a roll-up field reads blank on every record that has related records; `cause` `named` is a min, max or avg roll-up, which the plain run does not fill. */ +const ROLLUP_NEVER_COMPUTED: UserTextEntry = { + en: (p) => + `The roll-up field "${p.field}" on "${p.object}" is blank on every record that has related "${p.child}" ` + + `records: its stored value was never calculated for them. ` + + (p.cause === 'named' + ? `Ask whoever runs this environment to recalculate it by name (\`os migrate summary-nulls --apply --recompute-undefined-on-empty\`, naming this field): a minimum, ` + + `maximum or average roll-up is not filled by the plain recalculation.` + : `Ask whoever runs this environment to recalculate the roll-ups (\`os migrate summary-nulls --apply\`).`), + 'zh-Hans': (p) => + `“${p.object}”的汇总字段“${p.field}”在每条有相关“${p.child}”记录的记录上都是空的:它的存储值从未为这些记录计算过。` + + (p.cause === 'named' + ? `请让负责此环境的人按名称重新计算它(\`os migrate summary-nulls --apply --recompute-undefined-on-empty\`,并指明此字段):最小值、最大值或平均值汇总不会被普通的重新计算填充。` + : `请让负责此环境的人重新计算汇总字段(\`os migrate summary-nulls --apply\`)。`), + 'zh-Hant': (p) => + `「${p.object}」的匯總欄位「${p.field}」在每筆有相關「${p.child}」記錄的記錄上都是空的:它的儲存值從未為這些記錄計算過。` + + (p.cause === 'named' + ? `請讓負責此環境的人按名稱重新計算它(\`os migrate summary-nulls --apply --recompute-undefined-on-empty\`,並指明此欄位):最小值、最大值或平均值匯總不會被一般的重新計算填入。` + : `請讓負責此環境的人重新計算匯總欄位(\`os migrate summary-nulls --apply\`)。`), + es: (p) => + `El campo de resumen "${p.field}" de "${p.object}" está vacío en todos los registros que tienen registros ` + + `relacionados de "${p.child}": su valor almacenado nunca se calculó para ellos. ` + + (p.cause === 'named' + ? `Pida a quien administra este entorno que lo recalcule por nombre (\`os migrate summary-nulls --apply --recompute-undefined-on-empty\`, indicando este campo): ` + + `un resumen de mínimo, máximo o promedio no se rellena con el recálculo normal.` + : `Pida a quien administra este entorno que recalcule los resúmenes (\`os migrate summary-nulls --apply\`).`), + ar: (p) => + `حقل التجميع "${p.field}" في "${p.object}" فارغ في كل سجل له سجلات "${p.child}" مرتبطة: لم تُحسب قيمته المخزنة لها قط. ` + + (p.cause === 'named' + ? `اطلب من مسؤول هذه البيئة إعادة حسابه بالاسم (\`os migrate summary-nulls --apply --recompute-undefined-on-empty\` مع تسمية هذا الحقل): ` + + `حقل تجميع الحد الأدنى أو الأقصى أو المتوسط لا تملؤه إعادة الحساب العادية.` + : `اطلب من مسؤول هذه البيئة إعادة حساب حقول التجميع (\`os migrate summary-nulls --apply\`).`), + fr: (p) => + `Le champ de synthèse « ${p.field} » de « ${p.object} » est vide sur chaque enregistrement qui a des ` + + `enregistrements « ${p.child} » liés : sa valeur stockée n’a jamais été calculée pour eux. ` + + (p.cause === 'named' + ? `Demandez à la personne qui gère cet environnement de le recalculer nommément (\`os migrate summary-nulls --apply --recompute-undefined-on-empty\`, en nommant ce ` + + `champ) : une synthèse minimum, maximum ou moyenne n’est pas remplie par le recalcul ordinaire.` + : `Demandez à la personne qui gère cet environnement de recalculer les synthèses (\`os migrate summary-nulls --apply\`).`), + 'pt-BR': (p) => + `O campo de resumo "${p.field}" de "${p.object}" está vazio em todos os registros que têm registros ` + + `relacionados de "${p.child}": seu valor armazenado nunca foi calculado para eles. ` + + (p.cause === 'named' + ? `Peça a quem administra este ambiente que o recalcule pelo nome (\`os migrate summary-nulls --apply --recompute-undefined-on-empty\`, indicando este campo): ` + + `um resumo de mínimo, máximo ou média não é preenchido pelo recálculo comum.` + : `Peça a quem administra este ambiente que recalcule os resumos (\`os migrate summary-nulls --apply\`).`), + ru: (p) => + `Сводное поле «${p.field}» объекта «${p.object}» пустое во всех записях, у которых есть связанные записи ` + + `«${p.child}»: его сохранённое значение для них ни разу не рассчитывалось. ` + + (p.cause === 'named' + ? `Попросите администратора этой среды пересчитать его по имени (\`os migrate summary-nulls --apply --recompute-undefined-on-empty\` с указанием этого поля): ` + + `сводное поле минимума, максимума или среднего обычный пересчёт не заполняет.` + : `Попросите администратора этой среды пересчитать сводные поля (\`os migrate summary-nulls --apply\`).`), + de: (p) => + `Das Rollup-Feld „${p.field}“ in „${p.object}“ ist bei jedem Datensatz mit verknüpften „${p.child}“-Datensätzen ` + + `leer: Sein gespeicherter Wert wurde für sie nie berechnet. ` + + (p.cause === 'named' + ? `Bitten Sie die Person, die diese Umgebung betreibt, es namentlich neu zu berechnen (\`os migrate summary-nulls --apply --recompute-undefined-on-empty\` mit diesem ` + + `Feld): Ein Minimum-, Maximum- oder Durchschnitts-Rollup füllt die normale Neuberechnung nicht.` + : `Bitten Sie die Person, die diese Umgebung betreibt, die Rollups neu zu berechnen (\`os migrate summary-nulls --apply\`).`), + ja: (p) => + `「${p.object}」の積み上げ集計項目「${p.field}」は、関連する「${p.child}」レコードを持つすべてのレコードで空です。` + + `保存値がこれらのレコードについて一度も計算されていません。` + + (p.cause === 'named' + ? `この環境の管理者に、この項目を指定した再計算(\`os migrate summary-nulls --apply --recompute-undefined-on-empty\`)を依頼してください。` + + `最小・最大・平均の集計は通常の再計算では埋まりません。` + : `この環境の管理者に集計の再計算(\`os migrate summary-nulls --apply\`)を依頼してください。`), + ko: (p) => + `"${p.object}"의 롤업 필드 "${p.field}"가 관련 "${p.child}" 레코드가 있는 모든 레코드에서 비어 있습니다. ` + + `저장된 값이 이 레코드들에 대해 한 번도 계산되지 않았습니다. ` + + (p.cause === 'named' + ? `이 환경의 관리자에게 이 필드를 지정한 재계산(\`os migrate summary-nulls --apply --recompute-undefined-on-empty\`)을 요청하세요. ` + + `최소·최대·평균 롤업은 일반 재계산으로 채워지지 않습니다.` + : `이 환경의 관리자에게 롤업 재계산(\`os migrate summary-nulls --apply\`)을 요청하세요.`), +}; + +/** `seed_reference_unresolved`: sample records point at records that do not exist. */ +const SEED_REFERENCE_UNRESOLVED: UserTextEntry = { + en: (p) => + `Some sample "${p.object}" records (${p.count} value(s) in "${p.field}") point to "${p.target}" records that ` + + `do not exist, so on those records "${p.field}" leads nowhere. Fix or clear "${p.field}" in the sample data, ` + + `then publish again.`, + 'zh-Hans': (p) => + `部分“${p.object}”示例记录(“${p.field}”中有 ${p.count} 个值)指向不存在的“${p.target}”记录,因此这些记录上的“${p.field}”指向空处。` + + `请在示例数据中修正或清空“${p.field}”,然后重新发布。`, + 'zh-Hant': (p) => + `部分「${p.object}」示例記錄(「${p.field}」中有 ${p.count} 個值)指向不存在的「${p.target}」記錄,因此這些記錄上的「${p.field}」指向空處。` + + `請在示例資料中修正或清空「${p.field}」,然後重新發布。`, + es: (p) => + `Algunos registros de ejemplo de "${p.object}" (${p.count} valor(es) en "${p.field}") apuntan a registros de ` + + `"${p.target}" que no existen, así que en esos registros "${p.field}" no lleva a ninguna parte. Corrija o vacíe ` + + `"${p.field}" en los datos de ejemplo y vuelva a publicar.`, + ar: (p) => + `بعض سجلات "${p.object}" التجريبية (${p.count} قيمة في "${p.field}") تشير إلى سجلات "${p.target}" غير موجودة، ` + + `لذلك لا يؤدي "${p.field}" في هذه السجلات إلى أي مكان. صحّح "${p.field}" في البيانات التجريبية أو أفرغه، ثم أعد النشر.`, + fr: (p) => + `Certains enregistrements d’exemple « ${p.object} » (${p.count} valeur(s) dans « ${p.field} ») pointent vers ` + + `des enregistrements « ${p.target} » inexistants : sur ces enregistrements, « ${p.field} » ne mène nulle part. ` + + `Corrigez ou videz « ${p.field} » dans les données d’exemple, puis publiez à nouveau.`, + 'pt-BR': (p) => + `Alguns registros de exemplo de "${p.object}" (${p.count} valor(es) em "${p.field}") apontam para registros de ` + + `"${p.target}" que não existem, então nesses registros "${p.field}" não leva a lugar nenhum. Corrija ou limpe ` + + `"${p.field}" nos dados de exemplo e publique novamente.`, + ru: (p) => + `Некоторые примеры записей «${p.object}» (значений в поле «${p.field}»: ${p.count}) ссылаются на ` + + `несуществующие записи «${p.target}», поэтому в этих записях «${p.field}» никуда не ведёт. Исправьте или ` + + `очистите «${p.field}» в примерах данных и опубликуйте снова.`, + de: (p) => + `Einige Beispieldatensätze von „${p.object}“ (${p.count} Wert(e) in „${p.field}“) verweisen auf „${p.target}“-` + + `Datensätze, die nicht existieren, sodass „${p.field}“ bei diesen Datensätzen ins Leere führt. Korrigieren oder ` + + `leeren Sie „${p.field}“ in den Beispieldaten und veröffentlichen Sie dann erneut.`, + ja: (p) => + `「${p.object}」のサンプルレコードの一部(「${p.field}」の値 ${p.count} 件)が存在しない「${p.target}」レコードを参照しているため、` + + `それらのレコードの「${p.field}」はどこにもつながりません。サンプルデータの「${p.field}」を修正するか空にしてから、もう一度公開してください。`, + ko: (p) => + `일부 "${p.object}" 샘플 레코드("${p.field}"의 값 ${p.count}개)가 존재하지 않는 "${p.target}" 레코드를 가리키므로 ` + + `해당 레코드의 "${p.field}"는 아무 곳으로도 연결되지 않습니다. 샘플 데이터에서 "${p.field}"를 수정하거나 비운 후 다시 게시하세요.`, +}; + +/** + * `flow_connector_action_unresolved`: a flow step calls a connector this + * environment cannot use — two candidates or none in reach (`refused`), no such + * connector or action (`no-action`), or the connector is down (`degraded`). + */ +const FLOW_CONNECTOR_ACTION_UNRESOLVED: UserTextEntry = { + en: (p) => + `The step "${p.step}" in automation "${p.flow}" calls the connector "${p.connector}", ` + + (p.cause === 'degraded' + ? `which is not working right now, so the automation stops at that step until the connector is fixed.` + : p.cause === 'refused' + ? `but more than one connector, or none this app may use, has that name, so the automation stops at that step every time.` + : `which this environment does not have, so the automation stops at that step every time. Install the connector, or change the step.`), + 'zh-Hans': (p) => + `自动化“${p.flow}”中的步骤“${p.step}”调用了连接器“${p.connector}”,` + + (p.cause === 'degraded' + ? `但该连接器目前无法工作,所以在修复之前自动化会停在这一步。` + : p.cause === 'refused' + ? `但有多个同名连接器,或者没有本应用可用的同名连接器,所以自动化每次都会停在这一步。` + : `但当前环境没有这个连接器,所以自动化每次都会停在这一步。请安装该连接器,或修改这一步。`), + 'zh-Hant': (p) => + `自動化「${p.flow}」中的步驟「${p.step}」呼叫了連接器「${p.connector}」,` + + (p.cause === 'degraded' + ? `但該連接器目前無法運作,所以在修復之前自動化會停在這一步。` + : p.cause === 'refused' + ? `但有多個同名連接器,或沒有本應用可用的同名連接器,所以自動化每次都會停在這一步。` + : `但目前環境沒有這個連接器,所以自動化每次都會停在這一步。請安裝該連接器,或修改這一步。`), + es: (p) => + `El paso "${p.step}" de la automatización "${p.flow}" llama al conector "${p.connector}", ` + + (p.cause === 'degraded' + ? `que ahora no funciona, así que la automatización se detiene en ese paso hasta que se repare.` + : p.cause === 'refused' + ? `pero hay más de un conector con ese nombre, o ninguno que esta aplicación pueda usar, así que la automatización se detiene en ese paso cada vez.` + : `que este entorno no tiene, así que la automatización se detiene en ese paso cada vez. Instale el conector o cambie el paso.`), + ar: (p) => + `الخطوة "${p.step}" في الأتمتة "${p.flow}" تستدعي الموصل "${p.connector}"، ` + + (p.cause === 'degraded' + ? `وهو لا يعمل حاليًا، لذلك تتوقف الأتمتة عند هذه الخطوة حتى يتم إصلاحه.` + : p.cause === 'refused' + ? `لكن هناك أكثر من موصل بهذا الاسم، أو لا يوجد موصل يمكن لهذا التطبيق استخدامه، لذلك تتوقف الأتمتة عند هذه الخطوة في كل مرة.` + : `وهو غير موجود في هذه البيئة، لذلك تتوقف الأتمتة عند هذه الخطوة في كل مرة. ثبّت الموصل أو غيّر الخطوة.`), + fr: (p) => + `L’étape « ${p.step} » de l’automatisation « ${p.flow} » appelle le connecteur « ${p.connector} », ` + + (p.cause === 'degraded' + ? `qui ne fonctionne pas pour le moment : l’automatisation s’arrête à cette étape jusqu’à sa réparation.` + : p.cause === 'refused' + ? `mais plusieurs connecteurs portent ce nom, ou aucun que cette application peut utiliser : l’automatisation s’arrête à cette étape à chaque fois.` + : `que cet environnement n’a pas : l’automatisation s’arrête à cette étape à chaque fois. Installez le connecteur ou modifiez l’étape.`), + 'pt-BR': (p) => + `A etapa "${p.step}" da automação "${p.flow}" chama o conector "${p.connector}", ` + + (p.cause === 'degraded' + ? `que não está funcionando agora, então a automação para nessa etapa até que ele seja corrigido.` + : p.cause === 'refused' + ? `mas há mais de um conector com esse nome, ou nenhum que este aplicativo possa usar, então a automação para nessa etapa toda vez.` + : `que este ambiente não tem, então a automação para nessa etapa toda vez. Instale o conector ou altere a etapa.`), + ru: (p) => + `Шаг «${p.step}» автоматизации «${p.flow}» вызывает коннектор «${p.connector}», ` + + (p.cause === 'degraded' + ? `который сейчас не работает, поэтому автоматизация останавливается на этом шаге, пока его не исправят.` + : p.cause === 'refused' + ? `но коннекторов с таким именем несколько или нет ни одного, доступного этому приложению, поэтому автоматизация каждый раз останавливается на этом шаге.` + : `которого нет в этой среде, поэтому автоматизация каждый раз останавливается на этом шаге. Установите коннектор или измените шаг.`), + de: (p) => + `Der Schritt „${p.step}“ in der Automatisierung „${p.flow}“ ruft den Connector „${p.connector}“ auf, ` + + (p.cause === 'degraded' + ? `der gerade nicht funktioniert, daher hält die Automatisierung an diesem Schritt an, bis er behoben ist.` + : p.cause === 'refused' + ? `aber es gibt mehrere Connectoren mit diesem Namen oder keinen, den diese App verwenden darf, daher hält die Automatisierung jedes Mal an diesem Schritt an.` + : `den diese Umgebung nicht hat, daher hält die Automatisierung jedes Mal an diesem Schritt an. Installieren Sie den Connector oder ändern Sie den Schritt.`), + ja: (p) => + `自動化「${p.flow}」のステップ「${p.step}」はコネクタ「${p.connector}」を呼び出しますが、` + + (p.cause === 'degraded' + ? `このコネクタは現在動作していないため、修正されるまで自動化はこのステップで止まります。` + : p.cause === 'refused' + ? `この名前のコネクタが複数あるか、このアプリで使えるものがないため、自動化は毎回このステップで止まります。` + : `この環境にはこのコネクタがないため、自動化は毎回このステップで止まります。コネクタをインストールするか、ステップを変更してください。`), + ko: (p) => + `자동화 "${p.flow}"의 단계 "${p.step}"가 커넥터 "${p.connector}"를 호출하지만, ` + + (p.cause === 'degraded' + ? `이 커넥터가 현재 작동하지 않아 수정될 때까지 자동화가 이 단계에서 멈춥니다.` + : p.cause === 'refused' + ? `같은 이름의 커넥터가 여러 개이거나 이 앱에서 사용할 수 있는 것이 없어 자동화가 매번 이 단계에서 멈춥니다.` + : `이 환경에는 해당 커넥터가 없어 자동화가 매번 이 단계에서 멈춥니다. 커넥터를 설치하거나 단계를 변경하세요.`), +}; + /** * Every probe code's sentences. Typed by the probe's own code union, so a * code added to `RuntimeBuildIssueCode` without sentences does not compile. @@ -855,6 +1102,10 @@ export const BUILD_PROBE_USER_TEXT: Readonly readonly string[] | undefined; } /** The body of `ObjectStackProtocolImplementation#restoredBodyDerivation`; the method's docblock there is its contract. */ @@ -319,7 +321,7 @@ export function withTargetFoldedWithout( * The members {@link judgeRuntimeAuthoringRules} reads: the host facts and * collections every judgement of the shared rules is made against. */ -type RuntimeRulesHost = Pick; +type RuntimeRulesHost = Pick; /** The body of `ObjectStackProtocolImplementation#assertRuntimeAuthoringRules`; the method's docblock there is its contract. */ export async function assertRuntimeAuthoringRules( @@ -607,6 +609,11 @@ export async function judgeRuntimeAuthoringRules( // gate stays pure. const rlsMembershipResolverKeys = this.rlsMembershipResolverKeys(); + // The automation engine's node-type vocabulary, stated only once the engine + // has sealed it — a host fact of the same kind, read here per publish, on a + // flow write only, and passed in so the gate stays pure. + const flowNodeTypeVocabulary = singular === 'flow' ? this.sealedFlowNodeTypeVocabulary() : undefined; + // [#26188] Is a hierarchy resolver mounted — a host fact of the same kind, // read here per publish and passed in so the gate stays pure. const hierarchyResolverMounted = this.hierarchyResolverMounted(); @@ -656,6 +663,8 @@ export async function judgeRuntimeAuthoringRules( // [#25234] The resolver's keys, read per publish; with them the // gate judges who owns each membership key. ...(rlsMembershipResolverKeys !== undefined ? { rlsMembershipResolverKeys } : {}), + // With it the gate refuses a flow node no executor of this deployment runs. + ...(flowNodeTypeVocabulary !== undefined ? { flowNodeTypeVocabulary } : {}), // [#26188] With it the gate refuses a hierarchy scope no resolver enforces. ...(hierarchyResolverMounted !== undefined ? { hierarchyResolverMounted } : {}), // [#28448] With it the gate refuses a rule copy that changes what the package owns. @@ -870,3 +879,37 @@ export async function draftPublishJudgement( } return { refusals: told.length > 0 ? [...told, ...issues] : issues, advisories: verdict.advisories }; } + +/** + * [#34776] The node types the registered automation engine runs, read through + * its `getSealedNodeTypeVocabulary()`: the input the runtime publish gate + * refuses a flow node no executor runs with (`flow-node-type-no-executor`). + * + * Read per write, as the posture probes read their services, and recorded + * nowhere. `undefined` (the CLI's reading, under which no node type is judged) + * when the host has no registry, no automation service, or an engine that has + * not sealed its vocabulary yet: before the seal a plugin may still contribute + * a type, so "no executor" is not a verdict anyone may act on (AGENTS.md + * "Startup registry reads"). + */ +export function sealedFlowNodeTypeVocabulary( + this: { readonly getServicesRegistry?: () => Map }, +): readonly string[] | undefined { + let automation: unknown; + try { + automation = this.getServicesRegistry?.().get('automation'); + } catch { + return undefined; + } + const read = (automation as { getSealedNodeTypeVocabulary?: () => unknown } | undefined)?.getSealedNodeTypeVocabulary; + if (typeof read !== 'function') return undefined; + let vocabulary: unknown; + try { + vocabulary = read.call(automation); + } catch { + return undefined; + } + return Array.isArray(vocabulary) && vocabulary.length > 0 && vocabulary.every((t) => typeof t === 'string') + ? (vocabulary as readonly string[]) + : undefined; +} diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 8c634828c08..925ab97c77c 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -2663,6 +2663,7 @@ export class ProtocolHistoryAndPublishFacet { try { const { publishedItemReader, runBuildProbes } = await import('./build-probes.js'); const analytics = this.getServicesRegistry?.().get('analytics'); + const automation = this.getServicesRegistry?.().get('automation'); probes = await runBuildProbes({ engine: this.engine as any, // [ADR-0150 D3, #31700] A widget's dataset is resolved FROM @@ -2678,6 +2679,14 @@ export class ProtocolHistoryAndPublishFacet { // the ladder the door already states for this publish. ...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}), + // [#35146] The automation engine's connector lookups: a + // published flow's `connector_action` step is asked of + // them for this package, as its executor will ask. + ...(automation && typeof automation.resolveConnectorAction === 'function' ? { automation } : {}), + packageId: request.packageId ?? null, + // [#35146] The loader's own ids of the rows each seed + // landed on: the reference probe reads those rows only. + ...(seedApplied?.landed ? { seedLanded: seedApplied.landed } : {}), }); } catch { probes = undefined; diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 8b709139b40..73dd33deb17 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -273,6 +273,7 @@ import { restoredBodyDerivation, restoredBodyWriter, runAuthoringGate, + sealedFlowNodeTypeVocabulary, } from './protocol-authoring-gate.js'; // [#25467 cut 9] The credential carry-forward and the credential channel lookup. import { @@ -1858,20 +1859,8 @@ export class ObjectStackProtocolImplementation implements userTextLocales?: readonly (string | undefined)[]; }): Promise { // [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`). - const readAuthoringChannel = () => this.authoringChannel; - const readEngine = () => this.engine; - const host: ThisParameterType = { - get authoringChannel() { return readAuthoringChannel(); }, - get engine() { return readEngine(); }, - foldStoredCollection: (...a) => this.foldStoredCollection(...a), - hierarchyResolverMounted: (...a) => this.hierarchyResolverMounted(...a), - orgWallEnforced: (...a) => this.orgWallEnforced(...a), - resolveSduiManifest: (...a) => this.resolveSduiManifest(...a), - resolveWritePackageScope: (...a) => this.resolveWritePackageScope(...a), - rlsMembershipResolverKeys: (...a) => this.rlsMembershipResolverKeys(...a), - tenancyPostureInForce: (...a) => this.tenancyPostureInForce(...a), - }; - return assertRuntimeAuthoringRules.call(host, evt); + // [#34776] Its host is the draft verdicts' (a superset of the members it reads), so the two cannot drift. + return assertRuntimeAuthoringRules.call(this.draftVerdictHost(), evt); } /** @@ -1939,6 +1928,7 @@ export class ObjectStackProtocolImplementation implements resolveSduiManifest: (...a) => this.resolveSduiManifest(...a), resolveWritePackageScope: (...a) => this.resolveWritePackageScope(...a), rlsMembershipResolverKeys: (...a) => this.rlsMembershipResolverKeys(...a), + sealedFlowNodeTypeVocabulary: (...a) => this.sealedFlowNodeTypeVocabulary(...a), tenancyPostureInForce: (...a) => this.tenancyPostureInForce(...a), }; return host; @@ -2236,6 +2226,15 @@ export class ObjectStackProtocolImplementation implements return rlsMembershipResolverKeys.call(host); } + /** [#34776] The automation engine's sealed node-type vocabulary; the body's docblock is its contract. */ + private sealedFlowNodeTypeVocabulary(): readonly string[] | undefined { + const readGetServicesRegistry = () => this.getServicesRegistry; + const host: ThisParameterType = { + get getServicesRegistry() { return readGetServicesRegistry(); }, + }; + return sealedFlowNodeTypeVocabulary.call(host); + } + /** * [#26188] Is a hierarchy resolver mounted on this runtime — a service * registered under `HIERARCHY_SCOPE_RESOLVER_SERVICE` (ADR-0057; the diff --git a/packages/metadata-protocol/src/runtime-authoring-gate.ts b/packages/metadata-protocol/src/runtime-authoring-gate.ts index 0a8e2c4542b..649cdcd04e1 100644 --- a/packages/metadata-protocol/src/runtime-authoring-gate.ts +++ b/packages/metadata-protocol/src/runtime-authoring-gate.ts @@ -1435,6 +1435,15 @@ export function evaluateRuntimeAuthoringGate(args: { * carried there with no priority. */ storedObjectExtensions?: readonly StoredObjectExtension[]; + /** + * The node types the host's automation engine runs, stated only once the + * engine's vocabulary is SEALED (`getSealedNodeTypeVocabulary()`). A fact + * only the host holds, of the #6285 kind: handed to the shared rules, where + * `validateFlowNodeExecutors` refuses a flow node no executor runs. Absent + * (no automation service, or an engine not yet sealed), node types are not + * judged. + */ + flowNodeTypeVocabulary?: readonly string[]; }): RuntimeAuthoringVerdict { const toIssue = issueOf(args.userTextLocales ?? []); // [#26188] The one finding a draft hears: a hierarchy scope this runtime @@ -1511,6 +1520,9 @@ export function evaluateRuntimeAuthoringGate(args: { ...(args.storedObjectExtensions !== undefined ? { storedObjectExtensions: args.storedObjectExtensions } : {}), + ...(args.flowNodeTypeVocabulary !== undefined + ? { flowNodeTypeVocabulary: args.flowNodeTypeVocabulary } + : {}), }); // [#6285] The gate-local refusal, folded into the SAME verdict set as the diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 8e95758edef..a1000326fdb 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -10737,6 +10737,21 @@ export class AutomationEngine implements IAutomationService { return audit; } + /** + * The CLOSED node-type vocabulary — every type this engine can run — or + * `undefined` while {@link sealNodeTypeVocabulary} has not been called. + * + * Read by the metadata publish gate, which refuses a flow naming a type no + * executor serves (`flow-node-type-no-executor`, `@objectstack/lint`). + * `undefined` before the seal is the whole point: until the host declares + * the vocabulary closed, "not registered" is still "not registered YET" + * (AGENTS.md "Startup registry reads"), so the gate judges nothing rather + * than record a refusal the boot can contradict. Read-only; it never seals. + */ + getSealedNodeTypeVocabulary(): string[] | undefined { + return this.nodeTypeVocabularySealed ? [...this.knownNodeTypes()].sort() : undefined; + } + /** * Report — once per engine — that a flow ran on an engine whose node-type * vocabulary was never sealed, so the ADR-0018 §M1 check never ran (#4792). diff --git a/packages/services/service-automation/src/flow-node-type-audit.test.ts b/packages/services/service-automation/src/flow-node-type-audit.test.ts index 2c69feb1b32..b5c21e033be 100644 --- a/packages/services/service-automation/src/flow-node-type-audit.test.ts +++ b/packages/services/service-automation/src/flow-node-type-audit.test.ts @@ -25,7 +25,7 @@ import { describe, it, expect, vi } from 'vitest'; import { LiteKernel } from '@objectstack/core'; import type { Plugin, PluginContext } from '@objectstack/core'; import { AutomationServicePlugin } from './plugin.js'; -import type { AutomationEngine } from './engine.js'; +import { AutomationEngine } from './engine.js'; /** The showcase's shape: a flow whose only real node is an ADR-0019 `approval`. */ const approvalFlow = (name: string) => ({ @@ -203,3 +203,21 @@ describe('#4771 — flow node-type validation waits for the plugin-contributed v await kernel.shutdown(); }); }); + +describe('getSealedNodeTypeVocabulary — the closed vocabulary the publish gate judges against', () => { + it('answers nothing before the seal, and the closed vocabulary after it', async () => { + const quiet = { debug() {}, info() {}, warn() {}, error() {} } as never; + const engine = new AutomationEngine(quiet); + // Not sealed: "absent" is still "absent YET", so there is no vocabulary to judge by. + expect(engine.getSealedNodeTypeVocabulary()).toBeUndefined(); + engine.sealNodeTypeVocabulary(); + expect(engine.getSealedNodeTypeVocabulary()).toEqual(expect.arrayContaining(['start', 'end'])); + expect(engine.getSealedNodeTypeVocabulary()).not.toContain('approval'); + }); + + it('a plugin-contributed type is in the sealed vocabulary of the boot that installed it', async () => { + const { kernel, engine } = await boot({ flows: [], withApprovals: true }); + expect(engine.getSealedNodeTypeVocabulary()).toEqual(expect.arrayContaining(['approval', 'get_record', 'http'])); + await kernel.shutdown(); + }); +}); diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index af0c47b0b7e..c1322f3f6b3 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1920,34 +1920,46 @@ export const RuntimeBuildIssueSchema = lazySchema(() => z.object({ severity: z.enum(['error', 'warning']).describe( '`error`: the published artifact is broken at runtime, or the check that ' + 'judges it could not run (`object_field_ref_rule_failed`). `warning`: a ' - + 'dashboard widget was not probed, so nothing is known about it. Neither ' - + 'fails the publish.', + + 'dashboard widget was not probed, so nothing is known about it ' + + '(`widget_not_probed`, `probes_unavailable`); what landed reads in a way ' + + 'the person will notice although it may be the truth (`widget_empty_result`, ' + + '`rollup_never_computed`); or what landed is wrong in a way that depends on ' + + 'data or on what the environment serves rather than on the artifact alone: ' + + 'a stored reference that names no row (`seed_reference_unresolved`), a ' + + 'flow step that fails on every run that reaches it until the connector it ' + + 'names is served (`flow_connector_action_unresolved`). Neither fails the publish.', ), artifact: z.object({ - type: z.string().describe('Metadata type of the artifact (`seed`, `view`, `object`, `dashboard`).'), + type: z.string().describe('Metadata type of the artifact (`seed`, `view`, `object`, `dashboard`, `flow`).'), name: z.string().describe( 'Item name of the artifact. On `probes_unavailable` it is the name of ' + 'every dashboard whose widgets went unprobed, joined by `, `.', ), }).describe('The published artifact whose runtime behaviour the finding is about.'), ref: z.object({ - type: z.string().describe('Metadata type of what was exercised (`object`, `dataset`).'), + type: z.string().describe('Metadata type of what was exercised (`object`, `dataset`, `connector`).'), name: z.string().describe('Its item name.'), member: z.string().optional().describe( - 'The dashboard widget the finding is about, when the finding is about ' - + 'one widget: its `id`, else its `title` as a string, else `?`.', + 'The part of it the finding is about: the dashboard widget, when the ' + + 'finding is about one widget (its `id`, else its `title` as a string, ' + + 'else `?`); the field of an object (a roll-up, a reference column); the ' + + 'action of a connector.', ), }).optional().describe( - 'What the probe exercised, when that is not the artifact itself: the ' - + 'object a seed loads into or a view reads, the dataset a widget is bound ' - + 'to. Absent when the finding is about the artifact as a whole.', + 'What the probe exercised: the object a seed loads into or a view reads, ' + + 'the dataset a widget is bound to, the connector a flow step dispatches, ' + + 'or the published object itself when `member` names the field the ' + + 'finding is about (a roll-up). Absent when the finding is about the ' + + 'artifact as a whole.', ), code: z.string().describe( 'Stable machine id of the finding class, lowercase snake: a diagnostics ' + 'code carried in a 200, not an ADR-0112 error code. The probes emit ' + '`seed_not_applied`, `view_read_failed`, `object_field_ref_unknown`, ' + '`object_field_ref_rule_failed`, `empty_query`, `widget_query_failed`, ' - + '`widget_not_probed` and `probes_unavailable`. The list is the ' + + '`widget_not_probed`, `probes_unavailable`, `widget_empty_result`, ' + + '`rollup_never_computed`, `seed_reference_unresolved` and ' + + '`flow_connector_action_unresolved`. The list is the ' + 'producer\'s and may grow: a consumer treats an id it does not know as ' + 'any other finding.', ), diff --git a/packages/spec/src/data/validation.zod.ts b/packages/spec/src/data/validation.zod.ts index 43d82cff167..a85c8f03f83 100644 --- a/packages/spec/src/data/validation.zod.ts +++ b/packages/spec/src/data/validation.zod.ts @@ -194,7 +194,7 @@ export const StateMachineValidationSchema = lazySchema(() => strictObject({ type: z.literal('state_machine'), field: z.string().describe('State field (e.g. status)'), transitions: z.record(z.string(), z.array(z.string())).describe('Map of { OldState: [AllowedNewStates] }'), - initialStates: z.array(z.string()).optional().describe('States a record may be CREATED in. When set, an INSERT whose state field carries a value outside this list is rejected (server-enforced) — the FSM entry point. `transitions` only governs UPDATE, and a `select` field permits ANY declared option as an initial value, so without this a record could be born mid-flow (e.g. created already `approved`). Omit to keep the legacy behavior (no initial-state check on insert).'), + initialStates: z.array(z.string()).optional().describe('States a record may be CREATED in. When set, an INSERT whose state field carries a value outside this list is rejected (server-enforced) — the FSM entry point. `transitions` only governs UPDATE, and a `select` field permits ANY declared option as an initial value, so without this a record could be born mid-flow (e.g. created already `approved`). Omitted or empty, insert is not checked; the author-time rule `state-machine-no-initial-states` refuses an active machine declared that way at publish and in `os validate`.'), })); /** diff --git a/packages/spec/src/migrations/entries/semantic/18.publish-refuses-metadata-the-runtime-ignores.ts b/packages/spec/src/migrations/entries/semantic/18.publish-refuses-metadata-the-runtime-ignores.ts new file mode 100644 index 00000000000..8a16ecf683c --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.publish-refuses-metadata-the-runtime-ignores.ts @@ -0,0 +1,37 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of five author-time rules (#34776) that refuse, at +// publish and in `os validate` / `build`, metadata the schema still accepts but +// the runtime ignores or turns against its author. Notice only: no key is +// removed and no D2 conversion exists, because each fix is a choice only the +// author can make (which state a record starts in, how long a call may wait). +export const entry: SemanticMigration = { + id: 'publish-refuses-metadata-the-runtime-ignores', + surface: + 'Five author-time rules, run by the runtime publish gate and by `os validate` / `lint` / `compile` / `build`: ' + + 'a flow node whose `type` no executor in the deployment runs (`flow-node-type-no-executor`, judged at publish ' + + 'against the automation engine\'s sealed node-type vocabulary); an `approval` node whose decision out-edges are ' + + 'not labelled `approve` and `reject` (`flow-approval-decision-unrouted`); an `http` node with no `timeoutMs` ' + + '(`flow-http-timeout-missing`, a warning); an active `state_machine` validation with no or an empty ' + + '`initialStates` (`state-machine-no-initial-states`); a standalone action that declares `locations` but no `objectName` ' + + '(`action-no-object-binding`)', + replacement: + 'Give the node a type the deployment runs (or install the plugin that contributes it); label the approval node\'s ' + + 'two decision edges `approve` and `reject`; set a positive `config.timeoutMs` (or node-level `timeoutMs`) on the ' + + 'http node; list the states a record may be created in under `initialStates`; set the action\'s `objectName`, or write `locations: []` ' + + 'for an action that is headless (REST / MCP / AI only)', + reason: + 'Each declaration parses and publishes, then does nothing or works against its author at run time: a node no ' + + 'executor runs fails every run with NO_EXECUTOR; an approval decision no out-edge label claims runs every ' + + 'out-edge, so the approving and the rejecting branch both run; an http call with no timeout waits as long as the ' + + 'connection stays open; a state machine without `initialStates` lets a record be created already in its last ' + + 'state; an action bound to no object never renders. Stored items are not rewritten or refused at boot. The next ' + + 'publish or write of an item that carries one of the four errors is refused with the fix named, and the http timeout is reported as a warning, ' + + 'which makes `os validate --strict` exit 1 as any warning does.', + acceptanceCriteria: + 'os validate reports none of the four errors (`flow-node-type-no-executor` is judged only at publish, against the ' + + 'deployment\'s sealed vocabulary) and no `flow-http-timeout-missing` warning; a publish of every flow, object and ' + + 'action the package carries succeeds.', +};